|
| 1 | +/* |
| 2 | + * Licensed to Elasticsearch B.V. under one or more contributor |
| 3 | + * license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright |
| 5 | + * ownership. Elasticsearch B.V. licenses this file to you under |
| 6 | + * the Apache License, Version 2.0 (the "License"); you may |
| 7 | + * not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +package co.elastic.clients.transport.rest_client; |
| 21 | + |
| 22 | +import co.elastic.clients.transport.Endpoint; |
| 23 | +import io.opentelemetry.api.GlobalOpenTelemetry; |
| 24 | +import io.opentelemetry.api.OpenTelemetry; |
| 25 | +import io.opentelemetry.api.common.AttributeKey; |
| 26 | +import io.opentelemetry.api.trace.Span; |
| 27 | +import io.opentelemetry.api.trace.SpanKind; |
| 28 | +import io.opentelemetry.api.trace.Tracer; |
| 29 | +import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; |
| 30 | +import org.apache.commons.logging.Log; |
| 31 | +import org.apache.commons.logging.LogFactory; |
| 32 | +import org.apache.http.HttpEntity; |
| 33 | +import org.apache.http.HttpHost; |
| 34 | +import org.elasticsearch.client.Response; |
| 35 | + |
| 36 | +import javax.annotation.Nullable; |
| 37 | +import java.io.BufferedReader; |
| 38 | +import java.io.IOException; |
| 39 | +import java.io.InputStreamReader; |
| 40 | +import java.net.InetAddress; |
| 41 | +import java.nio.charset.StandardCharsets; |
| 42 | +import java.util.Arrays; |
| 43 | +import java.util.HashSet; |
| 44 | +import java.util.Locale; |
| 45 | +import java.util.Map; |
| 46 | +import java.util.Set; |
| 47 | +import java.util.stream.Collectors; |
| 48 | + |
| 49 | +public class Instrumentation { |
| 50 | + |
| 51 | + private static final Set<String> SEARCH_ENDPOINTS = new HashSet<>(Arrays.asList( |
| 52 | + "render_search_template", |
| 53 | + "terms_enum", |
| 54 | + "msearch_template", |
| 55 | + "eql.search", |
| 56 | + "msearch", |
| 57 | + "search_template", |
| 58 | + "async_search.submit", |
| 59 | + "search")); |
| 60 | + |
| 61 | + |
| 62 | + // these reflect the config options in the OTel Java agent |
| 63 | + private static final boolean INSTRUMENTATION_ENABLED = |
| 64 | + Boolean.parseBoolean( |
| 65 | + ConfigUtil.getConfigOption("otel.instrumentation.elasticsearch.enabled", "true")); |
| 66 | + |
| 67 | + private static final boolean CAPTURE_SEARCH_BODY = |
| 68 | + Boolean.parseBoolean( |
| 69 | + ConfigUtil.getConfigOption("otel.instrumentation.elasticsearch.capture-search-query", "false")); |
| 70 | + |
| 71 | + private static final Log logger = LogFactory.getLog(Instrumentation.class); |
| 72 | + |
| 73 | + private final Tracer tracer; |
| 74 | + |
| 75 | + public Instrumentation(@Nullable OpenTelemetry openTelemetry) { |
| 76 | + if (openTelemetry == null) { |
| 77 | + openTelemetry = GlobalOpenTelemetry.get(); |
| 78 | + } |
| 79 | + |
| 80 | + tracer = openTelemetry.getTracer("elasticsearch-api"); |
| 81 | + } |
| 82 | + |
| 83 | + public <RequestT, ResponseT, ErrorT> Span createSpanForRequest(RequestT request, |
| 84 | + Endpoint<RequestT, ResponseT, ErrorT> endpoint) { |
| 85 | + if (!INSTRUMENTATION_ENABLED) { |
| 86 | + return Span.getInvalid(); |
| 87 | + } |
| 88 | + |
| 89 | + Span span = tracer.spanBuilder(endpoint.id()).setSpanKind(SpanKind.CLIENT).startSpan(); |
| 90 | + if (isInvalidSpan(span)) { |
| 91 | + span.setAttribute(OTelAttributes.DB_SYSTEM, "elasticsearch"); |
| 92 | + span.setAttribute(OTelAttributes.DB_OPERATION, endpoint.id()); |
| 93 | + span.setAttribute(OTelAttributes.HTTP_REQUEST_METHOD, endpoint.method(request)); |
| 94 | + |
| 95 | + for (Map.Entry<String, String> pathParamEntry : endpoint.pathParameters(request).entrySet()) { |
| 96 | + String attributeKey = OTelAttributes.PATH_PART_PREFIX + pathParamEntry.getKey(); |
| 97 | + span.setAttribute(AttributeKey.stringKey(attributeKey), pathParamEntry.getValue()); |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + return span; |
| 102 | + } |
| 103 | + |
| 104 | + public void captureResponseInformation(@Nullable Span span, Response response) { |
| 105 | + if (isInvalidSpan(span)) { |
| 106 | + return; |
| 107 | + } |
| 108 | + |
| 109 | + HttpHost host = response.getHost(); |
| 110 | + String uri = response.getRequestLine().getUri(); |
| 111 | + uri = uri.startsWith("/") ? uri : "/" + uri; |
| 112 | + String fullUrl = host.toURI() + uri; |
| 113 | + |
| 114 | + span.setAttribute(OTelAttributes.URL_FULL, fullUrl); |
| 115 | + span.setAttribute(OTelAttributes.SERVER_PORT, host.getPort()); |
| 116 | + |
| 117 | + InetAddress hostAddress = response.getHost().getAddress(); |
| 118 | + if (hostAddress != null) { |
| 119 | + span.setAttribute(OTelAttributes.SERVER_ADDRESS, hostAddress.getHostAddress()); |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + public <RequestT> void captureBody(@Nullable Span span, Endpoint<RequestT, ?, ?> endpoint, |
| 124 | + HttpEntity httpEntity) { |
| 125 | + try { |
| 126 | + if (shouldCaptureBody(span, endpoint, httpEntity)) { |
| 127 | + |
| 128 | + String body = new BufferedReader( |
| 129 | + new InputStreamReader(httpEntity.getContent(), StandardCharsets.UTF_8)) |
| 130 | + .lines() |
| 131 | + .collect(Collectors.joining()); |
| 132 | + |
| 133 | + span.setAttribute(OTelAttributes.DB_STATEMENT, body); |
| 134 | + } |
| 135 | + } catch (IOException e) { |
| 136 | + logger.debug("Failed reading HTTP body content.", e); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + private <RequestT> boolean shouldCaptureBody(@Nullable Span span, Endpoint<RequestT, ?, ?> endpoint, HttpEntity httpEntity) { |
| 141 | + return !isInvalidSpan(span) |
| 142 | + && CAPTURE_SEARCH_BODY |
| 143 | + && SEARCH_ENDPOINTS.contains(endpoint.id()) |
| 144 | + && httpEntity != null |
| 145 | + && httpEntity.isRepeatable(); |
| 146 | + } |
| 147 | + |
| 148 | + private boolean isInvalidSpan(@Nullable Span span) { |
| 149 | + return !INSTRUMENTATION_ENABLED || span == null || !span.isRecording(); |
| 150 | + } |
| 151 | + |
| 152 | + private static final class OTelAttributes { |
| 153 | + private static final AttributeKey<String> DB_SYSTEM = SemanticAttributes.DB_SYSTEM; |
| 154 | + private static final AttributeKey<String> DB_OPERATION = SemanticAttributes.DB_OPERATION; |
| 155 | + private static final AttributeKey<String> DB_STATEMENT = SemanticAttributes.DB_STATEMENT; |
| 156 | + private static final AttributeKey<String> HTTP_REQUEST_METHOD = AttributeKey.stringKey("http.request.method"); |
| 157 | + private static final AttributeKey<String> URL_FULL = AttributeKey.stringKey("url.full"); |
| 158 | + private static final AttributeKey<String> SERVER_ADDRESS = AttributeKey.stringKey("server.address"); |
| 159 | + private static final AttributeKey<Long> SERVER_PORT = AttributeKey.longKey("server.port"); |
| 160 | + |
| 161 | + private static final String PATH_PART_PREFIX = "db.elasticsearch.path_parts."; |
| 162 | + } |
| 163 | + |
| 164 | + private static final class ConfigUtil { |
| 165 | + private static String getConfigOption(String key, String defaultValue) { |
| 166 | + String normalizedKey = normalizePropertyKey(key); |
| 167 | + String systemProperty = |
| 168 | + System.getProperties().entrySet().stream() |
| 169 | + .filter(entry -> normalizedKey.equals(normalizePropertyKey(entry.getKey().toString()))) |
| 170 | + .map(entry -> entry.getValue().toString()) |
| 171 | + .findFirst() |
| 172 | + .orElse(null); |
| 173 | + if (systemProperty != null) { |
| 174 | + return systemProperty; |
| 175 | + } |
| 176 | + return System.getenv().entrySet().stream() |
| 177 | + .filter(entry -> normalizedKey.equals(normalizeEnvironmentVariableKey(entry.getKey()))) |
| 178 | + .map(Map.Entry::getValue) |
| 179 | + .findFirst() |
| 180 | + .orElse(defaultValue); |
| 181 | + } |
| 182 | + |
| 183 | + /** |
| 184 | + * Normalize an environment variable key by converting to lower case and replacing "_" with ".". |
| 185 | + */ |
| 186 | + private static String normalizeEnvironmentVariableKey(String key) { |
| 187 | + return key.toLowerCase(Locale.ROOT).replace("_", "."); |
| 188 | + } |
| 189 | + |
| 190 | + /** |
| 191 | + * Normalize a property key by converting to lower case and replacing "-" with ".". |
| 192 | + */ |
| 193 | + private static String normalizePropertyKey(String key) { |
| 194 | + return key.toLowerCase(Locale.ROOT).replace("-", "."); |
| 195 | + } |
| 196 | + } |
| 197 | +} |
0 commit comments