-
Notifications
You must be signed in to change notification settings - Fork 77
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a monitor for the OpenMetrics endpoint. This populates the runnin…
…g and queued query metrics for active load balancing, and allows defining health using minimum and maximum values for arbitrary metrics
- Loading branch information
1 parent
a54cb14
commit 1a4519d
Showing
8 changed files
with
318 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
204 changes: 204 additions & 0 deletions
204
gateway-ha/src/main/java/io/trino/gateway/ha/clustermonitor/ClusterStatsMetricsMonitor.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) {} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,5 +18,6 @@ public enum ClusterStatsMonitorType | |
NOOP, | ||
INFO_API, | ||
UI_API, | ||
JDBC | ||
JDBC, | ||
METRICS | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.