Skip to content

Commit

Permalink
Total connections should stay positive (#360)
Browse files Browse the repository at this point in the history
A fix for #351
  • Loading branch information
kvosper authored Jan 7, 2019
1 parent 6f918f5 commit 0cb3c04
Show file tree
Hide file tree
Showing 7 changed files with 178 additions and 24 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright (C) 2013-2018 Expedia Inc.
Copyright (C) 2013-2019 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -29,6 +29,7 @@
import com.hotels.styx.server.netty.codec.NettyToStyxRequestDecoder;
import com.hotels.styx.server.netty.connectors.HttpPipelineHandler;
import com.hotels.styx.server.netty.connectors.ResponseEnhancer;
import com.hotels.styx.server.netty.handlers.ChannelActivityEventConstrainer;
import com.hotels.styx.server.netty.handlers.ChannelStatisticsHandler;
import com.hotels.styx.server.netty.handlers.ExcessConnectionRejector;
import com.hotels.styx.server.netty.handlers.RequestTimeoutHandler;
Expand Down Expand Up @@ -147,6 +148,7 @@ public void configure(Channel channel, HttpHandler httpPipeline) {

channel.pipeline()
.addLast("connection-throttler", excessConnectionRejector)
.addLast("channel-activity-event-constrainer", new ChannelActivityEventConstrainer())
.addLast("idle-handler", new IdleStateHandler(serverConfig.requestTimeoutMillis(), 0, serverConfig.keepAliveTimeoutMillis(), MILLISECONDS))
.addLast("channel-stats", channelStatsHandler)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright (C) 2013-2018 Expedia Inc.
Copyright (C) 2013-2019 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -218,6 +218,7 @@ protected void channelRead0(ChannelHandlerContext ctx, LiveHttpRequest request)
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
eventProcessor.submit(new ChannelInactiveEvent());

super.channelInactive(ctx);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
Copyright (C) 2013-2019 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.hotels.styx.server.netty.handlers;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
* Stops channelInactive events from propagating if the channel never became active to begin with.
*
* In some circumstances (e.g. when a channel is rejected due to having too many connections) we may receive a
* channelInactive event on a channel that was not active.
*
* This event is unneeded and will confuse later handlers that collect metrics about channel activity.
*
* Note that this handler is not sharable, because it tracks whether a single channel is active.
*/
public class ChannelActivityEventConstrainer extends ChannelInboundHandlerAdapter {
private boolean channelActivated;

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
channelActivated = true;
super.channelActive(ctx);
}

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// In some circumstances (e.g. when a channel is rejected due to having too many connections) we may receive a
// channelInactive event on a channel that was not active. We don't need this event (and it will confuse
// metrics, etc. so we prevent it from propagating)
if (channelActivated) {
super.channelInactive(ctx);
}

channelActivated = false;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright (C) 2013-2018 Expedia Inc.
Copyright (C) 2013-2019 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand All @@ -25,35 +25,29 @@
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.codahale.metrics.MetricRegistry.name;
import static java.lang.String.format;
import static org.slf4j.LoggerFactory.getLogger;

/**
* Collects statistics about channels.
*/
@ChannelHandler.Sharable
public class ChannelStatisticsHandler extends ChannelDuplexHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ChannelStatisticsHandler.class);

public static final String PREFIX = "connections";

public static final String RECEIVED_BYTES = "bytes-received";
public static final String SENT_BYTES = "bytes-sent";
public static final String TOTAL_CONNECTIONS = "total-connections";
private static final Logger LOGGER = getLogger(ChannelStatisticsHandler.class);

private final MetricRegistry metricRegistry;
private final Counter receivedBytesCount;
private final Counter sentBytesCount;
private final Counter totalConnections;

public ChannelStatisticsHandler(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry.scope(PREFIX);
this.metricRegistry = metricRegistry.scope("connections");

this.receivedBytesCount = this.metricRegistry.counter(RECEIVED_BYTES);
this.sentBytesCount = this.metricRegistry.counter(SENT_BYTES);
this.totalConnections = this.metricRegistry.counter(TOTAL_CONNECTIONS);
this.receivedBytesCount = this.metricRegistry.counter("bytes-received");
this.sentBytesCount = this.metricRegistry.counter("bytes-sent");
this.totalConnections = this.metricRegistry.counter("total-connections");
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public ExcessConnectionRejector(ChannelGroup channelGroup, int maxConnectionsCou
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
if (channelGroup.size() >= maxConnectionsCount) {
LOGGER.warn("Max allowed connection to server exceeded: current={} configured={}", channelGroup.size(), maxConnectionsCount);
LOGGER.warn("Max allowed connection to server exceeded: current={} configured={}", channelGroup.size(), maxConnectionsCount);
ctx.close();
return;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright (C) 2013-2018 Expedia Inc.
Copyright (C) 2013-2019 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -45,21 +45,18 @@ public void createHandler() {
public void countsReceivedBytes() throws Exception {
ByteBuf buf = httpRequestAsBuf(POST, "/foo/bar", "Hello, world");
this.handler.channelRead(mock(ChannelHandlerContext.class), buf);
assertThat(countOf(ChannelStatisticsHandler.RECEIVED_BYTES), is((long) buf.readableBytes()));
assertThat(countOf("connections.bytes-received"), is((long) buf.readableBytes()));
}

@Test
public void countsSentBytes() throws Exception {
ByteBuf buf = httpResponseAsBuf(OK, "Response from server");
this.handler.write(mock(ChannelHandlerContext.class), buf, mock(ChannelPromise.class));
assertThat(countOf(ChannelStatisticsHandler.SENT_BYTES), is((long) buf.readableBytes()));
assertThat(countOf("connections.bytes-sent"), is((long) buf.readableBytes()));
}

private long countOf(String sentBytes) {
return this.metricRegistry.counter(metricName(sentBytes)).getCount();
private long countOf(String counter) {
return this.metricRegistry.counter(counter).getCount();
}

private static String metricName(String sentBytes) {
return ChannelStatisticsHandler.PREFIX + "." + sentBytes;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
Copyright (C) 2013-2019 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.hotels.styx.server

import java.nio.charset.StandardCharsets.UTF_8
import java.util
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit.SECONDS

import com.hotels.styx.StyxProxySpec
import com.hotels.styx.api.{HttpRequest, HttpResponse}
import com.hotels.styx.api.HttpRequest.get
import com.hotels.styx.api.exceptions.TransportLostException
import com.hotels.styx.client.BadHttpResponseException
import com.hotels.styx.support.TestClientSupport
import com.hotels.styx.support.backends.FakeHttpServer
import com.hotels.styx.support.configuration.{HttpBackend, Origins, ProxyConfig, StyxConfig}
import org.scalatest.FunSpec
import org.scalatest.concurrent.Eventually

import scala.concurrent.duration._
import scala.concurrent.ExecutionException
import scala.util.{Failure, Success, Try}

class ServerConnectionsSpec extends FunSpec
with StyxProxySpec
with TestClientSupport
with Eventually {
val normalBackend = FakeHttpServer.HttpStartupConfig().start()

override val styxConfig = StyxConfig(ProxyConfig(maxConnectionsCount = 5))

override protected def beforeAll(): Unit = {
super.beforeAll()
styxServer.setBackends(
"/" -> HttpBackend("myapp", Origins(normalBackend))
)
}

override protected def afterAll(): Unit = {
normalBackend.stop()
super.afterAll()
}

override protected def beforeEach(): Unit = {
super.beforeEach()
}

override protected def afterEach(): Unit = {
super.afterEach()
}

describe("Ensuring connection metrics are accurate") {
it("should record zero total-connections after finishing responses, including when connections are rejected due to exceeeding the configured maximum") {
val request: HttpRequest = get("http://localhost:" + styxServer.proxyHttpAddress().getPort + "/").build()

val futures = new util.ArrayList[CompletableFuture[HttpResponse]]()

for (_ <- 1 to 10) {
futures.add(client.send(request))
}

// We expect exceptions because we are trying to establish more connections than we have configured the server to allow
futures.forEach(future => {
ignoreExpectedExceptions(() => future.get(1, SECONDS))
})

eventually(timeout(1 second)) {
getTotalConnectionsMetric.bodyAs(UTF_8) should be("{\"connections.total-connections\":{\"count\":0}}")
}
}
}

private def ignoreExpectedExceptions(fun: () => Unit): Unit = {
val outcome = Try(fun()) recoverWith {
case ee : ExecutionException => Failure(ee.getCause)
case e => Failure(e)
} recoverWith {
case bhre : BadHttpResponseException => Success("ignore this: " + bhre)
case tle: TransportLostException => Success("ignore this: " + tle)
case e => Failure(e)
}

// when the connection is rejected we expect to end up with Success("ignore this: BadHttpResponseException ....")

outcome.get
}

private def getTotalConnectionsMetric = {
val request: HttpRequest = get("http://localhost:" + styxServer.adminHttpAddress().getPort + "/admin/metrics/connections.total-connections").build()

client.send(request).get(1, SECONDS)
}
}


0 comments on commit 0cb3c04

Please sign in to comment.