Skip to content

Commit

Permalink
Add a monitor for the OpenMetrics endpoint. This populates the runnin…
Browse files Browse the repository at this point in the history
…g and queued query metrics for active load balancing, and allows defining health using minimum and maximum values for arbitrary metrics
  • Loading branch information
willmostly committed Jan 9, 2025
1 parent a54cb14 commit 1a4519d
Show file tree
Hide file tree
Showing 8 changed files with 318 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@
import static io.airlift.http.client.JsonResponseHandler.createJsonResponseHandler;
import static io.airlift.http.client.Request.Builder.prepareGet;
import static io.airlift.json.JsonCodec.jsonCodec;
import static java.net.HttpURLConnection.HTTP_BAD_GATEWAY;
import static java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT;
import static java.net.HttpURLConnection.HTTP_UNAVAILABLE;
import static io.trino.gateway.ha.clustermonitor.ClusterStatsMonitor.shouldRetry;
import static java.util.Objects.requireNonNull;

public class ClusterStatsInfoApiMonitor
Expand Down Expand Up @@ -88,16 +86,4 @@ private TrinoStatus checkStatus(String baseUrl, int retriesRemaining)
}
return TrinoStatus.UNHEALTHY;
}

public static boolean shouldRetry(int statusCode)
{
switch (statusCode) {
case HTTP_BAD_GATEWAY:
case HTTP_UNAVAILABLE:
case HTTP_GATEWAY_TIMEOUT:
return true;
default:
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
/*
* 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 io.trino.gateway.ha.clustermonitor;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.airlift.http.client.HttpClient;
import io.airlift.http.client.HttpUriBuilder;
import io.airlift.http.client.Request;
import io.airlift.http.client.Response;
import io.airlift.http.client.ResponseHandler;
import io.airlift.http.client.UnexpectedResponseException;
import io.airlift.log.Logger;
import io.trino.gateway.ha.config.BackendStateConfiguration;
import io.trino.gateway.ha.config.MonitorConfiguration;
import io.trino.gateway.ha.config.ProxyBackendConfiguration;
import io.trino.gateway.ha.security.util.BasicCredentials;

import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static io.airlift.http.client.HttpUriBuilder.uriBuilderFrom;
import static io.airlift.http.client.Request.Builder.prepareGet;
import static io.airlift.http.client.ResponseHandlerUtils.propagate;
import static io.trino.gateway.ha.clustermonitor.ClusterStatsMonitor.shouldRetry;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;

public class ClusterStatsMetricsMonitor
implements ClusterStatsMonitor
{
public static final String RUNNING_QUERIES_METRIC = "trino_execution_name_QueryManager_RunningQueries";
public static final String QUEUED_QUERIES_METRIC = "trino_execution_name_QueryManager_QueuedQueries";
private static final Logger log = Logger.get(ClusterStatsMetricsMonitor.class);
private final HttpClient client;
private final int retries;
private final MetricsResponseHandler metricsResponseHandler;
private final Header identityHeader;
private final String metricsEndpoint;
private final ImmutableSet<String> metricNames;
private final Map<String, Float> metricMinimumValues;
private final Map<String, Float> metricMaximumValues;

public ClusterStatsMetricsMonitor(HttpClient client, BackendStateConfiguration backendStateConfiguration, MonitorConfiguration monitorConfiguration)
{
this.client = requireNonNull(client, "client is null");
retries = monitorConfiguration.getRetries();
if (!isNullOrEmpty(backendStateConfiguration.getPassword())) {
identityHeader = new Header("Authorization",
new BasicCredentials(backendStateConfiguration.getUsername(), backendStateConfiguration.getPassword()).getBasicAuthHeader());
}
else {
identityHeader = new Header("X-Trino-User", backendStateConfiguration.getUsername());
}
metricsEndpoint = monitorConfiguration.getMetricsEndpoint();
metricMinimumValues = monitorConfiguration.getMetricMinimumValues();
metricMaximumValues = monitorConfiguration.getMetricMaximumValues();
metricNames = ImmutableSet.<String>builder()
.add(RUNNING_QUERIES_METRIC, QUEUED_QUERIES_METRIC)
.addAll(metricMinimumValues.keySet())
.addAll(metricMaximumValues.keySet())
.build();
metricsResponseHandler = new MetricsResponseHandler(metricNames);
}

private ClusterStats getUnhealthyStats(ProxyBackendConfiguration backend)
{
return ClusterStats.builder(backend.getName())
.trinoStatus(TrinoStatus.UNHEALTHY)
.proxyTo(backend.getProxyTo())
.externalUrl(backend.getExternalUrl())
.routingGroup(backend.getRoutingGroup())
.build();
}

@Override
public ClusterStats monitor(ProxyBackendConfiguration backend)
{
Map<String, String> metrics = getMetrics(backend.getProxyTo(), retries);
if (metrics.isEmpty()) {
log.error(String.format("No metrics available for %s!", backend.getName()));
return getUnhealthyStats(backend);
}

for (Map.Entry<String, Float> entry : metricMinimumValues.entrySet()) {
if (!metrics.containsKey(entry.getKey())
|| Float.parseFloat(metrics.get(entry.getKey())) < entry.getValue()) {
log.warn(String.format("Health metric value below min for cluster %s: %s=%s", backend.getName(), entry.getKey(), metrics.get(entry.getKey())));
return getUnhealthyStats(backend);
}
}

for (Map.Entry<String, Float> entry : metricMaximumValues.entrySet()) {
if (!metrics.containsKey(entry.getKey())
|| Float.parseFloat(metrics.get(entry.getKey())) > entry.getValue()) {
log.warn(String.format("Health metric value over max for cluster %s: %s=%s", backend.getName(), entry.getKey(), metrics.get(entry.getKey())));
return getUnhealthyStats(backend);
}
}
return ClusterStats.builder(backend.getName())
.trinoStatus(TrinoStatus.HEALTHY)
.runningQueryCount((int) Float.parseFloat(metrics.get(RUNNING_QUERIES_METRIC)))
.queuedQueryCount((int) Float.parseFloat(metrics.get(QUEUED_QUERIES_METRIC)))
.proxyTo(backend.getProxyTo())
.externalUrl(backend.getExternalUrl())
.routingGroup(backend.getRoutingGroup())
.build();
}

private Map<String, String> getMetrics(String baseUrl, int retriesRemaining)
{
HttpUriBuilder uri = uriBuilderFrom(URI.create(baseUrl)).appendPath(metricsEndpoint);
for (String metric : metricNames) {
uri.addParameter("name[]", metric);
}

Request request = prepareGet()
.setUri(uri.build())
.addHeader(identityHeader.name, identityHeader.value)
.addHeader("Content-Type", "application/openmetrics-text; version=1.0.0; charset=utf-8")
.build();
try {
return client.execute(request, metricsResponseHandler);
}
catch (UnexpectedResponseException e) {
if (shouldRetry(e.getStatusCode())) {
if (retriesRemaining > 0) {
log.warn("Retrying health check on error: %s, ", e.toString());
return getMetrics(baseUrl, retriesRemaining - 1);
}
else {
log.error("Encountered error %s, no retries remaining", e.toString());
}
}
else {
log.error(e, "Health check failed with non-retryable response. %s\n%s", e.getMessage(), e.toString());
}
}
catch (Exception e) {
log.error(e, "Exception checking %s for health", request.getUri());
}
return ImmutableMap.of();
}

private static class MetricsResponseHandler
implements ResponseHandler<Map<String, String>, RuntimeException>
{
private final ImmutableSet<String> requiredKeys;

public MetricsResponseHandler(ImmutableSet<String> requiredKeys)
{
this.requiredKeys = requiredKeys;
}

@Override
public Map<String, String> handleException(Request request, Exception exception)
throws RuntimeException
{
throw propagate(request, exception);
}

@Override
public Map<String, String> handle(Request request, Response response)
throws RuntimeException
{
try {
String responseBody = new String(response.getInputStream().readAllBytes(), UTF_8);
Map<String, String> metrics = Arrays.stream(responseBody.split("\n"))
.filter(s -> !s.startsWith("#"))
.collect(toImmutableMap(s -> s.split(" ")[0], s -> s.split(" ")[1]));
if (!metrics.keySet().containsAll(requiredKeys)) {
throw new UnexpectedResponseException(
String.format("Request is missing required keys: \n%s\nin response: '%s'", String.join("\n", requiredKeys), responseBody),
request,
response);
}
return metrics;
}
catch (IOException e) {
throw new UnexpectedResponseException(request, response);
}
}
}

private record Header(String name, String value) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@

import io.trino.gateway.ha.config.ProxyBackendConfiguration;

import static java.net.HttpURLConnection.HTTP_BAD_GATEWAY;
import static java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT;
import static java.net.HttpURLConnection.HTTP_UNAVAILABLE;

public interface ClusterStatsMonitor
{
ClusterStats monitor(ProxyBackendConfiguration backend);
Expand All @@ -27,4 +31,12 @@ static ClusterStats.Builder getClusterStatsBuilder(ProxyBackendConfiguration bac
builder.routingGroup(backend.getRoutingGroup());
return builder;
}

static boolean shouldRetry(int statusCode)
{
return switch (statusCode) {
case HTTP_BAD_GATEWAY, HTTP_UNAVAILABLE, HTTP_GATEWAY_TIMEOUT -> true;
default -> false;
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ public enum ClusterStatsMonitorType
NOOP,
INFO_API,
UI_API,
JDBC
JDBC,
METRICS
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,24 @@
*/
package io.trino.gateway.ha.config;

import com.google.common.collect.ImmutableMap;
import io.trino.gateway.ha.clustermonitor.ActiveClusterMonitor;

import java.util.Map;

public class MonitorConfiguration
{
private int taskDelaySeconds = ActiveClusterMonitor.MONITOR_TASK_DELAY_SECONDS;

private int retries;

private String metricsEndpoint = "/metrics";

// Require 1 node for health by default. This configuration only applies to the ClusterStatsMetricsMonitor
private Map<String, Float> metricMinimumValues = ImmutableMap.of("trino_metadata_name_DiscoveryNodeManager_ActiveNodeCount", 1f);

private Map<String, Float> metricMaximumValues = ImmutableMap.of();

public MonitorConfiguration() {}

public int getTaskDelaySeconds()
Expand All @@ -42,4 +52,34 @@ public void setRetries(int retries)
{
this.retries = retries;
}

public String getMetricsEndpoint()
{
return metricsEndpoint;
}

public void setMetricsEndpoint(String metricsEndpoint)
{
this.metricsEndpoint = metricsEndpoint;
}

public Map<String, Float> getMetricMinimumValues()
{
return metricMinimumValues;
}

public void setMetricMinimumValues(Map<String, Float> metricMinimumValues)
{
this.metricMinimumValues = metricMinimumValues;
}

public Map<String, Float> getMetricMaximumValues()
{
return metricMaximumValues;
}

public void setMetricMaximumValues(Map<String, Float> metricMaximumValues)
{
this.metricMaximumValues = metricMaximumValues;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import io.trino.gateway.ha.clustermonitor.ClusterStatsHttpMonitor;
import io.trino.gateway.ha.clustermonitor.ClusterStatsInfoApiMonitor;
import io.trino.gateway.ha.clustermonitor.ClusterStatsJdbcMonitor;
import io.trino.gateway.ha.clustermonitor.ClusterStatsMetricsMonitor;
import io.trino.gateway.ha.clustermonitor.ClusterStatsMonitor;
import io.trino.gateway.ha.clustermonitor.ForMonitor;
import io.trino.gateway.ha.clustermonitor.NoopClusterStatsMonitor;
Expand Down Expand Up @@ -51,6 +52,7 @@ public ClusterStatsMonitor getClusterStatsMonitor(@ForMonitor HttpClient httpCli
case UI_API -> new ClusterStatsHttpMonitor(config.getBackendState());
case JDBC -> new ClusterStatsJdbcMonitor(config.getBackendState(), config.getMonitor());
case NOOP -> new NoopClusterStatsMonitor();
case METRICS -> new ClusterStatsMetricsMonitor(httpClient, config.getBackendState(), config.getMonitor());
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ public static BasicCredentials extractBasicAuthCredentials(ContainerRequestConte
return extractBasicAuthCredentials(header);
}

public String getBasicAuthHeader()
{
return String.format("Basic %s", encodeCredentials());
}

public static BasicCredentials extractBasicAuthCredentials(String header)
throws AuthenticationException
{
Expand Down Expand Up @@ -78,4 +83,9 @@ private static String decodeCredentials(String credentials)
throw new AuthenticationException("Invalid base64 encoded credentials");
}
}

private String encodeCredentials()
{
return Base64.getEncoder().encodeToString(String.format("%s:%s", username, password).getBytes(ISO_8859_1));
}
}
Loading

0 comments on commit 1a4519d

Please sign in to comment.