diff --git a/client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java b/client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java index aa9306c376..f9f44e2f0b 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java @@ -24,6 +24,8 @@ import net.jpountz.lz4.LZ4Factory; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.apache.hc.client5.http.ConnectTimeoutException; +import org.apache.hc.client5.http.DnsResolver; +import org.apache.hc.client5.http.SchemePortResolver; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.config.ConnectionConfig; import org.apache.hc.client5.http.config.RequestConfig; @@ -35,6 +37,7 @@ import org.apache.hc.client5.http.impl.io.DefaultManagedHttpClientConnection; import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.client5.http.io.HttpClientConnectionOperator; import org.apache.hc.client5.http.io.HttpClientConnectionManager; import org.apache.hc.client5.http.io.ManagedHttpClientConnection; import org.apache.hc.client5.http.protocol.HttpClientContext; @@ -75,12 +78,14 @@ import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.io.CloseMode; import org.apache.hc.core5.io.IOCallback; +import org.apache.hc.core5.net.NamedEndpoint; import org.apache.hc.core5.net.URIAuthority; import org.apache.hc.core5.net.URIBuilder; import org.apache.hc.core5.pool.ConnPoolControl; import org.apache.hc.core5.pool.PoolConcurrencyPolicy; import org.apache.hc.core5.pool.PoolReusePolicy; import org.apache.hc.core5.util.TimeValue; +import org.apache.hc.core5.util.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -106,6 +111,7 @@ import java.net.URLEncoder; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.Arrays; import java.util.Base64; import java.util.Collection; @@ -263,8 +269,22 @@ private HttpClientConnectionManager basicConnectionManager(LayeredConnectionSock } private HttpClientConnectionManager poolConnectionManager(LayeredConnectionSocketFactory sslConnectionSocketFactory, SocketConfig socketConfig, Map configuration) { - PoolingHttpClientConnectionManagerBuilder connMgrBuilder = PoolingHttpClientConnectionManagerBuilder.create() - .setPoolConcurrencyPolicy(PoolConcurrencyPolicy.LAX); + MeteredManagedHttpClientConnectionFactory connectionFactory = new MeteredManagedHttpClientConnectionFactory( + Http1Config.custom() + .setBufferSize(ClientConfigProperties.CLIENT_NETWORK_BUFFER_SIZE.getOrDefault(configuration)) + .build(), + CharCodingConfig.DEFAULT, + DefaultHttpResponseParserFactory.INSTANCE); + PoolingHttpClientConnectionManagerBuilder connMgrBuilder = new PoolingHttpClientConnectionManagerBuilder() { + @Override + protected HttpClientConnectionOperator createConnectionOperator(SchemePortResolver schemePortResolver, + DnsResolver dnsResolver, + TlsSocketStrategy tlsSocketStrategy) { + return new MeteredHttpClientConnectionOperator( + super.createConnectionOperator(schemePortResolver, dnsResolver, tlsSocketStrategy), + connectionFactory); + } + }.setPoolConcurrencyPolicy(PoolConcurrencyPolicy.LAX); ConnectionReuseStrategy connectionReuseStrategy = ClientConfigProperties.CONNECTION_REUSE_STRATEGY.getOrDefault(configuration); switch (connectionReuseStrategy) { @@ -283,14 +303,6 @@ private HttpClientConnectionManager poolConnectionManager(LayeredConnectionSocke connMgrBuilder.setMaxConnTotal(Integer.MAX_VALUE); // as we do not know how many routes we will have ClientConfigProperties.HTTP_MAX_OPEN_CONNECTIONS.applyIfSet(configuration, connMgrBuilder::setMaxConnPerRoute); - int networkBufferSize = ClientConfigProperties.CLIENT_NETWORK_BUFFER_SIZE.getOrDefault(configuration); - MeteredManagedHttpClientConnectionFactory connectionFactory = new MeteredManagedHttpClientConnectionFactory( - Http1Config.custom() - .setBufferSize(networkBufferSize) - .build(), - CharCodingConfig.DEFAULT, - DefaultHttpResponseParserFactory.INSTANCE); - connMgrBuilder.setConnectionFactory(connectionFactory); connMgrBuilder.setSSLSocketFactory(sslConnectionSocketFactory); connMgrBuilder.setDefaultSocketConfig(socketConfig); @@ -308,7 +320,6 @@ private HttpClientConnectionManager poolConnectionManager(LayeredConnectionSocke applyMethod.invoke(micrometerLoader, metricsRegistry, mGroupName, connectionFactory); } catch (Exception e) { LOG.error("Failed to register metrics", e); - // No gauge will drain the recorded times, so stop recording them. connectionFactory.disableMetrics(); } } @@ -1383,8 +1394,6 @@ public MeteredManagedHttpClientConnectionFactory(Http1Config http1Config, CharCo ConcurrentLinkedQueue times = new ConcurrentLinkedQueue<>(); - // Connection times are drained only by the metrics gauge (see getTime()), so they are recorded - // only when a metrics registry is attached. Otherwise the queue would grow with every new connection. private volatile boolean metricsEnabled = false; public void enableMetrics() { @@ -1396,31 +1405,94 @@ public void disableMetrics() { this.times.clear(); } - @Override - public ManagedHttpClientConnection createConnection(Socket socket) throws IOException { - if (!metricsEnabled) { - return super.createConnection(socket); - } - long startT = System.currentTimeMillis(); - try { - return super.createConnection(socket); - } finally { - long endT = System.currentTimeMillis(); - times.add(endT - startT); + private boolean isMetricsEnabled() { + return metricsEnabled; + } + + void recordConnectTime(long connectTimeNanos) { + if (metricsEnabled) { + times.add(connectTimeNanos); } } public long getTime() { + return (long) getAverageTimeInMillis(); + } + + public double getAverageTimeInMillis() { int count = times.size(); - long runningAverage = 0; + double totalNanos = 0; + int sampleCount = 0; for (int i = 0; i < count; i++) { - Long t = times.poll(); - if (t != null) { - runningAverage += t; + Long connectTimeNanos = times.poll(); + if (connectTimeNanos != null) { + totalNanos += connectTimeNanos; + sampleCount++; } } - return count > 0 ? runningAverage / count : 0; + return sampleCount > 0 ? totalNanos / sampleCount / 1_000_000.0 : 0; + } + } + + static class MeteredHttpClientConnectionOperator implements HttpClientConnectionOperator { + private final HttpClientConnectionOperator delegate; + private final MeteredManagedHttpClientConnectionFactory connectionFactory; + + MeteredHttpClientConnectionOperator(HttpClientConnectionOperator delegate, + MeteredManagedHttpClientConnectionFactory connectionFactory) { + this.delegate = delegate; + this.connectionFactory = connectionFactory; + } + + private void connect(ConnectAction action) throws IOException { + if (!connectionFactory.isMetricsEnabled()) { + action.run(); + return; + } + long startTime = System.nanoTime(); + try { + action.run(); + } finally { + connectionFactory.recordConnectTime(System.nanoTime() - startTime); + } + } + + @Override + public void connect(ManagedHttpClientConnection connection, HttpHost host, InetSocketAddress localAddress, + TimeValue connectTimeout, SocketConfig socketConfig, HttpContext context) throws IOException { + connect(() -> delegate.connect(connection, host, localAddress, connectTimeout, socketConfig, context)); + } + + @Override + public void connect(ManagedHttpClientConnection connection, HttpHost host, NamedEndpoint namedEndpoint, + InetSocketAddress localAddress, Timeout connectTimeout, SocketConfig socketConfig, + Object attachment, HttpContext context) throws IOException { + connect(() -> delegate.connect(connection, host, namedEndpoint, localAddress, connectTimeout, + socketConfig, attachment, context)); + } + + @Override + public void connect(ManagedHttpClientConnection connection, HttpHost host, NamedEndpoint namedEndpoint, + Path path, InetSocketAddress localAddress, Timeout connectTimeout, + SocketConfig socketConfig, Object attachment, HttpContext context) throws IOException { + connect(() -> delegate.connect(connection, host, namedEndpoint, path, localAddress, connectTimeout, + socketConfig, attachment, context)); + } + + @Override + public void upgrade(ManagedHttpClientConnection connection, HttpHost host, HttpContext context) throws IOException { + delegate.upgrade(connection, host, context); + } + + @Override + public void upgrade(ManagedHttpClientConnection connection, HttpHost host, NamedEndpoint namedEndpoint, + Object attachment, HttpContext context) throws IOException { + delegate.upgrade(connection, host, namedEndpoint, attachment, context); + } + + private interface ConnectAction { + void run() throws IOException; } } diff --git a/client-v2/src/main/java/com/clickhouse/client/api/metrics/MicrometerLoader.java b/client-v2/src/main/java/com/clickhouse/client/api/metrics/MicrometerLoader.java index 00f6c03444..e279898a73 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/metrics/MicrometerLoader.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/metrics/MicrometerLoader.java @@ -54,8 +54,9 @@ public static void applyPoolingMetricsBinder(Object registry, String metricsGrou public static void applyConnectionMetricsBinder(Object registry, String metricsGroupName, HttpAPIClientHelper.MeteredManagedHttpClientConnectionFactory factory) { if (registry instanceof MeterRegistry) { - Gauge.builder("httpcomponents.httpclient.connect.time", factory, HttpAPIClientHelper.MeteredManagedHttpClientConnectionFactory::getTime) - .description("The running average connection creation time.") + Gauge.builder("httpcomponents.httpclient.connect.time", factory, + HttpAPIClientHelper.MeteredManagedHttpClientConnectionFactory::getAverageTimeInMillis) + .description("Average connection establishment time in milliseconds.") .tag("httpclient", metricsGroupName) .register((MeterRegistry) registry); } else { diff --git a/client-v2/src/test/java/com/clickhouse/client/api/internal/MeteredConnectionFactoryTest.java b/client-v2/src/test/java/com/clickhouse/client/api/internal/MeteredConnectionFactoryTest.java index c9a96cdf76..2fec708b77 100644 --- a/client-v2/src/test/java/com/clickhouse/client/api/internal/MeteredConnectionFactoryTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/api/internal/MeteredConnectionFactoryTest.java @@ -1,14 +1,58 @@ package com.clickhouse.client.api.internal; +import com.clickhouse.client.api.Client; +import com.clickhouse.client.api.enums.SSLMode; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; +import com.github.tomakehurst.wiremock.common.ConsoleNotifier; +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import io.micrometer.core.instrument.Gauge; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import org.apache.hc.client5.http.io.HttpClientConnectionOperator; +import org.apache.hc.client5.http.io.ManagedHttpClientConnection; +import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.config.CharCodingConfig; import org.apache.hc.core5.http.config.Http1Config; import org.apache.hc.core5.http.impl.io.DefaultHttpResponseParserFactory; +import org.apache.hc.core5.http.io.SocketConfig; +import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.net.NamedEndpoint; +import org.apache.hc.core5.util.TimeValue; +import org.apache.hc.core5.util.Timeout; import org.testng.Assert; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.net.ServerSocket; import java.net.Socket; +import java.net.SocketAddress; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.Base64; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; public class MeteredConnectionFactoryTest { + private static final long DELAY_MILLIS = 250; private static HttpAPIClientHelper.MeteredManagedHttpClientConnectionFactory newFactory() { return new HttpAPIClientHelper.MeteredManagedHttpClientConnectionFactory( @@ -18,6 +62,7 @@ private static HttpAPIClientHelper.MeteredManagedHttpClientConnectionFactory new @Test(groups = {"unit"}) public void testConnectionTimesNotRecordedWithoutMetrics() throws Exception { HttpAPIClientHelper.MeteredManagedHttpClientConnectionFactory factory = newFactory(); + factory.recordConnectTime(1_000_000L); for (int i = 0; i < 10; i++) { factory.createConnection(new Socket()); } @@ -28,11 +73,9 @@ public void testConnectionTimesNotRecordedWithoutMetrics() throws Exception { public void testConnectionTimesRecordedAndDrainedWithMetrics() throws Exception { HttpAPIClientHelper.MeteredManagedHttpClientConnectionFactory factory = newFactory(); factory.enableMetrics(); - for (int i = 0; i < 10; i++) { - factory.createConnection(new Socket()); - } - Assert.assertEquals(factory.times.size(), 10); - factory.getTime(); + factory.recordConnectTime(500_000L); + Assert.assertEquals(factory.times.size(), 1); + Assert.assertEquals(factory.getAverageTimeInMillis(), 0.5, 0.0); Assert.assertEquals(factory.times.size(), 0); } @@ -41,9 +84,234 @@ public void testConnectionTimesNotRecordedAfterMetricsDisabled() throws Exceptio HttpAPIClientHelper.MeteredManagedHttpClientConnectionFactory factory = newFactory(); factory.enableMetrics(); factory.createConnection(new Socket()); + Assert.assertEquals(factory.times.size(), 0, "Connection object creation must not record a connect time"); factory.disableMetrics(); Assert.assertEquals(factory.times.size(), 0); - factory.createConnection(new Socket()); + factory.recordConnectTime(1_000_000L); Assert.assertEquals(factory.times.size(), 0, "Connection times must not accumulate once metrics are disabled"); } + + @Test(groups = {"unit"}) + public void testDelayedTcpConnectIsIncludedInConnectionEstablishmentTime() throws Exception { + HttpAPIClientHelper.MeteredManagedHttpClientConnectionFactory factory = newFactory(); + factory.enableMetrics(); + try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + TestConnectionOperator delegate = new TestConnectionOperator(() -> { + try (Socket socket = new DelayedConnectSocket(DELAY_MILLIS)) { + socket.connect(server.getLocalSocketAddress(), 1_000); + } + }); + HttpAPIClientHelper.MeteredHttpClientConnectionOperator operator = + new HttpAPIClientHelper.MeteredHttpClientConnectionOperator(delegate, factory); + + operator.connect(null, null, null, null, null, Timeout.ofSeconds(1), null, null, null); + + Assert.assertTrue(delegate.connected, "Connection operator did not connect the socket"); + try (Socket accepted = server.accept()) { + Assert.assertTrue(accepted.isConnected()); + } + Assert.assertTrue(factory.getAverageTimeInMillis() >= DELAY_MILLIS - 50, + "Connection establishment time should include the delayed TCP connect"); + } + } + + @Test(groups = {"unit"}) + public void testDelayedTlsHandshakeIsIncludedInConnectionEstablishmentTime() throws Exception { + HttpAPIClientHelper.MeteredManagedHttpClientConnectionFactory factory = newFactory(); + factory.enableMetrics(); + SSLContext serverContext = createServerSslContext(); + SSLContext clientContext = createTrustAllSslContext(); + try (SSLServerSocket server = (SSLServerSocket) serverContext.getServerSocketFactory() + .createServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future handshake = executor.submit(() -> { + try (SSLSocket socket = (SSLSocket) server.accept()) { + Thread.sleep(DELAY_MILLIS); + socket.startHandshake(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + TestConnectionOperator delegate = new TestConnectionOperator(() -> { + try (SSLSocket socket = (SSLSocket) clientContext.getSocketFactory().createSocket()) { + socket.connect(server.getLocalSocketAddress(), 1_000); + socket.startHandshake(); + } + }); + HttpAPIClientHelper.MeteredHttpClientConnectionOperator operator = + new HttpAPIClientHelper.MeteredHttpClientConnectionOperator(delegate, factory); + + operator.connect(null, null, null, null, null, Timeout.ofSeconds(1), null, null, null); + handshake.get(5, TimeUnit.SECONDS); + + Assert.assertTrue(delegate.connected, "Connection operator did not complete the TLS handshake"); + Assert.assertTrue(factory.getAverageTimeInMillis() >= DELAY_MILLIS - 50, + "Connection establishment time should include the delayed TLS handshake"); + } finally { + executor.shutdownNow(); + } + } + } + + @DataProvider(name = "connectionMetricSchemes") + public Object[][] connectionMetricSchemes() { + return new Object[][] {{false}, {true}}; + } + + @Test(dataProvider = "connectionMetricSchemes", groups = {"unit"}) + public void testConnectionMetricThroughClient(boolean secure) { + WireMockServer server = new WireMockServer(WireMockConfiguration.options() + .dynamicPort() + .dynamicHttpsPort() + .notifier(new ConsoleNotifier(false))); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + try { + server.start(); + server.stubFor(WireMock.post(WireMock.anyUrl()).willReturn(WireMock.ok("1"))); + String scheme = secure ? "https" : "http"; + int port = secure ? server.httpsPort() : server.port(); + + Client.Builder builder = new Client.Builder() + .addEndpoint(scheme + "://localhost:" + port) + .enableConnectionPool(true) + .registerClientMetrics(registry, "connection-metric-test"); + if (secure) { + builder.setSSLMode(SSLMode.TRUST); + } + + try (Client client = builder.build()) { + Assert.assertTrue(client.ping(), "The client request should succeed"); + Gauge times = registry.get("httpcomponents.httpclient.connect.time").gauge(); + Assert.assertTrue(times.value() > 0, "A new connection should record its establishment time"); + + Assert.assertTrue(client.ping(), "The request on the pooled connection should succeed"); + Assert.assertEquals(times.value(), 0.0, 0.0, + "Reusing a pooled connection should not record another sample"); + } + server.verify(2, WireMock.postRequestedFor(WireMock.anyUrl())); + } finally { + registry.close(); + server.stop(); + } + } + + private static class TestConnectionOperator implements HttpClientConnectionOperator { + private final ConnectAction action; + private boolean connected; + + private TestConnectionOperator(ConnectAction action) { + this.action = action; + } + + @Override + public void connect(ManagedHttpClientConnection connection, HttpHost host, + java.net.InetSocketAddress localAddress, TimeValue connectTimeout, + SocketConfig socketConfig, HttpContext context) { + throw new AssertionError("Unexpected legacy connect overload"); + } + + @Override + public void connect(ManagedHttpClientConnection connection, HttpHost host, NamedEndpoint namedEndpoint, + java.nio.file.Path path, java.net.InetSocketAddress localAddress, Timeout connectTimeout, + SocketConfig socketConfig, Object attachment, HttpContext context) throws IOException { + action.run(); + connected = true; + } + + @Override + public void upgrade(ManagedHttpClientConnection connection, HttpHost host, HttpContext context) { + } + } + + private static class DelayedConnectSocket extends Socket { + private final long delayMillis; + + private DelayedConnectSocket(long delayMillis) { + this.delayMillis = delayMillis; + } + + @Override + public void connect(SocketAddress endpoint, int timeout) throws IOException { + try { + Thread.sleep(delayMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException(e); + } + super.connect(endpoint, timeout); + } + } + + private static SSLContext createServerSslContext() throws Exception { + String privateKeyPem = readTestResource("containers/clickhouse-server/certs/localhost.key"); + byte[] privateKeyBytes = Base64.getMimeDecoder().decode(privateKeyPem + .replace("-----BEGIN PRIVATE KEY-----", "") + .replace("-----END PRIVATE KEY-----", "")); + PrivateKey privateKey = KeyFactory.getInstance("RSA") + .generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)); + Certificate certificate; + try (InputStream input = MeteredConnectionFactoryTest.class.getClassLoader() + .getResourceAsStream("containers/clickhouse-server/certs/localhost.crt")) { + if (input == null) { + throw new IOException("Missing test TLS certificate"); + } + certificate = CertificateFactory.getInstance("X.509").generateCertificate(input); + } + + char[] password = "test".toCharArray(); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + keyStore.load(null, null); + keyStore.setKeyEntry("server", privateKey, password, new Certificate[] { certificate }); + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(keyStore, password); + + SSLContext context = SSLContext.getInstance("TLS"); + context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); + return context; + } + + private static SSLContext createTrustAllSslContext() throws Exception { + TrustManager[] trustManagers = new TrustManager[] { + new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) { + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + } + }; + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, trustManagers, new SecureRandom()); + return context; + } + + private static String readTestResource(String path) throws IOException { + try (InputStream input = MeteredConnectionFactoryTest.class.getClassLoader().getResourceAsStream(path)) { + if (input == null) { + throw new IOException("Missing test resource: " + path); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buffer = new byte[4_096]; + int read; + while ((read = input.read(buffer)) != -1) { + output.write(buffer, 0, read); + } + return new String(output.toByteArray(), StandardCharsets.US_ASCII); + } + } + + private interface ConnectAction { + void run() throws IOException; + } } diff --git a/client-v2/src/test/java/com/clickhouse/client/metrics/MetricsTest.java b/client-v2/src/test/java/com/clickhouse/client/metrics/MetricsTest.java index bfe671d997..35d2a893e6 100644 --- a/client-v2/src/test/java/com/clickhouse/client/metrics/MetricsTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/metrics/MetricsTest.java @@ -122,14 +122,13 @@ public void testRegisterMetrics() throws Exception { assertEquals(meterRegistry.getMeters().size(), 6); } - //Disabled because we can't assume the time is greater than 0 - @Test(groups = { "integration" }, enabled = false) + @Test(groups = { "integration" }) public void testConnectionTime() throws Exception { ClickHouseNode node = getServer(ClickHouseProtocol.HTTP); boolean isSecure = isCloud(); try (Client client = new Client.Builder() - .addEndpoint(Protocol.HTTP, "192.168.1.1", node.getPort(), isSecure) + .addEndpoint(Protocol.HTTP, node.getHost(), node.getPort(), isSecure) .setUsername("default") .setPassword(ClickHouseServerForTest.getPassword()) .setDefaultDatabase(ClickHouseServerForTest.getDatabase()) @@ -140,8 +139,11 @@ public void testConnectionTime() throws Exception { client.ping(); Gauge times = meterRegistry.get("httpcomponents.httpclient.connect.time").gauge(); - Assert.assertTrue(times.value() > 0); - assertEquals(times.value(), 0);//Second time should be 0 + Assert.assertTrue(times.value() > 0, "A new connection should record its establishment time"); + + client.ping(); + Assert.assertEquals(times.value(), 0.0, 0.0, + "Reusing a pooled connection should not record another sample"); } } }