From c272c65af7b48ba5d634b5a8b6e452c28541ac17 Mon Sep 17 00:00:00 2001 From: Justin Guerra Date: Thu, 14 Sep 2023 15:52:20 -0600 Subject: [PATCH] Format all --- .../zuul/message/HeadersBenchmark.java | 21 +- .../config/DynamicIntegerSetProperty.java | 3 +- .../config/PatternListStringProperty.java | 18 +- .../AbstrHttpConnectionExpiryHandler.java | 39 +- .../com/netflix/netty/common/ByteBufUtil.java | 1 - .../common/CategorizedThreadFactory.java | 6 +- .../ConnectionCloseChannelAttributes.java | 18 +- .../netty/common/ConnectionCloseType.java | 16 +- .../common/Http1ConnectionCloseHandler.java | 82 +-- .../common/Http1ConnectionExpiryHandler.java | 9 +- .../common/Http2ConnectionCloseHandler.java | 104 ++-- .../common/Http2ConnectionExpiryHandler.java | 9 +- .../netty/common/HttpChannelFlags.java | 24 +- .../HttpClientLifecycleChannelHandler.java | 37 +- .../common/HttpLifecycleChannelHandler.java | 105 ++-- .../common/HttpRequestReadTimeoutEvent.java | 3 +- .../common/HttpRequestReadTimeoutHandler.java | 43 +- .../HttpServerLifecycleChannelHandler.java | 47 +- .../LeastConnsEventLoopChooserFactory.java | 34 +- .../common/RequestResponseCompleteEvent.java | 4 +- .../common/SourceAddressChannelHandler.java | 6 +- .../netty/common/SslExceptionsHandler.java | 6 +- .../SwallowSomeHttp2ExceptionsHandler.java | 30 +- .../accesslog/AccessLogChannelHandler.java | 59 +- .../common/accesslog/AccessLogPublisher.java | 82 +-- .../common/channel/config/ChannelConfig.java | 27 +- .../channel/config/ChannelConfigKey.java | 23 +- .../channel/config/ChannelConfigValue.java | 12 +- .../config/CommonChannelConfigKeys.java | 47 +- .../common/http2/DynamicHttp2FrameLogger.java | 148 +++-- .../common/metrics/EventLoopGroupMetrics.java | 31 +- .../common/metrics/EventLoopMetrics.java | 27 +- .../metrics/Http2MetricsChannelHandlers.java | 70 +-- .../HttpBodySizeRecordingChannelHandler.java | 59 +- .../metrics/HttpMetricsChannelHandler.java | 38 +- .../InstrumentedResourceLeakDetector.java | 14 +- .../PerEventLoopMetricsChannelHandler.java | 39 +- .../ElbProxyProtocolChannelHandler.java | 16 +- .../HAProxyMessageChannelHandler.java | 20 +- .../StripUntrustedProxyHeadersHandler.java | 23 +- .../netty/common/ssl/ServerSslConfig.java | 89 ++- .../netty/common/ssl/SslHandshakeInfo.java | 28 +- .../common/status/ServerStatusManager.java | 4 +- .../MaxInboundConnectionsHandler.java | 24 +- .../netty/common/throttle/RejectionUtils.java | 120 +++- .../src/main/java/com/netflix/zuul/Attrs.java | 3 +- .../zuul/BasicFilterUsageNotifier.java | 11 +- .../zuul/BasicRequestCompleteHandler.java | 8 +- .../netflix/zuul/DefaultFilterFactory.java | 7 +- .../com/netflix/zuul/DynamicCodeCompiler.java | 1 - .../com/netflix/zuul/DynamicFilterLoader.java | 15 +- .../com/netflix/zuul/ExecutionStatus.java | 8 +- .../main/java/com/netflix/zuul/Filter.java | 11 +- .../java/com/netflix/zuul/FilterCategory.java | 7 +- .../java/com/netflix/zuul/FilterFactory.java | 4 +- .../com/netflix/zuul/FilterFileManager.java | 58 +- .../java/com/netflix/zuul/FilterLoader.java | 9 +- .../netflix/zuul/RequestCompleteHandler.java | 4 +- .../com/netflix/zuul/StaticFilterLoader.java | 27 +- .../netflix/zuul/constants/ZuulConstants.java | 5 +- .../netflix/zuul/constants/ZuulHeaders.java | 1 - .../zuul/context/CommonContextKeys.java | 8 +- .../java/com/netflix/zuul/context/Debug.java | 50 +- .../netflix/zuul/context/SessionCleaner.java | 3 +- .../netflix/zuul/context/SessionContext.java | 58 +- .../zuul/context/SessionContextFactory.java | 4 +- .../context/ZuulSessionContextDecorator.java | 5 +- .../com/netflix/zuul/exception/ErrorType.java | 23 +- .../zuul/exception/OutboundErrorType.java | 16 +- .../zuul/exception/OutboundException.java | 18 +- .../netflix/zuul/exception/ZuulException.java | 16 +- .../com/netflix/zuul/filters/BaseFilter.java | 20 +- .../netflix/zuul/filters/BaseSyncFilter.java | 10 +- .../com/netflix/zuul/filters/Endpoint.java | 12 +- .../com/netflix/zuul/filters/FilterError.java | 12 +- .../netflix/zuul/filters/FilterRegistry.java | 2 +- .../netflix/zuul/filters/FilterSyncType.java | 6 +- .../com/netflix/zuul/filters/FilterType.java | 29 +- .../zuul/filters/MutableFilterRegistry.java | 8 +- .../netflix/zuul/filters/ShouldFilter.java | 3 +- .../netflix/zuul/filters/SyncZuulFilter.java | 3 +- .../zuul/filters/SyncZuulFilterAdapter.java | 7 +- .../com/netflix/zuul/filters/ZuulFilter.java | 6 +- .../filters/common/GZipResponseFilter.java | 29 +- .../filters/common/SurgicalDebugFilter.java | 5 +- .../MissingEndpointHandlingFilter.java | 3 +- .../zuul/filters/endpoint/ProxyEndpoint.java | 274 ++++---- .../zuul/filters/http/HttpInboundFilter.java | 3 +- .../filters/http/HttpInboundSyncFilter.java | 3 +- .../zuul/filters/http/HttpOutboundFilter.java | 9 +- .../filters/http/HttpOutboundSyncFilter.java | 5 +- .../zuul/filters/http/HttpSyncEndpoint.java | 38 +- .../InboundPassportStampingFilter.java | 1 - .../OutboundPassportStampingFilter.java | 1 - .../passport/PassportStampingFilter.java | 5 +- .../Http2FrameLoggingPerClientIpHandler.java | 22 +- .../java/com/netflix/zuul/message/Header.java | 3 +- .../com/netflix/zuul/message/Headers.java | 12 +- .../com/netflix/zuul/message/ZuulMessage.java | 2 +- .../netflix/zuul/message/ZuulMessageImpl.java | 25 +- .../netflix/zuul/message/http/Cookies.java | 18 +- .../zuul/message/http/HttpHeaderNames.java | 22 +- .../message/http/HttpHeaderNamesCache.java | 15 +- .../zuul/message/http/HttpQueryParams.java | 72 +-- .../zuul/message/http/HttpRequestInfo.java | 4 +- .../zuul/message/http/HttpRequestMessage.java | 3 +- .../message/http/HttpRequestMessageImpl.java | 286 ++++----- .../zuul/message/http/HttpResponseInfo.java | 4 +- .../message/http/HttpResponseMessage.java | 3 +- .../message/http/HttpResponseMessageImpl.java | 92 ++- .../zuul/message/util/HttpRequestBuilder.java | 7 +- .../com/netflix/zuul/metrics/OriginStats.java | 4 +- .../zuul/metrics/OriginStatsFactory.java | 3 +- .../netflix/zuul/monitoring/ConnCounter.java | 9 +- .../netflix/zuul/monitoring/ConnTimer.java | 11 +- .../zuul/monitoring/MonitoringHelper.java | 1 - .../com/netflix/zuul/monitoring/Tracer.java | 1 - .../zuul/monitoring/TracerFactory.java | 4 +- .../com/netflix/zuul/netty/ChannelUtils.java | 12 +- .../netty/NettyRequestAttemptFactory.java | 9 +- .../zuul/netty/RequestCancelledEvent.java | 4 +- .../netflix/zuul/netty/SpectatorUtils.java | 3 +- .../connectionpool/BasicRequestStat.java | 1 - .../connectionpool/ClientChannelManager.java | 5 +- .../connectionpool/ClientTimeoutHandler.java | 23 +- .../ConnectionPoolConfigImpl.java | 29 +- .../connectionpool/ConnectionPoolHandler.java | 33 +- .../DefaultClientChannelManager.java | 160 +++-- .../DefaultOriginChannelInitializer.java | 19 +- .../netty/connectionpool/IConnectionPool.java | 11 +- .../NettyClientConnectionFactory.java | 14 +- .../OriginChannelInitializer.java | 2 +- .../OriginConnectException.java | 2 - .../PerServerConnectionPool.java | 130 ++-- .../connectionpool/PooledConnection.java | 88 ++- .../PooledConnectionFactory.java | 3 +- .../netty/connectionpool/RequestStat.java | 8 +- .../ZuulNettyExceptionMapper.java | 5 +- .../netty/filter/BaseZuulFilterRunner.java | 143 +++-- .../zuul/netty/filter/FilterRunner.java | 1 + .../zuul/netty/filter/ZuulEndPointRunner.java | 97 +-- .../netty/filter/ZuulFilterChainHandler.java | 52 +- .../netty/filter/ZuulFilterChainRunner.java | 36 +- .../insights/PassportLoggingHandler.java | 71 ++- .../PassportStateHttpClientHandler.java | 42 +- .../PassportStateHttpServerHandler.java | 54 +- .../netty/insights/PassportStateListener.java | 17 +- .../insights/PassportStateOriginHandler.java | 41 +- .../netty/insights/ServerStateHandler.java | 19 +- .../NullChannelHandlerProvider.java | 3 +- .../zuul/netty/server/BaseServerStartup.java | 94 +-- .../server/BaseZuulChannelInitializer.java | 137 ++-- .../server/ClientConnectionsShutdown.java | 36 +- .../netty/server/ClientRequestReceiver.java | 141 +++-- .../netty/server/ClientResponseWriter.java | 101 +-- .../netty/server/DefaultEventLoopConfig.java | 15 +- .../netty/server/DirectMemoryMonitor.java | 37 +- .../zuul/netty/server/EventLoopConfig.java | 3 +- .../Http1MutualSslChannelInitializer.java | 23 +- .../zuul/netty/server/MethodBinding.java | 3 +- .../zuul/netty/server/NamedSocketAddress.java | 7 +- .../netty/server/OriginResponseReceiver.java | 89 ++- .../com/netflix/zuul/netty/server/Server.java | 142 +++-- .../zuul/netty/server/ServerTimeout.java | 12 +- .../netty/server/SocketAddressProperty.java | 6 +- .../zuul/netty/server/ZuulDependencyKeys.java | 36 +- .../server/ZuulServerChannelInitializer.java | 15 +- .../server/http2/DummyChannelHandler.java | 3 +- .../server/http2/Http2Configuration.java | 14 +- .../Http2ContentLengthEnforcingHandler.java | 1 + .../server/http2/Http2OrHttpHandler.java | 19 +- .../server/http2/Http2ResetFrameHandler.java | 9 +- .../http2/Http2SslChannelInitializer.java | 74 ++- .../server/http2/Http2StreamErrorHandler.java | 2 +- .../http2/Http2StreamHeaderCleaner.java | 7 +- .../server/http2/Http2StreamInitializer.java | 58 +- .../netty/server/push/PushAuthHandler.java | 34 +- .../server/push/PushChannelInitializer.java | 6 +- .../push/PushClientProtocolHandler.java | 2 - .../netty/server/push/PushConnection.java | 13 +- .../server/push/PushConnectionRegistry.java | 8 +- .../netty/server/push/PushMessageFactory.java | 3 - .../netty/server/push/PushMessageSender.java | 50 +- .../push/PushMessageSenderInitializer.java | 1 - .../zuul/netty/server/push/PushProtocol.java | 9 +- .../server/push/PushRegistrationHandler.java | 74 ++- .../zuul/netty/server/push/PushUserAuth.java | 1 - .../server/ssl/SslHandshakeInfoHandler.java | 91 ++- .../zuul/netty/ssl/BaseSslContextFactory.java | 44 +- .../netty/ssl/ClientSslContextFactory.java | 15 +- .../zuul/netty/ssl/SslContextFactory.java | 7 +- .../netty/timeouts/OriginTimeoutManager.java | 7 +- .../com/netflix/zuul/niws/RequestAttempt.java | 132 ++-- .../netflix/zuul/niws/RequestAttempts.java | 32 +- .../zuul/origins/BasicNettyOrigin.java | 59 +- .../zuul/origins/BasicNettyOriginManager.java | 3 +- .../zuul/origins/InstrumentedOrigin.java | 1 - .../com/netflix/zuul/origins/NettyOrigin.java | 31 +- .../java/com/netflix/zuul/origins/Origin.java | 2 + .../OriginConcurrencyExceededException.java | 12 +- .../com/netflix/zuul/origins/OriginName.java | 10 +- .../origins/OriginThrottledException.java | 10 +- .../zuul/passport/CurrentPassport.java | 169 ++--- .../netflix/zuul/passport/PassportItem.java | 15 +- .../netflix/zuul/passport/PassportState.java | 7 +- .../netflix/zuul/passport/StartAndEnd.java | 9 +- .../java/com/netflix/zuul/plugins/Tracer.java | 5 +- .../netflix/zuul/stats/AmazonInfoHolder.java | 1 - .../stats/BasicRequestMetricsPublisher.java | 3 +- .../netflix/zuul/stats/ErrorStatsData.java | 3 +- .../netflix/zuul/stats/ErrorStatsManager.java | 15 +- .../zuul/stats/NamedCountingMonitor.java | 2 - .../zuul/stats/RequestMetricsPublisher.java | 3 +- .../zuul/stats/RouteStatusCodeMonitor.java | 5 +- .../com/netflix/zuul/stats/StatsManager.java | 10 +- .../stats/monitoring/MonitorRegistry.java | 4 +- .../zuul/stats/monitoring/NamedCount.java | 1 + .../stats/status/StatusCategoryUtils.java | 3 +- .../zuul/stats/status/ZuulStatusCategory.java | 18 +- .../java/com/netflix/zuul/util/Gzipper.java | 16 +- .../java/com/netflix/zuul/util/HttpUtils.java | 42 +- .../com/netflix/zuul/util/JsonUtility.java | 7 +- .../com/netflix/zuul/util/ProxyUtils.java | 32 +- .../java/com/netflix/zuul/util/VipUtils.java | 3 +- .../common/CloseOnIdleStateHandlerTest.java | 6 +- ...HttpServerLifecycleChannelHandlerTest.java | 7 +- .../SourceAddressChannelHandlerTest.java | 20 +- .../InstrumentedResourceLeakDetectorTest.java | 4 +- .../ElbProxyProtocolChannelHandlerTest.java | 125 ++-- .../HAProxyMessageChannelHandlerTest.java | 18 +- ...StripUntrustedProxyHeadersHandlerTest.java | 21 +- .../MaxInboundConnectionsHandlerTest.java | 13 +- .../test/java/com/netflix/zuul/AttrsTest.java | 6 +- .../netflix/zuul/DynamicFilterLoaderTest.java | 28 +- .../netflix/zuul/FilterFileManagerTest.java | 29 +- .../netflix/zuul/StaticFilterLoaderTest.java | 8 +- .../netty/server/push/PushConnectionTest.java | 8 +- .../com/netflix/zuul/context/DebugTest.java | 90 +-- .../zuul/context/SessionContextTest.java | 6 +- .../netflix/zuul/filters/BaseFilterTest.java | 11 +- .../common/GZipResponseFilterTest.java | 34 +- .../filters/endpoint/ProxyEndpointTest.java | 27 +- .../com/netflix/zuul/message/HeadersTest.java | 68 +- .../zuul/message/ZuulMessageImplTest.java | 5 +- .../message/http/HttpQueryParamsTest.java | 10 +- .../http/HttpRequestMessageImplTest.java | 586 ++++++++++++++---- .../http/HttpResponseMessageImplTest.java | 26 +- .../zuul/monitoring/ConnCounterTest.java | 7 +- .../zuul/monitoring/ConnTimerTest.java | 15 +- .../DefaultClientChannelManagerTest.java | 57 +- .../PerServerConnectionPoolTest.java | 158 +++-- .../netty/filter/ZuulEndPointRunnerTest.java | 26 +- .../filter/ZuulFilterChainRunnerTest.java | 50 +- .../insights/ServerStateHandlerTest.java | 14 +- .../BaseZuulChannelInitializerTest.java | 14 +- .../server/ClientConnectionsShutdownTest.java | 66 +- .../server/ClientRequestReceiverTest.java | 76 ++- .../server/ClientResponseWriterTest.java | 7 +- .../zuul/netty/server/IoUringTest.java | 61 +- .../netflix/zuul/netty/server/ServerTest.java | 40 +- .../server/SocketAddressPropertyTest.java | 22 +- ...ttp2ContentLengthEnforcingHandlerTest.java | 18 +- .../server/http2/Http2OrHttpHandlerTest.java | 27 +- .../server/push/PushAuthHandlerTest.java | 4 +- .../push/PushRegistrationHandlerTest.java | 29 +- .../ssl/SslHandshakeInfoHandlerTest.java | 21 +- .../netty/ssl/BaseSslContextFactoryTest.java | 3 +- .../ssl/ClientSslContextFactoryTest.java | 12 +- .../timeouts/OriginTimeoutManagerTest.java | 18 +- .../netflix/zuul/origins/OriginNameTest.java | 6 +- .../zuul/passport/CurrentPassportTest.java | 33 +- .../zuul/stats/ErrorStatsDataTest.java | 7 +- .../zuul/stats/ErrorStatsManagerTest.java | 9 +- .../stats/RouteStatusCodeMonitorTest.java | 4 +- .../netflix/zuul/stats/StatsManagerTest.java | 15 +- .../com/netflix/zuul/util/HttpUtilsTest.java | 12 +- .../netflix/zuul/util/JsonUtilityTest.java | 14 +- .../com/netflix/zuul/util/VipUtilsTest.java | 5 +- .../zuul/discovery/DiscoveryResult.java | 20 +- .../zuul/discovery/DynamicServerResolver.java | 16 +- .../zuul/discovery/NonDiscoveryServer.java | 1 + .../zuul/discovery/ResolverResult.java | 3 +- .../com/netflix/zuul/resolver/Resolver.java | 2 +- .../zuul/discovery/DiscoveryResultTest.java | 56 +- .../discovery/DynamicServerResolverTest.java | 8 +- .../netflix/zuul/groovy/GroovyCompiler.java | 1 - .../zuul/scriptManager/FilterInfo.java | 30 +- .../zuul/scriptManager/FilterVerifier.java | 18 +- .../zuul/groovy/GroovyCompilerTest.java | 17 +- .../zuul/groovy/GroovyFileFilterTest.java | 11 +- .../scriptManager/FilterVerifierTest.java | 177 +++--- .../zuul/guice/GuiceFilterFactory.java | 1 + .../netflix/zuul/init/ZuulFiltersModule.java | 20 +- .../guice/GuiceFilterFactoryIntegTest.java | 8 +- .../guice/TestGuiceConstructorFilter.java | 1 + .../zuul/guice/TestGuiceFieldFilter.java | 1 + .../com/netflix/zuul/init/InitTestModule.java | 4 +- .../zuul/init/ZuulFiltersModuleIntegTest.java | 22 +- .../zuul/init/ZuulFiltersModuleTest.java | 56 +- .../common/metrics/CustomLeakDetector.java | 9 +- .../zuul/integration/IntegrationTest.java | 266 ++++---- .../zuul/integration/server/Bootstrap.java | 3 +- .../server/FilterLoaderProvider.java | 9 +- .../zuul/integration/server/HeaderNames.java | 2 +- .../integration/server/OriginServerList.java | 2 +- .../zuul/integration/server/ServerModule.java | 18 +- .../integration/server/ServerStartup.java | 124 ++-- .../zuul/integration/server/TestUtil.java | 8 +- .../server/filters/InboundRoutesFilter.java | 2 - .../filters/processor/FilterProcessor.java | 33 +- .../processor/FilterProcessorTest.java | 18 +- .../filters/processor/TopLevelFilter.java | 3 +- .../processor/override/SubpackageFilter.java | 3 +- .../processor/override/package-info.java | 2 +- .../processor/subpackage/OverrideFilter.java | 3 +- .../com/netflix/zuul/sample/Bootstrap.java | 6 +- .../zuul/sample/SampleServerStartup.java | 142 +++-- .../netflix/zuul/sample/ZuulSampleModule.java | 18 +- .../sample/push/SamplePushAuthHandler.java | 3 +- .../sample/push/SamplePushMessageSender.java | 4 +- .../SamplePushMessageSenderInitializer.java | 2 +- .../push/SampleSSEPushChannelInitializer.java | 13 +- .../SampleSSEPushClientProtocolHandler.java | 18 +- ...SampleWebSocketPushChannelInitializer.java | 6 +- ...pleWebSocketPushClientProtocolHandler.java | 27 +- 325 files changed, 5120 insertions(+), 4516 deletions(-) diff --git a/zuul-core/src/jmh/java/com/netflix/zuul/message/HeadersBenchmark.java b/zuul-core/src/jmh/java/com/netflix/zuul/message/HeadersBenchmark.java index b4a03e45aa..51a7b78525 100644 --- a/zuul-core/src/jmh/java/com/netflix/zuul/message/HeadersBenchmark.java +++ b/zuul-core/src/jmh/java/com/netflix/zuul/message/HeadersBenchmark.java @@ -15,10 +15,6 @@ */ package com.netflix.zuul.message; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; @@ -29,6 +25,10 @@ import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; @State(Scope.Thread) public class HeadersBenchmark { @@ -51,7 +51,9 @@ public void setUp() { names = new HeaderName[stringNames.length]; values = new String[stringNames.length]; for (int i = 0; i < stringNames.length; i++) { - UUID uuid = new UUID(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()); + UUID uuid = new UUID( + ThreadLocalRandom.current().nextLong(), + ThreadLocalRandom.current().nextLong()); String name = uuid.toString(); assert name.length() >= nameLength; name = name.substring(0, nameLength); @@ -84,7 +86,6 @@ public Headers addHeaders_headerName() { } } - @State(Scope.Thread) public static class GetSetHeaders { @Param({"1", "5", "10", "30"}) @@ -105,7 +106,9 @@ public void setUp() { names = new HeaderName[stringNames.length]; values = new String[stringNames.length]; for (int i = 0; i < stringNames.length; i++) { - UUID uuid = new UUID(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()); + UUID uuid = new UUID( + ThreadLocalRandom.current().nextLong(), + ThreadLocalRandom.current().nextLong()); String name = uuid.toString(); assert name.length() >= nameLength; name = name.substring(0, nameLength); @@ -152,9 +155,6 @@ public void entries(Blackhole blackhole) { blackhole.consume(header); } } - - - } @Benchmark @@ -163,5 +163,4 @@ public void entries(Blackhole blackhole) { public Headers newHeaders() { return new Headers(); } - } \ No newline at end of file diff --git a/zuul-core/src/main/java/com/netflix/config/DynamicIntegerSetProperty.java b/zuul-core/src/main/java/com/netflix/config/DynamicIntegerSetProperty.java index be5248a605..76a6ead68e 100644 --- a/zuul-core/src/main/java/com/netflix/config/DynamicIntegerSetProperty.java +++ b/zuul-core/src/main/java/com/netflix/config/DynamicIntegerSetProperty.java @@ -18,8 +18,7 @@ import java.util.Set; -public class DynamicIntegerSetProperty extends DynamicSetProperty -{ +public class DynamicIntegerSetProperty extends DynamicSetProperty { public DynamicIntegerSetProperty(String propName, String defaultValue) { super(propName, defaultValue); } diff --git a/zuul-core/src/main/java/com/netflix/config/PatternListStringProperty.java b/zuul-core/src/main/java/com/netflix/config/PatternListStringProperty.java index 36ea50018e..1bdda424a4 100644 --- a/zuul-core/src/main/java/com/netflix/config/PatternListStringProperty.java +++ b/zuul-core/src/main/java/com/netflix/config/PatternListStringProperty.java @@ -28,26 +28,26 @@ * Date: 5/15/17 * Time: 4:38 PM */ -public class PatternListStringProperty extends DerivedStringProperty> -{ +public class PatternListStringProperty extends DerivedStringProperty> { private static final Logger LOG = LoggerFactory.getLogger(PatternListStringProperty.class); - public PatternListStringProperty(String name, String defaultValue) - { + public PatternListStringProperty(String name, String defaultValue) { super(name, defaultValue); } @Override - protected List derive(String value) - { + protected List derive(String value) { ArrayList ptns = new ArrayList<>(); if (value != null) { for (String ptnTxt : value.split(",")) { try { ptns.add(Pattern.compile(ptnTxt.trim())); - } - catch (Exception e) { - LOG.error("Error parsing regex pattern list from property! name = {}, value = {}, pattern = {}", String.valueOf(this.getName()), String.valueOf(this.getValue()), String.valueOf(value)); + } catch (Exception e) { + LOG.error( + "Error parsing regex pattern list from property! name = {}, value = {}, pattern = {}", + String.valueOf(this.getName()), + String.valueOf(this.getValue()), + String.valueOf(value)); } } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/AbstrHttpConnectionExpiryHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/AbstrHttpConnectionExpiryHandler.java index bfc9465563..0838f88a94 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/AbstrHttpConnectionExpiryHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/AbstrHttpConnectionExpiryHandler.java @@ -33,11 +33,10 @@ * Date: 7/17/17 * Time: 10:54 AM */ -public abstract class AbstrHttpConnectionExpiryHandler extends ChannelOutboundHandlerAdapter -{ - protected final static Logger LOG = LoggerFactory.getLogger(AbstrHttpConnectionExpiryHandler.class); - protected final static CachedDynamicLongProperty MAX_EXPIRY_DELTA = new CachedDynamicLongProperty( - "server.connection.expiry.delta", 20 * 1000); +public abstract class AbstrHttpConnectionExpiryHandler extends ChannelOutboundHandlerAdapter { + protected static final Logger LOG = LoggerFactory.getLogger(AbstrHttpConnectionExpiryHandler.class); + protected static final CachedDynamicLongProperty MAX_EXPIRY_DELTA = + new CachedDynamicLongProperty("server.connection.expiry.delta", 20 * 1000); protected final ConnectionCloseType connectionCloseType; protected final int maxRequests; @@ -48,8 +47,8 @@ public abstract class AbstrHttpConnectionExpiryHandler extends ChannelOutboundHa protected int requestCount = 0; protected int maxRequestsUnderBrownout = 0; - public AbstrHttpConnectionExpiryHandler(ConnectionCloseType connectionCloseType, int maxRequestsUnderBrownout, int maxRequests, int maxExpiry) - { + public AbstrHttpConnectionExpiryHandler( + ConnectionCloseType connectionCloseType, int maxRequestsUnderBrownout, int maxRequests, int maxExpiry) { this.connectionCloseType = connectionCloseType; this.maxRequestsUnderBrownout = maxRequestsUnderBrownout; this.maxRequests = maxRequests; @@ -61,8 +60,7 @@ public AbstrHttpConnectionExpiryHandler(ConnectionCloseType connectionCloseType, } @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (isResponseHeaders(msg)) { // Update the request count attribute for this channel. requestCount++; @@ -70,7 +68,9 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) if (isConnectionExpired(ctx.channel())) { // Flag this channel to be closed after response is written. Channel channel = HttpUtils.getMainChannel(ctx); - ctx.channel().attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE).set(ctx.newPromise()); + ctx.channel() + .attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE) + .set(ctx.newPromise()); ConnectionCloseType.setForChannel(channel, connectionCloseType); } } @@ -78,26 +78,25 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) super.write(ctx, msg, promise); } - protected boolean isConnectionExpired(Channel channel) - { - boolean expired = requestCount >= maxRequests(channel) || - System.currentTimeMillis() > connectionExpiryTime; + protected boolean isConnectionExpired(Channel channel) { + boolean expired = requestCount >= maxRequests(channel) || System.currentTimeMillis() > connectionExpiryTime; if (expired) { long lifetime = System.currentTimeMillis() - connectionStartTime; - LOG.info("Connection is expired. requestCount={}, lifetime={}, {}", - requestCount, lifetime, ChannelUtils.channelInfoForLogging(channel)); + LOG.info( + "Connection is expired. requestCount={}, lifetime={}, {}", + requestCount, + lifetime, + ChannelUtils.channelInfoForLogging(channel)); } return expired; } protected abstract boolean isResponseHeaders(Object msg); - protected int maxRequests(Channel ch) - { + protected int maxRequests(Channel ch) { if (HttpChannelFlags.IN_BROWNOUT.get(ch)) { return this.maxRequestsUnderBrownout; - } - else { + } else { return this.maxRequests; } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/ByteBufUtil.java b/zuul-core/src/main/java/com/netflix/netty/common/ByteBufUtil.java index 9df4ad5695..6441369db3 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/ByteBufUtil.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/ByteBufUtil.java @@ -17,7 +17,6 @@ package com.netflix.netty.common; import com.netflix.zuul.message.ZuulMessage; -import com.netflix.zuul.message.http.HttpRequestMessage; import io.netty.handler.codec.http.HttpResponse; import io.netty.util.ReferenceCounted; import io.netty.util.ResourceLeakDetector; diff --git a/zuul-core/src/main/java/com/netflix/netty/common/CategorizedThreadFactory.java b/zuul-core/src/main/java/com/netflix/netty/common/CategorizedThreadFactory.java index 7a9c5e2cbf..727fc68a85 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/CategorizedThreadFactory.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/CategorizedThreadFactory.java @@ -25,8 +25,7 @@ * Date: 6/8/16 * Time: 11:49 AM */ -public class CategorizedThreadFactory implements ThreadFactory -{ +public class CategorizedThreadFactory implements ThreadFactory { private String category; private int num = 0; @@ -36,8 +35,7 @@ public CategorizedThreadFactory(String category) { } public Thread newThread(final Runnable r) { - final FastThreadLocalThread t = new FastThreadLocalThread(r, - category + "-" + num++); + final FastThreadLocalThread t = new FastThreadLocalThread(r, category + "-" + num++); return t; } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/ConnectionCloseChannelAttributes.java b/zuul-core/src/main/java/com/netflix/netty/common/ConnectionCloseChannelAttributes.java index 3f9d3a65d2..1309c9b1eb 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/ConnectionCloseChannelAttributes.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/ConnectionCloseChannelAttributes.java @@ -23,21 +23,21 @@ import io.netty.channel.ChannelPromise; import io.netty.util.AttributeKey; -public class ConnectionCloseChannelAttributes -{ - public static final AttributeKey CLOSE_AFTER_RESPONSE = AttributeKey.newInstance("CLOSE_AFTER_RESPONSE"); +public class ConnectionCloseChannelAttributes { + public static final AttributeKey CLOSE_AFTER_RESPONSE = + AttributeKey.newInstance("CLOSE_AFTER_RESPONSE"); public static final AttributeKey CLOSE_TYPE = AttributeKey.newInstance("CLOSE_TYPE"); - public static int gracefulCloseDelay(Channel channel) - { - ChannelConfig channelConfig = channel.attr(BaseZuulChannelInitializer.ATTR_CHANNEL_CONFIG).get(); + public static int gracefulCloseDelay(Channel channel) { + ChannelConfig channelConfig = + channel.attr(BaseZuulChannelInitializer.ATTR_CHANNEL_CONFIG).get(); Integer gracefulCloseDelay = channelConfig.get(CommonChannelConfigKeys.connCloseDelay); return gracefulCloseDelay == null ? 0 : gracefulCloseDelay; } - public static boolean allowGracefulDelayed(Channel channel) - { - ChannelConfig channelConfig = channel.attr(BaseZuulChannelInitializer.ATTR_CHANNEL_CONFIG).get(); + public static boolean allowGracefulDelayed(Channel channel) { + ChannelConfig channelConfig = + channel.attr(BaseZuulChannelInitializer.ATTR_CHANNEL_CONFIG).get(); Boolean value = channelConfig.get(CommonChannelConfigKeys.http2AllowGracefulDelayed); return value == null ? false : value; } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/ConnectionCloseType.java b/zuul-core/src/main/java/com/netflix/netty/common/ConnectionCloseType.java index ab40c44ba3..2d4354071b 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/ConnectionCloseType.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/ConnectionCloseType.java @@ -23,13 +23,14 @@ * Date: 2/8/17 * Time: 2:04 PM */ -public enum ConnectionCloseType -{ - IMMEDIATE, GRACEFUL, DELAYED_GRACEFUL; +public enum ConnectionCloseType { + IMMEDIATE, + GRACEFUL, + DELAYED_GRACEFUL; - public static ConnectionCloseType fromChannel(Channel ch) - { - ConnectionCloseType type = ch.attr(ConnectionCloseChannelAttributes.CLOSE_TYPE).get(); + public static ConnectionCloseType fromChannel(Channel ch) { + ConnectionCloseType type = + ch.attr(ConnectionCloseChannelAttributes.CLOSE_TYPE).get(); if (type == null) { // Default to immediate. type = ConnectionCloseType.IMMEDIATE; @@ -37,8 +38,7 @@ public static ConnectionCloseType fromChannel(Channel ch) return type; } - public static void setForChannel(Channel ch, ConnectionCloseType type) - { + public static void setForChannel(Channel ch, ConnectionCloseType type) { ch.attr(ConnectionCloseChannelAttributes.CLOSE_TYPE).set(type); } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/Http1ConnectionCloseHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/Http1ConnectionCloseHandler.java index 847b96ba7c..c6e07f64e2 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/Http1ConnectionCloseHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/Http1ConnectionCloseHandler.java @@ -34,16 +34,16 @@ * Date: 2/8/17 * Time: 2:03 PM */ -public class Http1ConnectionCloseHandler extends ChannelDuplexHandler -{ +public class Http1ConnectionCloseHandler extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(Http1ConnectionCloseHandler.class); private final AtomicBoolean requestInflight = new AtomicBoolean(Boolean.FALSE); @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { - ChannelPromise closePromise = ctx.channel().attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE).get(); + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + ChannelPromise closePromise = ctx.channel() + .attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE) + .get(); if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; @@ -68,21 +68,18 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) } @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception - { + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { // Track when there's an inflight request. if (evt instanceof HttpLifecycleChannelHandler.StartEvent) { requestInflight.set(Boolean.TRUE); - } - else if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) { + } else if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) { requestInflight.set(Boolean.FALSE); } super.userEventTriggered(ctx, evt); } - protected void closeChannel(ChannelHandlerContext ctx, ConnectionCloseType evt, ChannelPromise promise) - { + protected void closeChannel(ChannelHandlerContext ctx, ConnectionCloseType evt, ChannelPromise promise) { switch (evt) { case DELAYED_GRACEFUL: gracefully(ctx, promise); @@ -98,48 +95,51 @@ protected void closeChannel(ChannelHandlerContext ctx, ConnectionCloseType evt, } } - protected void gracefully(ChannelHandlerContext ctx, ChannelPromise promise) - { + protected void gracefully(ChannelHandlerContext ctx, ChannelPromise promise) { final Channel channel = ctx.channel(); if (channel.isActive()) { final String channelId = channel.id().asShortText(); // In gracefulCloseDelay secs time, go ahead and close the connection if it hasn't already been. int gracefulCloseDelay = ConnectionCloseChannelAttributes.gracefulCloseDelay(channel); - ctx.executor().schedule(() -> { - - // Check that the client hasn't already closed the connection. - if (channel.isActive()) { - - // If there is still an inflight request, then don't close the conn now. Instead assume that it will be closed - // either after the response finally gets written (due to us having set the CLOSE_AFTER_RESPONSE flag), or when the IdleTimeout - // for this conn fires. - if (requestInflight.get()) { - LOG.debug("gracefully: firing graceful_shutdown event to close connection, but request still inflight, so leaving. channel={}", channelId); - } - else { - LOG.debug("gracefully: firing graceful_shutdown event to close connection. channel={}", channelId); - ctx.close(promise); - } - } - else { - LOG.debug("gracefully: connection already closed. channel={}", channelId); - promise.setSuccess(); - } - - }, gracefulCloseDelay, TimeUnit.SECONDS); - } - else { + ctx.executor() + .schedule( + () -> { + + // Check that the client hasn't already closed the connection. + if (channel.isActive()) { + + // If there is still an inflight request, then don't close the conn now. Instead + // assume that it will be closed + // either after the response finally gets written (due to us having set the + // CLOSE_AFTER_RESPONSE flag), or when the IdleTimeout + // for this conn fires. + if (requestInflight.get()) { + LOG.debug( + "gracefully: firing graceful_shutdown event to close connection, but request still inflight, so leaving. channel={}", + channelId); + } else { + LOG.debug( + "gracefully: firing graceful_shutdown event to close connection. channel={}", + channelId); + ctx.close(promise); + } + } else { + LOG.debug("gracefully: connection already closed. channel={}", channelId); + promise.setSuccess(); + } + }, + gracefulCloseDelay, + TimeUnit.SECONDS); + } else { promise.setSuccess(); } } - protected void immediately(ChannelHandlerContext ctx, ChannelPromise promise) - { + protected void immediately(ChannelHandlerContext ctx, ChannelPromise promise) { if (ctx.channel().isActive()) { ctx.close(promise); - } - else { + } else { promise.setSuccess(); } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/Http1ConnectionExpiryHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/Http1ConnectionExpiryHandler.java index dd1be27c6c..8056c247c7 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/Http1ConnectionExpiryHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/Http1ConnectionExpiryHandler.java @@ -23,16 +23,13 @@ * Date: 2/8/17 * Time: 9:58 AM */ -public class Http1ConnectionExpiryHandler extends AbstrHttpConnectionExpiryHandler -{ - public Http1ConnectionExpiryHandler(int maxRequests, int maxRequestsUnderBrownout, int maxExpiry) - { +public class Http1ConnectionExpiryHandler extends AbstrHttpConnectionExpiryHandler { + public Http1ConnectionExpiryHandler(int maxRequests, int maxRequestsUnderBrownout, int maxExpiry) { super(ConnectionCloseType.GRACEFUL, maxRequestsUnderBrownout, maxRequests, maxExpiry); } @Override - protected boolean isResponseHeaders(Object msg) - { + protected boolean isResponseHeaders(Object msg) { return msg instanceof HttpResponse; } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/Http2ConnectionCloseHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/Http2ConnectionCloseHandler.java index 9a08c99d36..5fefce1bee 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/Http2ConnectionCloseHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/Http2ConnectionCloseHandler.java @@ -43,25 +43,21 @@ * Time: 2:03 PM */ @ChannelHandler.Sharable -public class Http2ConnectionCloseHandler extends ChannelDuplexHandler -{ +public class Http2ConnectionCloseHandler extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(Http2ConnectionCloseHandler.class); private final Registry registry; private final Id counterBaseId; @Inject - public Http2ConnectionCloseHandler(Registry registry) - { + public Http2ConnectionCloseHandler(Registry registry) { super(); this.registry = registry; this.counterBaseId = registry.createId("server.connection.close.handled"); } - private void incrementCounter(ConnectionCloseType closeType, int port) - { - registry.counter( - counterBaseId + private void incrementCounter(ConnectionCloseType closeType, int port) { + registry.counter(counterBaseId .withTag("close_type", closeType.name()) .withTag("port", Integer.toString(port)) .withTag("protocol", "http2")) @@ -69,8 +65,7 @@ private void incrementCounter(ConnectionCloseType closeType, int port) } @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { // Close the connection immediately after LastContent is written, rather than // waiting until the graceful-delay is up if this flag is set. if (isEndOfRequestResponse(msg)) { @@ -97,17 +92,18 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) * @param parent * @return */ - private ChannelPromise shouldCloseAfter(ChannelHandlerContext ctx, Channel parent) - { - ChannelPromise closeAfterPromise = ctx.channel().attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE).get(); + private ChannelPromise shouldCloseAfter(ChannelHandlerContext ctx, Channel parent) { + ChannelPromise closeAfterPromise = ctx.channel() + .attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE) + .get(); if (closeAfterPromise == null) { - closeAfterPromise = parent.attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE).get(); + closeAfterPromise = parent.attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE) + .get(); } return closeAfterPromise; } - private boolean isEndOfRequestResponse(Object msg) - { + private boolean isEndOfRequestResponse(Object msg) { if (msg instanceof Http2HeadersFrame) { return ((Http2HeadersFrame) msg).isEndStream(); } @@ -117,8 +113,7 @@ private boolean isEndOfRequestResponse(Object msg) return false; } - private void closeChannel(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception - { + private void closeChannel(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { Channel child = ctx.channel(); Channel parent = HttpUtils.getMainChannel(ctx); @@ -139,8 +134,9 @@ private void closeChannel(ChannelHandlerContext ctx, ChannelPromise promise) thr // Close according to the specified close type. ConnectionCloseType closeType = ConnectionCloseType.fromChannel(parent); - Integer port = parent.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).get(); - port = port == null ? -1 :port; + Integer port = + parent.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).get(); + port = port == null ? -1 : port; incrementCounter(closeType, port); switch (closeType) { case DELAYED_GRACEFUL: @@ -166,16 +162,15 @@ private void closeChannel(ChannelHandlerContext ctx, ChannelPromise promise) thr * See this code in okhttp where it drops response header frame if state is already shutdown: * https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/internal/http2/Http2Connection.java#L609 */ - private void gracefullyWithDelay(EventExecutor executor, Channel parent, ChannelPromise promise) - { + private void gracefullyWithDelay(EventExecutor executor, Channel parent, ChannelPromise promise) { // See javadoc for explanation of why this may be disabled. boolean allowGracefulDelayed = ConnectionCloseChannelAttributes.allowGracefulDelayed(parent); - if (! allowGracefulDelayed) { + if (!allowGracefulDelayed) { immediate(parent, promise); return; } - if (! parent.isActive()) { + if (!parent.isActive()) { promise.setSuccess(); return; } @@ -190,50 +185,55 @@ private void gracefullyWithDelay(EventExecutor executor, Channel parent, Channel DefaultHttp2GoAwayFrame goaway = new DefaultHttp2GoAwayFrame(Http2Error.NO_ERROR); goaway.setExtraStreamIds(Integer.MAX_VALUE); parent.writeAndFlush(goaway); - LOG.debug("gracefullyWithDelay: flushed initial go_away frame. channel={}", parent.id().asShortText()); + LOG.debug( + "gracefullyWithDelay: flushed initial go_away frame. channel={}", + parent.id().asShortText()); // In N secs time, throw an error that causes the http2 codec to send another GOAWAY frame // (this time with accurate lastStreamId) and then close the connection. int gracefulCloseDelay = ConnectionCloseChannelAttributes.gracefulCloseDelay(parent); - executor.schedule(() -> { - - // Check that the client hasn't already closed the connection (due to the earlier goaway we sent). - if (parent.isActive()) { - // NOTE - the netty Http2ConnectionHandler specifically does not send another goaway when we call - // channel.close() if one has already been sent .... so when we want more than one sent, we need to do it - // explicitly ourselves like this. - LOG.debug("gracefullyWithDelay: firing graceful_shutdown event to make netty send a final go_away frame and then close connection. channel={}", parent.id().asShortText()); - Http2Exception h2e = new Http2Exception(Http2Error.NO_ERROR, Http2Exception.ShutdownHint.GRACEFUL_SHUTDOWN); - parent.pipeline().fireExceptionCaught(h2e); - - parent.close().addListener(future -> { - promise.setSuccess(); - }); - } else { - promise.setSuccess(); - } - - }, gracefulCloseDelay, TimeUnit.SECONDS); + executor.schedule( + () -> { + + // Check that the client hasn't already closed the connection (due to the earlier goaway we sent). + if (parent.isActive()) { + // NOTE - the netty Http2ConnectionHandler specifically does not send another goaway when we + // call + // channel.close() if one has already been sent .... so when we want more than one sent, we need + // to do it + // explicitly ourselves like this. + LOG.debug( + "gracefullyWithDelay: firing graceful_shutdown event to make netty send a final go_away frame and then close connection. channel={}", + parent.id().asShortText()); + Http2Exception h2e = + new Http2Exception(Http2Error.NO_ERROR, Http2Exception.ShutdownHint.GRACEFUL_SHUTDOWN); + parent.pipeline().fireExceptionCaught(h2e); + + parent.close().addListener(future -> { + promise.setSuccess(); + }); + } else { + promise.setSuccess(); + } + }, + gracefulCloseDelay, + TimeUnit.SECONDS); } - private void immediate(Channel parent, ChannelPromise promise) - { + private void immediate(Channel parent, ChannelPromise promise) { if (parent.isActive()) { parent.close().addListener(new DelegatingChannelPromiseNotifier(promise)); - } - else { + } else { promise.setSuccess(); } } - protected boolean isAlreadyClosing(Channel parentChannel) - { + protected boolean isAlreadyClosing(Channel parentChannel) { // If already closing, then just return. // This will happen because close() is called a 2nd time after sending the goaway frame. if (HttpChannelFlags.CLOSING.get(parentChannel)) { return true; - } - else { + } else { HttpChannelFlags.CLOSING.set(parentChannel); return false; } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/Http2ConnectionExpiryHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/Http2ConnectionExpiryHandler.java index 8127deae1e..ec3e3adf6d 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/Http2ConnectionExpiryHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/Http2ConnectionExpiryHandler.java @@ -27,16 +27,13 @@ * Time: 9:58 AM */ @ChannelHandler.Sharable -public class Http2ConnectionExpiryHandler extends AbstrHttpConnectionExpiryHandler -{ - public Http2ConnectionExpiryHandler(int maxRequests, int maxRequestsUnderBrownout, int maxExpiry) - { +public class Http2ConnectionExpiryHandler extends AbstrHttpConnectionExpiryHandler { + public Http2ConnectionExpiryHandler(int maxRequests, int maxRequestsUnderBrownout, int maxExpiry) { super(ConnectionCloseType.DELAYED_GRACEFUL, maxRequestsUnderBrownout, maxRequests, maxExpiry); } @Override - protected boolean isResponseHeaders(Object msg) - { + protected boolean isResponseHeaders(Object msg) { return msg instanceof Http2HeadersFrame; } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/HttpChannelFlags.java b/zuul-core/src/main/java/com/netflix/netty/common/HttpChannelFlags.java index ec7e6ce3d1..b4f9eab15a 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/HttpChannelFlags.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/HttpChannelFlags.java @@ -26,45 +26,37 @@ * Date: 7/10/17 * Time: 4:29 PM */ -public class HttpChannelFlags -{ +public class HttpChannelFlags { public static final Flag IN_BROWNOUT = new Flag("_brownout"); public static final Flag CLOSING = new Flag("_connection_closing"); - public static class Flag - { + public static class Flag { private final AttributeKey attributeKey; - public Flag(String name) - { + public Flag(String name) { attributeKey = AttributeKey.newInstance(name); } - public void set(Channel ch) - { + public void set(Channel ch) { ch.attr(attributeKey).set(Boolean.TRUE); } - public void remove(Channel ch) - { + public void remove(Channel ch) { ch.attr(attributeKey).set(null); } - public void set(ChannelHandlerContext ctx) - { + public void set(ChannelHandlerContext ctx) { set(ctx.channel()); } - public boolean get(Channel ch) - { + public boolean get(Channel ch) { Attribute attr = ch.attr(attributeKey); Boolean value = attr.get(); return (value == null) ? false : value; } - public boolean get(ChannelHandlerContext ctx) - { + public boolean get(ChannelHandlerContext ctx) { return get(ctx.channel()); } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/HttpClientLifecycleChannelHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/HttpClientLifecycleChannelHandler.java index fe7ea3a3b5..31ea09d565 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/HttpClientLifecycleChannelHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/HttpClientLifecycleChannelHandler.java @@ -28,25 +28,21 @@ /** * @author michaels */ -public class HttpClientLifecycleChannelHandler extends HttpLifecycleChannelHandler -{ +public class HttpClientLifecycleChannelHandler extends HttpLifecycleChannelHandler { public static final ChannelHandler INBOUND_CHANNEL_HANDLER = new HttpClientLifecycleInboundChannelHandler(); public static final ChannelHandler OUTBOUND_CHANNEL_HANDLER = new HttpClientLifecycleOutboundChannelHandler(); @ChannelHandler.Sharable - private static class HttpClientLifecycleInboundChannelHandler extends ChannelInboundHandlerAdapter - { + private static class HttpClientLifecycleInboundChannelHandler extends ChannelInboundHandlerAdapter { @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpResponse) { ctx.channel().attr(ATTR_HTTP_RESP).set((HttpResponse) msg); } try { super.channelRead(ctx, msg); - } - finally { + } finally { if (msg instanceof LastHttpContent) { fireCompleteEventIfNotAlready(ctx, CompleteReason.SESSION_COMPLETE); } @@ -54,24 +50,19 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception } @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception - { + public void channelInactive(ChannelHandlerContext ctx) throws Exception { try { super.channelInactive(ctx); - } - finally { + } finally { fireCompleteEventIfNotAlready(ctx, CompleteReason.INACTIVE); } } - } @ChannelHandler.Sharable - private static class HttpClientLifecycleOutboundChannelHandler extends ChannelOutboundHandlerAdapter - { + private static class HttpClientLifecycleOutboundChannelHandler extends ChannelOutboundHandlerAdapter { @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof HttpRequest) { fireStartEvent(ctx, (HttpRequest) msg); } @@ -80,32 +71,28 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) } @Override - public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception - { + public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { fireCompleteEventIfNotAlready(ctx, CompleteReason.DISCONNECT); super.disconnect(ctx, promise); } @Override - public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception - { + public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { fireCompleteEventIfNotAlready(ctx, CompleteReason.DEREGISTER); super.deregister(ctx, promise); } @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception - { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { super.exceptionCaught(ctx, cause); fireCompleteEventIfNotAlready(ctx, CompleteReason.EXCEPTION); } @Override - public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception - { + public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { fireCompleteEventIfNotAlready(ctx, CompleteReason.CLOSE); super.close(ctx, promise); diff --git a/zuul-core/src/main/java/com/netflix/netty/common/HttpLifecycleChannelHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/HttpLifecycleChannelHandler.java index 0e06b8463d..71fb3e304f 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/HttpLifecycleChannelHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/HttpLifecycleChannelHandler.java @@ -38,17 +38,18 @@ public abstract class HttpLifecycleChannelHandler { public static final AttributeKey ATTR_HTTP_REQ = AttributeKey.newInstance("_http_request"); public static final AttributeKey ATTR_HTTP_RESP = AttributeKey.newInstance("_http_response"); - public static final AttributeKey ATTR_HTTP_PIPELINE_REJECT = AttributeKey.newInstance("_http_pipeline_reject"); + public static final AttributeKey ATTR_HTTP_PIPELINE_REJECT = + AttributeKey.newInstance("_http_pipeline_reject"); protected enum State { - STARTED, COMPLETED + STARTED, + COMPLETED } @VisibleForTesting protected static final AttributeKey ATTR_STATE = AttributeKey.newInstance("_httplifecycle_state"); - protected static boolean fireStartEvent(ChannelHandlerContext ctx, HttpRequest request) - { + protected static boolean fireStartEvent(ChannelHandlerContext ctx, HttpRequest request) { // Only allow this method to run once per request. Channel channel = ctx.channel(); Attribute attr = channel.attr(ATTR_STATE); @@ -57,21 +58,22 @@ protected static boolean fireStartEvent(ChannelHandlerContext ctx, HttpRequest r if (state == State.STARTED) { // This could potentially happen if a bad client sends a 2nd request on the same connection // without waiting for the response from the first. And we don't support HTTP Pipelining. - logger.debug("Received a http request on connection where we already have a request being processed. Closing the connection now. channel = {}", channel.id().asLongText()); + logger.debug( + "Received a http request on connection where we already have a request being processed. Closing the connection now. channel = {}", + channel.id().asLongText()); channel.attr(ATTR_HTTP_PIPELINE_REJECT).set(Boolean.TRUE); channel.close(); return false; } - + channel.attr(ATTR_STATE).set(State.STARTED); channel.attr(ATTR_HTTP_REQ).set(request); ctx.pipeline().fireUserEventTriggered(new StartEvent(request)); - + return true; } - protected static boolean fireCompleteEventIfNotAlready(ChannelHandlerContext ctx, CompleteReason reason) - { + protected static boolean fireCompleteEventIfNotAlready(ChannelHandlerContext ctx, CompleteReason reason) { // Only allow this method to run once per request. Attribute attr = ctx.channel().attr(ATTR_STATE); State state = attr.get(); @@ -79,7 +81,7 @@ protected static boolean fireCompleteEventIfNotAlready(ChannelHandlerContext ctx if (state == null || state != State.STARTED) { return false; } - + attr.set(State.COMPLETED); HttpRequest request = ctx.channel().attr(ATTR_HTTP_REQ).get(); @@ -91,92 +93,83 @@ protected static boolean fireCompleteEventIfNotAlready(ChannelHandlerContext ctx // Fire the event to whole pipeline. ctx.pipeline().fireUserEventTriggered(new CompleteEvent(reason, request, response)); - + return true; } - protected static void addPassportState(ChannelHandlerContext ctx, PassportState state) - { + protected static void addPassportState(ChannelHandlerContext ctx, PassportState state) { CurrentPassport passport = CurrentPassport.fromChannel(ctx.channel()); passport.add(state); } - public enum CompleteReason - { + public enum CompleteReason { SESSION_COMPLETE, INACTIVE, -// IDLE, + // IDLE, DISCONNECT, DEREGISTER, PIPELINE_REJECT, EXCEPTION, CLOSE -// FAILURE_CLIENT_CANCELLED, -// FAILURE_CLIENT_TIMEOUT; - -// private final NfStatus nfStatus; -// private final int responseStatus; -// -// CompleteReason(NfStatus nfStatus, int responseStatus) { -// this.nfStatus = nfStatus; -// this.responseStatus = responseStatus; -// } -// -// CompleteReason() { -// //For status that never gets returned back to client, like channel inactive -// nfStatus = null; -// responseStatus = 501; -// } -// -// public NfStatus getNfStatus() { -// return nfStatus; -// } -// -// public int getResponseStatus() { -// return responseStatus; -// } + // FAILURE_CLIENT_CANCELLED, + // FAILURE_CLIENT_TIMEOUT; + + // private final NfStatus nfStatus; + // private final int responseStatus; + // + // CompleteReason(NfStatus nfStatus, int responseStatus) { + // this.nfStatus = nfStatus; + // this.responseStatus = responseStatus; + // } + // + // CompleteReason() { + // //For status that never gets returned back to client, like channel inactive + // nfStatus = null; + // responseStatus = 501; + // } + // + // public NfStatus getNfStatus() { + // return nfStatus; + // } + // + // public int getResponseStatus() { + // return responseStatus; + // } } - + public static class StartEvent { private final HttpRequest request; - public StartEvent(HttpRequest request) - { + public StartEvent(HttpRequest request) { this.request = request; } - public HttpRequest getRequest() - { + public HttpRequest getRequest() { return request; } } - + public static class CompleteEvent { private final CompleteReason reason; private final HttpRequest request; private final HttpResponse response; - public CompleteEvent(CompleteReason reason, HttpRequest request, HttpResponse response) - { + public CompleteEvent(CompleteReason reason, HttpRequest request, HttpResponse response) { this.reason = reason; this.request = request; this.response = response; } - public CompleteReason getReason() - { + public CompleteReason getReason() { return reason; } - public HttpRequest getRequest() - { + public HttpRequest getRequest() { return request; } - - public HttpResponse getResponse() - { + + public HttpResponse getResponse() { return response; } } - } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/HttpRequestReadTimeoutEvent.java b/zuul-core/src/main/java/com/netflix/netty/common/HttpRequestReadTimeoutEvent.java index 30928f2055..5370ab74c5 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/HttpRequestReadTimeoutEvent.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/HttpRequestReadTimeoutEvent.java @@ -21,7 +21,6 @@ * * ie. time between receiving request headers and LastHttpContent of request body. */ -public class HttpRequestReadTimeoutEvent -{ +public class HttpRequestReadTimeoutEvent { public static final HttpRequestReadTimeoutEvent INSTANCE = new HttpRequestReadTimeoutEvent(); } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/HttpRequestReadTimeoutHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/HttpRequestReadTimeoutHandler.java index 43639ee7a1..046916c54d 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/HttpRequestReadTimeoutHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/HttpRequestReadTimeoutHandler.java @@ -37,8 +37,7 @@ * * @author michaels */ -public class HttpRequestReadTimeoutHandler extends ChannelInboundHandlerAdapter -{ +public class HttpRequestReadTimeoutHandler extends ChannelInboundHandlerAdapter { private static final String HANDLER_NAME = "http_request_read_timeout_handler"; private static final String INTERNAL_HANDLER_NAME = "http_request_read_timeout_internal"; @@ -46,8 +45,7 @@ public class HttpRequestReadTimeoutHandler extends ChannelInboundHandlerAdapter private final TimeUnit unit; private final Counter httpRequestReadTimeoutCounter; - protected HttpRequestReadTimeoutHandler(long timeout, TimeUnit unit, Counter httpRequestReadTimeoutCounter) - { + protected HttpRequestReadTimeoutHandler(long timeout, TimeUnit unit, Counter httpRequestReadTimeoutCounter) { this.timeout = timeout; this.unit = unit; this.httpRequestReadTimeoutCounter = httpRequestReadTimeoutCounter; @@ -57,19 +55,18 @@ protected HttpRequestReadTimeoutHandler(long timeout, TimeUnit unit, Counter htt * Factory which ensures that this handler is added to the pipeline using the * correct name. */ - public static void addLast(ChannelPipeline pipeline, long timeout, TimeUnit unit, Counter httpRequestReadTimeoutCounter) - { - HttpRequestReadTimeoutHandler handler = new HttpRequestReadTimeoutHandler(timeout, unit, httpRequestReadTimeoutCounter); + public static void addLast( + ChannelPipeline pipeline, long timeout, TimeUnit unit, Counter httpRequestReadTimeoutCounter) { + HttpRequestReadTimeoutHandler handler = + new HttpRequestReadTimeoutHandler(timeout, unit, httpRequestReadTimeoutCounter); pipeline.addLast(HANDLER_NAME, handler); } @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof LastHttpContent) { removeInternalHandler(ctx); - } - else if (msg instanceof HttpRequest) { + } else if (msg instanceof HttpRequest) { // Start timeout handler. InternalReadTimeoutHandler handler = new InternalReadTimeoutHandler(timeout, unit); ctx.pipeline().addBefore(HANDLER_NAME, INTERNAL_HANDLER_NAME, handler); @@ -79,8 +76,7 @@ else if (msg instanceof HttpRequest) { } @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception - { + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof HttpRequestReadTimeoutEvent) { CurrentPassport.fromChannel(ctx.channel()).add(PassportState.IN_REQ_READ_TIMEOUT); removeInternalHandler(ctx); @@ -91,39 +87,32 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc } @Override - public void handlerRemoved(ChannelHandlerContext ctx) throws Exception - { + public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { removeInternalHandler(ctx); super.handlerRemoved(ctx); } @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception - { + public void channelInactive(ChannelHandlerContext ctx) throws Exception { removeInternalHandler(ctx); super.channelInactive(ctx); } - protected void removeInternalHandler(ChannelHandlerContext ctx) - { + protected void removeInternalHandler(ChannelHandlerContext ctx) { // Remove timeout handler if not already removed. ChannelHandlerContext handlerContext = ctx.pipeline().context(INTERNAL_HANDLER_NAME); - if (handlerContext != null && ! handlerContext.isRemoved()) { + if (handlerContext != null && !handlerContext.isRemoved()) { ctx.pipeline().remove(INTERNAL_HANDLER_NAME); } } - - static class InternalReadTimeoutHandler extends ReadTimeoutHandler - { - public InternalReadTimeoutHandler(long timeout, TimeUnit unit) - { + static class InternalReadTimeoutHandler extends ReadTimeoutHandler { + public InternalReadTimeoutHandler(long timeout, TimeUnit unit) { super(timeout, unit); } @Override - protected void readTimedOut(ChannelHandlerContext ctx) throws Exception - { + protected void readTimedOut(ChannelHandlerContext ctx) throws Exception { ctx.fireUserEventTriggered(HttpRequestReadTimeoutEvent.INSTANCE); } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/HttpServerLifecycleChannelHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/HttpServerLifecycleChannelHandler.java index ab838f7831..8fb0a9a392 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/HttpServerLifecycleChannelHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/HttpServerLifecycleChannelHandler.java @@ -30,57 +30,50 @@ /** * @author michaels */ -public final class HttpServerLifecycleChannelHandler extends HttpLifecycleChannelHandler -{ - public static final class HttpServerLifecycleInboundChannelHandler extends ChannelInboundHandlerAdapter - { +public final class HttpServerLifecycleChannelHandler extends HttpLifecycleChannelHandler { + public static final class HttpServerLifecycleInboundChannelHandler extends ChannelInboundHandlerAdapter { @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { - // Fire start event, and if that succeeded, then allow processing to + // Fire start event, and if that succeeded, then allow processing to // continue to next handler in pipeline. if (fireStartEvent(ctx, (HttpRequest) msg)) { super.channelRead(ctx, msg); } else { ReferenceCountUtil.release(msg); } - } - else { + } else { super.channelRead(ctx, msg); } } @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception - { + public void channelInactive(ChannelHandlerContext ctx) throws Exception { fireCompleteEventIfNotAlready(ctx, CompleteReason.INACTIVE); super.channelInactive(ctx); } - } - public static final class HttpServerLifecycleOutboundChannelHandler extends ChannelOutboundHandlerAdapter - { + public static final class HttpServerLifecycleOutboundChannelHandler extends ChannelOutboundHandlerAdapter { @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof HttpResponse) { ctx.channel().attr(ATTR_HTTP_RESP).set((HttpResponse) msg); } - + try { super.write(ctx, msg, promise); - } - finally { + } finally { if (msg instanceof LastHttpContent) { boolean dontFireCompleteYet = false; if (msg instanceof HttpResponse) { - // Handle case of 100 CONTINUE, where server sends an initial 100 status response to indicate to client + // Handle case of 100 CONTINUE, where server sends an initial 100 status response to indicate to + // client // that it can continue sending the initial request body. - // ie. in this case we don't want to consider the state to be COMPLETE until after the 2nd response. + // ie. in this case we don't want to consider the state to be COMPLETE until after the 2nd + // response. if (((HttpResponse) msg).status() == HttpResponseStatus.CONTINUE) { dontFireCompleteYet = true; } @@ -100,25 +93,25 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) } @Override - public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception - { + public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { fireCompleteEventIfNotAlready(ctx, CompleteReason.DISCONNECT); super.disconnect(ctx, promise); } @Override - public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception - { + public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { addPassportState(ctx, PassportState.SERVER_CH_CLOSE); // This will likely expand based on more specific reasons for completion - if (ctx.channel().attr(HttpLifecycleChannelHandler.ATTR_HTTP_PIPELINE_REJECT).get() == null) { + if (ctx.channel() + .attr(HttpLifecycleChannelHandler.ATTR_HTTP_PIPELINE_REJECT) + .get() + == null) { fireCompleteEventIfNotAlready(ctx, CompleteReason.CLOSE); } else { fireCompleteEventIfNotAlready(ctx, CompleteReason.PIPELINE_REJECT); } super.close(ctx, promise); } - } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/LeastConnsEventLoopChooserFactory.java b/zuul-core/src/main/java/com/netflix/netty/common/LeastConnsEventLoopChooserFactory.java index 66c0a5a269..9d19860cea 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/LeastConnsEventLoopChooserFactory.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/LeastConnsEventLoopChooserFactory.java @@ -33,52 +33,44 @@ * Date: 2/7/17 * Time: 2:44 PM */ -public class LeastConnsEventLoopChooserFactory implements EventExecutorChooserFactory -{ +public class LeastConnsEventLoopChooserFactory implements EventExecutorChooserFactory { private static final Logger LOG = LoggerFactory.getLogger(LeastConnsEventLoopChooserFactory.class); private final EventLoopGroupMetrics groupMetrics; - public LeastConnsEventLoopChooserFactory(EventLoopGroupMetrics groupMetrics) - { + public LeastConnsEventLoopChooserFactory(EventLoopGroupMetrics groupMetrics) { this.groupMetrics = groupMetrics; } @Override - public EventExecutorChooser newChooser(EventExecutor[] executors) - { + public EventExecutorChooser newChooser(EventExecutor[] executors) { return new LeastConnsEventExecutorChooser(executors, groupMetrics); } - private static class LeastConnsEventExecutorChooser implements EventExecutorChooser - { + private static class LeastConnsEventExecutorChooser implements EventExecutorChooser { private final List executors; private final EventLoopGroupMetrics groupMetrics; - public LeastConnsEventExecutorChooser(EventExecutor[] executors, final EventLoopGroupMetrics groupMetrics) - { + public LeastConnsEventExecutorChooser(EventExecutor[] executors, final EventLoopGroupMetrics groupMetrics) { this.executors = Arrays.asList(executors); this.groupMetrics = groupMetrics; } @Override - public EventExecutor next() - { + public EventExecutor next() { return chooseWithLeastConns(); } - private EventExecutor chooseWithLeastConns() - { + private EventExecutor chooseWithLeastConns() { EventExecutor leastExec = null; int leastValue = Integer.MAX_VALUE; - + Map connsPer = groupMetrics.connectionsPerEventLoop(); // Shuffle the list of executors each time so that if they all have the same number of connections, then // we don't favour the 1st one. Collections.shuffle(executors, ThreadLocalRandom.current()); - - for (EventExecutor executor : executors) - { + + for (EventExecutor executor : executors) { int value = connsPer.getOrDefault(executor, 0); if (value < leastValue) { leastValue = value; @@ -92,7 +84,11 @@ private EventExecutor chooseWithLeastConns() } if (LOG.isDebugEnabled()) { - LOG.debug("Chose eventloop: {}, leastValue={}, connsPer={}", String.valueOf(leastExec), leastValue, String.valueOf(connsPer)); + LOG.debug( + "Chose eventloop: {}, leastValue={}, connsPer={}", + String.valueOf(leastExec), + leastValue, + String.valueOf(connsPer)); } return leastExec; diff --git a/zuul-core/src/main/java/com/netflix/netty/common/RequestResponseCompleteEvent.java b/zuul-core/src/main/java/com/netflix/netty/common/RequestResponseCompleteEvent.java index 783a1ae8c3..37f726c8fc 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/RequestResponseCompleteEvent.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/RequestResponseCompleteEvent.java @@ -21,6 +21,4 @@ * Date: 5/24/16 * Time: 1:04 PM */ -public class RequestResponseCompleteEvent -{ -} +public class RequestResponseCompleteEvent {} diff --git a/zuul-core/src/main/java/com/netflix/netty/common/SourceAddressChannelHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/SourceAddressChannelHandler.java index 514c300d88..8f097d1738 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/SourceAddressChannelHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/SourceAddressChannelHandler.java @@ -23,13 +23,13 @@ import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.AttributeKey; +import javax.annotation.Nullable; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.UnknownHostException; -import javax.annotation.Nullable; /** * Stores the source IP address as an attribute of the channel. This has the advantage of allowing us to overwrite it if @@ -115,7 +115,9 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.channel().attr(ATTR_LOCAL_ADDRESS).setIfAbsent(getHostAddress(localAddress)); // ATTR_LOCAL_ADDRESS and ATTR_LOCAL_PORT get overwritten with what is received in // Proxy Protocol (via the LB), so set local server's address, port explicitly - ctx.channel().attr(ATTR_SERVER_LOCAL_ADDRESS).setIfAbsent(localAddress.getAddress().getHostAddress()); + ctx.channel() + .attr(ATTR_SERVER_LOCAL_ADDRESS) + .setIfAbsent(localAddress.getAddress().getHostAddress()); ctx.channel().attr(ATTR_SERVER_LOCAL_PORT).setIfAbsent(localAddress.getPort()); super.channelActive(ctx); diff --git a/zuul-core/src/main/java/com/netflix/netty/common/SslExceptionsHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/SslExceptionsHandler.java index 18184d0ef8..ee492783b0 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/SslExceptionsHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/SslExceptionsHandler.java @@ -20,10 +20,11 @@ import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; -import javax.net.ssl.SSLHandshakeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.net.ssl.SSLHandshakeException; + /** * Swallow specific SSL related exceptions to avoid propagating deep stack traces up the pipeline. * @@ -46,7 +47,8 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E // We intentionally avoid propagating this up the pipeline, to avoid verbose disk logging. if (cause.getCause() instanceof SSLHandshakeException) { logger.debug("SSL handshake failed on channel {}", ctx.channel(), cause); - registry.counter("server.ssl.exception.swallowed", "cause", "SSLHandshakeException").increment(); + registry.counter("server.ssl.exception.swallowed", "cause", "SSLHandshakeException") + .increment(); } else { super.exceptionCaught(ctx, cause); } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/SwallowSomeHttp2ExceptionsHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/SwallowSomeHttp2ExceptionsHandler.java index 2114c79f9f..a08856bc94 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/SwallowSomeHttp2ExceptionsHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/SwallowSomeHttp2ExceptionsHandler.java @@ -27,46 +27,42 @@ import org.slf4j.LoggerFactory; @ChannelHandler.Sharable -public class SwallowSomeHttp2ExceptionsHandler extends ChannelOutboundHandlerAdapter -{ +public class SwallowSomeHttp2ExceptionsHandler extends ChannelOutboundHandlerAdapter { private static final Logger LOG = LoggerFactory.getLogger(SwallowSomeHttp2ExceptionsHandler.class); private final Registry registry; - public SwallowSomeHttp2ExceptionsHandler(Registry registry) - { + public SwallowSomeHttp2ExceptionsHandler(Registry registry) { this.registry = registry; } @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception - { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { incrementExceptionCounter(cause); if (cause instanceof Http2Exception) { Http2Exception h2e = (Http2Exception) cause; if (h2e.error() == Http2Error.NO_ERROR && Http2Exception.ShutdownHint.GRACEFUL_SHUTDOWN.equals(h2e.shutdownHint())) { - // This is the exception we threw ourselves to make the http2 codec gracefully close the connection. So just + // This is the exception we threw ourselves to make the http2 codec gracefully close the connection. So + // just // swallow it so that it doesn't propagate and get logged. LOG.debug("Swallowed Http2Exception.ShutdownHint.GRACEFUL_SHUTDOWN ", cause); - } - else { + } else { super.exceptionCaught(ctx, cause); } - } - else if (cause instanceof Errors.NativeIoException) { + } else if (cause instanceof Errors.NativeIoException) { LOG.debug("Swallowed NativeIoException", cause); - } - else { + } else { super.exceptionCaught(ctx, cause); } } - private void incrementExceptionCounter(Throwable throwable) - { - registry.counter("server.connection.pipeline.exception", - "id", throwable.getClass().getSimpleName()) + private void incrementExceptionCounter(Throwable throwable) { + registry.counter( + "server.connection.pipeline.exception", + "id", + throwable.getClass().getSimpleName()) .increment(); } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/accesslog/AccessLogChannelHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/accesslog/AccessLogChannelHandler.java index f1c5bcfa99..4d71d6eb70 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/accesslog/AccessLogChannelHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/accesslog/AccessLogChannelHandler.java @@ -16,6 +16,7 @@ package com.netflix.netty.common.accesslog; +import com.netflix.netty.common.HttpLifecycleChannelHandler; import com.netflix.netty.common.SourceAddressChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; @@ -25,7 +26,6 @@ import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.util.AttributeKey; -import com.netflix.netty.common.HttpLifecycleChannelHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,22 +37,20 @@ * Time: 3:51 PM */ public final class AccessLogChannelHandler { - private static final AttributeKey ATTR_REQ_STATE = AttributeKey.newInstance("_accesslog_requeststate"); + private static final AttributeKey ATTR_REQ_STATE = + AttributeKey.newInstance("_accesslog_requeststate"); private static final Logger LOG = LoggerFactory.getLogger(AccessLogChannelHandler.class); - public static final class AccessLogInboundChannelHandler extends ChannelInboundHandlerAdapter - { + public static final class AccessLogInboundChannelHandler extends ChannelInboundHandlerAdapter { private final AccessLogPublisher publisher; - public AccessLogInboundChannelHandler(AccessLogPublisher publisher) - { + public AccessLogInboundChannelHandler(AccessLogPublisher publisher) { this.publisher = publisher; } @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { RequestState state = new RequestState(); state.request = (HttpRequest) msg; @@ -63,7 +61,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception if (msg instanceof HttpContent) { RequestState state = ctx.channel().attr(ATTR_REQ_STATE).get(); - if (state != null) { + if (state != null) { state.requestBodySize += ((HttpContent) msg).content().readableBytes(); } } @@ -72,39 +70,49 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception } @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception - { - if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) - { + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) { // Get the stored request, and remove the attr from channel to cleanup. RequestState state = ctx.channel().attr(ATTR_REQ_STATE).get(); ctx.channel().attr(ATTR_REQ_STATE).set(null); // Response complete, so now write to access log. long durationNs = System.nanoTime() - state.startTimeNs; - String remoteIp = ctx.channel().attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get(); - Integer localPort = ctx.channel().attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).get(); + String remoteIp = ctx.channel() + .attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS) + .get(); + Integer localPort = ctx.channel() + .attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT) + .get(); if (state.response == null) { - LOG.debug("Response null in AccessLog, Complete reason={}, duration={}, url={}, method={}", - ((HttpLifecycleChannelHandler.CompleteEvent)evt).getReason(), - durationNs/(1000*1000), state.request != null ? state.request.uri() : "-", + LOG.debug( + "Response null in AccessLog, Complete reason={}, duration={}, url={}, method={}", + ((HttpLifecycleChannelHandler.CompleteEvent) evt).getReason(), + durationNs / (1000 * 1000), + state.request != null ? state.request.uri() : "-", state.request != null ? state.request.method() : "-"); } - publisher.log(ctx.channel(), state.request, state.response, state.dateTime, localPort, remoteIp, durationNs, - state.requestBodySize, state.responseBodySize); + publisher.log( + ctx.channel(), + state.request, + state.response, + state.dateTime, + localPort, + remoteIp, + durationNs, + state.requestBodySize, + state.responseBodySize); } super.userEventTriggered(ctx, evt); } } - public static final class AccessLogOutboundChannelHandler extends ChannelOutboundHandlerAdapter - { + public static final class AccessLogOutboundChannelHandler extends ChannelOutboundHandlerAdapter { @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { RequestState state = ctx.channel().attr(ATTR_REQ_STATE).get(); if (msg instanceof HttpResponse) { @@ -120,8 +128,7 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) } } - private static class RequestState - { + private static class RequestState { LocalDateTime dateTime = LocalDateTime.now(); HttpRequest request; HttpResponse response; diff --git a/zuul-core/src/main/java/com/netflix/netty/common/accesslog/AccessLogPublisher.java b/zuul-core/src/main/java/com/netflix/netty/common/accesslog/AccessLogPublisher.java index 11e608f725..66ab47921c 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/accesslog/AccessLogPublisher.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/accesslog/AccessLogPublisher.java @@ -30,16 +30,17 @@ import java.util.List; import java.util.function.BiFunction; -public class AccessLogPublisher -{ - private final static char DELIM = '\t'; - private final static DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME; - - private final static List LOG_REQ_HEADERS = - new DynamicStringListProperty("zuul.access.log.requestheaders", "host,x-forwarded-for,x-forwarded-proto,x-forwarded-host,x-forwarded-port,user-agent").get(); - private final static List LOG_RESP_HEADERS = +public class AccessLogPublisher { + private static final char DELIM = '\t'; + private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME; + + private static final List LOG_REQ_HEADERS = new DynamicStringListProperty( + "zuul.access.log.requestheaders", + "host,x-forwarded-for,x-forwarded-proto,x-forwarded-host,x-forwarded-port,user-agent") + .get(); + private static final List LOG_RESP_HEADERS = new DynamicStringListProperty("zuul.access.log.responseheaders", "server,via,content-type").get(); - private final static DynamicIntProperty URI_LENGTH_LIMIT = + private static final DynamicIntProperty URI_LENGTH_LIMIT = new DynamicIntProperty("zuul.access.log.uri.length.limit", Integer.MAX_VALUE); private final Logger logger; @@ -47,15 +48,21 @@ public class AccessLogPublisher private static final Logger LOG = LoggerFactory.getLogger(AccessLogPublisher.class); - public AccessLogPublisher(String loggerName, BiFunction requestIdProvider) - { + public AccessLogPublisher(String loggerName, BiFunction requestIdProvider) { this.logger = LoggerFactory.getLogger(loggerName); this.requestIdProvider = requestIdProvider; } - public void log(Channel channel, HttpRequest request, HttpResponse response, LocalDateTime dateTime, Integer localPort, String remoteIp, - Long durationNs, Integer requestBodySize, Integer responseBodySize) - { + public void log( + Channel channel, + HttpRequest request, + HttpResponse response, + LocalDateTime dateTime, + Integer localPort, + String remoteIp, + Long durationNs, + Integer requestBodySize, + Integer responseBodySize) { StringBuilder sb = new StringBuilder(); String dateTimeStr = dateTime != null ? dateTime.format(DATE_TIME_FORMATTER) : "-----T-:-:-"; @@ -72,7 +79,8 @@ public void log(Channel channel, HttpRequest request, HttpResponse response, Loc try { requestId = requestIdProvider.apply(channel, request); } catch (Exception ex) { - LOG.error("requestIdProvider failed in AccessLogPublisher method={}, uri={}, status={}", method, uri, status); + LOG.error( + "requestIdProvider failed in AccessLogPublisher method={}, uri={}, status={}", method, uri, status); } requestId = requestId != null ? requestId : "-"; @@ -80,22 +88,29 @@ public void log(Channel channel, HttpRequest request, HttpResponse response, Loc String durationStr = (durationNs != null && durationNs > 0) ? String.valueOf(durationNs / 1000) : "-"; String requestBodySizeStr = (requestBodySize != null && requestBodySize > 0) ? requestBodySize.toString() : "-"; - String responseBodySizeStr = (responseBodySize != null && responseBodySize > 0) ? responseBodySize.toString() : "-"; - + String responseBodySizeStr = + (responseBodySize != null && responseBodySize > 0) ? responseBodySize.toString() : "-"; // Build the line. - sb - .append(dateTimeStr) - .append(DELIM).append(remoteIpStr) - .append(DELIM).append(port) - .append(DELIM).append(method) - .append(DELIM).append(uri) - .append(DELIM).append(status) - .append(DELIM).append(durationStr) - .append(DELIM).append(responseBodySizeStr) - .append(DELIM).append(requestId) - .append(DELIM).append(requestBodySizeStr) - ; + sb.append(dateTimeStr) + .append(DELIM) + .append(remoteIpStr) + .append(DELIM) + .append(port) + .append(DELIM) + .append(method) + .append(DELIM) + .append(uri) + .append(DELIM) + .append(status) + .append(DELIM) + .append(durationStr) + .append(DELIM) + .append(responseBodySizeStr) + .append(DELIM) + .append(requestId) + .append(DELIM) + .append(requestBodySizeStr); if (request != null && request.headers() != null) { includeMatchingHeaders(sb, LOG_REQ_HEADERS, request.headers()); @@ -111,17 +126,14 @@ public void log(Channel channel, HttpRequest request, HttpResponse response, Loc LOG.debug(access); } - void includeMatchingHeaders(StringBuilder builder, List requiredHeaders, HttpHeaders headers) - { - for (String headerName : requiredHeaders) - { + void includeMatchingHeaders(StringBuilder builder, List requiredHeaders, HttpHeaders headers) { + for (String headerName : requiredHeaders) { String value = headerAsString(headers, headerName); builder.append(DELIM).append('\"').append(value).append('\"'); } } - String headerAsString(HttpHeaders headers, String headerName) - { + String headerAsString(HttpHeaders headers, String headerName) { List values = headers.getAll(headerName); return (values.size() == 0) ? "-" : String.join(",", values); } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfig.java b/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfig.java index 529d79490a..2aaaca4b63 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfig.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfig.java @@ -23,32 +23,26 @@ * Date: 2/8/17 * Time: 6:43 PM */ -public class ChannelConfig implements Cloneable -{ +public class ChannelConfig implements Cloneable { private final HashMap parameters; - public ChannelConfig() - { + public ChannelConfig() { parameters = new HashMap<>(); } - public ChannelConfig(HashMap parameters) - { + public ChannelConfig(HashMap parameters) { this.parameters = (HashMap) parameters.clone(); } - public void add(ChannelConfigValue param) - { + public void add(ChannelConfigValue param) { this.parameters.put(param.key(), param); } - public void set(ChannelConfigKey key, T value) - { + public void set(ChannelConfigKey key, T value) { this.parameters.put(key, new ChannelConfigValue<>(key, value)); } - public T get(ChannelConfigKey key) - { + public T get(ChannelConfigKey key) { ChannelConfigValue ccv = parameters.get(key); T value = ccv == null ? null : (T) ccv.value(); @@ -59,19 +53,16 @@ public T get(ChannelConfigKey key) return value; } - public ChannelConfigValue getConfig(ChannelConfigKey key) - { + public ChannelConfigValue getConfig(ChannelConfigKey key) { return (ChannelConfigValue) parameters.get(key); } - public boolean contains(ChannelConfigKey key) - { + public boolean contains(ChannelConfigKey key) { return parameters.containsKey(key); } @Override - public ChannelConfig clone() - { + public ChannelConfig clone() { return new ChannelConfig(parameters); } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfigKey.java b/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfigKey.java index d1ab9b84c3..6fa27b2e27 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfigKey.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfigKey.java @@ -21,19 +21,16 @@ * Date: 2/8/17 * Time: 6:17 PM */ -public class ChannelConfigKey -{ +public class ChannelConfigKey { private final String key; private final T defaultValue; - public ChannelConfigKey(String key, T defaultValue) - { + public ChannelConfigKey(String key, T defaultValue) { this.key = key; this.defaultValue = defaultValue; } - public ChannelConfigKey(String key) - { + public ChannelConfigKey(String key) { this.key = key; this.defaultValue = null; } @@ -42,22 +39,16 @@ public String key() { return key; } - public T defaultValue() - { + public T defaultValue() { return defaultValue; } - public boolean hasDefaultValue() - { + public boolean hasDefaultValue() { return defaultValue != null; } @Override - public String toString() - { - return "ChannelConfigKey{" + - "key='" + key + '\'' + - ", defaultValue=" + defaultValue + - '}'; + public String toString() { + return "ChannelConfigKey{" + "key='" + key + '\'' + ", defaultValue=" + defaultValue + '}'; } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfigValue.java b/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfigValue.java index a1b8293129..396fb3daac 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfigValue.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfigValue.java @@ -21,24 +21,20 @@ * Date: 2/8/17 * Time: 6:41 PM */ -public class ChannelConfigValue -{ +public class ChannelConfigValue { private final ChannelConfigKey key; private final T value; - public ChannelConfigValue(ChannelConfigKey key, T value) - { + public ChannelConfigValue(ChannelConfigKey key, T value) { this.key = key; this.value = value; } - public ChannelConfigKey key() - { + public ChannelConfigKey key() { return key; } - public T value() - { + public T value() { return value; } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/channel/config/CommonChannelConfigKeys.java b/zuul-core/src/main/java/com/netflix/netty/common/channel/config/CommonChannelConfigKeys.java index 9a2be27cf5..d972941044 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/channel/config/CommonChannelConfigKeys.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/channel/config/CommonChannelConfigKeys.java @@ -28,38 +28,53 @@ * Date: 2/8/17 * Time: 6:21 PM */ -public class CommonChannelConfigKeys -{ - public static final ChannelConfigKey withProxyProtocol = new ChannelConfigKey<>("withProxyProtocol", false); +public class CommonChannelConfigKeys { + public static final ChannelConfigKey withProxyProtocol = + new ChannelConfigKey<>("withProxyProtocol", false); public static final ChannelConfigKey allowProxyHeadersWhen = new ChannelConfigKey<>("allowProxyHeadersWhen", StripUntrustedProxyHeadersHandler.AllowWhen.ALWAYS); - public static final ChannelConfigKey preferProxyProtocolForClientIp = new ChannelConfigKey<>("preferProxyProtocolForClientIp", true); + public static final ChannelConfigKey preferProxyProtocolForClientIp = + new ChannelConfigKey<>("preferProxyProtocolForClientIp", true); /** The Idle timeout of a connection, in milliseconds */ public static final ChannelConfigKey idleTimeout = new ChannelConfigKey<>("idleTimeout", 65000); + public static final ChannelConfigKey serverTimeout = new ChannelConfigKey<>("serverTimeout"); /** The HTTP request read timeout, in milliseconds */ public static final ChannelConfigKey httpRequestReadTimeout = new ChannelConfigKey<>("httpRequestReadTimeout", 5000); /** The maximum number of inbound connections to proxy. */ public static final ChannelConfigKey maxConnections = new ChannelConfigKey<>("maxConnections", 20000); - public static final ChannelConfigKey maxRequestsPerConnection = new ChannelConfigKey<>("maxRequestsPerConnection", 4000); - public static final ChannelConfigKey maxRequestsPerConnectionInBrownout = new ChannelConfigKey<>("maxRequestsPerConnectionInBrownout", 100); - public static final ChannelConfigKey connectionExpiry = new ChannelConfigKey<>("connectionExpiry", 20 * 60 * 1000); + + public static final ChannelConfigKey maxRequestsPerConnection = + new ChannelConfigKey<>("maxRequestsPerConnection", 4000); + public static final ChannelConfigKey maxRequestsPerConnectionInBrownout = + new ChannelConfigKey<>("maxRequestsPerConnectionInBrownout", 100); + public static final ChannelConfigKey connectionExpiry = + new ChannelConfigKey<>("connectionExpiry", 20 * 60 * 1000); // SSL: - public static final ChannelConfigKey isSSlFromIntermediary = new ChannelConfigKey<>("isSSlFromIntermediary", false); + public static final ChannelConfigKey isSSlFromIntermediary = + new ChannelConfigKey<>("isSSlFromIntermediary", false); public static final ChannelConfigKey serverSslConfig = new ChannelConfigKey<>("serverSslConfig"); - public static final ChannelConfigKey sslContextFactory = new ChannelConfigKey<>("sslContextFactory"); - public static final ChannelConfigKey> sniMapping = new ChannelConfigKey<>("sniMapping"); + public static final ChannelConfigKey sslContextFactory = + new ChannelConfigKey<>("sslContextFactory"); + public static final ChannelConfigKey> sniMapping = + new ChannelConfigKey<>("sniMapping"); // HTTP/2 specific: - public static final ChannelConfigKey maxConcurrentStreams = new ChannelConfigKey<>("maxConcurrentStreams", 100); - public static final ChannelConfigKey initialWindowSize = new ChannelConfigKey<>("initialWindowSize", 5242880); // 5MB + public static final ChannelConfigKey maxConcurrentStreams = + new ChannelConfigKey<>("maxConcurrentStreams", 100); + public static final ChannelConfigKey initialWindowSize = + new ChannelConfigKey<>("initialWindowSize", 5242880); // 5MB /* The amount of time to wait before closing a connection that has the `Connection: Close` header, in seconds */ public static final ChannelConfigKey connCloseDelay = new ChannelConfigKey<>("connCloseDelay", 10); - public static final ChannelConfigKey maxHttp2HeaderTableSize = new ChannelConfigKey<>("maxHttp2HeaderTableSize", 4096); - public static final ChannelConfigKey maxHttp2HeaderListSize = new ChannelConfigKey<>("maxHttp2HeaderListSize"); - public static final ChannelConfigKey http2AllowGracefulDelayed = new ChannelConfigKey<>("http2AllowGracefulDelayed", true); - public static final ChannelConfigKey http2SwallowUnknownExceptionsOnConnClose = new ChannelConfigKey<>("http2SwallowUnknownExceptionsOnConnClose", false); + public static final ChannelConfigKey maxHttp2HeaderTableSize = + new ChannelConfigKey<>("maxHttp2HeaderTableSize", 4096); + public static final ChannelConfigKey maxHttp2HeaderListSize = + new ChannelConfigKey<>("maxHttp2HeaderListSize"); + public static final ChannelConfigKey http2AllowGracefulDelayed = + new ChannelConfigKey<>("http2AllowGracefulDelayed", true); + public static final ChannelConfigKey http2SwallowUnknownExceptionsOnConnClose = + new ChannelConfigKey<>("http2SwallowUnknownExceptionsOnConnClose", false); } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/http2/DynamicHttp2FrameLogger.java b/zuul-core/src/main/java/com/netflix/netty/common/http2/DynamicHttp2FrameLogger.java index 57b5d6e1dd..f48b3ae41e 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/http2/DynamicHttp2FrameLogger.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/http2/DynamicHttp2FrameLogger.java @@ -32,15 +32,13 @@ import static io.netty.util.internal.ObjectUtil.checkNotNull; -public class DynamicHttp2FrameLogger extends Http2FrameLogger -{ +public class DynamicHttp2FrameLogger extends Http2FrameLogger { public static final AttributeKey ATTR_ENABLE = AttributeKey.valueOf("http2.frame.logger.enabled"); private static final int BUFFER_LENGTH_THRESHOLD = 64; private static final DynamicStringSetProperty FRAMES_TO_LOG = new DynamicStringSetProperty( "server.http2.logger.framestolog", "SETTINGS,WINDOW_UPDATE,HEADERS,GO_AWAY,RST_STREAM,PRIORITY,PING,PUSH_PROMISE"); - private final InternalLogger logger; private final InternalLogLevel level; @@ -50,8 +48,7 @@ public DynamicHttp2FrameLogger(LogLevel level, Class clazz) { this.logger = checkNotNull(InternalLoggerFactory.getInstance(clazz), "logger"); } - protected boolean enabled(ChannelHandlerContext ctx) - { + protected boolean enabled(ChannelHandlerContext ctx) { return ctx.channel().hasAttr(ATTR_ENABLE); } @@ -59,38 +56,79 @@ protected boolean enabled() { return logger.isEnabled(level); } - public void logData(Direction direction, ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, - boolean endStream) { + public void logData( + Direction direction, + ChannelHandlerContext ctx, + int streamId, + ByteBuf data, + int padding, + boolean endStream) { if (enabled()) { - log(direction, "DATA", ctx, + log( + direction, + "DATA", + ctx, "streamId=%d, endStream=%b, length=%d", - streamId, endStream, data.readableBytes()); + streamId, + endStream, + data.readableBytes()); } } - public void logHeaders(Direction direction, ChannelHandlerContext ctx, int streamId, Http2Headers headers, - int padding, boolean endStream) { + public void logHeaders( + Direction direction, + ChannelHandlerContext ctx, + int streamId, + Http2Headers headers, + int padding, + boolean endStream) { if (enabled()) { - log(direction, "HEADERS", ctx, "streamId=%d, headers=%s, endStream=%b", - streamId, headers, endStream); + log(direction, "HEADERS", ctx, "streamId=%d, headers=%s, endStream=%b", streamId, headers, endStream); } } - public void logHeaders(Direction direction, ChannelHandlerContext ctx, int streamId, Http2Headers headers, - int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) { + public void logHeaders( + Direction direction, + ChannelHandlerContext ctx, + int streamId, + Http2Headers headers, + int streamDependency, + short weight, + boolean exclusive, + int padding, + boolean endStream) { if (enabled()) { - log(direction, "HEADERS", ctx, - "streamId=%d, headers=%s, streamDependency=%d, weight=%d, " - + "exclusive=%b, endStream=%b", - streamId, headers, streamDependency, weight, exclusive, endStream); + log( + direction, + "HEADERS", + ctx, + "streamId=%d, headers=%s, streamDependency=%d, weight=%d, " + "exclusive=%b, endStream=%b", + streamId, + headers, + streamDependency, + weight, + exclusive, + endStream); } } - public void logPriority(Direction direction, ChannelHandlerContext ctx, int streamId, int streamDependency, - short weight, boolean exclusive) { + public void logPriority( + Direction direction, + ChannelHandlerContext ctx, + int streamId, + int streamDependency, + short weight, + boolean exclusive) { if (enabled()) { - log(direction, "PRIORITY", ctx, "streamId=%d, streamDependency=%d, weight=%d, exclusive=%b", - streamId, streamDependency, weight, exclusive); + log( + direction, + "PRIORITY", + ctx, + "streamId=%d, streamDependency=%d, weight=%d, exclusive=%b", + streamId, + streamDependency, + weight, + exclusive); } } @@ -124,35 +162,66 @@ public void logPingAck(Direction direction, ChannelHandlerContext ctx, long data } } - public void logPushPromise(Direction direction, ChannelHandlerContext ctx, int streamId, int promisedStreamId, - Http2Headers headers, int padding) { + public void logPushPromise( + Direction direction, + ChannelHandlerContext ctx, + int streamId, + int promisedStreamId, + Http2Headers headers, + int padding) { if (enabled()) { - log(direction, "PUSH_PROMISE", ctx, "streamId=%d, promisedStreamId=%d, headers=%s, padding=%d", - streamId, promisedStreamId, headers, padding); + log( + direction, + "PUSH_PROMISE", + ctx, + "streamId=%d, promisedStreamId=%d, headers=%s, padding=%d", + streamId, + promisedStreamId, + headers, + padding); } } - public void logGoAway(Direction direction, ChannelHandlerContext ctx, int lastStreamId, long errorCode, - ByteBuf debugData) { + public void logGoAway( + Direction direction, ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData) { if (enabled()) { - log(direction, "GO_AWAY", ctx, "lastStreamId=%d, errorCode=%d, length=%d, bytes=%s", - lastStreamId, errorCode, debugData.readableBytes(), toString(debugData)); + log( + direction, + "GO_AWAY", + ctx, + "lastStreamId=%d, errorCode=%d, length=%d, bytes=%s", + lastStreamId, + errorCode, + debugData.readableBytes(), + toString(debugData)); } } - public void logWindowsUpdate(Direction direction, ChannelHandlerContext ctx, int streamId, - int windowSizeIncrement) { + public void logWindowsUpdate( + Direction direction, ChannelHandlerContext ctx, int streamId, int windowSizeIncrement) { if (enabled()) { - log(direction, "WINDOW_UPDATE", ctx, "streamId=%d, windowSizeIncrement=%d", - streamId, windowSizeIncrement); + log(direction, "WINDOW_UPDATE", ctx, "streamId=%d, windowSizeIncrement=%d", streamId, windowSizeIncrement); } } - public void logUnknownFrame(Direction direction, ChannelHandlerContext ctx, byte frameType, int streamId, - Http2Flags flags, ByteBuf data) { + public void logUnknownFrame( + Direction direction, + ChannelHandlerContext ctx, + byte frameType, + int streamId, + Http2Flags flags, + ByteBuf data) { if (enabled()) { - log(direction, "UNKNOWN", ctx, "frameType=%d, streamId=%d, flags=%d, length=%d, bytes=%s", - frameType & 0xFF, streamId, flags.value(), data.readableBytes(), toString(data)); + log( + direction, + "UNKNOWN", + ctx, + "frameType=%d, streamId=%d, flags=%d, length=%d, bytes=%s", + frameType & 0xFF, + streamId, + flags.value(), + data.readableBytes(), + toString(data)); } } @@ -167,7 +236,6 @@ private String toString(ByteBuf buf) { return ByteBufUtil.hexDump(buf, buf.readerIndex(), length) + "..."; } - private void log(Direction direction, String frame, ChannelHandlerContext ctx, String format, Object... args) { if (shouldLogFrame(frame)) { StringBuilder b = new StringBuilder(200) diff --git a/zuul-core/src/main/java/com/netflix/netty/common/metrics/EventLoopGroupMetrics.java b/zuul-core/src/main/java/com/netflix/netty/common/metrics/EventLoopGroupMetrics.java index c7b4fbfae8..b62bd2d805 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/metrics/EventLoopGroupMetrics.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/metrics/EventLoopGroupMetrics.java @@ -29,18 +29,15 @@ * Time: 3:17 PM */ @Singleton -public class EventLoopGroupMetrics -{ +public class EventLoopGroupMetrics { private final ThreadLocal metricsForCurrentThread; private final Map byEventLoop = new HashMap<>(); private final Registry registry; @Inject - public EventLoopGroupMetrics(Registry registry) - { + public EventLoopGroupMetrics(Registry registry) { this.registry = registry; - this.metricsForCurrentThread = ThreadLocal.withInitial(() -> - { + this.metricsForCurrentThread = ThreadLocal.withInitial(() -> { String name = nameForCurrentEventLoop(); EventLoopMetrics metrics = new EventLoopMetrics(registry, name); byEventLoop.put(Thread.currentThread(), metrics); @@ -48,33 +45,27 @@ public EventLoopGroupMetrics(Registry registry) }); } - public Map connectionsPerEventLoop() - { + public Map connectionsPerEventLoop() { Map map = new HashMap<>(byEventLoop.size()); - for (Map.Entry entry : byEventLoop.entrySet()) - { + for (Map.Entry entry : byEventLoop.entrySet()) { map.put(entry.getKey(), entry.getValue().currentConnectionsCount()); } return map; } - public Map httpRequestsPerEventLoop() - { + public Map httpRequestsPerEventLoop() { Map map = new HashMap<>(byEventLoop.size()); - for (Map.Entry entry : byEventLoop.entrySet()) - { + for (Map.Entry entry : byEventLoop.entrySet()) { map.put(entry.getKey(), entry.getValue().currentHttpRequestsCount()); } return map; } - public EventLoopMetrics getForCurrentEventLoop() - { + public EventLoopMetrics getForCurrentEventLoop() { return metricsForCurrentThread.get(); } - private static String nameForCurrentEventLoop() - { + private static String nameForCurrentEventLoop() { // We're relying on the knowledge that we name the eventloop threads consistently. String threadName = Thread.currentThread().getName(); String parts[] = threadName.split("-ClientToZuulWorker-"); @@ -84,9 +75,9 @@ private static String nameForCurrentEventLoop() return threadName; } - interface EventLoopInfo - { + interface EventLoopInfo { int currentConnectionsCount(); + int currentHttpRequestsCount(); } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/metrics/EventLoopMetrics.java b/zuul-core/src/main/java/com/netflix/netty/common/metrics/EventLoopMetrics.java index 2ecebe8836..76527c0414 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/metrics/EventLoopMetrics.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/metrics/EventLoopMetrics.java @@ -26,8 +26,7 @@ * Date: 2/7/17 * Time: 3:18 PM */ -public class EventLoopMetrics implements EventLoopGroupMetrics.EventLoopInfo -{ +public class EventLoopMetrics implements EventLoopGroupMetrics.EventLoopInfo { private final String name; public final AtomicInteger currentRequests = new AtomicInteger(0); public final AtomicInteger currentConnections = new AtomicInteger(0); @@ -36,8 +35,7 @@ public class EventLoopMetrics implements EventLoopGroupMetrics.EventLoopInfo private final Id currentRequestsId; private final Id currentConnectionsId; - public EventLoopMetrics(Registry registry, String eventLoopName) - { + public EventLoopMetrics(Registry registry, String eventLoopName) { this.name = eventLoopName; this.registry = registry; @@ -46,43 +44,36 @@ public EventLoopMetrics(Registry registry, String eventLoopName) } @Override - public int currentConnectionsCount() - { + public int currentConnectionsCount() { return currentConnections.get(); } @Override - public int currentHttpRequestsCount() - { + public int currentHttpRequestsCount() { return currentRequests.get(); } - public void incrementCurrentRequests() - { + public void incrementCurrentRequests() { int value = this.currentRequests.incrementAndGet(); updateGauge(currentRequestsId, value); } - public void decrementCurrentRequests() - { + public void decrementCurrentRequests() { int value = this.currentRequests.decrementAndGet(); updateGauge(currentRequestsId, value); } - public void incrementCurrentConnections() - { + public void incrementCurrentConnections() { int value = this.currentConnections.incrementAndGet(); updateGauge(currentConnectionsId, value); } - public void decrementCurrentConnections() - { + public void decrementCurrentConnections() { int value = this.currentConnections.decrementAndGet(); updateGauge(currentConnectionsId, value); } - private void updateGauge(Id gaugeId, int value) - { + private void updateGauge(Id gaugeId, int value) { registry.gauge(gaugeId.withTag("eventloop", name)).set(value); } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/metrics/Http2MetricsChannelHandlers.java b/zuul-core/src/main/java/com/netflix/netty/common/metrics/Http2MetricsChannelHandlers.java index fb8832f2af..1fdf1072e3 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/metrics/Http2MetricsChannelHandlers.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/metrics/Http2MetricsChannelHandlers.java @@ -27,70 +27,55 @@ import io.netty.handler.codec.http2.Http2GoAwayFrame; import io.netty.handler.codec.http2.Http2ResetFrame; -public class Http2MetricsChannelHandlers -{ +public class Http2MetricsChannelHandlers { private final Inbound inbound; private final Outbound outbound; - - public Http2MetricsChannelHandlers(Registry registry, String metricPrefix, String metricId) - { + + public Http2MetricsChannelHandlers(Registry registry, String metricPrefix, String metricId) { super(); this.inbound = new Inbound(registry, metricId, metricPrefix); this.outbound = new Outbound(registry, metricId, metricPrefix); } - public Inbound inbound() - { + public Inbound inbound() { return inbound; } - public Outbound outbound() - { + public Outbound outbound() { return outbound; } - protected static void incrementErrorCounter(Registry registry, String counterName, String metricId, Http2Exception h2e) - { + protected static void incrementErrorCounter( + Registry registry, String counterName, String metricId, Http2Exception h2e) { String h2Error = h2e.error() != null ? h2e.error().name() : "NA"; String exceptionName = h2e.getClass().getSimpleName(); - registry.counter(counterName, - "id", metricId, - "error", h2Error, - "exception", exceptionName) + registry.counter(counterName, "id", metricId, "error", h2Error, "exception", exceptionName) .increment(); } - protected static void incrementCounter(Registry registry, String counterName, String metricId, Http2Frame frame) - { + protected static void incrementCounter(Registry registry, String counterName, String metricId, Http2Frame frame) { long errorCode; if (frame instanceof Http2ResetFrame) { errorCode = ((Http2ResetFrame) frame).errorCode(); - } - else if (frame instanceof Http2GoAwayFrame) { + } else if (frame instanceof Http2GoAwayFrame) { errorCode = ((Http2GoAwayFrame) frame).errorCode(); - } - else { + } else { errorCode = -1; } - registry.counter(counterName, - "id", metricId, - "frame", frame.name(), - "error_code", Long.toString(errorCode)) + registry.counter(counterName, "id", metricId, "frame", frame.name(), "error_code", Long.toString(errorCode)) .increment(); } @ChannelHandler.Sharable - private static class Inbound extends ChannelInboundHandlerAdapter - { + private static class Inbound extends ChannelInboundHandlerAdapter { private final Registry registry; private final String metricId; private final String frameCounterName; private final String errorCounterName; - public Inbound(Registry registry, String metricId, String metricPrefix) - { + public Inbound(Registry registry, String metricId, String metricPrefix) { this.registry = registry; this.metricId = metricId; this.frameCounterName = metricPrefix + ".http2.frame.inbound"; @@ -98,42 +83,36 @@ public Inbound(Registry registry, String metricId, String metricPrefix) } @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { if (msg instanceof Http2Frame) { incrementCounter(registry, frameCounterName, metricId, (Http2Frame) msg); } - } - finally { + } finally { super.channelRead(ctx, msg); } } @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception - { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { try { if (cause instanceof Http2Exception) { incrementErrorCounter(registry, errorCounterName, metricId, (Http2Exception) cause); } - } - finally { + } finally { super.exceptionCaught(ctx, cause); } } } @ChannelHandler.Sharable - private static class Outbound extends ChannelOutboundHandlerAdapter - { + private static class Outbound extends ChannelOutboundHandlerAdapter { private final Registry registry; private final String metricId; private final String frameCounterName; private final String errorCounterName; - public Outbound(Registry registry, String metricId, String metricPrefix) - { + public Outbound(Registry registry, String metricId, String metricPrefix) { this.registry = registry; this.metricId = metricId; this.frameCounterName = metricPrefix + ".http2.frame.outbound"; @@ -141,8 +120,7 @@ public Outbound(Registry registry, String metricId, String metricPrefix) } @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { super.write(ctx, msg, promise); if (msg instanceof Http2Frame) { @@ -151,14 +129,12 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) } @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception - { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { try { if (cause instanceof Http2Exception) { incrementErrorCounter(registry, errorCounterName, metricId, (Http2Exception) cause); } - } - finally { + } finally { super.exceptionCaught(ctx, cause); } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/metrics/HttpBodySizeRecordingChannelHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/metrics/HttpBodySizeRecordingChannelHandler.java index 4ca6f4ac63..a36a18dd77 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/metrics/HttpBodySizeRecordingChannelHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/metrics/HttpBodySizeRecordingChannelHandler.java @@ -36,18 +36,15 @@ public final class HttpBodySizeRecordingChannelHandler { private static final AttributeKey ATTR_STATE = AttributeKey.newInstance("_http_body_size_state"); - public static Provider getCurrentInboundBodySize(Channel ch) - { + public static Provider getCurrentInboundBodySize(Channel ch) { return new InboundBodySizeProvider(ch); } - public static Provider getCurrentOutboundBodySize(Channel ch) - { + public static Provider getCurrentOutboundBodySize(Channel ch) { return new OutboundBodySizeProvider(ch); } - - private static State getOrCreateCurrentState(Channel ch) - { + + private static State getOrCreateCurrentState(Channel ch) { State state = ch.attr(ATTR_STATE).get(); if (state == null) { state = createNewState(ch); @@ -55,25 +52,22 @@ private static State getOrCreateCurrentState(Channel ch) return state; } - private static State createNewState(Channel ch) - { + private static State createNewState(Channel ch) { State state = new State(); ch.attr(ATTR_STATE).set(state); return state; } - public static final class InboundChannelHandler extends ChannelInboundHandlerAdapter - { + public static final class InboundChannelHandler extends ChannelInboundHandlerAdapter { @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { State state = null; - + // Reset the state as each new inbound request comes in. if (msg instanceof HttpRequest) { state = createNewState(ctx.channel()); } - + // Update the inbound body size with this chunk. if (msg instanceof HttpContent) { if (state == null) { @@ -86,12 +80,10 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception } @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception - { + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { try { super.userEventTriggered(ctx, evt); - } - finally { + } finally { if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) { ctx.channel().attr(ATTR_STATE).set(null); } @@ -99,11 +91,9 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc } } - public static final class OutboundChannelHandler extends ChannelOutboundHandlerAdapter - { + public static final class OutboundChannelHandler extends ChannelOutboundHandlerAdapter { @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { State state = null; // Reset the state as each new outbound request goes out. @@ -123,41 +113,34 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) } } - private static class State - { + private static class State { long inboundBodySize = 0; long outboundBodySize = 0; } - - static class InboundBodySizeProvider implements Provider - { + + static class InboundBodySizeProvider implements Provider { private final Channel channel; - public InboundBodySizeProvider(Channel channel) - { + public InboundBodySizeProvider(Channel channel) { this.channel = channel; } @Override - public Long get() - { + public Long get() { State state = getOrCreateCurrentState(channel); return state == null ? 0 : state.inboundBodySize; } } - static class OutboundBodySizeProvider implements Provider - { + static class OutboundBodySizeProvider implements Provider { private final Channel channel; - public OutboundBodySizeProvider(Channel channel) - { + public OutboundBodySizeProvider(Channel channel) { this.channel = channel; } @Override - public Long get() - { + public Long get() { State state = getOrCreateCurrentState(channel); return state == null ? 0 : state.outboundBodySize; } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/metrics/HttpMetricsChannelHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/metrics/HttpMetricsChannelHandler.java index fc732eaeb8..e66f17db97 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/metrics/HttpMetricsChannelHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/metrics/HttpMetricsChannelHandler.java @@ -27,7 +27,6 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.AttributeKey; -import com.netflix.netty.common.HttpLifecycleChannelHandler; import java.util.concurrent.atomic.AtomicInteger; @@ -37,11 +36,11 @@ * Time: 3:51 PM */ @ChannelHandler.Sharable -public class HttpMetricsChannelHandler extends ChannelInboundHandlerAdapter -{ +public class HttpMetricsChannelHandler extends ChannelInboundHandlerAdapter { private static final AttributeKey ATTR_REQ_INFLIGHT = AttributeKey.newInstance("_httpmetrics_inflight"); private static final Object INFLIGHT = "is_inflight"; - private static final AttributeKey ATTR_CURRENT_REQS = AttributeKey.newInstance("_server_http_current_count"); + private static final AttributeKey ATTR_CURRENT_REQS = + AttributeKey.newInstance("_server_http_current_count"); private final AtomicInteger currentRequests = new AtomicInteger(0); @@ -49,30 +48,27 @@ public class HttpMetricsChannelHandler extends ChannelInboundHandlerAdapter private final Gauge currentRequestsGauge; private final Counter unSupportedPipeliningCounter; - public HttpMetricsChannelHandler(Registry registry, String name, String id) - { + public HttpMetricsChannelHandler(Registry registry, String name, String id) { super(); this.registry = registry; - this.currentRequestsGauge = this.registry.gauge(this.registry.createId(name + ".http.requests.current", "id", id)); + this.currentRequestsGauge = + this.registry.gauge(this.registry.createId(name + ".http.requests.current", "id", id)); this.unSupportedPipeliningCounter = this.registry.counter(name + ".http.requests.pipelining.dropped", "id", id); } - public static int getInflightRequestCountFromChannel(Channel ch) - { + public static int getInflightRequestCountFromChannel(Channel ch) { AtomicInteger current = ch.attr(ATTR_CURRENT_REQS).get(); return current == null ? 0 : current.get(); } - public int getInflightRequestsCount() - { + public int getInflightRequestsCount() { return currentRequests.get(); } @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception - { + public void channelActive(ChannelHandlerContext ctx) throws Exception { // Store a ref to the count of current inflight requests onto this channel. So that // other code can query it using getInflightRequestCountFromChannel(). ctx.channel().attr(ATTR_CURRENT_REQS).set(currentRequests); @@ -81,28 +77,24 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception } @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception - { + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof HttpServerLifecycleChannelHandler.StartEvent) { incrementCurrentRequestsInFlight(ctx); - } - else if (evt instanceof HttpServerLifecycleChannelHandler.CompleteEvent && ((CompleteEvent) evt).getReason() == CompleteReason.PIPELINE_REJECT ) { + } else if (evt instanceof HttpServerLifecycleChannelHandler.CompleteEvent + && ((CompleteEvent) evt).getReason() == CompleteReason.PIPELINE_REJECT) { unSupportedPipeliningCounter.increment(); - } - else if (evt instanceof HttpServerLifecycleChannelHandler.CompleteEvent) { + } else if (evt instanceof HttpServerLifecycleChannelHandler.CompleteEvent) { decrementCurrentRequestsIfOneInflight(ctx); } super.userEventTriggered(ctx, evt); } - private void incrementCurrentRequestsInFlight(ChannelHandlerContext ctx) - { + private void incrementCurrentRequestsInFlight(ChannelHandlerContext ctx) { currentRequestsGauge.set(currentRequests.incrementAndGet()); ctx.channel().attr(ATTR_REQ_INFLIGHT).set(INFLIGHT); } - private void decrementCurrentRequestsIfOneInflight(ChannelHandlerContext ctx) - { + private void decrementCurrentRequestsIfOneInflight(ChannelHandlerContext ctx) { if (ctx.channel().attr(ATTR_REQ_INFLIGHT).getAndSet(null) != null) { currentRequestsGauge.set(currentRequests.decrementAndGet()); } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/metrics/InstrumentedResourceLeakDetector.java b/zuul-core/src/main/java/com/netflix/netty/common/metrics/InstrumentedResourceLeakDetector.java index 34b14e226a..906250080e 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/metrics/InstrumentedResourceLeakDetector.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/metrics/InstrumentedResourceLeakDetector.java @@ -19,6 +19,7 @@ import com.google.common.annotations.VisibleForTesting; import com.netflix.zuul.netty.SpectatorUtils; import io.netty.util.ResourceLeakDetector; + import java.lang.reflect.Field; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; @@ -32,18 +33,20 @@ public class InstrumentedResourceLeakDetector extends ResourceLeakDetector { private final AtomicInteger instancesLeakCounter; + @VisibleForTesting final AtomicInteger leakCounter; public InstrumentedResourceLeakDetector(Class resourceType, int samplingInterval) { super(resourceType, samplingInterval); - this.instancesLeakCounter = SpectatorUtils.newGauge("NettyLeakDetector_instances", resourceType.getSimpleName(), new AtomicInteger()); - this.leakCounter = SpectatorUtils.newGauge("NettyLeakDetector", resourceType.getSimpleName(), new AtomicInteger()); + this.instancesLeakCounter = SpectatorUtils.newGauge( + "NettyLeakDetector_instances", resourceType.getSimpleName(), new AtomicInteger()); + this.leakCounter = + SpectatorUtils.newGauge("NettyLeakDetector", resourceType.getSimpleName(), new AtomicInteger()); } - public InstrumentedResourceLeakDetector(Class resourceType, int samplingInterval, long maxActive) - { + public InstrumentedResourceLeakDetector(Class resourceType, int samplingInterval, long maxActive) { this(resourceType, samplingInterval); } @@ -73,8 +76,7 @@ private void resetReportedLeaks() { if (f instanceof Map) { ((Map) f).clear(); } - } - catch (Throwable t) { + } catch (Throwable t) { // do nothing } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/metrics/PerEventLoopMetricsChannelHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/metrics/PerEventLoopMetricsChannelHandler.java index 25b180d298..363b3e8c39 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/metrics/PerEventLoopMetricsChannelHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/metrics/PerEventLoopMetricsChannelHandler.java @@ -16,76 +16,65 @@ package com.netflix.netty.common.metrics; +import com.netflix.netty.common.HttpLifecycleChannelHandler; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.AttributeKey; -import com.netflix.netty.common.HttpLifecycleChannelHandler; /** * User: michaels@netflix.com * Date: 2/6/17 * Time: 2:21 PM */ - -public class PerEventLoopMetricsChannelHandler -{ - private static final AttributeKey ATTR_REQ_INFLIGHT = AttributeKey.newInstance("_eventloop_metrics_inflight"); +public class PerEventLoopMetricsChannelHandler { + private static final AttributeKey ATTR_REQ_INFLIGHT = + AttributeKey.newInstance("_eventloop_metrics_inflight"); private static final Object INFLIGHT = "eventloop_is_inflight"; private final EventLoopGroupMetrics groupMetrics; - public PerEventLoopMetricsChannelHandler(EventLoopGroupMetrics groupMetrics) - { + public PerEventLoopMetricsChannelHandler(EventLoopGroupMetrics groupMetrics) { this.groupMetrics = groupMetrics; } @ChannelHandler.Sharable - public class Connections extends ChannelInboundHandlerAdapter - { + public class Connections extends ChannelInboundHandlerAdapter { @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception - { + public void channelActive(ChannelHandlerContext ctx) throws Exception { groupMetrics.getForCurrentEventLoop().incrementCurrentConnections(); super.channelActive(ctx); } @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception - { + public void channelInactive(ChannelHandlerContext ctx) throws Exception { try { super.channelInactive(ctx); - } - finally { + } finally { groupMetrics.getForCurrentEventLoop().decrementCurrentConnections(); } } } @ChannelHandler.Sharable - public class HttpRequests extends ChannelInboundHandlerAdapter - { + public class HttpRequests extends ChannelInboundHandlerAdapter { @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception - { + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof HttpLifecycleChannelHandler.StartEvent) { incrementCurrentRequestsInFlight(ctx); - } - else if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) { + } else if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) { decrementCurrentRequestsIfOneInflight(ctx); } super.userEventTriggered(ctx, evt); } - private void incrementCurrentRequestsInFlight(ChannelHandlerContext ctx) - { + private void incrementCurrentRequestsInFlight(ChannelHandlerContext ctx) { groupMetrics.getForCurrentEventLoop().incrementCurrentRequests(); ctx.channel().attr(ATTR_REQ_INFLIGHT).set(INFLIGHT); } - private void decrementCurrentRequestsIfOneInflight(ChannelHandlerContext ctx) - { + private void decrementCurrentRequestsIfOneInflight(ChannelHandlerContext ctx) { if (ctx.channel().attr(ATTR_REQ_INFLIGHT).getAndSet(null) != null) { groupMetrics.getForCurrentEventLoop().decrementCurrentRequests(); } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/ElbProxyProtocolChannelHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/ElbProxyProtocolChannelHandler.java index f83a2fec0b..12e483f405 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/ElbProxyProtocolChannelHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/ElbProxyProtocolChannelHandler.java @@ -16,7 +16,6 @@ package com.netflix.netty.common.proxyprotocol; -import static com.google.common.base.Preconditions.checkNotNull; import com.netflix.netty.common.SourceAddressChannelHandler; import com.netflix.spectator.api.Registry; import io.netty.buffer.ByteBuf; @@ -26,6 +25,8 @@ import io.netty.handler.codec.ProtocolDetectionState; import io.netty.handler.codec.haproxy.HAProxyMessageDecoder; +import static com.google.common.base.Preconditions.checkNotNull; + /** * Decides if we need to decode a HAProxyMessage. If so, adds the decoder followed by the handler. * Else, removes itself from the pipeline. @@ -48,13 +49,18 @@ public void addProxyProtocol(ChannelPipeline pipeline) { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (withProxyProtocol && isHAPMDetected(msg)) { - ctx.pipeline().addAfter(NAME, null, new HAProxyMessageChannelHandler()) + ctx.pipeline() + .addAfter(NAME, null, new HAProxyMessageChannelHandler()) .replace(this, null, new HAProxyMessageDecoder()); } else { if (withProxyProtocol) { - final int port = ctx.channel().attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).get(); - // This likely means initialization was requested with proxy protocol, but we encountered a non-ppv2 message - registry.counter("zuul.hapm.decode", "success", "false", "port", String.valueOf(port)).increment(); + final int port = ctx.channel() + .attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT) + .get(); + // This likely means initialization was requested with proxy protocol, but we encountered a non-ppv2 + // message + registry.counter("zuul.hapm.decode", "success", "false", "port", String.valueOf(port)) + .increment(); } ctx.pipeline().remove(this); } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/HAProxyMessageChannelHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/HAProxyMessageChannelHandler.java index 6de3f34976..9d8d5a1047 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/HAProxyMessageChannelHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/HAProxyMessageChannelHandler.java @@ -28,6 +28,7 @@ import io.netty.handler.codec.haproxy.HAProxyMessage; import io.netty.handler.codec.haproxy.HAProxyProtocolVersion; import io.netty.util.AttributeKey; + import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetSocketAddress; @@ -37,7 +38,6 @@ * Copies any decoded HAProxyMessage into the channel attributes, and doesn't pass it any further along the pipeline. * Use in conjunction with HAProxyMessageDecoder if proxy protocol is enabled on the ELB. */ - public final class HAProxyMessageChannelHandler extends ChannelInboundHandlerAdapter { public static final AttributeKey ATTR_HAPROXY_MESSAGE = @@ -47,8 +47,10 @@ public final class HAProxyMessageChannelHandler extends ChannelInboundHandlerAda @VisibleForTesting static final Attrs.Key HAPM_DEST_PORT = Attrs.newKey("hapm_port"); + @VisibleForTesting static final Attrs.Key HAPM_DEST_IP_VERSION = Attrs.newKey("hapm_dst_ipproto"); + @VisibleForTesting static final Attrs.Key HAPM_SRC_IP_VERSION = Attrs.newKey("hapm_src_ipproto"); @@ -75,9 +77,12 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception InetSocketAddress inetAddr = new InetSocketAddress( InetAddresses.forString(destinationAddress), hapm.destinationPort()); addr = inetAddr; - // setting PPv2 explicitly because SourceAddressChannelHandler.ATTR_LOCAL_ADDR could be PPv2 or not - channel.attr(SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS).set(inetAddr); - Attrs attrs = ctx.channel().attr(Server.CONN_DIMENSIONS).get(); + // setting PPv2 explicitly because SourceAddressChannelHandler.ATTR_LOCAL_ADDR could be PPv2 + // or not + channel.attr(SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS) + .set(inetAddr); + Attrs attrs = + ctx.channel().attr(Server.CONN_DIMENSIONS).get(); if (inetAddr.getAddress() instanceof Inet4Address) { HAPM_DEST_IP_VERSION.put(attrs, "v4"); } else if (inetAddr.getAddress() instanceof Inet6Address) { @@ -113,9 +118,10 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception case TCP4: case TCP6: InetSocketAddress inetAddr; - addr = inetAddr = new InetSocketAddress( - InetAddresses.forString(sourceAddress), hapm.sourcePort()); - Attrs attrs = ctx.channel().attr(Server.CONN_DIMENSIONS).get(); + addr = inetAddr = + new InetSocketAddress(InetAddresses.forString(sourceAddress), hapm.sourcePort()); + Attrs attrs = + ctx.channel().attr(Server.CONN_DIMENSIONS).get(); if (inetAddr.getAddress() instanceof Inet4Address) { HAPM_SRC_IP_VERSION.put(attrs, "v4"); } else if (inetAddr.getAddress() instanceof Inet6Address) { diff --git a/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/StripUntrustedProxyHeadersHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/StripUntrustedProxyHeadersHandler.java index c76eb606c2..357be2c2a3 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/StripUntrustedProxyHeadersHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/StripUntrustedProxyHeadersHandler.java @@ -38,8 +38,7 @@ * Strip out any X-Forwarded-* headers from inbound http requests if connection is not trusted. */ @ChannelHandler.Sharable -public class StripUntrustedProxyHeadersHandler extends ChannelInboundHandlerAdapter -{ +public class StripUntrustedProxyHeadersHandler extends ChannelInboundHandlerAdapter { private static final DynamicStringListProperty XFF_BLACKLIST = new DynamicStringListProperty("zuul.proxy.headers.host.blacklist", ""); @@ -54,19 +53,16 @@ public enum AllowWhen { new AsciiString("x-forwarded-port"), new AsciiString("x-forwarded-proto"), new AsciiString("x-forwarded-proto-version"), - new AsciiString("x-real-ip") - ); + new AsciiString("x-real-ip")); private final AllowWhen allowWhen; - public StripUntrustedProxyHeadersHandler(AllowWhen allowWhen) - { + public StripUntrustedProxyHeadersHandler(AllowWhen allowWhen) { this.allowWhen = allowWhen; } @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; @@ -75,7 +71,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception stripXFFHeaders(req); break; case MUTUAL_SSL_AUTH: - if (! connectionIsUsingMutualSSLWithAuthEnforced(ctx.channel())) { + if (!connectionIsUsingMutualSSLWithAuthEnforced(ctx.channel())) { stripXFFHeaders(req); } else { checkBlacklist(req, XFF_BLACKLIST.get()); @@ -94,10 +90,10 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception } @VisibleForTesting - boolean connectionIsUsingMutualSSLWithAuthEnforced(Channel ch) - { + boolean connectionIsUsingMutualSSLWithAuthEnforced(Channel ch) { boolean is = false; - SslHandshakeInfo sslHandshakeInfo = ch.attr(SslHandshakeInfoHandler.ATTR_SSL_INFO).get(); + SslHandshakeInfo sslHandshakeInfo = + ch.attr(SslHandshakeInfoHandler.ATTR_SSL_INFO).get(); if (sslHandshakeInfo != null) { if (sslHandshakeInfo.getClientAuthRequirement() == ClientAuth.REQUIRE) { is = true; @@ -107,8 +103,7 @@ boolean connectionIsUsingMutualSSLWithAuthEnforced(Channel ch) } @VisibleForTesting - void stripXFFHeaders(HttpRequest req) - { + void stripXFFHeaders(HttpRequest req) { HttpHeaders headers = req.headers(); for (AsciiString headerName : HEADERS_TO_STRIP) { headers.remove(headerName); diff --git a/zuul-core/src/main/java/com/netflix/netty/common/ssl/ServerSslConfig.java b/zuul-core/src/main/java/com/netflix/netty/common/ssl/ServerSslConfig.java index 093c22ef96..89d8f2c8f3 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/ssl/ServerSslConfig.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/ssl/ServerSslConfig.java @@ -18,12 +18,13 @@ import com.netflix.config.DynamicLongProperty; import io.netty.handler.ssl.ClientAuth; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; import java.io.File; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.List; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocketFactory; /** * User: michaels@netflix.com @@ -32,16 +33,16 @@ */ public class ServerSslConfig { private static final DynamicLongProperty DEFAULT_SESSION_TIMEOUT = - new DynamicLongProperty("server.ssl.session.timeout", (18 * 60)); // 18 hours + new DynamicLongProperty("server.ssl.session.timeout", (18 * 60)); // 18 hours private static final String[] DEFAULT_CIPHERS; + static { try { SSLContext context = SSLContext.getDefault(); SSLSocketFactory sf = context.getSocketFactory(); DEFAULT_CIPHERS = sf.getSupportedCipherSuites(); - } - catch (NoSuchAlgorithmException e) { + } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } @@ -69,8 +70,14 @@ public ServerSslConfig( } public ServerSslConfig( - String[] protocols, String[] ciphers, File certChainFile, File keyFile, ClientAuth clientAuth, - File clientAuthTrustStoreFile, File clientAuthTrustStorePasswordFile, boolean sessionTicketsEnabled) { + String[] protocols, + String[] ciphers, + File certChainFile, + File keyFile, + ClientAuth clientAuth, + File clientAuthTrustStoreFile, + File clientAuthTrustStorePasswordFile, + boolean sessionTicketsEnabled) { this.protocols = protocols; this.ciphers = ciphers != null ? Arrays.asList(ciphers) : null; this.certChainFile = certChainFile; @@ -84,8 +91,14 @@ public ServerSslConfig( } public ServerSslConfig( - String[] protocols, String[] ciphers, File certChainFile, File keyFile, ClientAuth clientAuth, - File clientAuthTrustStoreFile, String clientAuthTrustStorePassword, boolean sessionTicketsEnabled) { + String[] protocols, + String[] ciphers, + File certChainFile, + File keyFile, + ClientAuth clientAuth, + File clientAuthTrustStoreFile, + String clientAuthTrustStorePassword, + boolean sessionTicketsEnabled) { this.protocols = protocols; this.ciphers = Arrays.asList(ciphers); this.certChainFile = certChainFile; @@ -98,78 +111,64 @@ public ServerSslConfig( this.sessionTicketsEnabled = sessionTicketsEnabled; } - public static String[] getDefaultCiphers() - { + public static String[] getDefaultCiphers() { return DEFAULT_CIPHERS; } - public static ServerSslConfig withDefaultCiphers(File certChainFile, File keyFile, String ... protocols) - { + public static ServerSslConfig withDefaultCiphers(File certChainFile, File keyFile, String... protocols) { return new ServerSslConfig(protocols, getDefaultCiphers(), certChainFile, keyFile); } - public String[] getProtocols() - { + public String[] getProtocols() { return protocols; } - public List getCiphers() - { + public List getCiphers() { return ciphers; } - public File getCertChainFile() - { + public File getCertChainFile() { return certChainFile; } - public File getKeyFile() - { + public File getKeyFile() { return keyFile; } - public ClientAuth getClientAuth() - { + public ClientAuth getClientAuth() { return clientAuth; } - public File getClientAuthTrustStoreFile() - { + public File getClientAuthTrustStoreFile() { return clientAuthTrustStoreFile; } - public String getClientAuthTrustStorePassword() - { + public String getClientAuthTrustStorePassword() { return clientAuthTrustStorePassword; } - public File getClientAuthTrustStorePasswordFile() - { + public File getClientAuthTrustStorePasswordFile() { return clientAuthTrustStorePasswordFile; } - public long getSessionTimeout() - { + public long getSessionTimeout() { return sessionTimeout; } - public boolean sessionTicketsEnabled() - { + public boolean sessionTicketsEnabled() { return sessionTicketsEnabled; } @Override - public String toString() - { - return "ServerSslConfig{" + - "protocols=" + Arrays.toString(protocols) + - ", ciphers=" + ciphers + - ", certChainFile=" + certChainFile + - ", keyFile=" + keyFile + - ", clientAuth=" + clientAuth + - ", clientAuthTrustStoreFile=" + clientAuthTrustStoreFile + - ", sessionTimeout=" + sessionTimeout + - ", sessionTicketsEnabled=" + sessionTicketsEnabled + - '}'; + public String toString() { + return "ServerSslConfig{" + "protocols=" + + Arrays.toString(protocols) + ", ciphers=" + + ciphers + ", certChainFile=" + + certChainFile + ", keyFile=" + + keyFile + ", clientAuth=" + + clientAuth + ", clientAuthTrustStoreFile=" + + clientAuthTrustStoreFile + ", sessionTimeout=" + + sessionTimeout + ", sessionTicketsEnabled=" + + sessionTicketsEnabled + '}'; } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/ssl/SslHandshakeInfo.java b/zuul-core/src/main/java/com/netflix/netty/common/ssl/SslHandshakeInfo.java index bc342bd46c..139ca47d29 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/ssl/SslHandshakeInfo.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/ssl/SslHandshakeInfo.java @@ -18,8 +18,8 @@ import io.netty.handler.ssl.ClientAuth; -import java.security.cert.X509Certificate; import java.security.cert.Certificate; +import java.security.cert.X509Certificate; /** * User: michaels@netflix.com Date: 3/29/16 Time: 11:06 AM @@ -33,9 +33,13 @@ public class SslHandshakeInfo { private final X509Certificate clientCertificate; private final boolean isOfIntermediary; - public SslHandshakeInfo(boolean isOfIntermediary, String protocol, String cipherSuite, + public SslHandshakeInfo( + boolean isOfIntermediary, + String protocol, + String cipherSuite, ClientAuth clientAuthRequirement, - Certificate serverCertificate, X509Certificate clientCertificate) { + Certificate serverCertificate, + X509Certificate clientCertificate) { this.protocol = protocol; this.cipherSuite = cipherSuite; this.clientAuthRequirement = clientAuthRequirement; @@ -60,8 +64,7 @@ public ClientAuth getClientAuthRequirement() { return clientAuthRequirement; } - public Certificate getServerCertificate() - { + public Certificate getServerCertificate() { return serverCertificate; } @@ -71,13 +74,12 @@ public X509Certificate getClientCertificate() { @Override public String toString() { - return "SslHandshakeInfo{" + - "protocol='" + protocol + '\'' + - ", cipherSuite='" + cipherSuite + '\'' + - ", clientAuthRequirement=" + clientAuthRequirement + - ", serverCertificate=" + serverCertificate + - ", clientCertificate=" + clientCertificate + - ", isOfIntermediary=" + isOfIntermediary + - '}'; + return "SslHandshakeInfo{" + "protocol='" + + protocol + '\'' + ", cipherSuite='" + + cipherSuite + '\'' + ", clientAuthRequirement=" + + clientAuthRequirement + ", serverCertificate=" + + serverCertificate + ", clientCertificate=" + + clientCertificate + ", isOfIntermediary=" + + isOfIntermediary + '}'; } } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/status/ServerStatusManager.java b/zuul-core/src/main/java/com/netflix/netty/common/status/ServerStatusManager.java index bba8acd36c..af34b863f9 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/status/ServerStatusManager.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/status/ServerStatusManager.java @@ -22,15 +22,13 @@ import javax.inject.Inject; import javax.inject.Singleton; - /** * User: michaels@netflix.com * Date: 7/6/17 * Time: 3:37 PM */ @Singleton -public class ServerStatusManager -{ +public class ServerStatusManager { private final ApplicationInfoManager applicationInfoManager; @Inject diff --git a/zuul-core/src/main/java/com/netflix/netty/common/throttle/MaxInboundConnectionsHandler.java b/zuul-core/src/main/java/com/netflix/netty/common/throttle/MaxInboundConnectionsHandler.java index 6956fc23f4..7dfce8b858 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/throttle/MaxInboundConnectionsHandler.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/throttle/MaxInboundConnectionsHandler.java @@ -39,30 +39,29 @@ * */ @ChannelHandler.Sharable -public class MaxInboundConnectionsHandler extends ChannelInboundHandlerAdapter -{ +public class MaxInboundConnectionsHandler extends ChannelInboundHandlerAdapter { public static final AttributeKey ATTR_CH_THROTTLED = AttributeKey.newInstance("_channel_throttled"); private static final Logger LOG = LoggerFactory.getLogger(MaxInboundConnectionsHandler.class); - private final static AtomicInteger connections = new AtomicInteger(0); + private static final AtomicInteger connections = new AtomicInteger(0); private final Counter connectionThrottled; private final int maxConnections; - public MaxInboundConnectionsHandler(Registry registry, String metricId, int maxConnections) - { + public MaxInboundConnectionsHandler(Registry registry, String metricId, int maxConnections) { this.maxConnections = maxConnections; this.connectionThrottled = registry.counter("server.connections.throttled", "id", metricId); } @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception - { + public void channelActive(ChannelHandlerContext ctx) throws Exception { if (maxConnections > 0) { int currentCount = connections.getAndIncrement(); if (currentCount + 1 > maxConnections) { - LOG.warn("Throttling incoming connection as above configured max connections threshold of {}", maxConnections); + LOG.warn( + "Throttling incoming connection as above configured max connections threshold of {}", + maxConnections); Channel channel = ctx.channel(); channel.attr(ATTR_CH_THROTTLED).set(Boolean.TRUE); CurrentPassport.fromChannel(channel).add(PassportState.SERVER_CH_THROTTLING); @@ -75,20 +74,17 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception } @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (ctx.channel().attr(ATTR_CH_THROTTLED).get() != null) { // Discard this msg as channel is in process of being closed. ReferenceCountUtil.safeRelease(msg); - } - else { + } else { super.channelRead(ctx, msg); } } @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception - { + public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (maxConnections > 0) { connections.decrementAndGet(); } diff --git a/zuul-core/src/main/java/com/netflix/netty/common/throttle/RejectionUtils.java b/zuul-core/src/main/java/com/netflix/netty/common/throttle/RejectionUtils.java index 621832e2d4..9da9c11144 100644 --- a/zuul-core/src/main/java/com/netflix/netty/common/throttle/RejectionUtils.java +++ b/zuul-core/src/main/java/com/netflix/netty/common/throttle/RejectionUtils.java @@ -16,7 +16,6 @@ package com.netflix.netty.common.throttle; -import static com.netflix.netty.common.proxyprotocol.HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION; import com.netflix.netty.common.ConnectionCloseChannelAttributes; import com.netflix.zuul.passport.CurrentPassport; import com.netflix.zuul.passport.PassportState; @@ -36,11 +35,14 @@ import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.LastHttpContent; import io.netty.util.ReferenceCountUtil; + +import javax.annotation.Nullable; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; -import javax.annotation.Nullable; + +import static com.netflix.netty.common.proxyprotocol.HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION; /** * A collection of rejection related utilities useful for failing requests. These are tightly coupled with the channel @@ -62,14 +64,21 @@ public final class RejectionUtils { * sent up the pipeline. */ public static void rejectByClosingConnection( - ChannelHandlerContext ctx, StatusCategory nfStatus, String reason, HttpRequest request, + ChannelHandlerContext ctx, + StatusCategory nfStatus, + String reason, + HttpRequest request, @Nullable Integer injectedLatencyMillis) { if (injectedLatencyMillis != null && injectedLatencyMillis > 0) { // Delay closing the connection for configured time. - ctx.executor().schedule(() -> { - CurrentPassport.fromChannel(ctx.channel()).add(PassportState.SERVER_CH_REJECTING); - ctx.close(); - }, injectedLatencyMillis, TimeUnit.MILLISECONDS); + ctx.executor() + .schedule( + () -> { + CurrentPassport.fromChannel(ctx.channel()).add(PassportState.SERVER_CH_REJECTING); + ctx.close(); + }, + injectedLatencyMillis, + TimeUnit.MILLISECONDS); } else { // Close the connection immediately. CurrentPassport.fromChannel(ctx.channel()).add(PassportState.SERVER_CH_REJECTING); @@ -94,8 +103,13 @@ public static void rejectByClosingConnection( * @param rejectionHeaders additional HTTP headers to add to the rejection response */ public static void sendRejectionResponse( - ChannelHandlerContext ctx, StatusCategory nfStatus, String reason, HttpRequest request, - @Nullable Integer injectedLatencyMillis, HttpResponseStatus rejectedCode, String rejectedBody, + ChannelHandlerContext ctx, + StatusCategory nfStatus, + String reason, + HttpRequest request, + @Nullable Integer injectedLatencyMillis, + HttpResponseStatus rejectedCode, + String rejectedBody, Map rejectionHeaders) { boolean shouldClose = closeConnectionAfterReject(ctx.channel()); // Write out a rejection response message. @@ -103,10 +117,14 @@ public static void sendRejectionResponse( if (injectedLatencyMillis != null && injectedLatencyMillis > 0) { // Delay writing the response for configured time. - ctx.executor().schedule(() -> { - CurrentPassport.fromChannel(ctx.channel()).add(PassportState.IN_REQ_REJECTED); - ctx.writeAndFlush(response); - }, injectedLatencyMillis, TimeUnit.MILLISECONDS); + ctx.executor() + .schedule( + () -> { + CurrentPassport.fromChannel(ctx.channel()).add(PassportState.IN_REQ_REJECTED); + ctx.writeAndFlush(response); + }, + injectedLatencyMillis, + TimeUnit.MILLISECONDS); } else { // Write the response immediately. CurrentPassport.fromChannel(ctx.channel()).add(PassportState.IN_REQ_REJECTED); @@ -124,7 +142,9 @@ public static void sendRejectionResponse( */ public static void allowThenClose(ChannelHandlerContext ctx) { // Just flag this channel to be closed after response complete. - ctx.channel().attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE).set(ctx.newPromise()); + ctx.channel() + .attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE) + .set(ctx.newPromise()); // And allow this request through without rejecting. } @@ -145,8 +165,14 @@ public static void allowThenClose(ChannelHandlerContext ctx) { * @param rejectionHeaders additional HTTP headers to add to the rejection response */ public static void handleRejection( - ChannelHandlerContext ctx, Object msg, RejectionType rejectionType, StatusCategory nfStatus, String reason, - @Nullable Integer injectedLatencyMillis, HttpResponseStatus rejectedCode, String rejectedBody, + ChannelHandlerContext ctx, + Object msg, + RejectionType rejectionType, + StatusCategory nfStatus, + String reason, + @Nullable Integer injectedLatencyMillis, + HttpResponseStatus rejectedCode, + String rejectedBody, Map rejectionHeaders) throws Exception { @@ -167,7 +193,15 @@ public static void handleRejection( if (shouldRejectNow) { // Send a rejection response. HttpRequest request = msg instanceof HttpRequest ? (HttpRequest) msg : null; - reject(ctx, rejectionType, nfStatus, reason, request, injectedLatencyMillis, rejectedCode, rejectedBody, + reject( + ctx, + rejectionType, + nfStatus, + reason, + request, + injectedLatencyMillis, + rejectedCode, + rejectedBody, rejectionHeaders); } @@ -178,7 +212,6 @@ public static void handleRejection( } } - /** * Switches on the rejection type to decide how to reject the request and or close the conn. * @@ -193,10 +226,23 @@ public static void handleRejection( * @param rejectedBody the HTTP body to be sent back. It is assumed to be of type text/plain. */ public static void reject( - ChannelHandlerContext ctx, RejectionType rejectionType, StatusCategory nfStatus, String reason, - HttpRequest request, @Nullable Integer injectedLatencyMillis, HttpResponseStatus rejectedCode, + ChannelHandlerContext ctx, + RejectionType rejectionType, + StatusCategory nfStatus, + String reason, + HttpRequest request, + @Nullable Integer injectedLatencyMillis, + HttpResponseStatus rejectedCode, String rejectedBody) { - reject(ctx, rejectionType, nfStatus, reason, request, injectedLatencyMillis, rejectedCode, rejectedBody, + reject( + ctx, + rejectionType, + nfStatus, + reason, + request, + injectedLatencyMillis, + rejectedCode, + rejectedBody, Collections.emptyMap()); } @@ -215,13 +261,25 @@ public static void reject( * @param rejectionHeaders additional HTTP headers to add to the rejection response */ public static void reject( - ChannelHandlerContext ctx, RejectionType rejectionType, StatusCategory nfStatus, String reason, - HttpRequest request, @Nullable Integer injectedLatencyMillis, HttpResponseStatus rejectedCode, - String rejectedBody, Map rejectionHeaders) { + ChannelHandlerContext ctx, + RejectionType rejectionType, + StatusCategory nfStatus, + String reason, + HttpRequest request, + @Nullable Integer injectedLatencyMillis, + HttpResponseStatus rejectedCode, + String rejectedBody, + Map rejectionHeaders) { switch (rejectionType) { case REJECT: sendRejectionResponse( - ctx, nfStatus, reason, request, injectedLatencyMillis, rejectedCode, rejectedBody, + ctx, + nfStatus, + reason, + request, + injectedLatencyMillis, + rejectedCode, + rejectedBody, rejectionHeaders); return; case CLOSE: @@ -235,7 +293,10 @@ public static void reject( } private static void notifyHandlers( - ChannelHandlerContext ctx, StatusCategory nfStatus, HttpResponseStatus status, String reason, + ChannelHandlerContext ctx, + StatusCategory nfStatus, + HttpResponseStatus status, + String reason, HttpRequest request) { RequestRejectedEvent event = new RequestRejectedEvent(request, nfStatus, status, reason); // Send this from the beginning of the pipeline, as it may be sent from the ClientRequestReceiver. @@ -244,14 +305,17 @@ private static void notifyHandlers( private static boolean closeConnectionAfterReject(Channel channel) { if (channel.hasAttr(ATTR_HAPROXY_VERSION)) { - return HAProxyProtocolVersion.V2 == channel.attr(ATTR_HAPROXY_VERSION).get(); + return HAProxyProtocolVersion.V2 + == channel.attr(ATTR_HAPROXY_VERSION).get(); } else { return false; } } private static FullHttpResponse createRejectionResponse( - HttpResponseStatus status, String plaintextMessage, boolean closeConnection, + HttpResponseStatus status, + String plaintextMessage, + boolean closeConnection, Map rejectionHeaders) { ByteBuf body = Unpooled.wrappedBuffer(plaintextMessage.getBytes(StandardCharsets.UTF_8)); int length = body.readableBytes(); diff --git a/zuul-core/src/main/java/com/netflix/zuul/Attrs.java b/zuul-core/src/main/java/com/netflix/zuul/Attrs.java index ab66ea89f9..2eb30ec922 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/Attrs.java +++ b/zuul-core/src/main/java/com/netflix/zuul/Attrs.java @@ -17,6 +17,8 @@ package com.netflix.zuul; import com.google.common.annotations.VisibleForTesting; + +import javax.annotation.Nullable; import java.util.Collections; import java.util.IdentityHashMap; import java.util.LinkedHashSet; @@ -24,7 +26,6 @@ import java.util.Objects; import java.util.Set; import java.util.function.BiConsumer; -import javax.annotation.Nullable; /** * A heterogeneous map of attributes. diff --git a/zuul-core/src/main/java/com/netflix/zuul/BasicFilterUsageNotifier.java b/zuul-core/src/main/java/com/netflix/zuul/BasicFilterUsageNotifier.java index 0f39edb0ba..c0c6f3678e 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/BasicFilterUsageNotifier.java +++ b/zuul-core/src/main/java/com/netflix/zuul/BasicFilterUsageNotifier.java @@ -18,6 +18,7 @@ import com.netflix.spectator.api.Registry; import com.netflix.zuul.filters.ZuulFilter; + import javax.inject.Inject; /** @@ -35,9 +36,11 @@ public class BasicFilterUsageNotifier implements FilterUsageNotifier { @Override public void notify(ZuulFilter filter, ExecutionStatus status) { registry.counter( - "zuul.filter-" + filter.getClass().getSimpleName(), - "status", status.name(), - "filtertype", filter.filterType().toString()).increment(); + "zuul.filter-" + filter.getClass().getSimpleName(), + "status", + status.name(), + "filtertype", + filter.filterType().toString()) + .increment(); } } - diff --git a/zuul-core/src/main/java/com/netflix/zuul/BasicRequestCompleteHandler.java b/zuul-core/src/main/java/com/netflix/zuul/BasicRequestCompleteHandler.java index a3279cbc97..b5dbad6076 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/BasicRequestCompleteHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/BasicRequestCompleteHandler.java @@ -16,9 +16,9 @@ package com.netflix.zuul; +import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.http.HttpRequestInfo; import com.netflix.zuul.message.http.HttpResponseMessage; -import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.stats.RequestMetricsPublisher; import javax.annotation.Nullable; @@ -29,15 +29,13 @@ * Date: 6/4/15 * Time: 4:26 PM */ -public class BasicRequestCompleteHandler implements RequestCompleteHandler -{ +public class BasicRequestCompleteHandler implements RequestCompleteHandler { @Inject @Nullable private RequestMetricsPublisher requestMetricsPublisher; @Override - public void handle(HttpRequestInfo inboundRequest, HttpResponseMessage response) - { + public void handle(HttpRequestInfo inboundRequest, HttpResponseMessage response) { SessionContext context = inboundRequest.getContext(); // Publish request-level metrics. diff --git a/zuul-core/src/main/java/com/netflix/zuul/DefaultFilterFactory.java b/zuul-core/src/main/java/com/netflix/zuul/DefaultFilterFactory.java index 2f69ed2a0c..e3a605e8f5 100755 --- a/zuul-core/src/main/java/com/netflix/zuul/DefaultFilterFactory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/DefaultFilterFactory.java @@ -18,14 +18,14 @@ import com.netflix.zuul.filters.ZuulFilter; /** - * Default factory for creating instances of ZuulFilter. + * Default factory for creating instances of ZuulFilter. */ public class DefaultFilterFactory implements FilterFactory { /** - * Returns a new implementation of ZuulFilter as specified by the provided + * Returns a new implementation of ZuulFilter as specified by the provided * Class. The Class is instantiated using its nullary constructor. - * + * * @param clazz the Class to instantiate * @return A new instance of ZuulFilter */ @@ -33,5 +33,4 @@ public class DefaultFilterFactory implements FilterFactory { public ZuulFilter newInstance(Class clazz) throws InstantiationException, IllegalAccessException { return (ZuulFilter) clazz.newInstance(); } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/DynamicCodeCompiler.java b/zuul-core/src/main/java/com/netflix/zuul/DynamicCodeCompiler.java index 7a4aa71736..be582d49c5 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/DynamicCodeCompiler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/DynamicCodeCompiler.java @@ -18,7 +18,6 @@ import java.io.File; - /** * Interface to generate Classes from source code * User: mcohen diff --git a/zuul-core/src/main/java/com/netflix/zuul/DynamicFilterLoader.java b/zuul-core/src/main/java/com/netflix/zuul/DynamicFilterLoader.java index b2c15787f6..5f6765d438 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/DynamicFilterLoader.java +++ b/zuul-core/src/main/java/com/netflix/zuul/DynamicFilterLoader.java @@ -19,6 +19,11 @@ import com.netflix.zuul.filters.FilterRegistry; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.ZuulFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.inject.Inject; +import javax.inject.Singleton; import java.io.File; import java.lang.reflect.Modifier; import java.util.ArrayList; @@ -28,10 +33,6 @@ import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import javax.inject.Inject; -import javax.inject.Singleton; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; @Singleton public final class DynamicFilterLoader implements FilterLoader { @@ -51,9 +52,7 @@ public final class DynamicFilterLoader implements FilterLoader { @Inject public DynamicFilterLoader( - FilterRegistry filterRegistry, - DynamicCodeCompiler compiler, - FilterFactory filterFactory) { + FilterRegistry filterRegistry, DynamicCodeCompiler compiler, FilterFactory filterFactory) { this.filterRegistry = filterRegistry; this.compiler = compiler; this.filterFactory = filterFactory; @@ -141,7 +140,7 @@ private void putFilter(String filterName, ZuulFilter filter, long lastModi } SortedSet> set = hashFiltersByType.get(filter.filterType()); if (set != null) { - hashFiltersByType.remove(filter.filterType()); //rebuild this list + hashFiltersByType.remove(filter.filterType()); // rebuild this list } String nameAndType = filter.filterType() + ":" + filter.filterName(); diff --git a/zuul-core/src/main/java/com/netflix/zuul/ExecutionStatus.java b/zuul-core/src/main/java/com/netflix/zuul/ExecutionStatus.java index 97a7f0ac88..31b05df8c5 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/ExecutionStatus.java +++ b/zuul-core/src/main/java/com/netflix/zuul/ExecutionStatus.java @@ -16,9 +16,13 @@ package com.netflix.zuul; public enum ExecutionStatus { + SUCCESS(1), + SKIPPED(-1), + DISABLED(-2), + FAILED(-3), + BODY_AWAIT(-4), + ASYNC_AWAIT(-5); - SUCCESS (1), SKIPPED(-1), DISABLED(-2), FAILED(-3), BODY_AWAIT(-4), ASYNC_AWAIT(-5); - private int status; ExecutionStatus(int status) { diff --git a/zuul-core/src/main/java/com/netflix/zuul/Filter.java b/zuul-core/src/main/java/com/netflix/zuul/Filter.java index 8e6170735d..99ba0ae840 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/Filter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/Filter.java @@ -16,18 +16,19 @@ package com.netflix.zuul; -import static java.lang.annotation.ElementType.PACKAGE; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.CLASS; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - import com.netflix.zuul.filters.FilterSyncType; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.ZuulFilter; + import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.PACKAGE; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.CLASS; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + /** * Identifies a {@link ZuulFilter}. */ diff --git a/zuul-core/src/main/java/com/netflix/zuul/FilterCategory.java b/zuul-core/src/main/java/com/netflix/zuul/FilterCategory.java index e39e15dc8e..e27bd188b7 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/FilterCategory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/FilterCategory.java @@ -20,8 +20,9 @@ * Categorization of filters. */ public enum FilterCategory { - - ABUSE("abuse", "Abuse detection and protection filters, such as rate-limiting, malicious request detection, geo-blocking"), + ABUSE( + "abuse", + "Abuse detection and protection filters, such as rate-limiting, malicious request detection, geo-blocking"), ACCESS("access", "Authentication and authorization filters"), ADMIN("admin", "Admin only filters providing operational support"), CHAOS("chaos", "Failure injection testing and resilience support"), @@ -33,7 +34,7 @@ public enum FilterCategory { OVERLOAD("overload", "Filters to respond on the server being in an overloaded state such as brownout"), ROUTING("routing", "Filters which make routing decisions"), ; - + private final String code; private final String description; diff --git a/zuul-core/src/main/java/com/netflix/zuul/FilterFactory.java b/zuul-core/src/main/java/com/netflix/zuul/FilterFactory.java index bd6e7b22ae..5d98da0f32 100755 --- a/zuul-core/src/main/java/com/netflix/zuul/FilterFactory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/FilterFactory.java @@ -21,10 +21,10 @@ * Interface to provide instances of ZuulFilter from a given class. */ public interface FilterFactory { - + /** * Returns an instance of the specified class. - * + * * @param clazz the Class to instantiate * @return an instance of ZuulFilter * @throws Exception if an error occurs diff --git a/zuul-core/src/main/java/com/netflix/zuul/FilterFileManager.java b/zuul-core/src/main/java/com/netflix/zuul/FilterFileManager.java index 54c430e8df..163b4a2528 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/FilterFileManager.java +++ b/zuul-core/src/main/java/com/netflix/zuul/FilterFileManager.java @@ -17,6 +17,11 @@ import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.config.DynamicIntProperty; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.inject.Inject; +import javax.inject.Singleton; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; @@ -29,10 +34,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; -import javax.inject.Inject; -import javax.inject.Singleton; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * This class manages the directory polling for changes and new Groovy filters. @@ -47,8 +48,10 @@ public class FilterFileManager { private static final Logger LOG = LoggerFactory.getLogger(FilterFileManager.class); - private static final DynamicIntProperty FILE_PROCESSOR_THREADS = new DynamicIntProperty("zuul.filterloader.threads", 1); - private static final DynamicIntProperty FILE_PROCESSOR_TASKS_TIMEOUT_SECS = new DynamicIntProperty("zuul.filterloader.tasks.timeout", 120); + private static final DynamicIntProperty FILE_PROCESSOR_THREADS = + new DynamicIntProperty("zuul.filterloader.threads", 1); + private static final DynamicIntProperty FILE_PROCESSOR_TASKS_TIMEOUT_SECS = + new DynamicIntProperty("zuul.filterloader.tasks.timeout", 120); Thread poller; boolean bRunning = true; @@ -70,19 +73,21 @@ public FilterFileManager(FilterFileManagerConfig config, FilterLoader filterLoad */ @Inject public void init() throws Exception { - if(!config.enabled) { + if (!config.enabled) { return; } long startTime = System.currentTimeMillis(); - ThreadFactory tf = - new ThreadFactoryBuilder().setDaemon(true).setNameFormat("FilterFileManager_ProcessFiles-%d").build(); + ThreadFactory tf = new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("FilterFileManager_ProcessFiles-%d") + .build(); this.processFilesService = Executors.newFixedThreadPool(FILE_PROCESSOR_THREADS.get(), tf); filterLoader.putFiltersForClasses(config.getClassNames()); manageFiles(); startPoller(); - + LOG.warn("Finished loading all zuul filters. Duration = {} ms.", (System.currentTimeMillis() - startTime)); } @@ -108,8 +113,7 @@ public void run() { try { sleep(config.getPollingIntervalSeconds() * 1000); manageFiles(); - } - catch (Exception e) { + } catch (Exception e) { LOG.error("Error checking and/or loading filter files from Poller thread.", e); } } @@ -125,7 +129,7 @@ public void run() { * @return a File representing the directory path */ public File getDirectory(String sPath) { - File directory = new File(sPath); + File directory = new File(sPath); if (!directory.isDirectory()) { URL resource = FilterFileManager.class.getClassLoader().getResource(sPath); try { @@ -174,8 +178,7 @@ void processGroovyFiles(List aFiles) throws Exception { tasks.add(() -> { try { return filterLoader.putFilter(file); - } - catch(Exception e) { + } catch (Exception e) { LOG.error("Error loading groovy filter from disk! file = {}", String.valueOf(file), e); return false; } @@ -184,32 +187,35 @@ void processGroovyFiles(List aFiles) throws Exception { processFilesService.invokeAll(tasks, FILE_PROCESSOR_TASKS_TIMEOUT_SECS.get(), TimeUnit.SECONDS); } - void manageFiles() - { + void manageFiles() { try { List aFiles = getFiles(); processGroovyFiles(aFiles); - } - catch (Exception e) { + } catch (Exception e) { String msg = "Error updating groovy filters from disk!"; LOG.error(msg, e); throw new RuntimeException(msg, e); } } - public static class FilterFileManagerConfig - { + public static class FilterFileManagerConfig { private String[] directories; private String[] classNames; private int pollingIntervalSeconds; private FilenameFilter filenameFilter; boolean enabled; - public FilterFileManagerConfig(String[] directories, String[] classNames, int pollingIntervalSeconds, FilenameFilter filenameFilter) { + public FilterFileManagerConfig( + String[] directories, String[] classNames, int pollingIntervalSeconds, FilenameFilter filenameFilter) { this(directories, classNames, pollingIntervalSeconds, filenameFilter, true); } - public FilterFileManagerConfig(String[] directories, String[] classNames, int pollingIntervalSeconds, FilenameFilter filenameFilter, boolean enabled) { + public FilterFileManagerConfig( + String[] directories, + String[] classNames, + int pollingIntervalSeconds, + FilenameFilter filenameFilter, + boolean enabled) { this.directories = directories; this.classNames = classNames; this.pollingIntervalSeconds = pollingIntervalSeconds; @@ -220,13 +226,15 @@ public FilterFileManagerConfig(String[] directories, String[] classNames, int po public String[] getDirectories() { return directories; } - public String[] getClassNames() - { + + public String[] getClassNames() { return classNames; } + public int getPollingIntervalSeconds() { return pollingIntervalSeconds; } + public FilenameFilter getFilenameFilter() { return filenameFilter; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/FilterLoader.java b/zuul-core/src/main/java/com/netflix/zuul/FilterLoader.java index 8dec7122e7..b3d8a67949 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/FilterLoader.java +++ b/zuul-core/src/main/java/com/netflix/zuul/FilterLoader.java @@ -15,15 +15,16 @@ */ package com.netflix.zuul; -import static java.util.Objects.requireNonNull; - import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.ZuulFilter; + import java.io.File; import java.util.Comparator; import java.util.List; import java.util.SortedSet; +import static java.util.Objects.requireNonNull; + /** * This class is one of the core classes in Zuul. It compiles, loads from a File, and checks if source code changed. * It also holds ZuulFilters by filterType. @@ -48,7 +49,6 @@ public interface FilterLoader { */ List> putFiltersForClasses(String[] classNames) throws Exception; - ZuulFilter putFilterForClassName(String className) throws Exception; /** @@ -63,6 +63,7 @@ public interface FilterLoader { Comparator>> FILTER_CLASS_COMPARATOR = Comparator.>>comparingInt( - c -> requireNonNull(c.getAnnotation(Filter.class), () -> "missing annotation: " + c).order()) + c -> requireNonNull(c.getAnnotation(Filter.class), () -> "missing annotation: " + c) + .order()) .thenComparing(Class::getName); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/RequestCompleteHandler.java b/zuul-core/src/main/java/com/netflix/zuul/RequestCompleteHandler.java index 4ce36bdcf2..9bb20b01d8 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/RequestCompleteHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/RequestCompleteHandler.java @@ -18,8 +18,6 @@ import com.netflix.zuul.message.http.HttpRequestInfo; import com.netflix.zuul.message.http.HttpResponseMessage; -public interface RequestCompleteHandler -{ +public interface RequestCompleteHandler { void handle(HttpRequestInfo inboundRequest, HttpResponseMessage response); } - diff --git a/zuul-core/src/main/java/com/netflix/zuul/StaticFilterLoader.java b/zuul-core/src/main/java/com/netflix/zuul/StaticFilterLoader.java index 7c6c18d46d..1ae1ad7167 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/StaticFilterLoader.java +++ b/zuul-core/src/main/java/com/netflix/zuul/StaticFilterLoader.java @@ -19,7 +19,11 @@ import com.google.errorprone.annotations.DoNotCall; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.ZuulFilter; -import com.netflix.zuul.message.ZuulMessage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; +import javax.inject.Inject; import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -27,10 +31,7 @@ import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; import java.util.LinkedHashSet; @@ -40,10 +41,6 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; -import javax.annotation.Nullable; -import javax.inject.Inject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * An immutable static collection of filters. @@ -65,8 +62,12 @@ public StaticFilterLoader( for (Class> clz : filterTypes) { try { ZuulFilter f = filterFactory.newInstance(clz); - filtersByType.computeIfAbsent(f.filterType(), k -> new TreeSet<>(FILTER_COMPARATOR)).add(f); - filtersByName.computeIfAbsent(f.filterType(), k -> new HashMap<>()).put(f.filterName(), f); + filtersByType + .computeIfAbsent(f.filterType(), k -> new TreeSet<>(FILTER_COMPARATOR)) + .add(f); + filtersByName + .computeIfAbsent(f.filterType(), k -> new HashMap<>()) + .put(f.filterName(), f); } catch (RuntimeException | Error e) { throw e; } catch (Exception e) { @@ -84,8 +85,7 @@ public StaticFilterLoader( this.filtersByType = Collections.unmodifiableMap(filtersByType); } - public static Set>> loadFilterTypesFromResources(ClassLoader loader) - throws IOException { + public static Set>> loadFilterTypesFromResources(ClassLoader loader) throws IOException { Set>> filterTypes = new LinkedHashSet<>(); for (URL url : Collections.list(loader.getResources(RESOURCE_NAME))) { try (InputStream is = url.openStream(); @@ -113,8 +113,7 @@ public StaticFilterLoader( continue; } @SuppressWarnings("unchecked") - Class> filterClz = - (Class>) clz.asSubclass(ZuulFilter.class); + Class> filterClz = (Class>) clz.asSubclass(ZuulFilter.class); filterTypes.add(filterClz); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/constants/ZuulConstants.java b/zuul-core/src/main/java/com/netflix/zuul/constants/ZuulConstants.java index 3b17537c10..3cf98153ae 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/constants/ZuulConstants.java +++ b/zuul-core/src/main/java/com/netflix/zuul/constants/ZuulConstants.java @@ -26,7 +26,8 @@ public class ZuulConstants { public static final String DEFAULT_NFASTYANAX_WRITECONSISTENCY = "default.nfastyanax.writeConsistency"; public static final String DEFAULT_NFASTYANAX_SOCKETTIMEOUT = "default.nfastyanax.socketTimeout"; public static final String DEFAULT_NFASTYANAX_MAXCONNSPERHOST = "default.nfastyanax.maxConnsPerHost"; - public static final String DEFAULT_NFASTYANAX_MAXTIMEOUTWHENEXHAUSTED = "default.nfastyanax.maxTimeoutWhenExhausted"; + public static final String DEFAULT_NFASTYANAX_MAXTIMEOUTWHENEXHAUSTED = + "default.nfastyanax.maxTimeoutWhenExhausted"; public static final String DEFAULT_NFASTYANAX_MAXFAILOVERCOUNT = "default.nfastyanax.maxFailoverCount"; public static final String DEFAULT_NFASTYANAX_FAILOVERWAITTIME = "default.nfastyanax.failoverWaitTime"; public static final String ZUUL_CASSANDRA_KEYSPACE = "zuul.cassandra.keyspace"; @@ -48,7 +49,6 @@ public class ZuulConstants { public static final String ZUUL_FILTER_ADMIN_ENABLED = "zuul.filter.admin.enabled"; public static final String ZUUL_FILTER_ADMIN_REDIRECT = "zuul.filter.admin.redirect.path"; - public static final String ZUUL_DEBUG_REQUEST = "zuul.debug.request"; public static final String ZUUL_DEBUG_PARAMETER = "zuul.debug.parameter"; public static final String ZUUL_ROUTER_ALT_ROUTE_VIP = "zuul.router.alt.route.vip"; @@ -72,5 +72,4 @@ public class ZuulConstants { private ZuulConstants() { throw new AssertionError("Must not instantiate constant utility class"); } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/constants/ZuulHeaders.java b/zuul-core/src/main/java/com/netflix/zuul/constants/ZuulHeaders.java index 44e136ba44..9b1fbf9800 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/constants/ZuulHeaders.java +++ b/zuul-core/src/main/java/com/netflix/zuul/constants/ZuulHeaders.java @@ -51,5 +51,4 @@ public class ZuulHeaders { private ZuulHeaders() { throw new AssertionError("Must not instantiate constant utility class"); } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/context/CommonContextKeys.java b/zuul-core/src/main/java/com/netflix/zuul/context/CommonContextKeys.java index 9be4804550..a15a49a164 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/context/CommonContextKeys.java +++ b/zuul-core/src/main/java/com/netflix/zuul/context/CommonContextKeys.java @@ -25,9 +25,10 @@ import com.netflix.zuul.passport.CurrentPassport; import com.netflix.zuul.stats.status.StatusCategory; import io.netty.channel.Channel; + +import javax.inject.Provider; import java.net.InetAddress; import java.util.Map; -import javax.inject.Provider; /** * Common Context Keys @@ -37,11 +38,10 @@ */ public class CommonContextKeys { - public static final SessionContext.Key STATUS_CATGEORY = - SessionContext.newKey("status_category"); + public static final SessionContext.Key STATUS_CATGEORY = SessionContext.newKey("status_category"); public static final SessionContext.Key ORIGIN_STATUS_CATEGORY = SessionContext.newKey("origin_status_category"); - public static final SessionContext.Key ORIGIN_STATUS = SessionContext.newKey("origin_status"); + public static final SessionContext.Key ORIGIN_STATUS = SessionContext.newKey("origin_status"); public static final SessionContext.Key REQUEST_ATTEMPTS = SessionContext.newKey("request_attempts"); diff --git a/zuul-core/src/main/java/com/netflix/zuul/context/Debug.java b/zuul-core/src/main/java/com/netflix/zuul/context/Debug.java index 80bbe93c91..e8db93f3a5 100755 --- a/zuul-core/src/main/java/com/netflix/zuul/context/Debug.java +++ b/zuul-core/src/main/java/com/netflix/zuul/context/Debug.java @@ -20,13 +20,14 @@ import com.netflix.zuul.message.http.HttpRequestInfo; import com.netflix.zuul.message.http.HttpResponseInfo; import io.netty.util.ReferenceCounted; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + /** * Simple wrapper class around the RequestContext for setting and managing Request level Debug data. * @author Mikey Cohen @@ -48,12 +49,10 @@ public static boolean debugRequestHeadersOnly(SessionContext ctx) { return ctx.debugRequestHeadersOnly(); } - public static void setDebugRouting(SessionContext ctx, boolean bDebug) { ctx.setDebugRouting(bDebug); } - public static boolean debugRequest(SessionContext ctx) { return ctx.debugRequest(); } @@ -67,8 +66,7 @@ public static void addRoutingDebug(SessionContext ctx, String line) { rd.add(line); } - public static void addRequestDebugForMessage(SessionContext ctx, ZuulMessage message, String prefix) - { + public static void addRequestDebugForMessage(SessionContext ctx, ZuulMessage message, String prefix) { for (Header header : message.getHeaders().entries()) { Debug.addRequestDebug(ctx, prefix + " " + header.getKey() + " " + header.getValue()); } @@ -114,7 +112,6 @@ public static List getRequestDebug(SessionContext ctx) { return rd; } - /** * Adds debug details about changes that a given filter made to the request context. * @param filterName @@ -123,7 +120,8 @@ public static List getRequestDebug(SessionContext ctx) { public static void compareContextState(String filterName, SessionContext context, SessionContext copy) { // TODO - only comparing Attributes. Need to compare the messages too. - // Ensure that the routingDebug property already exists, otherwise we'll have a ConcurrentModificationException below + // Ensure that the routingDebug property already exists, otherwise we'll have a ConcurrentModificationException + // below getRoutingDebug(context); Iterator it = context.keySet().iterator(); @@ -137,7 +135,7 @@ public static void compareContextState(String filterName, SessionContext context addRoutingDebug(context, "{" + filterName + "} added " + key + "=" + newValue.toString()); } else if (oldValue != null && newValue != null) { if (!(oldValue.equals(newValue))) { - addRoutingDebug(context, "{" +filterName + "} changed " + key + "=" + newValue.toString()); + addRoutingDebug(context, "{" + filterName + "} changed " + key + "=" + newValue.toString()); } } } @@ -148,19 +146,24 @@ public static void compareContextState(String filterName, SessionContext context key = null; } } - } - public static Observable writeDebugRequest(SessionContext context, - HttpRequestInfo request, boolean isInbound) - { + public static Observable writeDebugRequest( + SessionContext context, HttpRequestInfo request, boolean isInbound) { Observable obs = null; if (Debug.debugRequest(context)) { String prefix = isInbound ? "REQUEST_INBOUND" : "REQUEST_OUTBOUND"; String arrow = ">"; - Debug.addRequestDebug(context, String.format("%s:: %s LINE: %s %s %s", - prefix, arrow, request.getMethod().toUpperCase(), request.getPathAndQuery(), request.getProtocol())); + Debug.addRequestDebug( + context, + String.format( + "%s:: %s LINE: %s %s %s", + prefix, + arrow, + request.getMethod().toUpperCase(), + request.getPathAndQuery(), + request.getProtocol())); obs = Debug.writeDebugMessage(context, request, prefix, arrow); } @@ -171,9 +174,8 @@ public static Observable writeDebugRequest(SessionContext context, return obs; } - public static Observable writeDebugResponse(SessionContext context, - HttpResponseInfo response, boolean isInbound) - { + public static Observable writeDebugResponse( + SessionContext context, HttpResponseInfo response, boolean isInbound) { Observable obs = null; if (Debug.debugRequest(context)) { String prefix = isInbound ? "RESPONSE_INBOUND" : "RESPONSE_OUTBOUND"; @@ -190,18 +192,18 @@ public static Observable writeDebugResponse(SessionContext context, return obs; } - public static Observable writeDebugMessage(SessionContext context, ZuulMessage msg, - String prefix, String arrow) - { + public static Observable writeDebugMessage( + SessionContext context, ZuulMessage msg, String prefix, String arrow) { Observable obs = null; for (Header header : msg.getHeaders().entries()) { - Debug.addRequestDebug(context, String.format("%s:: %s HDR: %s:%s", prefix, arrow, header.getKey(), header.getValue())); + Debug.addRequestDebug( + context, String.format("%s:: %s HDR: %s:%s", prefix, arrow, header.getKey(), header.getValue())); } // Capture the response body into a Byte array for later usage. if (msg.hasBody()) { - if (! Debug.debugRequestHeadersOnly(context)) { + if (!Debug.debugRequestHeadersOnly(context)) { // Convert body to a String and add to debug log. String body = msg.getBodyAsText(); Debug.addRequestDebug(context, String.format("%s:: %s BODY: %s", prefix, arrow, body)); diff --git a/zuul-core/src/main/java/com/netflix/zuul/context/SessionCleaner.java b/zuul-core/src/main/java/com/netflix/zuul/context/SessionCleaner.java index a98b98dbd4..cdac667b04 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/context/SessionCleaner.java +++ b/zuul-core/src/main/java/com/netflix/zuul/context/SessionCleaner.java @@ -23,7 +23,6 @@ * Date: 8/3/15 * Time: 12:30 PM */ -public interface SessionCleaner -{ +public interface SessionCleaner { Observable cleanup(SessionContext context); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/context/SessionContext.java b/zuul-core/src/main/java/com/netflix/zuul/context/SessionContext.java index 88ac4e40d6..ecea037fc8 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/context/SessionContext.java +++ b/zuul-core/src/main/java/com/netflix/zuul/context/SessionContext.java @@ -15,11 +15,12 @@ */ package com.netflix.zuul.context; - import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.netflix.config.DynamicPropertyFactory; import com.netflix.zuul.filters.FilterError; import com.netflix.zuul.message.http.HttpResponseMessage; + +import javax.annotation.Nullable; import java.net.URL; import java.util.ArrayList; import java.util.Collections; @@ -30,8 +31,6 @@ import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.function.BiConsumer; -import javax.annotation.Nullable; /** * Represents the context between client and origin server for the duration of the dedicated connection/session @@ -44,8 +43,9 @@ * Time: 6:45 PM */ public final class SessionContext extends HashMap implements Cloneable { - private static final int INITIAL_SIZE = - DynamicPropertyFactory.getInstance().getIntProperty("com.netflix.zuul.context.SessionContext.initialSize", 60).get(); + private static final int INITIAL_SIZE = DynamicPropertyFactory.getInstance() + .getIntProperty("com.netflix.zuul.context.SessionContext.initialSize", 60) + .get(); private boolean brownoutMode = false; private boolean shouldStopFilterProcessing = false; @@ -105,8 +105,7 @@ public int hashCode() { } } - public SessionContext() - { + public SessionContext() { // Use a higher than default initial capacity for the hashmap as we generally have more than the default // 16 entries. super(INITIAL_SIZE); @@ -221,14 +220,12 @@ public Set> keys() { * Makes a copy of the RequestContext. This is used for debugging. */ @Override - public SessionContext clone() - { + public SessionContext clone() { // TODO(carl-mastrangelo): copy over the type safe keys return (SessionContext) super.clone(); } - public String getString(String key) - { + public String getString(String key) { return (String) get(key); } @@ -273,18 +270,18 @@ public void set(String key, Object value) { } } - public String getUUID() - { + public String getUUID() { return getString(KEY_UUID); } - public void setUUID(String uuid) - { + + public void setUUID(String uuid) { set(KEY_UUID, uuid); } public void setStaticResponse(HttpResponseMessage response) { set(KEY_STATIC_RESPONSE, response); } + public HttpResponseMessage getStaticResponse() { return (HttpResponseMessage) get(KEY_STATIC_RESPONSE); } @@ -295,7 +292,6 @@ public HttpResponseMessage getStaticResponse() { */ public Throwable getError() { return (Throwable) get("_error"); - } /** @@ -303,12 +299,12 @@ public Throwable getError() { */ public void setError(Throwable th) { put("_error", th); - } public String getErrorEndpoint() { return (String) get("_error-endpoint"); } + public void setErrorEndpoint(String name) { put("_error-endpoint", name); } @@ -390,7 +386,13 @@ public void addFilterExecutionSummary(String name, String status, long time) { if (sb.length() > 0) { sb.append(", "); } - sb.append(name).append('[').append(status).append(']').append('[').append(time).append("ms]"); + sb.append(name) + .append('[') + .append(status) + .append(']') + .append('[') + .append(time) + .append("ms]"); } /** @@ -413,7 +415,6 @@ public void setShouldSendErrorResponse(boolean should) { this.shouldSendErrorResponse = should; } - public boolean errorResponseSent() { return this.errorResponseSent; } @@ -422,19 +423,16 @@ public void setErrorResponseSent(boolean should) { this.errorResponseSent = should; } - /** * This can be used by filters for flagging if the server is getting overloaded, and then choose * to disable/sample/rate-limit some optional features. * */ - public boolean isInBrownoutMode() - { + public boolean isInBrownoutMode() { return brownoutMode; } - public void setInBrownoutMode() - { + public void setInBrownoutMode() { this.brownoutMode = true; } @@ -465,13 +463,11 @@ public void setRouteVIP(String sVip) { set(KEY_VIP, sVip); } - public void setEndpoint(String endpoint) - { + public void setEndpoint(String endpoint) { put(KEY_ENDPOINT, endpoint); } - public String getEndpoint() - { + public String getEndpoint() { return (String) get(KEY_ENDPOINT); } @@ -487,13 +483,11 @@ public List getFilterErrors() { return (List) get(KEY_FILTER_ERRORS); } - public void setOriginReportedDuration(int duration) - { + public void setOriginReportedDuration(int duration) { put("_originReportedDuration", duration); } - public int getOriginReportedDuration() - { + public int getOriginReportedDuration() { Object value = get("_originReportedDuration"); if (value != null) { return (Integer) value; diff --git a/zuul-core/src/main/java/com/netflix/zuul/context/SessionContextFactory.java b/zuul-core/src/main/java/com/netflix/zuul/context/SessionContextFactory.java index 4f3b28307c..81c4759767 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/context/SessionContextFactory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/context/SessionContextFactory.java @@ -18,8 +18,8 @@ import com.netflix.zuul.message.ZuulMessage; import rx.Observable; -public interface SessionContextFactory -{ +public interface SessionContextFactory { public ZuulMessage create(SessionContext context, T nativeRequest, V nativeResponse); + public Observable write(ZuulMessage msg, V nativeResponse); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/context/ZuulSessionContextDecorator.java b/zuul-core/src/main/java/com/netflix/zuul/context/ZuulSessionContextDecorator.java index f6b813484a..a468472bde 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/context/ZuulSessionContextDecorator.java +++ b/zuul-core/src/main/java/com/netflix/zuul/context/ZuulSessionContextDecorator.java @@ -50,7 +50,8 @@ public ZuulSessionContextDecorator(OriginManager originManager) { public SessionContext decorate(SessionContext ctx) { // TODO split out commons parts from BaseSessionContextDecorator - ChannelHandlerContext nettyCtx = (ChannelHandlerContext) ctx.get(CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT); + ChannelHandlerContext nettyCtx = + (ChannelHandlerContext) ctx.get(CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT); if (nettyCtx == null) { return null; } @@ -61,7 +62,7 @@ public SessionContext decorate(SessionContext ctx) { ctx.put(CommonContextKeys.ORIGIN_MANAGER, originManager); // TODO -/* // The throttle result info. + /* // The throttle result info. ThrottleResult throttleResult = channel.attr(HttpRequestThrottleChannelHandler.ATTR_THROTTLE_RESULT).get(); ctx.set(CommonContextKeys.THROTTLE_RESULT, throttleResult);*/ diff --git a/zuul-core/src/main/java/com/netflix/zuul/exception/ErrorType.java b/zuul-core/src/main/java/com/netflix/zuul/exception/ErrorType.java index 8583807b69..c81cb09023 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/exception/ErrorType.java +++ b/zuul-core/src/main/java/com/netflix/zuul/exception/ErrorType.java @@ -29,21 +29,26 @@ public interface ErrorType { String PROP_PREFIX = "zuul.error.outbound"; - DynamicIntProperty ERROR_TYPE_READ_TIMEOUT_STATUS = new DynamicIntProperty(PROP_PREFIX + ".readtimeout.status", 504); - DynamicIntProperty ERROR_TYPE_CONNECT_ERROR_STATUS = new DynamicIntProperty(PROP_PREFIX + ".connecterror.status", 502); - DynamicIntProperty ERROR_TYPE_SERVICE_UNAVAILABLE_STATUS = new DynamicIntProperty(PROP_PREFIX + ".serviceunavailable.status", 503); - DynamicIntProperty ERROR_TYPE_ORIGIN_CONCURRENCY_EXCEEDED_STATUS = new DynamicIntProperty(PROP_PREFIX + ".originconcurrencyexceeded.status", 503); - DynamicIntProperty ERROR_TYPE_ERROR_STATUS_RESPONSE_STATUS = new DynamicIntProperty(PROP_PREFIX + ".errorstatusresponse.status", 500); + DynamicIntProperty ERROR_TYPE_READ_TIMEOUT_STATUS = + new DynamicIntProperty(PROP_PREFIX + ".readtimeout.status", 504); + DynamicIntProperty ERROR_TYPE_CONNECT_ERROR_STATUS = + new DynamicIntProperty(PROP_PREFIX + ".connecterror.status", 502); + DynamicIntProperty ERROR_TYPE_SERVICE_UNAVAILABLE_STATUS = + new DynamicIntProperty(PROP_PREFIX + ".serviceunavailable.status", 503); + DynamicIntProperty ERROR_TYPE_ORIGIN_CONCURRENCY_EXCEEDED_STATUS = + new DynamicIntProperty(PROP_PREFIX + ".originconcurrencyexceeded.status", 503); + DynamicIntProperty ERROR_TYPE_ERROR_STATUS_RESPONSE_STATUS = + new DynamicIntProperty(PROP_PREFIX + ".errorstatusresponse.status", 500); DynamicIntProperty ERROR_TYPE_NOSERVERS_STATUS = new DynamicIntProperty(PROP_PREFIX + ".noservers.status", 502); - DynamicIntProperty ERROR_TYPE_ORIGIN_SERVER_MAX_CONNS_STATUS = new DynamicIntProperty(PROP_PREFIX + ".servermaxconns.status", 503); - DynamicIntProperty ERROR_TYPE_ORIGIN_RESET_CONN_STATUS = new DynamicIntProperty(PROP_PREFIX + ".originresetconnection.status", 504); + DynamicIntProperty ERROR_TYPE_ORIGIN_SERVER_MAX_CONNS_STATUS = + new DynamicIntProperty(PROP_PREFIX + ".servermaxconns.status", 503); + DynamicIntProperty ERROR_TYPE_ORIGIN_RESET_CONN_STATUS = + new DynamicIntProperty(PROP_PREFIX + ".originresetconnection.status", 504); DynamicIntProperty ERROR_TYPE_OTHER_STATUS = new DynamicIntProperty(PROP_PREFIX + ".other.status", 500); - int getStatusCodeToReturn(); StatusCategory getStatusCategory(); ClientException.ErrorType getClientErrorType(); } - diff --git a/zuul-core/src/main/java/com/netflix/zuul/exception/OutboundErrorType.java b/zuul-core/src/main/java/com/netflix/zuul/exception/OutboundErrorType.java index 457fb9458b..b16297b579 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/exception/OutboundErrorType.java +++ b/zuul-core/src/main/java/com/netflix/zuul/exception/OutboundErrorType.java @@ -18,7 +18,6 @@ import com.netflix.client.ClientException; import com.netflix.zuul.stats.status.StatusCategory; -import com.netflix.zuul.stats.status.ZuulStatusCategory; import static com.netflix.client.ClientException.ErrorType.CLIENT_THROTTLED; import static com.netflix.client.ClientException.ErrorType.CONNECT_EXCEPTION; @@ -44,16 +43,21 @@ * Date: November 28, 2017 */ public enum OutboundErrorType implements ErrorType { - READ_TIMEOUT(ERROR_TYPE_READ_TIMEOUT_STATUS.get(), FAILURE_ORIGIN_READ_TIMEOUT, READ_TIMEOUT_EXCEPTION), CONNECT_ERROR(ERROR_TYPE_CONNECT_ERROR_STATUS.get(), FAILURE_ORIGIN_CONNECTIVITY, CONNECT_EXCEPTION), SERVICE_UNAVAILABLE(ERROR_TYPE_SERVICE_UNAVAILABLE_STATUS.get(), FAILURE_ORIGIN_THROTTLED, SERVER_THROTTLED), ERROR_STATUS_RESPONSE(ERROR_TYPE_ERROR_STATUS_RESPONSE_STATUS.get(), FAILURE_ORIGIN, GENERAL), NO_AVAILABLE_SERVERS(ERROR_TYPE_NOSERVERS_STATUS.get(), FAILURE_ORIGIN_NO_SERVERS, CONNECT_EXCEPTION), - ORIGIN_SERVER_MAX_CONNS(ERROR_TYPE_ORIGIN_SERVER_MAX_CONNS_STATUS.get(), FAILURE_LOCAL_THROTTLED_ORIGIN_SERVER_MAXCONN, CLIENT_THROTTLED), + ORIGIN_SERVER_MAX_CONNS( + ERROR_TYPE_ORIGIN_SERVER_MAX_CONNS_STATUS.get(), + FAILURE_LOCAL_THROTTLED_ORIGIN_SERVER_MAXCONN, + CLIENT_THROTTLED), RESET_CONNECTION(ERROR_TYPE_ORIGIN_RESET_CONN_STATUS.get(), FAILURE_ORIGIN_RESET_CONNECTION, CONNECT_EXCEPTION), CANCELLED(400, FAILURE_CLIENT_CANCELLED, SOCKET_TIMEOUT_EXCEPTION), - ORIGIN_CONCURRENCY_EXCEEDED(ERROR_TYPE_ORIGIN_CONCURRENCY_EXCEEDED_STATUS.get(), FAILURE_LOCAL_THROTTLED_ORIGIN_CONCURRENCY, SERVER_THROTTLED), + ORIGIN_CONCURRENCY_EXCEEDED( + ERROR_TYPE_ORIGIN_CONCURRENCY_EXCEEDED_STATUS.get(), + FAILURE_LOCAL_THROTTLED_ORIGIN_CONCURRENCY, + SERVER_THROTTLED), OTHER(ERROR_TYPE_OTHER_STATUS.get(), FAILURE_LOCAL, GENERAL); private static final String NAME_PREFIX = "ORIGIN_"; @@ -62,7 +66,8 @@ public enum OutboundErrorType implements ErrorType { private final StatusCategory statusCategory; private final ClientException.ErrorType clientErrorType; - OutboundErrorType(int statusCodeToReturn, StatusCategory statusCategory, ClientException.ErrorType clientErrorType) { + OutboundErrorType( + int statusCodeToReturn, StatusCategory statusCategory, ClientException.ErrorType clientErrorType) { this.statusCodeToReturn = statusCodeToReturn; this.statusCategory = statusCategory; this.clientErrorType = clientErrorType; @@ -83,7 +88,6 @@ public ClientException.ErrorType getClientErrorType() { return clientErrorType; } - @Override public String toString() { return NAME_PREFIX + name(); diff --git a/zuul-core/src/main/java/com/netflix/zuul/exception/OutboundException.java b/zuul-core/src/main/java/com/netflix/zuul/exception/OutboundException.java index 9282c9c782..a648593841 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/exception/OutboundException.java +++ b/zuul-core/src/main/java/com/netflix/zuul/exception/OutboundException.java @@ -19,7 +19,6 @@ import com.netflix.zuul.niws.RequestAttempt; import com.netflix.zuul.niws.RequestAttempts; - /** * Outbound Exception Decorator * @@ -27,13 +26,11 @@ * Date: 10/21/15 * Time: 11:46 AM */ -public class OutboundException extends ZuulException -{ +public class OutboundException extends ZuulException { private final ErrorType outboundErrorType; private final RequestAttempts requestAttempts; - public OutboundException(ErrorType outboundErrorType, RequestAttempts requestAttempts) - { + public OutboundException(ErrorType outboundErrorType, RequestAttempts requestAttempts) { super(outboundErrorType.toString(), outboundErrorType.toString(), true); this.outboundErrorType = outboundErrorType; this.requestAttempts = requestAttempts; @@ -41,8 +38,7 @@ public OutboundException(ErrorType outboundErrorType, RequestAttempts requestAtt this.dontLogAsError(); } - public OutboundException(ErrorType outboundErrorType, RequestAttempts requestAttempts, Throwable cause) - { + public OutboundException(ErrorType outboundErrorType, RequestAttempts requestAttempts, Throwable cause) { super(outboundErrorType.toString(), cause.getMessage(), true); this.outboundErrorType = outboundErrorType; this.requestAttempts = requestAttempts; @@ -50,15 +46,11 @@ public OutboundException(ErrorType outboundErrorType, RequestAttempts requestAtt this.dontLogAsError(); } - public RequestAttempt getFinalRequestAttempt() - { + public RequestAttempt getFinalRequestAttempt() { return requestAttempts == null ? null : requestAttempts.getFinalAttempt(); } - - public ErrorType getOutboundErrorType() - { + public ErrorType getOutboundErrorType() { return outboundErrorType; } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/exception/ZuulException.java b/zuul-core/src/main/java/com/netflix/zuul/exception/ZuulException.java index 9b0fbf953c..0aa7d425a4 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/exception/ZuulException.java +++ b/zuul-core/src/main/java/com/netflix/zuul/exception/ZuulException.java @@ -21,8 +21,7 @@ * Date: 10/20/11 * Time: 4:33 PM */ -public class ZuulException extends RuntimeException -{ +public class ZuulException extends RuntimeException { private String errorCause; private int statusCode = 500; private boolean shouldLogAsError = true; @@ -48,12 +47,12 @@ public ZuulException(String sMessage, String errorCause) { } public ZuulException(String sMessage, String errorCause, boolean noStackTrace) { - super(sMessage, null, noStackTrace, ! noStackTrace); + super(sMessage, null, noStackTrace, !noStackTrace); this.errorCause = errorCause; } public ZuulException(Throwable throwable, String sMessage, boolean noStackTrace) { - super(sMessage, throwable, noStackTrace, ! noStackTrace); + super(sMessage, throwable, noStackTrace, !noStackTrace); this.errorCause = "GENERAL"; } @@ -67,16 +66,15 @@ public ZuulException(String sMessage) { } public ZuulException(String sMessage, boolean noStackTrace) { - super(sMessage, null, noStackTrace, ! noStackTrace); + super(sMessage, null, noStackTrace, !noStackTrace); this.errorCause = "GENERAL"; } - public int getStatusCode() - { + public int getStatusCode() { return statusCode; } - public void setStatusCode(int statusCode) - { + + public void setStatusCode(int statusCode) { this.statusCode = statusCode; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/BaseFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/BaseFilter.java index 3c471c3207..ad15a05b3e 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/BaseFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/BaseFilter.java @@ -42,8 +42,7 @@ * Date: 10/26/11 * Time: 4:29 PM */ -public abstract class BaseFilter implements ZuulFilter -{ +public abstract class BaseFilter implements ZuulFilter { private final String baseName; private final AtomicInteger concurrentCount; private final Counter concurrencyRejections; @@ -51,7 +50,8 @@ public abstract class BaseFilter i private final CachedDynamicBooleanProperty filterDisabled; private final CachedDynamicIntProperty filterConcurrencyLimit; - private static final CachedDynamicBooleanProperty concurrencyProtectEnabled = new CachedDynamicBooleanProperty("zuul.filter.concurrency.protect.enabled", true); + private static final CachedDynamicBooleanProperty concurrencyProtectEnabled = + new CachedDynamicBooleanProperty("zuul.filter.concurrency.protect.enabled", true); protected BaseFilter() { baseName = getClass().getSimpleName() + "." + filterType(); @@ -67,8 +67,7 @@ public String filterName() { } @Override - public boolean overrideStopFilterProcessing() - { + public boolean overrideStopFilterProcessing() { return false; } @@ -96,20 +95,17 @@ public boolean isDisabled() { } @Override - public O getDefaultOutput(I input) - { - return (O)input; + public O getDefaultOutput(I input) { + return (O) input; } @Override - public FilterSyncType getSyncType() - { + public FilterSyncType getSyncType() { return FilterSyncType.ASYNC; } @Override - public String toString() - { + public String toString() { return String.valueOf(filterType()) + ":" + String.valueOf(filterName()); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/BaseSyncFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/BaseSyncFilter.java index 12b7aded11..db59890194 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/BaseSyncFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/BaseSyncFilter.java @@ -23,8 +23,8 @@ * Date: 5/8/15 * Time: 2:46 PM */ -public abstract class BaseSyncFilter extends BaseFilter implements SyncZuulFilter -{ +public abstract class BaseSyncFilter extends BaseFilter + implements SyncZuulFilter { /** * A wrapper implementation of applyAsync() that is intended just to aggregate a non-blocking apply() method * in an Observable. @@ -32,14 +32,12 @@ public abstract class BaseSyncFilter applyAsync(I input) - { + public Observable applyAsync(I input) { return Observable.just(this.apply(input)); } @Override - public FilterSyncType getSyncType() - { + public FilterSyncType getSyncType() { return FilterSyncType.SYNC; } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/Endpoint.java b/zuul-core/src/main/java/com/netflix/zuul/filters/Endpoint.java index af79e07866..2a56327eb8 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/Endpoint.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/Endpoint.java @@ -23,24 +23,20 @@ * Date: 5/16/15 * Time: 1:57 PM */ -public abstract class Endpoint extends BaseFilter -{ +public abstract class Endpoint extends BaseFilter { @Override - public int filterOrder() - { + public int filterOrder() { // Set all Endpoint filters to order of 0, because they are not processed sequentially like other filter types. return 0; } @Override - public FilterType filterType() - { + public FilterType filterType() { return FilterType.ENDPOINT; } @Override - public boolean shouldFilter(I msg) - { + public boolean shouldFilter(I msg) { // Always true, because Endpoint filters are chosen by name instead. return true; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/FilterError.java b/zuul-core/src/main/java/com/netflix/zuul/filters/FilterError.java index 48fd98fdb8..962153462e 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/FilterError.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/FilterError.java @@ -20,8 +20,7 @@ * Date: 5/7/15 * Time: 10:19 AM */ -public class FilterError implements Cloneable -{ +public class FilterError implements Cloneable { private String filterName; private String filterType; private Throwable exception = null; @@ -51,10 +50,9 @@ public Object clone() { @Override public String toString() { - return "FilterError{" + - "filterName='" + filterName + '\'' + - ", filterType='" + filterType + '\'' + - ", exception=" + exception + - '}'; + return "FilterError{" + "filterName='" + + filterName + '\'' + ", filterType='" + + filterType + '\'' + ", exception=" + + exception + '}'; } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/FilterRegistry.java b/zuul-core/src/main/java/com/netflix/zuul/filters/FilterRegistry.java index 42e706670b..dcec5a1b76 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/FilterRegistry.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/FilterRegistry.java @@ -15,8 +15,8 @@ */ package com.netflix.zuul.filters; -import java.util.Collection; import javax.annotation.Nullable; +import java.util.Collection; public interface FilterRegistry { @Nullable diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/FilterSyncType.java b/zuul-core/src/main/java/com/netflix/zuul/filters/FilterSyncType.java index 535fc129af..4a3f2ffb15 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/FilterSyncType.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/FilterSyncType.java @@ -21,7 +21,7 @@ * Date: 11/13/15 * Time: 9:13 PM */ -public enum FilterSyncType -{ - SYNC, ASYNC +public enum FilterSyncType { + SYNC, + ASYNC } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/FilterType.java b/zuul-core/src/main/java/com/netflix/zuul/filters/FilterType.java index b3e0e7ca36..98a3ba82a6 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/FilterType.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/FilterType.java @@ -21,9 +21,10 @@ * Date: 11/13/15 * Time: 7:50 PM */ -public enum FilterType -{ - INBOUND("in"), ENDPOINT("end"), OUTBOUND("out"); +public enum FilterType { + INBOUND("in"), + ENDPOINT("end"), + OUTBOUND("out"); private final String shortName; @@ -32,23 +33,21 @@ private FilterType(String shortName) { } @Override - public String toString() - { + public String toString() { return shortName; } - public static FilterType parse(String str) - { + public static FilterType parse(String str) { str = str.toLowerCase(); switch (str) { - case "in": - return INBOUND; - case "out": - return OUTBOUND; - case "end": - return ENDPOINT; - default: - throw new IllegalArgumentException("Unknown filter type! type=" + String.valueOf(str)); + case "in": + return INBOUND; + case "out": + return OUTBOUND; + case "end": + return ENDPOINT; + default: + throw new IllegalArgumentException("Unknown filter type! type=" + String.valueOf(str)); } } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/MutableFilterRegistry.java b/zuul-core/src/main/java/com/netflix/zuul/filters/MutableFilterRegistry.java index 122745a6cf..4106b71cbe 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/MutableFilterRegistry.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/MutableFilterRegistry.java @@ -15,14 +15,14 @@ */ package com.netflix.zuul.filters; -import static java.util.Objects.requireNonNull; - +import javax.annotation.Nullable; +import javax.inject.Singleton; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; -import javax.annotation.Nullable; -import javax.inject.Singleton; + +import static java.util.Objects.requireNonNull; @Singleton public final class MutableFilterRegistry implements FilterRegistry { diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/ShouldFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/ShouldFilter.java index 9b12595017..7e4d72c585 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/ShouldFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/ShouldFilter.java @@ -22,8 +22,7 @@ * Date: 5/7/15 * Time: 3:31 PM */ -public interface ShouldFilter -{ +public interface ShouldFilter { /** * a "true" return from this method means that the apply() method should be invoked * diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/SyncZuulFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/SyncZuulFilter.java index 4c8995d5e7..2f556c8232 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/SyncZuulFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/SyncZuulFilter.java @@ -23,7 +23,6 @@ * Date: 11/16/15 * Time: 2:07 PM */ -public interface SyncZuulFilter extends ZuulFilter -{ +public interface SyncZuulFilter extends ZuulFilter { O apply(I input); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/SyncZuulFilterAdapter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/SyncZuulFilterAdapter.java index 16fe94934d..b576b8104f 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/SyncZuulFilterAdapter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/SyncZuulFilterAdapter.java @@ -38,7 +38,8 @@ * TL;DR use this as a base class for your ZuulFilter if you intend to create new instances of ZuulFilter * Created by saroskar on 6/8/17. */ -public abstract class SyncZuulFilterAdapter implements SyncZuulFilter { +public abstract class SyncZuulFilterAdapter + implements SyncZuulFilter { @Override public boolean isDisabled() { @@ -88,11 +89,11 @@ public HttpContent processContentChunk(ZuulMessage zuulMessage, HttpContent chun @Override public void incrementConcurrency() { - //NOOP for sync filters + // NOOP for sync filters } @Override public void decrementConcurrency() { - //NOOP for sync filters + // NOOP for sync filters } } \ No newline at end of file diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/ZuulFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/ZuulFilter.java index b55d702c47..b043ddcd62 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/ZuulFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/ZuulFilter.java @@ -29,8 +29,7 @@ * Date: 10/27/11 * Time: 3:03 PM */ -public interface ZuulFilter extends ShouldFilter -{ +public interface ZuulFilter extends ShouldFilter { boolean isDisabled(); String filterName(); @@ -128,4 +127,5 @@ default FilterSyncType getSyncType() { /** * Optionally transform HTTP content chunk received. */ - HttpContent processContentChunk(ZuulMessage zuulMessage, HttpContent chunk);} + HttpContent processContentChunk(ZuulMessage zuulMessage, HttpContent chunk); +} diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/common/GZipResponseFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/common/GZipResponseFilter.java index 7ce3f89464..290b9e20b6 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/common/GZipResponseFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/common/GZipResponseFilter.java @@ -45,13 +45,13 @@ * @author Mike Smith */ @Filter(order = 110, type = FilterType.OUTBOUND) -public class GZipResponseFilter extends HttpOutboundSyncFilter -{ - private static DynamicStringSetProperty GZIPPABLE_CONTENT_TYPES = new DynamicStringSetProperty("zuul.gzip.contenttypes", - "text/html,application/x-javascript,text/css,application/javascript,text/javascript,text/plain,text/xml," + - "application/json,application/vnd.ms-fontobject,application/x-font-opentype,application/x-font-truetype," + - "application/x-font-ttf,application/xml,font/eot,font/opentype,font/otf,image/svg+xml,image/vnd.microsoft.icon," + - "text/event-stream", +public class GZipResponseFilter extends HttpOutboundSyncFilter { + private static DynamicStringSetProperty GZIPPABLE_CONTENT_TYPES = new DynamicStringSetProperty( + "zuul.gzip.contenttypes", + "text/html,application/x-javascript,text/css,application/javascript,text/javascript,text/plain,text/xml," + + "application/json,application/vnd.ms-fontobject,application/x-font-opentype,application/x-font-truetype," + + "application/x-font-ttf,application/xml,font/eot,font/opentype,font/otf,image/svg+xml,image/vnd.microsoft.icon," + + "text/event-stream", ","); // https://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits @@ -73,16 +73,21 @@ public boolean shouldFilter(HttpResponseMessage response) { // A flag on SessionContext can be set to override normal mechanism of checking if client accepts gzip.; final HttpRequestInfo request = response.getInboundRequest(); - final Boolean overrideIsGzipRequested = (Boolean) response.getContext().get(CommonContextKeys.OVERRIDE_GZIP_REQUESTED); - final boolean isGzipRequested = (overrideIsGzipRequested == null) ? - HttpUtils.acceptsGzip(request.getHeaders()) : overrideIsGzipRequested; + final Boolean overrideIsGzipRequested = + (Boolean) response.getContext().get(CommonContextKeys.OVERRIDE_GZIP_REQUESTED); + final boolean isGzipRequested = (overrideIsGzipRequested == null) + ? HttpUtils.acceptsGzip(request.getHeaders()) + : overrideIsGzipRequested; // Check the headers to see if response is already gzipped. final Headers respHeaders = response.getHeaders(); boolean isResponseCompressed = HttpUtils.isCompressed(respHeaders); // Decide what to do.; - final boolean shouldGzip = isGzippableContentType(response) && isGzipRequested && !isResponseCompressed && isRightSizeForGzip(response); + final boolean shouldGzip = isGzippableContentType(response) + && isGzipRequested + && !isResponseCompressed + && isRightSizeForGzip(response); if (shouldGzip) { response.getContext().set(CommonContextKeys.GZIPPER, getGzipper()); } @@ -96,7 +101,7 @@ protected Gzipper getGzipper() { @VisibleForTesting boolean isRightSizeForGzip(HttpResponseMessage response) { final Integer bodySize = HttpUtils.getBodySizeIfKnown(response); - //bodySize == null is chunked encoding which is eligible for gzip compression + // bodySize == null is chunked encoding which is eligible for gzip compression return (bodySize == null) || (bodySize >= MIN_BODY_SIZE_FOR_GZIP.get()); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/common/SurgicalDebugFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/common/SurgicalDebugFilter.java index b6112ddf0e..31eeb8d0e7 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/common/SurgicalDebugFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/common/SurgicalDebugFilter.java @@ -56,7 +56,8 @@ public int filterOrder() { @Override public boolean shouldFilter(HttpRequestMessage request) { - DynamicBooleanProperty debugFilterShutoff = new DynamicBooleanProperty(ZuulConstants.ZUUL_DEBUGFILTERS_DISABLED, false); + DynamicBooleanProperty debugFilterShutoff = + new DynamicBooleanProperty(ZuulConstants.ZUUL_DEBUGFILTERS_DISABLED, false); if (debugFilterShutoff.get()) { return false; @@ -73,7 +74,6 @@ public boolean shouldFilter(HttpRequestMessage request) { return notAlreadyFiltered && patternMatches(request); } - @Override public HttpRequestMessage apply(HttpRequestMessage request) { DynamicStringProperty routeVip = new DynamicStringProperty(ZuulConstants.ZUUL_DEBUG_VIP, null); @@ -93,7 +93,6 @@ public HttpRequestMessage apply(HttpRequestMessage request) { ctx.setDebugRequest(true); ctx.set("zuulToZuul", true); - } return request; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/MissingEndpointHandlingFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/MissingEndpointHandlingFilter.java index d190fccc5e..72bb88cfa4 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/MissingEndpointHandlingFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/MissingEndpointHandlingFilter.java @@ -31,7 +31,8 @@ * Created by saroskar on 2/13/17. */ @Filter(order = 0, type = FilterType.ENDPOINT) -public final class MissingEndpointHandlingFilter extends SyncZuulFilterAdapter { +public final class MissingEndpointHandlingFilter + extends SyncZuulFilterAdapter { private final String name; private static final Logger LOG = LoggerFactory.getLogger(MissingEndpointHandlingFilter.class); diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/ProxyEndpoint.java b/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/ProxyEndpoint.java index 03bf8f2e31..ed701133e9 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/ProxyEndpoint.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/ProxyEndpoint.java @@ -16,18 +16,6 @@ package com.netflix.zuul.filters.endpoint; -import static com.netflix.zuul.context.CommonContextKeys.ORIGIN_CHANNEL; -import static com.netflix.zuul.netty.connectionpool.DefaultOriginChannelInitializer.CONNECTION_POOL_HANDLER; -import static com.netflix.zuul.netty.server.ClientRequestReceiver.ATTR_ZUUL_RESP; -import static com.netflix.zuul.passport.PassportState.ORIGIN_CONN_ACQUIRE_END; -import static com.netflix.zuul.passport.PassportState.ORIGIN_CONN_ACQUIRE_FAILED; -import static com.netflix.zuul.passport.PassportState.ORIGIN_RETRY_START; -import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_ORIGIN; -import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_ORIGIN_THROTTLED; -import static com.netflix.zuul.stats.status.ZuulStatusCategory.SUCCESS; -import static com.netflix.zuul.stats.status.ZuulStatusCategory.SUCCESS_LOCAL_NO_ROUTE; -import static com.netflix.zuul.stats.status.ZuulStatusCategory.SUCCESS_NOT_FOUND; - import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; @@ -99,6 +87,10 @@ import io.netty.util.concurrent.Promise; import io.perfmark.PerfMark; import io.perfmark.TaskCloseable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.URLDecoder; @@ -110,9 +102,18 @@ import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.atomic.AtomicReference; -import javax.annotation.Nullable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import static com.netflix.zuul.context.CommonContextKeys.ORIGIN_CHANNEL; +import static com.netflix.zuul.netty.connectionpool.DefaultOriginChannelInitializer.CONNECTION_POOL_HANDLER; +import static com.netflix.zuul.netty.server.ClientRequestReceiver.ATTR_ZUUL_RESP; +import static com.netflix.zuul.passport.PassportState.ORIGIN_CONN_ACQUIRE_END; +import static com.netflix.zuul.passport.PassportState.ORIGIN_CONN_ACQUIRE_FAILED; +import static com.netflix.zuul.passport.PassportState.ORIGIN_RETRY_START; +import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_ORIGIN; +import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_ORIGIN_THROTTLED; +import static com.netflix.zuul.stats.status.ZuulStatusCategory.SUCCESS; +import static com.netflix.zuul.stats.status.ZuulStatusCategory.SUCCESS_LOCAL_NO_ROUTE; +import static com.netflix.zuul.stats.status.ZuulStatusCategory.SUCCESS_NOT_FOUND; /** * Not thread safe! New instance of this class is created per HTTP/1.1 request proxied to the origin but NOT for each @@ -120,7 +121,8 @@ * Created by saroskar on 5/31/17. */ @Filter(order = 0, type = FilterType.ENDPOINT) -public class ProxyEndpoint extends SyncZuulFilterAdapter implements GenericFutureListener> { +public class ProxyEndpoint extends SyncZuulFilterAdapter + implements GenericFutureListener> { private static final String ZUUL_ORIGIN_ATTEMPT_IPADDR_MAP_KEY = "_zuul_origin_attempt_ipaddr_map"; private static final String ZUUL_ORIGIN_REQUEST_URI = "_zuul_origin_request_uri"; @@ -133,8 +135,10 @@ public class ProxyEndpoint extends SyncZuulFilterAdapter IDEMPOTENT_HTTP_METHODS = Sets.newHashSet("GET", "HEAD", "OPTIONS"); - private static final DynamicIntegerSetProperty RETRIABLE_STATUSES_FOR_IDEMPOTENT_METHODS = new DynamicIntegerSetProperty("zuul.retry.allowed.statuses.idempotent", "500"); + private static final DynamicIntegerSetProperty RETRIABLE_STATUSES_FOR_IDEMPOTENT_METHODS = + new DynamicIntegerSetProperty("zuul.retry.allowed.statuses.idempotent", "500"); /** * Indicates how long Zuul should remember throttle events for an origin. As of this writing, throttling is used * to decide to cache request bodies. */ - private static final CachedDynamicLongProperty THROTTLE_MEMORY_SECONDS = - new CachedDynamicLongProperty("zuul.proxy.throttle_memory_seconds", Duration.ofMinutes(5).getSeconds()); - - - private static final Set REQUEST_HEADERS_TO_REMOVE = Sets.newHashSet(HttpHeaderNames.CONNECTION, HttpHeaderNames.KEEP_ALIVE); - private static final Set RESPONSE_HEADERS_TO_REMOVE = Sets.newHashSet(HttpHeaderNames.CONNECTION, HttpHeaderNames.KEEP_ALIVE); - public static final String POOLED_ORIGIN_CONNECTION_KEY = "_origin_pooled_conn"; + private static final CachedDynamicLongProperty THROTTLE_MEMORY_SECONDS = new CachedDynamicLongProperty( + "zuul.proxy.throttle_memory_seconds", Duration.ofMinutes(5).getSeconds()); + + private static final Set REQUEST_HEADERS_TO_REMOVE = + Sets.newHashSet(HttpHeaderNames.CONNECTION, HttpHeaderNames.KEEP_ALIVE); + private static final Set RESPONSE_HEADERS_TO_REMOVE = + Sets.newHashSet(HttpHeaderNames.CONNECTION, HttpHeaderNames.KEEP_ALIVE); + public static final String POOLED_ORIGIN_CONNECTION_KEY = "_origin_pooled_conn"; private static final Logger logger = LoggerFactory.getLogger(ProxyEndpoint.class); - private static final Counter NO_RETRY_INCOMPLETE_BODY = SpectatorUtils.newCounter("zuul.no.retry","incomplete_body"); - private static final Counter NO_RETRY_RESP_STARTED = SpectatorUtils.newCounter("zuul.no.retry","resp_started"); - - public ProxyEndpoint(final HttpRequestMessage inMesg, final ChannelHandlerContext ctx, - final FilterRunner filters, MethodBinding methodBinding) { + private static final Counter NO_RETRY_INCOMPLETE_BODY = + SpectatorUtils.newCounter("zuul.no.retry", "incomplete_body"); + private static final Counter NO_RETRY_RESP_STARTED = SpectatorUtils.newCounter("zuul.no.retry", "resp_started"); + + public ProxyEndpoint( + final HttpRequestMessage inMesg, + final ChannelHandlerContext ctx, + final FilterRunner filters, + MethodBinding methodBinding) { this(inMesg, ctx, filters, methodBinding, new NettyRequestAttemptFactory()); } - public ProxyEndpoint(final HttpRequestMessage inMesg, final ChannelHandlerContext ctx, - final FilterRunner filters, MethodBinding methodBinding, - NettyRequestAttemptFactory requestAttemptFactory) { + public ProxyEndpoint( + final HttpRequestMessage inMesg, + final ChannelHandlerContext ctx, + final FilterRunner filters, + MethodBinding methodBinding, + NettyRequestAttemptFactory requestAttemptFactory) { channelCtx = ctx; responseFilters = filters; zuulRequest = transformRequest(inMesg); @@ -220,7 +233,7 @@ public HttpRequestMessage getZuulRequest() { return zuulRequest; } - //Unlink OriginResponseReceiver from origin channel pipeline so that we no longer receive events + // Unlink OriginResponseReceiver from origin channel pipeline so that we no longer receive events private Channel unlinkFromOrigin() { if (originResponseReceiver != null) { originResponseReceiver.unlinkFromClientRequest(); @@ -261,7 +274,7 @@ public void finish(boolean error) { } // Publish each of the request stats (ie. one for each attempt). - if (! requestStats.isEmpty()) { + if (!requestStats.isEmpty()) { int indexFinal = requestStats.size() - 1; for (int i = 0; i < requestStats.size(); i++) { RequestStat stat = requestStats.get(i); @@ -298,7 +311,7 @@ public HttpResponseMessage apply(final HttpRequestMessage input) { origin.onRequestExecutionStart(zuulRequest); proxyRequestToOrigin(); - //Doesn't return origin response to caller, calls invokeNext() internally in response filter chain + // Doesn't return origin response to caller, calls invokeNext() internally in response filter chain return null; } catch (Exception ex) { handleError(ex); @@ -309,14 +322,14 @@ public HttpResponseMessage apply(final HttpRequestMessage input) { @Override public HttpContent processContentChunk(final ZuulMessage zuulReq, final HttpContent chunk) { if (originConn != null) { - //Connected to origin, stream request body without buffering + // Connected to origin, stream request body without buffering proxiedRequestWithoutBuffering = true; ByteBufUtil.touch(chunk, "ProxyEndpoint writing chunk to origin, request: ", zuulReq); originConn.getChannel().writeAndFlush(chunk); return null; } - //Not connected to origin yet, let caller buffer the request body + // Not connected to origin yet, let caller buffer the request body ByteBufUtil.touch(chunk, "ProxyEndpoint buffering chunk to origin, request: ", zuulReq); return chunk; } @@ -358,8 +371,10 @@ public void invokeNext(final HttpContent chunk) { private void filterResponseChunk(final HttpContent chunk) { if (context.isCancelled() || !channelCtx.channel().isActive()) { - SpectatorUtils.newCounter("zuul.origin.strayChunk", - origin == null ? "none" : origin.getName().getMetricId()).increment(); + SpectatorUtils.newCounter( + "zuul.origin.strayChunk", + origin == null ? "none" : origin.getName().getMetricId()) + .increment(); unlinkFromOrigin(); ReferenceCountUtil.safeRelease(chunk); return; @@ -383,12 +398,11 @@ private void storeAndLogOriginRequestInfo() { // supposed to be the mapping of IP addresses of the server. This is (AFAICT) only used for logging. It is // an IP address semantically, but a String here. The two should be swapped. // ZUUL_ORIGIN_CHOSEN_HOST_ADDR_MAP_KEY is almost always an IP address, but may some times be a hostname in - // case the discovery info is not an IP. + // case the discovery info is not an IP. Map attemptToIpAddressMap = (Map) eventProps.get(ZUUL_ORIGIN_ATTEMPT_IPADDR_MAP_KEY); - Map attemptToChosenHostMap = - (Map) eventProps.get( - CommonContextKeys.ZUUL_ORIGIN_CHOSEN_HOST_ADDR_MAP_KEY.name()); + Map attemptToChosenHostMap = (Map) + eventProps.get(CommonContextKeys.ZUUL_ORIGIN_CHOSEN_HOST_ADDR_MAP_KEY.name()); if (attemptToIpAddressMap == null) { attemptToIpAddressMap = new HashMap<>(); } @@ -456,7 +470,7 @@ private void proxyRequestToOrigin() { logger.error("Error while connecting to origin, UUID {}", context.getUUID(), ex); } storeAndLogOriginRequestInfo(); - if (promise != null && ! promise.isDone()) { + if (promise != null && !promise.isDone()) { promise.setFailure(ex); } else { errorFromOrigin(ex); @@ -483,7 +497,7 @@ public void operationComplete(final Future connectResult) { /** TODO(argha-c): This reliance on mutable update of the `chosenServer` must be improved. * @see DiscoveryResult.EMPTY indicates that the loadbalancer found no available servers. - */ + */ if (server != DiscoveryResult.EMPTY) { if (currentRequestStat != null) { currentRequestStat.server(server); @@ -500,8 +514,10 @@ public void operationComplete(final Future connectResult) { } }); } catch (Throwable ex) { - logger.error("Uncaught error in operationComplete(). Closing the server channel now. {}" - , ChannelUtils.channelInfoForLogging(channelCtx.channel()), ex); + logger.error( + "Uncaught error in operationComplete(). Closing the server channel now. {}", + ChannelUtils.channelInfoForLogging(channelCtx.channel()), + ex); unlinkFromOrigin(); @@ -519,8 +535,7 @@ private void onOriginConnectSucceeded(PooledConnection conn, Duration readTimeou // conn isn't actually busy so we can put it in the pool conn.setConnectionState(PooledConnection.ConnectionState.WRITE_READY); conn.release(); - } - else { + } else { // Update the RequestAttempt to reflect the readTimeout chosen. currentRequestAttempt.setReadTimeout(readTimeout.toMillis()); @@ -531,7 +546,7 @@ private void onOriginConnectSucceeded(PooledConnection conn, Duration readTimeou private void onOriginConnectFailed(Throwable cause) { passport.add(ORIGIN_CONN_ACQUIRE_FAILED); - if (! context.isCancelled()) { + if (!context.isCancelled()) { errorFromOrigin(cause); } } @@ -550,13 +565,14 @@ private void writeClientRequestToOrigin(final PooledConnection conn, Duration re final ChannelPipeline pipeline = ch.pipeline(); originResponseReceiver = getOriginResponseReceiver(); - pipeline.addBefore(CONNECTION_POOL_HANDLER, OriginResponseReceiver.CHANNEL_HANDLER_NAME, originResponseReceiver); + pipeline.addBefore( + CONNECTION_POOL_HANDLER, OriginResponseReceiver.CHANNEL_HANDLER_NAME, originResponseReceiver); ch.write(zuulRequest); writeBufferedBodyContent(zuulRequest, ch); ch.flush(); - //Get ready to read origin's response + // Get ready to read origin's response ch.read(); originConn = conn; @@ -584,8 +600,7 @@ protected boolean isRemoteZuulRetriesBelowRetryLimit(int maxAllowedRetries) { protected boolean isBelowRetryLimit() { int maxAllowedRetries = origin.getMaxRetriesForRequest(context); - return (attemptNum <= maxAllowedRetries) && - isRemoteZuulRetriesBelowRetryLimit(maxAllowedRetries); + return (attemptNum <= maxAllowedRetries) && isRemoteZuulRetriesBelowRetryLimit(maxAllowedRetries); } public void errorFromOrigin(final Throwable ex) { @@ -593,7 +608,8 @@ public void errorFromOrigin(final Throwable ex) { // Flag that there was an origin server related error for the loadbalancer to choose // whether to circuit-trip this server. if (originConn != null) { - // NOTE: if originConn is null, then these stats will have been incremented within PerServerConnectionPool + // NOTE: if originConn is null, then these stats will have been incremented within + // PerServerConnectionPool // so don't need to be here. originConn.getServer().incrementSuccessiveConnectionFailureCount(); originConn.getServer().addToFailureCount(); @@ -601,7 +617,7 @@ public void errorFromOrigin(final Throwable ex) { originConn.flagShouldClose(); } - //detach from current origin + // detach from current origin final Channel originCh = unlinkFromOrigin(); methodBinding.bind(() -> processErrorFromOrigin(ex, originCh)); @@ -615,18 +631,29 @@ private void processErrorFromOrigin(final Throwable ex, final Channel origCh) { final SessionContext zuulCtx = context; final ErrorType err = requestAttemptFactory.mapNettyToOutboundErrorType(ex); - // Be cautious about how much we log about errors from origins, as it can have perf implications at high rps. + // Be cautious about how much we log about errors from origins, as it can have perf implications at high + // rps. if (zuulCtx.isInBrownoutMode()) { // Don't include the stacktrace or the channel info. - logger.warn("{}, origin = {}: {}", err.getStatusCategory().name(), origin.getName(), String.valueOf(ex)); + logger.warn( + "{}, origin = {}: {}", err.getStatusCategory().name(), origin.getName(), String.valueOf(ex)); } else { final String origChInfo = (origCh != null) ? ChannelUtils.channelInfoForLogging(origCh) : ""; if (logger.isInfoEnabled()) { // Include the stacktrace. - logger.warn("{}, origin = {}, origin channel info = {}", err.getStatusCategory().name(), origin.getName(), origChInfo, ex); - } - else { - logger.warn("{}, origin = {}, {}, origin channel info = {}", err.getStatusCategory().name(), origin.getName(), String.valueOf(ex), origChInfo); + logger.warn( + "{}, origin = {}, origin channel info = {}", + err.getStatusCategory().name(), + origin.getName(), + origChInfo, + ex); + } else { + logger.warn( + "{}, origin = {}, {}, origin channel info = {}", + err.getStatusCategory().name(), + origin.getName(), + String.valueOf(ex), + origChInfo); } } @@ -642,13 +669,14 @@ private void processErrorFromOrigin(final Throwable ex, final Channel origCh) { postErrorProcessing(ex, zuulCtx, err, chosenServer.get(), attemptNum); - final ClientException niwsEx = new ClientException(ClientException.ErrorType.valueOf(err.getClientErrorType().name())); + final ClientException niwsEx = new ClientException( + ClientException.ErrorType.valueOf(err.getClientErrorType().name())); if (chosenServer.get() != DiscoveryResult.EMPTY) { origin.onRequestExceptionWithServer(zuulRequest, chosenServer.get(), attemptNum, niwsEx); } if ((isBelowRetryLimit()) && (isRetryable(err))) { - //retry request with different origin + // retry request with different origin passport.add(ORIGIN_RETRY_START); origin.adjustRetryPolicyIfNeeded(zuulRequest); proxyRequestToOrigin(); @@ -662,27 +690,33 @@ private void processErrorFromOrigin(final Throwable ex, final Channel origCh) { origin.recordFinalError(zuulRequest, ex); origin.onRequestExecutionFailed(zuulRequest, chosenServer.get(), attemptNum - 1, niwsEx); - //Send error response to client + // Send error response to client handleError(ex); } } catch (Exception e) { - //Use original origin returned exception + // Use original origin returned exception handleError(ex); } } - protected void postErrorProcessing(Throwable ex, SessionContext zuulCtx, ErrorType err, DiscoveryResult chosenServer, int attemptNum) { + protected void postErrorProcessing( + Throwable ex, SessionContext zuulCtx, ErrorType err, DiscoveryResult chosenServer, int attemptNum) { // override for custom processing } private void handleError(final Throwable cause) { - final ZuulException ze = (cause instanceof ZuulException) ? - (ZuulException) cause : requestAttemptFactory.mapNettyToOutboundException(cause, context); + final ZuulException ze = (cause instanceof ZuulException) + ? (ZuulException) cause + : requestAttemptFactory.mapNettyToOutboundException(cause, context); logger.debug("Proxy endpoint failed.", cause); - if (! startedSendingResponseToClient) { + if (!startedSendingResponseToClient) { startedSendingResponseToClient = true; zuulResponse = new HttpResponseMessageImpl(context, zuulRequest, ze.getStatusCode()); - zuulResponse.getHeaders().add("Connection", "close"); // TODO - why close the connection? maybe don't always want this to happen ... + zuulResponse + .getHeaders() + .add( + "Connection", + "close"); // TODO - why close the connection? maybe don't always want this to happen ... zuulResponse.finishBufferedBodyIfIncomplete(); invokeNext(zuulResponse); } else { @@ -699,10 +733,12 @@ private void handleNoOriginSelected() { } protected boolean isRetryable(final ErrorType err) { - if ((err == OutboundErrorType.RESET_CONNECTION) || - (err == OutboundErrorType.CONNECT_ERROR) || - (err == OutboundErrorType.READ_TIMEOUT && IDEMPOTENT_HTTP_METHODS.contains(zuulRequest.getMethod().toUpperCase()))){ - return isRequestReplayable() ; + if ((err == OutboundErrorType.RESET_CONNECTION) + || (err == OutboundErrorType.CONNECT_ERROR) + || (err == OutboundErrorType.READ_TIMEOUT + && IDEMPOTENT_HTTP_METHODS.contains( + zuulRequest.getMethod().toUpperCase()))) { + return isRequestReplayable(); } return false; } @@ -767,7 +803,8 @@ protected void handleOriginSuccessResponse(final HttpResponse originResponse, Di invokeNext(zuulResponse); } - private HttpResponseMessage buildZuulHttpResponse(final HttpResponse httpResponse, final StatusCategory statusCategory, final Throwable ex) { + private HttpResponseMessage buildZuulHttpResponse( + final HttpResponse httpResponse, final StatusCategory statusCategory, final Throwable ex) { startedSendingResponseToClient = true; // Translate the netty HttpResponse into a zuul HttpResponseMessage. @@ -784,7 +821,8 @@ private HttpResponseMessage buildZuulHttpResponse(final HttpResponse httpRespons // received any of the content). // NOTE that we also later may override this if it is Chunked encoding, but we receive // a LastHttpContent without any prior HttpContent's. - if (HttpUtils.hasChunkedTransferEncodingHeader(zuulResponse) || HttpUtils.hasNonZeroContentLengthHeader(zuulResponse)) { + if (HttpUtils.hasChunkedTransferEncodingHeader(zuulResponse) + || HttpUtils.hasNonZeroContentLengthHeader(zuulResponse)) { zuulResponse.setHasBody(true); } @@ -793,8 +831,8 @@ private HttpResponseMessage buildZuulHttpResponse(final HttpResponse httpRespons channelCtx.channel().attr(ATTR_ZUUL_RESP).set(zuulResponse); if (httpResponse instanceof DefaultFullHttpResponse) { - ByteBufUtil.touch(httpResponse, "ProxyEndpoint converting Netty response to Zuul response, request: ", - zuulRequest); + ByteBufUtil.touch( + httpResponse, "ProxyEndpoint converting Netty response to Zuul response, request: ", zuulRequest); final ByteBuf chunk = ((DefaultFullHttpResponse) httpResponse).content(); zuulResponse.bufferBodyContents(new DefaultLastHttpContent(chunk)); } @@ -803,10 +841,12 @@ private HttpResponseMessage buildZuulHttpResponse(final HttpResponse httpRespons // Request was a success even if server may have responded with an error code 5XX, except for 503. if (originConn != null) { if (statusCategory == ZuulStatusCategory.FAILURE_ORIGIN_THROTTLED) { - origin.onRequestExecutionFailed(zuulRequest, originConn.getServer(), attemptNum, + origin.onRequestExecutionFailed( + zuulRequest, + originConn.getServer(), + attemptNum, new ClientException(ClientException.ErrorType.SERVER_THROTTLED)); - } - else { + } else { origin.onRequestExecutionSuccess(zuulRequest, zuulResponse, originConn.getServer(), attemptNum); } } @@ -861,14 +901,18 @@ protected void handleOriginNonSuccessResponse(final HttpResponse originResponse, } // Flag this error with the ExecutionListener. - origin.onRequestExceptionWithServer(zuulRequest, chosenServer, attemptNum, - new ClientException(niwsErrorType)); + origin.onRequestExceptionWithServer(zuulRequest, chosenServer, attemptNum, new ClientException(niwsErrorType)); if ((isBelowRetryLimit()) && (isRetryable5xxResponse(zuulRequest, originResponse))) { - logger.debug("Retrying: status={}, attemptNum={}, maxRetries={}, startedSendingResponseToClient={}, hasCompleteBody={}, method={}", - respStatus, attemptNum, origin.getMaxRetriesForRequest(context), - startedSendingResponseToClient, zuulRequest.hasCompleteBody(), zuulRequest.getMethod()); - //detach from current origin. + logger.debug( + "Retrying: status={}, attemptNum={}, maxRetries={}, startedSendingResponseToClient={}, hasCompleteBody={}, method={}", + respStatus, + attemptNum, + origin.getMaxRetriesForRequest(context), + startedSendingResponseToClient, + zuulRequest.hasCompleteBody(), + zuulRequest.getMethod()); + // detach from current origin. ByteBufUtil.touch(originResponse, "ProxyEndpoint handling non-success retry, request: ", zuulRequest); unlinkFromOrigin(); releasePartialResponse(originResponse); @@ -877,30 +921,37 @@ protected void handleOriginNonSuccessResponse(final HttpResponse originResponse, // otherwise when the body is read by netty (in writeBufferedBodyContent) the body will appear empty zuulRequest.resetBodyReader(); - //retry request with different origin + // retry request with different origin passport.add(ORIGIN_RETRY_START); origin.adjustRetryPolicyIfNeeded(zuulRequest); proxyRequestToOrigin(); } else { SessionContext zuulCtx = context; - logger.info("Sending error to client: status={}, attemptNum={}, maxRetries={}, startedSendingResponseToClient={}, hasCompleteBody={}, method={}", - respStatus, attemptNum, origin.getMaxRetriesForRequest(zuulCtx), - startedSendingResponseToClient, zuulRequest.hasCompleteBody(), zuulRequest.getMethod()); - //This is a final response after all retries that will go to the client + logger.info( + "Sending error to client: status={}, attemptNum={}, maxRetries={}, startedSendingResponseToClient={}, hasCompleteBody={}, method={}", + respStatus, + attemptNum, + origin.getMaxRetriesForRequest(zuulCtx), + startedSendingResponseToClient, + zuulRequest.hasCompleteBody(), + zuulRequest.getMethod()); + // This is a final response after all retries that will go to the client ByteBufUtil.touch(originResponse, "ProxyEndpoint handling non-success response, request: ", zuulRequest); zuulResponse = buildZuulHttpResponse(originResponse, statusCategory, obe); invokeNext(zuulResponse); } } - public boolean isRetryable5xxResponse(final HttpRequestMessage zuulRequest, HttpResponse originResponse) { // int retryNum, int maxRetries) { + public boolean isRetryable5xxResponse( + final HttpRequestMessage zuulRequest, HttpResponse originResponse) { // int retryNum, int maxRetries) { if (isRequestReplayable()) { int status = originResponse.status().code(); if (status == 503 || originIndicatesRetryableInternalServerError(originResponse)) { return true; } // Retry if this is an idempotent http method AND status code was retriable for idempotent methods. - else if (RETRIABLE_STATUSES_FOR_IDEMPOTENT_METHODS.get().contains(status) && IDEMPOTENT_HTTP_METHODS.contains(zuulRequest.getMethod().toUpperCase())) { + else if (RETRIABLE_STATUSES_FOR_IDEMPOTENT_METHODS.get().contains(status) + && IDEMPOTENT_HTTP_METHODS.contains(zuulRequest.getMethod().toUpperCase())) { return true; } } @@ -912,7 +963,6 @@ protected boolean originIndicatesRetryableInternalServerError(final HttpResponse return false; } - /* static utility methods */ protected HttpRequestMessage transformRequest(HttpRequestMessage requestMsg) { @@ -945,7 +995,7 @@ private static HttpRequestMessage massageRequestURI(HttpRequestMessage request) // If another filter has specified an overrideURI, then use that instead of requested URI. final Object override = context.get("overrideURI"); - if(override != null ) { + if (override != null) { uri = override.toString(); } @@ -994,11 +1044,12 @@ private static HttpRequestMessage massageRequestURI(HttpRequestMessage request) @Nullable protected NettyOrigin getOrigin(HttpRequestMessage request) { SessionContext context = request.getContext(); - OriginManager originManager = (OriginManager) context.get(CommonContextKeys.ORIGIN_MANAGER); + OriginManager originManager = + (OriginManager) context.get(CommonContextKeys.ORIGIN_MANAGER); if (Debug.debugRequest(context)) { ImmutableList.Builder routingLogEntries = context.get(CommonContextKeys.ROUTING_LOG); - if(routingLogEntries != null) { + if (routingLogEntries != null) { for (String entry : routingLogEntries.build()) { Debug.addRequestDebug(context, "RoutingLog: " + entry); } @@ -1011,7 +1062,8 @@ protected NettyOrigin getOrigin(HttpRequestMessage request) { return null; } - // make sure the restClientName will never be a raw VIP in cases where it's the fallback for another route assignment + // make sure the restClientName will never be a raw VIP in cases where it's the fallback for another route + // assignment String restClientVIP = primaryRoute; boolean useFullName = context.getBoolean(CommonContextKeys.USE_FULL_VIP_NAME); String restClientName = useFullName ? restClientVIP : VipUtils.getVIPPrefix(restClientVIP); @@ -1032,8 +1084,12 @@ protected NettyOrigin getOrigin(HttpRequestMessage request) { // Update the routeVip on context to show the actual raw VIP from the clientConfig of the chosen Origin. if (origin != null) { - context.set(CommonContextKeys.ACTUAL_VIP, origin.getClientConfig().get(IClientConfigKey.Keys.DeploymentContextBasedVipAddresses)); - context.set(CommonContextKeys.ORIGIN_VIP_SECURE, origin.getClientConfig().get(IClientConfigKey.Keys.IsSecure)); + context.set( + CommonContextKeys.ACTUAL_VIP, + origin.getClientConfig().get(IClientConfigKey.Keys.DeploymentContextBasedVipAddresses)); + context.set( + CommonContextKeys.ORIGIN_VIP_SECURE, + origin.getClientConfig().get(IClientConfigKey.Keys.IsSecure)); } return origin; @@ -1059,21 +1115,25 @@ private NettyOrigin getOrCreateOrigin( if (origin == null) { // If no pre-registered and configured RestClient found for this VIP, then register one using default NIWS // properties. - logger.warn("Attempting to register RestClient for client that has not been configured. originName={}, uri={}", - originName, uri); + logger.warn( + "Attempting to register RestClient for client that has not been configured. originName={}, uri={}", + originName, + uri); origin = originManager.createOrigin(originName, uri, ctx); } return origin; } - private void verifyOrigin(SessionContext context, HttpRequestMessage request, String restClientName, Origin primaryOrigin) { + private void verifyOrigin( + SessionContext context, HttpRequestMessage request, String restClientName, Origin primaryOrigin) { if (primaryOrigin == null) { // If no origin found then add specific error-cause metric tag, and throw an exception with 404 status. context.put(CommonContextKeys.STATUS_CATGEORY, SUCCESS_LOCAL_NO_ROUTE); String causeName = "RESTCLIENT_NOTFOUND"; originNotFound(context, causeName); - ZuulException ze = new ZuulException("No origin found for request. name=" + restClientName - + ", uri=" + request.reconstructURI(), causeName); + ZuulException ze = new ZuulException( + "No origin found for request. name=" + restClientName + ", uri=" + request.reconstructURI(), + causeName); ze.setStatusCode(404); throw ze; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpInboundFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpInboundFilter.java index 8eb610061b..92bc6c651d 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpInboundFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpInboundFilter.java @@ -24,8 +24,7 @@ * Date: 5/29/15 * Time: 3:22 PM */ -public abstract class HttpInboundFilter extends BaseFilter -{ +public abstract class HttpInboundFilter extends BaseFilter { @Override public FilterType filterType() { return FilterType.INBOUND; diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpInboundSyncFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpInboundSyncFilter.java index 1aaeff22b7..a3f66d7821 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpInboundSyncFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpInboundSyncFilter.java @@ -24,8 +24,7 @@ * Date: 5/29/15 * Time: 3:22 PM */ -public abstract class HttpInboundSyncFilter extends BaseSyncFilter -{ +public abstract class HttpInboundSyncFilter extends BaseSyncFilter { @Override public FilterType filterType() { return FilterType.INBOUND; diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpOutboundFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpOutboundFilter.java index 4ccf02a65c..856c4efd63 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpOutboundFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpOutboundFilter.java @@ -15,26 +15,23 @@ */ package com.netflix.zuul.filters.http; +import com.netflix.zuul.filters.BaseFilter; import com.netflix.zuul.filters.FilterType; -import com.netflix.zuul.message.ZuulMessage; import com.netflix.zuul.message.http.HttpResponseMessage; -import com.netflix.zuul.filters.BaseFilter; /** * User: michaels@netflix.com * Date: 5/29/15 * Time: 3:23 PM */ -public abstract class HttpOutboundFilter extends BaseFilter -{ +public abstract class HttpOutboundFilter extends BaseFilter { @Override public FilterType filterType() { return FilterType.OUTBOUND; } @Override - public HttpResponseMessage getDefaultOutput(HttpResponseMessage input) - { + public HttpResponseMessage getDefaultOutput(HttpResponseMessage input) { return input; } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpOutboundSyncFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpOutboundSyncFilter.java index 7c5e5ed975..04d45f8f74 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpOutboundSyncFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpOutboundSyncFilter.java @@ -15,17 +15,16 @@ */ package com.netflix.zuul.filters.http; +import com.netflix.zuul.filters.BaseSyncFilter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.message.http.HttpResponseMessage; -import com.netflix.zuul.filters.BaseSyncFilter; /** * User: michaels@netflix.com * Date: 5/29/15 * Time: 3:23 PM */ -public abstract class HttpOutboundSyncFilter extends BaseSyncFilter -{ +public abstract class HttpOutboundSyncFilter extends BaseSyncFilter { @Override public FilterType filterType() { return FilterType.OUTBOUND; diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpSyncEndpoint.java b/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpSyncEndpoint.java index 188af717e9..b04ee2e1c4 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpSyncEndpoint.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpSyncEndpoint.java @@ -17,7 +17,6 @@ package com.netflix.zuul.filters.http; import com.netflix.config.CachedDynamicBooleanProperty; -import com.netflix.zuul.exception.ZuulFilterConcurrencyExceededException; import com.netflix.zuul.filters.Endpoint; import com.netflix.zuul.filters.SyncZuulFilter; import com.netflix.zuul.message.ZuulMessage; @@ -34,39 +33,38 @@ * Date: 6/16/15 * Time: 12:23 AM */ -public abstract class HttpSyncEndpoint extends Endpoint implements SyncZuulFilter -{ +public abstract class HttpSyncEndpoint extends Endpoint + implements SyncZuulFilter { // Feature flag for enabling this while we get some real data for the impact. - private static final CachedDynamicBooleanProperty WAIT_FOR_LASTCONTENT = new CachedDynamicBooleanProperty("zuul.endpoint.sync.wait_for_lastcontent", true); + private static final CachedDynamicBooleanProperty WAIT_FOR_LASTCONTENT = + new CachedDynamicBooleanProperty("zuul.endpoint.sync.wait_for_lastcontent", true); private static final String KEY_FOR_SUBSCRIBER = "_HttpSyncEndpoint_subscriber"; @Override - public HttpResponseMessage getDefaultOutput(HttpRequestMessage request) - { + public HttpResponseMessage getDefaultOutput(HttpRequestMessage request) { return HttpResponseMessageImpl.defaultErrorResponse(request); } @Override - public Observable applyAsync(HttpRequestMessage input) - { - if (WAIT_FOR_LASTCONTENT.get() && ! input.hasCompleteBody()) { - // Return an observable that won't complete until after we have received the LastContent from client (ie. that we've - // received the whole request body), so that we can't potentially corrupt the clients' http state on this connection. + public Observable applyAsync(HttpRequestMessage input) { + if (WAIT_FOR_LASTCONTENT.get() && !input.hasCompleteBody()) { + // Return an observable that won't complete until after we have received the LastContent from client (ie. + // that we've + // received the whole request body), so that we can't potentially corrupt the clients' http state on this + // connection. return Observable.create(subscriber -> { ZuulMessage response = this.apply(input); ResponseState state = new ResponseState(response, subscriber); input.getContext().set(KEY_FOR_SUBSCRIBER, state); }); - } - else { + } else { return Observable.just(this.apply(input)); } } @Override - public HttpContent processContentChunk(ZuulMessage zuulMessage, HttpContent chunk) - { + public HttpContent processContentChunk(ZuulMessage zuulMessage, HttpContent chunk) { // Only call onNext() after we've received the LastContent of request from client. if (chunk instanceof LastHttpContent) { ResponseState state = (ResponseState) zuulMessage.getContext().get(KEY_FOR_SUBSCRIBER); @@ -81,21 +79,19 @@ public HttpContent processContentChunk(ZuulMessage zuulMessage, HttpContent chun @Override public void incrementConcurrency() { - //NOOP, since this is supposed to be a SYNC filter in spirit + // NOOP, since this is supposed to be a SYNC filter in spirit } @Override public void decrementConcurrency() { - //NOOP, since this is supposed to be a SYNC filter in spirit + // NOOP, since this is supposed to be a SYNC filter in spirit } - private static class ResponseState - { + private static class ResponseState { final ZuulMessage response; final Subscriber subscriber; - public ResponseState(ZuulMessage response, Subscriber subscriber) - { + public ResponseState(ZuulMessage response, Subscriber subscriber) { this.response = response; this.subscriber = subscriber; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/passport/InboundPassportStampingFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/passport/InboundPassportStampingFilter.java index 870f21e13b..f632c1ed94 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/passport/InboundPassportStampingFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/passport/InboundPassportStampingFilter.java @@ -37,5 +37,4 @@ public InboundPassportStampingFilter(PassportState stamp) { public FilterType filterType() { return INBOUND; } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/passport/OutboundPassportStampingFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/passport/OutboundPassportStampingFilter.java index 776657e2a1..df14b580c8 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/passport/OutboundPassportStampingFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/passport/OutboundPassportStampingFilter.java @@ -37,5 +37,4 @@ public OutboundPassportStampingFilter(PassportState stamp) { public FilterType filterType() { return OUTBOUND; } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/passport/PassportStampingFilter.java b/zuul-core/src/main/java/com/netflix/zuul/filters/passport/PassportStampingFilter.java index 7bd688ad0c..22495b5a18 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/filters/passport/PassportStampingFilter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/filters/passport/PassportStampingFilter.java @@ -16,8 +16,8 @@ package com.netflix.zuul.filters.passport; -import com.netflix.zuul.message.ZuulMessage; import com.netflix.zuul.filters.SyncZuulFilterAdapter; +import com.netflix.zuul.message.ZuulMessage; import com.netflix.zuul.passport.CurrentPassport; import com.netflix.zuul.passport.PassportState; @@ -31,7 +31,7 @@ public abstract class PassportStampingFilter extends Sync public PassportStampingFilter(PassportState stamp) { this.stamp = stamp; - this.name = filterType().name()+"-"+stamp.name()+"-Filter"; + this.name = filterType().name() + "-" + stamp.name() + "-Filter"; } @Override @@ -49,5 +49,4 @@ public T apply(T input) { CurrentPassport.fromSessionContext(input.getContext()).add(stamp); return input; } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/logging/Http2FrameLoggingPerClientIpHandler.java b/zuul-core/src/main/java/com/netflix/zuul/logging/Http2FrameLoggingPerClientIpHandler.java index 380666290e..73a4613e18 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/logging/Http2FrameLoggingPerClientIpHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/logging/Http2FrameLoggingPerClientIpHandler.java @@ -17,32 +17,30 @@ package com.netflix.zuul.logging; import com.netflix.config.DynamicStringSetProperty; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; import com.netflix.netty.common.SourceAddressChannelHandler; import com.netflix.netty.common.http2.DynamicHttp2FrameLogger; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; /** * Be aware that this will only work correctly for devices connected _directly_ to Zuul - ie. connected * through an ELB TCP Listener. And not through FTL either. */ -public class Http2FrameLoggingPerClientIpHandler extends ChannelInboundHandlerAdapter -{ - private static DynamicStringSetProperty IPS = - new DynamicStringSetProperty("server.http2.frame.logging.ips", ""); - +public class Http2FrameLoggingPerClientIpHandler extends ChannelInboundHandlerAdapter { + private static DynamicStringSetProperty IPS = new DynamicStringSetProperty("server.http2.frame.logging.ips", ""); + @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { - String clientIP = ctx.channel().attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get(); + String clientIP = ctx.channel() + .attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS) + .get(); if (IPS.get().contains(clientIP)) { ctx.channel().attr(DynamicHttp2FrameLogger.ATTR_ENABLE).set(Boolean.TRUE); ctx.pipeline().remove(this); } - } - finally { + } finally { super.channelRead(ctx, msg); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/Header.java b/zuul-core/src/main/java/com/netflix/zuul/message/Header.java index 944da6b7d6..02ffe935ea 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/Header.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/Header.java @@ -23,8 +23,7 @@ public final class Header { private final HeaderName name; private final String value; - public Header(HeaderName name, String value) - { + public Header(HeaderName name, String value) { if (name == null) { throw new NullPointerException("Header name cannot be null!"); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/Headers.java b/zuul-core/src/main/java/com/netflix/zuul/message/Headers.java index 0e77d80d88..71f40a081d 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/Headers.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/Headers.java @@ -15,12 +15,12 @@ */ package com.netflix.zuul.message; -import static java.util.Objects.requireNonNull; - import com.google.common.annotations.VisibleForTesting; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Spectator; import com.netflix.zuul.exception.ZuulException; + +import javax.annotation.Nullable; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayList; import java.util.Collection; @@ -32,7 +32,8 @@ import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Predicate; -import javax.annotation.Nullable; + +import static java.util.Objects.requireNonNull; /** * An abstraction over a collection of http headers. Allows multiple headers with same name, and header names are @@ -48,7 +49,8 @@ public final class Headers { private final List names; private final List values; - private static final Counter invalidHeaderCounter = Spectator.globalRegistry().counter("zuul.header.invalid.char"); + private static final Counter invalidHeaderCounter = + Spectator.globalRegistry().counter("zuul.header.invalid.char"); public static Headers copyOf(Headers original) { return new Headers(requireNonNull(original, "original")); @@ -492,7 +494,7 @@ public Collection
entries() { */ public Set keySet() { Set headerNames = new LinkedHashSet<>(size()); - for (int i = 0 ; i < size(); i++) { + for (int i = 0; i < size(); i++) { HeaderName headerName = new HeaderName(originalName(i), name(i)); // We actually do need to check contains before adding to the set because the original name may change. // In this case, the first name wins. diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/ZuulMessage.java b/zuul-core/src/main/java/com/netflix/zuul/message/ZuulMessage.java index 0243bc11a7..017cbcfe83 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/ZuulMessage.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/ZuulMessage.java @@ -20,8 +20,8 @@ import com.netflix.zuul.filters.ZuulFilter; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.LastHttpContent; -import javax.annotation.Nullable; +import javax.annotation.Nullable; /** * Represents a message that propagates through the Zuul filter chain. diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/ZuulMessageImpl.java b/zuul-core/src/main/java/com/netflix/zuul/message/ZuulMessageImpl.java index 7635ae9a89..818708649b 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/ZuulMessageImpl.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/ZuulMessageImpl.java @@ -23,12 +23,12 @@ import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.message.http.HttpHeaderNames; -import io.netty.buffer.*; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.LastHttpContent; -import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -38,10 +38,9 @@ * Date: 2/20/15 * Time: 3:10 PM */ -public class ZuulMessageImpl implements ZuulMessage -{ - protected static final DynamicIntProperty MAX_BODY_SIZE_PROP = DynamicPropertyFactory.getInstance().getIntProperty( - "zuul.message.body.max.size", 25 * 1000 * 1024); +public class ZuulMessageImpl implements ZuulMessage { + protected static final DynamicIntProperty MAX_BODY_SIZE_PROP = + DynamicPropertyFactory.getInstance().getIntProperty("zuul.message.body.max.size", 25 * 1000 * 1024); protected final SessionContext context; protected Headers headers; @@ -50,7 +49,6 @@ public class ZuulMessageImpl implements ZuulMessage private boolean bodyBufferedCompletely; private List bodyChunks; - public ZuulMessageImpl(SessionContext context) { this(context, new Headers()); } @@ -81,7 +79,6 @@ public int getMaxBodySize() { return MAX_BODY_SIZE_PROP.get(); } - @Override public void setHasBody(boolean hasBody) { this.hasBody = hasBody; @@ -102,7 +99,7 @@ public void bufferBodyContents(final HttpContent chunk) { setHasBody(true); ByteBufUtil.touch(chunk, "ZuulMessage buffering body content."); bodyChunks.add(chunk); - if (chunk instanceof LastHttpContent) { + if (chunk instanceof LastHttpContent) { ByteBufUtil.touch(chunk, "ZuulMessage buffering body content complete."); bodyBufferedCompletely = true; } @@ -116,7 +113,7 @@ private void setContentLength(int length) { @Override public void setBodyAsText(String bodyText) { disposeBufferedBody(); - if (! Strings.isNullOrEmpty(bodyText)) { + if (!Strings.isNullOrEmpty(bodyText)) { byte[] bytes = bodyText.getBytes(Charsets.UTF_8); bufferBodyContents(new DefaultLastHttpContent(Unpooled.wrappedBuffer(bytes))); setContentLength(bytes.length); @@ -189,7 +186,7 @@ public void resetBodyReader() { @Override public boolean finishBufferedBodyIfIncomplete() { - if (! bodyBufferedCompletely) { + if (!bodyBufferedCompletely) { bufferBodyContents(new DefaultLastHttpContent()); return true; } @@ -209,16 +206,16 @@ public void disposeBufferedBody() { @Override public void runBufferedBodyContentThroughFilter(ZuulFilter filter) { - //Loop optimized for the common case: Most filters' processContentChunk() return + // Loop optimized for the common case: Most filters' processContentChunk() return // original chunk passed in as is without any processing final String filterName = filter.filterName(); - for (int i=0; i < bodyChunks.size(); i++) { + for (int i = 0; i < bodyChunks.size(); i++) { final HttpContent origChunk = bodyChunks.get(i); ByteBufUtil.touch(origChunk, "ZuulMessage processing chunk, filter: ", filterName); final HttpContent filteredChunk = filter.processContentChunk(this, origChunk); ByteBufUtil.touch(filteredChunk, "ZuulMessage processing filteredChunk, filter: ", filterName); if ((filteredChunk != null) && (filteredChunk != origChunk)) { - //filter actually did some processing, set the new chunk in and release the old chunk. + // filter actually did some processing, set the new chunk in and release the old chunk. bodyChunks.set(i, filteredChunk); final int refCnt = origChunk.refCnt(); if (refCnt > 0) { diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/http/Cookies.java b/zuul-core/src/main/java/com/netflix/zuul/message/http/Cookies.java index 6c81939e79..aa58edfd99 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/http/Cookies.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/http/Cookies.java @@ -28,13 +28,11 @@ * Date: 6/18/15 * Time: 12:04 AM */ -public class Cookies -{ +public class Cookies { private Map> map = new HashMap<>(); private List all = new ArrayList<>(); - public void add(Cookie cookie) - { + public void add(Cookie cookie) { List existing = map.get(cookie.getName()); if (existing == null) { existing = new ArrayList<>(); @@ -44,18 +42,15 @@ public void add(Cookie cookie) all.add(cookie); } - public List getAll() - { + public List getAll() { return all; } - public List get(String name) - { + public List get(String name) { return map.get(name); } - public Cookie getFirst(String name) - { + public Cookie getFirst(String name) { List found = map.get(name); if (found == null || found.size() == 0) { return null; @@ -63,8 +58,7 @@ public Cookie getFirst(String name) return found.get(0); } - public String getFirstValue(String name) - { + public String getFirstValue(String name) { Cookie c = getFirst(name); String value; if (c != null) { diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpHeaderNames.java b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpHeaderNames.java index e6ab57ffba..70013ae52d 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpHeaderNames.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpHeaderNames.java @@ -30,14 +30,12 @@ * Date: 8/5/15 * Time: 12:33 PM */ -public final class HttpHeaderNames -{ - private static final DynamicIntProperty MAX_CACHE_SIZE = - DynamicPropertyFactory.getInstance().getIntProperty("com.netflix.zuul.message.http.HttpHeaderNames.maxCacheSize", 30); +public final class HttpHeaderNames { + private static final DynamicIntProperty MAX_CACHE_SIZE = DynamicPropertyFactory.getInstance() + .getIntProperty("com.netflix.zuul.message.http.HttpHeaderNames.maxCacheSize", 30); private static final HttpHeaderNamesCache HEADER_NAME_CACHE = new HttpHeaderNamesCache(100, MAX_CACHE_SIZE.get()); - - + public static final HeaderName COOKIE = HEADER_NAME_CACHE.get("Cookie"); public static final HeaderName SET_COOKIE = HEADER_NAME_CACHE.get("Set-Cookie"); @@ -80,11 +78,14 @@ public final class HttpHeaderNames public static final HeaderName X_FORWARDED_PROTO_VERSION = HEADER_NAME_CACHE.get("X-Forwarded-Proto-Version"); public static final HeaderName ACCESS_CONTROL_ALLOW_ORIGIN = HEADER_NAME_CACHE.get("Access-Control-Allow-Origin"); - public static final HeaderName ACCESS_CONTROL_ALLOW_CREDENTIALS = HEADER_NAME_CACHE.get("Access-Control-Allow-Credentials"); + public static final HeaderName ACCESS_CONTROL_ALLOW_CREDENTIALS = + HEADER_NAME_CACHE.get("Access-Control-Allow-Credentials"); public static final HeaderName ACCESS_CONTROL_ALLOW_HEADERS = HEADER_NAME_CACHE.get("Access-Control-Allow-Headers"); public static final HeaderName ACCESS_CONTROL_ALLOW_METHODS = HEADER_NAME_CACHE.get("Access-Control-Allow-Methods"); - public static final HeaderName ACCESS_CONTROL_REQUEST_HEADERS = HEADER_NAME_CACHE.get("Access-Control-Request-Headers"); - public static final HeaderName ACCESS_CONTROL_EXPOSE_HEADERS = HEADER_NAME_CACHE.get("Access-Control-Expose-Headers"); + public static final HeaderName ACCESS_CONTROL_REQUEST_HEADERS = + HEADER_NAME_CACHE.get("Access-Control-Request-Headers"); + public static final HeaderName ACCESS_CONTROL_EXPOSE_HEADERS = + HEADER_NAME_CACHE.get("Access-Control-Expose-Headers"); public static final HeaderName ACCESS_CONTROL_MAX_AGE_HEADERS = HEADER_NAME_CACHE.get("Access-Control-Max-Age"); public static final HeaderName STRICT_TRANSPORT_SECURITY = HEADER_NAME_CACHE.get("Strict-Transport-Security"); public static final HeaderName LINK = HEADER_NAME_CACHE.get("Link"); @@ -96,8 +97,7 @@ public final class HttpHeaderNames * @param name * @return HeaderName - never null. */ - public static HeaderName get(String name) - { + public static HeaderName get(String name) { return HEADER_NAME_CACHE.get(name); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpHeaderNamesCache.java b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpHeaderNamesCache.java index 93f2fde689..4b10b08087 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpHeaderNamesCache.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpHeaderNamesCache.java @@ -25,24 +25,20 @@ * Date: 8/5/15 * Time: 1:08 PM */ -public class HttpHeaderNamesCache -{ +public class HttpHeaderNamesCache { private final ConcurrentHashMap cache; private final int maxSize; - public HttpHeaderNamesCache(int initialSize, int maxSize) - { + public HttpHeaderNamesCache(int initialSize, int maxSize) { this.cache = new ConcurrentHashMap<>(initialSize); this.maxSize = maxSize; } - public boolean isFull() - { + public boolean isFull() { return cache.size() >= maxSize; } - public HeaderName get(String name) - { + public HeaderName get(String name) { // Check in the static cache for this headername if available. // NOTE: we do this lookup case-sensitively, as doing case-INSENSITIVELY removes the purpose of // caching the object in the first place (ie. the expensive operation we want to avoid by caching @@ -53,8 +49,7 @@ public HeaderName get(String name) // too much if the cache overfills a bit. if (isFull()) { hn = new HeaderName(name); - } - else { + } else { hn = cache.computeIfAbsent(name, (newName) -> new HeaderName(newName)); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpQueryParams.java b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpQueryParams.java index cec5051bb4..c9291e61f2 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpQueryParams.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpQueryParams.java @@ -20,6 +20,7 @@ import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.ListMultimap; + import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; @@ -36,21 +37,18 @@ * Date: 2/24/15 * Time: 10:58 AM */ -public class HttpQueryParams implements Cloneable -{ +public class HttpQueryParams implements Cloneable { private final ListMultimap delegate; private final boolean immutable; private final HashMap trailingEquals; - public HttpQueryParams() - { + public HttpQueryParams() { delegate = ArrayListMultimap.create(); immutable = false; trailingEquals = new HashMap<>(); } - private HttpQueryParams(ListMultimap delegate) - { + private HttpQueryParams(ListMultimap delegate) { this.delegate = delegate; immutable = ImmutableListMultimap.class.isAssignableFrom(delegate.getClass()); trailingEquals = new HashMap<>(); @@ -75,8 +73,7 @@ public static HttpQueryParams parse(String queryString) { try { name = URLDecoder.decode(name, "UTF-8"); value = URLDecoder.decode(value, "UTF-8"); - } - catch (Exception e) { + } catch (Exception e) { // do nothing } @@ -93,8 +90,7 @@ else if (s.length() > 0) { try { name = URLDecoder.decode(name, "UTF-8"); - } - catch (Exception e) { + } catch (Exception e) { // do nothing } @@ -109,8 +105,7 @@ else if (s.length() > 0) { * Get the first value found for this key even if there are multiple. If none, then * return null. */ - public String getFirst(String name) - { + public String getFirst(String name) { List values = delegate.get(name); if (values != null) { if (values.size() > 0) { @@ -120,13 +115,11 @@ public String getFirst(String name) return null; } - public List get(String name) - { + public List get(String name) { return delegate.get(name.toLowerCase()); } - public boolean contains(String name) - { + public boolean contains(String name) { return delegate.containsKey(name); } @@ -138,37 +131,31 @@ public boolean containsIgnoreCase(String name) { return delegate.containsKey(name) || delegate.containsKey(name.toLowerCase(Locale.ROOT)); } - public boolean contains(String name, String value) - { + public boolean contains(String name, String value) { return delegate.containsEntry(name, value); } /** * Replace any/all entries with this key, with this single entry. */ - public void set(String name, String value) - { + public void set(String name, String value) { delegate.removeAll(name); - delegate.put(name, value); + delegate.put(name, value); } - public void add(String name, String value) - { + public void add(String name, String value) { delegate.put(name, value); } - public void removeAll(String name) - { + public void removeAll(String name) { delegate.removeAll(name); } - public void clear() - { + public void clear() { delegate.clear(); } - public Collection> entries() - { + public Collection> entries() { return delegate.entries(); } @@ -176,8 +163,7 @@ public Set keySet() { return delegate.keySet(); } - public String toEncodedString() - { + public String toEncodedString() { StringBuilder sb = new StringBuilder(); try { for (Map.Entry entry : entries()) { @@ -185,8 +171,7 @@ public String toEncodedString() if (!Strings.isNullOrEmpty(entry.getValue())) { sb.append('='); sb.append(URLEncoder.encode(entry.getValue(), "UTF-8")); - } - else if (isTrailingEquals(entry.getKey())) { + } else if (isTrailingEquals(entry.getKey())) { sb.append('='); } sb.append('&'); @@ -196,8 +181,7 @@ else if (isTrailingEquals(entry.getKey())) { if (sb.length() > 0 && '&' == sb.charAt(sb.length() - 1)) { sb.deleteCharAt(sb.length() - 1); } - } - catch (UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { // Won't happen. e.printStackTrace(); } @@ -205,8 +189,7 @@ else if (isTrailingEquals(entry.getKey())) { } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); for (Map.Entry entry : entries()) { sb.append(entry.getKey()); @@ -225,20 +208,17 @@ public String toString() } @Override - protected HttpQueryParams clone() - { + protected HttpQueryParams clone() { HttpQueryParams copy = new HttpQueryParams(); copy.delegate.putAll(this.delegate); return copy; } - public HttpQueryParams immutableCopy() - { + public HttpQueryParams immutableCopy() { return new HttpQueryParams(ImmutableListMultimap.copyOf(delegate)); } - public boolean isImmutable() - { + public boolean isImmutable() { return immutable; } @@ -251,14 +231,12 @@ public void setTrailingEquals(String key, boolean trailingEquals) { } @Override - public int hashCode() - { + public int hashCode() { return delegate.hashCode(); } @Override - public boolean equals(Object obj) - { + public boolean equals(Object obj) { if (obj == null) { return false; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestInfo.java b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestInfo.java index 7fdca4d766..f0770cf424 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestInfo.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestInfo.java @@ -18,6 +18,7 @@ import com.netflix.zuul.message.Headers; import com.netflix.zuul.message.ZuulMessage; + import java.util.Optional; /** @@ -25,8 +26,7 @@ * Date: 7/15/15 * Time: 1:18 PM */ -public interface HttpRequestInfo extends ZuulMessage -{ +public interface HttpRequestInfo extends ZuulMessage { String getProtocol(); String getMethod(); diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestMessage.java b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestMessage.java index d8e1aa6bca..a8e0ba083e 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestMessage.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestMessage.java @@ -23,8 +23,7 @@ * Date: 7/15/15 * Time: 5:36 PM */ -public interface HttpRequestMessage extends HttpRequestInfo -{ +public interface HttpRequestMessage extends HttpRequestInfo { void setProtocol(String protocol); void setMethod(String method); diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestMessageImpl.java b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestMessageImpl.java index 4f51fae9fc..8d8617b570 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestMessageImpl.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestMessageImpl.java @@ -15,7 +15,6 @@ */ package com.netflix.zuul.message.http; - import com.google.common.annotations.VisibleForTesting; import com.netflix.config.CachedDynamicBooleanProperty; import com.netflix.config.CachedDynamicIntProperty; @@ -31,6 +30,9 @@ import io.netty.handler.codec.http.Cookie; import io.netty.handler.codec.http.CookieDecoder; import io.netty.handler.codec.http.HttpContent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; @@ -42,33 +44,29 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * User: michaels * Date: 2/24/15 * Time: 10:54 AM */ -public class HttpRequestMessageImpl implements HttpRequestMessage -{ +public class HttpRequestMessageImpl implements HttpRequestMessage { private static final Logger LOG = LoggerFactory.getLogger(HttpRequestMessageImpl.class); - private static final CachedDynamicBooleanProperty STRICT_HOST_HEADER_VALIDATION = new CachedDynamicBooleanProperty( - "zuul.HttpRequestMessage.host.header.strict.validation", true - ); + private static final CachedDynamicBooleanProperty STRICT_HOST_HEADER_VALIDATION = + new CachedDynamicBooleanProperty("zuul.HttpRequestMessage.host.header.strict.validation", true); - private static final CachedDynamicIntProperty MAX_BODY_SIZE_PROP = new CachedDynamicIntProperty( - "zuul.HttpRequestMessage.body.max.size", 15 * 1000 * 1024 - ); - private static final CachedDynamicBooleanProperty CLEAN_COOKIES = new CachedDynamicBooleanProperty( - "zuul.HttpRequestMessage.cookies.clean", false - ); + private static final CachedDynamicIntProperty MAX_BODY_SIZE_PROP = + new CachedDynamicIntProperty("zuul.HttpRequestMessage.body.max.size", 15 * 1000 * 1024); + private static final CachedDynamicBooleanProperty CLEAN_COOKIES = + new CachedDynamicBooleanProperty("zuul.HttpRequestMessage.cookies.clean", false); /** ":::"-delimited list of regexes to strip out of the cookie headers. */ private static final DynamicStringProperty REGEX_PTNS_TO_STRIP_PROP = new DynamicStringProperty("zuul.request.cookie.cleaner.strip", " Secure,"); + private static final List RE_STRIP; + static { RE_STRIP = new ArrayList<>(); for (String ptn : REGEX_PTNS_TO_STRIP_PROP.get().split(":::")) { @@ -108,19 +106,45 @@ public String toString() { } }; - public HttpRequestMessageImpl(SessionContext context, String protocol, String method, String path, - HttpQueryParams queryParams, Headers headers, String clientIp, String scheme, - int port, String serverName) - { - this(context, protocol, method, path, queryParams, headers, clientIp, scheme, port, serverName, - UNDEFINED_CLIENT_DEST_ADDRESS, false); - } - - public HttpRequestMessageImpl(SessionContext context, String protocol, String method, String path, - HttpQueryParams queryParams, Headers headers, String clientIp, String scheme, - int port, String serverName, SocketAddress clientRemoteAddress, - boolean immutable) - { + public HttpRequestMessageImpl( + SessionContext context, + String protocol, + String method, + String path, + HttpQueryParams queryParams, + Headers headers, + String clientIp, + String scheme, + int port, + String serverName) { + this( + context, + protocol, + method, + path, + queryParams, + headers, + clientIp, + scheme, + port, + serverName, + UNDEFINED_CLIENT_DEST_ADDRESS, + false); + } + + public HttpRequestMessageImpl( + SessionContext context, + String protocol, + String method, + String path, + HttpQueryParams queryParams, + Headers headers, + String clientIp, + String scheme, + int port, + String serverName, + SocketAddress clientRemoteAddress, + boolean immutable) { this.immutable = immutable; this.message = new ZuulMessageImpl(context, headers); this.protocol = protocol; @@ -142,28 +166,25 @@ public HttpRequestMessageImpl(SessionContext context, String protocol, String me this.clientRemoteAddress = clientRemoteAddress; } - private void immutableCheck() - { + private void immutableCheck() { if (immutable) { - throw new IllegalStateException("This HttpRequestMessageImpl is immutable. No mutating operations allowed!"); + throw new IllegalStateException( + "This HttpRequestMessageImpl is immutable. No mutating operations allowed!"); } } @Override - public SessionContext getContext() - { + public SessionContext getContext() { return message.getContext(); } @Override - public Headers getHeaders() - { + public Headers getHeaders() { return message.getHeaders(); } @Override - public void setHeaders(Headers newHeaders) - { + public void setHeaders(Headers newHeaders) { immutableCheck(); message.setHeaders(newHeaders); } @@ -244,8 +265,7 @@ public String getProtocol() { } @Override - public void setProtocol(String protocol) - { + public void setProtocol(String protocol) { immutableCheck(); this.protocol = protocol; } @@ -254,9 +274,9 @@ public void setProtocol(String protocol) public String getMethod() { return method; } + @Override - public void setMethod(String method) - { + public void setMethod(String method) { immutableCheck(); this.method = method; } @@ -268,9 +288,9 @@ public String getPath() { } return path; } + @Override - public void setPath(String path) - { + public void setPath(String path) { immutableCheck(); this.path = path; this.decodedPath = path; @@ -282,26 +302,22 @@ public HttpQueryParams getQueryParams() { } @Override - public String getPathAndQuery() - { + public String getPathAndQuery() { // If this instance is immutable, then lazy-cache. if (immutable) { if (pathAndQuery == null) { pathAndQuery = generatePathAndQuery(); } return pathAndQuery; - } - else { + } else { return generatePathAndQuery(); } } - protected String generatePathAndQuery() - { + protected String generatePathAndQuery() { if (queryParams != null && queryParams.entries().size() > 0) { return getPath() + "?" + queryParams.toEncodedString(); - } - else { + } else { return getPath(); } } @@ -313,8 +329,7 @@ public String getClientIp() { @Deprecated @VisibleForTesting - void setClientIp(String clientIp) - { + void setClientIp(String clientIp) { immutableCheck(); this.clientIp = clientIp; } @@ -323,47 +338,42 @@ void setClientIp(String clientIp) * Note: this is meant to be used typically in cases where TLS termination happens on instance. * For CLB/ALB fronted traffic, consider using {@link #getOriginalScheme()} instead. */ - @Override public String getScheme() { return scheme; } + @Override - public void setScheme(String scheme) - { + public void setScheme(String scheme) { immutableCheck(); this.scheme = scheme; } @Override - public int getPort() - { + public int getPort() { return port; } @Deprecated @VisibleForTesting - void setPort(int port) - { + void setPort(int port) { immutableCheck(); this.port = port; } @Override - public String getServerName() - { + public String getServerName() { return serverName; } + @Override - public void setServerName(String serverName) - { + public void setServerName(String serverName) { immutableCheck(); this.serverName = serverName; } @Override - public Cookies parseCookies() - { + public Cookies parseCookies() { if (parsedCookies == null) { parsedCookies = reParseCookies(); } @@ -371,11 +381,9 @@ public Cookies parseCookies() } @Override - public Cookies reParseCookies() - { + public Cookies reParseCookies() { Cookies cookies = new Cookies(); - for (String aCookieHeader : getHeaders().getAll(HttpHeaderNames.COOKIE)) - { + for (String aCookieHeader : getHeaders().getAll(HttpHeaderNames.COOKIE)) { try { if (CLEAN_COOKIES.get()) { aCookieHeader = cleanCookieHeader(aCookieHeader); @@ -385,20 +393,19 @@ public Cookies reParseCookies() for (Cookie cookie : decoded) { cookies.add(cookie); } + } catch (Exception e) { + LOG.error( + "Error parsing request Cookie header. cookie={}, request-info={}", + aCookieHeader, + getInfoForLogging()); } - catch (Exception e) { - LOG.error("Error parsing request Cookie header. cookie={}, request-info={}", - aCookieHeader, getInfoForLogging()); - } - } parsedCookies = cookies; return cookies; } @VisibleForTesting - static String cleanCookieHeader(String cookie) - { + static String cleanCookieHeader(String cookie) { for (Pattern stripPtn : RE_STRIP) { Matcher matcher = stripPtn.matcher(cookie); if (matcher.find()) { @@ -414,71 +421,83 @@ public int getMaxBodySize() { } @Override - public ZuulMessage clone() - { - HttpRequestMessageImpl clone = new HttpRequestMessageImpl(message.getContext().clone(), - protocol, method, path, - queryParams.clone(), Headers.copyOf(message.getHeaders()), clientIp, scheme, - port, serverName, clientRemoteAddress, immutable); + public ZuulMessage clone() { + HttpRequestMessageImpl clone = new HttpRequestMessageImpl( + message.getContext().clone(), + protocol, + method, + path, + queryParams.clone(), + Headers.copyOf(message.getHeaders()), + clientIp, + scheme, + port, + serverName, + clientRemoteAddress, + immutable); if (getInboundRequest() != null) { clone.inboundRequest = (HttpRequestInfo) getInboundRequest().clone(); } return clone; } - protected HttpRequestInfo copyRequestInfo() - { - - HttpRequestMessageImpl req = new HttpRequestMessageImpl(message.getContext(), - protocol, method, path, - queryParams.immutableCopy(), Headers.copyOf(message.getHeaders()), clientIp, scheme, - port, serverName, clientRemoteAddress, true); + protected HttpRequestInfo copyRequestInfo() { + + HttpRequestMessageImpl req = new HttpRequestMessageImpl( + message.getContext(), + protocol, + method, + path, + queryParams.immutableCopy(), + Headers.copyOf(message.getHeaders()), + clientIp, + scheme, + port, + serverName, + clientRemoteAddress, + true); req.setHasBody(hasBody()); return req; } @Override - public void storeInboundRequest() - { + public void storeInboundRequest() { inboundRequest = copyRequestInfo(); } @Override - public HttpRequestInfo getInboundRequest() - { + public HttpRequestInfo getInboundRequest() { return inboundRequest; } @Override - public void setQueryParams(HttpQueryParams queryParams) - { + public void setQueryParams(HttpQueryParams queryParams) { immutableCheck(); this.queryParams = queryParams; } @Override - public String getInfoForLogging() - { + public String getInfoForLogging() { // If this instance is immutable, then lazy-cache generating this info. if (immutable) { if (infoForLogging == null) { infoForLogging = generateInfoForLogging(); } return infoForLogging; - } - else { + } else { return generateInfoForLogging(); } } - protected String generateInfoForLogging() - { + protected String generateInfoForLogging() { HttpRequestInfo req = getInboundRequest() == null ? this : getInboundRequest(); StringBuilder sb = new StringBuilder() - .append("uri=").append(req.reconstructURI()) - .append(", method=").append(req.getMethod()) - .append(", clientip=").append(HttpUtils.getClientIP(req)) - ; + .append("uri=") + .append(req.reconstructURI()) + .append(", method=") + .append(req.getMethod()) + .append(", clientip=") + .append(HttpUtils.getClientIP(req)); return sb.toString(); } @@ -511,8 +530,7 @@ static String getOriginalHost(Headers headers, String serverName) throws URISynt } @Override - public String getOriginalScheme() - { + public String getOriginalScheme() { String scheme = getHeaders().getFirst(HttpHeaderNames.X_FORWARDED_PROTO); if (scheme == null) { scheme = getScheme(); @@ -521,8 +539,7 @@ public String getOriginalScheme() } @Override - public String getOriginalProtocol() - { + public String getOriginalProtocol() { String proto = getHeaders().getFirst(HttpHeaderNames.X_FORWARDED_PROTO_VERSION); if (proto == null) { proto = getProtocol(); @@ -627,22 +644,19 @@ private static Pair parseHostHeader(Headers headers) throws URI * @return String */ @Override - public String reconstructURI() - { + public String reconstructURI() { // If this instance is immutable, then lazy-cache reconstructing the uri. if (immutable) { if (reconstructedUri == null) { reconstructedUri = _reconstructURI(); } return reconstructedUri; - } - else { + } else { return _reconstructURI(); } } - protected String _reconstructURI() - { + protected String _reconstructURI() { try { StringBuilder uri = new StringBuilder(100); @@ -651,8 +665,7 @@ protected String _reconstructURI() uri.append(URI_SCHEME_SEP).append(getOriginalHost(getHeaders(), getServerName())); int port = getOriginalPort(); - if ((URI_SCHEME_HTTP.equals(scheme) && 80 == port) - || (URI_SCHEME_HTTPS.equals(scheme) && 443 == port)) { + if ((URI_SCHEME_HTTP.equals(scheme) && 80 == port) || (URI_SCHEME_HTTPS.equals(scheme) && 443 == port)) { // Don't need to include port. } else { uri.append(':').append(port); @@ -661,13 +674,11 @@ protected String _reconstructURI() uri.append(getPathAndQuery()); return uri.toString(); - } - catch (URISyntaxException e) { + } catch (URISyntaxException e) { // This is not really so bad, just debug log it and move on. LOG.debug("Error reconstructing request URI!", e); return ""; - } - catch (Exception e) { + } catch (Exception e) { LOG.error("Error reconstructing request URI!", e); return ""; } @@ -675,22 +686,21 @@ protected String _reconstructURI() @Override public String toString() { - return "HttpRequestMessageImpl{" + - "immutable=" + immutable + - ", message=" + message + - ", protocol='" + protocol + '\'' + - ", method='" + method + '\'' + - ", path='" + path + '\'' + - ", queryParams=" + queryParams + - ", clientIp='" + clientIp + '\'' + - ", scheme='" + scheme + '\'' + - ", port=" + port + - ", serverName='" + serverName + '\'' + - ", inboundRequest=" + inboundRequest + - ", parsedCookies=" + parsedCookies + - ", reconstructedUri='" + reconstructedUri + '\'' + - ", pathAndQuery='" + pathAndQuery + '\'' + - ", infoForLogging='" + infoForLogging + '\'' + - '}'; + return "HttpRequestMessageImpl{" + "immutable=" + + immutable + ", message=" + + message + ", protocol='" + + protocol + '\'' + ", method='" + + method + '\'' + ", path='" + + path + '\'' + ", queryParams=" + + queryParams + ", clientIp='" + + clientIp + '\'' + ", scheme='" + + scheme + '\'' + ", port=" + + port + ", serverName='" + + serverName + '\'' + ", inboundRequest=" + + inboundRequest + ", parsedCookies=" + + parsedCookies + ", reconstructedUri='" + + reconstructedUri + '\'' + ", pathAndQuery='" + + pathAndQuery + '\'' + ", infoForLogging='" + + infoForLogging + '\'' + '}'; } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseInfo.java b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseInfo.java index ee3724551c..1eeb7a7f01 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseInfo.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseInfo.java @@ -23,8 +23,7 @@ * Date: 7/6/15 * Time: 5:27 PM */ -public interface HttpResponseInfo extends ZuulMessage -{ +public interface HttpResponseInfo extends ZuulMessage { int getStatus(); /** The immutable request that was originally received from client. */ @@ -37,5 +36,6 @@ public interface HttpResponseInfo extends ZuulMessage String getInfoForLogging(); Cookies parseSetCookieHeader(String setCookieValue); + boolean hasSetCookieWithName(String cookieName); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseMessage.java b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseMessage.java index 2696e96954..98ee1791ac 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseMessage.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseMessage.java @@ -23,8 +23,7 @@ * Date: 7/16/15 * Time: 12:45 AM */ -public interface HttpResponseMessage extends HttpResponseInfo -{ +public interface HttpResponseMessage extends HttpResponseInfo { void setStatus(int status); @Override diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseMessageImpl.java b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseMessageImpl.java index dca27b9870..10d3249ea5 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseMessageImpl.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseMessageImpl.java @@ -35,10 +35,9 @@ * Date: 2/24/15 * Time: 10:54 AM */ -public class HttpResponseMessageImpl implements HttpResponseMessage -{ - private static final DynamicIntProperty MAX_BODY_SIZE_PROP = DynamicPropertyFactory.getInstance().getIntProperty( - "zuul.HttpResponseMessage.body.max.size", 25 * 1000 * 1024); +public class HttpResponseMessageImpl implements HttpResponseMessage { + private static final DynamicIntProperty MAX_BODY_SIZE_PROP = DynamicPropertyFactory.getInstance() + .getIntProperty("zuul.HttpResponseMessage.body.max.size", 25 * 1000 * 1024); private static final Logger LOG = LoggerFactory.getLogger(HttpResponseMessageImpl.class); private ZuulMessage message; @@ -46,43 +45,39 @@ public class HttpResponseMessageImpl implements HttpResponseMessage private int status; private HttpResponseInfo inboundResponse = null; - public HttpResponseMessageImpl(SessionContext context, HttpRequestMessage request, int status) - { + public HttpResponseMessageImpl(SessionContext context, HttpRequestMessage request, int status) { this(context, new Headers(), request, status); } - public HttpResponseMessageImpl(SessionContext context, Headers headers, HttpRequestMessage request, int status) - { + public HttpResponseMessageImpl(SessionContext context, Headers headers, HttpRequestMessage request, int status) { this.message = new ZuulMessageImpl(context, headers); this.outboundRequest = request; if (this.outboundRequest.getInboundRequest() == null) { - LOG.warn("HttpResponseMessage created with a request that does not have a stored inboundRequest! Probably a bug in the filter that is creating this response.", new RuntimeException("Invalid HttpRequestMessage")); + LOG.warn( + "HttpResponseMessage created with a request that does not have a stored inboundRequest! Probably a bug in the filter that is creating this response.", + new RuntimeException("Invalid HttpRequestMessage")); } this.status = status; } - public static HttpResponseMessage defaultErrorResponse(HttpRequestMessage request) - { + public static HttpResponseMessage defaultErrorResponse(HttpRequestMessage request) { final HttpResponseMessage resp = new HttpResponseMessageImpl(request.getContext(), request, 500); resp.finishBufferedBodyIfIncomplete(); return resp; } @Override - public Headers getHeaders() - { + public Headers getHeaders() { return message.getHeaders(); } @Override - public SessionContext getContext() - { + public SessionContext getContext() { return message.getContext(); } @Override - public void setHeaders(Headers newHeaders) - { + public void setHeaders(Headers newHeaders) { message.setHeaders(newHeaders); } @@ -170,6 +165,7 @@ public HttpRequestMessage getOutboundRequest() { public int getStatus() { return status; } + @Override public void setStatus(int status) { this.status = status; @@ -181,8 +177,7 @@ public int getMaxBodySize() { } @Override - public Cookies parseSetCookieHeader(String setCookieValue) - { + public Cookies parseSetCookieHeader(String setCookieValue) { Cookies cookies = new Cookies(); for (Cookie cookie : CookieDecoder.decode(setCookieValue)) { cookies.add(cookie); @@ -191,8 +186,7 @@ public Cookies parseSetCookieHeader(String setCookieValue) } @Override - public boolean hasSetCookieWithName(String cookieName) - { + public boolean hasSetCookieWithName(String cookieName) { boolean has = false; for (String setCookieValue : getHeaders().getAll(HttpHeaderNames.SET_COOKIE)) { for (Cookie cookie : CookieDecoder.decode(setCookieValue)) { @@ -206,8 +200,7 @@ public boolean hasSetCookieWithName(String cookieName) } @Override - public boolean removeExistingSetCookie(String cookieName) - { + public boolean removeExistingSetCookie(String cookieName) { String cookieNamePrefix = cookieName + "="; boolean dirty = false; Headers filtered = new Headers(); @@ -219,13 +212,11 @@ public boolean removeExistingSetCookie(String cookieName) if (value.startsWith(cookieNamePrefix)) { // Don't copy it. dirty = true; - } - else { + } else { // Copy all other headers. filtered.add(hdr.getName(), hdr.getValue()); } - } - else { + } else { // Copy all other headers. filtered.add(hdr.getName(), hdr.getValue()); } @@ -238,61 +229,49 @@ public boolean removeExistingSetCookie(String cookieName) } @Override - public void addSetCookie(Cookie cookie) - { + public void addSetCookie(Cookie cookie) { getHeaders().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode(cookie)); } @Override - public void setSetCookie(Cookie cookie) - { + public void setSetCookie(Cookie cookie) { getHeaders().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode(cookie)); } @Override - public ZuulMessage clone() - { + public ZuulMessage clone() { // TODO - not sure if should be cloning the outbound request object here or not.... - HttpResponseMessageImpl clone = new HttpResponseMessageImpl(getContext().clone(), - Headers.copyOf(getHeaders()), - getOutboundRequest(), getStatus()); + HttpResponseMessageImpl clone = new HttpResponseMessageImpl( + getContext().clone(), Headers.copyOf(getHeaders()), getOutboundRequest(), getStatus()); if (getInboundResponse() != null) { clone.inboundResponse = (HttpResponseInfo) getInboundResponse().clone(); } return clone; } - protected HttpResponseInfo copyResponseInfo() - { - HttpResponseMessageImpl response = - new HttpResponseMessageImpl( - getContext(), - Headers.copyOf(getHeaders()), - getOutboundRequest(), - getStatus()); + protected HttpResponseInfo copyResponseInfo() { + HttpResponseMessageImpl response = new HttpResponseMessageImpl( + getContext(), Headers.copyOf(getHeaders()), getOutboundRequest(), getStatus()); response.setHasBody(hasBody()); return response; } @Override public String toString() { - return "HttpResponseMessageImpl{" + - "message=" + message + - ", outboundRequest=" + outboundRequest + - ", status=" + status + - ", inboundResponse=" + inboundResponse + - '}'; + return "HttpResponseMessageImpl{" + "message=" + + message + ", outboundRequest=" + + outboundRequest + ", status=" + + status + ", inboundResponse=" + + inboundResponse + '}'; } @Override - public void storeInboundResponse() - { + public void storeInboundResponse() { inboundResponse = copyResponseInfo(); } @Override - public HttpResponseInfo getInboundResponse() - { + public HttpResponseInfo getInboundResponse() { return inboundResponse; } @@ -300,8 +279,9 @@ public HttpResponseInfo getInboundResponse() public String getInfoForLogging() { HttpRequestInfo req = getInboundRequest() == null ? getOutboundRequest() : getInboundRequest(); StringBuilder sb = new StringBuilder() - .append(req.getInfoForLogging()) - .append(",proxy-status=").append(getStatus()); + .append(req.getInfoForLogging()) + .append(",proxy-status=") + .append(getStatus()); return sb.toString(); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/message/util/HttpRequestBuilder.java b/zuul-core/src/main/java/com/netflix/zuul/message/util/HttpRequestBuilder.java index f707c3e0cb..6ed152f32f 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/message/util/HttpRequestBuilder.java +++ b/zuul-core/src/main/java/com/netflix/zuul/message/util/HttpRequestBuilder.java @@ -23,6 +23,7 @@ import com.netflix.zuul.message.http.HttpRequestMessageImpl; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; + import java.util.Objects; /** @@ -86,7 +87,7 @@ public HttpRequestBuilder withHeaders(Headers requestHeaders) { } public HttpRequestBuilder withQueryParams(HttpQueryParams requestParams) { - this.queryParams = Objects.requireNonNull(requestParams); + this.queryParams = Objects.requireNonNull(requestParams); return this; } @@ -110,7 +111,7 @@ public HttpRequestMessage build() { throw new IllegalStateException("Builder must only be invoked once!"); } isBuilt = true; - return new HttpRequestMessageImpl(sessionContext, protocol, method, path, queryParams, headers, clientIp, scheme, port, - serverName); + return new HttpRequestMessageImpl( + sessionContext, protocol, method, path, queryParams, headers, clientIp, scheme, port, serverName); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/metrics/OriginStats.java b/zuul-core/src/main/java/com/netflix/zuul/metrics/OriginStats.java index b567463508..7d1f86e7ae 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/metrics/OriginStats.java +++ b/zuul-core/src/main/java/com/netflix/zuul/metrics/OriginStats.java @@ -20,8 +20,8 @@ * Date: 3/20/15 * Time: 5:55 PM */ -public interface OriginStats -{ +public interface OriginStats { public void started(); + public void completed(boolean success, long totalTimeMS); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/metrics/OriginStatsFactory.java b/zuul-core/src/main/java/com/netflix/zuul/metrics/OriginStatsFactory.java index ffa947cf45..4729815464 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/metrics/OriginStatsFactory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/metrics/OriginStatsFactory.java @@ -20,7 +20,6 @@ * Date: 3/20/15 * Time: 6:14 PM */ -public interface OriginStatsFactory -{ +public interface OriginStatsFactory { public OriginStats create(String name); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/monitoring/ConnCounter.java b/zuul-core/src/main/java/com/netflix/zuul/monitoring/ConnCounter.java index 183ad89a72..6db7296d3a 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/monitoring/ConnCounter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/monitoring/ConnCounter.java @@ -23,11 +23,12 @@ import com.netflix.zuul.netty.server.Server; import io.netty.channel.Channel; import io.netty.util.AttributeKey; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.HashMap; import java.util.Map; import java.util.Objects; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * A counter for connection stats. Not thread-safe. @@ -111,7 +112,9 @@ public void increment(String event, Attrs extraDimensions) { dimTags.put("from", lastCountKey != null ? lastCountKey : "nascent"); lastCountKey = event; - Id id = registry.createId(metricBase.name() + '.' + event).withTags(metricBase.tags()).withTags(dimTags); + Id id = registry.createId(metricBase.name() + '.' + event) + .withTags(metricBase.tags()) + .withTags(dimTags); Gauge gauge = registry.gauge(id); synchronized (getLock(id)) { diff --git a/zuul-core/src/main/java/com/netflix/zuul/monitoring/ConnTimer.java b/zuul-core/src/main/java/com/netflix/zuul/monitoring/ConnTimer.java index f03e0c82c3..9e2db678e7 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/monitoring/ConnTimer.java +++ b/zuul-core/src/main/java/com/netflix/zuul/monitoring/ConnTimer.java @@ -24,13 +24,14 @@ import com.netflix.zuul.netty.server.Server; import io.netty.channel.Channel; import io.netty.util.AttributeKey; + +import javax.annotation.Nullable; import java.time.Duration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; -import javax.annotation.Nullable; /** * A timer for connection stats. Not thread-safe. @@ -51,6 +52,7 @@ public final class ConnTimer { private final Channel chan; // TODO(carl-mastrangelo): make this changeable. private final Id metricBase; + @Nullable private final Id preciseMetricBase; @@ -114,8 +116,7 @@ public void record(Long now, String event, Attrs extraDimensions) { // it. return; } - registry.timer(buildId(metricBase, from, event, dimTags)) - .record(durationNanos, TimeUnit.NANOSECONDS); + registry.timer(buildId(metricBase, from, event, dimTags)).record(durationNanos, TimeUnit.NANOSECONDS); if (preciseMetricBase != null) { PercentileTimer.builder(registry) .withId(buildId(preciseMetricBase, from, event, dimTags)) @@ -128,6 +129,8 @@ public void record(Long now, String event, Attrs extraDimensions) { } private Id buildId(Id base, String from, String to, Map tags) { - return registry.createId(metricBase.name() + '.' + from + '-' + to).withTags(base.tags()).withTags(tags); + return registry.createId(metricBase.name() + '.' + from + '-' + to) + .withTags(base.tags()) + .withTags(tags); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/monitoring/MonitoringHelper.java b/zuul-core/src/main/java/com/netflix/zuul/monitoring/MonitoringHelper.java index 12b2653fa6..d1c2b42732 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/monitoring/MonitoringHelper.java +++ b/zuul-core/src/main/java/com/netflix/zuul/monitoring/MonitoringHelper.java @@ -39,5 +39,4 @@ public void setName(String name) {} @Override public void stopAndLog() {} } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/monitoring/Tracer.java b/zuul-core/src/main/java/com/netflix/zuul/monitoring/Tracer.java index 94a3741b69..6f2c7908d5 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/monitoring/Tracer.java +++ b/zuul-core/src/main/java/com/netflix/zuul/monitoring/Tracer.java @@ -34,5 +34,4 @@ public interface Tracer { * @param name a String value */ void setName(String name); - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/monitoring/TracerFactory.java b/zuul-core/src/main/java/com/netflix/zuul/monitoring/TracerFactory.java index 8102079990..f84fd7669c 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/monitoring/TracerFactory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/monitoring/TracerFactory.java @@ -34,9 +34,8 @@ public static final void initialize(TracerFactory f) { INSTANCE = f; } - /** - * Returns the singleton TracerFactory + * Returns the singleton TracerFactory * * @return a TracerFactory value */ @@ -48,5 +47,4 @@ public static final TracerFactory instance() { } public abstract Tracer startMicroTracer(String name); - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/ChannelUtils.java b/zuul-core/src/main/java/com/netflix/zuul/netty/ChannelUtils.java index 84f78a1872..5831970d88 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/ChannelUtils.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/ChannelUtils.java @@ -19,21 +19,19 @@ import com.netflix.zuul.passport.CurrentPassport; import io.netty.channel.Channel; -public class ChannelUtils -{ - public static String channelInfoForLogging(Channel ch) - { +public class ChannelUtils { + public static String channelInfoForLogging(Channel ch) { if (ch == null) { return "null"; } - - String channelInfo = ch.toString() + + String channelInfo = ch.toString() + ", active=" + ch.isActive() + ", open=" + ch.isOpen() + ", registered=" + ch.isRegistered() + ", writable=" + ch.isWritable() + ", id=" + ch.id(); - + CurrentPassport passport = CurrentPassport.fromChannel(ch); return "Channel: " + channelInfo + ", Passport: " + String.valueOf(passport); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/NettyRequestAttemptFactory.java b/zuul-core/src/main/java/com/netflix/zuul/netty/NettyRequestAttemptFactory.java index 3260f77763..30588650af 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/NettyRequestAttemptFactory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/NettyRequestAttemptFactory.java @@ -35,10 +35,9 @@ import static com.netflix.zuul.exception.OutboundErrorType.READ_TIMEOUT; import static com.netflix.zuul.exception.OutboundErrorType.RESET_CONNECTION; - public class NettyRequestAttemptFactory { - private final static Logger LOG = LoggerFactory.getLogger(NettyRequestAttemptFactory.class); + private static final Logger LOG = LoggerFactory.getLogger(NettyRequestAttemptFactory.class); public ErrorType mapNettyToOutboundErrorType(final Throwable t) { if (t instanceof ReadTimeoutException) { @@ -57,8 +56,10 @@ public ErrorType mapNettyToOutboundErrorType(final Throwable t) { return ((OutboundException) t).getOutboundErrorType(); } - if (t instanceof Errors.NativeIoException && Errors.ERRNO_ECONNRESET_NEGATIVE == ((Errors.NativeIoException) t).expectedErr()) { - // This is a "Connection reset by peer" which we see fairly often happening when Origin servers are overloaded. + if (t instanceof Errors.NativeIoException + && Errors.ERRNO_ECONNRESET_NEGATIVE == ((Errors.NativeIoException) t).expectedErr()) { + // This is a "Connection reset by peer" which we see fairly often happening when Origin servers are + // overloaded. LOG.warn("ERRNO_ECONNRESET_NEGATIVE mapped to RESET_CONNECTION", t); return RESET_CONNECTION; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/RequestCancelledEvent.java b/zuul-core/src/main/java/com/netflix/zuul/netty/RequestCancelledEvent.java index f50606d445..20c9b585d7 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/RequestCancelledEvent.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/RequestCancelledEvent.java @@ -21,6 +21,4 @@ * Date: 4/13/17 * Time: 6:09 PM */ -public class RequestCancelledEvent -{ -} +public class RequestCancelledEvent {} diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/SpectatorUtils.java b/zuul-core/src/main/java/com/netflix/zuul/netty/SpectatorUtils.java index 1fc192443d..60eea2fb12 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/SpectatorUtils.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/SpectatorUtils.java @@ -23,8 +23,7 @@ import com.netflix.spectator.api.Timer; public final class SpectatorUtils { - private SpectatorUtils() { - } + private SpectatorUtils() {} public static Counter newCounter(String name, String id) { return Spectator.globalRegistry().counter(name, "id", id); diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/BasicRequestStat.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/BasicRequestStat.java index 10d2b38f2a..2bf347f970 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/BasicRequestStat.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/BasicRequestStat.java @@ -23,7 +23,6 @@ import java.util.concurrent.TimeUnit; - /** * @author michaels */ diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ClientChannelManager.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ClientChannelManager.java index 358fd1cb85..25e9091725 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ClientChannelManager.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ClientChannelManager.java @@ -16,7 +16,6 @@ package com.netflix.zuul.netty.connectionpool; - import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.passport.CurrentPassport; import io.netty.channel.EventLoop; @@ -30,8 +29,7 @@ * Date: 7/8/16 * Time: 12:36 PM */ -public interface ClientChannelManager -{ +public interface ClientChannelManager { void init(); boolean isAvailable(); @@ -64,5 +62,4 @@ Promise acquire( int getConnsInUse(); ConnectionPoolConfig getConfig(); - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ClientTimeoutHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ClientTimeoutHandler.java index ca02939a1d..cef832a0b4 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ClientTimeoutHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ClientTimeoutHandler.java @@ -22,10 +22,11 @@ import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.LastHttpContent; import io.netty.util.AttributeKey; -import java.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.time.Duration; + /** * Client Timeout Handler * @@ -35,18 +36,19 @@ public final class ClientTimeoutHandler { private static final Logger LOG = LoggerFactory.getLogger(ClientTimeoutHandler.class); - public static final AttributeKey ORIGIN_RESPONSE_READ_TIMEOUT = AttributeKey.newInstance("originResponseReadTimeout"); + public static final AttributeKey ORIGIN_RESPONSE_READ_TIMEOUT = + AttributeKey.newInstance("originResponseReadTimeout"); public static final class InboundHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { if (msg instanceof LastHttpContent) { - LOG.debug("[{}] Removing read timeout handler", ctx.channel().id()); + LOG.debug( + "[{}] Removing read timeout handler", ctx.channel().id()); PooledConnection.getFromChannel(ctx.channel()).removeReadTimeoutHandler(); } - } - finally { + } finally { super.channelRead(ctx, msg); } } @@ -56,15 +58,18 @@ public static final class OutboundHandler extends ChannelOutboundHandlerAdapter @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { try { - final Duration timeout = ctx.channel().attr(ORIGIN_RESPONSE_READ_TIMEOUT).get(); + final Duration timeout = + ctx.channel().attr(ORIGIN_RESPONSE_READ_TIMEOUT).get(); if (timeout != null && msg instanceof LastHttpContent) { promise.addListener(e -> { - LOG.debug("[{}] Adding read timeout handler: {}", ctx.channel().id(), timeout.toMillis()); + LOG.debug( + "[{}] Adding read timeout handler: {}", + ctx.channel().id(), + timeout.toMillis()); PooledConnection.getFromChannel(ctx.channel()).startReadTimeoutHandler(timeout); }); } - } - finally { + } finally { super.write(ctx, msg, promise); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolConfigImpl.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolConfigImpl.java index 7291822686..119f6cc7a2 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolConfigImpl.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolConfigImpl.java @@ -21,6 +21,7 @@ import com.netflix.config.CachedDynamicBooleanProperty; import com.netflix.config.CachedDynamicIntProperty; import com.netflix.zuul.origins.OriginName; + import java.util.Objects; /** @@ -45,7 +46,6 @@ public class ConnectionPoolConfigImpl implements ConnectionPoolConfig { private final CachedDynamicIntProperty WRITE_BUFFER_LOW_WATER_MARK; private final CachedDynamicBooleanProperty AUTO_READ; - public ConnectionPoolConfigImpl(final OriginName originName, IClientConfig clientConfig) { this.originName = Objects.requireNonNull(originName, "originName"); String niwsClientName = originName.getNiwsClientName(); @@ -58,12 +58,10 @@ public ConnectionPoolConfigImpl(final OriginName originName, IClientConfig clien this.PER_SERVER_WATERLINE = new CachedDynamicIntProperty(niwsClientName + ".netty.client.perServerWaterline", 4); - this.SOCKET_KEEP_ALIVE = - new CachedDynamicBooleanProperty(niwsClientName + ".netty.client.TcpKeepAlive", false); - this.TCP_NO_DELAY = - new CachedDynamicBooleanProperty(niwsClientName + ".netty.client.TcpNoDelay", false); + this.SOCKET_KEEP_ALIVE = new CachedDynamicBooleanProperty(niwsClientName + ".netty.client.TcpKeepAlive", false); + this.TCP_NO_DELAY = new CachedDynamicBooleanProperty(niwsClientName + ".netty.client.TcpNoDelay", false); - //TODO(argha-c): Document why these values were chosen, as opposed to defaults of 32k/64k + // TODO(argha-c): Document why these values were chosen, as opposed to defaults of 32k/64k this.WRITE_BUFFER_HIGH_WATER_MARK = new CachedDynamicIntProperty(niwsClientName + ".netty.client.WriteBufferHighWaterMark", 32 * 1024); this.WRITE_BUFFER_LOW_WATER_MARK = @@ -87,20 +85,20 @@ public int getMaxRequestsPerConnection() { } @Override - public int maxConnectionsPerHost() - { - return clientConfig.getPropertyAsInteger(IClientConfigKey.Keys.MaxConnectionsPerHost, DEFAULT_MAX_CONNS_PER_HOST); + public int maxConnectionsPerHost() { + return clientConfig.getPropertyAsInteger( + IClientConfigKey.Keys.MaxConnectionsPerHost, DEFAULT_MAX_CONNS_PER_HOST); } @Override - public int perServerWaterline() - { + public int perServerWaterline() { return PER_SERVER_WATERLINE.get(); } @Override public int getIdleTimeout() { - return clientConfig.getPropertyAsInteger(IClientConfigKey.Keys.ConnIdleEvictTimeMilliSeconds, DEFAULT_IDLE_TIMEOUT); + return clientConfig.getPropertyAsInteger( + IClientConfigKey.Keys.ConnIdleEvictTimeMilliSeconds, DEFAULT_IDLE_TIMEOUT); } @Override @@ -139,15 +137,12 @@ public boolean getNettyAutoRead() { } @Override - public boolean isSecure() - { + public boolean isSecure() { return clientConfig.getPropertyAsBoolean(IClientConfigKey.Keys.IsSecure, false); } @Override - public boolean useIPAddrForServer() - { + public boolean useIPAddrForServer() { return clientConfig.getPropertyAsBoolean(IClientConfigKey.Keys.UseIPAddrForServer, true); } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolHandler.java index d7ef4b7a41..3a51aa3361 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolHandler.java @@ -24,7 +24,6 @@ import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpHeaderNames; -import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.timeout.IdleStateEvent; import org.slf4j.Logger; @@ -40,12 +39,11 @@ * Time: 1:57 PM */ @ChannelHandler.Sharable -public class ConnectionPoolHandler extends ChannelDuplexHandler -{ +public class ConnectionPoolHandler extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(ConnectionPoolHandler.class); public static final String METRIC_PREFIX = "connectionpool"; - + private final OriginName originName; private final Counter idleCounter; private final Counter inactiveCounter; @@ -71,11 +69,12 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc if (evt instanceof IdleStateEvent) { // Log some info about this. idleCounter.increment(); - final String msg = "Origin channel for origin - " + originName + " - idle timeout has fired. " + ChannelUtils.channelInfoForLogging(ctx.channel()); + final String msg = "Origin channel for origin - " + originName + " - idle timeout has fired. " + + ChannelUtils.channelInfoForLogging(ctx.channel()); closeConnection(ctx, msg); - } - else if (evt instanceof CompleteEvent) { - // The HttpLifecycleChannelHandler instance will fire this event when either a response has finished being written, or + } else if (evt instanceof CompleteEvent) { + // The HttpLifecycleChannelHandler instance will fire this event when either a response has finished being + // written, or // the channel is no longer active or disconnected. // Return the connection to pool. CompleteEvent completeEvt = (CompleteEvent) evt; @@ -84,7 +83,8 @@ else if (evt instanceof CompleteEvent) { final PooledConnection conn = PooledConnection.getFromChannel(ctx.channel()); if (conn != null) { if ("close".equalsIgnoreCase(getConnectionHeader(completeEvt))) { - final String msg = "Origin channel for origin - " + originName + " - completed because of expired keep-alive. " + final String msg = "Origin channel for origin - " + originName + + " - completed because of expired keep-alive. " + ChannelUtils.channelInfoForLogging(ctx.channel()); headerCloseCounter.increment(); closeConnection(ctx, msg); @@ -103,11 +103,12 @@ else if (evt instanceof CompleteEvent) { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - //super.exceptionCaught(ctx, cause); + // super.exceptionCaught(ctx, cause); errorCounter.increment(); final String mesg = "Exception on Origin channel for origin - " + originName + ". " - + ChannelUtils.channelInfoForLogging(ctx.channel()) + " - " + - cause.getClass().getCanonicalName() + ": " + cause.getMessage(); + + ChannelUtils.channelInfoForLogging(ctx.channel()) + " - " + + cause.getClass().getCanonicalName() + + ": " + cause.getMessage(); closeConnection(ctx, mesg); if (LOG.isDebugEnabled()) { @@ -117,7 +118,7 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { - //super.channelInactive(ctx); + // super.channelInactive(ctx); inactiveCounter.increment(); final String msg = "Client channel for origin - " + originName + " - inactive event has fired. " + ChannelUtils.channelInfoForLogging(ctx.channel()); @@ -132,8 +133,7 @@ private void closeConnection(ChannelHandlerContext ctx, String msg) { LOG.debug(msg, conn); } flagCloseAndReleaseConnection(conn); - } - else { + } else { // If somehow we don't have a PooledConnection instance attached to this channel, then // close the channel directly. LOG.warn("{} But no PooledConnection attribute. So just closing Channel.", msg); @@ -144,8 +144,7 @@ private void closeConnection(ChannelHandlerContext ctx, String msg) { private void flagCloseAndReleaseConnection(PooledConnection pooledConnection) { if (pooledConnection.isInPool()) { pooledConnection.closeAndRemoveFromPool(); - } - else { + } else { pooledConnection.flagShouldClose(); pooledConnection.release(); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/DefaultClientChannelManager.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/DefaultClientChannelManager.java index 9536706b23..0dbbea6e8f 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/DefaultClientChannelManager.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/DefaultClientChannelManager.java @@ -26,13 +26,13 @@ import com.netflix.zuul.discovery.DynamicServerResolver; import com.netflix.zuul.discovery.ResolverResult; import com.netflix.zuul.exception.OutboundErrorType; -import com.netflix.zuul.resolver.Resolver; -import com.netflix.zuul.resolver.ResolverListener; import com.netflix.zuul.netty.SpectatorUtils; import com.netflix.zuul.netty.insights.PassportStateHttpClientHandler; import com.netflix.zuul.netty.server.OriginResponseReceiver; import com.netflix.zuul.origins.OriginName; import com.netflix.zuul.passport.CurrentPassport; +import com.netflix.zuul.resolver.Resolver; +import com.netflix.zuul.resolver.ResolverListener; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; @@ -40,6 +40,10 @@ import io.netty.channel.EventLoop; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.Promise; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; @@ -49,9 +53,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import javax.annotation.Nullable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * User: michaels@netflix.com @@ -70,7 +71,8 @@ public class DefaultClientChannelManager implements ClientChannelManager { private final OriginName originName; - private static final Throwable SHUTTING_DOWN_ERR = new IllegalStateException("ConnectionPool is shutting down now."); + private static final Throwable SHUTTING_DOWN_ERR = + new IllegalStateException("ConnectionPool is shutting down now."); private volatile boolean shuttingDown = false; private final Counter createNewConnCounter; @@ -98,14 +100,15 @@ public class DefaultClientChannelManager implements ClientChannelManager { public static final String IDLE_STATE_HANDLER_NAME = "idleStateHandler"; - public DefaultClientChannelManager( - OriginName originName, IClientConfig clientConfig, Registry spectatorRegistry) { + public DefaultClientChannelManager(OriginName originName, IClientConfig clientConfig, Registry spectatorRegistry) { this(originName, clientConfig, new DynamicServerResolver(clientConfig), spectatorRegistry); } public DefaultClientChannelManager( - OriginName originName, IClientConfig clientConfig, - Resolver resolver, Registry spectatorRegistry) { + OriginName originName, + IClientConfig clientConfig, + Resolver resolver, + Registry spectatorRegistry) { this.originName = Objects.requireNonNull(originName, "originName"); this.dynamicServerResolver = resolver; @@ -122,23 +125,26 @@ public DefaultClientChannelManager( this.createConnFailedCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_create_fail", metricId); this.closeConnCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_close", metricId); - this.closeAbovePoolHighWaterMarkCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_closeAbovePoolHighWaterMark", metricId); - this.closeExpiredConnLifetimeCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_closeExpiredConnLifetime", metricId); + this.closeAbovePoolHighWaterMarkCounter = + SpectatorUtils.newCounter(METRIC_PREFIX + "_closeAbovePoolHighWaterMark", metricId); + this.closeExpiredConnLifetimeCounter = + SpectatorUtils.newCounter(METRIC_PREFIX + "_closeExpiredConnLifetime", metricId); this.requestConnCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_request", metricId); this.reuseConnCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_reuse", metricId); this.releaseConnCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_release", metricId); this.alreadyClosedCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_alreadyClosed", metricId); this.connTakenFromPoolIsNotOpen = SpectatorUtils.newCounter(METRIC_PREFIX + "_fromPoolIsClosed", metricId); - this.maxConnsPerHostExceededCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_maxConnsPerHostExceeded", metricId); + this.maxConnsPerHostExceededCounter = + SpectatorUtils.newCounter(METRIC_PREFIX + "_maxConnsPerHostExceeded", metricId); this.closeWrtBusyConnCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_closeWrtBusyConnCounter", metricId); - this.connEstablishTimer = PercentileTimer.get(spectatorRegistry, spectatorRegistry.createId(METRIC_PREFIX + "_createTiming", "id", metricId)); + this.connEstablishTimer = PercentileTimer.get( + spectatorRegistry, spectatorRegistry.createId(METRIC_PREFIX + "_createTiming", "id", metricId)); this.connsInPool = SpectatorUtils.newGauge(METRIC_PREFIX + "_inPool", metricId, new AtomicInteger()); this.connsInUse = SpectatorUtils.newGauge(METRIC_PREFIX + "_inUse", metricId, new AtomicInteger()); } @Override - public void init() - { + public void init() { dynamicServerResolver.setListener(new ServerPoolListener()); // Load channel initializer and conn factory. // We don't do this within the constructor because some subclass may not be initialized until post-construct. @@ -146,12 +152,13 @@ public void init() this.clientConnFactory = createNettyClientConnectionFactory(connPoolConfig, channelInitializer); } - protected OriginChannelInitializer createChannelInitializer(IClientConfig clientConfig, ConnectionPoolConfig connPoolConfig, Registry registry) { + protected OriginChannelInitializer createChannelInitializer( + IClientConfig clientConfig, ConnectionPoolConfig connPoolConfig, Registry registry) { return new DefaultOriginChannelInitializer(connPoolConfig, registry); } - protected NettyClientConnectionFactory createNettyClientConnectionFactory(ConnectionPoolConfig connPoolConfig, - ChannelInitializer clientConnInitializer) { + protected NettyClientConnectionFactory createNettyClientConnectionFactory( + ConnectionPoolConfig connPoolConfig, ChannelInitializer clientConnInitializer) { return new NettyClientConnectionFactory(connPoolConfig, clientConnInitializer); } @@ -216,40 +223,44 @@ public boolean release(final PooledConnection conn) { // TODO(argha-c): Document what is a reasonable default here, and the class of origins that optimizes for final boolean connExpiredLifetime = conn.getUsageCount() > connPoolConfig.getMaxRequestsPerConnection(); if (conn.isShouldClose() || connExpiredLifetime) { - // Close and discard the connection, as it has been flagged (possibly due to receiving a non-channel error like a 503). + // Close and discard the connection, as it has been flagged (possibly due to receiving a non-channel error + // like a 503). conn.setInPool(false); conn.close(); if (connExpiredLifetime) { closeExpiredConnLifetimeCounter.increment(); - LOG.debug("[{}] closing conn lifetime expired, usage: {}", conn.getChannel().id(), conn.getUsageCount()); + LOG.debug( + "[{}] closing conn lifetime expired, usage: {}", + conn.getChannel().id(), + conn.getUsageCount()); } else { - LOG.debug("[{}] closing conn flagged to be closed", conn.getChannel().id()); + LOG.debug( + "[{}] closing conn flagged to be closed", + conn.getChannel().id()); } - } - else if (discoveryResult.isCircuitBreakerTripped()) { - LOG.debug("[{}] closing conn, server circuit breaker tripped", conn.getChannel().id()); + } else if (discoveryResult.isCircuitBreakerTripped()) { + LOG.debug( + "[{}] closing conn, server circuit breaker tripped", + conn.getChannel().id()); // Don't put conns for currently circuit-tripped servers back into the pool. conn.setInPool(false); conn.close(); - } - else if (!conn.isActive()) { + } else if (!conn.isActive()) { LOG.debug("[{}] conn inactive, cleaning up", conn.getChannel().id()); // Connection is already closed, so discard. alreadyClosedCounter.increment(); // make sure to decrement OpenConnectionCounts conn.updateServerStats(); conn.setInPool(false); - } - else { + } else { releaseHandlers(conn); // Attempt to return connection to the pool. IConnectionPool pool = perServerPools.get(discoveryResult); if (pool != null) { released = pool.release(conn); - } - else { + } else { // The pool for this server no longer exists (maybe due to it falling out of // discovery). conn.setInPool(false); @@ -269,8 +280,10 @@ protected void releaseHandlers(PooledConnection conn) { // The Outbound handler is always after the inbound handler, so look for it. ChannelHandlerContext passportStateHttpClientHandlerCtx = pipeline.context(PassportStateHttpClientHandler.OutboundHandler.class); - pipeline.addAfter(passportStateHttpClientHandlerCtx.name(), IDLE_STATE_HANDLER_NAME, - new IdleStateHandler(0, 0, connPoolConfig.getIdleTimeout(), TimeUnit.MILLISECONDS)); + pipeline.addAfter( + passportStateHttpClientHandlerCtx.name(), + IDLE_STATE_HANDLER_NAME, + new IdleStateHandler(0, 0, connPoolConfig.getIdleTimeout(), TimeUnit.MILLISECONDS)); } public static void removeHandlerFromPipeline(final String handlerName, final ChannelPipeline pipeline) { @@ -292,8 +305,7 @@ public boolean remove(PooledConnection conn) { IConnectionPool pool = perServerPools.get(conn.getServer()); if (pool != null) { return pool.remove(conn); - } - else { + } else { // The pool for this server no longer exists (maybe due to it failling out of // discovery). conn.setInPool(false); @@ -324,46 +336,73 @@ public Promise acquire( // Choose the next load-balanced server. final DiscoveryResult chosenServer = dynamicServerResolver.resolve(key); - //(argha-c): Always ensure the selected server is updated, since the call chain relies on this mutation. + // (argha-c): Always ensure the selected server is updated, since the call chain relies on this mutation. selectedServer.set(chosenServer); if (chosenServer == DiscoveryResult.EMPTY) { Promise promise = eventLoop.newPromise(); - promise.setFailure(new OriginConnectException("No servers available", OutboundErrorType.NO_AVAILABLE_SERVERS)); + promise.setFailure( + new OriginConnectException("No servers available", OutboundErrorType.NO_AVAILABLE_SERVERS)); return promise; } - - // Now get the connection-pool for this server. IConnectionPool pool = perServerPools.computeIfAbsent(chosenServer, s -> { SocketAddress finalServerAddr = pickAddress(chosenServer); final ClientChannelManager clientChannelMgr = this; - PooledConnectionFactory pcf = createPooledConnectionFactory(chosenServer, clientChannelMgr, closeConnCounter, closeWrtBusyConnCounter); + PooledConnectionFactory pcf = createPooledConnectionFactory( + chosenServer, clientChannelMgr, closeConnCounter, closeWrtBusyConnCounter); // Create a new pool for this server. - return createConnectionPool(chosenServer, finalServerAddr, clientConnFactory, pcf, connPoolConfig, - clientConfig, createNewConnCounter, createConnSucceededCounter, createConnFailedCounter, - requestConnCounter, reuseConnCounter, connTakenFromPoolIsNotOpen, - closeAbovePoolHighWaterMarkCounter, maxConnsPerHostExceededCounter, - connEstablishTimer, connsInPool, connsInUse); + return createConnectionPool( + chosenServer, + finalServerAddr, + clientConnFactory, + pcf, + connPoolConfig, + clientConfig, + createNewConnCounter, + createConnSucceededCounter, + createConnFailedCounter, + requestConnCounter, + reuseConnCounter, + connTakenFromPoolIsNotOpen, + closeAbovePoolHighWaterMarkCounter, + maxConnsPerHostExceededCounter, + connEstablishTimer, + connsInPool, + connsInUse); }); return pool.acquire(eventLoop, passport, selectedHostAddr); } protected PooledConnectionFactory createPooledConnectionFactory( - DiscoveryResult chosenServer, ClientChannelManager clientChannelMgr, Counter closeConnCounter, + DiscoveryResult chosenServer, + ClientChannelManager clientChannelMgr, + Counter closeConnCounter, Counter closeWrtBusyConnCounter) { - return ch -> new PooledConnection(ch, chosenServer, clientChannelMgr, closeConnCounter, closeWrtBusyConnCounter); + return ch -> + new PooledConnection(ch, chosenServer, clientChannelMgr, closeConnCounter, closeWrtBusyConnCounter); } protected IConnectionPool createConnectionPool( - DiscoveryResult discoveryResult, SocketAddress serverAddr, - NettyClientConnectionFactory clientConnFactory, PooledConnectionFactory pcf, - ConnectionPoolConfig connPoolConfig, IClientConfig clientConfig, Counter createNewConnCounter, - Counter createConnSucceededCounter, Counter createConnFailedCounter, Counter requestConnCounter, - Counter reuseConnCounter, Counter connTakenFromPoolIsNotOpen, Counter closeAbovePoolHighWaterMarkCounter, Counter maxConnsPerHostExceededCounter, - PercentileTimer connEstablishTimer, AtomicInteger connsInPool, AtomicInteger connsInUse) { + DiscoveryResult discoveryResult, + SocketAddress serverAddr, + NettyClientConnectionFactory clientConnFactory, + PooledConnectionFactory pcf, + ConnectionPoolConfig connPoolConfig, + IClientConfig clientConfig, + Counter createNewConnCounter, + Counter createConnSucceededCounter, + Counter createConnFailedCounter, + Counter requestConnCounter, + Counter reuseConnCounter, + Counter connTakenFromPoolIsNotOpen, + Counter closeAbovePoolHighWaterMarkCounter, + Counter maxConnsPerHostExceededCounter, + PercentileTimer connEstablishTimer, + AtomicInteger connsInPool, + AtomicInteger connsInUse) { return new PerServerConnectionPool( discoveryResult, serverAddr, @@ -381,15 +420,16 @@ protected IConnectionPool createConnectionPool( maxConnsPerHostExceededCounter, connEstablishTimer, connsInPool, - connsInUse - ); + connsInUse); } final class ServerPoolListener implements ResolverListener { @Override public void onChange(List removedSet) { if (!removedSet.isEmpty()) { - LOG.debug("Removing connection pools for missing servers. name = {}. {} servers gone.", originName, + LOG.debug( + "Removing connection pools for missing servers. name = {}. {} servers gone.", + originName, removedSet.size()); for (DiscoveryResult s : removedSet) { IConnectionPool pool = perServerPools.remove(s); @@ -419,8 +459,8 @@ protected ConcurrentHashMap getPerServerPools( static SocketAddress pickAddressInternal(ResolverResult chosenServer, @Nullable OriginName originName) { String rawHost; int port; - rawHost = chosenServer.getHost(); - port = chosenServer.getPort(); + rawHost = chosenServer.getHost(); + port = chosenServer.getPort(); InetSocketAddress serverAddr; try { InetAddress ipAddr = InetAddresses.forString(rawHost); @@ -428,8 +468,7 @@ static SocketAddress pickAddressInternal(ResolverResult chosenServer, @Nullable } catch (IllegalArgumentException e1) { LOG.warn("NettyClientConnectionFactory got an unresolved address, addr: {}", rawHost); Counter unresolvedDiscoveryHost = SpectatorUtils.newCounter( - "unresolvedDiscoveryHost", - originName == null ? "unknownOrigin" : originName.getTarget()); + "unresolvedDiscoveryHost", originName == null ? "unknownOrigin" : originName.getTarget()); unresolvedDiscoveryHost.increment(); try { serverAddr = new InetSocketAddress(rawHost, port); @@ -448,5 +487,4 @@ static SocketAddress pickAddressInternal(ResolverResult chosenServer, @Nullable protected SocketAddress pickAddress(DiscoveryResult chosenServer) { return pickAddressInternal(chosenServer, connPoolConfig.getOriginName()); } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/DefaultOriginChannelInitializer.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/DefaultOriginChannelInitializer.java index cd4646081f..6ad3fc075a 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/DefaultOriginChannelInitializer.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/DefaultOriginChannelInitializer.java @@ -68,13 +68,14 @@ protected void initChannel(Channel ch) throws Exception { pipeline.addLast("ssl", sslContext.newHandler(ch.alloc())); } - pipeline.addLast(HTTP_CODEC_HANDLER_NAME, new HttpClientCodec( - BaseZuulChannelInitializer.MAX_INITIAL_LINE_LENGTH.get(), - BaseZuulChannelInitializer.MAX_HEADER_SIZE.get(), - BaseZuulChannelInitializer.MAX_CHUNK_SIZE.get(), - false, - false - )); + pipeline.addLast( + HTTP_CODEC_HANDLER_NAME, + new HttpClientCodec( + BaseZuulChannelInitializer.MAX_INITIAL_LINE_LENGTH.get(), + BaseZuulChannelInitializer.MAX_HEADER_SIZE.get(), + BaseZuulChannelInitializer.MAX_CHUNK_SIZE.get(), + false, + false)); pipeline.addLast(new PassportStateHttpClientHandler.InboundHandler()); pipeline.addLast(new PassportStateHttpClientHandler.OutboundHandler()); pipeline.addLast(ORIGIN_NETTY_LOGGER, nettyLogger); @@ -105,11 +106,9 @@ protected SslContext getClientSslContext(Registry spectatorRegistry) { * * @param pipeline the channel pipeline */ - protected void addMethodBindingHandler(ChannelPipeline pipeline) { - } + protected void addMethodBindingHandler(ChannelPipeline pipeline) {} public HttpMetricsChannelHandler getHttpMetricsHandler() { return httpMetricsHandler; } } - diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/IConnectionPool.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/IConnectionPool.java index d2a0e0440e..c63ffa7a3c 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/IConnectionPool.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/IConnectionPool.java @@ -28,20 +28,25 @@ * Date: 7/8/16 * Time: 1:10 PM */ -public interface IConnectionPool -{ +public interface IConnectionPool { Promise acquire( EventLoop eventLoop, CurrentPassport passport, AtomicReference selectedHostAddr); + boolean release(PooledConnection conn); + boolean remove(PooledConnection conn); + void shutdown(); default void drain() { shutdown(); } + boolean isAvailable(); + int getConnsInUse(); + int getConnsInPool(); - ConnectionPoolConfig getConfig(); + ConnectionPoolConfig getConfig(); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/NettyClientConnectionFactory.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/NettyClientConnectionFactory.java index ecac84fb1d..8d63a54097 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/NettyClientConnectionFactory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/NettyClientConnectionFactory.java @@ -25,6 +25,7 @@ import io.netty.channel.ChannelOption; import io.netty.channel.EventLoop; import io.netty.channel.WriteBufferWaterMark; + import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Objects; @@ -37,13 +38,14 @@ public final class NettyClientConnectionFactory { private final ConnectionPoolConfig connPoolConfig; private final ChannelInitializer channelInitializer; - NettyClientConnectionFactory(final ConnectionPoolConfig connPoolConfig, - final ChannelInitializer channelInitializer) { + NettyClientConnectionFactory( + final ConnectionPoolConfig connPoolConfig, final ChannelInitializer channelInitializer) { this.connPoolConfig = connPoolConfig; this.channelInitializer = channelInitializer; } - public ChannelFuture connect(final EventLoop eventLoop, SocketAddress socketAddress, CurrentPassport passport, IConnectionPool pool) { + public ChannelFuture connect( + final EventLoop eventLoop, SocketAddress socketAddress, CurrentPassport passport, IConnectionPool pool) { Objects.requireNonNull(socketAddress, "socketAddress"); if (socketAddress instanceof InetSocketAddress) { // This should be checked by the ClientConnectionManager @@ -60,8 +62,10 @@ public ChannelFuture connect(final EventLoop eventLoop, SocketAddress socketAddr .option(ChannelOption.TCP_NODELAY, connPoolConfig.getTcpNoDelay()) .option(ChannelOption.SO_SNDBUF, connPoolConfig.getTcpSendBufferSize()) .option(ChannelOption.SO_RCVBUF, connPoolConfig.getTcpReceiveBufferSize()) - .option(ChannelOption.WRITE_BUFFER_WATER_MARK, - new WriteBufferWaterMark(connPoolConfig.getNettyWriteBufferLowWaterMark(), + .option( + ChannelOption.WRITE_BUFFER_WATER_MARK, + new WriteBufferWaterMark( + connPoolConfig.getNettyWriteBufferLowWaterMark(), connPoolConfig.getNettyWriteBufferHighWaterMark())) .option(ChannelOption.AUTO_READ, connPoolConfig.getNettyAutoRead()) .remoteAddress(socketAddress); diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/OriginChannelInitializer.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/OriginChannelInitializer.java index 78998cbae9..1c9c032419 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/OriginChannelInitializer.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/OriginChannelInitializer.java @@ -16,9 +16,9 @@ package com.netflix.zuul.netty.connectionpool; +import com.netflix.netty.common.metrics.HttpMetricsChannelHandler; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; -import com.netflix.netty.common.metrics.HttpMetricsChannelHandler; /** * Origin Channel Initializer diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/OriginConnectException.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/OriginConnectException.java index 129fbf67bb..a042c0b54b 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/OriginConnectException.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/OriginConnectException.java @@ -16,7 +16,6 @@ package com.netflix.zuul.netty.connectionpool; - import com.netflix.zuul.exception.ErrorType; /** @@ -41,5 +40,4 @@ public OriginConnectException(String message, Throwable cause, ErrorType errorTy public ErrorType getErrorType() { return errorType; } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PerServerConnectionPool.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PerServerConnectionPool.java index f7fc599098..2d3478b147 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PerServerConnectionPool.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PerServerConnectionPool.java @@ -23,33 +23,30 @@ import com.netflix.zuul.exception.OutboundErrorType; import com.netflix.zuul.passport.CurrentPassport; import com.netflix.zuul.passport.PassportState; -import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoop; import io.netty.util.AttributeKey; import io.netty.util.concurrent.Promise; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; -import java.util.Collections; import java.util.Deque; -import java.util.Iterator; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import javax.annotation.Nullable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * User: michaels@netflix.com * Date: 7/8/16 * Time: 1:09 PM */ -public class PerServerConnectionPool implements IConnectionPool -{ +public class PerServerConnectionPool implements IConnectionPool { private static final Logger LOG = LoggerFactory.getLogger(PerServerConnectionPool.class); public static final AttributeKey CHANNEL_ATTR = AttributeKey.newInstance("_connection_pool"); private final ConcurrentHashMap> connectionsPerEventLoop = @@ -65,7 +62,7 @@ public class PerServerConnectionPool implements IConnectionPool private final Counter createNewConnCounter; private final Counter createConnSucceededCounter; private final Counter createConnFailedCounter; - + private final Counter requestConnCounter; private final Counter reuseConnCounter; private final Counter connTakenFromPoolIsNotOpen; @@ -75,8 +72,8 @@ public class PerServerConnectionPool implements IConnectionPool private final AtomicInteger connsInPool; private final AtomicInteger connsInUse; - /** - * This is the count of connections currently in progress of being established. + /** + * This is the count of connections currently in progress of being established. * They will only be added to connsInUse _after_ establishment has completed. */ private final AtomicInteger connCreationsInProgress; @@ -119,30 +116,26 @@ public PerServerConnectionPool( this.connEstablishTimer = connEstablishTimer; this.connsInPool = connsInPool; this.connsInUse = connsInUse; - + this.connCreationsInProgress = new AtomicInteger(0); } @Override - public ConnectionPoolConfig getConfig() - { + public ConnectionPoolConfig getConfig() { return this.config; } - public IClientConfig getNiwsClientConfig() - { + public IClientConfig getNiwsClientConfig() { return niwsClientConfig; } @Override - public boolean isAvailable() - { + public boolean isAvailable() { return !draining; } /** function to run when a connection is acquired before returning it to caller. */ - protected void onAcquire(final PooledConnection conn, CurrentPassport passport) - { + protected void onAcquire(final PooledConnection conn, CurrentPassport passport) { passport.setOnChannel(conn.getChannel()); removeIdleStateHandler(conn); @@ -151,20 +144,22 @@ protected void onAcquire(final PooledConnection conn, CurrentPassport passport) } protected void removeIdleStateHandler(PooledConnection conn) { - DefaultClientChannelManager.removeHandlerFromPipeline(DefaultClientChannelManager.IDLE_STATE_HANDLER_NAME, conn.getChannel().pipeline()); + DefaultClientChannelManager.removeHandlerFromPipeline( + DefaultClientChannelManager.IDLE_STATE_HANDLER_NAME, + conn.getChannel().pipeline()); } @Override public Promise acquire( EventLoop eventLoop, CurrentPassport passport, AtomicReference selectedHostAddr) { - if(draining) { + if (draining) { throw new IllegalStateException("Attempt to acquire connection while draining"); } requestConnCounter.increment(); server.incrementActiveRequestsCount(); - + Promise promise = eventLoop.newPromise(); // Try getting a connection from the pool. @@ -177,8 +172,7 @@ public Promise acquire( onAcquire(conn, passport); initPooledConnection(conn, promise); selectedHostAddr.set(getSelectedHostString(serverAddr)); - } - else { + } else { // connection pool empty, create new connection using client connection factory. tryMakingNewConnection(eventLoop, promise, passport, selectedHostAddr); } @@ -186,8 +180,7 @@ public Promise acquire( return promise; } - public PooledConnection tryGettingFromConnectionPool(EventLoop eventLoop) - { + public PooledConnection tryGettingFromConnectionPool(EventLoop eventLoop) { PooledConnection conn; Deque connections = getPoolForEventLoop(eventLoop); while ((conn = connections.poll()) != null) { @@ -200,8 +193,7 @@ public PooledConnection tryGettingFromConnectionPool(EventLoop eventLoop) connsInUse.incrementAndGet(); connsInPool.decrementAndGet(); return conn; - } - else { + } else { connTakenFromPoolIsNotOpen.increment(); connsInPool.decrementAndGet(); conn.close(); @@ -219,8 +211,7 @@ protected void initPooledConnection(PooledConnection conn, Promise getPoolForEventLoop(EventLoop eventLoop) - { + protected Deque getPoolForEventLoop(EventLoop eventLoop) { // We don't want to block under any circumstances, so can't use CHM.computeIfAbsent(). // Instead we accept the slight inefficiency of an unnecessary instantiation of a ConcurrentLinkedDeque. @@ -233,7 +224,9 @@ protected Deque getPoolForEventLoop(EventLoop eventLoop) } protected void tryMakingNewConnection( - EventLoop eventLoop, Promise promise, CurrentPassport passport, + EventLoop eventLoop, + Promise promise, + CurrentPassport passport, AtomicReference selectedHostAddr) { // Enforce MaxConnectionsPerHost config. int maxConnectionsPerHost = config.maxConnectionsPerHost(); @@ -241,9 +234,15 @@ protected void tryMakingNewConnection( if (maxConnectionsPerHost != -1 && openAndOpeningConnectionCount >= maxConnectionsPerHost) { maxConnsPerHostExceededCounter.increment(); promise.setFailure(new OriginConnectException( - "maxConnectionsPerHost=" + maxConnectionsPerHost + ", connectionsPerHost=" + openAndOpeningConnectionCount, + "maxConnectionsPerHost=" + maxConnectionsPerHost + ", connectionsPerHost=" + + openAndOpeningConnectionCount, OutboundErrorType.ORIGIN_SERVER_MAX_CONNS)); - LOG.warn("Unable to create new connection because at MaxConnectionsPerHost! maxConnectionsPerHost={}, connectionsPerHost={}, host={}origin={}", maxConnectionsPerHost, openAndOpeningConnectionCount, server.getServerId(), config.getOriginName()); + LOG.warn( + "Unable to create new connection because at MaxConnectionsPerHost! maxConnectionsPerHost={}, connectionsPerHost={}, host={}origin={}", + maxConnectionsPerHost, + openAndOpeningConnectionCount, + server.getServerId(), + config.getOriginName()); return; } @@ -258,22 +257,22 @@ protected void tryMakingNewConnection( if (cf.isDone()) { handleConnectCompletion(cf, promise, passport); - } - else { + } else { cf.addListener(future -> { try { handleConnectCompletion((ChannelFuture) future, promise, passport); - } - catch (Throwable e) { - if (! promise.isDone()) { + } catch (Throwable e) { + if (!promise.isDone()) { promise.setFailure(e); } - LOG.warn("Error creating new connection! origin={}, host={}", config.getOriginName(), server.getServerId()); + LOG.warn( + "Error creating new connection! origin={}, host={}", + config.getOriginName(), + server.getServerId()); } }); } - } - catch (Throwable e) { + } catch (Throwable e) { promise.setFailure(e); } } @@ -285,22 +284,22 @@ protected ChannelFuture connectToServer(EventLoop eventLoop, CurrentPassport pas protected void handleConnectCompletion( ChannelFuture cf, Promise callerPromise, CurrentPassport passport) { connCreationsInProgress.decrementAndGet(); - + if (cf.isSuccess()) { - + passport.add(PassportState.ORIGIN_CH_CONNECTED); server.incrementOpenConnectionsCount(); createConnSucceededCounter.increment(); connsInUse.incrementAndGet(); createConnection(cf, callerPromise, passport); - } - else { + } else { server.incrementSuccessiveConnectionFailureCount(); server.addToFailureCount(); server.decrementActiveRequestsCount(); createConnFailedCounter.increment(); - callerPromise.setFailure(new OriginConnectException(cf.cause().getMessage(), cf.cause(), OutboundErrorType.CONNECT_ERROR)); + callerPromise.setFailure( + new OriginConnectException(cf.cause().getMessage(), cf.cause(), OutboundErrorType.CONNECT_ERROR)); } } @@ -316,8 +315,7 @@ protected void createConnection( } @Override - public boolean release(PooledConnection conn) - { + public boolean release(PooledConnection conn) { if (conn == null) { return false; } @@ -325,8 +323,10 @@ public boolean release(PooledConnection conn) return false; } - if(draining) { - LOG.debug("[{}] closing released connection during drain", conn.getChannel().id()); + if (draining) { + LOG.debug( + "[{}] closing released connection during drain", + conn.getChannel().id()); conn.getChannel().close(); return false; } @@ -334,7 +334,7 @@ public boolean release(PooledConnection conn) // Get the eventloop for this channel. EventLoop eventLoop = conn.getChannel().eventLoop(); Deque connections = getPoolForEventLoop(eventLoop); - + CurrentPassport passport = CurrentPassport.fromChannel(conn.getChannel()); // Discard conn if already at least above waterline in the pool already for this server. @@ -351,8 +351,7 @@ else if (connections.offer(conn)) { connsInPool.incrementAndGet(); passport.add(PassportState.ORIGIN_CH_POOL_RETURNED); return true; - } - else { + } else { // If the pool is full, then close the conn and discard. conn.close(); conn.setInPool(false); @@ -361,12 +360,11 @@ else if (connections.offer(conn)) { } @Override - public boolean remove(PooledConnection conn) - { + public boolean remove(PooledConnection conn) { if (conn == null) { return false; } - if (! conn.isInPool()) { + if (!conn.isInPool()) { return false; } @@ -379,15 +377,13 @@ public boolean remove(PooledConnection conn) conn.setInPool(false); connsInPool.decrementAndGet(); return true; - } - else { + } else { return false; } } @Override - public void shutdown() - { + public void shutdown() { for (Deque connections : connectionsPerEventLoop.values()) { for (PooledConnection conn : connections) { conn.close(); @@ -397,12 +393,12 @@ public void shutdown() @Override public void drain() { - if(draining) { + if (draining) { throw new IllegalStateException("Already draining"); } draining = true; - connectionsPerEventLoop.forEach((eventLoop,v) -> drainIdleConnectionsOnEventLoop(eventLoop)); + connectionsPerEventLoop.forEach((eventLoop, v) -> drainIdleConnectionsOnEventLoop(eventLoop)); } @Override @@ -434,12 +430,12 @@ private static InetAddress getSelectedHostString(SocketAddress addr) { void drainIdleConnectionsOnEventLoop(EventLoop eventLoop) { eventLoop.execute(() -> { Deque connections = connectionsPerEventLoop.get(eventLoop); - if(connections == null) { + if (connections == null) { return; } - for(PooledConnection connection : connections) { - //any connections in the Deque are idle since they are removed in tryGettingFromConnectionPool() + for (PooledConnection connection : connections) { + // any connections in the Deque are idle since they are removed in tryGettingFromConnectionPool() connection.setInPool(false); LOG.debug("Closing connection {}", connection); connection.close(); @@ -447,6 +443,4 @@ void drainIdleConnectionsOnEventLoop(EventLoop eventLoop) { } }); } - - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PooledConnection.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PooledConnection.java index d97b13ec5c..9525796c32 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PooledConnection.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PooledConnection.java @@ -16,7 +16,6 @@ package com.netflix.zuul.netty.connectionpool; -import static com.netflix.zuul.netty.connectionpool.DefaultOriginChannelInitializer.ORIGIN_NETTY_LOGGER; import com.netflix.spectator.api.Counter; import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.passport.CurrentPassport; @@ -25,12 +24,14 @@ import io.netty.channel.ChannelPipeline; import io.netty.handler.timeout.ReadTimeoutHandler; import io.netty.util.AttributeKey; -import java.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.time.Duration; import java.util.concurrent.TimeUnit; +import static com.netflix.zuul.netty.connectionpool.DefaultOriginChannelInitializer.ORIGIN_NETTY_LOGGER; + /** * Created by saroskar on 3/15/16. */ @@ -62,7 +63,6 @@ public enum ConnectionState { WRITE_BUSY } - private ConnectionState connectionState; private long usageCount = 0; private long reqStartTime; @@ -70,25 +70,26 @@ public enum ConnectionState { private boolean shouldClose = false; protected boolean released = false; - public PooledConnection(final Channel channel, final DiscoveryResult server, final ClientChannelManager channelManager, - final Counter closeConnCounter, - final Counter closeWrtBusyConnCounter) - { + public PooledConnection( + final Channel channel, + final DiscoveryResult server, + final ClientChannelManager channelManager, + final Counter closeConnCounter, + final Counter closeWrtBusyConnCounter) { this.channel = channel; this.server = server; this.channelManager = channelManager; this.creationTS = System.currentTimeMillis(); this.closeConnCounter = closeConnCounter; this.closeWrtBusyConnCounter = closeWrtBusyConnCounter; - + this.connectionState = ConnectionState.WRITE_READY; // Store ourself as an attribute on the underlying Channel. channel.attr(CHANNEL_ATTR).set(this); } - public void setInUse() - { + public void setInUse() { this.connectionState = ConnectionState.WRITE_BUSY; this.released = false; } @@ -97,18 +98,15 @@ public void setConnectionState(ConnectionState state) { this.connectionState = state; } - public static PooledConnection getFromChannel(Channel ch) - { + public static PooledConnection getFromChannel(Channel ch) { return ch.attr(CHANNEL_ATTR).get(); } - public ConnectionPoolConfig getConfig() - { + public ConnectionPoolConfig getConfig() { return this.channelManager.getConfig(); } - public DiscoveryResult getServer() - { + public DiscoveryResult getServer() { return server; } @@ -116,13 +114,11 @@ public Channel getChannel() { return channel; } - public long getUsageCount() - { + public long getUsageCount() { return usageCount; } - public void incrementUsageCount() - { + public void incrementUsageCount() { this.usageCount++; } @@ -148,23 +144,19 @@ public boolean isActive() { return (channel.isActive() && channel.isRegistered()); } - public boolean isInPool() - { + public boolean isInPool() { return inPool; } - public void setInPool(boolean inPool) - { + public void setInPool(boolean inPool) { this.inPool = inPool; } - public boolean isShouldClose() - { + public boolean isShouldClose() { return shouldClose; } - public void flagShouldClose() - { + public void flagShouldClose() { this.shouldClose = true; } @@ -179,14 +171,12 @@ public void updateServerStats() { server.stopPublishingStats(); } - public ChannelFuture closeAndRemoveFromPool() - { + public ChannelFuture closeAndRemoveFromPool() { channelManager.remove(this); return this.close(); } - public boolean release() - { + public boolean release() { if (released) { return true; } @@ -196,10 +186,13 @@ public boolean release() closeWrtBusyConnCounter.increment(); } } - - if (! isShouldClose() && connectionState != ConnectionState.WRITE_READY) { + + if (!isShouldClose() && connectionState != ConnectionState.WRITE_READY) { CurrentPassport passport = CurrentPassport.fromChannel(channel); - LOG.info("Error - Attempt to put busy connection into the pool = {}, {}", this.toString(), String.valueOf(passport)); + LOG.info( + "Error - Attempt to put busy connection into the pool = {}, {}", + this.toString(), + String.valueOf(passport)); this.shouldClose = true; } @@ -209,25 +202,26 @@ public boolean release() return channelManager.release(this); } - public void removeReadTimeoutHandler() - { + public void removeReadTimeoutHandler() { // Remove (and therefore destroy) the readTimeoutHandler when we release the // channel back to the pool. As don't want it timing-out when it's not in use. final ChannelPipeline pipeline = getChannel().pipeline(); removeHandlerFromPipeline(READ_TIMEOUT_HANDLER_NAME, pipeline); } - private void removeHandlerFromPipeline(String handlerName, ChannelPipeline pipeline) - { + private void removeHandlerFromPipeline(String handlerName, ChannelPipeline pipeline) { if (pipeline.get(handlerName) != null) { pipeline.remove(handlerName); } } - public void startReadTimeoutHandler(Duration readTimeout) - { - getChannel().pipeline().addBefore(ORIGIN_NETTY_LOGGER, READ_TIMEOUT_HANDLER_NAME, - new ReadTimeoutHandler(readTimeout.toMillis(), TimeUnit.MILLISECONDS)); + public void startReadTimeoutHandler(Duration readTimeout) { + getChannel() + .pipeline() + .addBefore( + ORIGIN_NETTY_LOGGER, + READ_TIMEOUT_HANDLER_NAME, + new ReadTimeoutHandler(readTimeout.toMillis(), TimeUnit.MILLISECONDS)); } ConnectionState getConnectionState() { @@ -239,11 +233,7 @@ boolean isReleased() { } @Override - public String toString() - { - return "PooledConnection{" + - "channel=" + channel + - ", usageCount=" + usageCount + - '}'; + public String toString() { + return "PooledConnection{" + "channel=" + channel + ", usageCount=" + usageCount + '}'; } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PooledConnectionFactory.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PooledConnectionFactory.java index f84a460961..1d914cef56 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PooledConnectionFactory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PooledConnectionFactory.java @@ -23,7 +23,6 @@ * Date: 7/9/16 * Time: 2:25 PM */ -public interface PooledConnectionFactory -{ +public interface PooledConnectionFactory { PooledConnection create(Channel ch); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/RequestStat.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/RequestStat.java index d9d64d66b6..8b4cc32daf 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/RequestStat.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/RequestStat.java @@ -16,8 +16,8 @@ package com.netflix.zuul.netty.connectionpool; -import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.context.SessionContext; +import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.exception.ErrorType; /** @@ -30,14 +30,12 @@ public interface RequestStat { String SESSION_CONTEXT_KEY = "niwsRequestStat"; - static RequestStat putInSessionContext(RequestStat stat, SessionContext context) - { + static RequestStat putInSessionContext(RequestStat stat, SessionContext context) { context.put(SESSION_CONTEXT_KEY, stat); return stat; } - static RequestStat getFromSessionContext(SessionContext context) - { + static RequestStat getFromSessionContext(SessionContext context) { return (RequestStat) context.get(SESSION_CONTEXT_KEY); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ZuulNettyExceptionMapper.java b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ZuulNettyExceptionMapper.java index 1c2408997c..80568647ad 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ZuulNettyExceptionMapper.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ZuulNettyExceptionMapper.java @@ -21,7 +21,4 @@ * Date: 7/13/16 * Time: 6:02 PM */ -public class ZuulNettyExceptionMapper -{ - -} +public class ZuulNettyExceptionMapper {} diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/filter/BaseZuulFilterRunner.java b/zuul-core/src/main/java/com/netflix/zuul/netty/filter/BaseZuulFilterRunner.java index e2a268bf3a..b4eeb792d1 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/filter/BaseZuulFilterRunner.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/filter/BaseZuulFilterRunner.java @@ -40,9 +40,6 @@ import io.netty.handler.codec.http.HttpContent; import io.perfmark.Link; import io.perfmark.TaskCloseable; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observer; @@ -51,8 +48,10 @@ import rx.schedulers.Schedulers; import javax.annotation.concurrent.ThreadSafe; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import static com.google.common.base.Preconditions.checkNotNull; import static com.netflix.zuul.ExecutionStatus.DISABLED; @@ -81,13 +80,14 @@ public abstract class BaseZuulFilterRunner nextStage, Registry registry) { + protected BaseZuulFilterRunner( + FilterType filterType, FilterUsageNotifier usageNotifier, FilterRunner nextStage, Registry registry) { this.usageNotifier = Preconditions.checkNotNull(usageNotifier, "filter usage notifier"); this.nextStage = nextStage; this.RUNNING_FILTER_IDX_SESSION_CTX_KEY = filterType + "RunningFilterIndex"; @@ -97,8 +97,8 @@ protected BaseZuulFilterRunner(FilterType filterType, FilterUsageNotifier usageN } public static final ChannelHandlerContext getChannelHandlerContext(final ZuulMessage mesg) { - return (ChannelHandlerContext) checkNotNull(mesg.getContext().get(NETTY_SERVER_CHANNEL_HANDLER_CONTEXT), - "channel handler context"); + return (ChannelHandlerContext) + checkNotNull(mesg.getContext().get(NETTY_SERVER_CHANNEL_HANDLER_CONTEXT), "channel handler context"); } public FilterRunner getNextStage() { @@ -113,7 +113,8 @@ protected final AtomicInteger initRunningFilterIndex(I zuulMesg) { protected final AtomicInteger getRunningFilterIndex(I zuulMesg) { final SessionContext ctx = zuulMesg.getContext(); - return (AtomicInteger) Preconditions.checkNotNull(ctx.get(RUNNING_FILTER_IDX_SESSION_CTX_KEY), "runningFilterIndex"); + return (AtomicInteger) + Preconditions.checkNotNull(ctx.get(RUNNING_FILTER_IDX_SESSION_CTX_KEY), "runningFilterIndex"); } protected final boolean isFilterAwaitingBody(SessionContext context) { @@ -123,30 +124,29 @@ protected final boolean isFilterAwaitingBody(SessionContext context) { protected final void setFilterAwaitingBody(I zuulMesg, boolean flag) { if (flag) { zuulMesg.getContext().put(AWAITING_BODY_FLAG_SESSION_CTX_KEY, Boolean.TRUE); - } - else { + } else { zuulMesg.getContext().remove(AWAITING_BODY_FLAG_SESSION_CTX_KEY); } } protected final void invokeNextStage(final O zuulMesg, final HttpContent chunk) { if (nextStage != null) { - try (TaskCloseable ignored = - traceTask(this, s -> s.getClass().getSimpleName() + ".invokeNextStageChunk")){ + try (TaskCloseable ignored = traceTask(this, s -> s.getClass().getSimpleName() + ".invokeNextStageChunk")) { addPerfMarkTags(zuulMesg); nextStage.filter(zuulMesg, chunk); } } else { - //Next stage is Netty channel handler - try (TaskCloseable ignored = - traceTask(this, s -> s.getClass().getSimpleName() + ".fireChannelReadChunk")) { + // Next stage is Netty channel handler + try (TaskCloseable ignored = traceTask(this, s -> s.getClass().getSimpleName() + ".fireChannelReadChunk")) { addPerfMarkTags(zuulMesg); ChannelHandlerContext channelHandlerContext = getChannelHandlerContext(zuulMesg); if (!channelHandlerContext.channel().isActive()) { zuulMesg.getContext().cancel(); zuulMesg.disposeBufferedBody(); - SpectatorUtils.newCounter("zuul.filterChain.chunk.hanging", - zuulMesg.getClass().getSimpleName()).increment(); + SpectatorUtils.newCounter( + "zuul.filterChain.chunk.hanging", + zuulMesg.getClass().getSimpleName()) + .increment(); } else { channelHandlerContext.fireChannelRead(chunk); } @@ -156,24 +156,23 @@ protected final void invokeNextStage(final O zuulMesg, final HttpContent chunk) protected final void invokeNextStage(final O zuulMesg) { if (nextStage != null) { - try (TaskCloseable ignored = - traceTask(this, s -> s.getClass().getSimpleName() + ".invokeNextStage")) { + try (TaskCloseable ignored = traceTask(this, s -> s.getClass().getSimpleName() + ".invokeNextStage")) { addPerfMarkTags(zuulMesg); nextStage.filter(zuulMesg); } } else { - //Next stage is Netty channel handler - try (TaskCloseable ignored = - traceTask(this, s -> s.getClass().getSimpleName() + ".fireChannelRead")) { + // Next stage is Netty channel handler + try (TaskCloseable ignored = traceTask(this, s -> s.getClass().getSimpleName() + ".fireChannelRead")) { addPerfMarkTags(zuulMesg); ChannelHandlerContext channelHandlerContext = getChannelHandlerContext(zuulMesg); if (!channelHandlerContext.channel().isActive()) { zuulMesg.getContext().cancel(); zuulMesg.disposeBufferedBody(); - SpectatorUtils.newCounter("zuul.filterChain.message.hanging", - zuulMesg.getClass().getSimpleName()).increment(); - } - else { + SpectatorUtils.newCounter( + "zuul.filterChain.message.hanging", + zuulMesg.getClass().getSimpleName()) + .increment(); + } else { channelHandlerContext.fireChannelRead(zuulMesg); } } @@ -211,7 +210,7 @@ protected final O filter(final ZuulFilter filter, final I inMesg) { } ; - try (TaskCloseable ignored2 = traceTask(filter, f -> f.filterName() + ".shouldSkipFilter")){ + try (TaskCloseable ignored2 = traceTask(filter, f -> f.filterName() + ".shouldSkipFilter")) { if (shouldSkipFilter(inMesg, filter)) { filterRunStatus = SKIPPED; } @@ -228,16 +227,22 @@ protected final O filter(final ZuulFilter filter, final I inMesg) { if (!isMessageBodyReadyForFilter(filter, inMesg)) { setFilterAwaitingBody(inMesg, true); - logger.debug("Filter {} waiting for body, UUID {}", filter.filterName(), inMesg.getContext().getUUID()); - return null; //wait for whole body to be buffered + logger.debug( + "Filter {} waiting for body, UUID {}", + filter.filterName(), + inMesg.getContext().getUUID()); + return null; // wait for whole body to be buffered } setFilterAwaitingBody(inMesg, false); if (snapshot != null) { - Debug.addRoutingDebug(inMesg.getContext(), "Filter " + filter.filterType().toString() + " " + filter.filterOrder() + " " + filter.filterName()); + Debug.addRoutingDebug( + inMesg.getContext(), + "Filter " + filter.filterType().toString() + " " + filter.filterOrder() + " " + + filter.filterName()); } - //run body contents accumulated so far through this filter + // run body contents accumulated so far through this filter inMesg.runBufferedBodyContentThroughFilter(filter); if (filter.getSyncType() == FilterSyncType.SYNC) { @@ -252,7 +257,7 @@ protected final O filter(final ZuulFilter filter, final I inMesg) { } // async filter - try (TaskCloseable ignored2 = traceTask(filter, f -> f.filterName() + ".applyAsync")){ + try (TaskCloseable ignored2 = traceTask(filter, f -> f.filterName() + ".applyAsync")) { final Link nettyToSchedulerLink = linkOut(); filter.incrementConcurrency(); resumer = new FilterChainResumer(inMesg, filter, snapshot, startTime); @@ -266,14 +271,14 @@ protected final O filter(final ZuulFilter filter, final I inMesg) { .doOnNext(resumer.onNextStarted(nettyToSchedulerLink)) .doOnError(resumer.onErrorStarted(nettyToSchedulerLink)) .doOnCompleted(resumer.onCompletedStarted(nettyToSchedulerLink)) - .observeOn(Schedulers.from(getChannelHandlerContext(inMesg).executor())) + .observeOn( + Schedulers.from(getChannelHandlerContext(inMesg).executor())) .doOnUnsubscribe(resumer::decrementConcurrency) .subscribe(resumer); } - return null; //wait for the async filter to finish - } - catch (Throwable t) { + return null; // wait for the async filter to finish + } catch (Throwable t) { if (resumer != null) { resumer.decrementConcurrency(); } @@ -285,10 +290,10 @@ protected final O filter(final ZuulFilter filter, final I inMesg) { } /* This is typically set by a filter when wanting to reject a request and also reduce load on the server by - not processing any more filterChain */ + not processing any more filterChain */ protected final boolean shouldSkipFilter(final I inMesg, final ZuulFilter filter) { if (filter.filterType() == ENDPOINT) { - //Endpoints may not be skipped + // Endpoints may not be skipped return false; } final SessionContext zuulCtx = inMesg.getContext(); @@ -304,7 +309,6 @@ protected final boolean shouldSkipFilter(final I inMesg, final ZuulFilter return false; } - private boolean isMessageBodyReadyForFilter(final ZuulFilter filter, final I inMesg) { return ((!filter.needsBodyBuffered(inMesg)) || (inMesg.hasCompleteBody())); } @@ -320,34 +324,40 @@ protected O handleFilterException(final I inMesg, final ZuulFilter filter, protected void recordFilterError(final I inMesg, final ZuulFilter filter, final Throwable t) { // Add a log statement for this exception. - final String errorMsg = "Filter Exception: filter=" + filter.filterName() + - ", request-info=" + inMesg.getInfoForLogging() + ", msg=" + String.valueOf(t.getMessage()); + final String errorMsg = "Filter Exception: filter=" + filter.filterName() + ", request-info=" + + inMesg.getInfoForLogging() + ", msg=" + String.valueOf(t.getMessage()); if (t instanceof ZuulException && !((ZuulException) t).shouldLogAsError()) { logger.warn(errorMsg); - } - else { + } else { logger.error(errorMsg, t); } // Store this filter error for possible future use. But we still continue with next filter in the chain. final SessionContext zuulCtx = inMesg.getContext(); - zuulCtx.getFilterErrors().add(new FilterError(filter.filterName(), filter.filterType().toString(), t)); + zuulCtx.getFilterErrors() + .add(new FilterError(filter.filterName(), filter.filterType().toString(), t)); if (zuulCtx.debugRouting()) { - Debug.addRoutingDebug(zuulCtx, "Running Filter failed " + filter.filterName() + " type:" + - filter.filterType() + " order:" + filter.filterOrder() + " " + t.getMessage()); + Debug.addRoutingDebug( + zuulCtx, + "Running Filter failed " + filter.filterName() + " type:" + filter.filterType() + " order:" + + filter.filterOrder() + " " + t.getMessage()); } } - protected void recordFilterCompletion(final ExecutionStatus status, final ZuulFilter filter, long startTime, - final ZuulMessage zuulMesg, final ZuulMessage startSnapshot) { + protected void recordFilterCompletion( + final ExecutionStatus status, + final ZuulFilter filter, + long startTime, + final ZuulMessage zuulMesg, + final ZuulMessage startSnapshot) { final SessionContext zuulCtx = zuulMesg.getContext(); final long execTimeNs = System.nanoTime() - startTime; final long execTimeMs = execTimeNs / 1_000_000L; if (execTimeMs >= FILTER_EXCESSIVE_EXEC_TIME.get()) { registry.timer(filterExcessiveTimerId - .withTag("id", filter.filterName()) - .withTag("status", status.name())) + .withTag("id", filter.filterName()) + .withTag("status", status.name())) .record(execTimeMs, TimeUnit.MILLISECONDS); } @@ -363,9 +373,12 @@ protected void recordFilterCompletion(final ExecutionStatus status, final ZuulFi zuulCtx.addFilterExecutionSummary(filter.filterName(), SUCCESS.name(), execTimeMs); } if (startSnapshot != null) { - //debugRouting == true - Debug.addRoutingDebug(zuulCtx, "Filter {" + filter.filterName() + " TYPE:" + filter.filterType().toString() - + " ORDER:" + filter.filterOrder() + "} Execution time = " + execTimeMs + "ms"); + // debugRouting == true + Debug.addRoutingDebug( + zuulCtx, + "Filter {" + filter.filterName() + " TYPE:" + + filter.filterType().toString() + " ORDER:" + filter.filterOrder() + + "} Execution time = " + execTimeMs + "ms"); Debug.compareContextState(filter.filterName(), zuulCtx, startSnapshot.getContext()); } break; @@ -373,19 +386,20 @@ protected void recordFilterCompletion(final ExecutionStatus status, final ZuulFi break; } - logger.debug("Filter {} completed with status {}, UUID {}", filter.filterName(), status.name(), + logger.debug( + "Filter {} completed with status {}, UUID {}", + filter.filterName(), + status.name(), zuulMesg.getContext().getUUID()); // Notify configured listener. usageNotifier.notify(filter, status); } - protected void handleException(final ZuulMessage zuulMesg, final String filterName, final Exception ex) { HttpRequestInfo zuulReq = null; if (zuulMesg instanceof HttpRequestMessage) { zuulReq = (HttpRequestMessage) zuulMesg; - } - else if (zuulMesg instanceof HttpResponseMessage) { + } else if (zuulMesg instanceof HttpResponseMessage) { zuulReq = ((HttpResponseMessage) zuulMesg).getInboundRequest(); } final String path = (zuulReq != null) ? zuulReq.getPathAndQuery() : "-"; @@ -404,8 +418,7 @@ protected MethodBinding methodBinding(ZuulMessage zuulMesg) { protected void resumeInBindingContext(final O zuulMesg, final String filterName) { try { methodBinding(zuulMesg).bind(() -> resume(zuulMesg)); - } - catch (Exception ex) { + } catch (Exception ex) { handleException(zuulMesg, filterName, ex); } } @@ -421,8 +434,7 @@ private final class FilterChainResumer implements Observer { private final AtomicReference onErrorLinkOut = new AtomicReference<>(); private final AtomicReference onCompletedLinkOut = new AtomicReference<>(); - public FilterChainResumer( - I inMesg, ZuulFilter filter, ZuulMessage snapshot, long startTime) { + public FilterChainResumer(I inMesg, ZuulFilter filter, ZuulMessage snapshot, long startTime) { this.inMesg = Preconditions.checkNotNull(inMesg, "input message"); this.filter = Preconditions.checkNotNull(filter, "filter"); this.snapshot = snapshot; @@ -446,8 +458,7 @@ public void onNext(O outMesg) { outMesg = filter.getDefaultOutput(inMesg); } resumeInBindingContext(outMesg, filter.filterName()); - } - catch (Exception e) { + } catch (Exception e) { decrementConcurrency(); handleException(inMesg, filter.filterName(), e); } @@ -461,8 +472,7 @@ public void onError(Throwable ex) { recordFilterCompletion(FAILED, filter, startTime, inMesg, snapshot); final O outMesg = handleFilterException(inMesg, filter, ex); resumeInBindingContext(outMesg, filter.filterName()); - } - catch (Exception e) { + } catch (Exception e) { handleException(inMesg, filter.filterName(), e); } } @@ -502,5 +512,4 @@ private Action0 onCompletedStarted(Link onCompletedLinkIn) { }; } } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/filter/FilterRunner.java b/zuul-core/src/main/java/com/netflix/zuul/netty/filter/FilterRunner.java index 79a76aa1be..0a4b1c77f9 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/filter/FilterRunner.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/filter/FilterRunner.java @@ -25,5 +25,6 @@ public interface FilterRunner { void filter(I zuulMesg); + void filter(I zuulMesg, HttpContent chunk); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulEndPointRunner.java b/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulEndPointRunner.java index cf9e3cdace..3100603c1e 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulEndPointRunner.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulEndPointRunner.java @@ -26,28 +26,27 @@ import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.filters.Endpoint; import com.netflix.zuul.filters.FilterType; +import com.netflix.zuul.filters.SyncZuulFilterAdapter; import com.netflix.zuul.filters.ZuulFilter; +import com.netflix.zuul.filters.endpoint.MissingEndpointHandlingFilter; import com.netflix.zuul.filters.endpoint.ProxyEndpoint; import com.netflix.zuul.message.ZuulMessage; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.message.http.HttpResponseMessageImpl; -import com.netflix.zuul.filters.endpoint.MissingEndpointHandlingFilter; -import com.netflix.zuul.filters.SyncZuulFilterAdapter; import com.netflix.zuul.netty.server.MethodBinding; import io.netty.handler.codec.http.HttpContent; import io.netty.util.ReferenceCountUtil; import io.perfmark.PerfMark; import io.perfmark.TaskCloseable; -import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; import static com.netflix.zuul.context.CommonContextKeys.ZUUL_ENDPOINT; - /** * This class is supposed to be thread safe and hence should not have any non final member variables * Created by saroskar on 5/18/17. @@ -59,11 +58,14 @@ public class ZuulEndPointRunner extends BaseZuulFilterRunner respFilters, Registry registry) { + public static final DynamicStringProperty DEFAULT_ERROR_ENDPOINT = + new DynamicStringProperty("zuul.filters.error.default", "endpoint.ErrorResponse"); + + public ZuulEndPointRunner( + FilterUsageNotifier usageNotifier, + FilterLoader filterLoader, + FilterRunner respFilters, + Registry registry) { super(FilterType.ENDPOINT, usageNotifier, respFilters, registry); this.filterLoader = filterLoader; } @@ -77,7 +79,8 @@ public static ZuulFilter getEndpoint( return null; } - public static void setEndpoint(HttpRequestMessage zuulReq, ZuulFilter endpoint) { + public static void setEndpoint( + HttpRequestMessage zuulReq, ZuulFilter endpoint) { zuulReq.getContext().put(ZUUL_ENDPOINT, endpoint); } @@ -96,17 +99,21 @@ public void filter(final HttpRequestMessage zuulReq) { addPerfMarkTags(zuulReq); final ZuulFilter endpoint = getEndpoint(endpointName, zuulReq); - logger.debug("Got endpoint {}, UUID {}", endpoint.filterName(), zuulReq.getContext().getUUID()); + logger.debug( + "Got endpoint {}, UUID {}", + endpoint.filterName(), + zuulReq.getContext().getUUID()); setEndpoint(zuulReq, endpoint); final HttpResponseMessage zuulResp = filter(endpoint, zuulReq); - if ((zuulResp != null)&&(! (endpoint instanceof ProxyEndpoint))) { - //EdgeProxyEndpoint calls invokeNextStage internally - logger.debug("Endpoint calling invokeNextStage, UUID {}", zuulReq.getContext().getUUID()); + if ((zuulResp != null) && (!(endpoint instanceof ProxyEndpoint))) { + // EdgeProxyEndpoint calls invokeNextStage internally + logger.debug( + "Endpoint calling invokeNextStage, UUID {}", + zuulReq.getContext().getUUID()); invokeNextStage(zuulResp); } - } - catch (Exception ex) { + } catch (Exception ex) { handleException(zuulReq, endpointName, ex); } } @@ -131,30 +138,31 @@ public void filter(final HttpRequestMessage zuulReq, final HttpContent chunk) { String endpointName = "-"; try (TaskCloseable ignored = PerfMark.traceTask(this, s -> s.getClass().getSimpleName() + ".filterChunk")) { addPerfMarkTags(zuulReq); - ZuulFilter endpoint = Preconditions.checkNotNull( - getEndpoint(zuulReq), "endpoint"); + ZuulFilter endpoint = + Preconditions.checkNotNull(getEndpoint(zuulReq), "endpoint"); endpointName = endpoint.filterName(); ByteBufUtil.touch(chunk, "Endpoint processing chunk, ZuulMessage: ", zuulReq); final HttpContent newChunk = endpoint.processContentChunk(zuulReq, chunk); if (newChunk != null) { ByteBufUtil.touch(newChunk, "Endpoint buffering newChunk, ZuulMessage: ", zuulReq); - //Endpoints do not directly forward content chunks to next stage in the filter chain. + // Endpoints do not directly forward content chunks to next stage in the filter chain. zuulReq.bufferBodyContents(newChunk); - //deallocate original chunk if necessary + // deallocate original chunk if necessary if (newChunk != chunk) { chunk.release(); } - if (isFilterAwaitingBody(zuulReq.getContext()) && zuulReq.hasCompleteBody() && !(endpoint instanceof ProxyEndpoint)) { - //whole body has arrived, resume filter chain + if (isFilterAwaitingBody(zuulReq.getContext()) + && zuulReq.hasCompleteBody() + && !(endpoint instanceof ProxyEndpoint)) { + // whole body has arrived, resume filter chain ByteBufUtil.touch(newChunk, "Endpoint body complete, resume chain, ZuulMessage: ", zuulReq); invokeNextStage(filter(endpoint, zuulReq)); } } - } - catch (Exception ex) { + } catch (Exception ex) { ReferenceCountUtil.safeRelease(chunk); handleException(zuulReq, endpointName, ex); } @@ -171,8 +179,8 @@ protected String getEndPointName(final SessionContext zuulCtx) { } } - protected ZuulFilter getEndpoint(final String endpointName, - final HttpRequestMessage zuulRequest) { + protected ZuulFilter getEndpoint( + final String endpointName, final HttpRequestMessage zuulRequest) { final SessionContext zuulCtx = zuulRequest.getContext(); if (zuulCtx.getStaticResponse() != null) { @@ -202,30 +210,31 @@ protected ZuulFilter getEndpoint(final * @return the proxy endpoint */ protected ZuulFilter newProxyEndpoint(HttpRequestMessage zuulRequest) { - return new ProxyEndpoint(zuulRequest, getChannelHandlerContext(zuulRequest), getNextStage(), MethodBinding.NO_OP_BINDING); + return new ProxyEndpoint( + zuulRequest, getChannelHandlerContext(zuulRequest), getNextStage(), MethodBinding.NO_OP_BINDING); } protected Endpoint getEndpointFilter(String endpointName) { return (Endpoint) filterLoader.getFilterByNameAndType(endpointName, FilterType.ENDPOINT); } - final protected static ZuulFilter STATIC_RESPONSE_ENDPOINT = new SyncZuulFilterAdapter() { - @Override - public HttpResponseMessage apply(HttpRequestMessage request) { - final HttpResponseMessage resp = request.getContext().getStaticResponse(); - resp.finishBufferedBodyIfIncomplete(); - return resp; - } - - @Override - public String filterName() { - return "StaticResponseEndpoint"; - } + protected static final ZuulFilter STATIC_RESPONSE_ENDPOINT = + new SyncZuulFilterAdapter() { + @Override + public HttpResponseMessage apply(HttpRequestMessage request) { + final HttpResponseMessage resp = request.getContext().getStaticResponse(); + resp.finishBufferedBodyIfIncomplete(); + return resp; + } - @Override - public HttpResponseMessage getDefaultOutput(HttpRequestMessage input) { - return HttpResponseMessageImpl.defaultErrorResponse(input); - } - }; + @Override + public String filterName() { + return "StaticResponseEndpoint"; + } + @Override + public HttpResponseMessage getDefaultOutput(HttpRequestMessage input) { + return HttpResponseMessageImpl.defaultErrorResponse(input); + } + }; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilterChainHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilterChainHandler.java index 1c6a8ad44d..5110b167be 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilterChainHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilterChainHandler.java @@ -16,13 +16,6 @@ package com.netflix.zuul.netty.filter; -import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason.SESSION_COMPLETE; -import static com.netflix.zuul.context.CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT; -import static com.netflix.zuul.netty.server.ClientRequestReceiver.ATTR_ZUUL_RESP; -import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_CLIENT_CANCELLED; -import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_CLIENT_TIMEOUT; -import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_LOCAL; -import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_LOCAL_IDLE_TIMEOUT; import com.google.common.base.Preconditions; import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent; import com.netflix.netty.common.HttpRequestReadTimeoutEvent; @@ -45,11 +38,20 @@ import io.netty.handler.codec.http.HttpContent; import io.netty.handler.timeout.IdleStateEvent; import io.netty.util.ReferenceCountUtil; -import java.nio.channels.ClosedChannelException; -import javax.net.ssl.SSLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.net.ssl.SSLException; +import java.nio.channels.ClosedChannelException; + +import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason.SESSION_COMPLETE; +import static com.netflix.zuul.context.CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT; +import static com.netflix.zuul.netty.server.ClientRequestReceiver.ATTR_ZUUL_RESP; +import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_CLIENT_CANCELLED; +import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_CLIENT_TIMEOUT; +import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_LOCAL; +import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_LOCAL_IDLE_TIMEOUT; + /** * Created by saroskar on 5/18/17. */ @@ -61,8 +63,8 @@ public class ZuulFilterChainHandler extends ChannelInboundHandlerAdapter { private static final Logger logger = LoggerFactory.getLogger(ZuulFilterChainHandler.class); - - public ZuulFilterChainHandler(ZuulFilterChainRunner requestFilterChain, + public ZuulFilterChainHandler( + ZuulFilterChainRunner requestFilterChain, ZuulFilterChainRunner responseFilterChain) { this.requestFilterChain = Preconditions.checkNotNull(requestFilterChain, "request filter chain"); this.responseFilterChain = Preconditions.checkNotNull(responseFilterChain, "response filter chain"); @@ -73,7 +75,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception if (msg instanceof HttpRequestMessage) { zuulRequest = (HttpRequestMessage) msg; - //Replace NETTY_SERVER_CHANNEL_HANDLER_CONTEXT in SessionContext + // Replace NETTY_SERVER_CHANNEL_HANDLER_CONTEXT in SessionContext final SessionContext zuulCtx = zuulRequest.getContext(); zuulCtx.put(NETTY_SERVER_CHANNEL_HANDLER_CONTEXT, ctx); @@ -81,7 +83,8 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception } else if ((msg instanceof HttpContent) && (zuulRequest != null)) { requestFilterChain.filter(zuulRequest, (HttpContent) msg); } else { - logger.debug("Received unrecognized message type. {}", msg.getClass().getName()); + logger.debug( + "Received unrecognized message type. {}", msg.getClass().getName()); ReferenceCountUtil.release(msg); } } @@ -98,8 +101,8 @@ public final void userEventTriggered(ChannelHandlerContext ctx, Object evt) thro } else if (evt instanceof RequestCancelledEvent) { if (zuulRequest != null) { zuulRequest.getContext().cancel(); - StatusCategoryUtils.storeStatusCategoryIfNotAlreadyFailure(zuulRequest.getContext(), - FAILURE_CLIENT_CANCELLED); + StatusCategoryUtils.storeStatusCategoryIfNotAlreadyFailure( + zuulRequest.getContext(), FAILURE_CLIENT_CANCELLED); } fireEndpointFinish(true, ctx); ctx.close(); @@ -143,12 +146,15 @@ protected void fireEndpointFinish(final boolean error, final ChannelHandlerConte private void finishResponseFilters(ChannelHandlerContext ctx) { // check if there are any response filters awaiting a buffered body if (zuulRequest != null && responseFilterChain.isFilterAwaitingBody(zuulRequest.getContext())) { - HttpResponseMessage zuulResponse = ctx.channel().attr(ATTR_ZUUL_RESP).get(); + HttpResponseMessage zuulResponse = + ctx.channel().attr(ATTR_ZUUL_RESP).get(); if (zuulResponse != null) { // fire a last content into the filter chain to unblock any filters awaiting a buffered body responseFilterChain.filter(zuulResponse, new DefaultLastHttpContent()); - SpectatorUtils.newCounter("zuul.filterChain.bodyBuffer.hanging", - zuulRequest.getContext().getRouteVIP()).increment(); + SpectatorUtils.newCounter( + "zuul.filterChain.bodyBuffer.hanging", + zuulRequest.getContext().getRouteVIP()) + .increment(); } } } @@ -158,8 +164,10 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E if (cause instanceof SSLException) { logger.debug("SSL exception not handled in filter chain", cause); } else { - logger.error("zuul filter chain handler caught exception on channel: {}", - ChannelUtils.channelInfoForLogging(ctx.channel()), cause); + logger.error( + "zuul filter chain handler caught exception on channel: {}", + ChannelUtils.channelInfoForLogging(ctx.channel()), + cause); } if (zuulRequest != null && !isClientChannelClosed(cause)) { final SessionContext zuulCtx = zuulRequest.getContext(); @@ -172,12 +180,10 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E } } - // Race condition: channel.isActive() did not catch // channel close..resulting in an i/o exception private boolean isClientChannelClosed(Throwable cause) { - if (cause instanceof ClosedChannelException || - cause instanceof Errors.NativeIoException) { + if (cause instanceof ClosedChannelException || cause instanceof Errors.NativeIoException) { logger.error("ZuulFilterChainHandler::isClientChannelClosed - IO Exception"); return true; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilterChainRunner.java b/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilterChainRunner.java index 904557d181..e331a5692c 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilterChainRunner.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilterChainRunner.java @@ -27,10 +27,10 @@ import com.netflix.zuul.passport.CurrentPassport; import com.netflix.zuul.passport.PassportState; import io.netty.handler.codec.http.HttpContent; - import io.netty.util.ReferenceCountUtil; import io.perfmark.PerfMark; import io.perfmark.TaskCloseable; + import javax.annotation.concurrent.ThreadSafe; import java.util.concurrent.atomic.AtomicInteger; @@ -43,8 +43,11 @@ public class ZuulFilterChainRunner extends BaseZuulFilter private final ZuulFilter[] filters; - public ZuulFilterChainRunner(ZuulFilter[] zuulFilters, FilterUsageNotifier usageNotifier, - FilterRunner nextStage, Registry registry) { + public ZuulFilterChainRunner( + ZuulFilter[] zuulFilters, + FilterUsageNotifier usageNotifier, + FilterRunner nextStage, + Registry registry) { super(zuulFilters[0].filterType(), usageNotifier, nextStage, registry); this.filters = zuulFilters; } @@ -82,16 +85,15 @@ private final void runFilters(final T mesg, final AtomicInteger runningFilterIdx filterName = filter.filterName(); final T outMesg = filter(filter, inMesg); if (outMesg == null) { - return; //either async filter or waiting for the message body to be buffered + return; // either async filter or waiting for the message body to be buffered } inMesg = outMesg; i = runningFilterIdx.incrementAndGet(); } - //Filter chain has reached its end, pass result to the next stage + // Filter chain has reached its end, pass result to the next stage invokeNextStage(inMesg); - } - catch (Exception ex) { + } catch (Exception ex) { handleException(inMesg, filterName, ex); } } @@ -108,14 +110,14 @@ public void filter(T inMesg, HttpContent chunk) { for (int i = 0; i < limit; i++) { final ZuulFilter filter = filters[i]; filterName = filter.filterName(); - if ((! filter.isDisabled()) && (! shouldSkipFilter(inMesg, filter))) { - ByteBufUtil.touch(chunk, "Filter runner processing chunk, filter: " , filterName); + if ((!filter.isDisabled()) && (!shouldSkipFilter(inMesg, filter))) { + ByteBufUtil.touch(chunk, "Filter runner processing chunk, filter: ", filterName); final HttpContent newChunk = filter.processContentChunk(inMesg, chunk); - if (newChunk == null) { - //Filter wants to break the chain and stop propagating this chunk any further + if (newChunk == null) { + // Filter wants to break the chain and stop propagating this chunk any further return; } - //deallocate original chunk if necessary + // deallocate original chunk if necessary if ((newChunk != chunk) && (chunk.refCnt() > 0)) { ByteBufUtil.touch(chunk, "Filter runner processing newChunk, filter: ", filterName); chunk.release(chunk.refCnt()); @@ -125,7 +127,7 @@ public void filter(T inMesg, HttpContent chunk) { } if (limit >= filters.length) { - //Filter chain has run to end, pass down the channel pipeline + // Filter chain has run to end, pass down the channel pipeline ByteBufUtil.touch(chunk, "Filter runner chain complete, message: ", inMesg); invokeNextStage(inMesg, chunk); } else { @@ -143,8 +145,7 @@ public void filter(T inMesg, HttpContent chunk) { } else if (inMesg instanceof HttpResponseMessage) { passport.addIfNotAlready(PassportState.FILTERS_OUTBOUND_BUF_END); } - } - else { + } else { if (inMesg instanceof HttpRequestMessage) { passport.addIfNotAlready(PassportState.FILTERS_INBOUND_BUF_START); } else if (inMesg instanceof HttpResponseMessage) { @@ -154,13 +155,12 @@ public void filter(T inMesg, HttpContent chunk) { } if (isAwaitingBody && inMesg.hasCompleteBody()) { - //whole body has arrived, resume filter chain + // whole body has arrived, resume filter chain ByteBufUtil.touch(chunk, "Filter body complete, resume chain, ZuulMessage: ", inMesg); runFilters(inMesg, runningFilterIdx); } } - } - catch (Exception ex) { + } catch (Exception ex) { ReferenceCountUtil.safeRelease(chunk); handleException(inMesg, filterName, ex); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportLoggingHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportLoggingHandler.java index cd2fc3573e..80239e10b7 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportLoggingHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportLoggingHandler.java @@ -45,42 +45,36 @@ * Time: 5:41 PM */ @ChannelHandler.Sharable -public class PassportLoggingHandler extends ChannelInboundHandlerAdapter -{ +public class PassportLoggingHandler extends ChannelInboundHandlerAdapter { private static final Logger LOG = LoggerFactory.getLogger(PassportLoggingHandler.class); - private static final CachedDynamicLongProperty WARN_REQ_PROCESSING_TIME_NS = new CachedDynamicLongProperty("zuul.passport.log.request.time.threshold", - 1000 * 1000 * 1000); // 1000 ms - private static final CachedDynamicLongProperty WARN_RESP_PROCESSING_TIME_NS = new CachedDynamicLongProperty("zuul.passport.log.response.time.threshold", - 1000 * 1000 * 1000); // 1000 ms + private static final CachedDynamicLongProperty WARN_REQ_PROCESSING_TIME_NS = + new CachedDynamicLongProperty("zuul.passport.log.request.time.threshold", 1000 * 1000 * 1000); // 1000 ms + private static final CachedDynamicLongProperty WARN_RESP_PROCESSING_TIME_NS = + new CachedDynamicLongProperty("zuul.passport.log.response.time.threshold", 1000 * 1000 * 1000); // 1000 ms private final Counter incompleteProxySessionCounter; - public PassportLoggingHandler(Registry spectatorRegistry) - { + public PassportLoggingHandler(Registry spectatorRegistry) { incompleteProxySessionCounter = spectatorRegistry.counter("server.http.session.incomplete"); } @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception - { + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { try { super.userEventTriggered(ctx, evt); - } - finally { + } finally { if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) { try { logPassport(ctx.channel()); - } - catch(Exception e) { + } catch (Exception e) { LOG.error("Error logging passport info after request completed!", e); } } } } - private void logPassport(Channel channel) - { + private void logPassport(Channel channel) { // Collect attributes. CurrentPassport passport = CurrentPassport.fromChannel(channel); HttpRequestMessage request = ClientRequestReceiver.getRequestFromChannel(channel); @@ -91,7 +85,15 @@ private void logPassport(Channel channel) // Do some debug logging of the Passport. if (LOG.isDebugEnabled()) { - LOG.debug("State after complete. , current-server-conns = {}, current-http-reqs = {}, status = {}, nfstatus = {}, toplevelid = {}, req = {}, passport = {}", ConnCounter.from(channel).getCurrentActiveConns(), HttpMetricsChannelHandler.getInflightRequestCountFromChannel(channel), (response == null ? getRequestId(channel, ctx) : response.getStatus()), String.valueOf(StatusCategoryUtils.getStatusCategory(ctx)), topLevelRequestId, request.getInfoForLogging(), String.valueOf(passport)); + LOG.debug( + "State after complete. , current-server-conns = {}, current-http-reqs = {}, status = {}, nfstatus = {}, toplevelid = {}, req = {}, passport = {}", + ConnCounter.from(channel).getCurrentActiveConns(), + HttpMetricsChannelHandler.getInflightRequestCountFromChannel(channel), + (response == null ? getRequestId(channel, ctx) : response.getStatus()), + String.valueOf(StatusCategoryUtils.getStatusCategory(ctx)), + topLevelRequestId, + request.getInfoForLogging(), + String.valueOf(passport)); } // Some logging of session states if certain criteria match: @@ -100,27 +102,44 @@ private void logPassport(Channel channel) if (passport.findStateBackwards(PassportState.OUT_RESP_LAST_CONTENT_SENDING) == null) { incompleteProxySessionCounter.increment(); - LOG.info("Incorrect final state! toplevelid = {}, {}", topLevelRequestId, ChannelUtils.channelInfoForLogging(channel)); + LOG.info( + "Incorrect final state! toplevelid = {}, {}", + topLevelRequestId, + ChannelUtils.channelInfoForLogging(channel)); } } - if (! passport.wasProxyAttempt()) { + if (!passport.wasProxyAttempt()) { if (ctx != null && !isHealthcheckRequest(request)) { // Why did we fail to attempt to proxy this request? RequestAttempts attempts = RequestAttempts.getFromSessionContext(ctx); - LOG.debug("State after complete. , context-error = {}, current-http-reqs = {}, toplevelid = {}, req = {}, attempts = {}, passport = {}", String.valueOf(ctx.getError()), HttpMetricsChannelHandler.getInflightRequestCountFromChannel(channel), topLevelRequestId, request.getInfoForLogging(), String.valueOf(attempts), String.valueOf(passport)); + LOG.debug( + "State after complete. , context-error = {}, current-http-reqs = {}, toplevelid = {}, req = {}, attempts = {}, passport = {}", + String.valueOf(ctx.getError()), + HttpMetricsChannelHandler.getInflightRequestCountFromChannel(channel), + topLevelRequestId, + request.getInfoForLogging(), + String.valueOf(attempts), + String.valueOf(passport)); } } - StartAndEnd inReqToOutResp = passport.findFirstStartAndLastEndStates(PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.OUT_REQ_LAST_CONTENT_SENT); + StartAndEnd inReqToOutResp = passport.findFirstStartAndLastEndStates( + PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.OUT_REQ_LAST_CONTENT_SENT); if (passport.calculateTimeBetween(inReqToOutResp) > WARN_REQ_PROCESSING_TIME_NS.get()) { - LOG.info("Request processing took longer than threshold! toplevelid = {}, {}", topLevelRequestId, ChannelUtils.channelInfoForLogging(channel)); + LOG.info( + "Request processing took longer than threshold! toplevelid = {}, {}", + topLevelRequestId, + ChannelUtils.channelInfoForLogging(channel)); } - StartAndEnd inRespToOutResp = passport.findLastStartAndFirstEndStates(PassportState.IN_RESP_HEADERS_RECEIVED, PassportState.OUT_RESP_LAST_CONTENT_SENT); - if (passport.calculateTimeBetween(inRespToOutResp) - > WARN_RESP_PROCESSING_TIME_NS.get()) { - LOG.info("Response processing took longer than threshold! toplevelid = {}, {}", topLevelRequestId, ChannelUtils.channelInfoForLogging(channel)); + StartAndEnd inRespToOutResp = passport.findLastStartAndFirstEndStates( + PassportState.IN_RESP_HEADERS_RECEIVED, PassportState.OUT_RESP_LAST_CONTENT_SENT); + if (passport.calculateTimeBetween(inRespToOutResp) > WARN_RESP_PROCESSING_TIME_NS.get()) { + LOG.info( + "Response processing took longer than threshold! toplevelid = {}, {}", + topLevelRequestId, + ChannelUtils.channelInfoForLogging(channel)); } } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateHttpClientHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateHttpClientHandler.java index 3d9e14afef..dcd9a9d817 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateHttpClientHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateHttpClientHandler.java @@ -34,16 +34,13 @@ */ public final class PassportStateHttpClientHandler { - private static CurrentPassport passport(ChannelHandlerContext ctx) - { + private static CurrentPassport passport(ChannelHandlerContext ctx) { return CurrentPassport.fromChannel(ctx.channel()); } - public static final class InboundHandler extends ChannelInboundHandlerAdapter - { + public static final class InboundHandler extends ChannelInboundHandlerAdapter { @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { CurrentPassport passport = passport(ctx); @@ -53,46 +50,39 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception if (msg instanceof LastHttpContent) { passport.add(PassportState.IN_RESP_LAST_CONTENT_RECEIVED); - } - else if (msg instanceof HttpContent) { + } else if (msg instanceof HttpContent) { passport.add(PassportState.IN_RESP_CONTENT_RECEIVED); } - } - finally { + } finally { super.channelRead(ctx, msg); } } } - public static final class OutboundHandler extends ChannelOutboundHandlerAdapter - { + public static final class OutboundHandler extends ChannelOutboundHandlerAdapter { @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { try { CurrentPassport passport = passport(ctx); if (msg instanceof HttpRequest) { passport.add(PassportState.OUT_REQ_HEADERS_SENDING); - promise.addListener(new PassportStateListener(passport, - PassportState.OUT_REQ_HEADERS_SENT, - PassportState.OUT_REQ_HEADERS_ERROR_SENDING)); + promise.addListener(new PassportStateListener( + passport, PassportState.OUT_REQ_HEADERS_SENT, PassportState.OUT_REQ_HEADERS_ERROR_SENDING)); } - + if (msg instanceof LastHttpContent) { passport.add(PassportState.OUT_REQ_LAST_CONTENT_SENDING); - promise.addListener(new PassportStateListener(passport, + promise.addListener(new PassportStateListener( + passport, PassportState.OUT_REQ_LAST_CONTENT_SENT, PassportState.OUT_REQ_LAST_CONTENT_ERROR_SENDING)); - } - else if (msg instanceof HttpContent) { + } else if (msg instanceof HttpContent) { passport.add(PassportState.OUT_REQ_CONTENT_SENDING); - promise.addListener(new PassportStateListener(passport, - PassportState.OUT_REQ_CONTENT_SENT, - PassportState.OUT_REQ_CONTENT_ERROR_SENDING)); + promise.addListener(new PassportStateListener( + passport, PassportState.OUT_REQ_CONTENT_SENT, PassportState.OUT_REQ_CONTENT_ERROR_SENDING)); } - } - finally { + } finally { super.write(ctx, msg, promise); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateHttpServerHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateHttpServerHandler.java index 639980264d..b070b10a85 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateHttpServerHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateHttpServerHandler.java @@ -35,19 +35,16 @@ */ public final class PassportStateHttpServerHandler { - private static CurrentPassport passport(ChannelHandlerContext ctx) - { + private static CurrentPassport passport(ChannelHandlerContext ctx) { return CurrentPassport.fromChannel(ctx.channel()); } - - public static final class InboundHandler extends ChannelInboundHandlerAdapter - { + + public static final class InboundHandler extends ChannelInboundHandlerAdapter { @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // Get existing passport or create new if none already. CurrentPassport passport = passport(ctx); - + if (msg instanceof HttpRequest) { // If the current passport for this channel already contains an inbound http request, then // we know it's used, so discard and create a new one. @@ -56,27 +53,24 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception if (passport.findState(PassportState.IN_REQ_HEADERS_RECEIVED) != null) { passport = CurrentPassport.createForChannel(ctx.channel()); } - + passport.add(PassportState.IN_REQ_HEADERS_RECEIVED); } - + if (msg instanceof LastHttpContent) { passport.add(PassportState.IN_REQ_LAST_CONTENT_RECEIVED); - } - else if (msg instanceof HttpContent) { + } else if (msg instanceof HttpContent) { passport.add(PassportState.IN_REQ_CONTENT_RECEIVED); } - + super.channelRead(ctx, msg); } @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception - { + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { try { super.userEventTriggered(ctx, evt); - } - finally { + } finally { if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) { CurrentPassport.clearFromChannel(ctx.channel()); } @@ -84,34 +78,30 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc } } - public static final class OutboundHandler extends ChannelOutboundHandlerAdapter - { + public static final class OutboundHandler extends ChannelOutboundHandlerAdapter { @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { CurrentPassport passport = passport(ctx); - + // Set into the SENDING state. if (msg instanceof HttpResponse) { passport.add(PassportState.OUT_RESP_HEADERS_SENDING); - promise.addListener(new PassportStateListener(passport, - PassportState.OUT_RESP_HEADERS_SENT, - PassportState.OUT_RESP_HEADERS_ERROR_SENDING)); + promise.addListener(new PassportStateListener( + passport, PassportState.OUT_RESP_HEADERS_SENT, PassportState.OUT_RESP_HEADERS_ERROR_SENDING)); } if (msg instanceof LastHttpContent) { passport.add(PassportState.OUT_RESP_LAST_CONTENT_SENDING); - promise.addListener(new PassportStateListener(passport, + promise.addListener(new PassportStateListener( + passport, PassportState.OUT_RESP_LAST_CONTENT_SENT, PassportState.OUT_RESP_LAST_CONTENT_ERROR_SENDING)); - } - else if (msg instanceof HttpContent) { + } else if (msg instanceof HttpContent) { passport.add(PassportState.OUT_RESP_CONTENT_SENDING); - promise.addListener(new PassportStateListener(passport, - PassportState.OUT_RESP_CONTENT_SENT, - PassportState.OUT_RESP_CONTENT_ERROR_SENDING)); + promise.addListener(new PassportStateListener( + passport, PassportState.OUT_RESP_CONTENT_SENT, PassportState.OUT_RESP_CONTENT_ERROR_SENDING)); } - + // Continue with the write. super.write(ctx, msg, promise); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateListener.java b/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateListener.java index 17127f80b7..372f28dc21 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateListener.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateListener.java @@ -21,33 +21,28 @@ import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; -public class PassportStateListener implements GenericFutureListener -{ +public class PassportStateListener implements GenericFutureListener { private final CurrentPassport passport; private final PassportState successState; private final PassportState failState; - public PassportStateListener(CurrentPassport passport, PassportState successState) - { + public PassportStateListener(CurrentPassport passport, PassportState successState) { this.passport = passport; this.successState = successState; this.failState = null; } - - public PassportStateListener(CurrentPassport passport, PassportState successState, PassportState failState) - { + + public PassportStateListener(CurrentPassport passport, PassportState successState, PassportState failState) { this.passport = passport; this.successState = successState; this.failState = failState; } @Override - public void operationComplete(Future future) throws Exception - { + public void operationComplete(Future future) throws Exception { if (future.isSuccess()) { passport.add(successState); - } - else { + } else { if (failState != null) { // only capture a single failure state event, // as sending content errors will fire for all content chunks, diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateOriginHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateOriginHandler.java index adc7c02660..6123657160 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateOriginHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateOriginHandler.java @@ -31,30 +31,26 @@ * Time: 2:41 PM */ public final class PassportStateOriginHandler { - private static CurrentPassport passport(ChannelHandlerContext ctx) - { + private static CurrentPassport passport(ChannelHandlerContext ctx) { return CurrentPassport.fromChannel(ctx.channel()); } public static final class InboundHandler extends ChannelInboundHandlerAdapter { @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception - { + public void channelActive(ChannelHandlerContext ctx) throws Exception { passport(ctx).add(PassportState.ORIGIN_CH_ACTIVE); super.channelActive(ctx); } @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception - { + public void channelInactive(ChannelHandlerContext ctx) throws Exception { passport(ctx).add(PassportState.ORIGIN_CH_INACTIVE); super.channelInactive(ctx); } @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception - { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { passport(ctx).add(PassportState.ORIGIN_CH_EXCEPTION); super.exceptionCaught(ctx, cause); } @@ -63,35 +59,38 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E public static final class OutboundHandler extends ChannelOutboundHandlerAdapter { @Override - public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception - { + public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { passport(ctx).add(PassportState.ORIGIN_CH_DISCONNECT); super.disconnect(ctx, promise); } @Override - public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception - { + public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { passport(ctx).add(PassportState.ORIGIN_CH_CLOSE); super.close(ctx, promise); } @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception - { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { passport(ctx).add(PassportState.ORIGIN_CH_EXCEPTION); super.exceptionCaught(ctx, cause); } @Override - public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception - { - // We would prefer to set this passport state here, but if we do then it will be run _after_ the http request + public void connect( + ChannelHandlerContext ctx, + SocketAddress remoteAddress, + SocketAddress localAddress, + ChannelPromise promise) + throws Exception { + // We would prefer to set this passport state here, but if we do then it will be run _after_ the http + // request // has actually been written to the channel. Because another listener is added before this one. - // So instead we have to add this listener in the PerServerConnectionPool.handleConnectCompletion() method instead. - //passport.add(PassportState.ORIGIN_CH_CONNECTING); - //promise.addListener(new PassportStateListener(passport, PassportState.ORIGIN_CH_CONNECTED)); - + // So instead we have to add this listener in the PerServerConnectionPool.handleConnectCompletion() method + // instead. + // passport.add(PassportState.ORIGIN_CH_CONNECTING); + // promise.addListener(new PassportStateListener(passport, PassportState.ORIGIN_CH_CONNECTED)); + super.connect(ctx, remoteAddress, localAddress, promise); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/insights/ServerStateHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/insights/ServerStateHandler.java index dddb5c7559..cf9e015a8b 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/insights/ServerStateHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/insights/ServerStateHandler.java @@ -29,7 +29,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /** * User: Mike Smith Date: 9/24/16 Time: 2:41 PM */ @@ -74,9 +73,12 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { connectionErrors.increment(); - registry.counter("server.connection.exception.inbound", - "handler", "ServerStateHandler.InboundHandler", - "id", cause.getClass().getSimpleName()) + registry.counter( + "server.connection.exception.inbound", + "handler", + "ServerStateHandler.InboundHandler", + "id", + cause.getClass().getSimpleName()) .increment(); passport(ctx).add(PassportState.SERVER_CH_EXCEPTION); logger.info("Connection error on Inbound: {} ", cause); @@ -122,9 +124,12 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E passport(ctx).add(PassportState.SERVER_CH_EXCEPTION); if (cause instanceof Errors.NativeIoException) { logger.debug("PassportStateServerHandler Outbound NativeIoException {}", cause); - registry.counter("server.connection.exception.outbound", - "handler", "ServerStateHandler.OutboundHandler", - "id", cause.getClass().getSimpleName()) + registry.counter( + "server.connection.exception.outbound", + "handler", + "ServerStateHandler.OutboundHandler", + "id", + cause.getClass().getSimpleName()) .increment(); } else { diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/ratelimiting/NullChannelHandlerProvider.java b/zuul-core/src/main/java/com/netflix/zuul/netty/ratelimiting/NullChannelHandlerProvider.java index 76eff338b0..d753316a1d 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/ratelimiting/NullChannelHandlerProvider.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/ratelimiting/NullChannelHandlerProvider.java @@ -22,8 +22,7 @@ import javax.inject.Singleton; @Singleton -public class NullChannelHandlerProvider implements Provider -{ +public class NullChannelHandlerProvider implements Provider { @Override public ChannelHandler get() { return null; diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/BaseServerStartup.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/BaseServerStartup.java index 521f7cfdc0..8a8a973d2a 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/BaseServerStartup.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/BaseServerStartup.java @@ -43,22 +43,24 @@ import io.netty.handler.ssl.SslContext; import io.netty.util.AsyncMapping; import io.netty.util.concurrent.GlobalEventExecutor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; +import javax.inject.Inject; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Map; -import javax.annotation.Nullable; -import javax.inject.Inject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -public abstract class BaseServerStartup -{ +public abstract class BaseServerStartup { protected static final Logger LOG = LoggerFactory.getLogger(BaseServerStartup.class); protected final ServerStatusManager serverStatusManager; protected final Registry registry; + @SuppressWarnings("unused") // force initialization protected final DirectMemoryMonitor directMemoryMonitor; + protected final EventLoopGroupMetrics eventLoopGroupMetrics; protected final EventLoopConfig eventLoopConfig; protected final EurekaClient discoveryClient; @@ -73,16 +75,20 @@ public abstract class BaseServerStartup private ClientConnectionsShutdown clientConnectionsShutdown; private Server server; - @Inject - public BaseServerStartup(ServerStatusManager serverStatusManager, FilterLoader filterLoader, - SessionContextDecorator sessionCtxDecorator, FilterUsageNotifier usageNotifier, - RequestCompleteHandler reqCompleteHandler, Registry registry, - DirectMemoryMonitor directMemoryMonitor, EventLoopGroupMetrics eventLoopGroupMetrics, - EventLoopConfig eventLoopConfig, EurekaClient discoveryClient, + public BaseServerStartup( + ServerStatusManager serverStatusManager, + FilterLoader filterLoader, + SessionContextDecorator sessionCtxDecorator, + FilterUsageNotifier usageNotifier, + RequestCompleteHandler reqCompleteHandler, + Registry registry, + DirectMemoryMonitor directMemoryMonitor, + EventLoopGroupMetrics eventLoopGroupMetrics, + EventLoopConfig eventLoopConfig, + EurekaClient discoveryClient, ApplicationInfoManager applicationInfoManager, - AccessLogPublisher accessLogPublisher) - { + AccessLogPublisher accessLogPublisher) { this.serverStatusManager = serverStatusManager; this.registry = registry; this.directMemoryMonitor = directMemoryMonitor; @@ -97,17 +103,15 @@ public BaseServerStartup(ServerStatusManager serverStatusManager, FilterLoader f this.usageNotifier = usageNotifier; } - public Server server() - { + public Server server() { return server; } @Inject - public void init() throws Exception - { + public void init() throws Exception { ChannelGroup clientChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); - clientConnectionsShutdown = new ClientConnectionsShutdown(clientChannels, - GlobalEventExecutor.INSTANCE, discoveryClient); + clientConnectionsShutdown = + new ClientConnectionsShutdown(clientChannels, GlobalEventExecutor.INSTANCE, discoveryClient); addrsToChannelInitializers = chooseAddrsAndChannels(clientChannels); @@ -137,7 +141,6 @@ protected Map> chooseAddrsAndChannels( return Server.convertPortMap(portMap); } - protected ChannelConfig defaultChannelDependencies(String listenAddressName) { ChannelConfig channelDependencies = new ChannelConfig(); addChannelDependencies(channelDependencies, listenAddressName); @@ -191,9 +194,12 @@ public static boolean chooseBooleanChannelProperty( String listenAddressPropertyName = "server." + listenAddressName + "." + propertySuffix; Boolean value = new ChainedDynamicProperty.DynamicBooleanPropertyThatSupportsNull( - listenAddressPropertyName, null).get(); + listenAddressPropertyName, null) + .get(); if (value == null) { - value = new DynamicBooleanProperty(globalPropertyName, defaultValue).getDynamicProperty().getBoolean(); + value = new DynamicBooleanProperty(globalPropertyName, defaultValue) + .getDynamicProperty() + .getBoolean(); if (value == null) { value = defaultValue; } @@ -208,14 +214,17 @@ public static ChannelConfig defaultChannelConfig(String listenAddressName) { CommonChannelConfigKeys.maxConnections, chooseIntChannelProperty( listenAddressName, "connection.max", CommonChannelConfigKeys.maxConnections.defaultValue()))); - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.maxRequestsPerConnection, + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.maxRequestsPerConnection, chooseIntChannelProperty(listenAddressName, "connection.max.requests", 20000))); - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.maxRequestsPerConnectionInBrownout, + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.maxRequestsPerConnectionInBrownout, chooseIntChannelProperty( listenAddressName, "connection.max.requests.brownout", CommonChannelConfigKeys.maxRequestsPerConnectionInBrownout.defaultValue()))); - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.connectionExpiry, + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.connectionExpiry, chooseIntChannelProperty( listenAddressName, "connection.expiry", @@ -228,18 +237,20 @@ public static ChannelConfig defaultChannelConfig(String listenAddressName) { CommonChannelConfigKeys.httpRequestReadTimeout.defaultValue()))); int connectionIdleTimeout = chooseIntChannelProperty( - listenAddressName, "connection.idle.timeout", - CommonChannelConfigKeys.idleTimeout.defaultValue()); + listenAddressName, "connection.idle.timeout", CommonChannelConfigKeys.idleTimeout.defaultValue()); config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.idleTimeout, connectionIdleTimeout)); - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.serverTimeout, new ServerTimeout(connectionIdleTimeout))); + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.serverTimeout, new ServerTimeout(connectionIdleTimeout))); // For security, default to NEVER allowing XFF/Proxy headers from client. - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER)); + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER)); config.set(CommonChannelConfigKeys.withProxyProtocol, true); config.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.connCloseDelay, + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.connCloseDelay, chooseIntChannelProperty( listenAddressName, "connection.close.delay", @@ -249,29 +260,36 @@ public static ChannelConfig defaultChannelConfig(String listenAddressName) { } public static void addHttp2DefaultConfig(ChannelConfig config, String listenAddressName) { - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.maxConcurrentStreams, + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.maxConcurrentStreams, chooseIntChannelProperty( listenAddressName, "http2.max.concurrent.streams", CommonChannelConfigKeys.maxConcurrentStreams.defaultValue()))); - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.initialWindowSize, + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.initialWindowSize, chooseIntChannelProperty( listenAddressName, "http2.initialwindowsize", CommonChannelConfigKeys.initialWindowSize.defaultValue()))); - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.maxHttp2HeaderTableSize, + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.maxHttp2HeaderTableSize, chooseIntChannelProperty(listenAddressName, "http2.maxheadertablesize", 65536))); - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.maxHttp2HeaderListSize, + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.maxHttp2HeaderListSize, chooseIntChannelProperty(listenAddressName, "http2.maxheaderlistsize", 32768))); // Override this to a lower value, as we'll be using ELB TCP listeners for h2, and therefore the connection // is direct from each device rather than shared in an ELB pool. - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.maxRequestsPerConnection, + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.maxRequestsPerConnection, chooseIntChannelProperty(listenAddressName, "connection.max.requests", 4000))); - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.http2AllowGracefulDelayed, + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.http2AllowGracefulDelayed, chooseBooleanChannelProperty(listenAddressName, "connection.close.graceful.delayed.allow", true))); - config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.http2SwallowUnknownExceptionsOnConnClose, + config.add(new ChannelConfigValue<>( + CommonChannelConfigKeys.http2SwallowUnknownExceptionsOnConnClose, chooseBooleanChannelProperty(listenAddressName, "connection.close.swallow.unknown.exceptions", false))); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/BaseZuulChannelInitializer.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/BaseZuulChannelInitializer.java index 854ca5f6d9..900249be2c 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/BaseZuulChannelInitializer.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/BaseZuulChannelInitializer.java @@ -16,11 +16,6 @@ package com.netflix.zuul.netty.server; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.netflix.zuul.passport.PassportState.FILTERS_INBOUND_END; -import static com.netflix.zuul.passport.PassportState.FILTERS_INBOUND_START; -import static com.netflix.zuul.passport.PassportState.FILTERS_OUTBOUND_END; -import static com.netflix.zuul.passport.PassportState.FILTERS_OUTBOUND_START; import com.netflix.config.CachedDynamicIntProperty; import com.netflix.netty.common.CloseOnIdleStateHandler; import com.netflix.netty.common.Http1ConnectionCloseHandler; @@ -70,24 +65,33 @@ import io.netty.handler.logging.LoggingHandler; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.AttributeKey; + import java.util.SortedSet; import java.util.concurrent.TimeUnit; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.netflix.zuul.passport.PassportState.FILTERS_INBOUND_END; +import static com.netflix.zuul.passport.PassportState.FILTERS_INBOUND_START; +import static com.netflix.zuul.passport.PassportState.FILTERS_OUTBOUND_END; +import static com.netflix.zuul.passport.PassportState.FILTERS_OUTBOUND_START; + /** * User: Mike Smith * Date: 3/5/16 * Time: 6:26 PM */ -public abstract class BaseZuulChannelInitializer extends ChannelInitializer -{ +public abstract class BaseZuulChannelInitializer extends ChannelInitializer { public static final String HTTP_CODEC_HANDLER_NAME = "codec"; public static final AttributeKey ATTR_CHANNEL_CONFIG = AttributeKey.newInstance("channel_config"); protected static final LoggingHandler nettyLogger = new LoggingHandler("zuul.server.nettylog", LogLevel.INFO); - public static final CachedDynamicIntProperty MAX_INITIAL_LINE_LENGTH = new CachedDynamicIntProperty("server.http.decoder.maxInitialLineLength", 16384); - public static final CachedDynamicIntProperty MAX_HEADER_SIZE = new CachedDynamicIntProperty("server.http.decoder.maxHeaderSize", 32768); - public static final CachedDynamicIntProperty MAX_CHUNK_SIZE = new CachedDynamicIntProperty("server.http.decoder.maxChunkSize", 32768); + public static final CachedDynamicIntProperty MAX_INITIAL_LINE_LENGTH = + new CachedDynamicIntProperty("server.http.decoder.maxInitialLineLength", 16384); + public static final CachedDynamicIntProperty MAX_HEADER_SIZE = + new CachedDynamicIntProperty("server.http.decoder.maxHeaderSize", 32768); + public static final CachedDynamicIntProperty MAX_CHUNK_SIZE = + new CachedDynamicIntProperty("server.http.decoder.maxChunkSize", 32768); /** * The port that the server intends to listen on. Subclasses should NOT use this field, as it may not be set, and @@ -102,6 +106,7 @@ public abstract class BaseZuulChannelInitializer extends ChannelInitializer -1) { - HttpRequestReadTimeoutHandler.addLast(pipeline, httpRequestReadTimeout, TimeUnit.MILLISECONDS, httpRequestReadTimeoutCounter); + HttpRequestReadTimeoutHandler.addLast( + pipeline, httpRequestReadTimeout, TimeUnit.MILLISECONDS, httpRequestReadTimeoutCounter); } pipeline.addLast(new HttpServerLifecycleChannelHandler.HttpServerLifecycleInboundChannelHandler()); pipeline.addLast(new HttpServerLifecycleChannelHandler.HttpServerLifecycleOutboundChannelHandler()); @@ -280,7 +280,7 @@ protected void addHttpRelatedHandlers(ChannelPipeline pipeline) pipeline.addLast(rateLimitingChannelHandler); } - //pipeline.addLast(requestRejectedChannelHandler); + // pipeline.addLast(requestRejectedChannelHandler); } protected void addTimeoutHandlers(ChannelPipeline pipeline) { @@ -293,8 +293,7 @@ protected void addSslInfoHandlers(ChannelPipeline pipeline, boolean isSSlFromInt pipeline.addLast("ssl_exceptions", new SslExceptionsHandler(registry)); } - protected void addSslClientCertChecks(ChannelPipeline pipeline) - { + protected void addSslClientCertChecks(ChannelPipeline pipeline) { if (channelConfig.get(ZuulDependencyKeys.SSL_CLIENT_CERT_CHECK_REQUIRED)) { if (this.sslClientCertCheckChannelHandler == null) { throw new IllegalArgumentException("A sslClientCertCheckChannelHandler is required!"); @@ -303,8 +302,7 @@ protected void addSslClientCertChecks(ChannelPipeline pipeline) } } - protected void addZuulHandlers(final ChannelPipeline pipeline) - { + protected void addZuulHandlers(final ChannelPipeline pipeline) { pipeline.addLast("logger", nettyLogger); pipeline.addLast(new ClientRequestReceiver(sessionContextDecorator)); pipeline.addLast(passportLoggingHandler); @@ -318,42 +316,43 @@ protected void addZuulFilterChainHandler(final ChannelPipeline pipeline) { new OutboundPassportStampingFilter(FILTERS_OUTBOUND_END)); // response filter chain - final ZuulFilterChainRunner responseFilterChain = getFilterChainRunner(responseFilters, - filterUsageNotifier); + final ZuulFilterChainRunner responseFilterChain = + getFilterChainRunner(responseFilters, filterUsageNotifier); // endpoint | response filter chain - final FilterRunner endPoint = getEndpointRunner(responseFilterChain, - filterUsageNotifier, filterLoader); + final FilterRunner endPoint = + getEndpointRunner(responseFilterChain, filterUsageNotifier, filterLoader); final ZuulFilter[] requestFilters = getFilters( new InboundPassportStampingFilter(FILTERS_INBOUND_START), new InboundPassportStampingFilter(FILTERS_INBOUND_END)); // request filter chain | end point | response filter chain - final ZuulFilterChainRunner requestFilterChain = getFilterChainRunner(requestFilters, - filterUsageNotifier, endPoint); + final ZuulFilterChainRunner requestFilterChain = + getFilterChainRunner(requestFilters, filterUsageNotifier, endPoint); pipeline.addLast(new ZuulFilterChainHandler(requestFilterChain, responseFilterChain)); } - protected ZuulEndPointRunner getEndpointRunner(ZuulFilterChainRunner responseFilterChain, - FilterUsageNotifier filterUsageNotifier, FilterLoader filterLoader) { + protected ZuulEndPointRunner getEndpointRunner( + ZuulFilterChainRunner responseFilterChain, + FilterUsageNotifier filterUsageNotifier, + FilterLoader filterLoader) { return new ZuulEndPointRunner(filterUsageNotifier, filterLoader, responseFilterChain, registry); } - protected ZuulFilterChainRunner getFilterChainRunner(ZuulFilter[] filters, - FilterUsageNotifier filterUsageNotifier) { + protected ZuulFilterChainRunner getFilterChainRunner( + ZuulFilter[] filters, FilterUsageNotifier filterUsageNotifier) { return new ZuulFilterChainRunner<>(filters, filterUsageNotifier, registry); } - protected ZuulFilterChainRunner getFilterChainRunner(ZuulFilter[] filters, - FilterUsageNotifier filterUsageNotifier, - FilterRunner filterRunner) { + protected ZuulFilterChainRunner getFilterChainRunner( + ZuulFilter[] filters, FilterUsageNotifier filterUsageNotifier, FilterRunner filterRunner) { return new ZuulFilterChainRunner<>(filters, filterUsageNotifier, filterRunner, registry); } @SuppressWarnings("unchecked") // For the conversion from getFiltersByType. It's not safe, sorry. - public ZuulFilter [] getFilters(ZuulFilter start, ZuulFilter stop) { + public ZuulFilter[] getFilters(ZuulFilter start, ZuulFilter stop) { final SortedSet> zuulFilters = filterLoader.getFiltersByType(start.filterType()); final ZuulFilter[] filters = new ZuulFilter[zuulFilters.size() + 2]; filters[0] = start; @@ -362,7 +361,7 @@ protected ZuulFilterChainRunner) filter; } - filters[filters.length -1] = stop; + filters[filters.length - 1] = stop; return filters; } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientConnectionsShutdown.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientConnectionsShutdown.java index 07ef0c0866..f3b0896a5e 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientConnectionsShutdown.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientConnectionsShutdown.java @@ -30,10 +30,11 @@ import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.concurrent.TimeUnit; + /** * TODO: Change this class to be an instance per-port. * So that then the configuration can be different per-port, which is need for the combined FTL/Cloud clusters. @@ -45,11 +46,12 @@ public class ClientConnectionsShutdown { private static final Logger LOG = LoggerFactory.getLogger(ClientConnectionsShutdown.class); - private static final DynamicBooleanProperty ENABLED = new DynamicBooleanProperty( - "server.outofservice.connections.shutdown", false); + private static final DynamicBooleanProperty ENABLED = + new DynamicBooleanProperty("server.outofservice.connections.shutdown", false); private static final DynamicIntProperty DELAY_AFTER_OUT_OF_SERVICE_MS = new DynamicIntProperty("server.outofservice.connections.delay", 2000); - private static final DynamicIntProperty GRACEFUL_CLOSE_TIMEOUT = new DynamicIntProperty("server.outofservice.close.timeout", 30); + private static final DynamicIntProperty GRACEFUL_CLOSE_TIMEOUT = + new DynamicIntProperty("server.outofservice.close.timeout", 30); private final ChannelGroup channels; private final EventExecutor executor; @@ -74,12 +76,14 @@ private void initDiscoveryListener() { if (sce.getPreviousStatus() == InstanceInfo.InstanceStatus.UP && (sce.getStatus() == InstanceInfo.InstanceStatus.OUT_OF_SERVICE - || sce.getStatus() == InstanceInfo.InstanceStatus.DOWN)) { + || sce.getStatus() == InstanceInfo.InstanceStatus.DOWN)) { // TODO - Also should stop accepting any new client connections now too? // Schedule to gracefully close all the client connections. if (ENABLED.get()) { - executor.schedule(() -> gracefullyShutdownClientChannels(false), DELAY_AFTER_OUT_OF_SERVICE_MS.get(), + executor.schedule( + () -> gracefullyShutdownClientChannels(false), + DELAY_AFTER_OUT_OF_SERVICE_MS.get(), TimeUnit.MILLISECONDS); } } @@ -95,8 +99,8 @@ Promise gracefullyShutdownClientChannels(boolean forceCloseAfterTimeout) { // Mark all active connections to be closed after next response sent. LOG.warn("Flagging CLOSE_AFTER_RESPONSE on {} client channels.", channels.size()); - //racy situation if new connections are still coming in, but any channels created after newCloseFuture will - //be closed during the force close stage + // racy situation if new connections are still coming in, but any channels created after newCloseFuture will + // be closed during the force close stage ChannelGroupFuture closeFuture = channels.newCloseFuture(); for (Channel channel : channels) { ConnectionCloseType.setForChannel(channel, ConnectionCloseType.DELAYED_GRACEFUL); @@ -106,14 +110,17 @@ Promise gracefullyShutdownClientChannels(boolean forceCloseAfterTimeout) { Promise promise = executor.newPromise(); Runnable cancelTimeoutTask; - if(forceCloseAfterTimeout) { - ScheduledFuture timeoutTask = executor.schedule(() -> { - LOG.warn("Force closing remaining {} active client channels.", channels.size()); - channels.close(); - }, GRACEFUL_CLOSE_TIMEOUT.get(), TimeUnit.SECONDS); + if (forceCloseAfterTimeout) { + ScheduledFuture timeoutTask = executor.schedule( + () -> { + LOG.warn("Force closing remaining {} active client channels.", channels.size()); + channels.close(); + }, + GRACEFUL_CLOSE_TIMEOUT.get(), + TimeUnit.SECONDS); cancelTimeoutTask = () -> { if (!timeoutTask.isDone()) { - //close happened before the timeout + // close happened before the timeout timeoutTask.cancel(false); } }; @@ -128,5 +135,4 @@ Promise gracefullyShutdownClientChannels(boolean forceCloseAfterTimeout) { return promise; } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientRequestReceiver.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientRequestReceiver.java index 27759e10e2..403ecefd57 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientRequestReceiver.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientRequestReceiver.java @@ -16,11 +16,6 @@ package com.netflix.zuul.netty.server; -import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent; -import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason; -import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason.SESSION_COMPLETE; -import static com.netflix.zuul.netty.server.http2.Http2OrHttpHandler.PROTOCOL_NAME; - import com.netflix.netty.common.SourceAddressChannelHandler; import com.netflix.netty.common.ssl.SslHandshakeInfo; import com.netflix.netty.common.throttle.RejectionUtils; @@ -65,18 +60,22 @@ import io.netty.util.ReferenceCountUtil; import io.perfmark.PerfMark; import io.perfmark.TaskCloseable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.SSLException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.net.ssl.SSLException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent; +import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason; +import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason.SESSION_COMPLETE; +import static com.netflix.zuul.netty.server.http2.Http2OrHttpHandler.PROTOCOL_NAME; /** * Created by saroskar on 1/6/17. @@ -85,7 +84,8 @@ public class ClientRequestReceiver extends ChannelDuplexHandler { public static final AttributeKey ATTR_ZUUL_REQ = AttributeKey.newInstance("_zuul_request"); public static final AttributeKey ATTR_ZUUL_RESP = AttributeKey.newInstance("_zuul_response"); - public static final AttributeKey ATTR_LAST_CONTENT_RECEIVED = AttributeKey.newInstance("_last_content_received"); + public static final AttributeKey ATTR_LAST_CONTENT_RECEIVED = + AttributeKey.newInstance("_last_content_received"); private static final Logger LOG = LoggerFactory.getLogger(ClientRequestReceiver.class); private static final String SCHEME_HTTP = "http"; @@ -100,7 +100,6 @@ public class ClientRequestReceiver extends ChannelDuplexHandler { private HttpRequestMessage zuulRequest; private HttpRequest clientRequest; - public ClientRequestReceiver(SessionContextDecorator decorator) { this.decorator = decorator; } @@ -147,8 +146,7 @@ private void channelReadInternal(final ChannelHandlerContext ctx, Object msg) th ChannelUtils.channelInfoForLogging(ctx.channel()), clientRequest.decoderResult().cause()); StatusCategoryUtils.setStatusCategory( - zuulRequest.getContext(), - ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST); + zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST); RejectionUtils.rejectByClosingConnection( ctx, ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST, @@ -164,11 +162,14 @@ private void channelReadInternal(final ChannelHandlerContext ctx, Object msg) th final ZuulException ze = new ZuulException(errorMsg); ze.setStatusCode(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE.code()); StatusCategoryUtils.setStatusCategory( - zuulRequest.getContext(), - ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST); + zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST); zuulRequest.getContext().setError(ze); zuulRequest.getContext().setShouldSendErrorResponse(true); - } else if (zuulRequest.getHeaders().getAll(HttpHeaderNames.HOST.toString()).size() > 1) { + } else if (zuulRequest + .getHeaders() + .getAll(HttpHeaderNames.HOST.toString()) + .size() + > 1) { LOG.debug( "Multiple Host headers. clientRequest = {} , uri = {}, info = {}", clientRequest, @@ -177,32 +178,28 @@ private void channelReadInternal(final ChannelHandlerContext ctx, Object msg) th final ZuulException ze = new ZuulException("Multiple Host headers"); ze.setStatusCode(HttpResponseStatus.BAD_REQUEST.code()); StatusCategoryUtils.setStatusCategory( - zuulRequest.getContext(), - ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST); + zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST); zuulRequest.getContext().setError(ze); zuulRequest.getContext().setShouldSendErrorResponse(true); } handleExpect100Continue(ctx, clientRequest); - - //Send the request down the filter pipeline + // Send the request down the filter pipeline ctx.fireChannelRead(zuulRequest); - } - else if (msg instanceof HttpContent) { - if ((zuulRequest != null) && (! zuulRequest.getContext().isCancelled())) { + } else if (msg instanceof HttpContent) { + if ((zuulRequest != null) && (!zuulRequest.getContext().isCancelled())) { ctx.fireChannelRead(msg); } else { - //We already sent response for this request, these are laggard request body chunks that are still arriving + // We already sent response for this request, these are laggard request body chunks that are still + // arriving ReferenceCountUtil.release(msg); } - } - else if (msg instanceof HAProxyMessage) { + } else if (msg instanceof HAProxyMessage) { // do nothing, should already be handled by ElbProxyProtocolHandler LOG.debug("Received HAProxyMessage for Proxy Protocol IP: {}", ((HAProxyMessage) msg).sourceAddress()); ReferenceCountUtil.release(msg); - } - else { + } else { LOG.debug("Received unrecognized message type. {}", msg.getClass().getName()); ReferenceCountUtil.release(msg); } @@ -224,23 +221,32 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc if (reason == CompleteReason.INACTIVE && zuulRequest != null) { // Client closed connection prematurely. - StatusCategoryUtils.setStatusCategory(zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_CANCELLED); + StatusCategoryUtils.setStatusCategory( + zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_CANCELLED); } if (reason == CompleteReason.PIPELINE_REJECT && zuulRequest != null) { - StatusCategoryUtils.setStatusCategory(zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_PIPELINE_REJECT); + StatusCategoryUtils.setStatusCategory( + zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_PIPELINE_REJECT); } if (reason != SESSION_COMPLETE && zuulRequest != null) { final SessionContext zuulCtx = zuulRequest.getContext(); if (clientRequest != null) { if (LOG.isInfoEnabled()) { - // With http/2, the netty codec closes/completes the stream immediately after writing the lastcontent - // of response to the channel, which causes this CompleteEvent to fire before we have cleaned up state. But + // With http/2, the netty codec closes/completes the stream immediately after writing the + // lastcontent + // of response to the channel, which causes this CompleteEvent to fire before we have cleaned up + // state. But // thats ok, so don't log in that case. - if (! "HTTP/2".equals(zuulRequest.getProtocol())) { - LOG.debug("Client {} request UUID {} to {} completed with reason = {}, {}", clientRequest.method(), - zuulCtx.getUUID(), clientRequest.uri(), reason.name(), ChannelUtils.channelInfoForLogging(ctx.channel())); + if (!"HTTP/2".equals(zuulRequest.getProtocol())) { + LOG.debug( + "Client {} request UUID {} to {} completed with reason = {}, {}", + clientRequest.method(), + zuulCtx.getUUID(), + clientRequest.uri(), + reason.name(), + ChannelUtils.channelInfoForLogging(ctx.channel())); } } } @@ -278,9 +284,10 @@ private static void dumpDebugInfo(final List debugInfo) { private void handleExpect100Continue(ChannelHandlerContext ctx, HttpRequest req) { if (HttpUtil.is100ContinueExpected(req)) { PerfMark.event("CRR.handleExpect100Continue"); - final ChannelFuture f = ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); + final ChannelFuture f = + ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); f.addListener((s) -> { - if (! s.isSuccess()) { + if (!s.isSuccess()) { throw new ZuulException(s.cause(), "Failed while writing 100-continue response", true); } }); @@ -303,28 +310,33 @@ private HttpRequestMessage buildZuulHttpRequest( context = decorator.decorate(tempContext); // We expect the UUID is present after decoration PerfMark.attachTag("uuid", context, SessionContext::getUUID); - } - else { + } else { context = new SessionContext(); } // Get the client IP (ignore XFF headers at this point, as that can be app specific). final Channel channel = clientCtx.channel(); - final String clientIp = channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get(); + final String clientIp = + channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get(); // This is the only way I found to get the port of the request with netty... - final int port = channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).get(); - final String serverName = channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_ADDRESS).get(); - final SocketAddress clientDestinationAddress = channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get(); - final InetSocketAddress proxyProtocolDestinationAddress = - channel.attr(SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS).get(); + final int port = + channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).get(); + final String serverName = channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_ADDRESS) + .get(); + final SocketAddress clientDestinationAddress = + channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get(); + final InetSocketAddress proxyProtocolDestinationAddress = channel.attr( + SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS) + .get(); if (proxyProtocolDestinationAddress != null) { context.set(CommonContextKeys.PROXY_PROTOCOL_DESTINATION_ADDRESS, proxyProtocolDestinationAddress); } // Store info about the SSL handshake if applicable, and choose the http scheme. String scheme = SCHEME_HTTP; - final SslHandshakeInfo sslHandshakeInfo = channel.attr(SslHandshakeInfoHandler.ATTR_SSL_INFO).get(); + final SslHandshakeInfo sslHandshakeInfo = + channel.attr(SslHandshakeInfoHandler.ATTR_SSL_INFO).get(); if (sslHandshakeInfo != null) { context.set(CommonContextKeys.SSL_HANDSHAKE_INFO, sslHandshakeInfo); scheme = SCHEME_HTTPS; @@ -352,8 +364,7 @@ private HttpRequestMessage buildZuulHttpRequest( port, serverName, clientDestinationAddress, - false - ); + false); // Try to decide if this request has a body or not based on the headers (as we won't yet have // received any of the content). @@ -429,30 +440,30 @@ public static HttpQueryParams copyQueryParams(final HttpRequest nativeRequest) { return HttpQueryParams.parse(query); } - @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { try (TaskCloseable ignored = PerfMark.traceTask("CRR.write")) { if (msg instanceof HttpResponse) { promise.addListener((future) -> { - if (! future.isSuccess()) { + if (!future.isSuccess()) { fireWriteError("response headers", future.cause(), ctx); } }); super.write(ctx, msg, promise); - } - else if (msg instanceof HttpContent) { + } else if (msg instanceof HttpContent) { promise.addListener((future) -> { - if (! future.isSuccess()) { + if (!future.isSuccess()) { fireWriteError("response content", future.cause(), ctx); } }); super.write(ctx, msg, promise); - } - else { - //should never happen + } else { + // should never happen ReferenceCountUtil.release(msg); - throw new ZuulException("Attempt to write invalid content type to client: "+msg.getClass().getSimpleName(), true); + throw new ZuulException( + "Attempt to write invalid content type to client: " + + msg.getClass().getSimpleName(), + true); } } } @@ -461,21 +472,19 @@ private void fireWriteError(String requestPart, Throwable cause, ChannelHandlerC final String errMesg = String.format("Error writing %s to client", requestPart); - if (cause instanceof java.nio.channels.ClosedChannelException || - cause instanceof Errors.NativeIoException || - cause instanceof SSLException || - (cause.getCause() != null && cause.getCause() instanceof SSLException)) { + if (cause instanceof java.nio.channels.ClosedChannelException + || cause instanceof Errors.NativeIoException + || cause instanceof SSLException + || (cause.getCause() != null && cause.getCause() instanceof SSLException)) { LOG.debug("{} - client connection is closed.", errMesg); if (zuulRequest != null) { zuulRequest.getContext().cancel(); - StatusCategoryUtils.storeStatusCategoryIfNotAlreadyFailure(zuulRequest.getContext(), - ZuulStatusCategory.FAILURE_CLIENT_CANCELLED); + StatusCategoryUtils.storeStatusCategoryIfNotAlreadyFailure( + zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_CANCELLED); } - } - else { + } else { LOG.error(errMesg, cause); ctx.fireExceptionCaught(new ZuulException(cause, errMesg, true)); } } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientResponseWriter.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientResponseWriter.java index 99893652e9..48aa5db499 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientResponseWriter.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientResponseWriter.java @@ -16,12 +16,6 @@ package com.netflix.zuul.netty.server; -import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent; -import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason.INACTIVE; -import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason.SESSION_COMPLETE; -import static com.netflix.netty.common.HttpLifecycleChannelHandler.StartEvent; -import static com.netflix.zuul.netty.server.ClientRequestReceiver.ATTR_ZUUL_RESP; -import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.NoopRegistry; @@ -59,6 +53,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent; +import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason.INACTIVE; +import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason.SESSION_COMPLETE; +import static com.netflix.netty.common.HttpLifecycleChannelHandler.StartEvent; +import static com.netflix.zuul.netty.server.ClientRequestReceiver.ATTR_ZUUL_RESP; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; + /** * Created by saroskar on 2/26/17. */ @@ -69,12 +70,12 @@ public class ClientResponseWriter extends ChannelInboundHandlerAdapter { private final RequestCompleteHandler requestCompleteHandler; private final Counter responseBeforeReceivedLastContentCounter; - //state + // state private boolean isHandlingRequest; private boolean startedSendingResponseToClient; private boolean closeConnection; - //data + // data private HttpResponseMessage zuulResponse; private static final Logger logger = LoggerFactory.getLogger(ClientResponseWriter.class); @@ -85,7 +86,8 @@ public ClientResponseWriter(RequestCompleteHandler requestCompleteHandler) { public ClientResponseWriter(RequestCompleteHandler requestCompleteHandler, Registry registry) { this.requestCompleteHandler = requestCompleteHandler; - this.responseBeforeReceivedLastContentCounter = registry.counter("server.http.requests.responseBeforeReceivedLastContent"); + this.responseBeforeReceivedLastContentCounter = + registry.counter("server.http.requests.responseBeforeReceivedLastContent"); } @Override @@ -99,16 +101,16 @@ public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exce return; } - if ((! isHandlingRequest) || (startedSendingResponseToClient)) { + if ((!isHandlingRequest) || (startedSendingResponseToClient)) { /* This can happen if we are already in the process of streaming response back to client OR NOT within active - request/response cycle and something like IDLE or Request Read timeout occurs. In that case we have no way - to recover other than closing the socket and cleaning up resources used by BOTH responses. - */ + request/response cycle and something like IDLE or Request Read timeout occurs. In that case we have no way + to recover other than closing the socket and cleaning up resources used by BOTH responses. + */ resp.disposeBufferedBody(); if (zuulResponse != null) { zuulResponse.disposeBufferedBody(); } - ctx.close(); //This will trigger CompleteEvent if one is needed + ctx.close(); // This will trigger CompleteEvent if one is needed return; } @@ -121,7 +123,8 @@ public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exce if (channel.isActive()) { // Track if this is happening. - if (!ClientRequestReceiver.isLastContentReceivedForChannel(channel) && !shouldAllowPreemptiveResponse(channel)) { + if (!ClientRequestReceiver.isLastContentReceivedForChannel(channel) + && !shouldAllowPreemptiveResponse(channel)) { responseBeforeReceivedLastContentCounter.increment(); logger.warn( "Writing response to client channel before have received the LastContent of request! {}, {}", @@ -136,8 +139,7 @@ public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exce resp.disposeBufferedBody(); channel.close(); } - } - else if (msg instanceof HttpContent) { + } else if (msg instanceof HttpContent) { final HttpContent chunk = (HttpContent) msg; if (channel.isActive()) { channel.writeAndFlush(chunk); @@ -145,17 +147,18 @@ else if (msg instanceof HttpContent) { chunk.release(); channel.close(); } - } - else { - //should never happen + } else { + // should never happen ReferenceCountUtil.release(msg); throw new ZuulException("Received invalid message from origin", true); } } protected boolean shouldAllowPreemptiveResponse(Channel channel) { - // If the request timed-out while being read, then there won't have been any LastContent, but thats ok because the connection will have to be discarded anyway. - StatusCategory status = StatusCategoryUtils.getStatusCategory(ClientRequestReceiver.getRequestFromChannel(channel)); + // If the request timed-out while being read, then there won't have been any LastContent, but thats ok because + // the connection will have to be discarded anyway. + StatusCategory status = + StatusCategoryUtils.getStatusCategory(ClientRequestReceiver.getRequestFromChannel(channel)); return status == ZuulStatusCategory.FAILURE_CLIENT_TIMEOUT; } @@ -174,15 +177,14 @@ private HttpResponse buildHttpResponse(final HttpResponseMessage zuulResp) { final String inboundProtocol = zuulRequest.getProtocol(); if (inboundProtocol.startsWith("HTTP/1")) { responseHttpVersion = HttpVersion.valueOf(inboundProtocol); - } - else { + } else { // Default to 1.1. We do this to cope with HTTP/2 inbound requests. responseHttpVersion = HttpVersion.HTTP_1_1; } // Create the main http response to send, with body. - final DefaultHttpResponse nativeResponse = new DefaultHttpResponse(responseHttpVersion, - HttpResponseStatus.valueOf(zuulResp.getStatus()), false, false); + final DefaultHttpResponse nativeResponse = new DefaultHttpResponse( + responseHttpVersion, HttpResponseStatus.valueOf(zuulResp.getStatus()), false, false); // Now set all of the response headers - note this is a multi-set in keeping with HTTP semantics final HttpHeaders nativeHeaders = nativeResponse.headers(); @@ -191,7 +193,7 @@ private HttpResponse buildHttpResponse(final HttpResponseMessage zuulResp) { } // Netty does not automatically add Content-Length or Transfer-Encoding: chunked. So we add here if missing. - if (! HttpUtil.isContentLengthSet(nativeResponse) && ! HttpUtil.isTransferEncodingChunked(nativeResponse)) { + if (!HttpUtil.isContentLengthSet(nativeResponse) && !HttpUtil.isTransferEncodingChunked(nativeResponse)) { nativeResponse.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); } @@ -219,8 +221,7 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc startedSendingResponseToClient = false; closeConnection = false; zuulResponse = null; - } - else if (evt instanceof CompleteEvent) { + } else if (evt instanceof CompleteEvent) { HttpResponse response = ((CompleteEvent) evt).getResponse(); if (response != null) { if ("close".equalsIgnoreCase(response.headers().get("Connection"))) { @@ -235,29 +236,29 @@ else if (evt instanceof CompleteEvent) { handleComplete(ctx.channel()); // Choose to either close the connection, or prepare it for next use. - final CompleteEvent completeEvent = (CompleteEvent)evt; + final CompleteEvent completeEvent = (CompleteEvent) evt; final CompleteReason reason = completeEvent.getReason(); if (reason == SESSION_COMPLETE || reason == INACTIVE) { - if (! closeConnection) { - //Start reading next request over HTTP 1.1 persistent connection + if (!closeConnection) { + // Start reading next request over HTTP 1.1 persistent connection ctx.channel().read(); } else { ctx.close(); } - } - else { + } else { if (isHandlingRequest) { - logger.debug("Received complete event while still handling the request. With reason: {} -- {}", reason.name(), ChannelUtils.channelInfoForLogging(ctx.channel())); + logger.debug( + "Received complete event while still handling the request. With reason: {} -- {}", + reason.name(), + ChannelUtils.channelInfoForLogging(ctx.channel())); } ctx.close(); } isHandlingRequest = false; - } - else if (evt instanceof IdleStateEvent) { + } else if (evt instanceof IdleStateEvent) { logger.debug("Received IdleStateEvent."); - } - else { + } else { logger.debug("ClientResponseWriter Received event {}", evt); } } @@ -273,8 +274,7 @@ private void handleComplete(Channel channel) { requestCompleteHandler.handle(zuulRequest.getInboundRequest(), zuulResponse); } } - } - catch (Throwable ex) { + } catch (Throwable ex) { logger.error("Error in RequestCompleteHandler.", ex); } } @@ -290,22 +290,24 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E if (cause instanceof ZuulException) { final ZuulException ze = (ZuulException) cause; status = ze.getStatusCode(); - logger.error("Exception caught in ClientResponseWriter for channel {} ", ChannelUtils.channelInfoForLogging(ctx.channel()), cause); - } - else if (cause instanceof ReadTimeoutException) { + logger.error( + "Exception caught in ClientResponseWriter for channel {} ", + ChannelUtils.channelInfoForLogging(ctx.channel()), + cause); + } else if (cause instanceof ReadTimeoutException) { logger.debug("Read timeout for channel {} ", ChannelUtils.channelInfoForLogging(ctx.channel()), cause); status = 504; - } - else { + } else { logger.error("Exception caught in ClientResponseWriter: ", cause); } - if (isHandlingRequest && !startedSendingResponseToClient && ctx.channel().isActive()) { + if (isHandlingRequest + && !startedSendingResponseToClient + && ctx.channel().isActive()) { final HttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(status)); ctx.writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE); startedSendingResponseToClient = true; - } - else { + } else { ctx.close(); } } @@ -315,5 +317,4 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); ctx.close(); } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/DefaultEventLoopConfig.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/DefaultEventLoopConfig.java index a7198f9034..4c7ac835e5 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/DefaultEventLoopConfig.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/DefaultEventLoopConfig.java @@ -24,8 +24,7 @@ * By default, it configures a single acceptor thread with workers = logical cores available. */ @Singleton -public class DefaultEventLoopConfig implements EventLoopConfig -{ +public class DefaultEventLoopConfig implements EventLoopConfig { private static final DynamicIntProperty ACCEPTOR_THREADS = new DynamicIntProperty("zuul.server.netty.threads.acceptor", 1); private static final DynamicIntProperty WORKER_THREADS = @@ -35,27 +34,23 @@ public class DefaultEventLoopConfig implements EventLoopConfig private final int eventLoopCount; private final int acceptorCount; - public DefaultEventLoopConfig() - { + public DefaultEventLoopConfig() { eventLoopCount = WORKER_THREADS.get() > 0 ? WORKER_THREADS.get() : PROCESSOR_COUNT; acceptorCount = ACCEPTOR_THREADS.get(); } - public DefaultEventLoopConfig(int eventLoopCount, int acceptorCount) - { + public DefaultEventLoopConfig(int eventLoopCount, int acceptorCount) { this.eventLoopCount = eventLoopCount; this.acceptorCount = acceptorCount; } @Override - public int eventLoopCount() - { + public int eventLoopCount() { return eventLoopCount; } @Override - public int acceptorCount() - { + public int acceptorCount() { return acceptorCount; } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/DirectMemoryMonitor.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/DirectMemoryMonitor.java index 082efa1a21..8a108b68fd 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/DirectMemoryMonitor.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/DirectMemoryMonitor.java @@ -21,16 +21,14 @@ import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.patterns.PolledMeter; import io.netty.util.internal.PlatformDependent; -import java.lang.reflect.Field; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.inject.Inject; +import javax.inject.Singleton; import java.time.Duration; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Supplier; -import javax.inject.Inject; -import javax.inject.Singleton; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * User: michaels@netflix.com @@ -47,25 +45,26 @@ public final class DirectMemoryMonitor { @Inject public DirectMemoryMonitor(Registry registry) { - service = Executors.newSingleThreadScheduledExecutor( - new ThreadFactoryBuilder().setDaemon(true).setNameFormat("dmm-%d").build()); + service = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("dmm-%d") + .build()); PolledMeter.using(registry) - .withName(PROP_PREFIX + ".reserved") - .withDelay(Duration.ofSeconds(TASK_DELAY_PROP.get())) - .scheduleOn(service) - .monitorValue(DirectMemoryMonitor.class, DirectMemoryMonitor::getReservedMemory); + .withName(PROP_PREFIX + ".reserved") + .withDelay(Duration.ofSeconds(TASK_DELAY_PROP.get())) + .scheduleOn(service) + .monitorValue(DirectMemoryMonitor.class, DirectMemoryMonitor::getReservedMemory); PolledMeter.using(registry) - .withName(PROP_PREFIX + ".max") - .withDelay(Duration.ofSeconds(TASK_DELAY_PROP.get())) - .scheduleOn(service) - .monitorValue(DirectMemoryMonitor.class, DirectMemoryMonitor::getMaxMemory); - + .withName(PROP_PREFIX + ".max") + .withDelay(Duration.ofSeconds(TASK_DELAY_PROP.get())) + .scheduleOn(service) + .monitorValue(DirectMemoryMonitor.class, DirectMemoryMonitor::getMaxMemory); } public DirectMemoryMonitor() { - //no-op constructor + // no-op constructor this.service = null; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/EventLoopConfig.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/EventLoopConfig.java index 4e38e145c6..f267260f83 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/EventLoopConfig.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/EventLoopConfig.java @@ -15,8 +15,7 @@ */ package com.netflix.zuul.netty.server; -public interface EventLoopConfig -{ +public interface EventLoopConfig { int eventLoopCount(); int acceptorCount(); diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/Http1MutualSslChannelInitializer.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/Http1MutualSslChannelInitializer.java index 690808e8a8..02bda83ddc 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/Http1MutualSslChannelInitializer.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/Http1MutualSslChannelInitializer.java @@ -16,14 +16,14 @@ package com.netflix.zuul.netty.server; +import com.netflix.netty.common.channel.config.ChannelConfig; +import com.netflix.netty.common.channel.config.CommonChannelConfigKeys; import com.netflix.zuul.netty.ssl.SslContextFactory; import io.netty.channel.Channel; import io.netty.channel.ChannelPipeline; import io.netty.channel.group.ChannelGroup; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; -import com.netflix.netty.common.channel.config.ChannelConfig; -import com.netflix.netty.common.channel.config.CommonChannelConfigKeys; import javax.net.ssl.SSLException; @@ -32,8 +32,7 @@ * Date: 1/31/17 * Time: 11:43 PM */ -public class Http1MutualSslChannelInitializer extends BaseZuulChannelInitializer -{ +public class Http1MutualSslChannelInitializer extends BaseZuulChannelInitializer { private final SslContextFactory sslContextFactory; private final SslContext sslContext; private final boolean isSSlFromIntermediary; @@ -43,18 +42,12 @@ public class Http1MutualSslChannelInitializer extends BaseZuulChannelInitializer */ @Deprecated public Http1MutualSslChannelInitializer( - int port, - ChannelConfig channelConfig, - ChannelConfig channelDependencies, - ChannelGroup channels) { + int port, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) { this(String.valueOf(port), channelConfig, channelDependencies, channels); } public Http1MutualSslChannelInitializer( - String metricId, - ChannelConfig channelConfig, - ChannelConfig channelDependencies, - ChannelGroup channels) { + String metricId, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) { super(metricId, channelConfig, channelDependencies, channels); this.isSSlFromIntermediary = channelConfig.get(CommonChannelConfigKeys.isSSlFromIntermediary); @@ -62,8 +55,7 @@ public Http1MutualSslChannelInitializer( this.sslContextFactory = channelConfig.get(CommonChannelConfigKeys.sslContextFactory); try { sslContext = sslContextFactory.createBuilderForServer().build(); - } - catch (SSLException e) { + } catch (SSLException e) { throw new RuntimeException("Error configuring SslContext!", e); } @@ -75,8 +67,7 @@ public Http1MutualSslChannelInitializer( } @Override - protected void initChannel(Channel ch) throws Exception - { + protected void initChannel(Channel ch) throws Exception { SslHandler sslHandler = sslContext.newHandler(ch.alloc()); sslHandler.engine().setEnabledProtocols(sslContextFactory.getProtocols()); diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/MethodBinding.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/MethodBinding.java index 6e9149168e..3510e33e07 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/MethodBinding.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/MethodBinding.java @@ -40,8 +40,7 @@ public void bind(Runnable method) throws Exception { T bindingContext = bindingContextExtractor.call(); if (bindingContext == null) { method.run(); - } - else { + } else { boundMethod.accept(method, bindingContext); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/NamedSocketAddress.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/NamedSocketAddress.java index 8b9e8835f8..44d3851c12 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/NamedSocketAddress.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/NamedSocketAddress.java @@ -16,9 +16,9 @@ package com.netflix.zuul.netty.server; +import javax.annotation.CheckReturnValue; import java.net.SocketAddress; import java.util.Objects; -import javax.annotation.CheckReturnValue; public final class NamedSocketAddress extends SocketAddress { @@ -45,10 +45,7 @@ public NamedSocketAddress withNewSocket(SocketAddress delegate) { @Override public String toString() { - return "NamedSocketAddress{" + - "name='" + name + '\'' + - ", delegate=" + delegate + - '}'; + return "NamedSocketAddress{" + "name='" + name + '\'' + ", delegate=" + delegate + '}'; } @Override diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/OriginResponseReceiver.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/OriginResponseReceiver.java index 9f18d6863b..ac061e7ab1 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/OriginResponseReceiver.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/OriginResponseReceiver.java @@ -18,12 +18,12 @@ import com.netflix.zuul.exception.OutboundException; import com.netflix.zuul.exception.ZuulException; +import com.netflix.zuul.filters.endpoint.ProxyEndpoint; import com.netflix.zuul.message.Header; import com.netflix.zuul.message.http.HttpQueryParams; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.netty.ChannelUtils; import com.netflix.zuul.netty.connectionpool.OriginConnectException; -import com.netflix.zuul.filters.endpoint.ProxyEndpoint; import com.netflix.zuul.passport.PassportState; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; @@ -46,11 +46,11 @@ import java.io.IOException; -import static com.netflix.zuul.exception.OutboundErrorType.READ_TIMEOUT; -import static com.netflix.zuul.exception.OutboundErrorType.RESET_CONNECTION; import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent; import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason; import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason.SESSION_COMPLETE; +import static com.netflix.zuul.exception.OutboundErrorType.READ_TIMEOUT; +import static com.netflix.zuul.exception.OutboundErrorType.RESET_CONNECTION; /** * Created by saroskar on 1/18/17. @@ -60,7 +60,8 @@ public class OriginResponseReceiver extends ChannelDuplexHandler { private volatile ProxyEndpoint edgeProxy; private static final Logger logger = LoggerFactory.getLogger(OriginResponseReceiver.class); - private static final AttributeKey SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE = AttributeKey.newInstance("_ssl_handshake_from_origin_throwable"); + private static final AttributeKey SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE = + AttributeKey.newInstance("_ssl_handshake_from_origin_throwable"); public static final String CHANNEL_HANDLER_NAME = "_origin_response_receiver"; public OriginResponseReceiver(final ProxyEndpoint edgeProxy) { @@ -71,7 +72,6 @@ public void unlinkFromClientRequest() { edgeProxy = null; } - @Override public final void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { try (TaskCloseable a = PerfMark.traceTask("ORR.channelRead")) { @@ -83,13 +83,12 @@ private void channelReadInternal(final ChannelHandlerContext ctx, Object msg) th if (msg instanceof HttpResponse) { if (edgeProxy != null) { edgeProxy.responseFromOrigin((HttpResponse) msg); - } else if (ReferenceCountUtil.refCnt(msg) > 0){ + } else if (ReferenceCountUtil.refCnt(msg) > 0) { // this handles the case of a DefaultFullHttpResponse that could have content that needs to be released ReferenceCountUtil.safeRelease(msg); } ctx.channel().read(); - } - else if (msg instanceof HttpContent) { + } else if (msg instanceof HttpContent) { final HttpContent chunk = (HttpContent) msg; if (edgeProxy != null) { edgeProxy.invokeNext(chunk); @@ -97,9 +96,8 @@ else if (msg instanceof HttpContent) { ReferenceCountUtil.safeRelease(chunk); } ctx.channel().read(); - } - else { - //should never happen + } else { + // should never happen ReferenceCountUtil.release(msg); final Exception error = new IllegalStateException("Received invalid message from origin"); if (edgeProxy != null) { @@ -114,8 +112,10 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc if (evt instanceof CompleteEvent) { final CompleteReason reason = ((CompleteEvent) evt).getReason(); if ((reason != SESSION_COMPLETE) && (edgeProxy != null)) { - logger.error("Origin request completed with reason other than COMPLETE: {}, {}", - reason.name(), ChannelUtils.channelInfoForLogging(ctx.channel())); + logger.error( + "Origin request completed with reason other than COMPLETE: {}, {}", + reason.name(), + ChannelUtils.channelInfoForLogging(ctx.channel())); final ZuulException ze = new ZuulException("CompleteEvent", reason.name(), true); edgeProxy.errorFromOrigin(ze); } @@ -124,23 +124,20 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc // See channelWrite() where these vars are first set onto the channel. try { super.userEventTriggered(ctx, evt); - } - finally { + } finally { postCompleteHook(ctx, evt); } - } - else if (evt instanceof SslHandshakeCompletionEvent && !((SslHandshakeCompletionEvent) evt).isSuccess()) { + } else if (evt instanceof SslHandshakeCompletionEvent && !((SslHandshakeCompletionEvent) evt).isSuccess()) { Throwable cause = ((SslHandshakeCompletionEvent) evt).cause(); ctx.channel().attr(SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE).set(cause); - } - else if (evt instanceof IdleStateEvent) { + } else if (evt instanceof IdleStateEvent) { if (edgeProxy != null) { - logger.error("Origin request received IDLE event: {}", ChannelUtils.channelInfoForLogging(ctx.channel())); + logger.error( + "Origin request received IDLE event: {}", ChannelUtils.channelInfoForLogging(ctx.channel())); edgeProxy.errorFromOrigin(new OutboundException(READ_TIMEOUT, edgeProxy.getRequestAttempts())); } super.userEventTriggered(ctx, evt); - } - else { + } else { super.userEventTriggered(ctx, evt); } } @@ -152,8 +149,7 @@ else if (evt instanceof IdleStateEvent) { * @param evt - netty event * @throws Exception */ - protected void postCompleteHook(ChannelHandlerContext ctx, Object evt) throws Exception { - } + protected void postCompleteHook(ChannelHandlerContext ctx, Object evt) throws Exception {} private HttpRequest buildOriginHttpRequest(final HttpRequestMessage zuulRequest) { final String method = zuulRequest.getMethod().toUpperCase(); @@ -161,7 +157,8 @@ private HttpRequest buildOriginHttpRequest(final HttpRequestMessage zuulRequest) customRequestProcessing(zuulRequest); - final DefaultHttpRequest nettyReq = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method), uri, false); + final DefaultHttpRequest nettyReq = + new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method), uri, false); // Copy headers across. for (final Header h : zuulRequest.getHeaders().entries()) { nettyReq.headers().add(h.getKey(), h.getValue()); @@ -175,17 +172,16 @@ private HttpRequest buildOriginHttpRequest(final HttpRequestMessage zuulRequest) * * @param headers */ - protected void customRequestProcessing(HttpRequestMessage headers) { - } + protected void customRequestProcessing(HttpRequestMessage headers) {} private static String pathAndQueryString(HttpRequestMessage request) { // parsing the params cleans up any empty/null params using the logic of the HttpQueryParams class - final HttpQueryParams cleanParams = HttpQueryParams.parse(request.getQueryParams().toEncodedString()); + final HttpQueryParams cleanParams = + HttpQueryParams.parse(request.getQueryParams().toEncodedString()); final String cleanQueryStr = cleanParams.toEncodedString(); if (cleanQueryStr == null || cleanQueryStr.isEmpty()) { return request.getPath(); - } - else { + } else { return request.getPath() + "?" + cleanParams.toEncodedString(); } } @@ -206,12 +202,18 @@ private void writeInternal(ChannelHandlerContext ctx, Object msg, ChannelPromise if (msg instanceof HttpRequestMessage) { promise.addListener((future) -> { if (!future.isSuccess()) { - Throwable cause = ctx.channel().attr(SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE).get(); + Throwable cause = ctx.channel() + .attr(SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE) + .get(); if (cause != null) { // Set the specific SSL handshake error if the handlers have already caught them - ctx.channel().attr(SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE).set(null); + ctx.channel() + .attr(SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE) + .set(null); fireWriteError("request headers", cause, ctx); - logger.debug("SSLException is overridden by SSLHandshakeException caught in handler level. Original SSL exception message: ", future.cause()); + logger.debug( + "SSLException is overridden by SSLHandshakeException caught in handler level. Original SSL exception message: ", + future.cause()); } else { fireWriteError("request headers", future.cause(), ctx); } @@ -222,17 +224,15 @@ private void writeInternal(ChannelHandlerContext ctx, Object msg, ChannelPromise preWriteHook(ctx, zuulReq); super.write(ctx, buildOriginHttpRequest(zuulReq), promise); - } - else if (msg instanceof HttpContent) { + } else if (msg instanceof HttpContent) { promise.addListener((future) -> { if (!future.isSuccess()) { fireWriteError("request content chunk", future.cause(), ctx); } }); super.write(ctx, msg, promise); - } - else { - //should never happen + } else { + // should never happen ReferenceCountUtil.release(msg); throw new ZuulException("Received invalid message from client", true); } @@ -244,8 +244,7 @@ else if (msg instanceof HttpContent) { * @param ctx channel handler context * @param zuulReq request message to modify */ - protected void preWriteHook(ChannelHandlerContext ctx, HttpRequestMessage zuulReq) { - } + protected void preWriteHook(ChannelHandlerContext ctx, HttpRequestMessage zuulReq) {} private void fireWriteError(String requestPart, Throwable cause, ChannelHandlerContext ctx) throws Exception { String errMesg = "Error while proxying " + requestPart + " to origin "; @@ -263,11 +262,12 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E if (edgeProxy != null) { if (cause instanceof ReadTimeoutException) { edgeProxy.getPassport().add(PassportState.ORIGIN_CH_READ_TIMEOUT); - logger.debug("read timeout on origin channel {} ", ChannelUtils.channelInfoForLogging(ctx.channel()), cause); - } - else if (cause instanceof IOException) { + logger.debug( + "read timeout on origin channel {} ", ChannelUtils.channelInfoForLogging(ctx.channel()), cause); + } else if (cause instanceof IOException) { edgeProxy.getPassport().add(PassportState.ORIGIN_CH_IO_EX); - logger.debug("I/O error on origin channel {} ", ChannelUtils.channelInfoForLogging(ctx.channel()), cause); + logger.debug( + "I/O error on origin channel {} ", ChannelUtils.channelInfoForLogging(ctx.channel()), cause); } else { logger.error("Error from Origin connection:", cause); } @@ -286,5 +286,4 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); ctx.close(); } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/Server.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/Server.java index ad18914db8..f1c36ef716 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/Server.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/Server.java @@ -16,8 +16,6 @@ package com.netflix.zuul.netty.server; -import static com.google.common.base.Preconditions.checkNotNull; - import com.google.common.annotations.VisibleForTesting; import com.netflix.appinfo.InstanceInfo; import com.netflix.config.DynamicBooleanProperty; @@ -65,6 +63,9 @@ import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.EventExecutorChooserFactory; import io.netty.util.concurrent.ThreadPerTaskExecutor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.net.InetSocketAddress; import java.nio.channels.spi.SelectorProvider; import java.util.ArrayList; @@ -79,8 +80,8 @@ import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import static com.google.common.base.Preconditions.checkNotNull; /** * @@ -90,8 +91,7 @@ * Date: 11/8/14 * Time: 8:39 PM */ -public class Server -{ +public class Server { /** * This field is effectively a noop, as Epoll is enabled automatically if available. This can be disabled by * using the {@link #FORCE_NIO} property. @@ -130,6 +130,7 @@ public class Server * Unlike the above, the socket addresses in this map are the *bound* addresses, rather than the requested ones. */ private final Map addressesToChannels = new LinkedHashMap<>(); + private final EventLoopConfig eventLoopConfig; /** @@ -146,10 +147,16 @@ public class Server */ @SuppressWarnings("rawtypes") @Deprecated - public Server(Map portsToChannelInitializers, ServerStatusManager serverStatusManager, - ClientConnectionsShutdown clientConnectionsShutdown, EventLoopGroupMetrics eventLoopGroupMetrics) - { - this(portsToChannelInitializers, serverStatusManager, clientConnectionsShutdown, eventLoopGroupMetrics, + public Server( + Map portsToChannelInitializers, + ServerStatusManager serverStatusManager, + ClientConnectionsShutdown clientConnectionsShutdown, + EventLoopGroupMetrics eventLoopGroupMetrics) { + this( + portsToChannelInitializers, + serverStatusManager, + clientConnectionsShutdown, + eventLoopGroupMetrics, new DefaultEventLoopConfig()); } @@ -158,20 +165,31 @@ public Server(Map portsToChannelInitializers, Serve * EventLoopConfig)} * instead. */ - @SuppressWarnings({"unchecked", "rawtypes"}) // Channel init map has the wrong generics and we can't fix without api breakage. + @SuppressWarnings({"unchecked", "rawtypes" + }) // Channel init map has the wrong generics and we can't fix without api breakage. @Deprecated - public Server(Map portsToChannelInitializers, ServerStatusManager serverStatusManager, - ClientConnectionsShutdown clientConnectionsShutdown, EventLoopGroupMetrics eventLoopGroupMetrics, - EventLoopConfig eventLoopConfig) { - this(Spectator.globalRegistry(), serverStatusManager, + public Server( + Map portsToChannelInitializers, + ServerStatusManager serverStatusManager, + ClientConnectionsShutdown clientConnectionsShutdown, + EventLoopGroupMetrics eventLoopGroupMetrics, + EventLoopConfig eventLoopConfig) { + this( + Spectator.globalRegistry(), + serverStatusManager, convertPortMap((Map>) (Map) portsToChannelInitializers), - clientConnectionsShutdown, eventLoopGroupMetrics, eventLoopConfig); + clientConnectionsShutdown, + eventLoopGroupMetrics, + eventLoopConfig); } - public Server(Registry registry, ServerStatusManager serverStatusManager, - Map> addressesToInitializers, - ClientConnectionsShutdown clientConnectionsShutdown, EventLoopGroupMetrics eventLoopGroupMetrics, - EventLoopConfig eventLoopConfig) { + public Server( + Registry registry, + ServerStatusManager serverStatusManager, + Map> addressesToInitializers, + ClientConnectionsShutdown clientConnectionsShutdown, + EventLoopGroupMetrics eventLoopGroupMetrics, + EventLoopConfig eventLoopConfig) { this.registry = Objects.requireNonNull(registry); this.addressesToInitializers = Collections.unmodifiableMap(new LinkedHashMap<>(addressesToInitializers)); this.serverStatusManager = checkNotNull(serverStatusManager, "serverStatusManager"); @@ -181,10 +199,14 @@ public Server(Registry registry, ServerStatusManager serverStatusManager, this.jvmShutdownHook = new Thread(this::stop, "Zuul-JVM-shutdown-hook"); } - public Server(Registry registry, ServerStatusManager serverStatusManager, + public Server( + Registry registry, + ServerStatusManager serverStatusManager, Map> addressesToInitializers, - ClientConnectionsShutdown clientConnectionsShutdown, EventLoopGroupMetrics eventLoopGroupMetrics, - EventLoopConfig eventLoopConfig, Thread jvmShutdownHook) { + ClientConnectionsShutdown clientConnectionsShutdown, + EventLoopGroupMetrics eventLoopGroupMetrics, + EventLoopConfig eventLoopConfig, + Thread jvmShutdownHook) { this.registry = Objects.requireNonNull(registry); this.addressesToInitializers = Collections.unmodifiableMap(new LinkedHashMap<>(addressesToInitializers)); this.serverStatusManager = checkNotNull(serverStatusManager, "serverStatusManager"); @@ -194,7 +216,6 @@ public Server(Registry registry, ServerStatusManager serverStatusManager, this.jvmShutdownHook = jvmShutdownHook; } - public void stop() { LOG.info("Shutting down Zuul."); serverGroup.stop(); @@ -202,7 +223,7 @@ public void stop() { } public void start() { - if(jvmShutdownHook != null) { + if (jvmShutdownHook != null) { Runtime.getRuntime().addShutdownHook(jvmShutdownHook); } @@ -213,8 +234,8 @@ public void start() { List allBindFutures = new ArrayList<>(addressesToInitializers.size()); // Setup each of the channel initializers on requested ports. - for (Map.Entry> entry - : addressesToInitializers.entrySet()) { + for (Map.Entry> entry : + addressesToInitializers.entrySet()) { NamedSocketAddress requestedNamedAddr = entry.getKey(); ChannelFuture nettyServerFuture = setupServerBootstrap(requestedNamedAddr, entry.getValue()); Channel chan = nettyServerFuture.channel(); @@ -228,14 +249,15 @@ public void start() { ByteBufAllocator alloc = allBindFutures.get(0).channel().alloc(); if (alloc instanceof ByteBufAllocatorMetricProvider) { ByteBufAllocatorMetric metrics = ((ByteBufAllocatorMetricProvider) alloc).metric(); - PolledMeter.using(registry).withId(registry.createId("zuul.nettybuffermem.live", "type", "heap")) + PolledMeter.using(registry) + .withId(registry.createId("zuul.nettybuffermem.live", "type", "heap")) .monitorValue(metrics, ByteBufAllocatorMetric::usedHeapMemory); - PolledMeter.using(registry).withId(registry.createId("zuul.nettybuffermem.live", "type", "direct")) + PolledMeter.using(registry) + .withId(registry.createId("zuul.nettybuffermem.live", "type", "direct")) .monitorValue(metrics, ByteBufAllocatorMetric::usedDirectMemory); } } - } - catch (InterruptedException e) { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @@ -254,13 +276,12 @@ public final List getListeningAddresses() { } @VisibleForTesting - public void waitForEachEventLoop() throws InterruptedException, ExecutionException - { - for (EventExecutor exec : serverGroup.clientToProxyWorkerPool) - { + public void waitForEachEventLoop() throws InterruptedException, ExecutionException { + for (EventExecutor exec : serverGroup.clientToProxyWorkerPool) { exec.submit(() -> { - // Do nothing. - }).get(); + // Do nothing. + }) + .get(); } } @@ -311,14 +332,13 @@ private ChannelFuture setupServerBootstrap( * @param clientToProxyBossPool - acceptor pool * @param clientToProxyWorkerPool - worker pool */ - public void postEventLoopCreationHook(EventLoopGroup clientToProxyBossPool, EventLoopGroup clientToProxyWorkerPool) { + public void postEventLoopCreationHook( + EventLoopGroup clientToProxyBossPool, EventLoopGroup clientToProxyWorkerPool) {} - } - - private final class ServerGroup - { + private final class ServerGroup { /** A name for this ServerGroup to use in naming threads. */ private final String name; + private final int acceptorThreads; private final int workerThreads; private final EventLoopGroupMetrics eventLoopGroupMetrics; @@ -330,7 +350,8 @@ private final class ServerGroup private volatile boolean stopped = false; - private ServerGroup(String name, int acceptorThreads, int workerThreads, EventLoopGroupMetrics eventLoopGroupMetrics) { + private ServerGroup( + String name, int acceptorThreads, int workerThreads, EventLoopGroupMetrics eventLoopGroupMetrics) { this.name = name; this.acceptorThreads = acceptorThreads; this.workerThreads = workerThreads; @@ -343,8 +364,7 @@ public void uncaughtException(final Thread t, final Throwable e) { }); } - private void initializeTransport() - { + private void initializeTransport() { // TODO - try our own impl of ChooserFactory that load-balances across the eventloops using leastconns algo? EventExecutorChooserFactory chooserFactory; if (USE_LEASTCONNS_FOR_EVENTLOOPS.get()) { @@ -363,34 +383,23 @@ private void initializeTransport() channelType = IOUringServerSocketChannel.class; defaultOutboundChannelType.set(IOUringSocketChannel.class); clientToProxyBossPool = new IOUringEventLoopGroup( - acceptorThreads, - new CategorizedThreadFactory(name + "-ClientToZuulAcceptor")); - clientToProxyWorkerPool = new IOUringEventLoopGroup( - workerThreads, - workerExecutor); + acceptorThreads, new CategorizedThreadFactory(name + "-ClientToZuulAcceptor")); + clientToProxyWorkerPool = new IOUringEventLoopGroup(workerThreads, workerExecutor); } else if (!useNio && epollIsAvailable()) { channelType = EpollServerSocketChannel.class; defaultOutboundChannelType.set(EpollSocketChannel.class); extraOptions.put(EpollChannelOption.TCP_DEFER_ACCEPT, -1); clientToProxyBossPool = new EpollEventLoopGroup( - acceptorThreads, - new CategorizedThreadFactory(name + "-ClientToZuulAcceptor")); + acceptorThreads, new CategorizedThreadFactory(name + "-ClientToZuulAcceptor")); clientToProxyWorkerPool = new EpollEventLoopGroup( - workerThreads, - workerExecutor, - chooserFactory, - DefaultSelectStrategyFactory.INSTANCE); + workerThreads, workerExecutor, chooserFactory, DefaultSelectStrategyFactory.INSTANCE); } else if (!useNio && kqueueIsAvailable()) { channelType = KQueueServerSocketChannel.class; defaultOutboundChannelType.set(KQueueSocketChannel.class); clientToProxyBossPool = new KQueueEventLoopGroup( - acceptorThreads, - new CategorizedThreadFactory(name + "-ClientToZuulAcceptor")); + acceptorThreads, new CategorizedThreadFactory(name + "-ClientToZuulAcceptor")); clientToProxyWorkerPool = new KQueueEventLoopGroup( - workerThreads, - workerExecutor, - chooserFactory, - DefaultSelectStrategyFactory.INSTANCE); + workerThreads, workerExecutor, chooserFactory, DefaultSelectStrategyFactory.INSTANCE); } else { channelType = NioServerSocketChannel.class; defaultOutboundChannelType.set(NioSocketChannel.class); @@ -399,12 +408,10 @@ private void initializeTransport() workerExecutor, chooserFactory, SelectorProvider.provider(), - DefaultSelectStrategyFactory.INSTANCE - ); + DefaultSelectStrategyFactory.INSTANCE); elg.setIoRatio(90); clientToProxyBossPool = new NioEventLoopGroup( - acceptorThreads, - new CategorizedThreadFactory(name + "-ClientToZuulAcceptor")); + acceptorThreads, new CategorizedThreadFactory(name + "-ClientToZuulAcceptor")); clientToProxyWorkerPool = elg; } @@ -413,8 +420,7 @@ private void initializeTransport() postEventLoopCreationHook(clientToProxyBossPool, clientToProxyWorkerPool); } - synchronized private void stop() - { + private synchronized void stop() { LOG.info("Shutting down"); if (stopped) { LOG.info("Already stopped"); diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ServerTimeout.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ServerTimeout.java index f20f62a71e..f90e3a7167 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ServerTimeout.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ServerTimeout.java @@ -16,22 +16,18 @@ package com.netflix.zuul.netty.server; -public class ServerTimeout -{ +public class ServerTimeout { private final int connectionIdleTimeout; - public ServerTimeout(int connectionIdleTimeout) - { + public ServerTimeout(int connectionIdleTimeout) { this.connectionIdleTimeout = connectionIdleTimeout; } - public int connectionIdleTimeout() - { + public int connectionIdleTimeout() { return connectionIdleTimeout; } - public int defaultRequestExpiryTimeout() - { + public int defaultRequestExpiryTimeout() { // Note this is the timeout for the inbound request to zuul, not for each outbound attempt. // It needs to align with the inbound connection idle timeout and/or the ELB idle timeout. So we // set it here to 1 sec less than that. diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/SocketAddressProperty.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/SocketAddressProperty.java index 0a61cb998f..f559e6dcaf 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/SocketAddressProperty.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/SocketAddressProperty.java @@ -19,13 +19,14 @@ import com.google.common.annotations.VisibleForTesting; import com.netflix.config.StringDerivedProperty; import io.netty.channel.unix.DomainSocketAddress; + +import javax.annotation.Nullable; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Locale; import java.util.concurrent.Callable; import java.util.function.Supplier; -import javax.annotation.Nullable; /** * This class expresses an address that Zuul can bind to. Similar to {@link @@ -121,7 +122,8 @@ public SocketAddress apply(String input) { BindType bindType = BindType.valueOf(rawBindType.toUpperCase(Locale.ROOT)); String rawAddress = input.substring(equalsPosition + 1); int port; - parsePort: { + parsePort: + { switch (bindType) { case ANY: // fallthrough case IPV4_ANY: // fallthrough diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ZuulDependencyKeys.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ZuulDependencyKeys.java index fce76ea851..9870054c11 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ZuulDependencyKeys.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ZuulDependencyKeys.java @@ -40,20 +40,32 @@ */ public class ZuulDependencyKeys { - public static final ChannelConfigKey accessLogPublisher = new ChannelConfigKey<>("accessLogPublisher"); - public static final ChannelConfigKey eventLoopGroupMetrics = new ChannelConfigKey<>("eventLoopGroupMetrics"); + public static final ChannelConfigKey accessLogPublisher = + new ChannelConfigKey<>("accessLogPublisher"); + public static final ChannelConfigKey eventLoopGroupMetrics = + new ChannelConfigKey<>("eventLoopGroupMetrics"); public static final ChannelConfigKey registry = new ChannelConfigKey<>("registry"); - public static final ChannelConfigKey sessionCtxDecorator = new ChannelConfigKey<>("sessionCtxDecorator"); - public static final ChannelConfigKey requestCompleteHandler = new ChannelConfigKey<>("requestCompleteHandler"); - public static final ChannelConfigKey httpRequestReadTimeoutCounter = new ChannelConfigKey<>("httpRequestReadTimeoutCounter"); + public static final ChannelConfigKey sessionCtxDecorator = + new ChannelConfigKey<>("sessionCtxDecorator"); + public static final ChannelConfigKey requestCompleteHandler = + new ChannelConfigKey<>("requestCompleteHandler"); + public static final ChannelConfigKey httpRequestReadTimeoutCounter = + new ChannelConfigKey<>("httpRequestReadTimeoutCounter"); public static final ChannelConfigKey filterLoader = new ChannelConfigKey<>("filterLoader"); - public static final ChannelConfigKey filterUsageNotifier = new ChannelConfigKey<>("filterUsageNotifier"); + public static final ChannelConfigKey filterUsageNotifier = + new ChannelConfigKey<>("filterUsageNotifier"); public static final ChannelConfigKey discoveryClient = new ChannelConfigKey<>("discoveryClient"); - public static final ChannelConfigKey applicationInfoManager = new ChannelConfigKey<>("applicationInfoManager"); - public static final ChannelConfigKey serverStatusManager = new ChannelConfigKey<>("serverStatusManager"); - public static final ChannelConfigKey SSL_CLIENT_CERT_CHECK_REQUIRED = new ChannelConfigKey<>("requiresSslClientCertCheck", false); + public static final ChannelConfigKey applicationInfoManager = + new ChannelConfigKey<>("applicationInfoManager"); + public static final ChannelConfigKey serverStatusManager = + new ChannelConfigKey<>("serverStatusManager"); + public static final ChannelConfigKey SSL_CLIENT_CERT_CHECK_REQUIRED = + new ChannelConfigKey<>("requiresSslClientCertCheck", false); - public static final ChannelConfigKey> rateLimitingChannelHandlerProvider = new ChannelConfigKey<>("rateLimitingChannelHandlerProvider"); - public static final ChannelConfigKey> sslClientCertCheckChannelHandlerProvider = new ChannelConfigKey<>("sslClientCertCheckChannelHandlerProvider"); - public static final ChannelConfigKey pushConnectionRegistry = new ChannelConfigKey<>("pushConnectionRegistry"); + public static final ChannelConfigKey> rateLimitingChannelHandlerProvider = + new ChannelConfigKey<>("rateLimitingChannelHandlerProvider"); + public static final ChannelConfigKey> sslClientCertCheckChannelHandlerProvider = + new ChannelConfigKey<>("sslClientCertCheckChannelHandlerProvider"); + public static final ChannelConfigKey pushConnectionRegistry = + new ChannelConfigKey<>("pushConnectionRegistry"); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ZuulServerChannelInitializer.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ZuulServerChannelInitializer.java index 455f3e2520..45ef16a212 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ZuulServerChannelInitializer.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ZuulServerChannelInitializer.java @@ -16,10 +16,10 @@ package com.netflix.zuul.netty.server; +import com.netflix.netty.common.channel.config.ChannelConfig; import io.netty.channel.Channel; import io.netty.channel.ChannelPipeline; import io.netty.channel.group.ChannelGroup; -import com.netflix.netty.common.channel.config.ChannelConfig; /** * User: Mike Smith @@ -29,10 +29,7 @@ public class ZuulServerChannelInitializer extends BaseZuulChannelInitializer { public ZuulServerChannelInitializer( - String metricId, - ChannelConfig channelConfig, - ChannelConfig channelDependencies, - ChannelGroup channels) { + String metricId, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) { super(metricId, channelConfig, channelDependencies, channels); } @@ -41,16 +38,12 @@ public ZuulServerChannelInitializer( */ @Deprecated public ZuulServerChannelInitializer( - int port, - ChannelConfig channelConfig, - ChannelConfig channelDependencies, - ChannelGroup channels) { + int port, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) { this(String.valueOf(port), channelConfig, channelDependencies, channels); } @Override - protected void initChannel(Channel ch) throws Exception - { + protected void initChannel(Channel ch) throws Exception { // Configure our pipeline of ChannelHandlerS. ChannelPipeline pipeline = ch.pipeline(); diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/DummyChannelHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/DummyChannelHandler.java index d4fec7fe38..d93a69c6f7 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/DummyChannelHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/DummyChannelHandler.java @@ -25,8 +25,7 @@ * Author: Arthur Gonigberg * Date: December 15, 2017 */ -public class DummyChannelHandler implements ChannelHandler -{ +public class DummyChannelHandler implements ChannelHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception {} diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2Configuration.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2Configuration.java index 072e359823..9fea16f76e 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2Configuration.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2Configuration.java @@ -21,14 +21,15 @@ import io.netty.handler.ssl.ApplicationProtocolNames; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; + import javax.net.ssl.SSLException; public class Http2Configuration { - + public static SslContext configureSSL(SslContextFactory sslContextFactory, String metricId) { SslContextBuilder builder = sslContextFactory.createBuilderForServer(); - String[] supportedProtocols = new String[]{ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1}; + String[] supportedProtocols = new String[] {ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1}; ApplicationProtocolConfig apn = new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. @@ -39,9 +40,7 @@ public static SslContext configureSSL(SslContextFactory sslContextFactory, Strin final SslContext sslContext; try { - sslContext = builder - .applicationProtocolConfig(apn) - .build(); + sslContext = builder.applicationProtocolConfig(apn).build(); } catch (SSLException e) { throw new RuntimeException("Error configuring SslContext with ALPN!", e); } @@ -69,7 +68,10 @@ public static SslContext configureSSLWithH2Disabled(SslContextFactory sslContext ApplicationProtocolNames.HTTP_1_1); final SslContext sslContext; try { - sslContext = sslContextFactory.createBuilderForServer().applicationProtocolConfig(apn).build(); + sslContext = sslContextFactory + .createBuilderForServer() + .applicationProtocolConfig(apn) + .build(); } catch (SSLException e) { throw new RuntimeException("Error configuring SslContext with ALPN!", e); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2ContentLengthEnforcingHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2ContentLengthEnforcingHandler.java index bfceba0945..ca428caeb4 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2ContentLengthEnforcingHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2ContentLengthEnforcingHandler.java @@ -27,6 +27,7 @@ import io.netty.handler.codec.http2.DefaultHttp2ResetFrame; import io.netty.handler.codec.http2.Http2Error; import io.netty.util.ReferenceCountUtil; + import java.util.List; /** diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2OrHttpHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2OrHttpHandler.java index 7208da5251..b7ca4be0c4 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2OrHttpHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2OrHttpHandler.java @@ -16,8 +16,6 @@ package com.netflix.zuul.netty.server.http2; -import static com.netflix.zuul.netty.server.BaseZuulChannelInitializer.HTTP_CODEC_HANDLER_NAME; - import com.netflix.netty.common.channel.config.ChannelConfig; import com.netflix.netty.common.channel.config.CommonChannelConfigKeys; import com.netflix.netty.common.http2.DynamicHttp2FrameLogger; @@ -35,8 +33,11 @@ import io.netty.handler.ssl.ApplicationProtocolNames; import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler; import io.netty.util.AttributeKey; + import java.util.function.Consumer; +import static com.netflix.zuul.netty.server.BaseZuulChannelInitializer.HTTP_CODEC_HANDLER_NAME; + /** * Http2 Or Http Handler * @@ -46,7 +47,8 @@ public class Http2OrHttpHandler extends ApplicationProtocolNegotiationHandler { public static final AttributeKey PROTOCOL_NAME = AttributeKey.valueOf("protocol_name"); - private static final DynamicHttp2FrameLogger FRAME_LOGGER = new DynamicHttp2FrameLogger(LogLevel.DEBUG, Http2FrameCodec.class); + private static final DynamicHttp2FrameLogger FRAME_LOGGER = + new DynamicHttp2FrameLogger(LogLevel.DEBUG, Http2FrameCodec.class); private final ChannelHandler http2StreamHandler; private final int maxConcurrentStreams; @@ -55,9 +57,10 @@ public class Http2OrHttpHandler extends ApplicationProtocolNegotiationHandler { private final long maxHeaderListSize; private final Consumer addHttpHandlerFn; - - public Http2OrHttpHandler(ChannelHandler http2StreamHandler, ChannelConfig channelConfig, - Consumer addHttpHandlerFn) { + public Http2OrHttpHandler( + ChannelHandler http2StreamHandler, + ChannelConfig channelConfig, + Consumer addHttpHandlerFn) { super(ApplicationProtocolNames.HTTP_1_1); this.http2StreamHandler = http2StreamHandler; this.maxConcurrentStreams = channelConfig.get(CommonChannelConfigKeys.maxConcurrentStreams); @@ -99,8 +102,8 @@ private void configureHttp2(ChannelPipeline pipeline) { .build(); Http2Connection conn = frameCodec.connection(); // Use the uniform byte distributor until https://github.com/netty/netty/issues/10525 is fixed. - conn.remote().flowController( - new DefaultHttp2RemoteFlowController(conn, new UniformStreamByteDistributor(conn))); + conn.remote() + .flowController(new DefaultHttp2RemoteFlowController(conn, new UniformStreamByteDistributor(conn))); Http2MultiplexHandler multiplexHandler = new Http2MultiplexHandler(http2StreamHandler); diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2ResetFrameHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2ResetFrameHandler.java index ee35a9e62c..e96e097908 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2ResetFrameHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2ResetFrameHandler.java @@ -29,17 +29,14 @@ * Time: 6:02 PM */ @ChannelHandler.Sharable -public class Http2ResetFrameHandler extends ChannelInboundHandlerAdapter -{ +public class Http2ResetFrameHandler extends ChannelInboundHandlerAdapter { @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof Http2ResetFrame) { // Inform zuul to cancel the request. ctx.fireUserEventTriggered(new RequestCancelledEvent()); ReferenceCountUtil.safeRelease(msg); - } - else { + } else { super.channelRead(ctx, msg); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2SslChannelInitializer.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2SslChannelInitializer.java index a4a0b3ef7c..fd09e702ca 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2SslChannelInitializer.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2SslChannelInitializer.java @@ -16,8 +16,6 @@ package com.netflix.zuul.netty.server.http2; -import static com.google.common.base.Preconditions.checkNotNull; - import com.netflix.netty.common.Http2ConnectionCloseHandler; import com.netflix.netty.common.Http2ConnectionExpiryHandler; import com.netflix.netty.common.SwallowSomeHttp2ExceptionsHandler; @@ -36,6 +34,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static com.google.common.base.Preconditions.checkNotNull; + /** * User: Mike Smith * Date: 3/5/16 @@ -51,22 +51,17 @@ public final class Http2SslChannelInitializer extends BaseZuulChannelInitializer private final SwallowSomeHttp2ExceptionsHandler swallowSomeHttp2ExceptionsHandler; private final String metricId; - /** * Use {@link #Http2SslChannelInitializer(String, ChannelConfig, ChannelConfig, ChannelGroup)} instead. */ @Deprecated - public Http2SslChannelInitializer(int port, - ChannelConfig channelConfig, - ChannelConfig channelDependencies, - ChannelGroup channels) { + public Http2SslChannelInitializer( + int port, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) { this(String.valueOf(port), channelConfig, channelDependencies, channels); } - public Http2SslChannelInitializer(String metricId, - ChannelConfig channelConfig, - ChannelConfig channelDependencies, - ChannelGroup channels) { + public Http2SslChannelInitializer( + String metricId, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) { super(metricId, channelConfig, channelDependencies, channels); this.metricId = checkNotNull(metricId, "metricId"); @@ -84,18 +79,26 @@ protected void initChannel(Channel ch) throws Exception { SslHandler sslHandler = sslContext.newHandler(ch.alloc()); sslHandler.engine().setEnabledProtocols(serverSslConfig.getProtocols()); -// SSLParameters sslParameters = new SSLParameters(); -// AlgorithmConstraints algoConstraints = new AlgorithmConstraints(); -// sslParameters.setAlgorithmConstraints(algoConstraints); -// sslParameters.setUseCipherSuitesOrder(true); -// sslHandler.engine().setSSLParameters(sslParameters); + // SSLParameters sslParameters = new SSLParameters(); + // AlgorithmConstraints algoConstraints = new AlgorithmConstraints(); + // sslParameters.setAlgorithmConstraints(algoConstraints); + // sslParameters.setUseCipherSuitesOrder(true); + // sslHandler.engine().setSSLParameters(sslParameters); if (LOG.isDebugEnabled()) { - LOG.debug("ssl protocols supported: {}", String.join(", ", sslHandler.engine().getSupportedProtocols())); - LOG.debug("ssl protocols enabled: {}", String.join(", ", sslHandler.engine().getEnabledProtocols())); - - LOG.debug("ssl ciphers supported: {}", String.join(", ", sslHandler.engine().getSupportedCipherSuites())); - LOG.debug("ssl ciphers enabled: {}", String.join(", ", sslHandler.engine().getEnabledCipherSuites())); + LOG.debug( + "ssl protocols supported: {}", + String.join(", ", sslHandler.engine().getSupportedProtocols())); + LOG.debug( + "ssl protocols enabled: {}", + String.join(", ", sslHandler.engine().getEnabledProtocols())); + + LOG.debug( + "ssl ciphers supported: {}", + String.join(", ", sslHandler.engine().getSupportedCipherSuites())); + LOG.debug( + "ssl ciphers enabled: {}", + String.join(", ", sslHandler.engine().getEnabledCipherSuites())); } // Configure our pipeline of ChannelHandlerS. @@ -111,18 +114,26 @@ protected void initChannel(Channel ch) throws Exception { addSslClientCertChecks(pipeline); Http2MetricsChannelHandlers http2MetricsChannelHandlers = - new Http2MetricsChannelHandlers(registry,"server", "http2-" + metricId); + new Http2MetricsChannelHandlers(registry, "server", "http2-" + metricId); Http2ConnectionCloseHandler connectionCloseHandler = new Http2ConnectionCloseHandler(registry); - Http2ConnectionExpiryHandler connectionExpiryHandler = new Http2ConnectionExpiryHandler(maxRequestsPerConnection, maxRequestsPerConnectionInBrownout, connectionExpiry); - - pipeline.addLast("http2CodecSwapper", new Http2OrHttpHandler( - new Http2StreamInitializer(ch, this::http1Handlers, http2MetricsChannelHandlers, connectionCloseHandler, connectionExpiryHandler), - channelConfig, - cp -> { - http1Codec(cp); - http1Handlers(cp); - })); + Http2ConnectionExpiryHandler connectionExpiryHandler = new Http2ConnectionExpiryHandler( + maxRequestsPerConnection, maxRequestsPerConnectionInBrownout, connectionExpiry); + + pipeline.addLast( + "http2CodecSwapper", + new Http2OrHttpHandler( + new Http2StreamInitializer( + ch, + this::http1Handlers, + http2MetricsChannelHandlers, + connectionCloseHandler, + connectionExpiryHandler), + channelConfig, + cp -> { + http1Codec(cp); + http1Handlers(cp); + })); pipeline.addLast("codec_placeholder", DUMMY_HANDLER); pipeline.addLast(swallowSomeHttp2ExceptionsHandler); @@ -137,4 +148,3 @@ protected void http1Codec(ChannelPipeline pipeline) { pipeline.replace("codec_placeholder", HTTP_CODEC_HANDLER_NAME, createHttpServerCodec()); } } - diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamErrorHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamErrorHandler.java index e2f9dff89d..01d10cf685 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamErrorHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamErrorHandler.java @@ -22,7 +22,7 @@ import io.netty.handler.codec.http2.DefaultHttp2ResetFrame; import io.netty.handler.codec.http2.Http2Error; -import static io.netty.handler.codec.http2.Http2Exception.*; +import static io.netty.handler.codec.http2.Http2Exception.StreamException; /** * Author: Susheel Aroskar diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamHeaderCleaner.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamHeaderCleaner.java index 2277fd3391..5f44bee06e 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamHeaderCleaner.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamHeaderCleaner.java @@ -30,11 +30,9 @@ * stop doing this. Although potentially we _never_ want to pass these downstream to origins .... ? */ @ChannelHandler.Sharable -public class Http2StreamHeaderCleaner extends ChannelInboundHandlerAdapter -{ +public class Http2StreamHeaderCleaner extends ChannelInboundHandlerAdapter { @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; @@ -48,4 +46,3 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception super.channelRead(ctx, msg); } } - diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamInitializer.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamInitializer.java index 4a2f5b8237..631b69aea8 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamInitializer.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamInitializer.java @@ -16,7 +16,6 @@ package com.netflix.zuul.netty.server.http2; -import static com.netflix.zuul.netty.server.http2.Http2OrHttpHandler.PROTOCOL_NAME; import com.netflix.netty.common.Http2ConnectionCloseHandler; import com.netflix.netty.common.Http2ConnectionExpiryHandler; import com.netflix.netty.common.SourceAddressChannelHandler; @@ -31,14 +30,16 @@ import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.http2.Http2StreamFrameToHttpObjectCodec; import io.netty.util.AttributeKey; + import java.util.function.Consumer; +import static com.netflix.zuul.netty.server.http2.Http2OrHttpHandler.PROTOCOL_NAME; + /** * TODO - can this be done when we create the Http2StreamChannelBootstrap instead now? */ @ChannelHandler.Sharable -public class Http2StreamInitializer extends ChannelInboundHandlerAdapter -{ +public class Http2StreamInitializer extends ChannelInboundHandlerAdapter { private static final Http2StreamHeaderCleaner http2StreamHeaderCleaner = new Http2StreamHeaderCleaner(); private static final Http2ResetFrameHandler http2ResetFrameHandler = new Http2ResetFrameHandler(); private static final Http2StreamErrorHandler http2StreamErrorHandler = new Http2StreamErrorHandler(); @@ -50,11 +51,12 @@ public class Http2StreamInitializer extends ChannelInboundHandlerAdapter private final Http2ConnectionCloseHandler connectionCloseHandler; private final Http2ConnectionExpiryHandler connectionExpiryHandler; - public Http2StreamInitializer(Channel parent, Consumer addHttpHandlerFn, - Http2MetricsChannelHandlers http2MetricsChannelHandlers, - Http2ConnectionCloseHandler connectionCloseHandler, - Http2ConnectionExpiryHandler connectionExpiryHandler) - { + public Http2StreamInitializer( + Channel parent, + Consumer addHttpHandlerFn, + Http2MetricsChannelHandlers http2MetricsChannelHandlers, + Http2ConnectionCloseHandler connectionCloseHandler, + Http2ConnectionExpiryHandler connectionExpiryHandler) { this.parent = parent; this.addHttpHandlerFn = addHttpHandlerFn; @@ -64,8 +66,7 @@ public Http2StreamInitializer(Channel parent, Consumer addHttpH } @Override - public void handlerAdded(ChannelHandlerContext ctx) throws Exception - { + public void handlerAdded(ChannelHandlerContext ctx) throws Exception { copyAttrsFromParentChannel(this.parent, ctx.channel()); addHttp2StreamSpecificHandlers(ctx.pipeline()); @@ -74,8 +75,7 @@ public void handlerAdded(ChannelHandlerContext ctx) throws Exception ctx.pipeline().remove(this); } - protected void addHttp2StreamSpecificHandlers(ChannelPipeline pipeline) - { + protected void addHttp2StreamSpecificHandlers(ChannelPipeline pipeline) { pipeline.addLast("h2_metrics_inbound", http2MetricsChannelHandlers.inbound()); pipeline.addLast("h2_metrics_outbound", http2MetricsChannelHandlers.outbound()); pipeline.addLast("h2_max_requests_per_conn", connectionExpiryHandler); @@ -88,24 +88,21 @@ protected void addHttp2StreamSpecificHandlers(ChannelPipeline pipeline) pipeline.addLast(new Http2ContentLengthEnforcingHandler()); } - protected void copyAttrsFromParentChannel(Channel parent, Channel child) - { + protected void copyAttrsFromParentChannel(Channel parent, Channel child) { AttributeKey[] attributesToCopy = { - SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS, - SourceAddressChannelHandler.ATTR_LOCAL_INET_ADDR, - SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS, - SourceAddressChannelHandler.ATTR_REMOTE_ADDR, - SourceAddressChannelHandler.ATTR_SOURCE_INET_ADDR, - SourceAddressChannelHandler.ATTR_SERVER_LOCAL_ADDRESS, - SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT, - SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS, - - PROTOCOL_NAME, - SslHandshakeInfoHandler.ATTR_SSL_INFO, - HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE, - HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION, - - BaseZuulChannelInitializer.ATTR_CHANNEL_CONFIG + SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS, + SourceAddressChannelHandler.ATTR_LOCAL_INET_ADDR, + SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS, + SourceAddressChannelHandler.ATTR_REMOTE_ADDR, + SourceAddressChannelHandler.ATTR_SOURCE_INET_ADDR, + SourceAddressChannelHandler.ATTR_SERVER_LOCAL_ADDRESS, + SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT, + SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS, + PROTOCOL_NAME, + SslHandshakeInfoHandler.ATTR_SSL_INFO, + HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE, + HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION, + BaseZuulChannelInitializer.ATTR_CHANNEL_CONFIG }; for (AttributeKey key : attributesToCopy) { @@ -113,8 +110,7 @@ protected void copyAttrsFromParentChannel(Channel parent, Channel child) } } - protected void copyAttrFromParentChannel(Channel parent, Channel child, AttributeKey key) - { + protected void copyAttrFromParentChannel(Channel parent, Channel child, AttributeKey key) { child.attr(key).set(parent.attr(key).get()); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushAuthHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushAuthHandler.java index aced5ac69f..0422ba7732 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushAuthHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushAuthHandler.java @@ -17,14 +17,30 @@ import com.google.common.base.Strings; import com.netflix.zuul.message.http.Cookies; -import io.netty.channel.*; -import io.netty.handler.codec.http.*; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http.Cookie; +import io.netty.handler.codec.http.CookieDecoder; +import io.netty.handler.codec.http.DefaultFullHttpResponse; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.FullHttpResponse; +import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpRequest; +import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.codec.http.HttpUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; -import static io.netty.handler.codec.http.HttpResponseStatus.*; +import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; +import static io.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED; +import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; +import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** @@ -40,7 +56,6 @@ public abstract class PushAuthHandler extends SimpleChannelInboundHandler rate) { - tkBktAllowance = rate; //cap max to rate + tkBktAllowance = rate; // cap max to rate } if (tkBktAllowance < 1.0) { @@ -92,5 +92,4 @@ public ChannelFuture sendPushMessage(String mesg) { public ChannelFuture sendPing() { return pushProtocol.sendPing(ctx); } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushConnectionRegistry.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushConnectionRegistry.java index 3ab1dd865e..1975294419 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushConnectionRegistry.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushConnectionRegistry.java @@ -15,14 +15,13 @@ */ package com.netflix.zuul.netty.server.push; - +import javax.annotation.Nullable; +import javax.inject.Inject; +import javax.inject.Singleton; import java.security.SecureRandom; import java.util.Base64; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import javax.annotation.Nullable; -import javax.inject.Inject; -import javax.inject.Singleton; /** * Maintains client identity to web socket or SSE channel mapping. @@ -65,5 +64,4 @@ public PushConnection remove(final String clientId) { public int size() { return clientPushConnectionMap.size(); } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageFactory.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageFactory.java index b4130b047a..b9188c3e40 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageFactory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageFactory.java @@ -25,8 +25,6 @@ */ public abstract class PushMessageFactory { - - public final void sendErrorAndClose(ChannelHandlerContext ctx, int statusCode, String reasonText) { ctx.writeAndFlush(serverClosingConnectionMessage(statusCode, reasonText)) .addListener(ChannelFutureListener.CLOSE); @@ -42,5 +40,4 @@ public final void sendErrorAndClose(ChannelHandlerContext ctx, int statusCode, S * Message server sends to the client just before it force closes connection from its side */ protected abstract Object serverClosingConnectionMessage(int statusCode, String reasonText); - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageSender.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageSender.java index 378ec4429c..ff6d540371 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageSender.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageSender.java @@ -15,16 +15,6 @@ */ package com.netflix.zuul.netty.server.push; -import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; -import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; -import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; -import static io.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED; -import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; -import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; -import static io.netty.handler.codec.http.HttpResponseStatus.OK; -import static io.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED; -import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; - import com.google.common.base.Strings; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelFuture; @@ -39,12 +29,20 @@ import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpUtil; import io.netty.util.ReferenceCountUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.inject.Inject; -import javax.inject.Singleton; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; +import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; +import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; +import static io.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED; +import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; +import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; +import static io.netty.handler.codec.http.HttpResponseStatus.OK; +import static io.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** * Serves "/push" URL that is used by the backend to POST push messages to a given Zuul instance. This URL handler @@ -56,22 +54,20 @@ * Date: 5/14/18 */ @ChannelHandler.Sharable -public abstract class PushMessageSender extends SimpleChannelInboundHandler { +public abstract class PushMessageSender extends SimpleChannelInboundHandler { private final PushConnectionRegistry pushConnectionRegistry; public static final String SECURE_TOKEN_HEADER_NAME = "X-Zuul.push.secure.token"; private static final Logger logger = LoggerFactory.getLogger(PushMessageSender.class); - @Inject public PushMessageSender(PushConnectionRegistry pushConnectionRegistry) { this.pushConnectionRegistry = pushConnectionRegistry; } - - private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest request, HttpResponseStatus status, - PushUserAuth userAuth) { + private void sendHttpResponse( + ChannelHandlerContext ctx, FullHttpRequest request, HttpResponseStatus status, PushUserAuth userAuth) { final FullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, status); resp.headers().add("Content-Length", "0"); final ChannelFuture cf = ctx.channel().writeAndFlush(resp); @@ -90,8 +86,7 @@ protected boolean verifySecureToken(final FullHttpRequest request, final PushCon return secureToken.equals(conn.getSecureToken()); } - - @Override + @Override protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendHttpResponse(ctx, request, BAD_REQUEST, null); @@ -113,7 +108,6 @@ protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpReque return; } - final PushUserAuth userAuth = getPushUserAuth(request); if (!userAuth.isSuccess()) { sendHttpResponse(ctx, request, UNAUTHORIZED, userAuth); @@ -128,14 +122,14 @@ protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpReque return; } - if (! verifySecureToken(request, pushConn)) { + if (!verifySecureToken(request, pushConn)) { sendHttpResponse(ctx, request, FORBIDDEN, userAuth); logSecurityTokenVerificationFail(); return; } if (method == HttpMethod.GET) { - //client only checking if particular CID + ESN is connected to this instance + // client only checking if particular CID + ESN is connected to this instance sendHttpResponse(ctx, request, OK, userAuth); return; } @@ -167,9 +161,8 @@ protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpReque } sendHttpResponse(ctx, request, status, userAuth); }); - } - else { - //Last handler in the chain + } else { + // Last handler in the chain sendHttpResponse(ctx, request, BAD_REQUEST, null); } } @@ -207,9 +200,4 @@ protected void logPushEvent(FullHttpRequest request, HttpResponseStatus status, } protected abstract PushUserAuth getPushUserAuth(FullHttpRequest request); - - - - - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageSenderInitializer.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageSenderInitializer.java index 847bf6f04f..4106372f31 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageSenderInitializer.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageSenderInitializer.java @@ -42,5 +42,4 @@ protected void initChannel(Channel ch) throws Exception { } protected abstract PushMessageSender getPushMessageSender(PushConnectionRegistry pushConnectionRegistry); - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushProtocol.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushProtocol.java index 7804d5b031..497599947a 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushProtocol.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushProtocol.java @@ -29,7 +29,6 @@ * Created by saroskar on 10/10/16. */ public enum PushProtocol { - WEBSOCKET { @Override // The alternative object for HANDSHAKE_COMPLETE is not publicly visible, so disable deprecation warnings. In @@ -64,7 +63,6 @@ public Object goAwayMessage() { public Object serverClosingConnectionMessage(int statusCode, String reasonText) { return new CloseWebSocketFrame(statusCode, reasonText); } - }, SSE { @@ -96,7 +94,7 @@ public ChannelFuture sendPushMessage(ChannelHandlerContext ctx, ByteBuf mesg) { return ctx.channel().writeAndFlush(newBuff); } - private static final String SSE_PING = "event: ping\r\ndata: ping\r\n\r\n"; + private static final String SSE_PING = "event: ping\r\ndata: ping\r\n\r\n"; @Override public ChannelFuture sendPing(ChannelHandlerContext ctx) { @@ -115,7 +113,6 @@ public Object goAwayMessage() { public Object serverClosingConnectionMessage(int statusCode, String reasonText) { return "event: close\r\ndata: " + statusCode + " " + reasonText + "\r\n\r\n"; } - }; public final void sendErrorAndClose(ChannelHandlerContext ctx, int statusCode, String reasonText) { @@ -124,8 +121,11 @@ public final void sendErrorAndClose(ChannelHandlerContext ctx, int statusCode, S } public abstract Object getHandshakeCompleteEvent(); + public abstract String getPath(); + public abstract ChannelFuture sendPushMessage(ChannelHandlerContext ctx, ByteBuf mesg); + public abstract ChannelFuture sendPing(ChannelHandlerContext ctx); /** * Application level protocol for asking client to close connection @@ -136,5 +136,4 @@ public final void sendErrorAndClose(ChannelHandlerContext ctx, int statusCode, S * Message server sends to the client just before it force closes connection from its side */ public abstract Object serverClosingConnectionMessage(int statusCode, String reasonText); - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushRegistrationHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushRegistrationHandler.java index 859814e955..5c261e2440 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushRegistrationHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushRegistrationHandler.java @@ -22,12 +22,12 @@ import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; import io.netty.util.concurrent.ScheduledFuture; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -50,16 +50,21 @@ public class PushRegistrationHandler extends ChannelInboundHandlerAdapter { private volatile PushConnection pushConnection; private final List> scheduledFutures; - public static final CachedDynamicIntProperty PUSH_REGISTRY_TTL = new CachedDynamicIntProperty("zuul.push.registry.ttl.seconds", 30 * 60); - public static final CachedDynamicIntProperty RECONNECT_DITHER = new CachedDynamicIntProperty("zuul.push.reconnect.dither.seconds", 3 * 60); - public static final CachedDynamicIntProperty UNAUTHENTICATED_CONN_TTL = new CachedDynamicIntProperty("zuul.push.noauth.ttl.seconds", 8); - public static final CachedDynamicIntProperty CLIENT_CLOSE_GRACE_PERIOD = new CachedDynamicIntProperty("zuul.push.client.close.grace.period", 4); - public static final CachedDynamicBooleanProperty KEEP_ALIVE_ENABLED = new CachedDynamicBooleanProperty("zuul.push.keepalive.enabled", true); - public static final CachedDynamicIntProperty KEEP_ALIVE_INTERVAL = new CachedDynamicIntProperty("zuul.push.keepalive.interval.seconds", 3 * 60); + public static final CachedDynamicIntProperty PUSH_REGISTRY_TTL = + new CachedDynamicIntProperty("zuul.push.registry.ttl.seconds", 30 * 60); + public static final CachedDynamicIntProperty RECONNECT_DITHER = + new CachedDynamicIntProperty("zuul.push.reconnect.dither.seconds", 3 * 60); + public static final CachedDynamicIntProperty UNAUTHENTICATED_CONN_TTL = + new CachedDynamicIntProperty("zuul.push.noauth.ttl.seconds", 8); + public static final CachedDynamicIntProperty CLIENT_CLOSE_GRACE_PERIOD = + new CachedDynamicIntProperty("zuul.push.client.close.grace.period", 4); + public static final CachedDynamicBooleanProperty KEEP_ALIVE_ENABLED = + new CachedDynamicBooleanProperty("zuul.push.keepalive.enabled", true); + public static final CachedDynamicIntProperty KEEP_ALIVE_INTERVAL = + new CachedDynamicIntProperty("zuul.push.keepalive.interval.seconds", 3 * 60); private static final Logger logger = LoggerFactory.getLogger(PushRegistrationHandler.class); - public PushRegistrationHandler(PushConnectionRegistry pushConnectionRegistry, PushProtocol pushProtocol) { this.pushConnectionRegistry = pushConnectionRegistry; this.pushProtocol = pushProtocol; @@ -71,8 +76,8 @@ protected final boolean isAuthenticated() { return (authEvent != null && authEvent.isSuccess()); } - private void tearDown() { - if (! destroyed.getAndSet(true)) { + private void tearDown() { + if (!destroyed.getAndSet(true)) { if (authEvent != null) { // We should only remove the PushConnection entry from the registry if it's still this pushConnection. String clientID = authEvent.getClientIdentity(); @@ -102,15 +107,17 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E } protected final void forceCloseConnectionFromServerSide() { - if (! destroyed.get()) { + if (!destroyed.get()) { logger.debug("server forcing close connection"); pushProtocol.sendErrorAndClose(ctx, 1000, "Server closed connection"); } } private void closeIfNotAuthenticated() { - if (! isAuthenticated()) { - logger.error("Closing connection because it is still unauthenticated after {} seconds.", UNAUTHENTICATED_CONN_TTL.get()); + if (!isAuthenticated()) { + logger.error( + "Closing connection because it is still unauthenticated after {} seconds.", + UNAUTHENTICATED_CONN_TTL.get()); forceCloseConnectionFromServerSide(); } } @@ -120,8 +127,11 @@ private void requestClientToCloseConnection() { // Application level protocol for asking client to close connection ctx.writeAndFlush(pushProtocol.goAwayMessage()); // Force close connection if client doesn't close in reasonable time after we made request - scheduledFutures.add(ctx.executor().schedule(this::forceCloseConnectionFromServerSide, - CLIENT_CLOSE_GRACE_PERIOD.get(), TimeUnit.SECONDS)); + scheduledFutures.add(ctx.executor() + .schedule( + this::forceCloseConnectionFromServerSide, + CLIENT_CLOSE_GRACE_PERIOD.get(), + TimeUnit.SECONDS)); } else { forceCloseConnectionFromServerSide(); } @@ -141,15 +151,15 @@ private int ditheredReconnectDeadline() { @Override public final void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { this.ctx = ctx; - if (! destroyed.get()) { - if (evt == pushProtocol.getHandshakeCompleteEvent()) { + if (!destroyed.get()) { + if (evt == pushProtocol.getHandshakeCompleteEvent()) { pushConnection = new PushConnection(pushProtocol, ctx); // Unauthenticated connection, wait for small amount of time for a client to send auth token in // a first web socket frame, otherwise close connection - ctx.executor().schedule(this::closeIfNotAuthenticated, UNAUTHENTICATED_CONN_TTL.get(), TimeUnit.SECONDS); + ctx.executor() + .schedule(this::closeIfNotAuthenticated, UNAUTHENTICATED_CONN_TTL.get(), TimeUnit.SECONDS); logger.debug("WebSocket handshake complete."); - } - else if (evt instanceof PushUserAuth) { + } else if (evt instanceof PushUserAuth) { authEvent = (PushUserAuth) evt; if ((authEvent.isSuccess()) && (pushConnection != null)) { logger.debug("registering client {}", authEvent); @@ -157,7 +167,10 @@ else if (evt instanceof PushUserAuth) { registerClient(ctx, authEvent, pushConnection, pushConnectionRegistry); logger.debug("Authentication complete {}", authEvent); } else { - logger.error("Push registration failed: Auth success={}, WS handshake success={}", authEvent.isSuccess(), pushConnection != null); + logger.error( + "Push registration failed: Auth success={}, WS handshake success={}", + authEvent.isSuccess(), + pushConnection != null); if (pushConnection != null) { pushProtocol.sendErrorAndClose(ctx, 1008, "Auth failed"); } @@ -181,15 +194,16 @@ else if (evt instanceof PushUserAuth) { * to use blocking Memcached/redis driver in a background thread-pool to do the actual registration so that Netty * event loop doesn't block */ - protected void registerClient(ChannelHandlerContext ctx, PushUserAuth authEvent, - PushConnection conn, PushConnectionRegistry registry) { + protected void registerClient( + ChannelHandlerContext ctx, PushUserAuth authEvent, PushConnection conn, PushConnectionRegistry registry) { registry.put(authEvent.getClientIdentity(), conn); - //Make client reconnect after ttl seconds by closing this connection to limit stickiness of the client - scheduledFutures.add(ctx.executor().schedule(this::requestClientToCloseConnection, ditheredReconnectDeadline(), - TimeUnit.SECONDS)); + // Make client reconnect after ttl seconds by closing this connection to limit stickiness of the client + scheduledFutures.add(ctx.executor() + .schedule(this::requestClientToCloseConnection, ditheredReconnectDeadline(), TimeUnit.SECONDS)); if (KEEP_ALIVE_ENABLED.get()) { - scheduledFutures.add(ctx.executor().scheduleWithFixedDelay(this::keepAlive, KEEP_ALIVE_INTERVAL.get(), - KEEP_ALIVE_INTERVAL.get(), TimeUnit.SECONDS)); + scheduledFutures.add(ctx.executor() + .scheduleWithFixedDelay( + this::keepAlive, KEEP_ALIVE_INTERVAL.get(), KEEP_ALIVE_INTERVAL.get(), TimeUnit.SECONDS)); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushUserAuth.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushUserAuth.java index 648c8e4bde..e0d410d490 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushUserAuth.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushUserAuth.java @@ -22,5 +22,4 @@ public interface PushUserAuth { int statusCode(); String getClientIdentity(); - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ssl/SslHandshakeInfoHandler.java b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ssl/SslHandshakeInfoHandler.java index a3e1d62570..935cab95ed 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/server/ssl/SslHandshakeInfoHandler.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/server/ssl/SslHandshakeInfoHandler.java @@ -16,9 +16,9 @@ package com.netflix.zuul.netty.server.ssl; -import static com.google.common.base.Preconditions.checkNotNull; - import com.google.common.annotations.VisibleForTesting; +import com.netflix.netty.common.SourceAddressChannelHandler; +import com.netflix.netty.common.ssl.SslHandshakeInfo; import com.netflix.spectator.api.NoopRegistry; import com.netflix.spectator.api.Registry; import com.netflix.zuul.netty.ChannelUtils; @@ -32,18 +32,18 @@ import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; import io.netty.util.AttributeKey; -import com.netflix.netty.common.SourceAddressChannelHandler; -import com.netflix.netty.common.ssl.SslHandshakeInfo; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; -import java.security.cert.X509Certificate; import java.nio.channels.ClosedChannelException; import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.google.common.base.Preconditions.checkNotNull; /** * Stores info about the client and server's SSL certificates in the context, after a successful handshake. @@ -100,8 +100,13 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc serverCert = session.getLocalCertificates()[0]; } - SslHandshakeInfo info = new SslHandshakeInfo(isSSlFromIntermediary, session.getProtocol(), - session.getCipherSuite(), clientAuth, serverCert, peerCert); + SslHandshakeInfo info = new SslHandshakeInfo( + isSSlFromIntermediary, + session.getProtocol(), + session.getCipherSuite(), + clientAuth, + serverCert, + peerCert); ctx.channel().attr(ATTR_SSL_INFO).set(info); // Metrics. @@ -109,27 +114,41 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc logger.debug("Successful SSL Handshake: {}", info); } else { - String clientIP = ctx.channel().attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get(); + String clientIP = ctx.channel() + .attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS) + .get(); Throwable cause = sslEvent.cause(); - PassportState passportState = CurrentPassport.fromChannel(ctx.channel()).getState(); - if (cause instanceof ClosedChannelException && - (PassportState.SERVER_CH_INACTIVE.equals(passportState) + PassportState passportState = + CurrentPassport.fromChannel(ctx.channel()).getState(); + if (cause instanceof ClosedChannelException + && (PassportState.SERVER_CH_INACTIVE.equals(passportState) || PassportState.SERVER_CH_IDLE_TIMEOUT.equals(passportState))) { // Either client closed the connection without/before having completed a handshake, or // the connection idle timed-out before handshake. - // NOTE: we were seeing a lot of these in prod and can repro by just telnetting to port and then closing terminal + // NOTE: we were seeing a lot of these in prod and can repro by just telnetting to port and then + // closing terminal // without sending anything. // So don't treat these as SSL handshake failures. - logger.debug("Client closed connection or it idle timed-out without doing an ssl handshake. , client_ip = {}, channel_info = {}", clientIP, ChannelUtils.channelInfoForLogging(ctx.channel())); - } else if (cause instanceof SSLException && cause.getMessage().contains("handshake timed out")) { - logger.debug("Client timed-out doing the ssl handshake. , client_ip = {}, channel_info = {}", clientIP, ChannelUtils.channelInfoForLogging(ctx.channel())); + logger.debug( + "Client closed connection or it idle timed-out without doing an ssl handshake. , client_ip = {}, channel_info = {}", + clientIP, + ChannelUtils.channelInfoForLogging(ctx.channel())); + } else if (cause instanceof SSLException + && cause.getMessage().contains("handshake timed out")) { + logger.debug( + "Client timed-out doing the ssl handshake. , client_ip = {}, channel_info = {}", + clientIP, + ChannelUtils.channelInfoForLogging(ctx.channel())); } else if (cause instanceof SSLException && cause.getMessage().contains("failure when writing TLS control frames")) { // This can happen if the ClientHello is sent followed by a RST packet, before we can respond. - logger.debug("Client terminated handshake early., client_ip = {}, channel_info = {}", clientIP, ChannelUtils.channelInfoForLogging(ctx.channel())); + logger.debug( + "Client terminated handshake early., client_ip = {}, channel_info = {}", + clientIP, + ChannelUtils.channelInfoForLogging(ctx.channel())); } else { - if(logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { String msg = "Unsuccessful SSL Handshake: " + sslEvent + ", client_ip = " + clientIP + ", channel_info = " + ChannelUtils.channelInfoForLogging(ctx.channel()) @@ -159,8 +178,9 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc spectatorRegistry.counter("zuul.sni.parse.success").increment(); } else { Throwable cause = sniCompletionEvent.cause(); - spectatorRegistry.counter("zuul.sni.parse.failure", - "cause", cause != null ? cause.getMessage() : "UNKNOWN").increment(); + spectatorRegistry + .counter("zuul.sni.parse.failure", "cause", cause != null ? cause.getMessage() : "UNKNOWN") + .increment(); } } super.userEventTriggered(ctx, evt); @@ -185,14 +205,27 @@ private void incrementCounters( String proto = handshakeInfo.getProtocol().length() > 0 ? handshakeInfo.getProtocol() : "unknown"; String ciphsuite = handshakeInfo.getCipherSuite().length() > 0 ? handshakeInfo.getCipherSuite() : "unknown"; - spectatorRegistry.counter("server.ssl.handshake", "success", "true", - "protocol", proto, "ciphersuite", ciphsuite, - "clientauth", String.valueOf(handshakeInfo.getClientAuthRequirement()) - ).increment(); + spectatorRegistry + .counter( + "server.ssl.handshake", + "success", + "true", + "protocol", + proto, + "ciphersuite", + ciphsuite, + "clientauth", + String.valueOf(handshakeInfo.getClientAuthRequirement())) + .increment(); } else { - spectatorRegistry.counter("server.ssl.handshake", "success", "false", - "failure_cause", getFailureCause(sslHandshakeCompletionEvent.cause()) - ).increment(); + spectatorRegistry + .counter( + "server.ssl.handshake", + "success", + "false", + "failure_cause", + getFailureCause(sslHandshakeCompletionEvent.cause())) + .increment(); } } catch (Exception e) { logger.error("Error incrementing counters for SSL handshake!", e); @@ -202,7 +235,7 @@ private void incrementCounters( @VisibleForTesting String getFailureCause(Throwable throwable) { String message = throwable.getMessage(); - if(message == null) { + if (message == null) { return throwable.toString(); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/BaseSslContextFactory.java b/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/BaseSslContextFactory.java index 976c16bf9d..c72c6e99d4 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/BaseSslContextFactory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/BaseSslContextFactory.java @@ -31,8 +31,10 @@ import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import io.netty.handler.ssl.SupportedCipherSuiteFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; @@ -47,8 +49,6 @@ import java.util.List; import java.util.Objects; import java.util.function.ToDoubleFunction; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * User: michaels@netflix.com @@ -88,14 +88,12 @@ public SslContextBuilder createBuilderForServer() { .sslProvider(sslProvider); if (serverSslConfig.getClientAuth() != null && trustedCerts != null && !trustedCerts.isEmpty()) { - builder = builder - .trustManager(trustedCerts.toArray(new X509Certificate[0])) + builder = builder.trustManager(trustedCerts.toArray(new X509Certificate[0])) .clientAuth(serverSslConfig.getClientAuth()); } return builder; - } - catch (Exception e) { + } catch (Exception e) { throw new RuntimeException("Error configuring SslContext!", e); } } @@ -121,7 +119,9 @@ public void enableSessionTickets(SslContext sslContext) { public void configureOpenSslStatsMetrics(SslContext sslContext, String sslContextId) { // Setup metrics tracking the OpenSSL stats. if (sslContext instanceof ReferenceCountedOpenSslContext) { - OpenSslSessionStats stats = ((ReferenceCountedOpenSslContext) sslContext).sessionContext().stats(); + OpenSslSessionStats stats = ((ReferenceCountedOpenSslContext) sslContext) + .sessionContext() + .stats(); openSslStatGauge(stats, sslContextId, "accept", OpenSslSessionStats::accept); openSslStatGauge(stats, sslContextId, "accept_good", OpenSslSessionStats::acceptGood); @@ -143,7 +143,9 @@ public void configureOpenSslStatsMetrics(SslContext sslContext, String sslContex } private void openSslStatGauge( - OpenSslSessionStats stats, String sslContextId, String statName, + OpenSslSessionStats stats, + String sslContextId, + String statName, ToDoubleFunction value) { Id id = spectatorRegistry.createId("server.ssl.stats", "id", sslContextId, "stat", statName); PolledMeter.using(spectatorRegistry).withId(id).monitorValue(stats, value); @@ -155,8 +157,7 @@ public static SslProvider chooseSslProvider() { SslProvider sslProvider; if (ALLOW_USE_OPENSSL.get() && OpenSsl.isAvailable() && SslProvider.isAlpnSupported(SslProvider.OPENSSL)) { sslProvider = SslProvider.OPENSSL; - } - else { + } else { sslProvider = SslProvider.JDK; } return sslProvider; @@ -179,21 +180,23 @@ protected CipherSuiteFilter getCiphersFilter() { return SupportedCipherSuiteFilter.INSTANCE; } - protected ArrayList getTrustedX509Certificates() throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException { + protected ArrayList getTrustedX509Certificates() + throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException { ArrayList trustedCerts = new ArrayList<>(); // Add the certificates from the JKS truststore - ie. the CA's of the client cert that peer Zuul's will use. - if (serverSslConfig.getClientAuth() == ClientAuth.REQUIRE || serverSslConfig.getClientAuth() == ClientAuth.OPTIONAL) { + if (serverSslConfig.getClientAuth() == ClientAuth.REQUIRE + || serverSslConfig.getClientAuth() == ClientAuth.OPTIONAL) { // Get the encrypted bytes of the truststore password. byte[] trustStorePwdBytes; if (serverSslConfig.getClientAuthTrustStorePassword() != null) { trustStorePwdBytes = Base64.getDecoder().decode(serverSslConfig.getClientAuthTrustStorePassword()); - } - else if (serverSslConfig.getClientAuthTrustStorePasswordFile() != null) { - trustStorePwdBytes = Files.readAllBytes(serverSslConfig.getClientAuthTrustStorePasswordFile().toPath()); - } - else { - throw new IllegalArgumentException("Must specify either ClientAuthTrustStorePassword or ClientAuthTrustStorePasswordFile!"); + } else if (serverSslConfig.getClientAuthTrustStorePasswordFile() != null) { + trustStorePwdBytes = Files.readAllBytes( + serverSslConfig.getClientAuthTrustStorePasswordFile().toPath()); + } else { + throw new IllegalArgumentException( + "Must specify either ClientAuthTrustStorePassword or ClientAuthTrustStorePasswordFile!"); } // Decrypt the truststore password. @@ -205,7 +208,8 @@ else if (serverSslConfig.getClientAuthTrustStorePasswordFile() != null) { } final KeyStore trustStore = KeyStore.getInstance("JKS"); - trustStore.load(new FileInputStream(serverSslConfig.getClientAuthTrustStoreFile()), + trustStore.load( + new FileInputStream(serverSslConfig.getClientAuthTrustStoreFile()), trustStorePassword.toCharArray()); Enumeration aliases = trustStore.aliases(); diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/ClientSslContextFactory.java b/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/ClientSslContextFactory.java index d2e5bb0e6f..9652377a6c 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/ClientSslContextFactory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/ClientSslContextFactory.java @@ -38,37 +38,30 @@ public final class ClientSslContextFactory extends BaseSslContextFactory { private static final Logger log = LoggerFactory.getLogger(ClientSslContextFactory.class); private static final ServerSslConfig DEFAULT_CONFIG = new ServerSslConfig( - maybeAddTls13(ENABLE_CLIENT_TLS13.get(), "TLSv1.2"), - ServerSslConfig.getDefaultCiphers(), - null, - null - ); + maybeAddTls13(ENABLE_CLIENT_TLS13.get(), "TLSv1.2"), ServerSslConfig.getDefaultCiphers(), null, null); public ClientSslContextFactory(Registry spectatorRegistry) { super(spectatorRegistry, DEFAULT_CONFIG); } - public ClientSslContextFactory(Registry spectatorRegistry, ServerSslConfig serverSslConfig) { super(spectatorRegistry, serverSslConfig); } public SslContext getClientSslContext() { try { - return SslContextBuilder - .forClient() + return SslContextBuilder.forClient() .sslProvider(chooseSslProvider()) .ciphers(getCiphers(), getCiphersFilter()) .protocols(getProtocols()) .build(); - } - catch (Exception e) { + } catch (Exception e) { log.error("Error loading SslContext client request.", e); throw new RuntimeException("Error configuring SslContext for client request!", e); } } - static String[] maybeAddTls13(boolean enableTls13, String ... defaultProtocols) { + static String[] maybeAddTls13(boolean enableTls13, String... defaultProtocols) { if (enableTls13) { String[] protocols = new String[defaultProtocols.length + 1]; System.arraycopy(defaultProtocols, 0, protocols, 1, defaultProtocols.length); diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/SslContextFactory.java b/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/SslContextFactory.java index 6be5ef8707..8374c31874 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/SslContextFactory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/SslContextFactory.java @@ -27,11 +27,14 @@ * Date: 11/8/16 * Time: 1:01 PM */ -public interface SslContextFactory -{ +public interface SslContextFactory { SslContextBuilder createBuilderForServer(); + String[] getProtocols(); + List getCiphers() throws NoSuchAlgorithmException; + void enableSessionTickets(SslContext sslContext); + void configureOpenSslStatsMetrics(SslContext sslContext, String sslContextId); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/netty/timeouts/OriginTimeoutManager.java b/zuul-core/src/main/java/com/netflix/zuul/netty/timeouts/OriginTimeoutManager.java index ab1f5a8a21..89f27a6339 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/netty/timeouts/OriginTimeoutManager.java +++ b/zuul-core/src/main/java/com/netflix/zuul/netty/timeouts/OriginTimeoutManager.java @@ -24,10 +24,11 @@ import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.origins.NettyOrigin; + +import javax.annotation.Nullable; import java.time.Duration; import java.util.Objects; import java.util.Optional; -import javax.annotation.Nullable; /** * Origin Timeout Manager @@ -44,8 +45,8 @@ public OriginTimeoutManager(NettyOrigin origin) { } @VisibleForTesting - static final DynamicLongProperty MAX_OUTBOUND_READ_TIMEOUT_MS = - new DynamicLongProperty("zuul.origin.readtimeout.max", Duration.ofSeconds(90).toMillis()); + static final DynamicLongProperty MAX_OUTBOUND_READ_TIMEOUT_MS = new DynamicLongProperty( + "zuul.origin.readtimeout.max", Duration.ofSeconds(90).toMillis()); /** * Derives the read timeout from the configuration. This implementation prefers the longer of either the origin diff --git a/zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempt.java b/zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempt.java index 2a555ba54f..192718c2b2 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempt.java +++ b/zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempt.java @@ -25,8 +25,8 @@ import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.zuul.discovery.DiscoveryResult; -import com.netflix.zuul.exception.OutboundException; import com.netflix.zuul.discovery.SimpleMetaInfo; +import com.netflix.zuul.exception.OutboundException; import com.netflix.zuul.netty.connectionpool.OriginConnectException; import io.netty.handler.timeout.ReadTimeoutException; @@ -37,8 +37,7 @@ * Date: 9/2/14 * Time: 2:52 PM */ -public class RequestAttempt -{ +public class RequestAttempt { private static final ObjectMapper JACKSON_MAPPER = new ObjectMapper(); private int attempt; @@ -59,9 +58,17 @@ public class RequestAttempt private int connectTimeout; private int maxRetries; - public RequestAttempt(int attemptNumber, InstanceInfo server, String targetVip, String chosenWarmupLB, int status, String error, String exceptionType, - int readTimeout, int connectTimeout, int maxRetries) - { + public RequestAttempt( + int attemptNumber, + InstanceInfo server, + String targetVip, + String chosenWarmupLB, + int status, + String error, + String exceptionType, + int readTimeout, + int connectTimeout, + int maxRetries) { if (attemptNumber < 1) { throw new IllegalArgumentException("Attempt number must be greater than 0! - " + attemptNumber); } @@ -81,7 +88,8 @@ public RequestAttempt(int attemptNumber, InstanceInfo server, String targetVip, } if (server.getDataCenterInfo() instanceof AmazonInfo) { - this.availabilityZone = ((AmazonInfo) server.getDataCenterInfo()).getMetadata().get("availability-zone"); + this.availabilityZone = + ((AmazonInfo) server.getDataCenterInfo()).getMetadata().get("availability-zone"); // HACK - get region by just removing the last char from zone. String az = getAvailabilityZone(); @@ -90,7 +98,7 @@ public RequestAttempt(int attemptNumber, InstanceInfo server, String targetVip, } } } - + this.status = status; this.error = error; this.exceptionType = exceptionType; @@ -99,7 +107,8 @@ public RequestAttempt(int attemptNumber, InstanceInfo server, String targetVip, this.maxRetries = maxRetries; } - public RequestAttempt(final DiscoveryResult server, final IClientConfig clientConfig, int attemptNumber, int readTimeout) { + public RequestAttempt( + final DiscoveryResult server, final IClientConfig clientConfig, int attemptNumber, int readTimeout) { this.status = -1; this.attempt = attemptNumber; this.readTimeout = readTimeout; @@ -118,8 +127,7 @@ public RequestAttempt(final DiscoveryResult server, final IClientConfig clientCo this.vip = server.getTarget(); this.availabilityZone = server.getAvailabilityZone(); - } - else { + } else { SimpleMetaInfo metaInfo = server.getMetaInfo(); if (metaInfo != null) { this.asg = metaInfo.getServerGroup(); @@ -138,11 +146,9 @@ public RequestAttempt(final DiscoveryResult server, final IClientConfig clientCo } } - private RequestAttempt() { - } + private RequestAttempt() {} - public void complete(int responseStatus, long durationMs, Throwable exception) - { + public void complete(int responseStatus, long durationMs, Throwable exception) { if (responseStatus > -1) { setStatus(responseStatus); } @@ -154,13 +160,11 @@ public void complete(int responseStatus, long durationMs, Throwable exception) } } - public int getAttempt() - { + public int getAttempt() { return attempt; } - public String getVip() - { + public String getVip() { return vip; } @@ -176,8 +180,7 @@ public String getError() { return error; } - public String getApp() - { + public String getApp() { return app; } @@ -197,8 +200,7 @@ public int getPort() { return port; } - public String getRegion() - { + public String getRegion() { return region; } @@ -206,88 +208,71 @@ public String getAvailabilityZone() { return availabilityZone; } - public String getExceptionType() - { + public String getExceptionType() { return exceptionType; } - public long getReadTimeout() - { + public long getReadTimeout() { return readTimeout; } - public int getConnectTimeout() - { + public int getConnectTimeout() { return connectTimeout; } - public int getMaxRetries() - { + public int getMaxRetries() { return maxRetries; } - public void setStatus(int status) - { + public void setStatus(int status) { this.status = status; } - public void setError(String error) - { + public void setError(String error) { this.error = error; } - public void setExceptionType(String exceptionType) - { + public void setExceptionType(String exceptionType) { this.exceptionType = exceptionType; } - public void setApp(String app) - { + public void setApp(String app) { this.app = app; } - public void setAsg(String asg) - { + public void setAsg(String asg) { this.asg = asg; } - public void setInstanceId(String instanceId) - { + public void setInstanceId(String instanceId) { this.instanceId = instanceId; } - public void setHost(String host) - { + public void setHost(String host) { this.host = host; } - public void setPort(int port) - { + public void setPort(int port) { this.port = port; } - public void setVip(String vip) - { + public void setVip(String vip) { this.vip = vip; } - public void setRegion(String region) - { + public void setRegion(String region) { this.region = region; } - public void setAvailabilityZone(String availabilityZone) - { + public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; } - public void setReadTimeout(long readTimeout) - { + public void setReadTimeout(long readTimeout) { this.readTimeout = readTimeout; } - public void setConnectTimeout(int connectTimeout) - { + public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } @@ -296,35 +281,29 @@ public void setException(Throwable t) { if (t instanceof ReadTimeoutException) { error = "READ_TIMEOUT"; exceptionType = t.getClass().getSimpleName(); - } - else if (t instanceof OriginConnectException) { + } else if (t instanceof OriginConnectException) { OriginConnectException oce = (OriginConnectException) t; if (oce.getErrorType() != null) { error = oce.getErrorType().toString(); - } - else { + } else { error = "ORIGIN_CONNECT_ERROR"; } final Throwable cause = t.getCause(); if (cause != null) { exceptionType = t.getCause().getClass().getSimpleName(); - } - else { + } else { exceptionType = t.getClass().getSimpleName(); } - } - else if (t instanceof OutboundException) { + } else if (t instanceof OutboundException) { OutboundException obe = (OutboundException) t; error = obe.getOutboundErrorType().toString(); exceptionType = OutboundException.class.getSimpleName(); - } - else if (t instanceof SSLHandshakeException) { + } else if (t instanceof SSLHandshakeException) { error = t.getMessage(); exceptionType = t.getClass().getSimpleName(); cause = t.getCause().getMessage(); - } - else { + } else { error = t.getMessage(); exceptionType = t.getClass().getSimpleName(); cause = Throwables.getStackTraceAsString(t); @@ -332,24 +311,20 @@ else if (t instanceof SSLHandshakeException) { } } - public void setMaxRetries(int maxRetries) - { + public void setMaxRetries(int maxRetries) { this.maxRetries = maxRetries; } @Override - public String toString() - { + public String toString() { try { return JACKSON_MAPPER.writeValueAsString(toJsonNode()); - } - catch (JsonProcessingException e) { + } catch (JsonProcessingException e) { throw new RuntimeException("Error serializing RequestAttempt!", e); } } - public ObjectNode toJsonNode() - { + public ObjectNode toJsonNode() { ObjectNode root = JACKSON_MAPPER.createObjectNode(); root.put("status", status); root.put("duration", duration); @@ -372,8 +347,7 @@ public ObjectNode toJsonNode() return root; } - private static ObjectNode putNullableAttribute(ObjectNode node, String name, String value) - { + private static ObjectNode putNullableAttribute(ObjectNode node, String name, String value) { if (value != null) { node.put(name, value); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempts.java b/zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempts.java index e47338c583..6270e07f36 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempts.java +++ b/zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempts.java @@ -21,10 +21,10 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; -import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; @@ -33,39 +33,32 @@ * Date: 6/25/15 * Time: 1:03 PM */ -public class RequestAttempts extends ArrayList -{ +public class RequestAttempts extends ArrayList { private static final Logger LOG = LoggerFactory.getLogger(RequestAttempts.class); private static final ObjectMapper JACKSON_MAPPER = new ObjectMapper(); - public RequestAttempts() - { + public RequestAttempts() { super(); } @Nullable - public RequestAttempt getFinalAttempt() - { + public RequestAttempt getFinalAttempt() { if (size() > 0) { return get(size() - 1); - } - else { + } else { return null; } } - public static RequestAttempts getFromSessionContext(SessionContext ctx) - { + public static RequestAttempts getFromSessionContext(SessionContext ctx) { return ctx.get(CommonContextKeys.REQUEST_ATTEMPTS); } - public static RequestAttempts parse(String attemptsJson) throws IOException - { + public static RequestAttempts parse(String attemptsJson) throws IOException { return JACKSON_MAPPER.readValue(attemptsJson, RequestAttempts.class); } - public String toJSON() - { + public String toJSON() { ArrayNode array = JACKSON_MAPPER.createArrayNode(); for (RequestAttempt attempt : this) { array.add(attempt.toJsonNode()); @@ -73,19 +66,16 @@ public String toJSON() try { return JACKSON_MAPPER.writeValueAsString(array); - } - catch (JsonProcessingException e) { + } catch (JsonProcessingException e) { throw new RuntimeException("Error serializing RequestAttempts!", e); } } @Override - public String toString() - { + public String toString() { try { return toJSON(); - } - catch (Throwable e) { + } catch (Throwable e) { LOG.error(e.getMessage(), e); return ""; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/origins/BasicNettyOrigin.java b/zuul-core/src/main/java/com/netflix/zuul/origins/BasicNettyOrigin.java index 52d3a15dd4..60f83de8a8 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/origins/BasicNettyOrigin.java +++ b/zuul-core/src/main/java/com/netflix/zuul/origins/BasicNettyOrigin.java @@ -16,10 +16,6 @@ package com.netflix.zuul.origins; -import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_ORIGIN; -import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_ORIGIN_THROTTLED; -import static com.netflix.zuul.stats.status.ZuulStatusCategory.SUCCESS; - import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; @@ -27,9 +23,9 @@ import com.netflix.config.CachedDynamicIntProperty; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Registry; -import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; +import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.exception.ErrorType; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpResponseMessage; @@ -44,12 +40,17 @@ import com.netflix.zuul.stats.status.StatusCategoryUtils; import io.netty.channel.EventLoop; import io.netty.util.concurrent.Promise; + import java.net.InetAddress; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_ORIGIN; +import static com.netflix.zuul.stats.status.ZuulStatusCategory.FAILURE_ORIGIN_THROTTLED; +import static com.netflix.zuul.stats.status.ZuulStatusCategory.SUCCESS; + /** * Netty Origin basic implementation that can be used for most apps, with the more complex methods having no-op * implementations. @@ -80,14 +81,12 @@ public BasicNettyOrigin(OriginName originName, Registry registry) { String niwsClientName = getName().getNiwsClientName(); this.concurrentRequests = - SpectatorUtils.newGauge( - "zuul.origin.concurrent.requests", niwsClientName, new AtomicInteger(0)); - this.rejectedRequests = - SpectatorUtils.newCounter("zuul.origin.rejected.requests", niwsClientName); + SpectatorUtils.newGauge("zuul.origin.concurrent.requests", niwsClientName, new AtomicInteger(0)); + this.rejectedRequests = SpectatorUtils.newCounter("zuul.origin.rejected.requests", niwsClientName); this.concurrencyMax = new CachedDynamicIntProperty("zuul.origin." + niwsClientName + ".concurrency.max.requests", 200); - this.concurrencyProtectionEnabled = - new CachedDynamicBooleanProperty("zuul.origin." + niwsClientName + ".concurrency.protect.enabled", true); + this.concurrencyProtectionEnabled = new CachedDynamicBooleanProperty( + "zuul.origin." + niwsClientName + ".concurrency.protect.enabled", true); } protected IClientConfig setupClientConfig(OriginName originName) { @@ -116,8 +115,12 @@ public boolean isCold() { @Override public Promise connectToOrigin( - HttpRequestMessage zuulReq, EventLoop eventLoop, int attemptNumber, CurrentPassport passport, - AtomicReference chosenServer, AtomicReference chosenHostAddr) { + HttpRequestMessage zuulReq, + EventLoop eventLoop, + int attemptNumber, + CurrentPassport passport, + AtomicReference chosenServer, + AtomicReference chosenHostAddr) { return clientChannelManager.acquire(eventLoop, null, passport, chosenServer, chosenHostAddr); } @@ -176,8 +179,7 @@ public void recordFinalResponse(HttpResponseMessage resp) { StatusCategory originNfs = SUCCESS; if (originStatusCode == 503) { originNfs = FAILURE_ORIGIN_THROTTLED; - } - else if (StatusCategoryUtils.isResponseHttpErrorStatus(originStatusCode)) { + } else if (StatusCategoryUtils.isResponseHttpErrorStatus(originStatusCode)) { originNfs = FAILURE_ORIGIN; } zuulCtx.put(CommonContextKeys.ORIGIN_STATUS_CATEGORY, originNfs); @@ -215,30 +217,29 @@ public double getErrorAllPercentage() { } @Override - public void onRequestExecutionStart(HttpRequestMessage zuulReq) { - } + public void onRequestExecutionStart(HttpRequestMessage zuulReq) {} @Override - public void onRequestStartWithServer(HttpRequestMessage zuulReq, DiscoveryResult discoveryResult, int attemptNum) { - } + public void onRequestStartWithServer(HttpRequestMessage zuulReq, DiscoveryResult discoveryResult, int attemptNum) {} @Override - public void onRequestExceptionWithServer(HttpRequestMessage zuulReq, DiscoveryResult discoveryResult, int attemptNum, Throwable t) { - } + public void onRequestExceptionWithServer( + HttpRequestMessage zuulReq, DiscoveryResult discoveryResult, int attemptNum, Throwable t) {} @Override - public void onRequestExecutionSuccess(HttpRequestMessage zuulReq, HttpResponseMessage zuulResp, DiscoveryResult discoveryResult, int attemptNum) { - } + public void onRequestExecutionSuccess( + HttpRequestMessage zuulReq, + HttpResponseMessage zuulResp, + DiscoveryResult discoveryResult, + int attemptNum) {} @Override - public void onRequestExecutionFailed(HttpRequestMessage zuulReq, DiscoveryResult discoveryResult, int attemptNum, Throwable t) { - } + public void onRequestExecutionFailed( + HttpRequestMessage zuulReq, DiscoveryResult discoveryResult, int attemptNum, Throwable t) {} @Override - public void adjustRetryPolicyIfNeeded(HttpRequestMessage zuulRequest) { - } + public void adjustRetryPolicyIfNeeded(HttpRequestMessage zuulRequest) {} @Override - public void recordSuccessResponse() { - } + public void recordSuccessResponse() {} } diff --git a/zuul-core/src/main/java/com/netflix/zuul/origins/BasicNettyOriginManager.java b/zuul-core/src/main/java/com/netflix/zuul/origins/BasicNettyOriginManager.java index 2ababc88ff..e452472371 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/origins/BasicNettyOriginManager.java +++ b/zuul-core/src/main/java/com/netflix/zuul/origins/BasicNettyOriginManager.java @@ -48,8 +48,7 @@ public BasicNettyOrigin getOrigin(OriginName originName, String uri, SessionCont } @Override - public BasicNettyOrigin createOrigin( - OriginName originName, String uri, SessionContext ctx) { + public BasicNettyOrigin createOrigin(OriginName originName, String uri, SessionContext ctx) { return new BasicNettyOrigin(originName, registry); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/origins/InstrumentedOrigin.java b/zuul-core/src/main/java/com/netflix/zuul/origins/InstrumentedOrigin.java index 2459eb8b3e..e2ad4ab002 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/origins/InstrumentedOrigin.java +++ b/zuul-core/src/main/java/com/netflix/zuul/origins/InstrumentedOrigin.java @@ -17,7 +17,6 @@ package com.netflix.zuul.origins; import com.netflix.zuul.message.http.HttpRequestMessage; -import javax.annotation.Nullable; /** * User: michaels@netflix.com diff --git a/zuul-core/src/main/java/com/netflix/zuul/origins/NettyOrigin.java b/zuul-core/src/main/java/com/netflix/zuul/origins/NettyOrigin.java index 666b17b3b5..102b72b280 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/origins/NettyOrigin.java +++ b/zuul-core/src/main/java/com/netflix/zuul/origins/NettyOrigin.java @@ -18,8 +18,8 @@ import com.netflix.client.config.IClientConfig; import com.netflix.spectator.api.Registry; -import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.context.SessionContext; +import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.netty.connectionpool.PooledConnection; @@ -39,25 +39,32 @@ */ public interface NettyOrigin extends InstrumentedOrigin { - Promise connectToOrigin(final HttpRequestMessage zuulReq, EventLoop eventLoop, - int attemptNumber, CurrentPassport passport, - AtomicReference chosenServer, - AtomicReference chosenHostAddr); + Promise connectToOrigin( + final HttpRequestMessage zuulReq, + EventLoop eventLoop, + int attemptNumber, + CurrentPassport passport, + AtomicReference chosenServer, + AtomicReference chosenHostAddr); int getMaxRetriesForRequest(SessionContext context); void onRequestExecutionStart(final HttpRequestMessage zuulReq); - void onRequestStartWithServer(final HttpRequestMessage zuulReq, final DiscoveryResult discoveryResult, int attemptNum); + void onRequestStartWithServer( + final HttpRequestMessage zuulReq, final DiscoveryResult discoveryResult, int attemptNum); - void onRequestExceptionWithServer(final HttpRequestMessage zuulReq, final DiscoveryResult discoveryResult, - final int attemptNum, Throwable t); + void onRequestExceptionWithServer( + final HttpRequestMessage zuulReq, final DiscoveryResult discoveryResult, final int attemptNum, Throwable t); - void onRequestExecutionSuccess(final HttpRequestMessage zuulReq, final HttpResponseMessage zuulResp, - final DiscoveryResult discoveryResult, final int attemptNum); + void onRequestExecutionSuccess( + final HttpRequestMessage zuulReq, + final HttpResponseMessage zuulResp, + final DiscoveryResult discoveryResult, + final int attemptNum); - void onRequestExecutionFailed(final HttpRequestMessage zuulReq, final DiscoveryResult discoveryResult, - final int attemptNum, Throwable t); + void onRequestExecutionFailed( + final HttpRequestMessage zuulReq, final DiscoveryResult discoveryResult, final int attemptNum, Throwable t); void recordFinalError(final HttpRequestMessage requestMsg, final Throwable throwable); diff --git a/zuul-core/src/main/java/com/netflix/zuul/origins/Origin.java b/zuul-core/src/main/java/com/netflix/zuul/origins/Origin.java index 6927978fda..c3c8cc141a 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/origins/Origin.java +++ b/zuul-core/src/main/java/com/netflix/zuul/origins/Origin.java @@ -22,6 +22,8 @@ */ public interface Origin { OriginName getName(); + boolean isAvailable(); + boolean isCold(); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/origins/OriginConcurrencyExceededException.java b/zuul-core/src/main/java/com/netflix/zuul/origins/OriginConcurrencyExceededException.java index 1c9c2a73a5..e85db40106 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/origins/OriginConcurrencyExceededException.java +++ b/zuul-core/src/main/java/com/netflix/zuul/origins/OriginConcurrencyExceededException.java @@ -16,13 +16,13 @@ package com.netflix.zuul.origins; - import com.netflix.zuul.stats.status.ZuulStatusCategory; -public class OriginConcurrencyExceededException extends OriginThrottledException -{ - public OriginConcurrencyExceededException(OriginName originName) - { - super(originName, "Max concurrent requests on origin exceeded", ZuulStatusCategory.FAILURE_LOCAL_THROTTLED_ORIGIN_CONCURRENCY); +public class OriginConcurrencyExceededException extends OriginThrottledException { + public OriginConcurrencyExceededException(OriginName originName) { + super( + originName, + "Max concurrent requests on origin exceeded", + ZuulStatusCategory.FAILURE_LOCAL_THROTTLED_ORIGIN_CONCURRENCY); } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/origins/OriginName.java b/zuul-core/src/main/java/com/netflix/zuul/origins/OriginName.java index 45c38ff547..8301a24464 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/origins/OriginName.java +++ b/zuul-core/src/main/java/com/netflix/zuul/origins/OriginName.java @@ -17,6 +17,7 @@ package com.netflix.zuul.origins; import com.netflix.zuul.util.VipUtils; + import java.util.Locale; import java.util.Objects; @@ -150,10 +151,9 @@ public int hashCode() { @Override public String toString() { - return "OriginName{" + - "niwsClientName='" + niwsClientName + '\'' + - ", target='" + target + '\'' + - ", authority='" + authority + '\'' + - '}'; + return "OriginName{" + "niwsClientName='" + + niwsClientName + '\'' + ", target='" + + target + '\'' + ", authority='" + + authority + '\'' + '}'; } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/origins/OriginThrottledException.java b/zuul-core/src/main/java/com/netflix/zuul/origins/OriginThrottledException.java index 8b24a5d4b5..901db64aac 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/origins/OriginThrottledException.java +++ b/zuul-core/src/main/java/com/netflix/zuul/origins/OriginThrottledException.java @@ -18,15 +18,14 @@ import com.netflix.zuul.exception.ZuulException; import com.netflix.zuul.stats.status.StatusCategory; + import java.util.Objects; -public abstract class OriginThrottledException extends ZuulException -{ +public abstract class OriginThrottledException extends ZuulException { private final OriginName originName; private final StatusCategory statusCategory; - public OriginThrottledException(OriginName originName, String msg, StatusCategory statusCategory) - { + public OriginThrottledException(OriginName originName, String msg, StatusCategory statusCategory) { // Ensure this exception does not fill its stacktrace as causes too much load. super(msg + ", origin=" + originName, true); this.originName = Objects.requireNonNull(originName, "originName"); @@ -38,8 +37,7 @@ public OriginName getOriginName() { return originName; } - public StatusCategory getStatusCategory() - { + public StatusCategory getStatusCategory() { return statusCategory; } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/passport/CurrentPassport.java b/zuul-core/src/main/java/com/netflix/zuul/passport/CurrentPassport.java index e6816f3557..898111ce12 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/passport/CurrentPassport.java +++ b/zuul-core/src/main/java/com/netflix/zuul/passport/CurrentPassport.java @@ -26,6 +26,8 @@ import com.netflix.zuul.context.SessionContext; import io.netty.channel.Channel; import io.netty.util.AttributeKey; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; @@ -35,20 +37,15 @@ import java.util.LinkedList; import java.util.List; import java.util.Set; -import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class CurrentPassport -{ +public class CurrentPassport { private static final Logger logger = LoggerFactory.getLogger(CurrentPassport.class); - private static final CachedDynamicBooleanProperty COUNT_STATES = new CachedDynamicBooleanProperty( - "zuul.passport.count.enabled", false); + private static final CachedDynamicBooleanProperty COUNT_STATES = + new CachedDynamicBooleanProperty("zuul.passport.count.enabled", false); public static final AttributeKey CHANNEL_ATTR = AttributeKey.newInstance("_current_passport"); private static final Ticker SYSTEM_TICKER = Ticker.systemTicker(); @@ -58,10 +55,9 @@ public class CurrentPassport PassportState.OUT_REQ_CONTENT_SENDING, PassportState.OUT_REQ_CONTENT_SENT, PassportState.OUT_RESP_CONTENT_SENDING, - PassportState.OUT_RESP_CONTENT_SENT - ); - private static final CachedDynamicBooleanProperty CONTENT_STATE_ENABLED = new CachedDynamicBooleanProperty( - "zuul.passport.state.content.enabled", false); + PassportState.OUT_RESP_CONTENT_SENT); + private static final CachedDynamicBooleanProperty CONTENT_STATE_ENABLED = + new CachedDynamicBooleanProperty("zuul.passport.state.content.enabled", false); private final Ticker ticker; private final LinkedList history; @@ -70,6 +66,7 @@ public class CurrentPassport private final IntrospectiveReentrantLock historyLock = new IntrospectiveReentrantLock(); private final Unlocker unlocker = new Unlocker(); + private final class Unlocker implements AutoCloseable { @Override @@ -77,7 +74,8 @@ public void close() { historyLock.unlock(); } } - private final static class IntrospectiveReentrantLock extends ReentrantLock { + + private static final class IntrospectiveReentrantLock extends ReentrantLock { @Override protected Thread getOwner() { @@ -102,42 +100,36 @@ private Unlocker lock() { return unlocker; } - CurrentPassport() - { + CurrentPassport() { this(SYSTEM_TICKER); } @VisibleForTesting - public CurrentPassport(Ticker ticker) - { + public CurrentPassport(Ticker ticker) { this.ticker = ticker; this.history = new LinkedList<>(); this.statesAdded = new HashSet<>(); this.creationTimeSinceEpochMs = System.currentTimeMillis(); } - public static CurrentPassport create() - { + public static CurrentPassport create() { if (COUNT_STATES.get()) { return new CountingCurrentPassport(); } return new CurrentPassport(); } - public static CurrentPassport fromSessionContext(SessionContext ctx) - { + public static CurrentPassport fromSessionContext(SessionContext ctx) { return ctx.get(CommonContextKeys.PASSPORT); } - public static CurrentPassport createForChannel(Channel ch) - { + public static CurrentPassport createForChannel(Channel ch) { CurrentPassport passport = create(); passport.setOnChannel(ch); return passport; } - public static CurrentPassport fromChannel(Channel ch) - { + public static CurrentPassport fromChannel(Channel ch) { CurrentPassport passport = fromChannelOrNull(ch); if (passport == null) { passport = create(); @@ -146,12 +138,10 @@ public static CurrentPassport fromChannel(Channel ch) return passport; } - public static CurrentPassport fromChannelOrNull(Channel ch) - { + public static CurrentPassport fromChannelOrNull(Channel ch) { return ch.attr(CHANNEL_ATTR).get(); } - public void setOnChannel(Channel ch) { ch.attr(CHANNEL_ATTR).set(this); } @@ -161,24 +151,22 @@ public static void clearFromChannel(Channel ch) { } public PassportState getState() { - try (Unlocker ignored = lock()){ + try (Unlocker ignored = lock()) { PassportItem passportItem = history.peekLast(); return passportItem != null ? passportItem.getState() : null; } } @VisibleForTesting - public LinkedList getHistory() - { + public LinkedList getHistory() { try (Unlocker ignored = lock()) { // best effort, but doesn't actually protect anything return history; } } - public void add(PassportState state) - { - if (! CONTENT_STATE_ENABLED.get()) { + public void add(PassportState state) { + if (!CONTENT_STATE_ENABLED.get()) { if (CONTENT_STATES.contains(state)) { // Discard. return; @@ -191,15 +179,13 @@ public void add(PassportState state) statesAdded.add(state); } - public void addIfNotAlready(PassportState state) - { - if (! statesAdded.contains(state)) { + public void addIfNotAlready(PassportState state) { + if (!statesAdded.contains(state)) { add(state); } } - public long calculateTimeBetweenFirstAnd(PassportState endState) - { + public long calculateTimeBetweenFirstAnd(PassportState endState) { long startTime = firstTime(); try (Unlocker ignored = lock()) { for (PassportItem item : history) { @@ -214,28 +200,24 @@ public long calculateTimeBetweenFirstAnd(PassportState endState) /** * NOTE: This is NOT nanos since epoch. It's just since an arbitrary point in time. So only use relatively. */ - public long firstTime() - { + public long firstTime() { try (Unlocker ignored = lock()) { return history.getFirst().getTime(); } } - public long creationTimeSinceEpochMs() - { + public long creationTimeSinceEpochMs() { return creationTimeSinceEpochMs; } - public long calculateTimeBetween(StartAndEnd sae) - { + public long calculateTimeBetween(StartAndEnd sae) { if (sae.startNotFound() || sae.endNotFound()) { return 0; } return sae.endTime - sae.startTime; } - public long calculateTimeBetweenButIfNoEndThenUseNow(StartAndEnd sae) - { + public long calculateTimeBetweenButIfNoEndThenUseNow(StartAndEnd sae) { if (sae.startNotFound()) { return 0; } @@ -248,15 +230,13 @@ public long calculateTimeBetweenButIfNoEndThenUseNow(StartAndEnd sae) return sae.endTime - sae.startTime; } - public StartAndEnd findStartAndEndStates(PassportState startState, PassportState endState) - { + public StartAndEnd findStartAndEndStates(PassportState startState, PassportState endState) { StartAndEnd sae = new StartAndEnd(); try (Unlocker ignored = lock()) { for (PassportItem item : history) { if (item.getState() == startState) { sae.startTime = item.getTime(); - } - else if (item.getState() == endState) { + } else if (item.getState() == endState) { sae.endTime = item.getTime(); } } @@ -265,15 +245,13 @@ else if (item.getState() == endState) { return sae; } - public StartAndEnd findFirstStartAndLastEndStates(PassportState startState, PassportState endState) - { + public StartAndEnd findFirstStartAndLastEndStates(PassportState startState, PassportState endState) { StartAndEnd sae = new StartAndEnd(); try (Unlocker ignored = lock()) { for (PassportItem item : history) { if (sae.startNotFound() && item.getState() == startState) { sae.startTime = item.getTime(); - } - else if (item.getState() == endState) { + } else if (item.getState() == endState) { sae.endTime = item.getTime(); } } @@ -281,8 +259,7 @@ else if (item.getState() == endState) { return sae; } - public StartAndEnd findLastStartAndFirstEndStates(PassportState startState, PassportState endState) - { + public StartAndEnd findLastStartAndFirstEndStates(PassportState startState, PassportState endState) { StartAndEnd sae = new StartAndEnd(); try (Unlocker ignored = lock()) { for (PassportItem item : history) { @@ -295,9 +272,8 @@ public StartAndEnd findLastStartAndFirstEndStates(PassportState startState, Pass } return sae; } - - public List findEachPairOf(PassportState startState, PassportState endState) - { + + public List findEachPairOf(PassportState startState, PassportState endState) { ArrayList items = new ArrayList<>(); StartAndEnd currentPair = null; @@ -319,12 +295,11 @@ public List findEachPairOf(PassportState startState, PassportState } } } - + return items; } - public PassportItem findState(PassportState state) - { + public PassportItem findState(PassportState state) { try (Unlocker ignored = lock()) { for (PassportItem item : history) { if (item.getState() == state) { @@ -335,8 +310,7 @@ public PassportItem findState(PassportState state) return null; } - public PassportItem findStateBackwards(PassportState state) - { + public PassportItem findStateBackwards(PassportState state) { try (Unlocker ignored = lock()) { Iterator itr = history.descendingIterator(); while (itr.hasNext()) { @@ -349,8 +323,7 @@ public PassportItem findStateBackwards(PassportState state) return null; } - public List findStates(PassportState state) - { + public List findStates(PassportState state) { ArrayList items = new ArrayList<>(); try (Unlocker ignored = lock()) { for (PassportItem item : history) { @@ -362,8 +335,7 @@ public List findStates(PassportState state) return items; } - public List findTimes(PassportState state) - { + public List findTimes(PassportState state) { long startTick = firstTime(); ArrayList items = new ArrayList<>(); try (Unlocker ignored = lock()) { @@ -376,21 +348,18 @@ public List findTimes(PassportState state) return items; } - public boolean wasProxyAttempt() - { + public boolean wasProxyAttempt() { // If an attempt was made to send outbound request headers on this session, then assume it was an // attempt to proxy. return findState(PassportState.OUT_REQ_HEADERS_SENDING) != null; } - - private long now() - { + + private long now() { return ticker.read(); } @Override - public String toString() - { + public String toString() { try (Unlocker ignored = lock()) { long startTime = history.size() > 0 ? firstTime() : 0; long now = now(); @@ -401,7 +370,10 @@ public String toString() sb.append('['); for (PassportItem item : history) { - sb.append('+').append(item.getTime() - startTime).append('=').append(item.getState().name()) + sb.append('+') + .append(item.getTime() - startTime) + .append('=') + .append(item.getState().name()) .append(", "); } sb.append('+').append(now - startTime).append('=').append("NOW"); @@ -414,8 +386,7 @@ public String toString() } @VisibleForTesting - public static CurrentPassport parseFromToString(String text) - { + public static CurrentPassport parseFromToString(String text) { CurrentPassport passport = null; Pattern ptn = Pattern.compile("CurrentPassport \\{start_ms=\\d+, \\[(.*)\\]\\}"); Pattern ptnState = Pattern.compile("^\\+(\\d+)=(.+)$"); @@ -445,60 +416,52 @@ public static CurrentPassport parseFromToString(String text) return passport; } - private static class MockTicker extends Ticker - { + private static class MockTicker extends Ticker { private long now = -1; @Override - public long read() - { + public long read() { if (now == -1) { throw new IllegalStateException(); } return now; } - public void setNow(long now) - { + public void setNow(long now) { this.now = now; } } } -class CountingCurrentPassport extends CurrentPassport -{ - private final static Counter IN_REQ_HEADERS_RECEIVED_CNT = createCounter("in_req_hdrs_rec"); - private final static Counter IN_REQ_LAST_CONTENT_RECEIVED_CNT = createCounter("in_req_last_cont_rec"); +class CountingCurrentPassport extends CurrentPassport { + private static final Counter IN_REQ_HEADERS_RECEIVED_CNT = createCounter("in_req_hdrs_rec"); + private static final Counter IN_REQ_LAST_CONTENT_RECEIVED_CNT = createCounter("in_req_last_cont_rec"); - private final static Counter IN_RESP_HEADERS_RECEIVED_CNT = createCounter("in_resp_hdrs_rec"); - private final static Counter IN_RESP_LAST_CONTENT_RECEIVED_CNT = createCounter("in_resp_last_cont_rec"); + private static final Counter IN_RESP_HEADERS_RECEIVED_CNT = createCounter("in_resp_hdrs_rec"); + private static final Counter IN_RESP_LAST_CONTENT_RECEIVED_CNT = createCounter("in_resp_last_cont_rec"); - private final static Counter OUT_REQ_HEADERS_SENT_CNT = createCounter("out_req_hdrs_sent"); - private final static Counter OUT_REQ_LAST_CONTENT_SENT_CNT = createCounter("out_req_last_cont_sent"); + private static final Counter OUT_REQ_HEADERS_SENT_CNT = createCounter("out_req_hdrs_sent"); + private static final Counter OUT_REQ_LAST_CONTENT_SENT_CNT = createCounter("out_req_last_cont_sent"); - private final static Counter OUT_RESP_HEADERS_SENT_CNT = createCounter("out_resp_hdrs_sent"); - private final static Counter OUT_RESP_LAST_CONTENT_SENT_CNT = createCounter("out_resp_last_cont_sent"); + private static final Counter OUT_RESP_HEADERS_SENT_CNT = createCounter("out_resp_hdrs_sent"); + private static final Counter OUT_RESP_LAST_CONTENT_SENT_CNT = createCounter("out_resp_last_cont_sent"); - private static Counter createCounter(String name) - { + private static Counter createCounter(String name) { return Spectator.globalRegistry().counter("zuul.passport." + name); } - public CountingCurrentPassport() - { + public CountingCurrentPassport() { super(); incrementStateCounter(getState()); } @Override - public void add(PassportState state) - { + public void add(PassportState state) { super.add(state); incrementStateCounter(state); } - private void incrementStateCounter(PassportState state) - { + private void incrementStateCounter(PassportState state) { switch (state) { case IN_REQ_HEADERS_RECEIVED: IN_REQ_HEADERS_RECEIVED_CNT.increment(); diff --git a/zuul-core/src/main/java/com/netflix/zuul/passport/PassportItem.java b/zuul-core/src/main/java/com/netflix/zuul/passport/PassportItem.java index f3e6046a03..5468bba242 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/passport/PassportItem.java +++ b/zuul-core/src/main/java/com/netflix/zuul/passport/PassportItem.java @@ -16,30 +16,25 @@ package com.netflix.zuul.passport; -public class PassportItem -{ +public class PassportItem { private final long time; private final PassportState state; - public PassportItem(PassportState state, long time) - { + public PassportItem(PassportState state, long time) { this.time = time; this.state = state; } - public long getTime() - { + public long getTime() { return time; } - public PassportState getState() - { + public PassportState getState() { return state; } @Override - public String toString() - { + public String toString() { return time + "=" + state; } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/passport/PassportState.java b/zuul-core/src/main/java/com/netflix/zuul/passport/PassportState.java index 23c76a96c2..794f634ba8 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/passport/PassportState.java +++ b/zuul-core/src/main/java/com/netflix/zuul/passport/PassportState.java @@ -16,8 +16,7 @@ package com.netflix.zuul.passport; -public enum PassportState -{ +public enum PassportState { IN_REQ_HEADERS_RECEIVED, IN_REQ_CONTENT_RECEIVED, IN_REQ_LAST_CONTENT_RECEIVED, @@ -58,11 +57,11 @@ public enum PassportState FILTERS_INBOUND_BUF_END, FILTERS_OUTBOUND_BUF_START, FILTERS_OUTBOUND_BUF_END, - + ORIGIN_CONN_ACQUIRE_START, ORIGIN_CONN_ACQUIRE_END, ORIGIN_CONN_ACQUIRE_FAILED, - + MISC_IO_START, MISC_IO_STOP, diff --git a/zuul-core/src/main/java/com/netflix/zuul/passport/StartAndEnd.java b/zuul-core/src/main/java/com/netflix/zuul/passport/StartAndEnd.java index cf45bffdfb..598776198e 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/passport/StartAndEnd.java +++ b/zuul-core/src/main/java/com/netflix/zuul/passport/StartAndEnd.java @@ -16,18 +16,15 @@ package com.netflix.zuul.passport; -public class StartAndEnd -{ +public class StartAndEnd { long startTime = -1; long endTime = -1; - public long getStart() - { + public long getStart() { return startTime; } - public long getEnd() - { + public long getEnd() { return endTime; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/plugins/Tracer.java b/zuul-core/src/main/java/com/netflix/zuul/plugins/Tracer.java index bb50cfbe60..d744ab5a7b 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/plugins/Tracer.java +++ b/zuul-core/src/main/java/com/netflix/zuul/plugins/Tracer.java @@ -17,6 +17,7 @@ import com.netflix.spectator.api.Spectator; import com.netflix.zuul.monitoring.TracerFactory; + import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.TimeUnit; @@ -31,7 +32,6 @@ public class Tracer extends TracerFactory { @Override - public com.netflix.zuul.monitoring.Tracer startMicroTracer(String name) { return new SpectatorTracer(name); } @@ -48,7 +48,8 @@ private SpectatorTracer(String name) { @Override public void stopAndLog() { - Spectator.globalRegistry().timer(name, "hostname", getHostName(), "ip", getIp()) + Spectator.globalRegistry() + .timer(name, "hostname", getHostName(), "ip", getIp()) .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/stats/AmazonInfoHolder.java b/zuul-core/src/main/java/com/netflix/zuul/stats/AmazonInfoHolder.java index 907baf333b..ce66f6d965 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/stats/AmazonInfoHolder.java +++ b/zuul-core/src/main/java/com/netflix/zuul/stats/AmazonInfoHolder.java @@ -31,5 +31,4 @@ public static final AmazonInfo getInfo() { } private AmazonInfoHolder() {} - } \ No newline at end of file diff --git a/zuul-core/src/main/java/com/netflix/zuul/stats/BasicRequestMetricsPublisher.java b/zuul-core/src/main/java/com/netflix/zuul/stats/BasicRequestMetricsPublisher.java index d05ac1d17e..682f82b216 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/stats/BasicRequestMetricsPublisher.java +++ b/zuul-core/src/main/java/com/netflix/zuul/stats/BasicRequestMetricsPublisher.java @@ -23,8 +23,7 @@ * Date: 6/4/15 * Time: 4:22 PM */ -public class BasicRequestMetricsPublisher implements RequestMetricsPublisher -{ +public class BasicRequestMetricsPublisher implements RequestMetricsPublisher { @Override public void collectAndPublish(SessionContext context) { // Record metrics here. diff --git a/zuul-core/src/main/java/com/netflix/zuul/stats/ErrorStatsData.java b/zuul-core/src/main/java/com/netflix/zuul/stats/ErrorStatsData.java index 25ece7a372..c736e446b5 100755 --- a/zuul-core/src/main/java/com/netflix/zuul/stats/ErrorStatsData.java +++ b/zuul-core/src/main/java/com/netflix/zuul/stats/ErrorStatsData.java @@ -41,7 +41,7 @@ public class ErrorStatsData implements NamedCount { * @param cause */ public ErrorStatsData(String route, String cause) { - if(null == route || "".equals(route)){ + if (null == route || "".equals(route)) { route = "UNKNOWN"; } id = route + "_" + cause; @@ -65,7 +65,6 @@ public boolean equals(Object o) { ErrorStatsData that = (ErrorStatsData) o; return !(errorCause != null ? !errorCause.equals(that.errorCause) : that.errorCause != null); - } @Override diff --git a/zuul-core/src/main/java/com/netflix/zuul/stats/ErrorStatsManager.java b/zuul-core/src/main/java/com/netflix/zuul/stats/ErrorStatsManager.java index 1c72d28cb4..cefa6aa829 100755 --- a/zuul-core/src/main/java/com/netflix/zuul/stats/ErrorStatsManager.java +++ b/zuul-core/src/main/java/com/netflix/zuul/stats/ErrorStatsManager.java @@ -27,8 +27,9 @@ * Time: 4:16 PM */ public class ErrorStatsManager { - ConcurrentHashMap> routeMap = new ConcurrentHashMap>(); - final static ErrorStatsManager INSTANCE = new ErrorStatsManager(); + ConcurrentHashMap> routeMap = + new ConcurrentHashMap>(); + static final ErrorStatsManager INSTANCE = new ErrorStatsManager(); /** * @@ -38,7 +39,6 @@ public static ErrorStatsManager getManager() { return INSTANCE; } - /** * * @param route @@ -81,12 +81,5 @@ public void putStats(String route, String cause) { sd.update(); } - - - public static class UnitTest { - - } - - + public static class UnitTest {} } - diff --git a/zuul-core/src/main/java/com/netflix/zuul/stats/NamedCountingMonitor.java b/zuul-core/src/main/java/com/netflix/zuul/stats/NamedCountingMonitor.java index fa18374b22..cbc88ae83f 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/stats/NamedCountingMonitor.java +++ b/zuul-core/src/main/java/com/netflix/zuul/stats/NamedCountingMonitor.java @@ -30,7 +30,6 @@ */ public class NamedCountingMonitor implements NamedCount { - private final String name; private final AtomicLong count = new AtomicLong(); @@ -69,5 +68,4 @@ public String getName() { public long getCount() { return this.count.get(); } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/stats/RequestMetricsPublisher.java b/zuul-core/src/main/java/com/netflix/zuul/stats/RequestMetricsPublisher.java index 4a866bad07..bef8897503 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/stats/RequestMetricsPublisher.java +++ b/zuul-core/src/main/java/com/netflix/zuul/stats/RequestMetricsPublisher.java @@ -22,7 +22,6 @@ * Date: 3/9/15 * Time: 5:56 PM */ -public interface RequestMetricsPublisher -{ +public interface RequestMetricsPublisher { void collectAndPublish(SessionContext context); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/stats/RouteStatusCodeMonitor.java b/zuul-core/src/main/java/com/netflix/zuul/stats/RouteStatusCodeMonitor.java index ff89111e26..9cd2e60ab0 100755 --- a/zuul-core/src/main/java/com/netflix/zuul/stats/RouteStatusCodeMonitor.java +++ b/zuul-core/src/main/java/com/netflix/zuul/stats/RouteStatusCodeMonitor.java @@ -20,9 +20,10 @@ import com.netflix.spectator.api.Spectator; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.zuul.stats.monitoring.NamedCount; + +import javax.annotation.Nullable; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; -import javax.annotation.Nullable; /** * counter for per route/status code counting @@ -32,8 +33,10 @@ */ public class RouteStatusCodeMonitor implements NamedCount { private final String routeCode; + @VisibleForTesting final String route; + private final int statusCode; private final AtomicLong count = new AtomicLong(); diff --git a/zuul-core/src/main/java/com/netflix/zuul/stats/StatsManager.java b/zuul-core/src/main/java/com/netflix/zuul/stats/StatsManager.java index ae053a42e1..228fb733c4 100755 --- a/zuul-core/src/main/java/com/netflix/zuul/stats/StatsManager.java +++ b/zuul-core/src/main/java/com/netflix/zuul/stats/StatsManager.java @@ -36,16 +36,14 @@ */ public class StatsManager { - private static final Logger LOG = LoggerFactory.getLogger(StatsManager.class); - protected static final Pattern HEX_PATTERN = Pattern.compile("[0-9a-fA-F]+"); // should match *.amazonaws.com, *.nflxvideo.net, or raw IP addresses. private static final Pattern HOST_PATTERN = - Pattern.compile("(?:(.+)\\.amazonaws\\.com)|((?:\\d{1,3}\\.?){4})|(ip-\\d+-\\d+-\\d+-\\d+)|" + - "(?:(.+)\\.nflxvideo\\.net)|(?:(.+)\\.llnwd\\.net)|(?:(.+)\\.nflximg\\.com)"); + Pattern.compile("(?:(.+)\\.amazonaws\\.com)|((?:\\d{1,3}\\.?){4})|(ip-\\d+-\\d+-\\d+-\\d+)|" + + "(?:(.+)\\.nflxvideo\\.net)|(?:(.+)\\.llnwd\\.net)|(?:(.+)\\.nflximg\\.com)"); @VisibleForTesting static final String HOST_HEADER = "host"; @@ -71,7 +69,6 @@ public class StatsManager { private final ConcurrentMap ipVersionCounterMap = new ConcurrentHashMap(); - protected static StatsManager INSTANCE = new StatsManager(); public static StatsManager getManager() { @@ -134,7 +131,6 @@ private static final String protocolKey(String proto) { return String.format("protocol_%s", proto); } - /** * Collects counts statistics about the request: client ip address from the x-forwarded-for header; * ipv4 or ipv6 and host name from the host header; @@ -256,7 +252,7 @@ public void collectRouteStats(String route, int statusCode) { } RouteStatusCodeMonitor sd = statsMap.get(statusCode); if (sd == null) { - //don't register only 404 status codes (these are garbage endpoints) + // don't register only 404 status codes (these are garbage endpoints) if (statusCode == 404) { if (statsMap.size() == 0) { return; diff --git a/zuul-core/src/main/java/com/netflix/zuul/stats/monitoring/MonitorRegistry.java b/zuul-core/src/main/java/com/netflix/zuul/stats/monitoring/MonitorRegistry.java index 5b2681c829..3c056d0487 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/stats/monitoring/MonitorRegistry.java +++ b/zuul-core/src/main/java/com/netflix/zuul/stats/monitoring/MonitorRegistry.java @@ -24,7 +24,7 @@ */ public class MonitorRegistry { - private static final MonitorRegistry instance = new MonitorRegistry(); + private static final MonitorRegistry instance = new MonitorRegistry(); private Monitor publisher; /** @@ -35,8 +35,6 @@ public void setPublisher(Monitor publisher) { this.publisher = publisher; } - - public static MonitorRegistry getInstance() { return instance; } diff --git a/zuul-core/src/main/java/com/netflix/zuul/stats/monitoring/NamedCount.java b/zuul-core/src/main/java/com/netflix/zuul/stats/monitoring/NamedCount.java index c389971a35..fb5dea88f7 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/stats/monitoring/NamedCount.java +++ b/zuul-core/src/main/java/com/netflix/zuul/stats/monitoring/NamedCount.java @@ -23,5 +23,6 @@ */ public interface NamedCount { String getName(); + long getCount(); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/stats/status/StatusCategoryUtils.java b/zuul-core/src/main/java/com/netflix/zuul/stats/status/StatusCategoryUtils.java index 827b3c4530..1f7b4f2fba 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/stats/status/StatusCategoryUtils.java +++ b/zuul-core/src/main/java/com/netflix/zuul/stats/status/StatusCategoryUtils.java @@ -20,10 +20,11 @@ import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.ZuulMessage; import com.netflix.zuul.message.http.HttpResponseMessage; -import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; + /** * User: michaels@netflix.com * Date: 6/9/15 diff --git a/zuul-core/src/main/java/com/netflix/zuul/stats/status/ZuulStatusCategory.java b/zuul-core/src/main/java/com/netflix/zuul/stats/status/ZuulStatusCategory.java index 6340c531dc..911b09e437 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/stats/status/ZuulStatusCategory.java +++ b/zuul-core/src/main/java/com/netflix/zuul/stats/status/ZuulStatusCategory.java @@ -40,26 +40,29 @@ */ public enum ZuulStatusCategory implements StatusCategory { SUCCESS(ZuulStatusCategoryGroup.SUCCESS, 1), - SUCCESS_NOT_FOUND(ZuulStatusCategoryGroup.SUCCESS, 3), // This is set on for all 404 responses + SUCCESS_NOT_FOUND(ZuulStatusCategoryGroup.SUCCESS, 3), // This is set on for all 404 responses - SUCCESS_LOCAL_NOTSET(ZuulStatusCategoryGroup.SUCCESS, 4), // This is set on the SessionContext as the default value. + SUCCESS_LOCAL_NOTSET(ZuulStatusCategoryGroup.SUCCESS, 4), // This is set on the SessionContext as the default value. SUCCESS_LOCAL_NO_ROUTE(ZuulStatusCategoryGroup.SUCCESS, 5), FAILURE_LOCAL(ZuulStatusCategoryGroup.FAILURE, 1), - FAILURE_LOCAL_THROTTLED_ORIGIN_SERVER_MAXCONN(ZuulStatusCategoryGroup.FAILURE, 7), //NIWS client throttling based on max connections per origin server. - FAILURE_LOCAL_THROTTLED_ORIGIN_CONCURRENCY(ZuulStatusCategoryGroup.FAILURE, 8), // when zuul throttles for a vip because concurrency is too high. + FAILURE_LOCAL_THROTTLED_ORIGIN_SERVER_MAXCONN( + ZuulStatusCategoryGroup.FAILURE, 7), // NIWS client throttling based on max connections per origin server. + FAILURE_LOCAL_THROTTLED_ORIGIN_CONCURRENCY( + ZuulStatusCategoryGroup.FAILURE, 8), // when zuul throttles for a vip because concurrency is too high. FAILURE_LOCAL_IDLE_TIMEOUT(ZuulStatusCategoryGroup.FAILURE, 9), FAILURE_CLIENT_BAD_REQUEST(ZuulStatusCategoryGroup.FAILURE, 12), - FAILURE_CLIENT_CANCELLED(ZuulStatusCategoryGroup.FAILURE, 13), // client abandoned/closed the connection before origin responded. + FAILURE_CLIENT_CANCELLED( + ZuulStatusCategoryGroup.FAILURE, 13), // client abandoned/closed the connection before origin responded. FAILURE_CLIENT_PIPELINE_REJECT(ZuulStatusCategoryGroup.FAILURE, 17), FAILURE_CLIENT_TIMEOUT(ZuulStatusCategoryGroup.FAILURE, 18), FAILURE_ORIGIN(ZuulStatusCategoryGroup.FAILURE, 2), FAILURE_ORIGIN_READ_TIMEOUT(ZuulStatusCategoryGroup.FAILURE, 3), FAILURE_ORIGIN_CONNECTIVITY(ZuulStatusCategoryGroup.FAILURE, 4), - FAILURE_ORIGIN_THROTTLED(ZuulStatusCategoryGroup.FAILURE, 6), // Throttled by origin by returning 503 - FAILURE_ORIGIN_NO_SERVERS(ZuulStatusCategoryGroup.FAILURE, 14), // No UP origin servers available in Discovery. + FAILURE_ORIGIN_THROTTLED(ZuulStatusCategoryGroup.FAILURE, 6), // Throttled by origin by returning 503 + FAILURE_ORIGIN_NO_SERVERS(ZuulStatusCategoryGroup.FAILURE, 14), // No UP origin servers available in Discovery. FAILURE_ORIGIN_RESET_CONNECTION(ZuulStatusCategoryGroup.FAILURE, 15); private final StatusCategoryGroup group; @@ -74,6 +77,7 @@ public enum ZuulStatusCategory implements StatusCategory { public String getId() { return id; } + @Override public StatusCategoryGroup getGroup() { return group; diff --git a/zuul-core/src/main/java/com/netflix/zuul/util/Gzipper.java b/zuul-core/src/main/java/com/netflix/zuul/util/Gzipper.java index 59ae68ec60..6268001b00 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/util/Gzipper.java +++ b/zuul-core/src/main/java/com/netflix/zuul/util/Gzipper.java @@ -32,8 +32,7 @@ * Date: 5/10/16 * Time: 12:31 PM */ -public class Gzipper -{ +public class Gzipper { private final ByteArrayOutputStream baos; private final GZIPOutputStream gzos; @@ -41,8 +40,7 @@ public Gzipper() throws RuntimeException { try { baos = new ByteArrayOutputStream(256); gzos = new GZIPOutputStream(baos, true); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException("Error finalizing the GzipOutputstream", e); } } @@ -67,11 +65,9 @@ public void write(final HttpContent chunk) { try { write(chunk.content()); gzos.flush(); - } - catch(IOException ioEx) { + } catch (IOException ioEx) { throw new ZuulException(ioEx, "Error Gzipping response content chunk", true); - } - finally { + } finally { chunk.release(); } } @@ -81,8 +77,7 @@ public void finish() throws RuntimeException { gzos.finish(); gzos.flush(); gzos.close(); - } - catch (IOException ioEx) { + } catch (IOException ioEx) { throw new ZuulException(ioEx, "Error finalizing the GzipOutputStream", true); } } @@ -92,5 +87,4 @@ public ByteBuf getByteBuf() { baos.reset(); return copy; } - } diff --git a/zuul-core/src/main/java/com/netflix/zuul/util/HttpUtils.java b/zuul-core/src/main/java/com/netflix/zuul/util/HttpUtils.java index c6ebc14b43..c153088a3a 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/util/HttpUtils.java +++ b/zuul-core/src/main/java/com/netflix/zuul/util/HttpUtils.java @@ -25,17 +25,17 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http2.Http2StreamChannel; -import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; + /** * User: Mike Smith * Date: 4/28/15 * Time: 11:05 PM */ -public class HttpUtils -{ +public class HttpUtils { private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class); private static final char[] MALICIOUS_HEADER_CHARS = {'\r', '\n'}; @@ -48,8 +48,7 @@ public class HttpUtils * @param request HttpRequestMessage * @return String IP address */ - public static String getClientIP(HttpRequestInfo request) - { + public static String getClientIP(HttpRequestInfo request) { final String xForwardedFor = request.getHeaders().getFirst(HttpHeaderNames.X_FORWARDED_FOR); String clientIP; if (xForwardedFor == null) { @@ -81,10 +80,10 @@ public static String extractClientIpFromXForwardedFor(String xForwardedFor) { @VisibleForTesting static boolean isCompressed(String contentEncoding) { - return contentEncoding.contains(HttpHeaderValues.GZIP.toString()) || - contentEncoding.contains(HttpHeaderValues.DEFLATE.toString()) || - contentEncoding.contains(HttpHeaderValues.BR.toString()) || - contentEncoding.contains(HttpHeaderValues.COMPRESS.toString()); + return contentEncoding.contains(HttpHeaderValues.GZIP.toString()) + || contentEncoding.contains(HttpHeaderValues.DEFLATE.toString()) + || contentEncoding.contains(HttpHeaderValues.BR.toString()) + || contentEncoding.contains(HttpHeaderValues.COMPRESS.toString()); } public static boolean isCompressed(Headers headers) { @@ -116,23 +115,19 @@ public static String stripMaliciousHeaderChars(@Nullable String input) { return input; } - - public static boolean hasNonZeroContentLengthHeader(ZuulMessage msg) - { + public static boolean hasNonZeroContentLengthHeader(ZuulMessage msg) { final Integer contentLengthVal = getContentLengthIfPresent(msg); return (contentLengthVal != null) && (contentLengthVal > 0); } - public static Integer getContentLengthIfPresent(ZuulMessage msg) - { - final String contentLengthValue = msg.getHeaders().getFirst(com.netflix.zuul.message.http.HttpHeaderNames.CONTENT_LENGTH); + public static Integer getContentLengthIfPresent(ZuulMessage msg) { + final String contentLengthValue = + msg.getHeaders().getFirst(com.netflix.zuul.message.http.HttpHeaderNames.CONTENT_LENGTH); if (!Strings.isNullOrEmpty(contentLengthValue)) { try { return Integer.valueOf(contentLengthValue); - } - catch (NumberFormatException e) { - LOG.info("Invalid Content-Length header value on request. " + - "value = {}", contentLengthValue, e); + } catch (NumberFormatException e) { + LOG.info("Invalid Content-Length header value on request. " + "value = {}", contentLengthValue, e); } } return null; @@ -149,8 +144,7 @@ public static Integer getBodySizeIfKnown(ZuulMessage msg) { return null; } - public static boolean hasChunkedTransferEncodingHeader(ZuulMessage msg) - { + public static boolean hasChunkedTransferEncodingHeader(ZuulMessage msg) { boolean isChunked = false; String teValue = msg.getHeaders().getFirst(com.netflix.zuul.message.http.HttpHeaderNames.TRANSFER_ENCODING); if (!Strings.isNullOrEmpty(teValue)) { @@ -163,13 +157,11 @@ public static boolean hasChunkedTransferEncodingHeader(ZuulMessage msg) * If http/1 then will always want to just use ChannelHandlerContext.channel(), but for http/2 * will want the parent channel (as the child channel is different for each h2 stream). */ - public static Channel getMainChannel(ChannelHandlerContext ctx) - { + public static Channel getMainChannel(ChannelHandlerContext ctx) { return getMainChannel(ctx.channel()); } - public static Channel getMainChannel(Channel channel) - { + public static Channel getMainChannel(Channel channel) { if (channel instanceof Http2StreamChannel) { return channel.parent(); } diff --git a/zuul-core/src/main/java/com/netflix/zuul/util/JsonUtility.java b/zuul-core/src/main/java/com/netflix/zuul/util/JsonUtility.java index 287268364f..6b0b4f6f7c 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/util/JsonUtility.java +++ b/zuul-core/src/main/java/com/netflix/zuul/util/JsonUtility.java @@ -18,7 +18,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; /** * Utility for generating JSON from Maps/Lists @@ -79,7 +81,6 @@ public static String jsonFromMap(Map jsonData) { logger.error("Could not create JSON from Map. ", e); return "{}"; } - } /* @@ -140,12 +141,10 @@ public JsonDocument addValue(String key, String value) { public String toString() { return json.toString(); } - } public static interface JsonCapableObject { public Map jsonMap(); - } } diff --git a/zuul-core/src/main/java/com/netflix/zuul/util/ProxyUtils.java b/zuul-core/src/main/java/com/netflix/zuul/util/ProxyUtils.java index d18c95a1b5..4d43156545 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/util/ProxyUtils.java +++ b/zuul-core/src/main/java/com/netflix/zuul/util/ProxyUtils.java @@ -30,11 +30,12 @@ * Date: 6/8/15 * Time: 11:50 AM */ -public class ProxyUtils -{ - private static final CachedDynamicBooleanProperty OVERWRITE_XF_HEADERS = new CachedDynamicBooleanProperty("zuul.headers.xforwarded.overwrite", false); +public class ProxyUtils { + private static final CachedDynamicBooleanProperty OVERWRITE_XF_HEADERS = + new CachedDynamicBooleanProperty("zuul.headers.xforwarded.overwrite", false); private static final Set RESP_HEADERS_TO_STRIP = new HashSet<>(); + static { RESP_HEADERS_TO_STRIP.add(HttpHeaderNames.CONNECTION); RESP_HEADERS_TO_STRIP.add(HttpHeaderNames.TRANSFER_ENCODING); @@ -42,25 +43,26 @@ public class ProxyUtils } private static final Set REQ_HEADERS_TO_STRIP = new HashSet<>(); + static { - REQ_HEADERS_TO_STRIP.add(HttpHeaderNames.CONTENT_LENGTH); // Because the httpclient library sets this itself, and doesn't like it if set by us. + REQ_HEADERS_TO_STRIP.add( + HttpHeaderNames + .CONTENT_LENGTH); // Because the httpclient library sets this itself, and doesn't like it if set + // by us. REQ_HEADERS_TO_STRIP.add(HttpHeaderNames.CONNECTION); REQ_HEADERS_TO_STRIP.add(HttpHeaderNames.TRANSFER_ENCODING); REQ_HEADERS_TO_STRIP.add(HttpHeaderNames.KEEP_ALIVE); } - public static boolean isValidRequestHeader(HeaderName headerName) - { - return ! REQ_HEADERS_TO_STRIP.contains(headerName); + public static boolean isValidRequestHeader(HeaderName headerName) { + return !REQ_HEADERS_TO_STRIP.contains(headerName); } - public static boolean isValidResponseHeader(HeaderName headerName) - { - return ! RESP_HEADERS_TO_STRIP.contains(headerName); + public static boolean isValidResponseHeader(HeaderName headerName) { + return !RESP_HEADERS_TO_STRIP.contains(headerName); } - public static void addXForwardedHeaders(HttpRequestMessage request) - { + public static void addXForwardedHeaders(HttpRequestMessage request) { // Add standard Proxy request headers. Headers headers = request.getHeaders(); addXForwardedHeader(headers, HttpHeaderNames.X_FORWARDED_HOST, request.getOriginalHost()); @@ -69,12 +71,10 @@ public static void addXForwardedHeaders(HttpRequestMessage request) addXForwardedHeader(headers, HttpHeaderNames.X_FORWARDED_FOR, request.getClientIp()); } - public static void addXForwardedHeader(Headers headers, HeaderName name, String latestValue) - { + public static void addXForwardedHeader(Headers headers, HeaderName name, String latestValue) { if (OVERWRITE_XF_HEADERS.get()) { headers.set(name, latestValue); - } - else { + } else { // If this proxy header already exists (possibly due to an upstream ELB or reverse proxy // setting it) then keep that value. String existingValue = headers.getFirst(name); diff --git a/zuul-core/src/main/java/com/netflix/zuul/util/VipUtils.java b/zuul-core/src/main/java/com/netflix/zuul/util/VipUtils.java index 1caab2b38c..f896994f39 100644 --- a/zuul-core/src/main/java/com/netflix/zuul/util/VipUtils.java +++ b/zuul-core/src/main/java/com/netflix/zuul/util/VipUtils.java @@ -16,8 +16,7 @@ package com.netflix.zuul.util; -public final class VipUtils -{ +public final class VipUtils { public static String getVIPPrefix(String vipAddress) { for (int i = 0; i < vipAddress.length(); i++) { char c = vipAddress.charAt(i); diff --git a/zuul-core/src/test/java/com/netflix/netty/common/CloseOnIdleStateHandlerTest.java b/zuul-core/src/test/java/com/netflix/netty/common/CloseOnIdleStateHandlerTest.java index 1c1f769c08..6c152d4d8e 100644 --- a/zuul-core/src/test/java/com/netflix/netty/common/CloseOnIdleStateHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/netty/common/CloseOnIdleStateHandlerTest.java @@ -16,9 +16,6 @@ package com.netflix.netty.common; -import static io.netty.handler.timeout.IdleStateEvent.ALL_IDLE_STATE_EVENT; -import static org.junit.jupiter.api.Assertions.assertEquals; - import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Id; @@ -28,6 +25,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static io.netty.handler.timeout.IdleStateEvent.ALL_IDLE_STATE_EVENT; +import static org.junit.jupiter.api.Assertions.assertEquals; + class CloseOnIdleStateHandlerTest { private Registry registry = new DefaultRegistry(); diff --git a/zuul-core/src/test/java/com/netflix/netty/common/HttpServerLifecycleChannelHandlerTest.java b/zuul-core/src/test/java/com/netflix/netty/common/HttpServerLifecycleChannelHandlerTest.java index d157360707..df576b02d4 100644 --- a/zuul-core/src/test/java/com/netflix/netty/common/HttpServerLifecycleChannelHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/netty/common/HttpServerLifecycleChannelHandlerTest.java @@ -16,7 +16,6 @@ package com.netflix.netty.common; -import static com.netflix.netty.common.HttpLifecycleChannelHandler.ATTR_HTTP_PIPELINE_REJECT; import com.google.common.truth.Truth; import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent; import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason; @@ -35,6 +34,8 @@ import io.netty.util.ReferenceCountUtil; import org.junit.jupiter.api.Test; +import static com.netflix.netty.common.HttpLifecycleChannelHandler.ATTR_HTTP_PIPELINE_REJECT; + class HttpServerLifecycleChannelHandlerTest { final class AssertReasonHandler extends ChannelInboundHandlerAdapter { @@ -90,8 +91,8 @@ void pipelineRejectReleasesIfNeeded() { ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.buffer(); try { Truth.assertThat(buffer.refCnt()).isEqualTo(1); - FullHttpRequest httpRequest = new DefaultFullHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.GET, "/whatever", buffer); + FullHttpRequest httpRequest = + new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/whatever", buffer); channel.attr(HttpLifecycleChannelHandler.ATTR_STATE).set(State.STARTED); channel.writeInbound(httpRequest); diff --git a/zuul-core/src/test/java/com/netflix/netty/common/SourceAddressChannelHandlerTest.java b/zuul-core/src/test/java/com/netflix/netty/common/SourceAddressChannelHandlerTest.java index 69119a6775..53db8950d5 100644 --- a/zuul-core/src/test/java/com/netflix/netty/common/SourceAddressChannelHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/netty/common/SourceAddressChannelHandlerTest.java @@ -16,7 +16,9 @@ package com.netflix.netty.common; -import static org.junit.jupiter.api.Assertions.*; +import org.junit.AssumptionViolatedException; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; import java.net.Inet4Address; import java.net.Inet6Address; @@ -27,9 +29,10 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.junit.AssumptionViolatedException; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit tests for {@link SourceAddressChannelHandler}. @@ -39,7 +42,7 @@ class SourceAddressChannelHandlerTest { @Test void ipv6AddressScopeIdRemoved() throws Exception { Inet6Address address = - Inet6Address.getByAddress("localhost", new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 2); + Inet6Address.getByAddress("localhost", new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 2); assertEquals(2, address.getScopeId()); String addressString = SourceAddressChannelHandler.getHostAddress(new InetSocketAddress(address, 8080)); @@ -49,7 +52,7 @@ void ipv6AddressScopeIdRemoved() throws Exception { @Test void ipv4AddressString() throws Exception { - InetAddress address = Inet4Address.getByAddress("localhost", new byte[]{127, 0, 0, 1}); + InetAddress address = Inet4Address.getByAddress("localhost", new byte[] {127, 0, 0, 1}); String addressString = SourceAddressChannelHandler.getHostAddress(new InetSocketAddress(address, 8080)); @@ -70,7 +73,7 @@ void mapsIpv4AddressFromIpv6Address() throws Exception { // Can't think of a reason why this would ever come up, but testing it just in case. // ::ffff:127.0.0.1 Inet6Address address = Inet6Address.getByAddress( - "localhost", new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xFF, (byte) 0xFF, 127, 0, 0, 1}, -1); + "localhost", new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xFF, (byte) 0xFF, 127, 0, 0, 1}, -1); assertEquals(0, address.getScopeId()); String addressString = SourceAddressChannelHandler.getHostAddress(new InetSocketAddress(address, 8080)); @@ -83,13 +86,12 @@ void ipv6AddressScopeNameRemoved() throws Exception { List nics = Collections.list(NetworkInterface.getNetworkInterfaces()); Assumptions.assumeTrue(!nics.isEmpty(), "No network interfaces"); - List failures = new ArrayList<>(); for (NetworkInterface nic : nics) { Inet6Address address; try { address = Inet6Address.getByAddress( - "localhost", new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, nic); + "localhost", new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, nic); } catch (UnknownHostException e) { // skip, the nic doesn't match failures.add(e); diff --git a/zuul-core/src/test/java/com/netflix/netty/common/metrics/InstrumentedResourceLeakDetectorTest.java b/zuul-core/src/test/java/com/netflix/netty/common/metrics/InstrumentedResourceLeakDetectorTest.java index 68b6e02458..67c35a9f83 100644 --- a/zuul-core/src/test/java/com/netflix/netty/common/metrics/InstrumentedResourceLeakDetectorTest.java +++ b/zuul-core/src/test/java/com/netflix/netty/common/metrics/InstrumentedResourceLeakDetectorTest.java @@ -16,14 +16,14 @@ package com.netflix.netty.common.metrics; -import static org.junit.jupiter.api.Assertions.assertEquals; - import io.netty.buffer.ByteBuf; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; +import static org.junit.jupiter.api.Assertions.assertEquals; + @ExtendWith(MockitoExtension.class) class InstrumentedResourceLeakDetectorTest { diff --git a/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/ElbProxyProtocolChannelHandlerTest.java b/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/ElbProxyProtocolChannelHandlerTest.java index d54a5ad7ae..f7b2960a3d 100644 --- a/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/ElbProxyProtocolChannelHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/ElbProxyProtocolChannelHandlerTest.java @@ -16,10 +16,6 @@ package com.netflix.netty.common.proxyprotocol; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.net.InetAddresses; import com.netflix.netty.common.SourceAddressChannelHandler; import com.netflix.spectator.api.Counter; @@ -33,19 +29,25 @@ import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.haproxy.HAProxyMessage; import io.netty.handler.codec.haproxy.HAProxyProtocolVersion; -import java.net.InetSocketAddress; -import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + @ExtendWith(MockitoExtension.class) class ElbProxyProtocolChannelHandlerTest { private Registry registry; - + @BeforeEach void setup() { registry = new DefaultRegistry(); @@ -70,8 +72,10 @@ void noProxy() { assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); assertNull(channel.pipeline().context("HAProxyMessageChannelHandler")); - assertNull(channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); - assertNull(channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); + assertNull( + channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); + assertNull( + channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); @@ -108,7 +112,7 @@ void passThrough_ProxyProtocolEnabled_nonProxyBytes() { channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); - //Note that the bytes aren't prefixed by PROXY, as required by the spec + // Note that the bytes aren't prefixed by PROXY, as required by the spec ByteBuf buf = Unpooled.wrappedBuffer( "TCP4 192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf); @@ -119,8 +123,10 @@ void passThrough_ProxyProtocolEnabled_nonProxyBytes() { assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); assertNull(channel.pipeline().context("HAProxyMessageChannelHandler")); - assertNull(channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); - assertNull(channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); + assertNull( + channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); + assertNull( + channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); @@ -136,7 +142,7 @@ void incrementCounterWhenPPEnabledButNonHAPMMessage() { channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(port); channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); - //Note that the bytes aren't prefixed by PROXY, as required by the spec + // Note that the bytes aren't prefixed by PROXY, as required by the spec ByteBuf buf = Unpooled.wrappedBuffer( "TCP4 192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf); @@ -159,11 +165,10 @@ void detectsSplitPpv1Message() { channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); - ByteBuf buf1 = Unpooled.wrappedBuffer( - "PROXY TCP4".getBytes(StandardCharsets.US_ASCII)); + ByteBuf buf1 = Unpooled.wrappedBuffer("PROXY TCP4".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf1); - ByteBuf buf2 = Unpooled.wrappedBuffer( - "192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); + ByteBuf buf2 = + Unpooled.wrappedBuffer("192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf2); Object msg = channel.readInbound(); @@ -195,15 +200,24 @@ void negotiateProxy_ppv1_ipv4() { // The handler should remove itself. assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); assertNull(channel.pipeline().context(HAProxyMessageChannelHandler.class)); - assertEquals(HAProxyProtocolVersion.V1, channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); + assertEquals( + HAProxyProtocolVersion.V1, + channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); // TODO(carl-mastrangelo): this check is in place, but it should be removed. The message is not properly GC'd // in later versions of netty. - assertNotNull(channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); - assertEquals("124.123.111.111", channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); - assertEquals(new InetSocketAddress(InetAddresses.forString("124.123.111.111"), 443), + assertNotNull( + channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); + assertEquals( + "124.123.111.111", + channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); + assertEquals( + new InetSocketAddress(InetAddresses.forString("124.123.111.111"), 443), channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get()); - assertEquals("192.168.0.1", channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); - assertEquals(new InetSocketAddress(InetAddresses.forString("192.168.0.1"), 10008), + assertEquals( + "192.168.0.1", + channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); + assertEquals( + new InetSocketAddress(InetAddresses.forString("192.168.0.1"), 10008), channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR).get()); } @@ -216,8 +230,7 @@ void negotiateProxy_ppv1_ipv6() { channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); - ByteBuf buf = Unpooled.wrappedBuffer( - "PROXY TCP6 ::1 ::2 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); + ByteBuf buf = Unpooled.wrappedBuffer("PROXY TCP6 ::1 ::2 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf); Object dropped = channel.readInbound(); @@ -226,15 +239,21 @@ void negotiateProxy_ppv1_ipv6() { // The handler should remove itself. assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); assertEquals( - HAProxyProtocolVersion.V1, channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); + HAProxyProtocolVersion.V1, + channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); // TODO(carl-mastrangelo): this check is in place, but it should be removed. The message is not properly GC'd // in later versions of netty. - assertNotNull(channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); - assertEquals("::2", channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); + assertNotNull( + channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); + assertEquals( + "::2", + channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); assertEquals( new InetSocketAddress(InetAddresses.forString("::2"), 443), channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get()); - assertEquals("::1", channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); + assertEquals( + "::1", + channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); assertEquals( new InetSocketAddress(InetAddresses.forString("::1"), 10008), channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR).get()); @@ -249,10 +268,36 @@ void negotiateProxy_ppv2_ipv4() { channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); - ByteBuf buf = Unpooled.wrappedBuffer( - new byte[]{0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A, 0x21, 0x11, 0x00, - 0x0C, (byte) 0xC0, (byte) 0xA8, 0x00, 0x01, 0x7C, 0x7B, 0x6F, 0x6F, 0x27, 0x18, 0x01, - (byte) 0xbb}); + ByteBuf buf = Unpooled.wrappedBuffer(new byte[] { + 0x0D, + 0x0A, + 0x0D, + 0x0A, + 0x00, + 0x0D, + 0x0A, + 0x51, + 0x55, + 0x49, + 0x54, + 0x0A, + 0x21, + 0x11, + 0x00, + 0x0C, + (byte) 0xC0, + (byte) 0xA8, + 0x00, + 0x01, + 0x7C, + 0x7B, + 0x6F, + 0x6F, + 0x27, + 0x18, + 0x01, + (byte) 0xbb + }); channel.writeInbound(buf); Object dropped = channel.readInbound(); @@ -261,15 +306,21 @@ void negotiateProxy_ppv2_ipv4() { // The handler should remove itself. assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); assertEquals( - HAProxyProtocolVersion.V2, channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); + HAProxyProtocolVersion.V2, + channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); // TODO(carl-mastrangelo): this check is in place, but it should be removed. The message is not properly GC'd // in later versions of netty. - assertNotNull(channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); - assertEquals("124.123.111.111", channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); + assertNotNull( + channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); + assertEquals( + "124.123.111.111", + channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); assertEquals( new InetSocketAddress(InetAddresses.forString("124.123.111.111"), 443), channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get()); - assertEquals("192.168.0.1", channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); + assertEquals( + "192.168.0.1", + channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); assertEquals( new InetSocketAddress(InetAddresses.forString("192.168.0.1"), 10008), channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR).get()); diff --git a/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/HAProxyMessageChannelHandlerTest.java b/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/HAProxyMessageChannelHandlerTest.java index a6d19da260..928b37ad3a 100644 --- a/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/HAProxyMessageChannelHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/HAProxyMessageChannelHandlerTest.java @@ -16,9 +16,6 @@ package com.netflix.netty.common.proxyprotocol; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - import com.netflix.netty.common.SourceAddressChannelHandler; import com.netflix.zuul.Attrs; import com.netflix.zuul.netty.server.Server; @@ -26,9 +23,13 @@ import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.haproxy.HAProxyMessageDecoder; +import org.junit.jupiter.api.Test; + import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; -import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; class HAProxyMessageChannelHandlerTest { @@ -49,12 +50,13 @@ void setClientDestPortForHAPM() { Object result = channel.readInbound(); assertNull(result); - InetSocketAddress destAddress = channel - .attr(SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS).get(); - - InetSocketAddress srcAddress = (InetSocketAddress) channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR) + InetSocketAddress destAddress = channel.attr( + SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS) .get(); + InetSocketAddress srcAddress = (InetSocketAddress) + channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR).get(); + assertEquals("124.123.111.111", destAddress.getHostString()); assertEquals(443, destAddress.getPort()); diff --git a/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/StripUntrustedProxyHeadersHandlerTest.java b/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/StripUntrustedProxyHeadersHandlerTest.java index cf3da151ca..2664f3663c 100644 --- a/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/StripUntrustedProxyHeadersHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/StripUntrustedProxyHeadersHandlerTest.java @@ -16,13 +16,6 @@ package com.netflix.netty.common.proxyprotocol; -import static com.netflix.zuul.netty.server.ssl.SslHandshakeInfoHandler.ATTR_SSL_INFO; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableList; import com.netflix.netty.common.proxyprotocol.StripUntrustedProxyHeadersHandler.AllowWhen; import com.netflix.netty.common.ssl.SslHandshakeInfo; @@ -43,6 +36,14 @@ import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; +import static com.netflix.zuul.netty.server.ssl.SslHandshakeInfoHandler.ATTR_SSL_INFO; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + /** * Strip Untrusted Proxy Headers Handler Test * @@ -55,15 +56,18 @@ class StripUntrustedProxyHeadersHandlerTest { @Mock private ChannelHandlerContext channelHandlerContext; + @Mock private HttpRequest msg; + private HttpHeaders headers; + @Mock private Channel channel; + @Mock private SslHandshakeInfo sslHandshakeInfo; - @BeforeEach void before() { when(channelHandlerContext.channel()).thenReturn(channel); @@ -156,5 +160,4 @@ void strip_match() { private StripUntrustedProxyHeadersHandler getHandler(AllowWhen allowWhen) { return spy(new StripUntrustedProxyHeadersHandler(allowWhen)); } - } diff --git a/zuul-core/src/test/java/com/netflix/netty/common/throttle/MaxInboundConnectionsHandlerTest.java b/zuul-core/src/test/java/com/netflix/netty/common/throttle/MaxInboundConnectionsHandlerTest.java index 8a41b338b6..2f64bf5443 100644 --- a/zuul-core/src/test/java/com/netflix/netty/common/throttle/MaxInboundConnectionsHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/netty/common/throttle/MaxInboundConnectionsHandlerTest.java @@ -16,10 +16,6 @@ package com.netflix.netty.common.throttle; -import static com.netflix.netty.common.throttle.MaxInboundConnectionsHandler.ATTR_CH_THROTTLED; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Id; @@ -31,6 +27,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static com.netflix.netty.common.throttle.MaxInboundConnectionsHandler.ATTR_CH_THROTTLED; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + class MaxInboundConnectionsHandlerTest { private Registry registry = new DefaultRegistry(); @@ -56,8 +56,9 @@ void verifyPassportStateAndAttrs() { final Counter throttledCount = (Counter) registry.get(counterId); assertEquals(1, throttledCount.count()); - assertEquals(PassportState.SERVER_CH_THROTTLING, CurrentPassport.fromChannel(channel).getState()); + assertEquals( + PassportState.SERVER_CH_THROTTLING, + CurrentPassport.fromChannel(channel).getState()); assertTrue(channel.attr(ATTR_CH_THROTTLED).get()); - } } diff --git a/zuul-core/src/test/java/com/netflix/zuul/AttrsTest.java b/zuul-core/src/test/java/com/netflix/zuul/AttrsTest.java index 6607f7553a..969bfbc121 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/AttrsTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/AttrsTest.java @@ -16,12 +16,14 @@ package com.netflix.zuul; -import static org.junit.jupiter.api.Assertions.*; - import com.google.common.truth.Truth; import com.netflix.zuul.Attrs.Key; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + class AttrsTest { @Test void keysAreUnique() { diff --git a/zuul-core/src/test/java/com/netflix/zuul/DynamicFilterLoaderTest.java b/zuul-core/src/test/java/com/netflix/zuul/DynamicFilterLoaderTest.java index e8a47eda93..c0e5bd7a88 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/DynamicFilterLoaderTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/DynamicFilterLoaderTest.java @@ -15,24 +15,26 @@ */ package com.netflix.zuul; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.when; - import com.netflix.zuul.filters.BaseSyncFilter; import com.netflix.zuul.filters.FilterRegistry; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.MutableFilterRegistry; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.message.ZuulMessage; -import java.io.File; -import java.util.Collection; -import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import java.io.File; +import java.util.Collection; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; + class DynamicFilterLoaderTest { @Mock @@ -50,8 +52,7 @@ class DynamicFilterLoaderTest { private final TestZuulFilter filter = new TestZuulFilter(); @BeforeEach - void before() throws Exception - { + void before() throws Exception { MockitoAnnotations.initMocks(this); loader = new DynamicFilterLoader(registry, compiler, filterFactory); @@ -70,7 +71,7 @@ void testGetFilterFromFile() throws Exception { @Test void testPutFiltersForClasses() throws Exception { - loader.putFiltersForClasses(new String[]{TestZuulFilter.class.getName()}); + loader.putFiltersForClasses(new String[] {TestZuulFilter.class.getName()}); Collection> filters = registry.getAllFilters(); assertEquals(1, filters.size()); @@ -80,9 +81,8 @@ void testPutFiltersForClasses() throws Exception { void testPutFiltersForClassesException() throws Exception { Exception caught = null; try { - loader.putFiltersForClasses(new String[]{"asdf"}); - } - catch (ClassNotFoundException e) { + loader.putFiltersForClasses(new String[] {"asdf"}); + } catch (ClassNotFoundException e) { caught = e; } assertTrue(caught != null); @@ -113,7 +113,7 @@ void testGetFilterFromString() throws Exception { assertNotNull(filter); assertEquals(TestZuulFilter.class, filter.getClass()); -// assertTrue(loader.filterInstanceMapSize() == 1); + // assertTrue(loader.filterInstanceMapSize() == 1); } private static final class TestZuulFilter extends BaseSyncFilter { diff --git a/zuul-core/src/test/java/com/netflix/zuul/FilterFileManagerTest.java b/zuul-core/src/test/java/com/netflix/zuul/FilterFileManagerTest.java index dcccdd5289..cf514592a8 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/FilterFileManagerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/FilterFileManagerTest.java @@ -15,15 +15,6 @@ */ package com.netflix.zuul; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.io.File; -import java.io.FilenameFilter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -31,6 +22,15 @@ import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension; +import java.io.File; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + /** * Tests for {@link FilterFileManager}. */ @@ -38,10 +38,13 @@ class FilterFileManagerTest { @Mock private File nonGroovyFile; + @Mock private File groovyFile; + @Mock private File directory; + @Mock private FilterLoader filterLoader; @@ -52,12 +55,8 @@ void before() { @Test void testFileManagerInit() throws Exception { - FilterFileManager.FilterFileManagerConfig config = - new FilterFileManager.FilterFileManagerConfig( - new String[]{"test", "test1"}, - new String[]{"com.netflix.blah.SomeFilter"}, - 1, - (dir, name) -> false); + FilterFileManager.FilterFileManagerConfig config = new FilterFileManager.FilterFileManagerConfig( + new String[] {"test", "test1"}, new String[] {"com.netflix.blah.SomeFilter"}, 1, (dir, name) -> false); FilterFileManager manager = new FilterFileManager(config, filterLoader); manager = spy(manager); diff --git a/zuul-core/src/test/java/com/netflix/zuul/StaticFilterLoaderTest.java b/zuul-core/src/test/java/com/netflix/zuul/StaticFilterLoaderTest.java index e255cac997..d70caf4f4c 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/StaticFilterLoaderTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/StaticFilterLoaderTest.java @@ -22,10 +22,11 @@ import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.filters.http.HttpInboundSyncFilter; import com.netflix.zuul.message.http.HttpRequestMessage; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.List; import java.util.SortedSet; -import org.junit.jupiter.api.Test; class StaticFilterLoaderTest { @@ -33,9 +34,8 @@ class StaticFilterLoaderTest { @Test void getFiltersByType() { - StaticFilterLoader filterLoader = - new StaticFilterLoader(factory, - ImmutableSet.of(DummyFilter2.class, DummyFilter1.class, DummyFilter22.class)); + StaticFilterLoader filterLoader = new StaticFilterLoader( + factory, ImmutableSet.of(DummyFilter2.class, DummyFilter1.class, DummyFilter22.class)); SortedSet> filters = filterLoader.getFiltersByType(FilterType.INBOUND); Truth.assertThat(filters).hasSize(3); diff --git a/zuul-core/src/test/java/com/netflix/zuul/com/netflix/zuul/netty/server/push/PushConnectionTest.java b/zuul-core/src/test/java/com/netflix/zuul/com/netflix/zuul/netty/server/push/PushConnectionTest.java index adeab86458..f60b6ca62b 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/com/netflix/zuul/netty/server/push/PushConnectionTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/com/netflix/zuul/netty/server/push/PushConnectionTest.java @@ -16,13 +16,13 @@ package com.netflix.zuul.com.netflix.zuul.netty.server.push; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - import com.netflix.zuul.netty.server.push.PushConnection; import com.netflix.zuul.netty.server.push.PushProtocol; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Author: Susheel Aroskar * Date: 10/18/2018 @@ -80,6 +80,4 @@ void testMessagesInBatches() throws InterruptedException { assertFalse(conn.isRateLimited()); assertTrue(conn.isRateLimited()); } - - } diff --git a/zuul-core/src/test/java/com/netflix/zuul/context/DebugTest.java b/zuul-core/src/test/java/com/netflix/zuul/context/DebugTest.java index af716d7e4a..01bc06379e 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/context/DebugTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/context/DebugTest.java @@ -15,30 +15,30 @@ */ package com.netflix.zuul.context; -import static com.netflix.zuul.context.Debug.addRequestDebug; -import static com.netflix.zuul.context.Debug.addRoutingDebug; -import static com.netflix.zuul.context.Debug.debugRequest; -import static com.netflix.zuul.context.Debug.debugRouting; -import static com.netflix.zuul.context.Debug.getRequestDebug; -import static com.netflix.zuul.context.Debug.getRoutingDebug; -import static com.netflix.zuul.context.Debug.setDebugRequest; -import static com.netflix.zuul.context.Debug.setDebugRouting; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - import com.google.common.truth.Truth; import com.netflix.zuul.message.Headers; import com.netflix.zuul.message.http.HttpQueryParams; import com.netflix.zuul.message.http.HttpRequestMessage; -import com.netflix.zuul.message.http.HttpRequestMessageImpl; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.message.http.HttpResponseMessageImpl; import com.netflix.zuul.message.util.HttpRequestBuilder; import io.netty.handler.codec.http.HttpMethod; -import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.List; + +import static com.netflix.zuul.context.Debug.addRequestDebug; +import static com.netflix.zuul.context.Debug.addRoutingDebug; +import static com.netflix.zuul.context.Debug.debugRequest; +import static com.netflix.zuul.context.Debug.debugRouting; +import static com.netflix.zuul.context.Debug.getRequestDebug; +import static com.netflix.zuul.context.Debug.getRoutingDebug; +import static com.netflix.zuul.context.Debug.setDebugRequest; +import static com.netflix.zuul.context.Debug.setDebugRouting; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + class DebugTest { private SessionContext ctx; @@ -57,10 +57,12 @@ void setup() { params = new HttpQueryParams(); params.add("k1", "v1"); - request = new HttpRequestBuilder(ctx).withMethod(HttpMethod.POST) + request = new HttpRequestBuilder(ctx) + .withMethod(HttpMethod.POST) .withUri("/some/where") .withHeaders(headers) - .withQueryParams(params).build(); + .withQueryParams(params) + .build(); request.setBodyAsText("some text"); request.storeInboundRequest(); @@ -91,10 +93,11 @@ void testWriteInboundRequestDebug() { Debug.writeDebugRequest(ctx, request, true).toBlocking().single(); List debugLines = getRequestDebug(ctx); - Truth.assertThat(debugLines).containsExactly( - "REQUEST_INBOUND:: > LINE: POST /some/where?k1=v1 HTTP/1.1", - "REQUEST_INBOUND:: > HDR: Content-Length:13", - "REQUEST_INBOUND:: > HDR: lah:deda"); + Truth.assertThat(debugLines) + .containsExactly( + "REQUEST_INBOUND:: > LINE: POST /some/where?k1=v1 HTTP/1.1", + "REQUEST_INBOUND:: > HDR: Content-Length:13", + "REQUEST_INBOUND:: > HDR: lah:deda"); } @Test @@ -104,10 +107,11 @@ void testWriteOutboundRequestDebug() { Debug.writeDebugRequest(ctx, request, false).toBlocking().single(); List debugLines = getRequestDebug(ctx); - Truth.assertThat(debugLines).containsExactly( - "REQUEST_OUTBOUND:: > LINE: POST /some/where?k1=v1 HTTP/1.1", - "REQUEST_OUTBOUND:: > HDR: Content-Length:13", - "REQUEST_OUTBOUND:: > HDR: lah:deda"); + Truth.assertThat(debugLines) + .containsExactly( + "REQUEST_OUTBOUND:: > LINE: POST /some/where?k1=v1 HTTP/1.1", + "REQUEST_OUTBOUND:: > HDR: Content-Length:13", + "REQUEST_OUTBOUND:: > HDR: lah:deda"); } @Test @@ -117,11 +121,12 @@ void testWriteRequestDebug_WithBody() { Debug.writeDebugRequest(ctx, request, true).toBlocking().single(); List debugLines = getRequestDebug(ctx); - Truth.assertThat(debugLines).containsExactly( - "REQUEST_INBOUND:: > LINE: POST /some/where?k1=v1 HTTP/1.1", - "REQUEST_INBOUND:: > HDR: Content-Length:13", - "REQUEST_INBOUND:: > HDR: lah:deda", - "REQUEST_INBOUND:: > BODY: some text"); + Truth.assertThat(debugLines) + .containsExactly( + "REQUEST_INBOUND:: > LINE: POST /some/where?k1=v1 HTTP/1.1", + "REQUEST_INBOUND:: > HDR: Content-Length:13", + "REQUEST_INBOUND:: > HDR: lah:deda", + "REQUEST_INBOUND:: > BODY: some text"); } @Test @@ -131,10 +136,11 @@ void testWriteInboundResponseDebug() { Debug.writeDebugResponse(ctx, response, true).toBlocking().single(); List debugLines = getRequestDebug(ctx); - Truth.assertThat(debugLines).containsExactly( - "RESPONSE_INBOUND:: < STATUS: 200", - "RESPONSE_INBOUND:: < HDR: Content-Length:13", - "RESPONSE_INBOUND:: < HDR: lah:deda"); + Truth.assertThat(debugLines) + .containsExactly( + "RESPONSE_INBOUND:: < STATUS: 200", + "RESPONSE_INBOUND:: < HDR: Content-Length:13", + "RESPONSE_INBOUND:: < HDR: lah:deda"); } @Test @@ -144,10 +150,11 @@ void testWriteOutboundResponseDebug() { Debug.writeDebugResponse(ctx, response, false).toBlocking().single(); List debugLines = getRequestDebug(ctx); - Truth.assertThat(debugLines).containsExactly( - "RESPONSE_OUTBOUND:: < STATUS: 200", - "RESPONSE_OUTBOUND:: < HDR: Content-Length:13", - "RESPONSE_OUTBOUND:: < HDR: lah:deda"); + Truth.assertThat(debugLines) + .containsExactly( + "RESPONSE_OUTBOUND:: < STATUS: 200", + "RESPONSE_OUTBOUND:: < HDR: Content-Length:13", + "RESPONSE_OUTBOUND:: < HDR: lah:deda"); } @Test @@ -157,11 +164,12 @@ void testWriteResponseDebug_WithBody() { Debug.writeDebugResponse(ctx, response, true).toBlocking().single(); List debugLines = getRequestDebug(ctx); - Truth.assertThat(debugLines).containsExactly( - "RESPONSE_INBOUND:: < STATUS: 200", - "RESPONSE_INBOUND:: < HDR: Content-Length:13", - "RESPONSE_INBOUND:: < HDR: lah:deda", - "RESPONSE_INBOUND:: < BODY: response text"); + Truth.assertThat(debugLines) + .containsExactly( + "RESPONSE_INBOUND:: < STATUS: 200", + "RESPONSE_INBOUND:: < HDR: Content-Length:13", + "RESPONSE_INBOUND:: < HDR: lah:deda", + "RESPONSE_INBOUND:: < BODY: response text"); } @Test diff --git a/zuul-core/src/test/java/com/netflix/zuul/context/SessionContextTest.java b/zuul-core/src/test/java/com/netflix/zuul/context/SessionContextTest.java index 7f4584db0c..59ae267cd1 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/context/SessionContextTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/context/SessionContextTest.java @@ -15,14 +15,16 @@ */ package com.netflix.zuul.context; -import static org.junit.jupiter.api.Assertions.*; - import com.google.common.truth.Truth; import com.netflix.zuul.context.SessionContext.Key; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + @ExtendWith(MockitoExtension.class) class SessionContextTest { diff --git a/zuul-core/src/test/java/com/netflix/zuul/filters/BaseFilterTest.java b/zuul-core/src/test/java/com/netflix/zuul/filters/BaseFilterTest.java index 33ae8dd6af..395545a335 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/filters/BaseFilterTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/filters/BaseFilterTest.java @@ -15,15 +15,15 @@ */ package com.netflix.zuul.filters; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - import com.netflix.zuul.message.ZuulMessage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + /** * Tests for {@link BaseFilter}. Currently named BaseFilter2Test as there is an existing * class named BaseFilterTest. @@ -32,8 +32,10 @@ class BaseFilterTest { @Mock private BaseFilter f1; + @Mock private BaseFilter f2; + @Mock private ZuulMessage req; @@ -44,8 +46,7 @@ void before() { @Test void testShouldFilter() { - class TestZuulFilter extends BaseSyncFilter - { + class TestZuulFilter extends BaseSyncFilter { @Override public int filterOrder() { return 0; diff --git a/zuul-core/src/test/java/com/netflix/zuul/filters/common/GZipResponseFilterTest.java b/zuul-core/src/test/java/com/netflix/zuul/filters/common/GZipResponseFilterTest.java index e2ee0944de..365a5119e8 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/filters/common/GZipResponseFilterTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/filters/common/GZipResponseFilterTest.java @@ -16,9 +16,6 @@ package com.netflix.zuul.filters.common; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.when; - import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.Headers; import com.netflix.zuul.message.http.HttpHeaderNames; @@ -29,9 +26,6 @@ import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpContent; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.zip.GZIPInputStream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -39,6 +33,15 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.zip.GZIPInputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + @ExtendWith(MockitoExtension.class) class GZipResponseFilterTest { private final SessionContext context = new SessionContext(); @@ -46,6 +49,7 @@ class GZipResponseFilterTest { @Mock private HttpRequestMessage request; + @Mock private HttpRequestMessage originalRequest; @@ -54,7 +58,7 @@ class GZipResponseFilterTest { @BeforeEach void setup() { - //when(request.getContext()).thenReturn(context); + // when(request.getContext()).thenReturn(context); when(originalRequest.getHeaders()).thenReturn(originalRequestHeaders); filter = Mockito.spy(new GZipResponseFilter()); @@ -69,14 +73,16 @@ void prepareResponseBody_NeedsGZipping() throws Exception { byte[] originBody = "blah".getBytes(); response.getHeaders().set("Content-Length", Integer.toString(originBody.length)); - Mockito.when(filter.isRightSizeForGzip(response)).thenReturn(true); //Force GZip for small response + Mockito.when(filter.isRightSizeForGzip(response)).thenReturn(true); // Force GZip for small response response.setHasBody(true); assertTrue(filter.shouldFilter(response)); final HttpResponseMessage result = filter.apply(response); - final HttpContent hc1 = filter.processContentChunk(response, new DefaultHttpContent(Unpooled.wrappedBuffer(originBody)).retain()); + final HttpContent hc1 = filter.processContentChunk( + response, new DefaultHttpContent(Unpooled.wrappedBuffer(originBody)).retain()); final HttpContent hc2 = filter.processContentChunk(response, new DefaultLastHttpContent()); - final byte[] body = new byte[hc1.content().readableBytes() + hc2.content().readableBytes()]; + final byte[] body = + new byte[hc1.content().readableBytes() + hc2.content().readableBytes()]; final int hc1Len = hc1.content().readableBytes(); final int hc2Len = hc2.content().readableBytes(); hc1.content().readBytes(body, 0, hc1Len); @@ -106,14 +112,16 @@ void prepareResponseBody_NeedsGZipping_gzipDeflate() throws Exception { byte[] originBody = "blah".getBytes(); response.getHeaders().set("Content-Length", Integer.toString(originBody.length)); - Mockito.when(filter.isRightSizeForGzip(response)).thenReturn(true); //Force GZip for small response + Mockito.when(filter.isRightSizeForGzip(response)).thenReturn(true); // Force GZip for small response response.setHasBody(true); assertTrue(filter.shouldFilter(response)); final HttpResponseMessage result = filter.apply(response); - final HttpContent hc1 = filter.processContentChunk(response, new DefaultHttpContent(Unpooled.wrappedBuffer(originBody)).retain()); + final HttpContent hc1 = filter.processContentChunk( + response, new DefaultHttpContent(Unpooled.wrappedBuffer(originBody)).retain()); final HttpContent hc2 = filter.processContentChunk(response, new DefaultLastHttpContent()); - final byte[] body = new byte[hc1.content().readableBytes() + hc2.content().readableBytes()]; + final byte[] body = + new byte[hc1.content().readableBytes() + hc2.content().readableBytes()]; final int hc1Len = hc1.content().readableBytes(); final int hc2Len = hc2.content().readableBytes(); hc1.content().readBytes(body, 0, hc1Len); diff --git a/zuul-core/src/test/java/com/netflix/zuul/filters/endpoint/ProxyEndpointTest.java b/zuul-core/src/test/java/com/netflix/zuul/filters/endpoint/ProxyEndpointTest.java index 78029b0476..ac7748aebe 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/filters/endpoint/ProxyEndpointTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/filters/endpoint/ProxyEndpointTest.java @@ -51,12 +51,23 @@ void setup() { ChannelHandlerContext chc = mock(ChannelHandlerContext.class); NettyRequestAttemptFactory attemptFactory = mock(NettyRequestAttemptFactory.class); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", null, + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", null, - "192.168.0.2", "https", 7002, "localhost", new LocalAddress("777"), false); + null, + "192.168.0.2", + "https", + 7002, + "localhost", + new LocalAddress("777"), + false); request.setBody("Hello There".getBytes()); - request.getContext().set(CommonContextKeys.ORIGIN_MANAGER, new BasicNettyOriginManager(Spectator.globalRegistry())); + request.getContext() + .set(CommonContextKeys.ORIGIN_MANAGER, new BasicNettyOriginManager(Spectator.globalRegistry())); request.getContext().setRouteVIP("some-vip"); request.getContext().put(CommonContextKeys.PASSPORT, CurrentPassport.create()); proxyEndpoint = new ProxyEndpoint(request, chc, null, MethodBinding.NO_OP_BINDING, attemptFactory); @@ -68,13 +79,17 @@ void testRetryWillResetBodyReader() { assertEquals("Hello There", new String(request.getBody())); // move the body readerIndex to the end to mimic nettys behavior after writing to the origin channel - request.getBodyContents().forEach((b) -> b.content().readerIndex(b.content().capacity())); + request.getBodyContents() + .forEach((b) -> b.content().readerIndex(b.content().capacity())); HttpResponse response = mock(HttpResponse.class); when(response.status()).thenReturn(new HttpResponseStatus(503, "Retry")); - InstanceInfo instanceInfo = - InstanceInfo.Builder.newBuilder().setAppName("app").setHostName("localhost").setPort(443).build(); + InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() + .setAppName("app") + .setHostName("localhost") + .setPort(443) + .build(); DiscoveryResult discoveryResult = DiscoveryResult.from(instanceInfo, true); // when retrying a response, the request body reader should have it's indexes reset diff --git a/zuul-core/src/test/java/com/netflix/zuul/message/HeadersTest.java b/zuul-core/src/test/java/com/netflix/zuul/message/HeadersTest.java index c32443f7ef..8755576c4e 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/message/HeadersTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/message/HeadersTest.java @@ -16,10 +16,9 @@ package com.netflix.zuul.message; -import static org.junit.jupiter.api.Assertions.*; - import com.google.common.truth.Truth; import com.netflix.zuul.exception.ZuulException; +import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -29,7 +28,11 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for {@link Headers}. @@ -116,11 +119,14 @@ void forEachNormalised() { headers.add("Cookie", "frizzle=Frazzle"); Map> result = new LinkedHashMap<>(); - headers.forEachNormalised((k, v) -> result.computeIfAbsent(k, discard -> new ArrayList<>()).add(v)); + headers.forEachNormalised((k, v) -> + result.computeIfAbsent(k, discard -> new ArrayList<>()).add(v)); - Truth.assertThat(result).containsExactly( - "via", Collections.singletonList("duct"), - "cookie", Arrays.asList("this=that", "frizzle=Frazzle")).inOrder(); + Truth.assertThat(result) + .containsExactly( + "via", Collections.singletonList("duct"), + "cookie", Arrays.asList("this=that", "frizzle=Frazzle")) + .inOrder(); } @Test @@ -130,7 +136,9 @@ void getAll() { headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); - Truth.assertThat(headers.getAll("CookiE")).containsExactly("this=that", "frizzle=frazzle").inOrder(); + Truth.assertThat(headers.getAll("CookiE")) + .containsExactly("this=that", "frizzle=frazzle") + .inOrder(); } @Test @@ -141,7 +149,8 @@ void getAll_headerName() { headers.add("Cookie", "frizzle=frazzle"); Truth.assertThat(headers.getAll(new HeaderName("CookiE"))) - .containsExactly("this=that", "frizzle=frazzle").inOrder(); + .containsExactly("this=that", "frizzle=frazzle") + .inOrder(); } @Test @@ -297,7 +306,9 @@ void setIfAbsentKeepsExisting() { headers.setIfAbsent("cookIe", "dilly=dally"); - Truth.assertThat(headers.getAll("CookiE")).containsExactly("this=that", "frizzle=frazzle").inOrder(); + Truth.assertThat(headers.getAll("CookiE")) + .containsExactly("this=that", "frizzle=frazzle") + .inOrder(); } @Test @@ -309,7 +320,9 @@ void setIfAbsentKeepsExisting_headerName() { headers.setIfAbsent(new HeaderName("cookIe"), "dilly=dally"); - Truth.assertThat(headers.getAll("CookiE")).containsExactly("this=that", "frizzle=frazzle").inOrder(); + Truth.assertThat(headers.getAll("CookiE")) + .containsExactly("this=that", "frizzle=frazzle") + .inOrder(); } @Test @@ -395,7 +408,9 @@ void add() { headers.add("via", "con Dios"); - Truth.assertThat(headers.getAll("Via")).containsExactly("duct", "con Dios").inOrder(); + Truth.assertThat(headers.getAll("Via")) + .containsExactly("duct", "con Dios") + .inOrder(); } @Test @@ -407,7 +422,9 @@ void add_headerName() { headers.add(new HeaderName("via"), "con Dios"); - Truth.assertThat(headers.getAll("Via")).containsExactly("duct", "con Dios").inOrder(); + Truth.assertThat(headers.getAll("Via")) + .containsExactly("duct", "con Dios") + .inOrder(); } @Test @@ -418,7 +435,9 @@ void addIfValid() { headers.addIfValid("cookie", "uvw=xyz"); Truth.assertThat(headers.getAll("Via")).containsExactly("duct"); - Truth.assertThat(headers.getAll("Cookie")).containsExactly("abc=def", "uvw=xyz").inOrder(); + Truth.assertThat(headers.getAll("Cookie")) + .containsExactly("abc=def", "uvw=xyz") + .inOrder(); Truth.assertThat(headers.size()).isEqualTo(3); } @@ -430,7 +449,9 @@ void addIfValid_headerName() { headers.addIfValid(new HeaderName("cookie"), "uvw=xyz"); Truth.assertThat(headers.getAll("Via")).containsExactly("duct"); - Truth.assertThat(headers.getAll("Cookie")).containsExactly("abc=def", "uvw=xyz").inOrder(); + Truth.assertThat(headers.getAll("Cookie")) + .containsExactly("abc=def", "uvw=xyz") + .inOrder(); Truth.assertThat(headers.size()).isEqualTo(3); } @@ -466,11 +487,12 @@ void putAll() { // Only check the order per field, not for the entire set. Truth.assertThat(headers.getAll("Via")).containsExactly("duct", "com").inOrder(); - Truth.assertThat(headers.getAll("coOkiE")).containsExactly("this=that", "frizzle=frazzle", "a=b").inOrder(); + Truth.assertThat(headers.getAll("coOkiE")) + .containsExactly("this=that", "frizzle=frazzle", "a=b") + .inOrder(); Truth.assertThat(headers.size()).isEqualTo(5); } - @Test void remove() { Headers headers = new Headers(); @@ -484,7 +506,9 @@ void remove() { Truth.assertThat(headers.getAll("Cookie")).isEmpty(); Truth.assertThat(headers.getAll("Soup")).containsExactly("salad"); Truth.assertThat(headers.size()).isEqualTo(2); - Truth.assertThat(removed).containsExactly("this=that", "frizzle=frazzle").inOrder(); + Truth.assertThat(removed) + .containsExactly("this=that", "frizzle=frazzle") + .inOrder(); } @Test @@ -500,7 +524,9 @@ void remove_headerName() { Truth.assertThat(headers.getAll("Cookie")).isEmpty(); Truth.assertThat(headers.getAll("Soup")).containsExactly("salad"); Truth.assertThat(headers.size()).isEqualTo(2); - Truth.assertThat(removed).containsExactly("this=that", "frizzle=frazzle").inOrder(); + Truth.assertThat(removed) + .containsExactly("this=that", "frizzle=frazzle") + .inOrder(); } @Test @@ -692,14 +718,14 @@ void testSanitizeValues_UTF8Value() { // Ideally Unicode characters should not appear in the Header values. Headers headers = new Headers(); - String rawHeaderValue = "\u017d" + "\u0172" + "\u016e" + "\u013F"; //ŽŲŮĽ + String rawHeaderValue = "\u017d" + "\u0172" + "\u016e" + "\u013F"; // ŽŲŮĽ byte[] bytes = rawHeaderValue.getBytes(StandardCharsets.UTF_8); String utf8HeaderValue = new String(bytes, StandardCharsets.UTF_8); headers.addAndValidate("x-test-UTF8", utf8HeaderValue); Truth.assertThat(headers.getAll("x-test-UTF8")).containsExactly(utf8HeaderValue); Truth.assertThat(headers.size()).isEqualTo(1); - rawHeaderValue = "\u017d" + "\u0172" + "uuu" + "\u016e" + "\u013F"; //ŽŲuuuŮĽ + rawHeaderValue = "\u017d" + "\u0172" + "uuu" + "\u016e" + "\u013F"; // ŽŲuuuŮĽ bytes = rawHeaderValue.getBytes(StandardCharsets.UTF_8); utf8HeaderValue = new String(bytes, StandardCharsets.UTF_8); headers.setAndValidate("x-test-UTF8", utf8HeaderValue); diff --git a/zuul-core/src/test/java/com/netflix/zuul/message/ZuulMessageImplTest.java b/zuul-core/src/test/java/com/netflix/zuul/message/ZuulMessageImplTest.java index 87b91d098d..53e63bff07 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/message/ZuulMessageImplTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/message/ZuulMessageImplTest.java @@ -25,7 +25,9 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(MockitoExtension.class) class ZuulMessageImplTest { @@ -181,5 +183,4 @@ void testResettingBodyReaderIndex() { msg.resetBodyReader(); assertEquals("Hello World!", new String(msg.getBody())); } - } diff --git a/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpQueryParamsTest.java b/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpQueryParamsTest.java index 4eb450c80a..823911e2b1 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpQueryParamsTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpQueryParamsTest.java @@ -16,15 +16,15 @@ package com.netflix.zuul.message.http; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Locale; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; +import java.util.Locale; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + @ExtendWith(MockitoExtension.class) class HttpQueryParamsTest { diff --git a/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpRequestMessageImplTest.java b/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpRequestMessageImplTest.java index a208c067f9..33c06b3741 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpRequestMessageImplTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpRequestMessageImplTest.java @@ -16,30 +16,31 @@ package com.netflix.zuul.message.http; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - import com.google.common.net.InetAddresses; import com.netflix.config.ConfigurationManager; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.Headers; import io.netty.channel.local.LocalAddress; +import org.apache.commons.configuration.AbstractConfiguration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; -import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URISyntaxException; import java.util.Optional; -import org.apache.commons.configuration.AbstractConfiguration; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.junit.jupiter.MockitoExtension; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class HttpRequestMessageImplTest { @@ -58,18 +59,31 @@ void testOriginalRequestInfo() { queryParams.add("flag", "5"); Headers headers = new Headers(); headers.add("Host", "blah.netflix.com"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost", new LocalAddress("777"), false); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost", + new LocalAddress("777"), + false); request.storeInboundRequest(); HttpRequestInfo originalRequest = request.getInboundRequest(); assertEquals(request.getPort(), originalRequest.getPort()); assertEquals(request.getPath(), originalRequest.getPath()); - assertEquals(request.getQueryParams().getFirst("flag"), + assertEquals( + request.getQueryParams().getFirst("flag"), originalRequest.getQueryParams().getFirst("flag")); - assertEquals(request.getHeaders().getFirst("Host"), originalRequest.getHeaders().getFirst("Host")); + assertEquals( + request.getHeaders().getFirst("Host"), + originalRequest.getHeaders().getFirst("Host")); request.setPort(8080); request.setPath("/another/place"); @@ -88,18 +102,34 @@ void testReconstructURI() { queryParams.add("flag", "5"); Headers headers = new Headers(); headers.add("Host", "blah.netflix.com"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("https://blah.netflix.com:7002/some/where?flag=5", request.reconstructURI()); queryParams = new HttpQueryParams(); headers = new Headers(); headers.add("X-Forwarded-Host", "place.netflix.com"); headers.add("X-Forwarded-Port", "80"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "http", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "http", + 7002, + "localhost"); assertEquals("http://place.netflix.com/some/where", request.reconstructURI()); queryParams = new HttpQueryParams(); @@ -107,25 +137,49 @@ void testReconstructURI() { headers.add("X-Forwarded-Host", "place.netflix.com"); headers.add("X-Forwarded-Proto", "https"); headers.add("X-Forwarded-Port", "443"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "http", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "http", + 7002, + "localhost"); assertEquals("https://place.netflix.com/some/where", request.reconstructURI()); queryParams = new HttpQueryParams(); headers = new Headers(); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "http", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "http", + 7002, + "localhost"); assertEquals("http://localhost:7002/some/where", request.reconstructURI()); queryParams = new HttpQueryParams(); queryParams.add("flag", "5"); queryParams.add("flag B", "9"); headers = new Headers(); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some%20where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some%20where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("https://localhost:7002/some%20where?flag=5&flag+B=9", request.reconstructURI()); } @@ -135,20 +189,38 @@ void testReconstructURI_immutable() { queryParams.add("flag", "5"); Headers headers = new Headers(); headers.add("Host", "blah.netflix.com"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost", new SocketAddress() { - }, true); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost", + new SocketAddress() {}, + true); // Check it's the same value 2nd time. assertEquals("https://blah.netflix.com:7002/some/where?flag=5", request.reconstructURI()); assertEquals("https://blah.netflix.com:7002/some/where?flag=5", request.reconstructURI()); // Check that cached on 1st usage. - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost", new SocketAddress() { - }, true); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost", + new SocketAddress() {}, + true); request = spy(request); when(request._reconstructURI()).thenReturn("http://testhost/blah"); verify(request, times(1))._reconstructURI(); @@ -168,9 +240,17 @@ void testReconstructURI_immutable() { void testPathAndQuery() { HttpQueryParams queryParams = new HttpQueryParams(); queryParams.add("flag", "5"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, new Headers(), - "192.168.0.2", "https", 7002, "localhost"); + "192.168.0.2", + "https", + 7002, + "localhost"); // Check that value changes. assertEquals("/some/where?flag=5", request.getPathAndQuery()); @@ -184,20 +264,38 @@ void testPathAndQuery() { void testPathAndQuery_immutable() { HttpQueryParams queryParams = new HttpQueryParams(); queryParams.add("flag", "5"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, new Headers(), - "192.168.0.2", "https", 7002, "localhost", new SocketAddress() { - }, true); + "192.168.0.2", + "https", + 7002, + "localhost", + new SocketAddress() {}, + true); // Check it's the same value 2nd time. assertEquals("/some/where?flag=5", request.getPathAndQuery()); assertEquals("/some/where?flag=5", request.getPathAndQuery()); // Check that cached on 1st usage. - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, new Headers(), - "192.168.0.2", "https", 7002, "localhost", new SocketAddress() { - }, true); + "192.168.0.2", + "https", + 7002, + "localhost", + new SocketAddress() {}, + true); request = spy(request); when(request.generatePathAndQuery()).thenReturn("/blah"); verify(request, times(1)).generatePathAndQuery(); @@ -210,63 +308,127 @@ void testGetOriginalHost() { HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "blah.netflix.com"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("blah.netflix.com", request.getOriginalHost()); queryParams = new HttpQueryParams(); headers = new Headers(); headers.add("Host", "0.0.0.1"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("0.0.0.1", request.getOriginalHost()); queryParams = new HttpQueryParams(); headers = new Headers(); headers.add("Host", "0.0.0.1:2"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("0.0.0.1", request.getOriginalHost()); queryParams = new HttpQueryParams(); headers = new Headers(); headers.add("Host", "[::2]"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("[::2]", request.getOriginalHost()); queryParams = new HttpQueryParams(); headers = new Headers(); headers.add("Host", "[::2]:3"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("[::2]", request.getOriginalHost()); headers = new Headers(); headers.add("Host", "blah.netflix.com"); headers.add("X-Forwarded-Host", "foo.netflix.com"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("foo.netflix.com", request.getOriginalHost()); headers = new Headers(); headers.add("X-Forwarded-Host", "foo.netflix.com"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("foo.netflix.com", request.getOriginalHost()); headers = new Headers(); headers.add("Host", "blah.netflix.com:8080"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("blah.netflix.com", request.getOriginalHost()); } @@ -277,30 +439,62 @@ void testGetOriginalHost_handlesNonRFC2396Hostnames() { HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "my_underscore_endpoint.netflix.com"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("my_underscore_endpoint.netflix.com", request.getOriginalHost()); headers = new Headers(); headers.add("Host", "my_underscore_endpoint.netflix.com:8080"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("my_underscore_endpoint.netflix.com", request.getOriginalHost()); headers = new Headers(); headers.add("Host", "my_underscore_endpoint^including~more-chars.netflix.com"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("my_underscore_endpoint^including~more-chars.netflix.com", request.getOriginalHost()); headers = new Headers(); headers.add("Host", "hostname%5Ewith-url-encoded.netflix.com"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals("hostname%5Ewith-url-encoded.netflix.com", request.getOriginalHost()); } @@ -309,9 +503,17 @@ void getOriginalHost_failsOnUnbracketedIpv6Address() { HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "ba::dd"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertThrows(URISyntaxException.class, () -> HttpRequestMessageImpl.getOriginalHost(headers, "server")); } @@ -323,9 +525,17 @@ void getOriginalHost_fallsBackOnUnbracketedIpv6Address_WithNonStrictValidation() HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "ba::dd"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "server"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "server"); assertEquals("server", request.getOriginalHost()); } @@ -334,67 +544,139 @@ void getOriginalHost_fallsBackOnUnbracketedIpv6Address_WithNonStrictValidation() void testGetOriginalPort() { HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals(7002, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "blah.netflix.com"); headers.add("X-Forwarded-Port", "443"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals(443, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "blah.netflix.com:443"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals(443, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "127.0.0.2:443"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals(443, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "127.0.0.2"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals(7002, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "[::2]:443"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals(443, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "[::2]"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals(7002, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "blah.netflix.com:443"); headers.add("X-Forwarded-Port", "7005"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals(7005, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "host_with_underscores.netflix.com:8080"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals(7002, request.getOriginalPort(), "should fallback to server port"); } @@ -405,23 +687,47 @@ void testGetOriginalPort_NonStrictValidation() { HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "host_with_underscores.netflix.com:8080"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals(8080, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "host-with-carrots^1.0.0.netflix.com:8080"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals(8080, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "host-with-carrots-no-port^1.0.0.netflix.com"); - request = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, - headers, - "192.168.0.2", "https", 7002, "localhost"); + request = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + queryParams, + headers, + "192.168.0.2", + "https", + 7002, + "localhost"); assertEquals(7002, request.getOriginalPort()); } @@ -445,7 +751,8 @@ void getOriginalPort_EmptyXFFPort() throws URISyntaxException { @Test void getOriginalPort_respectsProxyProtocol() throws URISyntaxException { SessionContext context = new SessionContext(); - context.set(CommonContextKeys.PROXY_PROTOCOL_DESTINATION_ADDRESS, + context.set( + CommonContextKeys.PROXY_PROTOCOL_DESTINATION_ADDRESS, new InetSocketAddress(InetAddresses.forString("1.1.1.1"), 443)); Headers headers = new Headers(); headers.add("X-Forwarded-Port", "6000"); @@ -454,20 +761,33 @@ void getOriginalPort_respectsProxyProtocol() throws URISyntaxException { @Test void testCleanCookieHeaders() { - assertEquals("BlahId=12345; something=67890;", + assertEquals( + "BlahId=12345; something=67890;", HttpRequestMessageImpl.cleanCookieHeader("BlahId=12345; Secure, something=67890;")); - assertEquals("BlahId=12345; something=67890;", + assertEquals( + "BlahId=12345; something=67890;", HttpRequestMessageImpl.cleanCookieHeader("BlahId=12345; something=67890;")); - assertEquals(" BlahId=12345; something=67890;", + assertEquals( + " BlahId=12345; something=67890;", HttpRequestMessageImpl.cleanCookieHeader(" Secure, BlahId=12345; Secure, something=67890;")); assertEquals("", HttpRequestMessageImpl.cleanCookieHeader("")); } @Test void shouldPreferClientDestPortWhenInitialized() { - HttpRequestMessageImpl message = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", - "/some/where", new HttpQueryParams(), new Headers(), - "192.168.0.2", "https", 7002, "localhost", new InetSocketAddress("api.netflix.com", 443), true); + HttpRequestMessageImpl message = new HttpRequestMessageImpl( + new SessionContext(), + "HTTP/1.1", + "POST", + "/some/where", + new HttpQueryParams(), + new Headers(), + "192.168.0.2", + "https", + 7002, + "localhost", + new InetSocketAddress("api.netflix.com", 443), + true); assertEquals(message.getClientDestinationPort(), Optional.of(443)); } diff --git a/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpResponseMessageImplTest.java b/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpResponseMessageImplTest.java index 6fbf5ac012..044d2b7186 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpResponseMessageImplTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpResponseMessageImplTest.java @@ -16,8 +16,6 @@ package com.netflix.zuul.message.http; -import static org.junit.jupiter.api.Assertions.*; - import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.Headers; import org.junit.jupiter.api.BeforeEach; @@ -28,6 +26,10 @@ import java.nio.charset.StandardCharsets; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Unit tests for {@link HttpResponseMessageImpl}. */ @@ -48,8 +50,14 @@ void setup() { @Test void testHasSetCookieWithName() { - response.getHeaders().add("Set-Cookie", "c1=1234; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com"); - response.getHeaders().add("Set-Cookie", "c2=4567; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com"); + response.getHeaders() + .add( + "Set-Cookie", + "c1=1234; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com"); + response.getHeaders() + .add( + "Set-Cookie", + "c2=4567; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com"); assertTrue(response.hasSetCookieWithName("c1")); assertTrue(response.hasSetCookieWithName("c2")); @@ -58,8 +66,14 @@ void testHasSetCookieWithName() { @Test void testRemoveExistingSetCookie() { - response.getHeaders().add("Set-Cookie", "c1=1234; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com"); - response.getHeaders().add("Set-Cookie", "c2=4567; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com"); + response.getHeaders() + .add( + "Set-Cookie", + "c1=1234; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com"); + response.getHeaders() + .add( + "Set-Cookie", + "c2=4567; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com"); response.removeExistingSetCookie("c1"); diff --git a/zuul-core/src/test/java/com/netflix/zuul/monitoring/ConnCounterTest.java b/zuul-core/src/test/java/com/netflix/zuul/monitoring/ConnCounterTest.java index f4ed4a09e9..f09e078621 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/monitoring/ConnCounterTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/monitoring/ConnCounterTest.java @@ -16,9 +16,6 @@ package com.netflix.zuul.monitoring; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Registry; @@ -27,6 +24,9 @@ import io.netty.channel.embedded.EmbeddedChannel; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + class ConnCounterTest { @Test void record() { @@ -67,7 +67,6 @@ void activeConnsCount() { ConnCounter.from(channel).increment("active"); ConnCounter.from(channel).increment("active"); - assertEquals(1, ConnCounter.from(channel).getCurrentActiveConns(), 0); } } diff --git a/zuul-core/src/test/java/com/netflix/zuul/monitoring/ConnTimerTest.java b/zuul-core/src/test/java/com/netflix/zuul/monitoring/ConnTimerTest.java index 4071599566..06585921fd 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/monitoring/ConnTimerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/monitoring/ConnTimerTest.java @@ -16,9 +16,6 @@ package com.netflix.zuul.monitoring; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.histogram.PercentileTimer; @@ -27,6 +24,9 @@ import io.netty.channel.embedded.EmbeddedChannel; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + class ConnTimerTest { @Test void record() { @@ -41,18 +41,15 @@ void record() { Attrs.newKey("bar").put(attrs, "baz"); timer.record(4000L, "end"); - PercentileTimer meter1 = - PercentileTimer.get(registry, registry.createId("foo.start-middle")); + PercentileTimer meter1 = PercentileTimer.get(registry, registry.createId("foo.start-middle")); assertNotNull(meter1); assertEquals(1000L, meter1.totalTime()); - PercentileTimer meter2 = - PercentileTimer.get(registry, registry.createId("foo.middle-end", "bar", "baz")); + PercentileTimer meter2 = PercentileTimer.get(registry, registry.createId("foo.middle-end", "bar", "baz")); assertNotNull(meter2); assertEquals(2000L, meter2.totalTime()); - PercentileTimer meter3 = - PercentileTimer.get(registry, registry.createId("foo.start-end", "bar", "baz")); + PercentileTimer meter3 = PercentileTimer.get(registry, registry.createId("foo.start-end", "bar", "baz")); assertNotNull(meter3); assertEquals(3000L, meter3.totalTime()); } diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/connectionpool/DefaultClientChannelManagerTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/connectionpool/DefaultClientChannelManagerTest.java index 1a3704d8ec..3c0f5b1f7d 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/connectionpool/DefaultClientChannelManagerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/connectionpool/DefaultClientChannelManagerTest.java @@ -16,19 +16,12 @@ package com.netflix.zuul.netty.connectionpool; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import com.google.common.net.InetAddresses; import com.google.common.truth.Truth; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.Builder; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.spectator.api.DefaultRegistry; -import com.netflix.spectator.api.NoopRegistry; import com.netflix.spectator.api.Registry; import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.discovery.DynamicServerResolver; @@ -38,17 +31,24 @@ import com.netflix.zuul.passport.CurrentPassport; import io.netty.channel.DefaultEventLoop; import io.netty.channel.EventLoop; -import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.Promise; +import org.junit.jupiter.api.Test; + import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.SocketAddress; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * Tests for {@link DefaultClientChannelManager}. These tests don't use IPv6 addresses because {@link InstanceInfo} is @@ -58,8 +58,11 @@ class DefaultClientChannelManagerTest { @Test void pickAddressInternal_discovery() { - InstanceInfo instanceInfo = - Builder.newBuilder().setAppName("app").setHostName("192.168.0.1").setPort(443).build(); + InstanceInfo instanceInfo = Builder.newBuilder() + .setAppName("app") + .setHostName("192.168.0.1") + .setPort(443) + .build(); DiscoveryResult s = DiscoveryResult.from(instanceInfo, true); SocketAddress addr = DefaultClientChannelManager.pickAddressInternal(s, OriginName.fromVip("vip")); @@ -72,8 +75,11 @@ void pickAddressInternal_discovery() { @Test void pickAddressInternal_discovery_unresolved() { - InstanceInfo instanceInfo = - Builder.newBuilder().setAppName("app").setHostName("localhost").setPort(443).build(); + InstanceInfo instanceInfo = Builder.newBuilder() + .setAppName("app") + .setHostName("localhost") + .setPort(443) + .build(); DiscoveryResult s = DiscoveryResult.from(instanceInfo, true); SocketAddress addr = DefaultClientChannelManager.pickAddressInternal(s, OriginName.fromVip("vip")); @@ -118,13 +124,13 @@ void updateServerRefOnEmptyDiscoveryResult() { when(resolver.resolve(any())).thenReturn(DiscoveryResult.EMPTY); - final DefaultClientChannelManager clientChannelManager = new DefaultClientChannelManager(originName, - clientConfig, resolver, new DefaultRegistry()); + final DefaultClientChannelManager clientChannelManager = + new DefaultClientChannelManager(originName, clientConfig, resolver, new DefaultRegistry()); final AtomicReference serverRef = new AtomicReference<>(); - final Promise promise = clientChannelManager - .acquire(new DefaultEventLoop(), null, CurrentPassport.create(), serverRef, new AtomicReference<>()); + final Promise promise = clientChannelManager.acquire( + new DefaultEventLoop(), null, CurrentPassport.create(), serverRef, new AtomicReference<>()); Truth.assertThat(promise.isSuccess()).isFalse(); Truth.assertThat(serverRef.get()).isSameInstanceAs(DiscoveryResult.EMPTY); @@ -139,19 +145,20 @@ void updateServerRefOnValidDiscoveryResult() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("server-equality") .setHostName("server-equality") - .setPort(7777).build(); + .setPort(7777) + .build(); final DiscoveryResult discoveryResult = DiscoveryResult.from(instanceInfo, false); when(resolver.resolve(any())).thenReturn(discoveryResult); - final DefaultClientChannelManager clientChannelManager = new DefaultClientChannelManager(originName, - clientConfig, resolver, new DefaultRegistry()); + final DefaultClientChannelManager clientChannelManager = + new DefaultClientChannelManager(originName, clientConfig, resolver, new DefaultRegistry()); final AtomicReference serverRef = new AtomicReference<>(); - //TODO(argha-c) capture and assert on the promise once we have a dummy with ServerStats initialized - clientChannelManager - .acquire(new DefaultEventLoop(), null, CurrentPassport.create(), serverRef, new AtomicReference<>()); + // TODO(argha-c) capture and assert on the promise once we have a dummy with ServerStats initialized + clientChannelManager.acquire( + new DefaultEventLoop(), null, CurrentPassport.create(), serverRef, new AtomicReference<>()); Truth.assertThat(serverRef.get()).isSameInstanceAs(discoveryResult); } @@ -180,8 +187,8 @@ void initializeAndShutdown() throws Exception { when(resolver.hasServers()).thenReturn(true); final Registry registry = new DefaultRegistry(); - final DefaultClientChannelManager clientChannelManager = new DefaultClientChannelManager(originName, - clientConfig, resolver, registry); + final DefaultClientChannelManager clientChannelManager = + new DefaultClientChannelManager(originName, clientConfig, resolver, registry); final NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(10); final EventLoop eventLoop = eventLoopGroup.next(); diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/connectionpool/PerServerConnectionPoolTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/connectionpool/PerServerConnectionPoolTest.java index 58276d4e1d..089e98c461 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/connectionpool/PerServerConnectionPoolTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/connectionpool/PerServerConnectionPoolTest.java @@ -16,14 +16,6 @@ package com.netflix.zuul.netty.connectionpool; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.spy; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.Builder; import com.netflix.client.config.DefaultClientConfigImpl; @@ -49,12 +41,6 @@ import io.netty.channel.local.LocalChannel; import io.netty.channel.local.LocalServerChannel; import io.netty.util.concurrent.Promise; -import java.util.Deque; -import java.util.UUID; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -63,6 +49,21 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import java.util.Deque; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.spy; /** * @author Justin Guerra @@ -106,13 +107,13 @@ static void staticSetup() throws InterruptedException { CLIENT_EVENT_LOOP = CLIENT_EVENT_LOOP_GROUP.next(); ORIGIN_EVENT_LOOP_GROUP = new DefaultEventLoopGroup(1); - ServerBootstrap bootstrap = new ServerBootstrap().group(ORIGIN_EVENT_LOOP_GROUP) + ServerBootstrap bootstrap = new ServerBootstrap() + .group(ORIGIN_EVENT_LOOP_GROUP) .localAddress(LOCAL_ADDRESS) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer() { @Override - protected void initChannel(LocalChannel ch) { - } + protected void initChannel(LocalChannel ch) {} }); bootstrap.bind().sync(); @@ -136,7 +137,6 @@ void setup() { registry = new DefaultRegistry(); - int index = 0; createNewConnCounter = registry.counter("fake_counter" + index++); createConnSucceededCounter = registry.counter("fake_counter" + index++); @@ -162,21 +162,32 @@ void setup() { clientConfig = new DefaultClientConfigImpl(); connectionPoolConfig = spy(new ConnectionPoolConfigImpl(originName, clientConfig)); - NettyClientConnectionFactory nettyConnectionFactory = new NettyClientConnectionFactory(connectionPoolConfig, - new ChannelInitializer() { + NettyClientConnectionFactory nettyConnectionFactory = + new NettyClientConnectionFactory(connectionPoolConfig, new ChannelInitializer() { @Override - protected void initChannel(Channel ch) { - } + protected void initChannel(Channel ch) {} }); PooledConnectionFactory pooledConnectionFactory = this::newPooledConnection; - pool = new PerServerConnectionPool(discoveryResult, LOCAL_ADDRESS, nettyConnectionFactory, + pool = new PerServerConnectionPool( + discoveryResult, + LOCAL_ADDRESS, + nettyConnectionFactory, pooledConnectionFactory, - connectionPoolConfig, clientConfig, - createNewConnCounter, createConnSucceededCounter, createConnFailedCounter, requestConnCounter, - reuseConnCounter, connTakenFromPoolIsNotOpen, closeAboveHighWaterMarkCounter, - maxConnsPerHostExceededCounter, connEstablishTimer, connsInPool, connsInUse); + connectionPoolConfig, + clientConfig, + createNewConnCounter, + createConnSucceededCounter, + createConnFailedCounter, + requestConnCounter, + reuseConnCounter, + connTakenFromPoolIsNotOpen, + closeAboveHighWaterMarkCounter, + maxConnsPerHostExceededCounter, + connEstablishTimer, + connsInPool, + connsInUse); } @Test @@ -206,10 +217,12 @@ void acquireNewConnection() throws InterruptedException, ExecutionException { assertEquals(1, createConnSucceededCounter.count()); assertEquals(1, connsInUse.get()); - //check state on PooledConnection - not all thread safe - CLIENT_EVENT_LOOP.submit(() -> { - checkChannelState(connection, currentPassport, 1); - }).sync(); + // check state on PooledConnection - not all thread safe + CLIENT_EVENT_LOOP + .submit(() -> { + checkChannelState(connection, currentPassport, 1); + }) + .sync(); } @Test @@ -219,9 +232,11 @@ void acquireConnectionFromPoolAndRelease() throws InterruptedException, Executio PooledConnection connection = promise.sync().get(); - CLIENT_EVENT_LOOP.submit(() -> { - pool.release(connection); - }).sync(); + CLIENT_EVENT_LOOP + .submit(() -> { + pool.release(connection); + }) + .sync(); assertEquals(1, connsInPool.get()); @@ -233,10 +248,11 @@ void acquireConnectionFromPoolAndRelease() throws InterruptedException, Executio assertEquals(2, requestConnCounter.count()); assertEquals(0, connsInPool.get()); - - CLIENT_EVENT_LOOP.submit(() -> { - checkChannelState(connection, newPassport, 2); - }).sync(); + CLIENT_EVENT_LOOP + .submit(() -> { + checkChannelState(connection, newPassport, 2); + }) + .sync(); } @Test @@ -246,11 +262,13 @@ void releaseFromPoolButAlreadyClosed() throws InterruptedException, ExecutionExc PooledConnection connection = promise.sync().get(); - CLIENT_EVENT_LOOP.submit(() -> { - pool.release(connection); - }).sync(); + CLIENT_EVENT_LOOP + .submit(() -> { + pool.release(connection); + }) + .sync(); - //make the connection invalid + // make the connection invalid connection.getChannel().deregister().sync(); CurrentPassport newPassport = CurrentPassport.create(); @@ -260,7 +278,9 @@ void releaseFromPoolButAlreadyClosed() throws InterruptedException, ExecutionExc assertNotEquals(connection, connection2); assertEquals(1, connTakenFromPoolIsNotOpen.count()); assertEquals(0, connsInPool.get()); - assertTrue(connection.getChannel().closeFuture().await(5, TimeUnit.SECONDS), "Channel should have been closed by pool"); + assertTrue( + connection.getChannel().closeFuture().await(5, TimeUnit.SECONDS), + "Channel should have been closed by pool"); } @Test @@ -275,12 +295,16 @@ void releaseFromPoolAboveHighWaterMark() throws InterruptedException, ExecutionE PooledConnection connection = promise.sync().get(); try { configuration.setProperty(propertyName, 0); - CLIENT_EVENT_LOOP.submit(() -> { - assertFalse(pool.release(connection)); - assertEquals(1, closeAboveHighWaterMarkCounter.count()); - assertFalse(connection.isInPool()); - }).sync(); - assertTrue(connection.getChannel().closeFuture().await(5, TimeUnit.SECONDS), "connection should have been closed"); + CLIENT_EVENT_LOOP + .submit(() -> { + assertFalse(pool.release(connection)); + assertEquals(1, closeAboveHighWaterMarkCounter.count()); + assertFalse(connection.isInPool()); + }) + .sync(); + assertTrue( + connection.getChannel().closeFuture().await(5, TimeUnit.SECONDS), + "connection should have been closed"); } finally { configuration.setProperty(propertyName, 4); } @@ -288,25 +312,33 @@ void releaseFromPoolAboveHighWaterMark() throws InterruptedException, ExecutionE @Test void releaseFromPoolWhileDraining() throws InterruptedException, ExecutionException { - Promise promise = pool.acquire(CLIENT_EVENT_LOOP, CurrentPassport.create(), new AtomicReference<>()); + Promise promise = + pool.acquire(CLIENT_EVENT_LOOP, CurrentPassport.create(), new AtomicReference<>()); PooledConnection connection = promise.sync().get(); pool.drain(); - CLIENT_EVENT_LOOP.submit(() -> { - assertFalse(connection.isInPool()); - assertTrue(connection.getChannel().isActive(), "connection was incorrectly closed during the drain"); - pool.release(connection); - }).sync(); - - assertTrue(connection.getChannel().closeFuture().await(5, TimeUnit.SECONDS), "connection should have been closed after release"); + CLIENT_EVENT_LOOP + .submit(() -> { + assertFalse(connection.isInPool()); + assertTrue( + connection.getChannel().isActive(), "connection was incorrectly closed during the drain"); + pool.release(connection); + }) + .sync(); + + assertTrue( + connection.getChannel().closeFuture().await(5, TimeUnit.SECONDS), + "connection should have been closed after release"); } @Test void acquireWhileDraining() { pool.drain(); assertFalse(pool.isAvailable()); - assertThrows(IllegalStateException.class, () -> pool.acquire(CLIENT_EVENT_LOOP, CurrentPassport.create(), new AtomicReference<>())); + assertThrows( + IllegalStateException.class, + () -> pool.acquire(CLIENT_EVENT_LOOP, CurrentPassport.create(), new AtomicReference<>())); } @Test @@ -317,7 +349,6 @@ void gracefulDrain() { PooledConnection connection1 = newPooledConnection(channel1); PooledConnection connection2 = newPooledConnection(channel2); - Deque connections = pool.getPoolForEventLoop(channel1.eventLoop()); connections.add(connection1); connections.add(connection2); @@ -342,8 +373,11 @@ private void checkChannelState(PooledConnection connection, CurrentPassport pass } private PooledConnection newPooledConnection(Channel ch) { - return new PooledConnection(ch, discoveryResult, - channelManager, registry.counter("fake_close_counter"), registry.counter("fake_close_wrt_counter")); + return new PooledConnection( + ch, + discoveryResult, + channelManager, + registry.counter("fake_close_counter"), + registry.counter("fake_close_wrt_counter")); } - } \ No newline at end of file diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/filter/ZuulEndPointRunnerTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/filter/ZuulEndPointRunnerTest.java index 4396899ee3..437134a6f4 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/filter/ZuulEndPointRunnerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/filter/ZuulEndPointRunnerTest.java @@ -33,19 +33,20 @@ import com.netflix.zuul.message.http.HttpRequestMessageImpl; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.message.http.HttpResponseMessageImpl; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import io.netty.channel.ChannelHandlerContext; import io.netty.util.concurrent.ImmediateEventExecutor; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import rx.Observable; import static com.netflix.zuul.context.CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT; import static com.netflix.zuul.context.CommonContextKeys.ZUUL_ENDPOINT; import static com.netflix.zuul.netty.filter.ZuulEndPointRunner.DEFAULT_ERROR_ENDPOINT; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -79,7 +80,17 @@ void beforeEachTest() { ChannelHandlerContext chc = mock(ChannelHandlerContext.class); when(chc.executor()).thenReturn(ImmediateEventExecutor.INSTANCE); context.put(NETTY_SERVER_CHANNEL_HANDLER_CONTEXT, chc); - request = new HttpRequestMessageImpl(context, "http", "GET", "/foo/bar", new HttpQueryParams(), headers, "127.0.0.1", "http", 8080, "server123"); + request = new HttpRequestMessageImpl( + context, + "http", + "GET", + "/foo/bar", + new HttpQueryParams(), + headers, + "127.0.0.1", + "http", + 8080, + "server123"); request.storeInboundRequest(); } @@ -89,7 +100,8 @@ void nonErrorEndpoint() { request.getContext().setEndpoint(BASIC_ENDPOINT); assertNull(request.getContext().get(ZUUL_ENDPOINT)); endpointRunner.filter(request); - final ZuulFilter filter = request.getContext().get(ZUUL_ENDPOINT); + final ZuulFilter filter = + request.getContext().get(ZUUL_ENDPOINT); assertTrue(filter instanceof BasicEndpoint); ArgumentCaptor captor = ArgumentCaptor.forClass(HttpResponseMessage.class); diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/filter/ZuulFilterChainRunnerTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/filter/ZuulFilterChainRunnerTest.java index 44880f11b5..53563cf7ed 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/filter/ZuulFilterChainRunnerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/filter/ZuulFilterChainRunnerTest.java @@ -15,17 +15,6 @@ */ package com.netflix.zuul.netty.filter; -import static com.netflix.zuul.context.CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - import com.netflix.spectator.api.Registry; import com.netflix.zuul.ExecutionStatus; import com.netflix.zuul.FilterUsageNotifier; @@ -40,13 +29,22 @@ import com.netflix.zuul.message.http.HttpRequestMessageImpl; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.message.http.HttpResponseMessageImpl; - import io.netty.channel.ChannelHandlerContext; import io.netty.util.concurrent.ImmediateEventExecutor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import rx.Observable; +import static com.netflix.zuul.context.CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; class ZuulFilterChainRunnerTest { private HttpRequestMessage request; @@ -59,7 +57,17 @@ void before() { ChannelHandlerContext chc = mock(ChannelHandlerContext.class); when(chc.executor()).thenReturn(ImmediateEventExecutor.INSTANCE); context.put(NETTY_SERVER_CHANNEL_HANDLER_CONTEXT, chc); - request = new HttpRequestMessageImpl(context, "http", "GET", "/foo/bar", new HttpQueryParams(), headers, "127.0.0.1", "http", 8080, "server123"); + request = new HttpRequestMessageImpl( + context, + "http", + "GET", + "/foo/bar", + new HttpQueryParams(), + headers, + "127.0.0.1", + "http", + 8080, + "server123"); request.storeInboundRequest(); response = new HttpResponseMessageImpl(context, request, 200); } @@ -69,15 +77,12 @@ void testInboundFilterChain() { final SimpleInboundFilter inbound1 = spy(new SimpleInboundFilter(true)); final SimpleInboundFilter inbound2 = spy(new SimpleInboundFilter(false)); - final ZuulFilter[] filters = new ZuulFilter[]{inbound1, inbound2}; + final ZuulFilter[] filters = new ZuulFilter[] {inbound1, inbound2}; final FilterUsageNotifier notifier = mock(FilterUsageNotifier.class); final Registry registry = mock(Registry.class); - final ZuulFilterChainRunner runner = new ZuulFilterChainRunner( - filters, - notifier, - registry); + final ZuulFilterChainRunner runner = new ZuulFilterChainRunner(filters, notifier, registry); runner.filter(request); @@ -94,15 +99,12 @@ void testOutboundFilterChain() { final SimpleOutboundFilter outbound1 = spy(new SimpleOutboundFilter(true)); final SimpleOutboundFilter outbound2 = spy(new SimpleOutboundFilter(false)); - final ZuulFilter[] filters = new ZuulFilter[]{outbound1, outbound2}; + final ZuulFilter[] filters = new ZuulFilter[] {outbound1, outbound2}; final FilterUsageNotifier notifier = mock(FilterUsageNotifier.class); final Registry registry = mock(Registry.class); - final ZuulFilterChainRunner runner = new ZuulFilterChainRunner( - filters, - notifier, - registry); + final ZuulFilterChainRunner runner = new ZuulFilterChainRunner(filters, notifier, registry); runner.filter(response); @@ -169,6 +171,4 @@ public boolean shouldFilter(HttpResponseMessage msg) { return this.shouldFilter; } } - } - diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/insights/ServerStateHandlerTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/insights/ServerStateHandlerTest.java index 920d53f6b0..01e87be070 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/insights/ServerStateHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/insights/ServerStateHandlerTest.java @@ -16,11 +16,8 @@ package com.netflix.zuul.netty.insights; -import static org.junit.jupiter.api.Assertions.assertEquals; - import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; -import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.zuul.netty.insights.ServerStateHandler.InboundHandler; @@ -31,6 +28,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + class ServerStateHandlerTest { private Registry registry; @@ -85,7 +84,9 @@ void setPassportStateOnConnect() { channel.pipeline().context(DummyChannelHandler.class).fireChannelActive(); - assertEquals(PassportState.SERVER_CH_ACTIVE, CurrentPassport.fromChannel(channel).getState()); + assertEquals( + PassportState.SERVER_CH_ACTIVE, + CurrentPassport.fromChannel(channel).getState()); } @Test @@ -96,7 +97,8 @@ void setPassportStateOnDisconnect() { channel.pipeline().context(DummyChannelHandler.class).fireChannelInactive(); - assertEquals(PassportState.SERVER_CH_INACTIVE, CurrentPassport.fromChannel(channel).getState()); + assertEquals( + PassportState.SERVER_CH_INACTIVE, + CurrentPassport.fromChannel(channel).getState()); } - } diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/server/BaseZuulChannelInitializerTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/server/BaseZuulChannelInitializerTest.java index 442df9bdc0..08219ba551 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/server/BaseZuulChannelInitializerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/server/BaseZuulChannelInitializerTest.java @@ -16,8 +16,6 @@ package com.netflix.zuul.netty.server; -import static org.junit.jupiter.api.Assertions.assertNotNull; - import com.netflix.netty.common.SourceAddressChannelHandler; import com.netflix.netty.common.channel.config.ChannelConfig; import com.netflix.netty.common.channel.config.CommonChannelConfigKeys; @@ -34,6 +32,8 @@ import io.netty.util.concurrent.GlobalEventExecutor; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * Unit tests for {@link BaseZuulChannelInitializer}. */ @@ -53,8 +53,7 @@ void tcpHandlersAdded() { new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) { @Override - protected void initChannel(Channel ch) { - } + protected void initChannel(Channel ch) {} }; EmbeddedChannel channel = new EmbeddedChannel(); @@ -81,8 +80,7 @@ void tcpHandlersAdded_withProxyProtocol() { new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) { @Override - protected void initChannel(Channel ch) { - } + protected void initChannel(Channel ch) {} }; EmbeddedChannel channel = new EmbeddedChannel(); @@ -109,8 +107,7 @@ void serverStateHandlerAdded() { new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) { @Override - protected void initChannel(Channel ch) { - } + protected void initChannel(Channel ch) {} }; EmbeddedChannel channel = new EmbeddedChannel(); @@ -118,6 +115,5 @@ protected void initChannel(Channel ch) { assertNotNull(channel.pipeline().context(ServerStateHandler.InboundHandler.class)); assertNotNull(channel.pipeline().context(ServerStateHandler.OutboundHandler.class)); - } } diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientConnectionsShutdownTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientConnectionsShutdownTest.java index a7d1e2a970..d40e160cec 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientConnectionsShutdownTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientConnectionsShutdownTest.java @@ -16,14 +16,6 @@ package com.netflix.zuul.netty.server; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.EurekaClient; @@ -43,10 +35,6 @@ import io.netty.channel.local.LocalServerChannel; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.Promise; -import java.util.UUID; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -56,13 +44,27 @@ import org.mockito.ArgumentMatchers; import org.mockito.Mockito; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + /** * @author Justin Guerra * @since 2/28/23 */ class ClientConnectionsShutdownTest { - //using LocalChannels instead of EmbeddedChannels to re-create threading behavior in an actual deployment + // using LocalChannels instead of EmbeddedChannels to re-create threading behavior in an actual deployment private static LocalAddress LOCAL_ADDRESS; private static DefaultEventLoopGroup SERVER_EVENT_LOOP; private static DefaultEventLoopGroup CLIENT_EVENT_LOOP; @@ -74,15 +76,14 @@ static void staticSetup() throws InterruptedException { CLIENT_EVENT_LOOP = new DefaultEventLoopGroup(4); SERVER_EVENT_LOOP = new DefaultEventLoopGroup(4); - ServerBootstrap serverBootstrap = new ServerBootstrap().group(SERVER_EVENT_LOOP) - .localAddress(LOCAL_ADDRESS) - .channel(LocalServerChannel.class) - .childHandler(new ChannelInitializer() { - @Override - protected void initChannel(LocalChannel ch) { - - } - }); + ServerBootstrap serverBootstrap = new ServerBootstrap() + .group(SERVER_EVENT_LOOP) + .localAddress(LOCAL_ADDRESS) + .channel(LocalServerChannel.class) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(LocalChannel ch) {} + }); serverBootstrap.bind().sync(); EVENT_LOOP = new DefaultEventLoop(Executors.newSingleThreadExecutor()); @@ -115,8 +116,7 @@ void discoveryShutdown() { EurekaClient eureka = Mockito.mock(EurekaClient.class); EventExecutor executor = Mockito.mock(EventExecutor.class); - ArgumentCaptor captor = ArgumentCaptor.forClass( - EurekaEventListener.class); + ArgumentCaptor captor = ArgumentCaptor.forClass(EurekaEventListener.class); shutdown = spy(new ClientConnectionsShutdown(channels, executor, eureka)); verify(eureka).registerEventListener(captor.capture()); doReturn(executor.newPromise()).when(shutdown).gracefullyShutdownClientChannels(); @@ -132,7 +132,8 @@ void discoveryShutdown() { Mockito.reset(executor); listener.onEvent(new StatusChangeEvent(InstanceStatus.STARTING, InstanceStatus.OUT_OF_SERVICE)); - verify(executor, never()).schedule(ArgumentMatchers.isA(Callable.class), anyLong(), eq(TimeUnit.MILLISECONDS)); + verify(executor, never()) + .schedule(ArgumentMatchers.isA(Callable.class), anyLong(), eq(TimeUnit.MILLISECONDS)); } finally { configuration.setProperty(configName, "false"); } @@ -145,11 +146,11 @@ void allConnectionsGracefullyClosed() throws Exception { Promise testPromise = EVENT_LOOP.newPromise(); promise.addListener(future -> { - if(future.isSuccess()) { - testPromise.setSuccess(null); - } else { - testPromise.setFailure(future.cause()); - } + if (future.isSuccess()) { + testPromise.setSuccess(null); + } else { + testPromise.setFailure(future.cause()); + } }); channels.forEach(Channel::close); @@ -167,7 +168,9 @@ void connectionNeedsToBeForceClosed() throws Exception { createChannels(10); shutdown.gracefullyShutdownClientChannels().await(10, TimeUnit.SECONDS); - assertTrue(channels.isEmpty(), "All channels in group should have been force closed after the timeout was triggered"); + assertTrue( + channels.isEmpty(), + "All channels in group should have been force closed after the timeout was triggered"); } finally { configuration.setProperty(configName, "30"); } @@ -213,5 +216,4 @@ protected void initChannel(LocalChannel ch) {} channels.add(connect.channel()); } } - } \ No newline at end of file diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientRequestReceiverTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientRequestReceiverTest.java index a8c960af50..e5358a9ea3 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientRequestReceiverTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientRequestReceiverTest.java @@ -16,8 +16,6 @@ package com.netflix.zuul.netty.server; -import static org.junit.jupiter.api.Assertions.*; - import com.google.common.net.InetAddresses; import com.netflix.netty.common.HttpLifecycleChannelHandler; import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent; @@ -43,13 +41,20 @@ import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpVersion; -import java.net.InetSocketAddress; -import java.util.Arrays; -import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; +import java.net.InetSocketAddress; +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Unit tests for {@link ClientRequestReceiver}. */ @@ -61,7 +66,8 @@ void proxyProtocol_portSetInSessionContextAndInHttpRequestMessageImpl() { EmbeddedChannel channel = new EmbeddedChannel(new ClientRequestReceiver(null)); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); InetSocketAddress hapmDestinationAddress = new InetSocketAddress(InetAddresses.forString("2.2.2.2"), 444); - channel.attr(SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS).set(hapmDestinationAddress); + channel.attr(SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS) + .set(hapmDestinationAddress); channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).set(hapmDestinationAddress); HttpRequestMessageImpl result; { @@ -71,8 +77,9 @@ void proxyProtocol_portSetInSessionContextAndInHttpRequestMessageImpl() { result.disposeBufferedBody(); } assertEquals((int) result.getClientDestinationPort().get(), hapmDestinationAddress.getPort()); - int destinationPort = ((InetSocketAddress) result.getContext() - .get(CommonContextKeys.PROXY_PROTOCOL_DESTINATION_ADDRESS)).getPort(); + int destinationPort = ((InetSocketAddress) + result.getContext().get(CommonContextKeys.PROXY_PROTOCOL_DESTINATION_ADDRESS)) + .getPort(); assertEquals(444, destinationPort); assertEquals(444, result.getOriginalPort()); channel.close(); @@ -85,8 +92,11 @@ void parseUriFromNetty_relative() { channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); HttpRequestMessageImpl result; { - channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, - "/foo/bar/somePath/%5E1.0.0?param1=foo¶m2=bar¶m3=baz", Unpooled.buffer())); + channel.writeInbound(new DefaultFullHttpRequest( + HttpVersion.HTTP_1_1, + HttpMethod.POST, + "/foo/bar/somePath/%5E1.0.0?param1=foo¶m2=bar¶m3=baz", + Unpooled.buffer())); result = channel.readInbound(); result.disposeBufferedBody(); } @@ -103,8 +113,11 @@ void parseUriFromNetty_absolute() { channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); HttpRequestMessageImpl result; { - channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, - "https://www.netflix.com/foo/bar/somePath/%5E1.0.0?param1=foo¶m2=bar¶m3=baz", Unpooled.buffer())); + channel.writeInbound(new DefaultFullHttpRequest( + HttpVersion.HTTP_1_1, + HttpMethod.POST, + "https://www.netflix.com/foo/bar/somePath/%5E1.0.0?param1=foo¶m2=bar¶m3=baz", + Unpooled.buffer())); result = channel.readInbound(); result.disposeBufferedBody(); } @@ -121,8 +134,8 @@ void parseUriFromNetty_unknown() { channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); HttpRequestMessageImpl result; { - channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, - "asdf", Unpooled.buffer())); + channel.writeInbound( + new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "asdf", Unpooled.buffer())); result = channel.readInbound(); result.disposeBufferedBody(); } @@ -139,8 +152,11 @@ void parseQueryParamsWithEncodedCharsInURI() { channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); HttpRequestMessageImpl result; { - channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, - "/foo/bar/somePath/%5E1.0.0?param1=foo¶m2=bar¶m3=baz", Unpooled.buffer())); + channel.writeInbound(new DefaultFullHttpRequest( + HttpVersion.HTTP_1_1, + HttpMethod.POST, + "/foo/bar/somePath/%5E1.0.0?param1=foo¶m2=bar¶m3=baz", + Unpooled.buffer())); result = channel.readInbound(); result.disposeBufferedBody(); } @@ -227,12 +243,7 @@ void maxHeaderSizeExceeded_setBadRequestStatus() { // Required for messages channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); - channel.pipeline().addLast(new HttpServerCodec( - maxInitialLineLength, - maxHeaderSize, - maxChunkSize, - false - )); + channel.pipeline().addLast(new HttpServerCodec(maxInitialLineLength, maxHeaderSize, maxChunkSize, false)); channel.pipeline().addLast(receiver); channel.pipeline().addLast(loggingHandler); @@ -251,7 +262,8 @@ void maxHeaderSizeExceeded_setBadRequestStatus() { HttpRequestMessage request = ClientRequestReceiver.getRequestFromChannel(channel); assertEquals( - ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST, StatusCategoryUtils.getStatusCategory(request.getContext())); + ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST, + StatusCategoryUtils.getStatusCategory(request.getContext())); } @Test @@ -278,8 +290,7 @@ void multipleHostHeaders_setBadRequestStatus() { HttpRequestMessage request = ClientRequestReceiver.getRequestFromChannel(channel); SessionContext context = request.getContext(); - assertEquals( - ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST, StatusCategoryUtils.getStatusCategory(context)); + assertEquals(ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST, StatusCategoryUtils.getStatusCategory(context)); assertEquals("Multiple Host headers", context.getError().getMessage()); } @@ -289,8 +300,8 @@ void setStatusCategoryForHttpPipelining() { EmbeddedChannel channel = new EmbeddedChannel(new ClientRequestReceiver(null)); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); - final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, - "?ELhAWDLM1hwm8bhU0UT4", Unpooled.buffer()); + final DefaultFullHttpRequest request = new DefaultFullHttpRequest( + HttpVersion.HTTP_1_1, HttpMethod.POST, "?ELhAWDLM1hwm8bhU0UT4", Unpooled.buffer()); // Write the message and save a copy channel.writeInbound(request); @@ -300,11 +311,15 @@ void setStatusCategoryForHttpPipelining() { channel.attr(HttpLifecycleChannelHandler.ATTR_HTTP_PIPELINE_REJECT).set(Boolean.TRUE); // Fire completion event - channel.pipeline().fireUserEventTriggered(new CompleteEvent(CompleteReason.PIPELINE_REJECT, request, - new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST))); + channel.pipeline() + .fireUserEventTriggered(new CompleteEvent( + CompleteReason.PIPELINE_REJECT, + request, + new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST))); channel.close(); - assertEquals(ZuulStatusCategory.FAILURE_CLIENT_PIPELINE_REJECT, + assertEquals( + ZuulStatusCategory.FAILURE_CLIENT_PIPELINE_REJECT, StatusCategoryUtils.getStatusCategory(inboundRequest.getContext())); } @@ -342,4 +357,3 @@ void headersAllCopied() { assertEquals(Arrays.asList("Duplicate1", "Duplicate2"), duplicates); } } - diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientResponseWriterTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientResponseWriterTest.java index 01141cd827..0087d400f8 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientResponseWriterTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientResponseWriterTest.java @@ -16,7 +16,6 @@ package com.netflix.zuul.netty.server; -import static com.google.common.truth.Truth.assertThat; import com.netflix.zuul.BasicRequestCompleteHandler; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; @@ -31,6 +30,8 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; +import static com.google.common.truth.Truth.assertThat; + @ExtendWith(MockitoExtension.class) class ClientResponseWriterTest { @@ -67,8 +68,8 @@ void allowExtensionForPremptingResponse() { final ClientResponseWriter responseWriter = new ClientResponseWriter(new BasicRequestCompleteHandler()) { @Override protected boolean shouldAllowPreemptiveResponse(Channel channel) { - StatusCategory status = StatusCategoryUtils.getStatusCategory( - ClientRequestReceiver.getRequestFromChannel(channel)); + StatusCategory status = + StatusCategoryUtils.getStatusCategory(ClientRequestReceiver.getRequestFromChannel(channel)); return status == customStatus; } }; diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/server/IoUringTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/server/IoUringTest.java index b33d7768ad..6a5d02198f 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/server/IoUringTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/server/IoUringTest.java @@ -16,10 +16,6 @@ package com.netflix.zuul.netty.server; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.mock; - import com.netflix.config.ConfigurationManager; import com.netflix.netty.common.metrics.EventLoopGroupMetrics; import com.netflix.netty.common.status.ServerStatusManager; @@ -32,30 +28,40 @@ import io.netty.incubator.channel.uring.IOUringSocketChannel; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.internal.PlatformDependent; - -import java.io.OutputStream; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.nio.charset.StandardCharsets; -import java.util.*; - import org.apache.commons.configuration.AbstractConfiguration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static java.util.concurrent.TimeUnit.SECONDS; import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; /* - Goals of this test: - 1) verify that the server starts - 2) verify that the server is listening on 2 ports - 3) verify that the correct number of IOUringSocketChannel's are initialized - 4) verify that the server stops + Goals of this test: + 1) verify that the server starts + 2) verify that the server is listening on 2 ports + 3) verify that the correct number of IOUringSocketChannel's are initialized + 4) verify that the server stops - */ +*/ @Disabled class IoUringTest { private static final Logger LOGGER = LoggerFactory.getLogger(IoUringTest.class); @@ -85,7 +91,8 @@ private void exerciseIoUringServer() throws Exception { Map> initializers = new HashMap<>(); - final List ioUringChannels = Collections.synchronizedList(new ArrayList()); + final List ioUringChannels = + Collections.synchronizedList(new ArrayList()); ChannelInitializer init = new ChannelInitializer() { @Override @@ -98,13 +105,12 @@ protected void initChannel(Channel ch) { }; initializers.put(new NamedSocketAddress("test", new InetSocketAddress(0)), init); // The port to channel map keys on the port, post bind. This should be unique even if InetAddress is same - initializers.put(new NamedSocketAddress("test2", new InetSocketAddress( 0)), init); + initializers.put(new NamedSocketAddress("test2", new InetSocketAddress(0)), init); - ClientConnectionsShutdown ccs = - new ClientConnectionsShutdown( - new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), - GlobalEventExecutor.INSTANCE, - /* discoveryClient= */ null); + ClientConnectionsShutdown ccs = new ClientConnectionsShutdown( + new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), + GlobalEventExecutor.INSTANCE, + /* discoveryClient= */ null); EventLoopGroupMetrics elgm = new EventLoopGroupMetrics(Spectator.globalRegistry()); EventLoopConfig elc = new EventLoopConfig() { @Override @@ -130,9 +136,7 @@ public int acceptorCount() { checkConnection(inetAddress.getPort()); }); - await() - .atMost(1, SECONDS) - .until(() -> ioUringChannels.size() == 2); + await().atMost(1, SECONDS).until(() -> ioUringChannels.size() == 2); s.stop(); @@ -160,8 +164,7 @@ private static void checkConnection(final int port) { } finally { try { sock.close(); - } - catch (Exception ignored) { + } catch (Exception ignored) { } } } diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/server/ServerTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/server/ServerTest.java index f9523792b1..eb7b36cf0f 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/server/ServerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/server/ServerTest.java @@ -16,11 +16,6 @@ package com.netflix.zuul.netty.server; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.awaitility.Awaitility.await; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.mock; - import com.netflix.config.ConfigurationManager; import com.netflix.netty.common.metrics.EventLoopGroupMetrics; import com.netflix.netty.common.status.ServerStatusManager; @@ -31,6 +26,11 @@ import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.GlobalEventExecutor; +import org.apache.commons.configuration.AbstractConfiguration; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.OutputStream; import java.net.InetSocketAddress; @@ -42,11 +42,13 @@ import java.util.List; import java.util.Map; -import org.apache.commons.configuration.AbstractConfiguration; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; /** * Tests for {@link Server}. @@ -77,12 +79,11 @@ protected void initChannel(final Channel ch) { }; initializers.put(new NamedSocketAddress("test", new InetSocketAddress(0)), init); // The port to channel map keys on the port, post bind. This should be unique even if InetAddress is same - initializers.put(new NamedSocketAddress("test2", new InetSocketAddress( 0)), init); - ClientConnectionsShutdown ccs = - new ClientConnectionsShutdown( - new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), - GlobalEventExecutor.INSTANCE, - /* discoveryClient= */ null); + initializers.put(new NamedSocketAddress("test2", new InetSocketAddress(0)), init); + ClientConnectionsShutdown ccs = new ClientConnectionsShutdown( + new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), + GlobalEventExecutor.INSTANCE, + /* discoveryClient= */ null); EventLoopGroupMetrics elgm = new EventLoopGroupMetrics(Spectator.globalRegistry()); EventLoopConfig elc = new EventLoopConfig() { @Override @@ -107,9 +108,7 @@ public int acceptorCount() { checkConnection(port); } - await() - .atMost(1, SECONDS) - .until(() -> nioChannels.size() == 2); + await().atMost(1, SECONDS).until(() -> nioChannels.size() == 2); s.stop(); @@ -136,8 +135,7 @@ private static void checkConnection(final int port) { } finally { try { sock.close(); - } - catch (Exception ignored) { + } catch (Exception ignored) { } } } diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/server/SocketAddressPropertyTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/server/SocketAddressPropertyTest.java index 95cd0310da..eab6a9c613 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/server/SocketAddressPropertyTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/server/SocketAddressPropertyTest.java @@ -16,22 +16,26 @@ package com.netflix.zuul.netty.server; -import static com.netflix.zuul.netty.server.SocketAddressProperty.BindType.ANY; -import static com.netflix.zuul.netty.server.SocketAddressProperty.BindType.ANY_LOCAL; -import static com.netflix.zuul.netty.server.SocketAddressProperty.BindType.IPV4_ANY; -import static com.netflix.zuul.netty.server.SocketAddressProperty.BindType.IPV4_LOCAL; -import static com.netflix.zuul.netty.server.SocketAddressProperty.BindType.IPV6_ANY; -import static com.netflix.zuul.netty.server.SocketAddressProperty.BindType.IPV6_LOCAL; -import static org.junit.jupiter.api.Assertions.*; - import com.netflix.zuul.netty.server.SocketAddressProperty.BindType; import io.netty.channel.unix.DomainSocketAddress; +import org.junit.jupiter.api.Test; + import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Arrays; -import org.junit.jupiter.api.Test; + +import static com.netflix.zuul.netty.server.SocketAddressProperty.BindType.ANY; +import static com.netflix.zuul.netty.server.SocketAddressProperty.BindType.ANY_LOCAL; +import static com.netflix.zuul.netty.server.SocketAddressProperty.BindType.IPV4_ANY; +import static com.netflix.zuul.netty.server.SocketAddressProperty.BindType.IPV4_LOCAL; +import static com.netflix.zuul.netty.server.SocketAddressProperty.BindType.IPV6_ANY; +import static com.netflix.zuul.netty.server.SocketAddressProperty.BindType.IPV6_LOCAL; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class SocketAddressPropertyTest { diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/server/http2/Http2ContentLengthEnforcingHandlerTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/server/http2/Http2ContentLengthEnforcingHandlerTest.java index 0bfa672289..10ba2ddbcf 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/server/http2/Http2ContentLengthEnforcingHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/server/http2/Http2ContentLengthEnforcingHandlerTest.java @@ -14,11 +14,8 @@ * limitations under the License. */ - package com.netflix.zuul.netty.server.http2; -import static com.google.common.truth.Truth.assertThat; - import io.netty.buffer.ByteBufUtil; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.channel.embedded.EmbeddedChannel; @@ -32,6 +29,8 @@ import io.netty.handler.codec.http2.Http2ResetFrame; import org.junit.jupiter.api.Test; +import static com.google.common.truth.Truth.assertThat; + class Http2ContentLengthEnforcingHandlerTest { @Test @@ -39,8 +38,7 @@ void failsOnMultipleContentLength() { EmbeddedChannel chan = new EmbeddedChannel(); chan.pipeline().addLast(new Http2ContentLengthEnforcingHandler()); - HttpRequest req = new DefaultHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.GET, ""); + HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); req.headers().add(HttpHeaderNames.CONTENT_LENGTH, 1); req.headers().add(HttpHeaderNames.CONTENT_LENGTH, 2); chan.writeInbound(req); @@ -54,8 +52,7 @@ void failsOnMixedContentLengthAndChunked() { EmbeddedChannel chan = new EmbeddedChannel(); chan.pipeline().addLast(new Http2ContentLengthEnforcingHandler()); - HttpRequest req = new DefaultHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.GET, ""); + HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); req.headers().add(HttpHeaderNames.CONTENT_LENGTH, 1); req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, "identity, chunked"); req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, "fzip"); @@ -70,8 +67,7 @@ void failsOnShortContentLength() { EmbeddedChannel chan = new EmbeddedChannel(); chan.pipeline().addLast(new Http2ContentLengthEnforcingHandler()); - DefaultHttpRequest req = new DefaultHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.GET, ""); + DefaultHttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); req.headers().add(HttpHeaderNames.CONTENT_LENGTH, 1); chan.writeInbound(req); @@ -98,8 +94,7 @@ void failsOnShortContent() { EmbeddedChannel chan = new EmbeddedChannel(); chan.pipeline().addLast(new Http2ContentLengthEnforcingHandler()); - DefaultHttpRequest req = new DefaultHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.GET, ""); + DefaultHttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); req.headers().add(HttpHeaderNames.CONTENT_LENGTH, 2); chan.writeInbound(req); @@ -119,5 +114,4 @@ void failsOnShortContent() { out = chan.readOutbound(); assertThat(out).isInstanceOf(Http2ResetFrame.class); } - } diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/server/http2/Http2OrHttpHandlerTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/server/http2/Http2OrHttpHandlerTest.java index 45628c5e97..c8bc77d359 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/server/http2/Http2OrHttpHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/server/http2/Http2OrHttpHandlerTest.java @@ -16,9 +16,6 @@ package com.netflix.zuul.netty.server.http2; -import static com.google.common.truth.Truth.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; - import com.netflix.netty.common.Http2ConnectionCloseHandler; import com.netflix.netty.common.Http2ConnectionExpiryHandler; import com.netflix.netty.common.channel.config.ChannelConfig; @@ -33,11 +30,13 @@ import io.netty.handler.ssl.ApplicationProtocolNames; import org.junit.jupiter.api.Test; +import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * @author Argha C * @since November 18, 2020 */ - class Http2OrHttpHandlerTest { @Test @@ -48,16 +47,19 @@ void swapInHttp2HandlerBasedOnALPN() throws Exception { channelConfig.add(new ChannelConfigValue<>(CommonChannelConfigKeys.maxHttp2HeaderListSize, 32768)); Http2ConnectionCloseHandler connectionCloseHandler = new Http2ConnectionCloseHandler(registry); - Http2ConnectionExpiryHandler connectionExpiryHandler = new Http2ConnectionExpiryHandler(100, 100, - 20 * 60 * 1000); - Http2MetricsChannelHandlers http2MetricsChannelHandlers = new Http2MetricsChannelHandlers(registry, "server", - "http2-443"); + Http2ConnectionExpiryHandler connectionExpiryHandler = + new Http2ConnectionExpiryHandler(100, 100, 20 * 60 * 1000); + Http2MetricsChannelHandlers http2MetricsChannelHandlers = + new Http2MetricsChannelHandlers(registry, "server", "http2-443"); final Http2OrHttpHandler http2OrHttpHandler = new Http2OrHttpHandler( - new Http2StreamInitializer(channel, (x) -> { - }, http2MetricsChannelHandlers, connectionCloseHandler, connectionExpiryHandler), + new Http2StreamInitializer( + channel, + (x) -> {}, + http2MetricsChannelHandlers, + connectionCloseHandler, + connectionExpiryHandler), channelConfig, - cp -> { - }); + cp -> {}); channel.pipeline().addLast("codec_placeholder", new DummyChannelHandler()); channel.pipeline().addLast(Http2OrHttpHandler.class.getSimpleName(), http2OrHttpHandler); @@ -70,5 +72,4 @@ void swapInHttp2HandlerBasedOnALPN() throws Exception { .isInstanceOf(Http2MultiplexHandler.class); assertEquals("HTTP/2", channel.attr(Http2OrHttpHandler.PROTOCOL_NAME).get()); } - } \ No newline at end of file diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/server/push/PushAuthHandlerTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/server/push/PushAuthHandlerTest.java index a5a945f744..f3302f1f63 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/server/push/PushAuthHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/server/push/PushAuthHandlerTest.java @@ -33,8 +33,8 @@ class PushAuthHandlerTest { void testIsInvalidOrigin() { ZuulPushAuthHandlerTest authHandler = new ZuulPushAuthHandlerTest(); - final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, - "/ws", Unpooled.buffer()); + final DefaultFullHttpRequest request = + new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/ws", Unpooled.buffer()); // Invalid input assertTrue(authHandler.isInvalidOrigin(request)); diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/server/push/PushRegistrationHandlerTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/server/push/PushRegistrationHandlerTest.java index 2445791c8f..155246b127 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/server/push/PushRegistrationHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/server/push/PushRegistrationHandlerTest.java @@ -15,12 +15,6 @@ */ package com.netflix.zuul.netty.server.push; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import com.google.common.util.concurrent.MoreExecutors; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; @@ -31,11 +25,6 @@ import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.util.concurrent.ScheduledFuture; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -46,6 +35,22 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + /** * @author Justin Guerra * @since 8/31/22 @@ -191,7 +196,6 @@ private void validateConnectionClosed(int expected, String messaged) { verify(channelFuture).addListener(ChannelFutureListener.CLOSE); } - private static class TestAuth implements PushUserAuth { private final boolean success; @@ -215,5 +219,4 @@ public String getClientIdentity() { return "whatever"; } } - } \ No newline at end of file diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/server/ssl/SslHandshakeInfoHandlerTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/server/ssl/SslHandshakeInfoHandlerTest.java index 8c675203ad..a81248c22b 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/server/ssl/SslHandshakeInfoHandlerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/server/ssl/SslHandshakeInfoHandlerTest.java @@ -16,26 +16,23 @@ package com.netflix.zuul.netty.server.ssl; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -import com.netflix.spectator.api.NoopRegistry; -import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.channel.embedded.EmbeddedChannel; -import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.util.SelfSignedCertificate; import io.netty.util.ReferenceCountUtil; -import java.nio.channels.ClosedChannelException; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLException; import org.junit.jupiter.api.Test; +import javax.net.ssl.SSLEngine; +import java.nio.channels.ClosedChannelException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + /** * Unit tests for {@link SslHandshakeInfoHandler}. */ @@ -49,8 +46,8 @@ void sslEarlyHandshakeFailure() throws Exception { EmbeddedChannel serverChannel = new EmbeddedChannel(); SelfSignedCertificate cert = new SelfSignedCertificate("localhorse"); - SSLEngine serverEngine = SslContextBuilder.forServer(cert.key(), cert.cert()).build() - .newEngine(serverChannel.alloc()); + SSLEngine serverEngine = + SslContextBuilder.forServer(cert.key(), cert.cert()).build().newEngine(serverChannel.alloc()); serverChannel.pipeline().addLast(new ChannelOutboundHandlerAdapter() { @Override diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/ssl/BaseSslContextFactoryTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/ssl/BaseSslContextFactoryTest.java index 14e91eb829..bc39e897fa 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/ssl/BaseSslContextFactoryTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/ssl/BaseSslContextFactoryTest.java @@ -16,11 +16,10 @@ package com.netflix.zuul.netty.ssl; -import static org.junit.jupiter.api.Assertions.assertEquals; - import io.netty.handler.ssl.SslProvider; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for {@link BaseSslContextFactory}. diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/ssl/ClientSslContextFactoryTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/ssl/ClientSslContextFactoryTest.java index 19653599dc..aeae78aa7a 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/ssl/ClientSslContextFactoryTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/ssl/ClientSslContextFactoryTest.java @@ -16,19 +16,17 @@ package com.netflix.zuul.netty.ssl; -import static com.google.common.truth.Truth.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.Arrays; -import java.util.List; - import com.netflix.spectator.api.DefaultRegistry; import io.netty.handler.ssl.OpenSslClientContext; import io.netty.handler.ssl.SslContext; import org.junit.jupiter.api.Test; import javax.net.ssl.SSLSessionContext; +import java.util.Arrays; +import java.util.List; +import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for {@link ClientSslContextFactory}. @@ -64,7 +62,7 @@ void testGetSslContext() { @Test void testGetProtocols() { ClientSslContextFactory factory = new ClientSslContextFactory(new DefaultRegistry()); - assertThat(factory.getProtocols()).isEqualTo(new String[] { "TLSv1.2" }); + assertThat(factory.getProtocols()).isEqualTo(new String[] {"TLSv1.2"}); } @Test diff --git a/zuul-core/src/test/java/com/netflix/zuul/netty/timeouts/OriginTimeoutManagerTest.java b/zuul-core/src/test/java/com/netflix/zuul/netty/timeouts/OriginTimeoutManagerTest.java index 8ee29c42fe..71f65942e0 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/netty/timeouts/OriginTimeoutManagerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/netty/timeouts/OriginTimeoutManagerTest.java @@ -16,10 +16,6 @@ package com.netflix.zuul.netty.timeouts; -import static com.netflix.zuul.netty.timeouts.OriginTimeoutManager.MAX_OUTBOUND_READ_TIMEOUT_MS; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; - import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; @@ -27,13 +23,18 @@ import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.origins.NettyOrigin; -import java.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import java.time.Duration; + +import static com.netflix.zuul.netty.timeouts.OriginTimeoutManager.MAX_OUTBOUND_READ_TIMEOUT_MS; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + /** * Origin Timeout Manager Test * @@ -45,6 +46,7 @@ class OriginTimeoutManagerTest { @Mock private NettyOrigin origin; + @Mock private HttpRequestMessage request; @@ -125,10 +127,8 @@ void computeReadTimeout_bolth_requestLower() { @Test void computeReadTimeout_bolth_enforceMax() { - requestConfig.set(CommonClientConfigKey.ReadTimeout, - (int) MAX_OUTBOUND_READ_TIMEOUT_MS.get() + 1000); - originConfig.set(CommonClientConfigKey.ReadTimeout, - (int) MAX_OUTBOUND_READ_TIMEOUT_MS.get() + 10000); + requestConfig.set(CommonClientConfigKey.ReadTimeout, (int) MAX_OUTBOUND_READ_TIMEOUT_MS.get() + 1000); + originConfig.set(CommonClientConfigKey.ReadTimeout, (int) MAX_OUTBOUND_READ_TIMEOUT_MS.get() + 10000); Duration timeout = originTimeoutManager.computeReadTimeout(request, 1); diff --git a/zuul-core/src/test/java/com/netflix/zuul/origins/OriginNameTest.java b/zuul-core/src/test/java/com/netflix/zuul/origins/OriginNameTest.java index 32cd06716e..e28d78455a 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/origins/OriginNameTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/origins/OriginNameTest.java @@ -14,14 +14,13 @@ * limitations under the License. */ - package com.netflix.zuul.origins; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.jupiter.api.Test; - class OriginNameTest { @Test void getAuthority() { @@ -38,7 +37,6 @@ void getMetrics() { assertEquals("WOODLY-doodly", trusted.getNiwsClientName()); } - @Test void equals() { OriginName name1 = OriginName.fromVipAndApp("woodly-doodly", "westerndigital"); diff --git a/zuul-core/src/test/java/com/netflix/zuul/passport/CurrentPassportTest.java b/zuul-core/src/test/java/com/netflix/zuul/passport/CurrentPassportTest.java index 5678c0e8fd..b2ea2a1906 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/passport/CurrentPassportTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/passport/CurrentPassportTest.java @@ -24,23 +24,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; -class CurrentPassportTest -{ +class CurrentPassportTest { @Test - void test_findEachPairOf_1pair() - { + void test_findEachPairOf_1pair() { CurrentPassport passport = CurrentPassport.parseFromToString( "CurrentPassport {start_ms=0, [+0=IN_REQ_HEADERS_RECEIVED, +5=FILTERS_INBOUND_START, +50=IN_REQ_LAST_CONTENT_RECEIVED, +200=MISC_IO_START, +250=MISC_IO_STOP, +350=FILTERS_INBOUND_END, +1117794707=NOW]}"); - List pairs = passport.findEachPairOf(PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.IN_REQ_LAST_CONTENT_RECEIVED); + List pairs = passport.findEachPairOf( + PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.IN_REQ_LAST_CONTENT_RECEIVED); assertEquals(1, pairs.size()); assertEquals(0, pairs.get(0).startTime); assertEquals(50, pairs.get(0).endTime); } @Test - void test_findEachPairOf_2pairs() - { + void test_findEachPairOf_2pairs() { CurrentPassport passport = CurrentPassport.parseFromToString( "CurrentPassport {start_ms=0, [+0=IN_REQ_HEADERS_RECEIVED, +5=FILTERS_INBOUND_START, +50=IN_REQ_LAST_CONTENT_RECEIVED, +200=MISC_IO_START, +250=MISC_IO_STOP, +300=MISC_IO_START, +350=FILTERS_INBOUND_END, +400=MISC_IO_STOP, +1117794707=NOW]}"); @@ -53,38 +51,37 @@ void test_findEachPairOf_2pairs() } @Test - void test_findEachPairOf_noneFound() - { + void test_findEachPairOf_noneFound() { CurrentPassport passport = CurrentPassport.parseFromToString( "CurrentPassport {start_ms=0, [+0=FILTERS_INBOUND_START, +200=MISC_IO_START, +1117794707=NOW]}"); - List pairs = passport.findEachPairOf(PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.IN_REQ_LAST_CONTENT_RECEIVED); + List pairs = passport.findEachPairOf( + PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.IN_REQ_LAST_CONTENT_RECEIVED); assertEquals(0, pairs.size()); } @Test - void test_findEachPairOf_endButNoStart() - { + void test_findEachPairOf_endButNoStart() { CurrentPassport passport = CurrentPassport.parseFromToString( "CurrentPassport {start_ms=0, [+0=FILTERS_INBOUND_START, +50=IN_REQ_LAST_CONTENT_RECEIVED, +200=MISC_IO_START, +1117794707=NOW]}"); - List pairs = passport.findEachPairOf(PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.IN_REQ_LAST_CONTENT_RECEIVED); + List pairs = passport.findEachPairOf( + PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.IN_REQ_LAST_CONTENT_RECEIVED); assertEquals(0, pairs.size()); } @Test - void test_findEachPairOf_wrongOrder() - { + void test_findEachPairOf_wrongOrder() { CurrentPassport passport = CurrentPassport.parseFromToString( "CurrentPassport {start_ms=0, [+0=FILTERS_INBOUND_START, +50=IN_REQ_LAST_CONTENT_RECEIVED, +200=MISC_IO_START, +250=IN_REQ_HEADERS_RECEIVED, +1117794707=NOW]}"); - List pairs = passport.findEachPairOf(PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.IN_REQ_LAST_CONTENT_RECEIVED); + List pairs = passport.findEachPairOf( + PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.IN_REQ_LAST_CONTENT_RECEIVED); assertEquals(0, pairs.size()); } @Test - void testFindBackwards() - { + void testFindBackwards() { CurrentPassport passport = CurrentPassport.parseFromToString( "CurrentPassport {start_ms=0, [+0=FILTERS_INBOUND_START, +50=IN_REQ_LAST_CONTENT_RECEIVED, +200=MISC_IO_START, +250=IN_REQ_HEADERS_RECEIVED, +1117794707=NOW]}"); diff --git a/zuul-core/src/test/java/com/netflix/zuul/stats/ErrorStatsDataTest.java b/zuul-core/src/test/java/com/netflix/zuul/stats/ErrorStatsDataTest.java index 290a7e320b..33ac4ae1a4 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/stats/ErrorStatsDataTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/stats/ErrorStatsDataTest.java @@ -16,13 +16,13 @@ package com.netflix.zuul.stats; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + /** * Unit tests for {@link ErrorStatsData}. */ @@ -38,7 +38,6 @@ void testUpdateStats() { assertEquals(2, sd.getCount()); } - @Test void testEquals() { ErrorStatsData sd = new ErrorStatsData("route", "test"); diff --git a/zuul-core/src/test/java/com/netflix/zuul/stats/ErrorStatsManagerTest.java b/zuul-core/src/test/java/com/netflix/zuul/stats/ErrorStatsManagerTest.java index dc6b36c858..1ccb236015 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/stats/ErrorStatsManagerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/stats/ErrorStatsManagerTest.java @@ -16,14 +16,15 @@ package com.netflix.zuul.stats; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.util.concurrent.ConcurrentHashMap; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; +import java.util.concurrent.ConcurrentHashMap; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * Unit tests for {@link ErrorStatsManager}. */ diff --git a/zuul-core/src/test/java/com/netflix/zuul/stats/RouteStatusCodeMonitorTest.java b/zuul-core/src/test/java/com/netflix/zuul/stats/RouteStatusCodeMonitorTest.java index 926e5280f3..54d34bbe11 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/stats/RouteStatusCodeMonitorTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/stats/RouteStatusCodeMonitorTest.java @@ -16,11 +16,11 @@ package com.netflix.zuul.stats; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; -import org.junit.jupiter.api.Test; - /** * Unit tests for {@link RouteStatusCodeMonitor}. */ diff --git a/zuul-core/src/test/java/com/netflix/zuul/stats/StatsManagerTest.java b/zuul-core/src/test/java/com/netflix/zuul/stats/StatsManagerTest.java index 6fdcc98055..1ddaa42198 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/stats/StatsManagerTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/stats/StatsManagerTest.java @@ -16,17 +16,21 @@ package com.netflix.zuul.stats; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.when; - import com.netflix.zuul.message.Headers; import com.netflix.zuul.message.http.HttpRequestInfo; -import java.util.concurrent.ConcurrentHashMap; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import java.util.concurrent.ConcurrentHashMap; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + /** * Unit tests for {@link StatsManager}. */ @@ -47,13 +51,10 @@ void testCollectRouteStats() { ConcurrentHashMap routeStatusMap = sm.routeStatusMap.get("test"); assertNotNull(routeStatusMap); - RouteStatusCodeMonitor routeStatusMonitor = routeStatusMap.get(status); - // 2nd request sm.collectRouteStats(route, status); - } @Test diff --git a/zuul-core/src/test/java/com/netflix/zuul/util/HttpUtilsTest.java b/zuul-core/src/test/java/com/netflix/zuul/util/HttpUtilsTest.java index 012c4a9049..f962f13622 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/util/HttpUtilsTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/util/HttpUtilsTest.java @@ -16,9 +16,6 @@ package com.netflix.zuul.util; -import static com.google.common.truth.Truth.assertThat; -import static org.junit.jupiter.api.Assertions.*; - import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.Headers; import com.netflix.zuul.message.ZuulMessage; @@ -30,6 +27,12 @@ import com.netflix.zuul.message.http.HttpResponseMessageImpl; import org.junit.jupiter.api.Test; +import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Unit tests for {@link HttpUtils}. */ @@ -103,7 +106,8 @@ void getBodySizeIfKnown_returnsResponseBodySize() { SessionContext context = new SessionContext(); Headers headers = new Headers(); HttpQueryParams queryParams = new HttpQueryParams(); - HttpRequestMessage request = new HttpRequestMessageImpl(context, "http", "GET", "/path", queryParams, headers, "127.0.0.1", "scheme", 6666, "server-name"); + HttpRequestMessage request = new HttpRequestMessageImpl( + context, "http", "GET", "/path", queryParams, headers, "127.0.0.1", "scheme", 6666, "server-name"); request.storeInboundRequest(); HttpResponseMessage response = new HttpResponseMessageImpl(context, request, 200); response.setBodyAsText("Hello world"); diff --git a/zuul-core/src/test/java/com/netflix/zuul/util/JsonUtilityTest.java b/zuul-core/src/test/java/com/netflix/zuul/util/JsonUtilityTest.java index 7bc12d333c..4d8c678b66 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/util/JsonUtilityTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/util/JsonUtilityTest.java @@ -16,12 +16,13 @@ package com.netflix.zuul.util; -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Unit tests for {@link JsonUtility}. @@ -81,7 +82,8 @@ void testNestedMapTwo() { jsonData.put("myNestedData", jsonData2); String json = JsonUtility.jsonFromMap(jsonData); - String expected = "{\"myKey\":\"myValue\",\"myNestedData\":{\"myNestedKey\":\"myNestedValue\",\"myNestedKey2\":\"myNestedValue2\"}}"; + String expected = + "{\"myKey\":\"myValue\",\"myNestedData\":{\"myNestedKey\":\"myNestedValue\",\"myNestedKey2\":\"myNestedValue2\"}}"; assertEquals(expected, json); } @@ -142,7 +144,8 @@ void testMapAndList() { jsonData.put("myNestedData", jsonData2); String json = JsonUtility.jsonFromMap(jsonData); - String expected = "{\"myKey\":\"myValue\",\"myNumbers\":[1,2,3,4],\"myNestedData\":{\"myNestedKey\":\"myNestedValue\",\"myNestedKey2\":\"myNestedValue2\",\"myStringNumbers\":[\"one\",\"two\",\"three\",\"four\"]}}"; + String expected = + "{\"myKey\":\"myValue\",\"myNumbers\":[1,2,3,4],\"myNestedData\":{\"myNestedKey\":\"myNestedValue\",\"myNestedKey2\":\"myNestedValue2\",\"myStringNumbers\":[\"one\",\"two\",\"three\",\"four\"]}}"; assertEquals(expected, json); } @@ -165,7 +168,8 @@ void testArrayOfMaps() { jsonData.put("messages", messages); String json = JsonUtility.jsonFromMap(jsonData); - String expected = "{\"messages\":[{\"a\":\"valueA1\",\"b\":\"valueB1\"},{\"a\":\"valueA2\",\"b\":\"valueB2\"}]}"; + String expected = + "{\"messages\":[{\"a\":\"valueA1\",\"b\":\"valueB1\"},{\"a\":\"valueA2\",\"b\":\"valueB2\"}]}"; assertEquals(expected, json); } diff --git a/zuul-core/src/test/java/com/netflix/zuul/util/VipUtilsTest.java b/zuul-core/src/test/java/com/netflix/zuul/util/VipUtilsTest.java index d2bb5e5cbb..4a4ab7b057 100644 --- a/zuul-core/src/test/java/com/netflix/zuul/util/VipUtilsTest.java +++ b/zuul-core/src/test/java/com/netflix/zuul/util/VipUtilsTest.java @@ -16,12 +16,11 @@ package com.netflix.zuul.util; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.junit.jupiter.api.Test; - /** * Unit tests for {@link VipUtils}. */ diff --git a/zuul-discovery/src/main/java/com/netflix/zuul/discovery/DiscoveryResult.java b/zuul-discovery/src/main/java/com/netflix/zuul/discovery/DiscoveryResult.java index 041288c9a4..3a7f9a982c 100644 --- a/zuul-discovery/src/main/java/com/netflix/zuul/discovery/DiscoveryResult.java +++ b/zuul-discovery/src/main/java/com/netflix/zuul/discovery/DiscoveryResult.java @@ -23,10 +23,11 @@ import com.netflix.loadbalancer.LoadBalancerStats; import com.netflix.loadbalancer.ServerStats; import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; + +import javax.annotation.Nullable; import java.util.Locale; import java.util.Objects; import java.util.Optional; -import javax.annotation.Nullable; /** * @author Argha C @@ -42,11 +43,13 @@ public final class DiscoveryResult implements ResolverResult { * This exists to allow for a semblance of type safety, and encourages avoiding null checks on the underlying Server, * thus representing a sentinel value for an empty resolution result. */ - public static final DiscoveryResult EMPTY = - DiscoveryResult.from(InstanceInfo.Builder.newBuilder() - .setAppName("undefined") - .setHostName("undefined") - .setPort(-1).build(), false); + public static final DiscoveryResult EMPTY = DiscoveryResult.from( + InstanceInfo.Builder.newBuilder() + .setAppName("undefined") + .setHostName("undefined") + .setPort(-1) + .build(), + false); public DiscoveryResult(DiscoveryEnabledServer server, LoadBalancerStats lbStats) { this.server = server; @@ -126,7 +129,6 @@ public String getTarget() { } } - public SimpleMetaInfo getMetaInfo() { return new SimpleMetaInfo(server.getMetaInfo()); } @@ -153,7 +155,7 @@ public DiscoveryEnabledServer getServer() { } @VisibleForTesting - ServerStats getServerStats(){ + ServerStats getServerStats() { return this.serverStats; } @@ -226,7 +228,6 @@ public int hashCode() { return Objects.hashCode(server); } - /** * Two instances are deemed identical if they wrap the same underlying discovery server instance. */ @@ -242,5 +243,4 @@ public boolean equals(Object obj) { final DiscoveryResult other = (DiscoveryResult) obj; return server.equals(other.server); } - } diff --git a/zuul-discovery/src/main/java/com/netflix/zuul/discovery/DynamicServerResolver.java b/zuul-discovery/src/main/java/com/netflix/zuul/discovery/DynamicServerResolver.java index 35860d8b86..e7b027d645 100644 --- a/zuul-discovery/src/main/java/com/netflix/zuul/discovery/DynamicServerResolver.java +++ b/zuul-discovery/src/main/java/com/netflix/zuul/discovery/DynamicServerResolver.java @@ -65,7 +65,7 @@ public DynamicServerResolver(DynamicServerListLoadBalancer loadBalancer) { @Override public void setListener(ResolverListener listener) { - if(this.listener != null) { + if (this.listener != null) { LOG.warn("Ignoring call to setListener, because a listener was already set"); return; } @@ -77,7 +77,9 @@ public void setListener(ResolverListener listener) { @Override public DiscoveryResult resolve(@Nullable Object key) { final Server server = loadBalancer.chooseServer(key); - return server!= null ? new DiscoveryResult((DiscoveryEnabledServer) server, loadBalancer.getLoadBalancerStats()) : DiscoveryResult.EMPTY; + return server != null + ? new DiscoveryResult((DiscoveryEnabledServer) server, loadBalancer.getLoadBalancerStats()) + : DiscoveryResult.EMPTY; } @Override @@ -91,7 +93,8 @@ public void shutdown() { } private static DynamicServerListLoadBalancer createLoadBalancer(IClientConfig clientConfig) { - //TODO(argha-c): Revisit this style of LB initialization post modularization. Ideally the LB should be pluggable. + // TODO(argha-c): Revisit this style of LB initialization post modularization. Ideally the LB should be + // pluggable. // Use a hard coded string for the LB default name to avoid a dependency on Ribbon classes. String loadBalancerClassName = @@ -100,7 +103,9 @@ private static DynamicServerListLoadBalancer createLoadBalancer(IClientConfig DynamicServerListLoadBalancer lb; try { Class clazz = Class.forName(loadBalancerClassName); - lb = clazz.asSubclass(DynamicServerListLoadBalancer.class).getConstructor().newInstance(); + lb = clazz.asSubclass(DynamicServerListLoadBalancer.class) + .getConstructor() + .newInstance(); lb.initWithNiwsConfig(clientConfig); } catch (Exception e) { Throwables.throwIfUnchecked(e); @@ -115,7 +120,8 @@ void onUpdate(List oldList, List newList) { Set oldSet = new HashSet<>(oldList); Set newSet = new HashSet<>(newList); final List discoveryResults = Sets.difference(oldSet, newSet).stream() - .map(server -> new DiscoveryResult((DiscoveryEnabledServer) server, loadBalancer.getLoadBalancerStats())) + .map(server -> + new DiscoveryResult((DiscoveryEnabledServer) server, loadBalancer.getLoadBalancerStats())) .collect(Collectors.toList()); listener.onChange(discoveryResults); } diff --git a/zuul-discovery/src/main/java/com/netflix/zuul/discovery/NonDiscoveryServer.java b/zuul-discovery/src/main/java/com/netflix/zuul/discovery/NonDiscoveryServer.java index ea767b2c15..b5c4153023 100644 --- a/zuul-discovery/src/main/java/com/netflix/zuul/discovery/NonDiscoveryServer.java +++ b/zuul-discovery/src/main/java/com/netflix/zuul/discovery/NonDiscoveryServer.java @@ -17,6 +17,7 @@ package com.netflix.zuul.discovery; import com.netflix.loadbalancer.Server; + import java.util.Objects; /** diff --git a/zuul-discovery/src/main/java/com/netflix/zuul/discovery/ResolverResult.java b/zuul-discovery/src/main/java/com/netflix/zuul/discovery/ResolverResult.java index b7bda4a2d2..b3914127c7 100644 --- a/zuul-discovery/src/main/java/com/netflix/zuul/discovery/ResolverResult.java +++ b/zuul-discovery/src/main/java/com/netflix/zuul/discovery/ResolverResult.java @@ -22,10 +22,9 @@ * Wraps the result of a resolution attempt. * At this time, it doesn't encapsulate a collection of instances, but ideally should. */ - public interface ResolverResult { - //TODO(argha-c): This should ideally model returning a collection of host/port pairs. + // TODO(argha-c): This should ideally model returning a collection of host/port pairs. public String getHost(); public int getPort(); diff --git a/zuul-discovery/src/main/java/com/netflix/zuul/resolver/Resolver.java b/zuul-discovery/src/main/java/com/netflix/zuul/resolver/Resolver.java index 7104b13f9e..6437e36367 100644 --- a/zuul-discovery/src/main/java/com/netflix/zuul/resolver/Resolver.java +++ b/zuul-discovery/src/main/java/com/netflix/zuul/resolver/Resolver.java @@ -30,7 +30,7 @@ public interface Resolver { * can narrow this down to be nullable. * @return the result of a resolver lookup */ - //TODO(argha-c) Param needs to be typed, once the ribbon LB lookup API is figured out. + // TODO(argha-c) Param needs to be typed, once the ribbon LB lookup API is figured out. T resolve(Object key); /** diff --git a/zuul-discovery/src/test/java/com/netflix/zuul/discovery/DiscoveryResultTest.java b/zuul-discovery/src/test/java/com/netflix/zuul/discovery/DiscoveryResultTest.java index ce8afcc835..394cca1890 100644 --- a/zuul-discovery/src/test/java/com/netflix/zuul/discovery/DiscoveryResultTest.java +++ b/zuul-discovery/src/test/java/com/netflix/zuul/discovery/DiscoveryResultTest.java @@ -16,9 +16,6 @@ package com.netflix.zuul.discovery; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - import com.google.common.truth.Truth; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.Builder; @@ -27,9 +24,13 @@ import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import com.netflix.loadbalancer.Server; import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; -import java.util.Optional; import org.junit.jupiter.api.Test; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + class DiscoveryResultTest { @Test @@ -57,11 +58,13 @@ void serverStatsCacheForSameServer() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("serverstats-cache") .setHostName("serverstats-cache") - .setPort(7777).build(); + .setPort(7777) + .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false); final DiscoveryEnabledServer serverSecure = new DiscoveryEnabledServer(instanceInfo, true); - final DynamicServerListLoadBalancer lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); + final DynamicServerListLoadBalancer lb = + new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); final DiscoveryResult result1 = new DiscoveryResult(serverSecure, lb.getLoadBalancerStats()); @@ -74,15 +77,18 @@ void serverStatsDifferForDifferentServer() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("serverstats-cache") .setHostName("serverstats-cache") - .setPort(7777).build(); + .setPort(7777) + .build(); final InstanceInfo otherInstance = Builder.newBuilder() .setAppName("serverstats-cache-2") .setHostName("serverstats-cache-2") - .setPort(7777).build(); + .setPort(7777) + .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false); final DiscoveryEnabledServer serverSecure = new DiscoveryEnabledServer(otherInstance, false); - final DynamicServerListLoadBalancer lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); + final DynamicServerListLoadBalancer lb = + new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); final DiscoveryResult result1 = new DiscoveryResult(serverSecure, lb.getLoadBalancerStats()); @@ -97,10 +103,12 @@ void ipAddrV4FromInstanceInfo() { .setAppName("ipAddrv4") .setHostName("ipAddrv4") .setIPAddr(ipAddr) - .setPort(7777).build(); + .setPort(7777) + .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false); - final DynamicServerListLoadBalancer lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); + final DynamicServerListLoadBalancer lb = + new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); Truth.assertThat(result.getIPAddr()).isEqualTo(Optional.of(ipAddr)); @@ -111,10 +119,12 @@ void ipAddrEmptyForIncompleteInstanceInfo() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("ipAddrMissing") .setHostName("ipAddrMissing") - .setPort(7777).build(); + .setPort(7777) + .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false); - final DynamicServerListLoadBalancer lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); + final DynamicServerListLoadBalancer lb = + new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); Truth.assertThat(result.getIPAddr()).isEqualTo(Optional.empty()); @@ -125,12 +135,14 @@ void sameUnderlyingInstanceInfoEqualsSameResult() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("server-equality") .setHostName("server-equality") - .setPort(7777).build(); + .setPort(7777) + .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false); final DiscoveryEnabledServer otherServer = new DiscoveryEnabledServer(instanceInfo, false); - final DynamicServerListLoadBalancer lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); + final DynamicServerListLoadBalancer lb = + new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); final DiscoveryResult otherResult = new DiscoveryResult(otherServer, lb.getLoadBalancerStats()); @@ -143,16 +155,19 @@ void serverInstancesExposingDiffPortsAreNotEqual() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("server-equality") .setHostName("server-equality") - .setPort(7777).build(); + .setPort(7777) + .build(); final InstanceInfo otherPort = Builder.newBuilder() .setAppName("server-equality") .setHostName("server-equality") - .setPort(9999).build(); + .setPort(9999) + .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false); - final DiscoveryEnabledServer otherServer = new DiscoveryEnabledServer(otherPort, false); + final DiscoveryEnabledServer otherServer = new DiscoveryEnabledServer(otherPort, false); - final DynamicServerListLoadBalancer lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); + final DynamicServerListLoadBalancer lb = + new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); final DiscoveryResult otherResult = new DiscoveryResult(otherServer, lb.getLoadBalancerStats()); @@ -177,7 +192,8 @@ void securePortMustCheckInstanceInfo() { final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, true); final DiscoveryEnabledServer secureServer = new DiscoveryEnabledServer(secureEnabled, true); - final DynamicServerListLoadBalancer lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); + final DynamicServerListLoadBalancer lb = + new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); final DiscoveryResult secure = new DiscoveryResult(secureServer, lb.getLoadBalancerStats()); diff --git a/zuul-discovery/src/test/java/com/netflix/zuul/discovery/DynamicServerResolverTest.java b/zuul-discovery/src/test/java/com/netflix/zuul/discovery/DynamicServerResolverTest.java index 2343f61cea..3574a12f71 100644 --- a/zuul-discovery/src/test/java/com/netflix/zuul/discovery/DynamicServerResolverTest.java +++ b/zuul-discovery/src/test/java/com/netflix/zuul/discovery/DynamicServerResolverTest.java @@ -24,12 +24,11 @@ import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; import com.netflix.zuul.resolver.ResolverListener; -import java.security.cert.TrustAnchor; -import java.util.List; import org.junit.jupiter.api.Test; -class DynamicServerResolverTest { +import java.util.List; +class DynamicServerResolverTest { @Test void verifyListenerUpdates() { @@ -69,7 +68,8 @@ public List updatedList() { resolver.onUpdate(ImmutableList.of(server1, server2), ImmutableList.of()); - Truth.assertThat(listener.updatedList()).containsExactly(new DiscoveryResult(server1), new DiscoveryResult(server2)); + Truth.assertThat(listener.updatedList()) + .containsExactly(new DiscoveryResult(server1), new DiscoveryResult(server2)); } @Test diff --git a/zuul-groovy/src/main/java/com/netflix/zuul/groovy/GroovyCompiler.java b/zuul-groovy/src/main/java/com/netflix/zuul/groovy/GroovyCompiler.java index 76fb7dd547..25470ae7f2 100644 --- a/zuul-groovy/src/main/java/com/netflix/zuul/groovy/GroovyCompiler.java +++ b/zuul-groovy/src/main/java/com/netflix/zuul/groovy/GroovyCompiler.java @@ -63,4 +63,3 @@ public Class compile(File file) throws IOException { return groovyClass; } } - diff --git a/zuul-groovy/src/main/java/com/netflix/zuul/scriptManager/FilterInfo.java b/zuul-groovy/src/main/java/com/netflix/zuul/scriptManager/FilterInfo.java index 0483a67ba9..c980e543d4 100644 --- a/zuul-groovy/src/main/java/com/netflix/zuul/scriptManager/FilterInfo.java +++ b/zuul-groovy/src/main/java/com/netflix/zuul/scriptManager/FilterInfo.java @@ -17,15 +17,15 @@ import com.netflix.zuul.filters.FilterType; +import javax.annotation.concurrent.ThreadSafe; import java.util.Date; import java.util.concurrent.atomic.AtomicBoolean; -import javax.annotation.concurrent.ThreadSafe; /** * Representation of a ZuulFilter for representing and storing in a database */ @ThreadSafe -public class FilterInfo implements Comparable{ +public class FilterInfo implements Comparable { private final String filter_id; private final String filter_name; @@ -78,7 +78,6 @@ public String getFilterCode() { return filter_code; } - /** * @return the name of the property to disable the filter. */ @@ -93,19 +92,17 @@ public FilterType getFilterType() { return filter_type; } - @Override public String toString() { - return "FilterInfo{" + - "filter_id='" + filter_id + '\'' + - ", filter_name='" + filter_name + '\'' + - ", filter_type='" + filter_type + '\'' + - ", revision=" + revision + - ", creationDate=" + creationDate + - ", isActive=" + isActive + - ", isCanary=" + isCanary + - ", application_name=" + application_name + - '}'; + return "FilterInfo{" + "filter_id='" + + filter_id + '\'' + ", filter_name='" + + filter_name + '\'' + ", filter_type='" + + filter_type + '\'' + ", revision=" + + revision + ", creationDate=" + + creationDate + ", isActive=" + + isActive + ", isCanary=" + + isCanary + ", application_name=" + + application_name + '}'; } /** @@ -139,7 +136,6 @@ public FilterInfo( this.filter_order = filter_order; this.filter_disablePropertyName = disablePropertyName; this.application_name = application_name; - } /** @@ -175,7 +171,6 @@ public boolean isCanary() { return isCanary.get(); } - /** * * @return unique key for the filter @@ -254,10 +249,9 @@ public int hashCode() { @Override public int compareTo(FilterInfo filterInfo) { - if(filterInfo.getFilterName().equals(this.getFilterName())){ + if (filterInfo.getFilterName().equals(this.getFilterName())) { return filterInfo.creationDate.compareTo(getCreationDate()); } return filterInfo.getFilterName().compareTo(this.getFilterName()); } - } diff --git a/zuul-groovy/src/main/java/com/netflix/zuul/scriptManager/FilterVerifier.java b/zuul-groovy/src/main/java/com/netflix/zuul/scriptManager/FilterVerifier.java index 7d411849d8..d59599341d 100644 --- a/zuul-groovy/src/main/java/com/netflix/zuul/scriptManager/FilterVerifier.java +++ b/zuul-groovy/src/main/java/com/netflix/zuul/scriptManager/FilterVerifier.java @@ -51,10 +51,17 @@ public FilterInfo verifyFilter(String sFilterCode) checkZuulFilterInstance(instance); BaseFilter filter = (BaseFilter) instance; + String filter_id = FilterInfo.buildFilterID( + ZuulApplicationInfo.getApplicationName(), filter.filterType(), groovyClass.getSimpleName()); - String filter_id = FilterInfo.buildFilterID(ZuulApplicationInfo.getApplicationName(), filter.filterType(), groovyClass.getSimpleName()); - - return new FilterInfo(filter_id, sFilterCode, filter.filterType(), groovyClass.getSimpleName(), filter.disablePropertyName(), "" + filter.filterOrder(), ZuulApplicationInfo.getApplicationName()); + return new FilterInfo( + filter_id, + sFilterCode, + filter.filterType(), + groovyClass.getSimpleName(), + filter.disablePropertyName(), + "" + filter.filterOrder(), + ZuulApplicationInfo.getApplicationName()); } Object instantiateClass(Class groovyClass) throws InstantiationException, IllegalAccessException { @@ -71,11 +78,8 @@ void checkZuulFilterInstance(Object zuulFilter) throws InstantiationException { * compiles the Groovy source code * */ - public Class compileGroovy(String sFilterCode) - throws CompilationFailedException { + public Class compileGroovy(String sFilterCode) throws CompilationFailedException { GroovyClassLoader loader = new GroovyClassLoader(); return loader.parseClass(sFilterCode); } } - - diff --git a/zuul-groovy/src/test/java/com/netflix/zuul/groovy/GroovyCompilerTest.java b/zuul-groovy/src/test/java/com/netflix/zuul/groovy/GroovyCompilerTest.java index e8ed4bec47..e94d950a76 100644 --- a/zuul-groovy/src/test/java/com/netflix/zuul/groovy/GroovyCompilerTest.java +++ b/zuul-groovy/src/test/java/com/netflix/zuul/groovy/GroovyCompilerTest.java @@ -16,17 +16,16 @@ package com.netflix.zuul.groovy; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.spy; - import groovy.lang.GroovyObject; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * Unit tests for {@link GroovyCompiler}. */ @@ -41,13 +40,13 @@ void testLoadGroovyFromString() { try { String code = "class test { public String hello(){return \"hello\" } } "; - Class clazz = compiler.compile(code,"test"); + Class clazz = compiler.compile(code, "test"); assertNotNull(clazz); - assertEquals("test",clazz.getName()); + assertEquals("test", clazz.getName()); GroovyObject groovyObject = (GroovyObject) clazz.newInstance(); Object[] args = {}; - String s = (String) groovyObject.invokeMethod("hello",args); - assertEquals("hello",s); + String s = (String) groovyObject.invokeMethod("hello", args); + assertEquals("hello", s); } catch (Exception e) { assertFalse(true); } diff --git a/zuul-groovy/src/test/java/com/netflix/zuul/groovy/GroovyFileFilterTest.java b/zuul-groovy/src/test/java/com/netflix/zuul/groovy/GroovyFileFilterTest.java index dcd1dffac3..3ce510f51f 100644 --- a/zuul-groovy/src/test/java/com/netflix/zuul/groovy/GroovyFileFilterTest.java +++ b/zuul-groovy/src/test/java/com/netflix/zuul/groovy/GroovyFileFilterTest.java @@ -16,11 +16,12 @@ package com.netflix.zuul.groovy; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; import java.io.File; -import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit tests for {@link GroovyFileFilter}. @@ -32,7 +33,7 @@ void testGroovyFileFilter() { GroovyFileFilter filter = new GroovyFileFilter(); - assertFalse(filter.accept(new File("/"),"file.mikey")); - assertTrue(filter.accept(new File("/"),"file.groovy")); + assertFalse(filter.accept(new File("/"), "file.mikey")); + assertTrue(filter.accept(new File("/"), "file.groovy")); } } diff --git a/zuul-groovy/src/test/java/com/netflix/zuul/scriptManager/FilterVerifierTest.java b/zuul-groovy/src/test/java/com/netflix/zuul/scriptManager/FilterVerifierTest.java index 032c895db9..7b9fecdd61 100644 --- a/zuul-groovy/src/test/java/com/netflix/zuul/scriptManager/FilterVerifierTest.java +++ b/zuul-groovy/src/test/java/com/netflix/zuul/scriptManager/FilterVerifierTest.java @@ -16,98 +16,97 @@ package com.netflix.zuul.scriptManager; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - import com.netflix.zuul.filters.FilterType; import org.codehaus.groovy.control.CompilationFailedException; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Unit tests for {@link FilterVerifier}. */ class FilterVerifierTest { - private final String sGoodGroovyScriptFilter = "import com.netflix.zuul.filters.*\n" + - "import com.netflix.zuul.context.*\n" + - "import com.netflix.zuul.message.*\n" + - "import com.netflix.zuul.message.http.*\n" + - "\n" + - "class filter extends BaseSyncFilter {\n" + - "\n" + - " FilterType filterType() {\n" + - " return FilterType.INBOUND\n" + - " }\n" + - "\n" + - " int filterOrder() {\n" + - " return 1\n" + - " }\n" + - "\n" + - " boolean shouldFilter(HttpRequestMessage req) {\n" + - " return true\n" + - " }\n" + - "\n" + - " HttpRequestMessage apply(HttpRequestMessage req) {\n" + - " return null\n" + - " }\n" + - "\n" + - "\n" + - "}"; - - private final String sNotZuulFilterGroovy = "import com.netflix.zuul.filters.*\n" + - "import com.netflix.zuul.context.*\n" + - "import com.netflix.zuul.message.*\n" + - "import com.netflix.zuul.message.http.*\n" + - "\n" + - "class filter {\n" + - "\n" + - " FilterType filterType() {\n" + - " return FilterType.INBOUND\n" + - " }\n" + - "\n" + - " int filterOrder() {\n" + - " return 1\n" + - " }\n" + - "\n" + - " boolean shouldFilter(SessionContext ctx) {\n" + - " return true\n" + - " }\n" + - "\n" + - " SessionContext apply(SessionContext ctx) {\n" + - " return null\n" + - " }\n" + - "\n" + - "\n" + - "}"; - - private final String sCompileFailCode = "import com.netflix.zuul.filters.*\n" + - "import com.netflix.zuul.context.*\n" + - "import com.netflix.zuul.message.*\n" + - "import com.netflix.zuul.message.http.*\n" + - "\n" + - "ccclass filter extends BaseSyncFilter {\n" + - "\n" + - " FilterType filterType() {\n" + - " return FilterType.INBOUND\n" + - " }\n" + - "\n" + - " int filterOrder() {\n" + - " return 1\n" + - " }\n" + - "\n" + - " boolean shouldFilter(HttpRequestMessage req) {\n" + - " return true\n" + - " }\n" + - "\n" + - " HttpRequestMessage apply(HttpRequestMessage req) {\n" + - " return null\n" + - " }\n" + - "\n" + - "\n" + - "}"; + private final String sGoodGroovyScriptFilter = + "import com.netflix.zuul.filters.*\n" + "import com.netflix.zuul.context.*\n" + + "import com.netflix.zuul.message.*\n" + + "import com.netflix.zuul.message.http.*\n" + + "\n" + + "class filter extends BaseSyncFilter {\n" + + "\n" + + " FilterType filterType() {\n" + + " return FilterType.INBOUND\n" + + " }\n" + + "\n" + + " int filterOrder() {\n" + + " return 1\n" + + " }\n" + + "\n" + + " boolean shouldFilter(HttpRequestMessage req) {\n" + + " return true\n" + + " }\n" + + "\n" + + " HttpRequestMessage apply(HttpRequestMessage req) {\n" + + " return null\n" + + " }\n" + + "\n" + + "\n" + + "}"; + + private final String sNotZuulFilterGroovy = + "import com.netflix.zuul.filters.*\n" + "import com.netflix.zuul.context.*\n" + + "import com.netflix.zuul.message.*\n" + + "import com.netflix.zuul.message.http.*\n" + + "\n" + + "class filter {\n" + + "\n" + + " FilterType filterType() {\n" + + " return FilterType.INBOUND\n" + + " }\n" + + "\n" + + " int filterOrder() {\n" + + " return 1\n" + + " }\n" + + "\n" + + " boolean shouldFilter(SessionContext ctx) {\n" + + " return true\n" + + " }\n" + + "\n" + + " SessionContext apply(SessionContext ctx) {\n" + + " return null\n" + + " }\n" + + "\n" + + "\n" + + "}"; + + private final String sCompileFailCode = + "import com.netflix.zuul.filters.*\n" + "import com.netflix.zuul.context.*\n" + + "import com.netflix.zuul.message.*\n" + + "import com.netflix.zuul.message.http.*\n" + + "\n" + + "ccclass filter extends BaseSyncFilter {\n" + + "\n" + + " FilterType filterType() {\n" + + " return FilterType.INBOUND\n" + + " }\n" + + "\n" + + " int filterOrder() {\n" + + " return 1\n" + + " }\n" + + "\n" + + " boolean shouldFilter(HttpRequestMessage req) {\n" + + " return true\n" + + " }\n" + + "\n" + + " HttpRequestMessage apply(HttpRequestMessage req) {\n" + + " return null\n" + + " }\n" + + "\n" + + "\n" + + "}"; @Test void testCompile() { @@ -116,7 +115,7 @@ void testCompile() { filterClass = FilterVerifier.INSTANCE.compileGroovy(sNotZuulFilterGroovy); assertNotNull(filterClass); - assertThrows(CompilationFailedException.class,() -> FilterVerifier.INSTANCE.compileGroovy(sCompileFailCode)); + assertThrows(CompilationFailedException.class, () -> FilterVerifier.INSTANCE.compileGroovy(sCompileFailCode)); } @Test @@ -131,21 +130,21 @@ void testZuulFilterInstance() throws Exception { assertNotNull(filterClass); Object filter2 = FilterVerifier.INSTANCE.instantiateClass(filterClass); - assertThrows(InstantiationException.class,() -> FilterVerifier.INSTANCE.checkZuulFilterInstance(filter2)); + assertThrows(InstantiationException.class, () -> FilterVerifier.INSTANCE.checkZuulFilterInstance(filter2)); } @Test void testVerify() throws Exception { FilterInfo filterInfo1 = FilterVerifier.INSTANCE.verifyFilter(sGoodGroovyScriptFilter); assertNotNull(filterInfo1); - assertEquals("null:filter:in",filterInfo1.getFilterID()); - assertEquals(FilterType.INBOUND,filterInfo1.getFilterType()); - assertEquals("filter",filterInfo1.getFilterName()); + assertEquals("null:filter:in", filterInfo1.getFilterID()); + assertEquals(FilterType.INBOUND, filterInfo1.getFilterType()); + assertEquals("filter", filterInfo1.getFilterName()); assertFalse(filterInfo1.isActive()); assertFalse(filterInfo1.isCanary()); - assertThrows(InstantiationException.class,() -> FilterVerifier.INSTANCE.verifyFilter(sNotZuulFilterGroovy)); + assertThrows(InstantiationException.class, () -> FilterVerifier.INSTANCE.verifyFilter(sNotZuulFilterGroovy)); - assertThrows(CompilationFailedException.class,() -> FilterVerifier.INSTANCE.verifyFilter(sCompileFailCode)); + assertThrows(CompilationFailedException.class, () -> FilterVerifier.INSTANCE.verifyFilter(sCompileFailCode)); } } diff --git a/zuul-guice/src/main/java/com/netflix/zuul/guice/GuiceFilterFactory.java b/zuul-guice/src/main/java/com/netflix/zuul/guice/GuiceFilterFactory.java index 2e73156560..b1907a7768 100644 --- a/zuul-guice/src/main/java/com/netflix/zuul/guice/GuiceFilterFactory.java +++ b/zuul-guice/src/main/java/com/netflix/zuul/guice/GuiceFilterFactory.java @@ -19,6 +19,7 @@ import com.google.inject.Injector; import com.netflix.zuul.FilterFactory; import com.netflix.zuul.filters.ZuulFilter; + import javax.inject.Inject; import javax.inject.Singleton; diff --git a/zuul-guice/src/main/java/com/netflix/zuul/init/ZuulFiltersModule.java b/zuul-guice/src/main/java/com/netflix/zuul/init/ZuulFiltersModule.java index 40011a49bf..7e5d1860b9 100644 --- a/zuul-guice/src/main/java/com/netflix/zuul/init/ZuulFiltersModule.java +++ b/zuul-guice/src/main/java/com/netflix/zuul/init/ZuulFiltersModule.java @@ -25,11 +25,11 @@ import com.netflix.zuul.FilterUsageNotifier; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.guice.GuiceFilterFactory; -import java.io.FilenameFilter; import org.apache.commons.configuration.AbstractConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.FilenameFilter; import java.io.IOException; import java.util.Arrays; import java.util.function.Predicate; @@ -58,14 +58,14 @@ protected void configure() { @Provides FilterFileManagerConfig provideFilterFileManagerConfig( - AbstractConfiguration config, FilenameFilter filenameFilter) { + AbstractConfiguration config, FilenameFilter filenameFilter) { // Get filter directories. String[] filterLocations = findFilterLocations(config); String[] filterClassNames = findClassNames(config); // Init the FilterStore. FilterFileManagerConfig filterConfig = - new FilterFileManagerConfig(filterLocations, filterClassNames, 5, filenameFilter); + new FilterFileManagerConfig(filterLocations, filterClassNames, 5, filenameFilter); return filterConfig; } @@ -75,17 +75,15 @@ String[] findClassNames(AbstractConfiguration config) { // Find individually-specified filter classes. String[] filterClassNamesStrArray = config.getStringArray("zuul.filters.classes"); - Stream classNameStream = Arrays.stream(filterClassNamesStrArray) - .map(String::trim) - .filter(blank.negate()); + Stream classNameStream = + Arrays.stream(filterClassNamesStrArray).map(String::trim).filter(blank.negate()); // Find filter classes in specified packages. String[] packageNamesStrArray = config.getStringArray("zuul.filters.packages"); ClassPath cp; try { cp = ClassPath.from(this.getClass().getClassLoader()); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException("Error attempting to read classpath to find filters!", e); } Stream packageStream = Arrays.stream(packageNamesStrArray) @@ -96,8 +94,8 @@ String[] findClassNames(AbstractConfiguration config) { .filter(ZuulFilter.class::isAssignableFrom) .map(Class::getCanonicalName); - - String[] filterClassNames = Stream.concat(classNameStream, packageStream).toArray(String[]::new); + String[] filterClassNames = + Stream.concat(classNameStream, packageStream).toArray(String[]::new); if (filterClassNames.length != 0) { LOG.info("Using filter classnames: "); for (String location : filterClassNames) { @@ -112,7 +110,7 @@ String[] findClassNames(AbstractConfiguration config) { String[] findFilterLocations(AbstractConfiguration config) { String[] locations = config.getStringArray("zuul.filters.locations"); if (locations == null) { - locations = new String[]{"inbound", "outbound", "endpoint"}; + locations = new String[] {"inbound", "outbound", "endpoint"}; } String[] filterLocations = Arrays.stream(locations) .map(String::trim) diff --git a/zuul-guice/src/test/java/com/netflix/zuul/guice/GuiceFilterFactoryIntegTest.java b/zuul-guice/src/test/java/com/netflix/zuul/guice/GuiceFilterFactoryIntegTest.java index 494543f3ae..0220ab08ba 100644 --- a/zuul-guice/src/test/java/com/netflix/zuul/guice/GuiceFilterFactoryIntegTest.java +++ b/zuul-guice/src/test/java/com/netflix/zuul/guice/GuiceFilterFactoryIntegTest.java @@ -16,12 +16,12 @@ package com.netflix.zuul.guice; -import static org.junit.jupiter.api.Assertions.assertNotNull; - import com.google.inject.Inject; import com.netflix.zuul.BaseInjectionIntegTest; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertNotNull; + class GuiceFilterFactoryIntegTest extends BaseInjectionIntegTest { @Inject @@ -29,7 +29,8 @@ class GuiceFilterFactoryIntegTest extends BaseInjectionIntegTest { @Test void ctorInjection() throws Exception { - TestGuiceConstructorFilter filter = (TestGuiceConstructorFilter) filterFactory.newInstance(TestGuiceConstructorFilter.class); + TestGuiceConstructorFilter filter = + (TestGuiceConstructorFilter) filterFactory.newInstance(TestGuiceConstructorFilter.class); assertNotNull(filter.injector); } @@ -40,5 +41,4 @@ void fieldInjection() throws Exception { assertNotNull(filter.injector); } - } \ No newline at end of file diff --git a/zuul-guice/src/test/java/com/netflix/zuul/guice/TestGuiceConstructorFilter.java b/zuul-guice/src/test/java/com/netflix/zuul/guice/TestGuiceConstructorFilter.java index 51cb3c6c9e..4e67214974 100644 --- a/zuul-guice/src/test/java/com/netflix/zuul/guice/TestGuiceConstructorFilter.java +++ b/zuul-guice/src/test/java/com/netflix/zuul/guice/TestGuiceConstructorFilter.java @@ -20,6 +20,7 @@ import com.netflix.zuul.filters.BaseSyncFilter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.message.ZuulMessage; + import javax.inject.Inject; public class TestGuiceConstructorFilter extends BaseSyncFilter { diff --git a/zuul-guice/src/test/java/com/netflix/zuul/guice/TestGuiceFieldFilter.java b/zuul-guice/src/test/java/com/netflix/zuul/guice/TestGuiceFieldFilter.java index 68d75ae8f8..431fb36c1a 100644 --- a/zuul-guice/src/test/java/com/netflix/zuul/guice/TestGuiceFieldFilter.java +++ b/zuul-guice/src/test/java/com/netflix/zuul/guice/TestGuiceFieldFilter.java @@ -20,6 +20,7 @@ import com.netflix.zuul.filters.BaseSyncFilter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.message.ZuulMessage; + import javax.inject.Inject; public class TestGuiceFieldFilter extends BaseSyncFilter { diff --git a/zuul-guice/src/test/java/com/netflix/zuul/init/InitTestModule.java b/zuul-guice/src/test/java/com/netflix/zuul/init/InitTestModule.java index 967bf3ea3d..03527df1d7 100644 --- a/zuul-guice/src/test/java/com/netflix/zuul/init/InitTestModule.java +++ b/zuul-guice/src/test/java/com/netflix/zuul/init/InitTestModule.java @@ -20,9 +20,10 @@ import com.netflix.config.ConfigurationManager; import com.netflix.spectator.api.NoopRegistry; import com.netflix.spectator.api.Registry; -import java.io.FilenameFilter; import org.apache.commons.configuration.AbstractConfiguration; +import java.io.FilenameFilter; + public class InitTestModule extends AbstractModule { @Override protected void configure() { @@ -30,5 +31,4 @@ protected void configure() { bind(FilenameFilter.class).toInstance((dir, name) -> false); bind(Registry.class).to(NoopRegistry.class); } - } diff --git a/zuul-guice/src/test/java/com/netflix/zuul/init/ZuulFiltersModuleIntegTest.java b/zuul-guice/src/test/java/com/netflix/zuul/init/ZuulFiltersModuleIntegTest.java index 095bc1468a..83a338dd15 100644 --- a/zuul-guice/src/test/java/com/netflix/zuul/init/ZuulFiltersModuleIntegTest.java +++ b/zuul-guice/src/test/java/com/netflix/zuul/init/ZuulFiltersModuleIntegTest.java @@ -16,16 +16,17 @@ package com.netflix.zuul.init; -import static org.junit.jupiter.api.Assertions.assertEquals; - import com.netflix.config.ConfigurationManager; import com.netflix.zuul.BaseInjectionIntegTest; import com.netflix.zuul.FilterFileManager.FilterFileManagerConfig; -import javax.inject.Inject; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import javax.inject.Inject; + +import static org.junit.jupiter.api.Assertions.assertEquals; + class ZuulFiltersModuleIntegTest extends BaseInjectionIntegTest { @Inject @@ -34,8 +35,8 @@ class ZuulFiltersModuleIntegTest extends BaseInjectionIntegTest { @BeforeAll static void before() { AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); - configuration.setProperty("zuul.filters.locations","inbound,outbound,endpoint"); - configuration.setProperty("zuul.filters.packages","com.netflix.zuul.init,com.netflix.zuul.init2"); + configuration.setProperty("zuul.filters.locations", "inbound,outbound,endpoint"); + configuration.setProperty("zuul.filters.packages", "com.netflix.zuul.init,com.netflix.zuul.init2"); } @Test @@ -43,12 +44,11 @@ void scanningWorks() { String[] filterLocations = filterFileManagerConfig.getDirectories(); String[] classNames = filterFileManagerConfig.getClassNames(); - assertEquals(3,filterLocations.length); - assertEquals("outbound",filterLocations[1]); + assertEquals(3, filterLocations.length); + assertEquals("outbound", filterLocations[1]); - assertEquals(2,classNames.length); - assertEquals("com.netflix.zuul.init.TestZuulFilter",classNames[0]); - assertEquals("com.netflix.zuul.init2.TestZuulFilter2",classNames[1]); + assertEquals(2, classNames.length); + assertEquals("com.netflix.zuul.init.TestZuulFilter", classNames[0]); + assertEquals("com.netflix.zuul.init2.TestZuulFilter2", classNames[1]); } - } diff --git a/zuul-guice/src/test/java/com/netflix/zuul/init/ZuulFiltersModuleTest.java b/zuul-guice/src/test/java/com/netflix/zuul/init/ZuulFiltersModuleTest.java index 151fe52bc2..1773f80f72 100644 --- a/zuul-guice/src/test/java/com/netflix/zuul/init/ZuulFiltersModuleTest.java +++ b/zuul-guice/src/test/java/com/netflix/zuul/init/ZuulFiltersModuleTest.java @@ -16,9 +16,6 @@ package com.netflix.zuul.init; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; - import com.netflix.zuul.init2.TestZuulFilter2; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.jupiter.api.Test; @@ -27,6 +24,9 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + @ExtendWith(MockitoExtension.class) class ZuulFiltersModuleTest { @@ -42,8 +42,8 @@ void testDefaultFilterLocations() { String[] filterLocations = module.findFilterLocations(configuration); - assertThat(filterLocations.length,equalTo(3)); - assertThat(filterLocations[1],equalTo("outbound")); + assertThat(filterLocations.length, equalTo(3)); + assertThat(filterLocations[1], equalTo("outbound")); } @Test @@ -52,17 +52,17 @@ void testEmptyFilterLocations() { String[] filterLocations = module.findFilterLocations(configuration); - assertThat(filterLocations.length,equalTo(0)); + assertThat(filterLocations.length, equalTo(0)); } @Test void testEmptyClassNames() { - Mockito.when(configuration.getStringArray("zuul.filters.classes")).thenReturn(new String[]{}); - Mockito.when(configuration.getStringArray("zuul.filters.packages")).thenReturn(new String[]{}); + Mockito.when(configuration.getStringArray("zuul.filters.classes")).thenReturn(new String[] {}); + Mockito.when(configuration.getStringArray("zuul.filters.packages")).thenReturn(new String[] {}); String[] classNames = module.findClassNames(configuration); - assertThat(classNames.length,equalTo(0)); + assertThat(classNames.length, equalTo(0)); } @Test @@ -71,14 +71,13 @@ void testClassNamesOnly() { Class expectedClass = TestZuulFilter.class; Mockito.when(configuration.getStringArray("zuul.filters.classes")) - .thenReturn(new String[]{"com.netflix.zuul.init.TestZuulFilter"}); - Mockito.when(configuration.getStringArray("zuul.filters.packages")).thenReturn(new String[]{}); + .thenReturn(new String[] {"com.netflix.zuul.init.TestZuulFilter"}); + Mockito.when(configuration.getStringArray("zuul.filters.packages")).thenReturn(new String[] {}); String[] classNames = module.findClassNames(configuration); - assertThat(classNames.length,equalTo(1)); - assertThat(classNames[0],equalTo(expectedClass.getCanonicalName())); - + assertThat(classNames.length, equalTo(1)); + assertThat(classNames[0], equalTo(expectedClass.getCanonicalName())); } @Test @@ -86,15 +85,14 @@ void testClassNamesPackagesOnly() { Class expectedClass = TestZuulFilter.class; - Mockito.when(configuration.getStringArray("zuul.filters.classes")).thenReturn(new String[]{}); + Mockito.when(configuration.getStringArray("zuul.filters.classes")).thenReturn(new String[] {}); Mockito.when(configuration.getStringArray("zuul.filters.packages")) - .thenReturn(new String[]{"com.netflix.zuul.init"}); + .thenReturn(new String[] {"com.netflix.zuul.init"}); String[] classNames = module.findClassNames(configuration); - assertThat(classNames.length,equalTo(1)); - assertThat(classNames[0],equalTo(expectedClass.getCanonicalName())); - + assertThat(classNames.length, equalTo(1)); + assertThat(classNames[0], equalTo(expectedClass.getCanonicalName())); } @Test @@ -102,16 +100,16 @@ void testMultiClasses() { Class expectedClass1 = TestZuulFilter.class; Class expectedClass2 = TestZuulFilter2.class; - Mockito.when(configuration.getStringArray("zuul.filters.classes")) - .thenReturn(new String[]{ - "com.netflix.zuul.init.TestZuulFilter","com.netflix.zuul.init2.TestZuulFilter2"}); + Mockito.when(configuration.getStringArray("zuul.filters.classes")).thenReturn(new String[] { + "com.netflix.zuul.init.TestZuulFilter", "com.netflix.zuul.init2.TestZuulFilter2" + }); Mockito.when(configuration.getStringArray("zuul.filters.packages")).thenReturn(new String[0]); String[] classNames = module.findClassNames(configuration); - assertThat(classNames.length,equalTo(2)); - assertThat(classNames[0],equalTo(expectedClass1.getCanonicalName())); - assertThat(classNames[1],equalTo(expectedClass2.getCanonicalName())); + assertThat(classNames.length, equalTo(2)); + assertThat(classNames[0], equalTo(expectedClass1.getCanonicalName())); + assertThat(classNames[1], equalTo(expectedClass2.getCanonicalName())); } @Test @@ -121,12 +119,12 @@ void testMultiPackages() { Mockito.when(configuration.getStringArray("zuul.filters.classes")).thenReturn(new String[0]); Mockito.when(configuration.getStringArray("zuul.filters.packages")) - .thenReturn(new String[]{"com.netflix.zuul.init","com.netflix.zuul.init2"}); + .thenReturn(new String[] {"com.netflix.zuul.init", "com.netflix.zuul.init2"}); String[] classNames = module.findClassNames(configuration); - assertThat(classNames.length,equalTo(2)); - assertThat(classNames[0],equalTo(expectedClass1.getCanonicalName())); - assertThat(classNames[1],equalTo(expectedClass2.getCanonicalName())); + assertThat(classNames.length, equalTo(2)); + assertThat(classNames[0], equalTo(expectedClass1.getCanonicalName())); + assertThat(classNames[1], equalTo(expectedClass2.getCanonicalName())); } } \ No newline at end of file diff --git a/zuul-integration-test/src/test/java/com/netflix/netty/common/metrics/CustomLeakDetector.java b/zuul-integration-test/src/test/java/com/netflix/netty/common/metrics/CustomLeakDetector.java index 7f0fe8fa60..a88ea017b0 100644 --- a/zuul-integration-test/src/test/java/com/netflix/netty/common/metrics/CustomLeakDetector.java +++ b/zuul-integration-test/src/test/java/com/netflix/netty/common/metrics/CustomLeakDetector.java @@ -26,8 +26,8 @@ public class CustomLeakDetector extends InstrumentedResourceLeakDetector { public static void assertZeroLeaks() { List leaks = GLOBAL_REGISTRY.stream() - .filter(detector -> detector.leakCounter.get() > 0) - .collect(Collectors.toList()); + .filter(detector -> detector.leakCounter.get() > 0) + .collect(Collectors.toList()); assertTrue(leaks.isEmpty(), "LEAKS DETECTED: " + leaks); } @@ -45,9 +45,6 @@ public CustomLeakDetector(Class resourceType, int samplingInterval, long maxA @Override public String toString() { - return "CustomLeakDetector: " - + this.resourceTypeName - + " leakCount=" - + leakCounter.get(); + return "CustomLeakDetector: " + this.resourceTypeName + " leakCount=" + leakCounter.get(); } } diff --git a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/IntegrationTest.java b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/IntegrationTest.java index f726745521..668c8d2078 100644 --- a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/IntegrationTest.java +++ b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/IntegrationTest.java @@ -64,9 +64,9 @@ import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.ok; @@ -82,26 +82,23 @@ class IntegrationTest { static { - System.setProperty("io.netty.customResourceLeakDetector", - CustomLeakDetector.class.getCanonicalName()); + System.setProperty("io.netty.customResourceLeakDetector", CustomLeakDetector.class.getCanonicalName()); } + private static Bootstrap bootstrap; + private static final int ZUUL_SERVER_PORT = findAvailableTcpPort(); - static private Bootstrap bootstrap; - static private final int ZUUL_SERVER_PORT = findAvailableTcpPort(); - - static private final Duration CLIENT_READ_TIMEOUT = Duration.ofMillis(3000); - static private final Duration ORIGIN_READ_TIMEOUT = Duration.ofMillis(1000); + private static final Duration CLIENT_READ_TIMEOUT = Duration.ofMillis(3000); + private static final Duration ORIGIN_READ_TIMEOUT = Duration.ofMillis(1000); private final String zuulBaseUri = "http://localhost:" + ZUUL_SERVER_PORT; private String pathSegment; private WireMockRuntimeInfo wmRuntimeInfo; @RegisterExtension static WireMockExtension wireMockExtension = WireMockExtension.newInstance() - .configureStaticDsl(true) - .options(wireMockConfig().dynamicPort()) - .build(); - + .configureStaticDsl(true) + .options(wireMockConfig().dynamicPort()) + .build(); @BeforeAll static void beforeAll() { @@ -127,7 +124,6 @@ static void afterAll() { assertZeroLeaks(); } - @BeforeEach void beforeEachTest(final WireMockRuntimeInfo wmRuntimeInfo) { this.pathSegment = randomPathSegment(); @@ -136,24 +132,25 @@ void beforeEachTest(final WireMockRuntimeInfo wmRuntimeInfo) { private static OkHttpClient setupOkHttpClient(final Protocol... protocols) { return new OkHttpClient.Builder() - .connectTimeout(30, TimeUnit.MILLISECONDS) - .readTimeout(CLIENT_READ_TIMEOUT) - .followRedirects(false) - .followSslRedirects(false) - .retryOnConnectionFailure(false) - .protocols(Arrays.asList(protocols)) - .build(); + .connectTimeout(30, TimeUnit.MILLISECONDS) + .readTimeout(CLIENT_READ_TIMEOUT) + .followRedirects(false) + .followSslRedirects(false) + .retryOnConnectionFailure(false) + .protocols(Arrays.asList(protocols)) + .build(); } - private Request.Builder setupRequestBuilder(final boolean requestBodyBuffering, final boolean responseBodyBuffering) { + private Request.Builder setupRequestBuilder( + final boolean requestBodyBuffering, final boolean responseBodyBuffering) { final HttpUrl url = new HttpUrl.Builder() - .scheme("http") - .host("localhost") - .port(ZUUL_SERVER_PORT) - .addPathSegment(pathSegment) - .addQueryParameter("bufferRequestBody", "" + requestBodyBuffering) - .addQueryParameter("bufferResponseBody", "" + responseBodyBuffering) - .build(); + .scheme("http") + .host("localhost") + .port(ZUUL_SERVER_PORT) + .addPathSegment(pathSegment) + .addQueryParameter("bufferRequestBody", "" + requestBodyBuffering) + .addQueryParameter("bufferResponseBody", "" + responseBodyBuffering) + .build(); return new Request.Builder().url(url); } @@ -163,10 +160,7 @@ static Stream arguments() { for (boolean requestBodyBuffering : ImmutableSet.of(Boolean.TRUE, Boolean.FALSE)) { for (boolean responseBodyBuffering : ImmutableSet.of(Boolean.TRUE, Boolean.FALSE)) { list.add(Arguments.of( - protocol.name(), - setupOkHttpClient(protocol), - requestBodyBuffering, - responseBodyBuffering)); + protocol.name(), setupOkHttpClient(protocol), requestBodyBuffering, responseBodyBuffering)); } } } @@ -175,16 +169,19 @@ static Stream arguments() { @ParameterizedTest @MethodSource("arguments") - void httpGetHappyPath(final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { + void httpGetHappyPath( + final String description, + final OkHttpClient okHttp, + final boolean requestBodyBuffering, + final boolean responseBodyBuffering) + throws Exception { final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - get(anyUrl()) - .willReturn( - ok() - .withBody("hello world"))); + wireMock.register(get(anyUrl()).willReturn(ok().withBody("hello world"))); - Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering).get().build(); + Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) + .get() + .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(200); assertThat(response.body().string()).isEqualTo("hello world"); @@ -193,17 +190,18 @@ void httpGetHappyPath(final String description, final OkHttpClient okHttp, final @ParameterizedTest @MethodSource("arguments") - void httpPostHappyPath(final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { + void httpPostHappyPath( + final String description, + final OkHttpClient okHttp, + final boolean requestBodyBuffering, + final boolean responseBodyBuffering) + throws Exception { final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - post(anyUrl()) - .willReturn( - ok() - .withBody("Thank you next"))); + wireMock.register(post(anyUrl()).willReturn(ok().withBody("Thank you next"))); Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) - .post(RequestBody.create("Simple POST request body".getBytes(StandardCharsets.UTF_8))) - .build(); + .post(RequestBody.create("Simple POST request body".getBytes(StandardCharsets.UTF_8))) + .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(200); assertThat(response.body().string()).isEqualTo("Thank you next"); @@ -212,18 +210,19 @@ void httpPostHappyPath(final String description, final OkHttpClient okHttp, fina @ParameterizedTest @MethodSource("arguments") - void httpPostWithInvalidHostHeader(final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { + void httpPostWithInvalidHostHeader( + final String description, + final OkHttpClient okHttp, + final boolean requestBodyBuffering, + final boolean responseBodyBuffering) + throws Exception { final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - post(anyUrl()) - .willReturn( - ok() - .withBody("Thank you next"))); + wireMock.register(post(anyUrl()).willReturn(ok().withBody("Thank you next"))); Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) - .addHeader("Host", "_invalid_hostname_") - .post(RequestBody.create("Simple POST request body".getBytes(StandardCharsets.UTF_8))) - .build(); + .addHeader("Host", "_invalid_hostname_") + .post(RequestBody.create("Simple POST request body".getBytes(StandardCharsets.UTF_8))) + .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(500); @@ -232,16 +231,20 @@ void httpPostWithInvalidHostHeader(final String description, final OkHttpClient @ParameterizedTest @MethodSource("arguments") - void httpGetFailsDueToOriginReadTimeout(final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { + void httpGetFailsDueToOriginReadTimeout( + final String description, + final OkHttpClient okHttp, + final boolean requestBodyBuffering, + final boolean responseBodyBuffering) + throws Exception { final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - get(anyUrl()) - .willReturn( - ok() - .withFixedDelay((int) ORIGIN_READ_TIMEOUT.toMillis() + 50) + wireMock.register(get(anyUrl()) + .willReturn(ok().withFixedDelay((int) ORIGIN_READ_TIMEOUT.toMillis() + 50) .withBody("Slow poke"))); - Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering).get().build(); + Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) + .get() + .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(504); assertThat(response.body().string()).isEqualTo(""); @@ -250,15 +253,18 @@ void httpGetFailsDueToOriginReadTimeout(final String description, final OkHttpCl @ParameterizedTest @MethodSource("arguments") - void httpGetFailsDueToMalformedResponseChunk(final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { + void httpGetFailsDueToMalformedResponseChunk( + final String description, + final OkHttpClient okHttp, + final boolean requestBodyBuffering, + final boolean responseBodyBuffering) + throws Exception { final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - get(anyUrl()) - .willReturn( - aResponse() - .withFault(Fault.MALFORMED_RESPONSE_CHUNK))); + wireMock.register(get(anyUrl()).willReturn(aResponse().withFault(Fault.MALFORMED_RESPONSE_CHUNK))); - Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering).get().build(); + Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) + .get() + .build(); Response response = okHttp.newCall(request).execute(); final int expectedStatusCode = (responseBodyBuffering) ? 504 : 200; assertThat(response.code()).isEqualTo(expectedStatusCode); @@ -267,15 +273,18 @@ void httpGetFailsDueToMalformedResponseChunk(final String description, final OkH @ParameterizedTest @MethodSource("arguments") - void zuulWillRetryHttpGetWhenOriginReturns500(final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { + void zuulWillRetryHttpGetWhenOriginReturns500( + final String description, + final OkHttpClient okHttp, + final boolean requestBodyBuffering, + final boolean responseBodyBuffering) + throws Exception { final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - get(anyUrl()) - .willReturn( - aResponse() - .withStatus(500))); + wireMock.register(get(anyUrl()).willReturn(aResponse().withStatus(500))); - Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering).get().build(); + Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) + .get() + .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(500); assertThat(response.body().string()).isEqualTo(""); @@ -284,15 +293,18 @@ void zuulWillRetryHttpGetWhenOriginReturns500(final String description, final Ok @ParameterizedTest @MethodSource("arguments") - void zuulWillRetryHttpGetWhenOriginReturns503(final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { + void zuulWillRetryHttpGetWhenOriginReturns503( + final String description, + final OkHttpClient okHttp, + final boolean requestBodyBuffering, + final boolean responseBodyBuffering) + throws Exception { final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - get(anyUrl()) - .willReturn( - aResponse() - .withStatus(503))); + wireMock.register(get(anyUrl()).willReturn(aResponse().withStatus(503))); - Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering).get().build(); + Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) + .get() + .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(503); assertThat(response.body().string()).isEqualTo(""); @@ -301,15 +313,18 @@ void zuulWillRetryHttpGetWhenOriginReturns503(final String description, final Ok @ParameterizedTest @MethodSource("arguments") - void httpGetReturnsStatus500DueToConnectionResetByPeer(final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { + void httpGetReturnsStatus500DueToConnectionResetByPeer( + final String description, + final OkHttpClient okHttp, + final boolean requestBodyBuffering, + final boolean responseBodyBuffering) + throws Exception { final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - get(anyUrl()) - .willReturn( - aResponse() - .withFault(Fault.CONNECTION_RESET_BY_PEER))); + wireMock.register(get(anyUrl()).willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER))); - Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering).get().build(); + Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) + .get() + .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(500); assertThat(response.body().string()).isEqualTo(""); @@ -318,17 +333,22 @@ void httpGetReturnsStatus500DueToConnectionResetByPeer(final String description, @ParameterizedTest @MethodSource("arguments") - void httpGet_ServerChunkedDribbleDelay(final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { + void httpGet_ServerChunkedDribbleDelay( + final String description, + final OkHttpClient okHttp, + final boolean requestBodyBuffering, + final boolean responseBodyBuffering) + throws Exception { final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - get(anyUrl()) - .willReturn( - aResponse() + wireMock.register(get(anyUrl()) + .willReturn(aResponse() .withStatus(200) .withBody("Hello world, is anybody listening?") .withChunkedDribbleDelay(10, (int) CLIENT_READ_TIMEOUT.toMillis() + 500))); - Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering).get().build(); + Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) + .get() + .build(); Response response = okHttp.newCall(request).execute(); final int expectedStatusCode = (responseBodyBuffering) ? 504 : 200; assertThat(response.code()).isEqualTo(expectedStatusCode); @@ -337,13 +357,17 @@ void httpGet_ServerChunkedDribbleDelay(final String description, final OkHttpCli @ParameterizedTest @MethodSource("arguments") - void blockRequestWithMultipleHostHeaders(final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { + void blockRequestWithMultipleHostHeaders( + final String description, + final OkHttpClient okHttp, + final boolean requestBodyBuffering, + final boolean responseBodyBuffering) + throws Exception { final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - get(anyUrl()) - .willReturn(aResponse().withStatus(200))); + wireMock.register(get(anyUrl()).willReturn(aResponse().withStatus(200))); - Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering).get() + Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) + .get() .addHeader("Host", "aaa.example.com") .addHeader("Host", "aaa.foobar.com") .build(); @@ -353,15 +377,12 @@ void blockRequestWithMultipleHostHeaders(final String description, final OkHttpC response.close(); } - @Test void deflateOnly() throws Exception { final String expectedResponseBody = TestUtil.COMPRESSIBLE_CONTENT; final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - get(anyUrl()) - .willReturn( - aResponse() + wireMock.register(get(anyUrl()) + .willReturn(aResponse() .withStatus(200) .withBody(expectedResponseBody) .withHeader("Content-Type", TestUtil.COMPRESSIBLE_CONTENT_TYPE))); @@ -389,10 +410,8 @@ void deflateOnly() throws Exception { void gzipOnly() throws Exception { final String expectedResponseBody = TestUtil.COMPRESSIBLE_CONTENT; final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - get(anyUrl()) - .willReturn( - aResponse() + wireMock.register(get(anyUrl()) + .willReturn(aResponse() .withStatus(200) .withBody(expectedResponseBody) .withHeader("Content-Type", TestUtil.COMPRESSIBLE_CONTENT_TYPE))); @@ -420,13 +439,11 @@ void brotliOnly() throws Throwable { Brotli.ensureAvailability(); final String expectedResponseBody = TestUtil.COMPRESSIBLE_CONTENT; final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - get(anyUrl()) - .willReturn( - aResponse() - .withStatus(200) - .withBody(expectedResponseBody) - .withHeader("Content-Type", TestUtil.COMPRESSIBLE_CONTENT_TYPE))); + wireMock.register(get(anyUrl()) + .willReturn(aResponse() + .withStatus(200) + .withBody(expectedResponseBody) + .withHeader("Content-Type", TestUtil.COMPRESSIBLE_CONTENT_TYPE))); URL url = new URL(zuulBaseUri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); @@ -441,8 +458,8 @@ void brotliOnly() throws Throwable { assertTrue(compressedData.length > 0); DirectDecompress decompressResult = DirectDecompress.decompress(compressedData); assertEquals(DecoderJNI.Status.DONE, decompressResult.getResultStatus()); - assertEquals("Hello Hello Hello Hello Hello", - new String(decompressResult.getDecompressedData(), TestUtil.CHARSET)); + assertEquals( + "Hello Hello Hello Hello Hello", new String(decompressResult.getDecompressedData(), TestUtil.CHARSET)); inputStream.close(); connection.disconnect(); @@ -452,10 +469,8 @@ void brotliOnly() throws Throwable { void noCompression() throws Exception { final String expectedResponseBody = TestUtil.COMPRESSIBLE_CONTENT; final WireMock wireMock = wmRuntimeInfo.getWireMock(); - wireMock.register( - get(anyUrl()) - .willReturn( - aResponse() + wireMock.register(get(anyUrl()) + .willReturn(aResponse() .withStatus(200) .withBody(expectedResponseBody) .withHeader("Content-Type", TestUtil.COMPRESSIBLE_CONTENT_TYPE))); @@ -488,8 +503,7 @@ private static int findAvailableTcpPort() { } } - static private void verifyResponseHeaders(final Response response) { + private static void verifyResponseHeaders(final Response response) { assertThat(response.header(HeaderNames.REQUEST_ID)).startsWith("RQ-"); } - } diff --git a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/Bootstrap.java b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/Bootstrap.java index d71704e2fb..8b0ba385fd 100644 --- a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/Bootstrap.java +++ b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/Bootstrap.java @@ -43,8 +43,7 @@ public void start() { server.start(); long startupDuration = System.nanoTime() - startNanos; - logger.info( - "Zuul: finished startup. Duration = {}ms", TimeUnit.NANOSECONDS.toMillis(startupDuration)); + logger.info("Zuul: finished startup. Duration = {}ms", TimeUnit.NANOSECONDS.toMillis(startupDuration)); // server.awaitTermination(); } catch (Throwable t) { exitCode = 1; diff --git a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/FilterLoaderProvider.java b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/FilterLoaderProvider.java index dc220dc0e4..00966c0d38 100644 --- a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/FilterLoaderProvider.java +++ b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/FilterLoaderProvider.java @@ -23,16 +23,15 @@ import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.integration.server.filters.InboundRoutesFilter; import com.netflix.zuul.integration.server.filters.NeedsBodyBufferedInboundFilter; +import com.netflix.zuul.integration.server.filters.NeedsBodyBufferedOutboundFilter; import com.netflix.zuul.integration.server.filters.RequestHeaderFilter; import com.netflix.zuul.integration.server.filters.ResponseHeaderFilter; -import com.netflix.zuul.integration.server.filters.NeedsBodyBufferedOutboundFilter; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; -public class FilterLoaderProvider - implements Provider { +public class FilterLoaderProvider implements Provider { private static final Set>> FILTER_TYPES; @@ -48,9 +47,7 @@ public class FilterLoaderProvider } public FilterLoader get() { - StaticFilterLoader loader = new StaticFilterLoader( - new DefaultFilterFactory(), - FILTER_TYPES); + StaticFilterLoader loader = new StaticFilterLoader(new DefaultFilterFactory(), FILTER_TYPES); return loader; } } diff --git a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/HeaderNames.java b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/HeaderNames.java index 5c3446dee8..2ad6b84972 100644 --- a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/HeaderNames.java +++ b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/HeaderNames.java @@ -17,7 +17,7 @@ package com.netflix.zuul.integration.server; public class HeaderNames { - private HeaderNames() { } + private HeaderNames() {} public static final String REQUEST_ID = "request-id"; } diff --git a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/OriginServerList.java b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/OriginServerList.java index 161198b661..ca286127ef 100644 --- a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/OriginServerList.java +++ b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/OriginServerList.java @@ -30,7 +30,7 @@ public class OriginServerList extends ConfigurationBasedServerList { protected List derive(String value) { List list = Lists.newArrayList(); if (!Strings.isNullOrEmpty(value)) { - for (String s: value.split(",")) { + for (String s : value.split(",")) { String[] hostAndPort = s.split(":"); String host = hostAndPort[0]; int port = Integer.parseInt(hostAndPort[1]); diff --git a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/ServerModule.java b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/ServerModule.java index ac44dfe2a8..25b52b10ca 100644 --- a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/ServerModule.java +++ b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/ServerModule.java @@ -23,7 +23,9 @@ import com.netflix.netty.common.status.ServerStatusManager; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; -import com.netflix.zuul.*; +import com.netflix.zuul.BasicRequestCompleteHandler; +import com.netflix.zuul.FilterLoader; +import com.netflix.zuul.RequestCompleteHandler; import com.netflix.zuul.context.SessionContextDecorator; import com.netflix.zuul.context.ZuulSessionContextDecorator; import com.netflix.zuul.filters.FilterRegistry; @@ -43,9 +45,9 @@ public class ServerModule extends AbstractModule { @Override protected void configure() { try { - ConfigurationManager.loadCascadedPropertiesFromResources("application"); + ConfigurationManager.loadCascadedPropertiesFromResources("application"); } catch (Exception ex) { - throw new RuntimeException("Error loading configuration: " + ex.getMessage(), ex); + throw new RuntimeException("Error loading configuration: " + ex.getMessage(), ex); } bind(FilenameFilter.class).to(NoFilenameFilter.class); @@ -67,13 +69,17 @@ protected void configure() { // general server bindings bind(ServerStatusManager.class); // health/discovery status - bind(SessionContextDecorator.class).to(ZuulSessionContextDecorator.class); // decorate new sessions when requests come in + bind(SessionContextDecorator.class) + .to(ZuulSessionContextDecorator.class); // decorate new sessions when requests come in bind(Registry.class).to(DefaultRegistry.class); // atlas metrics registry bind(RequestCompleteHandler.class).to(BasicRequestCompleteHandler.class); // metrics post-request completion bind(RequestMetricsPublisher.class).to(BasicRequestMetricsPublisher.class); // timings publisher // access logger, including request ID generator - bind(AccessLogPublisher.class).toInstance(new AccessLogPublisher("ACCESS", - (channel, httpRequest) -> ClientRequestReceiver.getRequestFromChannel(channel).getContext().getUUID())); + bind(AccessLogPublisher.class) + .toInstance(new AccessLogPublisher( + "ACCESS", (channel, httpRequest) -> ClientRequestReceiver.getRequestFromChannel(channel) + .getContext() + .getUUID())); } } diff --git a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/ServerStartup.java b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/ServerStartup.java index bf4c1dd03d..8dbaf12d2e 100644 --- a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/ServerStartup.java +++ b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/ServerStartup.java @@ -31,7 +31,14 @@ import com.netflix.zuul.FilterUsageNotifier; import com.netflix.zuul.RequestCompleteHandler; import com.netflix.zuul.context.SessionContextDecorator; -import com.netflix.zuul.netty.server.*; +import com.netflix.zuul.netty.server.BaseServerStartup; +import com.netflix.zuul.netty.server.DefaultEventLoopConfig; +import com.netflix.zuul.netty.server.DirectMemoryMonitor; +import com.netflix.zuul.netty.server.Http1MutualSslChannelInitializer; +import com.netflix.zuul.netty.server.NamedSocketAddress; +import com.netflix.zuul.netty.server.SocketAddressProperty; +import com.netflix.zuul.netty.server.ZuulDependencyKeys; +import com.netflix.zuul.netty.server.ZuulServerChannelInitializer; import com.netflix.zuul.netty.server.http2.Http2SslChannelInitializer; import com.netflix.zuul.netty.server.push.PushConnectionRegistry; import com.netflix.zuul.netty.ssl.BaseSslContextFactory; @@ -62,20 +69,37 @@ enum ServerType { SSE } - private static final String[] WWW_PROTOCOLS = new String[]{"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"}; + private static final String[] WWW_PROTOCOLS = new String[] {"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"}; private static final ServerType SERVER_TYPE = ServerType.HTTP; private final PushConnectionRegistry pushConnectionRegistry; -// private final SamplePushMessageSenderInitializer pushSenderInitializer; + // private final SamplePushMessageSenderInitializer pushSenderInitializer; @Inject - public ServerStartup(ServerStatusManager serverStatusManager, FilterLoader filterLoader, - SessionContextDecorator sessionCtxDecorator, FilterUsageNotifier usageNotifier, - RequestCompleteHandler reqCompleteHandler, Registry registry, - DirectMemoryMonitor directMemoryMonitor, EventLoopGroupMetrics eventLoopGroupMetrics, - EurekaClient discoveryClient, ApplicationInfoManager applicationInfoManager, - AccessLogPublisher accessLogPublisher, PushConnectionRegistry pushConnectionRegistry) { - super(serverStatusManager, filterLoader, sessionCtxDecorator, usageNotifier, reqCompleteHandler, registry, - directMemoryMonitor, eventLoopGroupMetrics, new DefaultEventLoopConfig(), discoveryClient, applicationInfoManager, + public ServerStartup( + ServerStatusManager serverStatusManager, + FilterLoader filterLoader, + SessionContextDecorator sessionCtxDecorator, + FilterUsageNotifier usageNotifier, + RequestCompleteHandler reqCompleteHandler, + Registry registry, + DirectMemoryMonitor directMemoryMonitor, + EventLoopGroupMetrics eventLoopGroupMetrics, + EurekaClient discoveryClient, + ApplicationInfoManager applicationInfoManager, + AccessLogPublisher accessLogPublisher, + PushConnectionRegistry pushConnectionRegistry) { + super( + serverStatusManager, + filterLoader, + sessionCtxDecorator, + usageNotifier, + reqCompleteHandler, + registry, + directMemoryMonitor, + eventLoopGroupMetrics, + new DefaultEventLoopConfig(), + discoveryClient, + applicationInfoManager, accessLogPublisher); this.pushConnectionRegistry = pushConnectionRegistry; // this.pushSenderInitializer = pushSenderInitializer; @@ -87,8 +111,7 @@ protected Map> chooseAddrsAndChannels( SocketAddress sockAddr; String metricId; { - @Deprecated - int port = new DynamicIntProperty("zuul.server.port.main", 7001).get(); + @Deprecated int port = new DynamicIntProperty("zuul.server.port.main", 7001).get(); sockAddr = new SocketAddressProperty("zuul.server.addr.main", "=" + port).getValue(); if (sockAddr instanceof InetSocketAddress) { metricId = String.valueOf(((InetSocketAddress) sockAddr).getPort()); @@ -101,8 +124,7 @@ protected Map> chooseAddrsAndChannels( SocketAddress pushSockAddr; { int pushPort = new DynamicIntProperty("zuul.server.port.http.push", 7008).get(); - pushSockAddr = new SocketAddressProperty( - "zuul.server.addr.http.push", "=" + pushPort).getValue(); + pushSockAddr = new SocketAddressProperty("zuul.server.addr.http.push", "=" + pushPort).getValue(); } String mainListenAddressName = "main"; @@ -114,22 +136,22 @@ protected Map> chooseAddrsAndChannels( * or directly on the internet. */ switch (SERVER_TYPE) { - /* The below settings can be used when running behind an ELB HTTP listener that terminates SSL for you - * and passes XFF headers. - */ + /* The below settings can be used when running behind an ELB HTTP listener that terminates SSL for you + * and passes XFF headers. + */ case HTTP: - channelConfig.set(CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.ALWAYS); + channelConfig.set( + CommonChannelConfigKeys.allowProxyHeadersWhen, + StripUntrustedProxyHeadersHandler.AllowWhen.ALWAYS); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, false); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, false); addrsToChannels.put( new NamedSocketAddress("http", sockAddr), - new ZuulServerChannelInitializer( - metricId, channelConfig, channelDependencies, clientChannels) { + new ZuulServerChannelInitializer(metricId, channelConfig, channelDependencies, clientChannels) { @Override - protected void addHttp1Handlers(ChannelPipeline pipeline) - { + protected void addHttp1Handlers(ChannelPipeline pipeline) { super.addHttp1Handlers(pipeline); pipeline.addLast(new HttpContentCompressor((CompressionOptions[]) null)); } @@ -137,36 +159,36 @@ protected void addHttp1Handlers(ChannelPipeline pipeline) logAddrConfigured(sockAddr); break; - /* The below settings can be used when running behind an ELB TCP listener with proxy protocol, terminating - * SSL in Zuul. - */ + /* The below settings can be used when running behind an ELB TCP listener with proxy protocol, terminating + * SSL in Zuul. + */ case HTTP2: sslConfig = ServerSslConfig.withDefaultCiphers( - loadFromResources("server.cert"), - loadFromResources("server.key"), - WWW_PROTOCOLS); + loadFromResources("server.cert"), loadFromResources("server.key"), WWW_PROTOCOLS); - channelConfig.set(CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); + channelConfig.set( + CommonChannelConfigKeys.allowProxyHeadersWhen, + StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.serverSslConfig, sslConfig); - channelConfig.set(CommonChannelConfigKeys.sslContextFactory, new BaseSslContextFactory(registry, sslConfig)); + channelConfig.set( + CommonChannelConfigKeys.sslContextFactory, new BaseSslContextFactory(registry, sslConfig)); addHttp2DefaultConfig(channelConfig, mainListenAddressName); addrsToChannels.put( new NamedSocketAddress("http2", sockAddr), - new Http2SslChannelInitializer( - metricId, channelConfig, channelDependencies, clientChannels)); + new Http2SslChannelInitializer(metricId, channelConfig, channelDependencies, clientChannels)); logAddrConfigured(sockAddr, sslConfig); break; - /* The below settings can be used when running behind an ELB TCP listener with proxy protocol, terminating - * SSL in Zuul. - * - * Can be tested using certs in resources directory: - * curl https://localhost:7001/test -vk --cert src/main/resources/ssl/client.cert:zuul123 --key src/main/resources/ssl/client.key - */ + /* The below settings can be used when running behind an ELB TCP listener with proxy protocol, terminating + * SSL in Zuul. + * + * Can be tested using certs in resources directory: + * curl https://localhost:7001/test -vk --cert src/main/resources/ssl/client.cert:zuul123 --key src/main/resources/ssl/client.key + */ case HTTP_MUTUAL_TLS: sslConfig = new ServerSslConfig( WWW_PROTOCOLS, @@ -178,12 +200,15 @@ protected void addHttp1Handlers(ChannelPipeline pipeline) loadFromResources("truststore.key"), false); - channelConfig.set(CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); + channelConfig.set( + CommonChannelConfigKeys.allowProxyHeadersWhen, + StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); channelConfig.set(CommonChannelConfigKeys.serverSslConfig, sslConfig); - channelConfig.set(CommonChannelConfigKeys.sslContextFactory, new BaseSslContextFactory(registry, sslConfig)); + channelConfig.set( + CommonChannelConfigKeys.sslContextFactory, new BaseSslContextFactory(registry, sslConfig)); addrsToChannels.put( new NamedSocketAddress("http_mtls", sockAddr), @@ -192,10 +217,12 @@ protected void addHttp1Handlers(ChannelPipeline pipeline) logAddrConfigured(sockAddr, sslConfig); break; - /* Settings to be used when running behind an ELB TCP listener with proxy protocol as a Push notification - * server using WebSockets */ + /* Settings to be used when running behind an ELB TCP listener with proxy protocol as a Push notification + * server using WebSockets */ case WEBSOCKET: - channelConfig.set(CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); + channelConfig.set( + CommonChannelConfigKeys.allowProxyHeadersWhen, + StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); @@ -214,17 +241,18 @@ protected void addHttp1Handlers(ChannelPipeline pipeline) logAddrConfigured(pushSockAddr); break; - /* Settings to be used when running behind an ELB TCP listener with proxy protocol as a Push notification - * server using Server Sent Events (SSE) */ + /* Settings to be used when running behind an ELB TCP listener with proxy protocol as a Push notification + * server using Server Sent Events (SSE) */ case SSE: - channelConfig.set(CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); + channelConfig.set( + CommonChannelConfigKeys.allowProxyHeadersWhen, + StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); channelDependencies.set(ZuulDependencyKeys.pushConnectionRegistry, pushConnectionRegistry); - /* addrsToChannels.put( new NamedSocketAddress("sse", sockAddr), diff --git a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/TestUtil.java b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/TestUtil.java index d27201e778..728d5a2781 100644 --- a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/TestUtil.java +++ b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/TestUtil.java @@ -24,14 +24,15 @@ import java.util.UUID; public class TestUtil { - private TestUtil() { } + private TestUtil() {} public static final Charset CHARSET = StandardCharsets.UTF_8; public static final String COMPRESSIBLE_CONTENT = "Hello Hello Hello Hello Hello"; public static final String COMPRESSIBLE_CONTENT_TYPE = "text/plain"; - public static DiscoveryEnabledServer makeDiscoveryEnabledServer(final String appName, final String ipAddress, final int port) { + public static DiscoveryEnabledServer makeDiscoveryEnabledServer( + final String appName, final String ipAddress, final int port) { InstanceInfo instanceInfo = new InstanceInfo( UUID.randomUUID().toString(), appName, @@ -58,8 +59,7 @@ public static DiscoveryEnabledServer makeDiscoveryEnabledServer(final String app null, null, null, - null - ); + null); return new DiscoveryEnabledServer(instanceInfo, false, true); } } diff --git a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/filters/InboundRoutesFilter.java b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/filters/InboundRoutesFilter.java index af543b2c00..0e59cd963f 100644 --- a/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/filters/InboundRoutesFilter.java +++ b/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/filters/InboundRoutesFilter.java @@ -22,8 +22,6 @@ import com.netflix.zuul.filters.endpoint.ProxyEndpoint; import com.netflix.zuul.filters.http.HttpInboundSyncFilter; import com.netflix.zuul.message.http.HttpRequestMessage; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.UnpooledByteBufAllocator; @Filter(order = 0, type = FilterType.INBOUND) public class InboundRoutesFilter extends HttpInboundSyncFilter { diff --git a/zuul-processor/src/main/java/com/netflix/zuul/filters/processor/FilterProcessor.java b/zuul-processor/src/main/java/com/netflix/zuul/filters/processor/FilterProcessor.java index 309e7247fd..7ed7257269 100644 --- a/zuul-processor/src/main/java/com/netflix/zuul/filters/processor/FilterProcessor.java +++ b/zuul-processor/src/main/java/com/netflix/zuul/filters/processor/FilterProcessor.java @@ -17,6 +17,18 @@ package com.netflix.zuul.filters.processor; import com.google.common.annotations.VisibleForTesting; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.Filer; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedSourceVersion; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.Modifier; +import javax.lang.model.element.TypeElement; +import javax.tools.FileObject; +import javax.tools.StandardLocation; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; @@ -36,18 +48,6 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import javax.annotation.processing.AbstractProcessor; -import javax.annotation.processing.Filer; -import javax.annotation.processing.RoundEnvironment; -import javax.annotation.processing.SupportedAnnotationTypes; -import javax.annotation.processing.SupportedSourceVersion; -import javax.lang.model.SourceVersion; -import javax.lang.model.element.Element; -import javax.lang.model.element.Modifier; -import javax.lang.model.element.TypeElement; -import javax.tools.FileObject; -import javax.tools.StandardLocation; - @SupportedAnnotationTypes(FilterProcessor.FILTER_TYPE) @SupportedSourceVersion(SourceVersion.RELEASE_8) @@ -59,13 +59,16 @@ public final class FilterProcessor extends AbstractProcessor { @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { - Set annotated = - roundEnv.getElementsAnnotatedWith(processingEnv.getElementUtils().getTypeElement(FILTER_TYPE)); + Set annotated = roundEnv.getElementsAnnotatedWith( + processingEnv.getElementUtils().getTypeElement(FILTER_TYPE)); for (Element el : annotated) { if (el.getModifiers().contains(Modifier.ABSTRACT)) { continue; } - annotatedElements.add(processingEnv.getElementUtils().getBinaryName((TypeElement) el).toString()); + annotatedElements.add(processingEnv + .getElementUtils() + .getBinaryName((TypeElement) el) + .toString()); } if (roundEnv.processingOver()) { diff --git a/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/FilterProcessorTest.java b/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/FilterProcessorTest.java index c67a16e170..2a608f3a34 100644 --- a/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/FilterProcessorTest.java +++ b/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/FilterProcessorTest.java @@ -21,9 +21,10 @@ import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.filters.processor.override.SubpackageFilter; import com.netflix.zuul.filters.processor.subpackage.OverrideFilter; -import java.util.Collection; import org.junit.jupiter.api.Test; +import java.util.Collection; + /** * Tests for {@link FilterProcessor}. */ @@ -34,12 +35,13 @@ void allFilterClassedRecorded() throws Exception { Collection>> filters = StaticFilterLoader.loadFilterTypesFromResources(getClass().getClassLoader()); - Truth.assertThat(filters).containsExactly( - OuterClassFilter.class, - TopLevelFilter.class, - TopLevelFilter.StaticSubclassFilter.class, - TopLevelFilter.SubclassFilter.class, - OverrideFilter.class, - SubpackageFilter.class); + Truth.assertThat(filters) + .containsExactly( + OuterClassFilter.class, + TopLevelFilter.class, + TopLevelFilter.StaticSubclassFilter.class, + TopLevelFilter.SubclassFilter.class, + OverrideFilter.class, + SubpackageFilter.class); } } diff --git a/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/TopLevelFilter.java b/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/TopLevelFilter.java index 300a97cbac..a85b54cfde 100644 --- a/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/TopLevelFilter.java +++ b/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/TopLevelFilter.java @@ -30,7 +30,7 @@ static final class StaticSubclassFilter extends TestFilter {} @SuppressWarnings("unused") // This should be ignored by the processor, since it is abstract @Filter(order = 22, type = FilterType.INBOUND) - static abstract class AbstractSubclassFilter extends TestFilter {} + abstract static class AbstractSubclassFilter extends TestFilter {} @SuppressWarnings("InnerClassMayBeStatic") // The purpose of this test @Filter(order = 23, type = FilterType.INBOUND) @@ -44,5 +44,6 @@ final class SubclassFilter extends TestFilter {} final class MethodClassFilter {} } } + @Filter(order = 24, type = FilterType.INBOUND) final class OuterClassFilter extends TestFilter {} diff --git a/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/override/SubpackageFilter.java b/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/override/SubpackageFilter.java index 3ec6fec33b..e08f48039e 100644 --- a/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/override/SubpackageFilter.java +++ b/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/override/SubpackageFilter.java @@ -21,5 +21,4 @@ import com.netflix.zuul.filters.processor.TestFilter; @Filter(order = 30, type = FilterType.INBOUND) -public final class SubpackageFilter extends TestFilter { -} +public final class SubpackageFilter extends TestFilter {} diff --git a/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/override/package-info.java b/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/override/package-info.java index 2636cc1a0d..9d52160d24 100644 --- a/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/override/package-info.java +++ b/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/override/package-info.java @@ -15,4 +15,4 @@ */ @com.netflix.zuul.Filter.FilterPackageName("MySubpackage") -package com.netflix.zuul.filters.processor.override; \ No newline at end of file +package com.netflix.zuul.filters.processor.override; diff --git a/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/subpackage/OverrideFilter.java b/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/subpackage/OverrideFilter.java index a335407757..6b3fc2f865 100644 --- a/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/subpackage/OverrideFilter.java +++ b/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/subpackage/OverrideFilter.java @@ -21,5 +21,4 @@ import com.netflix.zuul.filters.processor.TestFilter; @Filter(order = 30, type = FilterType.INBOUND) -public final class OverrideFilter extends TestFilter { -} +public final class OverrideFilter extends TestFilter {} diff --git a/zuul-sample/src/main/java/com/netflix/zuul/sample/Bootstrap.java b/zuul-sample/src/main/java/com/netflix/zuul/sample/Bootstrap.java index b1a9953201..2c37bd5584 100644 --- a/zuul-sample/src/main/java/com/netflix/zuul/sample/Bootstrap.java +++ b/zuul-sample/src/main/java/com/netflix/zuul/sample/Bootstrap.java @@ -20,10 +20,11 @@ import com.google.inject.Injector; import com.netflix.zuul.netty.server.BaseServerStartup; import com.netflix.zuul.netty.server.Server; -import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.concurrent.TimeUnit; + /** * Bootstrap * @@ -62,8 +63,7 @@ public void start() { System.err.println("Zuul Sample: initialization failed. Forcing shutdown now."); System.err.println("###############"); exitCode = 1; - } - finally { + } finally { // server shutdown if (server != null) { server.stop(); diff --git a/zuul-sample/src/main/java/com/netflix/zuul/sample/SampleServerStartup.java b/zuul-sample/src/main/java/com/netflix/zuul/sample/SampleServerStartup.java index c46285d90f..a57e6fea77 100644 --- a/zuul-sample/src/main/java/com/netflix/zuul/sample/SampleServerStartup.java +++ b/zuul-sample/src/main/java/com/netflix/zuul/sample/SampleServerStartup.java @@ -19,35 +19,42 @@ import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.config.DynamicIntProperty; import com.netflix.discovery.EurekaClient; +import com.netflix.netty.common.accesslog.AccessLogPublisher; +import com.netflix.netty.common.channel.config.ChannelConfig; +import com.netflix.netty.common.channel.config.CommonChannelConfigKeys; +import com.netflix.netty.common.metrics.EventLoopGroupMetrics; +import com.netflix.netty.common.proxyprotocol.StripUntrustedProxyHeadersHandler; +import com.netflix.netty.common.ssl.ServerSslConfig; +import com.netflix.netty.common.status.ServerStatusManager; import com.netflix.spectator.api.Registry; import com.netflix.zuul.FilterLoader; import com.netflix.zuul.FilterUsageNotifier; import com.netflix.zuul.RequestCompleteHandler; import com.netflix.zuul.context.SessionContextDecorator; -import com.netflix.zuul.netty.server.*; +import com.netflix.zuul.netty.server.BaseServerStartup; +import com.netflix.zuul.netty.server.DefaultEventLoopConfig; +import com.netflix.zuul.netty.server.DirectMemoryMonitor; +import com.netflix.zuul.netty.server.Http1MutualSslChannelInitializer; +import com.netflix.zuul.netty.server.NamedSocketAddress; +import com.netflix.zuul.netty.server.SocketAddressProperty; +import com.netflix.zuul.netty.server.ZuulDependencyKeys; +import com.netflix.zuul.netty.server.ZuulServerChannelInitializer; import com.netflix.zuul.netty.server.http2.Http2SslChannelInitializer; import com.netflix.zuul.netty.server.push.PushConnectionRegistry; import com.netflix.zuul.netty.ssl.BaseSslContextFactory; +import com.netflix.zuul.sample.push.SamplePushMessageSenderInitializer; import com.netflix.zuul.sample.push.SampleSSEPushChannelInitializer; import com.netflix.zuul.sample.push.SampleWebSocketPushChannelInitializer; -import com.netflix.zuul.sample.push.SamplePushMessageSenderInitializer; import io.netty.channel.ChannelInitializer; import io.netty.channel.group.ChannelGroup; import io.netty.handler.ssl.ClientAuth; -import com.netflix.netty.common.accesslog.AccessLogPublisher; -import com.netflix.netty.common.channel.config.ChannelConfig; -import com.netflix.netty.common.channel.config.CommonChannelConfigKeys; -import com.netflix.netty.common.metrics.EventLoopGroupMetrics; -import com.netflix.netty.common.proxyprotocol.StripUntrustedProxyHeadersHandler; -import com.netflix.netty.common.ssl.ServerSslConfig; -import com.netflix.netty.common.status.ServerStatusManager; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.util.Collections; import javax.inject.Inject; import javax.inject.Singleton; import java.io.File; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -68,21 +75,38 @@ enum ServerType { SSE } - private static final String[] WWW_PROTOCOLS = new String[]{"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"}; + private static final String[] WWW_PROTOCOLS = new String[] {"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"}; private static final ServerType SERVER_TYPE = ServerType.HTTP; private final PushConnectionRegistry pushConnectionRegistry; private final SamplePushMessageSenderInitializer pushSenderInitializer; @Inject - public SampleServerStartup(ServerStatusManager serverStatusManager, FilterLoader filterLoader, - SessionContextDecorator sessionCtxDecorator, FilterUsageNotifier usageNotifier, - RequestCompleteHandler reqCompleteHandler, Registry registry, - DirectMemoryMonitor directMemoryMonitor, EventLoopGroupMetrics eventLoopGroupMetrics, - EurekaClient discoveryClient, ApplicationInfoManager applicationInfoManager, - AccessLogPublisher accessLogPublisher, PushConnectionRegistry pushConnectionRegistry, - SamplePushMessageSenderInitializer pushSenderInitializer) { - super(serverStatusManager, filterLoader, sessionCtxDecorator, usageNotifier, reqCompleteHandler, registry, - directMemoryMonitor, eventLoopGroupMetrics, new DefaultEventLoopConfig(), discoveryClient, applicationInfoManager, + public SampleServerStartup( + ServerStatusManager serverStatusManager, + FilterLoader filterLoader, + SessionContextDecorator sessionCtxDecorator, + FilterUsageNotifier usageNotifier, + RequestCompleteHandler reqCompleteHandler, + Registry registry, + DirectMemoryMonitor directMemoryMonitor, + EventLoopGroupMetrics eventLoopGroupMetrics, + EurekaClient discoveryClient, + ApplicationInfoManager applicationInfoManager, + AccessLogPublisher accessLogPublisher, + PushConnectionRegistry pushConnectionRegistry, + SamplePushMessageSenderInitializer pushSenderInitializer) { + super( + serverStatusManager, + filterLoader, + sessionCtxDecorator, + usageNotifier, + reqCompleteHandler, + registry, + directMemoryMonitor, + eventLoopGroupMetrics, + new DefaultEventLoopConfig(), + discoveryClient, + applicationInfoManager, accessLogPublisher); this.pushConnectionRegistry = pushConnectionRegistry; this.pushSenderInitializer = pushSenderInitializer; @@ -94,8 +118,7 @@ protected Map> chooseAddrsAndChannels( SocketAddress sockAddr; String metricId; { - @Deprecated - int port = new DynamicIntProperty("zuul.server.port.main", 7001).get(); + @Deprecated int port = new DynamicIntProperty("zuul.server.port.main", 7001).get(); sockAddr = new SocketAddressProperty("zuul.server.addr.main", "=" + port).getValue(); if (sockAddr instanceof InetSocketAddress) { metricId = String.valueOf(((InetSocketAddress) sockAddr).getPort()); @@ -108,8 +131,7 @@ protected Map> chooseAddrsAndChannels( SocketAddress pushSockAddr; { int pushPort = new DynamicIntProperty("zuul.server.port.http.push", 7008).get(); - pushSockAddr = new SocketAddressProperty( - "zuul.server.addr.http.push", "=" + pushPort).getValue(); + pushSockAddr = new SocketAddressProperty("zuul.server.addr.http.push", "=" + pushPort).getValue(); } String mainListenAddressName = "main"; @@ -121,52 +143,53 @@ protected Map> chooseAddrsAndChannels( * or directly on the internet. */ switch (SERVER_TYPE) { - /* The below settings can be used when running behind an ELB HTTP listener that terminates SSL for you - * and passes XFF headers. - */ + /* The below settings can be used when running behind an ELB HTTP listener that terminates SSL for you + * and passes XFF headers. + */ case HTTP: - channelConfig.set(CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.ALWAYS); + channelConfig.set( + CommonChannelConfigKeys.allowProxyHeadersWhen, + StripUntrustedProxyHeadersHandler.AllowWhen.ALWAYS); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, false); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, false); addrsToChannels.put( new NamedSocketAddress("http", sockAddr), - new ZuulServerChannelInitializer( - metricId, channelConfig, channelDependencies, clientChannels)); + new ZuulServerChannelInitializer(metricId, channelConfig, channelDependencies, clientChannels)); logAddrConfigured(sockAddr); break; - /* The below settings can be used when running behind an ELB TCP listener with proxy protocol, terminating - * SSL in Zuul. - */ + /* The below settings can be used when running behind an ELB TCP listener with proxy protocol, terminating + * SSL in Zuul. + */ case HTTP2: sslConfig = ServerSslConfig.withDefaultCiphers( - loadFromResources("server.cert"), - loadFromResources("server.key"), - WWW_PROTOCOLS); + loadFromResources("server.cert"), loadFromResources("server.key"), WWW_PROTOCOLS); - channelConfig.set(CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); + channelConfig.set( + CommonChannelConfigKeys.allowProxyHeadersWhen, + StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.serverSslConfig, sslConfig); - channelConfig.set(CommonChannelConfigKeys.sslContextFactory, new BaseSslContextFactory(registry, sslConfig)); + channelConfig.set( + CommonChannelConfigKeys.sslContextFactory, new BaseSslContextFactory(registry, sslConfig)); addHttp2DefaultConfig(channelConfig, mainListenAddressName); addrsToChannels.put( new NamedSocketAddress("http2", sockAddr), - new Http2SslChannelInitializer( - metricId, channelConfig, channelDependencies, clientChannels)); + new Http2SslChannelInitializer(metricId, channelConfig, channelDependencies, clientChannels)); logAddrConfigured(sockAddr, sslConfig); break; - /* The below settings can be used when running behind an ELB TCP listener with proxy protocol, terminating - * SSL in Zuul. - * - * Can be tested using certs in resources directory: - * curl https://localhost:7001/test -vk --cert src/main/resources/ssl/client.cert:zuul123 --key src/main/resources/ssl/client.key - */ + /* The below settings can be used when running behind an ELB TCP listener with proxy protocol, terminating + * SSL in Zuul. + * + * Can be tested using certs in resources directory: + * curl https://localhost:7001/test -vk --cert src/main/resources/ssl/client.cert:zuul123 --key src/main/resources/ssl/client.key + */ case HTTP_MUTUAL_TLS: sslConfig = new ServerSslConfig( WWW_PROTOCOLS, @@ -178,12 +201,15 @@ protected Map> chooseAddrsAndChannels( loadFromResources("truststore.key"), false); - channelConfig.set(CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); + channelConfig.set( + CommonChannelConfigKeys.allowProxyHeadersWhen, + StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); channelConfig.set(CommonChannelConfigKeys.serverSslConfig, sslConfig); - channelConfig.set(CommonChannelConfigKeys.sslContextFactory, new BaseSslContextFactory(registry, sslConfig)); + channelConfig.set( + CommonChannelConfigKeys.sslContextFactory, new BaseSslContextFactory(registry, sslConfig)); addrsToChannels.put( new NamedSocketAddress("http_mtls", sockAddr), @@ -192,10 +218,12 @@ protected Map> chooseAddrsAndChannels( logAddrConfigured(sockAddr, sslConfig); break; - /* Settings to be used when running behind an ELB TCP listener with proxy protocol as a Push notification - * server using WebSockets */ + /* Settings to be used when running behind an ELB TCP listener with proxy protocol as a Push notification + * server using WebSockets */ case WEBSOCKET: - channelConfig.set(CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); + channelConfig.set( + CommonChannelConfigKeys.allowProxyHeadersWhen, + StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); @@ -213,10 +241,12 @@ protected Map> chooseAddrsAndChannels( logAddrConfigured(pushSockAddr); break; - /* Settings to be used when running behind an ELB TCP listener with proxy protocol as a Push notification - * server using Server Sent Events (SSE) */ + /* Settings to be used when running behind an ELB TCP listener with proxy protocol as a Push notification + * server using Server Sent Events (SSE) */ case SSE: - channelConfig.set(CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); + channelConfig.set( + CommonChannelConfigKeys.allowProxyHeadersWhen, + StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); diff --git a/zuul-sample/src/main/java/com/netflix/zuul/sample/ZuulSampleModule.java b/zuul-sample/src/main/java/com/netflix/zuul/sample/ZuulSampleModule.java index ef43a4264f..eda1aebc29 100644 --- a/zuul-sample/src/main/java/com/netflix/zuul/sample/ZuulSampleModule.java +++ b/zuul-sample/src/main/java/com/netflix/zuul/sample/ZuulSampleModule.java @@ -42,9 +42,10 @@ import com.netflix.zuul.origins.OriginManager; import com.netflix.zuul.stats.BasicRequestMetricsPublisher; import com.netflix.zuul.stats.RequestMetricsPublisher; -import java.io.FilenameFilter; import org.apache.commons.configuration.AbstractConfiguration; +import java.io.FilenameFilter; + /** * Zuul Sample Module * @@ -55,9 +56,9 @@ public class ZuulSampleModule extends AbstractModule { @Override protected void configure() { try { - ConfigurationManager.loadCascadedPropertiesFromResources("application"); + ConfigurationManager.loadCascadedPropertiesFromResources("application"); } catch (Exception ex) { - throw new RuntimeException("Error loading configuration: " + ex.getMessage(), ex); + throw new RuntimeException("Error loading configuration: " + ex.getMessage(), ex); } bind(AbstractConfiguration.class).toInstance(ConfigurationManager.getConfigInstance()); @@ -78,16 +79,19 @@ protected void configure() { bind(FilterRegistry.class).to(MutableFilterRegistry.class); bind(FilterFileManager.class).asEagerSingleton(); - // general server bindings bind(ServerStatusManager.class); // health/discovery status - bind(SessionContextDecorator.class).to(ZuulSessionContextDecorator.class); // decorate new sessions when requests come in + bind(SessionContextDecorator.class) + .to(ZuulSessionContextDecorator.class); // decorate new sessions when requests come in bind(Registry.class).to(DefaultRegistry.class); // atlas metrics registry bind(RequestCompleteHandler.class).to(BasicRequestCompleteHandler.class); // metrics post-request completion bind(RequestMetricsPublisher.class).to(BasicRequestMetricsPublisher.class); // timings publisher // access logger, including request ID generator - bind(AccessLogPublisher.class).toInstance(new AccessLogPublisher("ACCESS", - (channel, httpRequest) -> ClientRequestReceiver.getRequestFromChannel(channel).getContext().getUUID())); + bind(AccessLogPublisher.class) + .toInstance(new AccessLogPublisher( + "ACCESS", (channel, httpRequest) -> ClientRequestReceiver.getRequestFromChannel(channel) + .getContext() + .getUUID())); } } diff --git a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushAuthHandler.java b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushAuthHandler.java index 03061e9f00..1d2f523bb5 100644 --- a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushAuthHandler.java +++ b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushAuthHandler.java @@ -52,7 +52,7 @@ protected boolean isDelayedAuth(FullHttpRequest req, ChannelHandlerContext ctx) protected PushUserAuth doAuth(FullHttpRequest req) { final Cookies cookies = parseCookies(req); for (final Cookie c : cookies.getAll()) { - if(c.getName().equals("userAuthCookie")) { + if (c.getName().equals("userAuthCookie")) { final String customerId = c.getValue(); if (!Strings.isNullOrEmpty(customerId)) { return new SamplePushUserAuth(customerId); @@ -61,5 +61,4 @@ protected PushUserAuth doAuth(FullHttpRequest req) { } return new SamplePushUserAuth(HttpResponseStatus.UNAUTHORIZED.code()); } - } diff --git a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushMessageSender.java b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushMessageSender.java index d206675aa7..3dc94d0a20 100644 --- a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushMessageSender.java +++ b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushMessageSender.java @@ -22,6 +22,7 @@ import io.netty.channel.ChannelHandler; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; + import javax.inject.Singleton; /** @@ -43,8 +44,5 @@ protected PushUserAuth getPushUserAuth(FullHttpRequest request) { return new SamplePushUserAuth(HttpResponseStatus.UNAUTHORIZED.code()); } return new SamplePushUserAuth(cid); - } - } - diff --git a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushMessageSenderInitializer.java b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushMessageSenderInitializer.java index 859450916a..b0de46d4de 100644 --- a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushMessageSenderInitializer.java +++ b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushMessageSenderInitializer.java @@ -18,6 +18,7 @@ import com.netflix.zuul.netty.server.push.PushConnectionRegistry; import com.netflix.zuul.netty.server.push.PushMessageSender; import com.netflix.zuul.netty.server.push.PushMessageSenderInitializer; + import javax.inject.Inject; import javax.inject.Singleton; @@ -40,5 +41,4 @@ public SamplePushMessageSenderInitializer(PushConnectionRegistry pushConnectionR protected PushMessageSender getPushMessageSender(PushConnectionRegistry pushConnectionRegistry) { return pushMessageSender; } - } diff --git a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleSSEPushChannelInitializer.java b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleSSEPushChannelInitializer.java index 6a1a864b4a..8c6a10bd14 100644 --- a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleSSEPushChannelInitializer.java +++ b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleSSEPushChannelInitializer.java @@ -18,7 +18,11 @@ import com.netflix.netty.common.channel.config.ChannelConfig; import com.netflix.zuul.netty.server.ZuulDependencyKeys; -import com.netflix.zuul.netty.server.push.*; +import com.netflix.zuul.netty.server.push.PushAuthHandler; +import com.netflix.zuul.netty.server.push.PushChannelInitializer; +import com.netflix.zuul.netty.server.push.PushConnectionRegistry; +import com.netflix.zuul.netty.server.push.PushProtocol; +import com.netflix.zuul.netty.server.push.PushRegistrationHandler; import io.netty.channel.ChannelPipeline; import io.netty.channel.group.ChannelGroup; @@ -32,21 +36,16 @@ public class SampleSSEPushChannelInitializer extends PushChannelInitializer { private final PushAuthHandler pushAuthHandler; public SampleSSEPushChannelInitializer( - String metricId, - ChannelConfig channelConfig, - ChannelConfig channelDependencies, - ChannelGroup channels) { + String metricId, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) { super(metricId, channelConfig, channelDependencies, channels); pushConnectionRegistry = channelDependencies.get(ZuulDependencyKeys.pushConnectionRegistry); pushAuthHandler = new SamplePushAuthHandler(PushProtocol.SSE.getPath()); } - @Override protected void addPushHandlers(final ChannelPipeline pipeline) { pipeline.addLast(PushAuthHandler.NAME, pushAuthHandler); pipeline.addLast(new PushRegistrationHandler(pushConnectionRegistry, PushProtocol.SSE)); pipeline.addLast(new SampleSSEPushClientProtocolHandler()); } - } diff --git a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleSSEPushClientProtocolHandler.java b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleSSEPushClientProtocolHandler.java index 478927594e..b4eb328f7a 100644 --- a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleSSEPushClientProtocolHandler.java +++ b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleSSEPushClientProtocolHandler.java @@ -18,15 +18,17 @@ import com.netflix.config.CachedDynamicIntProperty; import com.netflix.zuul.netty.server.push.PushClientProtocolHandler; -import com.netflix.zuul.netty.server.push.PushConnectionRegistry; import com.netflix.zuul.netty.server.push.PushProtocol; -import com.netflix.zuul.netty.server.push.PushRegistrationHandler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; -import io.netty.handler.codec.http.*; - -import java.util.concurrent.ThreadLocalRandom; +import io.netty.handler.codec.http.DefaultHttpResponse; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpContentCompressor; +import io.netty.handler.codec.http.HttpHeaders; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpObjectAggregator; +import io.netty.handler.codec.http.HttpResponseStatus; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; @@ -35,11 +37,12 @@ */ public class SampleSSEPushClientProtocolHandler extends PushClientProtocolHandler { - public static final CachedDynamicIntProperty SSE_RETRY_BASE_INTERVAL = new CachedDynamicIntProperty("zuul.push.sse.retry.base", 5000); + public static final CachedDynamicIntProperty SSE_RETRY_BASE_INTERVAL = + new CachedDynamicIntProperty("zuul.push.sse.retry.base", 5000); @Override public void channelRead(final ChannelHandlerContext ctx, final Object mesg) throws Exception { - if (mesg instanceof FullHttpRequest) { + if (mesg instanceof FullHttpRequest) { final FullHttpRequest req = (FullHttpRequest) mesg; if ((req.method() == HttpMethod.GET) && (PushProtocol.SSE.getPath().equals(req.uri()))) { ctx.pipeline().fireUserEventTriggered(PushProtocol.SSE.getHandshakeCompleteEvent()); @@ -67,5 +70,4 @@ public void channelRead(final ChannelHandlerContext ctx, final Object mesg) thro } } } - } \ No newline at end of file diff --git a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleWebSocketPushChannelInitializer.java b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleWebSocketPushChannelInitializer.java index 7b1ec2e5fd..85df21321a 100644 --- a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleWebSocketPushChannelInitializer.java +++ b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleWebSocketPushChannelInitializer.java @@ -17,7 +17,11 @@ import com.netflix.netty.common.channel.config.ChannelConfig; import com.netflix.zuul.netty.server.ZuulDependencyKeys; -import com.netflix.zuul.netty.server.push.*; +import com.netflix.zuul.netty.server.push.PushAuthHandler; +import com.netflix.zuul.netty.server.push.PushChannelInitializer; +import com.netflix.zuul.netty.server.push.PushConnectionRegistry; +import com.netflix.zuul.netty.server.push.PushProtocol; +import com.netflix.zuul.netty.server.push.PushRegistrationHandler; import io.netty.channel.ChannelPipeline; import io.netty.channel.group.ChannelGroup; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; diff --git a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleWebSocketPushClientProtocolHandler.java b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleWebSocketPushClientProtocolHandler.java index 476221533a..ae3e3b345d 100644 --- a/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleWebSocketPushClientProtocolHandler.java +++ b/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleWebSocketPushClientProtocolHandler.java @@ -18,7 +18,11 @@ import com.netflix.zuul.netty.server.push.PushClientProtocolHandler; import com.netflix.zuul.netty.server.push.PushProtocol; import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.http.websocketx.*; +import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; +import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; +import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; +import io.netty.handler.codec.http.websocketx.PongWebSocketFrame; +import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.util.ReferenceCountUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,35 +38,28 @@ public class SampleWebSocketPushClientProtocolHandler extends PushClientProtocol @Override public final void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { - if (! isAuthenticated()) { + if (!isAuthenticated()) { // Do not entertain ANY message from unauthenticated client PushProtocol.WEBSOCKET.sendErrorAndClose(ctx, 1007, "Missing authentication"); - } - else if (msg instanceof PingWebSocketFrame) { + } else if (msg instanceof PingWebSocketFrame) { logger.debug("received ping frame"); ctx.writeAndFlush(new PongWebSocketFrame()); - } - else if (msg instanceof CloseWebSocketFrame) { + } else if (msg instanceof CloseWebSocketFrame) { logger.debug("received close frame"); ctx.close(); - } - else if (msg instanceof TextWebSocketFrame) { + } else if (msg instanceof TextWebSocketFrame) { final TextWebSocketFrame tf = (TextWebSocketFrame) msg; final String text = tf.text(); logger.debug("received test frame: {}", text); - if (text != null && text.startsWith("ECHO ")) { //echo protocol + if (text != null && text.startsWith("ECHO ")) { // echo protocol ctx.channel().writeAndFlush(tf.copy()); } - } - else if (msg instanceof BinaryWebSocketFrame) { + } else if (msg instanceof BinaryWebSocketFrame) { logger.debug("received binary frame"); PushProtocol.WEBSOCKET.sendErrorAndClose(ctx, 1003, "Binary WebSocket frames not supported"); } - } - finally { + } finally { ReferenceCountUtil.release(msg); } } - - }