-
Notifications
You must be signed in to change notification settings - Fork 318
/
ElasticsearchRestClientInstrumentationHelper.java
192 lines (165 loc) · 8.39 KB
/
ElasticsearchRestClientInstrumentationHelper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you 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 co.elastic.apm.agent.esrestclient;
import co.elastic.apm.agent.common.util.WildcardMatcher;
import co.elastic.apm.agent.sdk.internal.util.IOUtils;
import co.elastic.apm.agent.sdk.internal.util.LoggerUtils;
import co.elastic.apm.agent.sdk.logging.Logger;
import co.elastic.apm.agent.sdk.logging.LoggerFactory;
import co.elastic.apm.agent.sdk.weakconcurrent.DetachedThreadLocal;
import co.elastic.apm.agent.sdk.weakconcurrent.WeakConcurrent;
import co.elastic.apm.agent.tracer.AbstractSpan;
import co.elastic.apm.agent.tracer.GlobalTracer;
import co.elastic.apm.agent.tracer.Outcome;
import co.elastic.apm.agent.tracer.Span;
import co.elastic.apm.agent.tracer.Tracer;
import co.elastic.apm.agent.tracer.pooling.Allocator;
import co.elastic.apm.agent.tracer.pooling.ObjectPool;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.ResponseListener;
import javax.annotation.Nullable;
import java.util.concurrent.CancellationException;
public class ElasticsearchRestClientInstrumentationHelper {
private static final DetachedThreadLocal<ElasticsearchEndpointDefinition> currentRequestEndpoint = WeakConcurrent.buildThreadLocal();
private static final Logger logger = LoggerFactory.getLogger(ElasticsearchRestClientInstrumentationHelper.class);
private static final Logger unsupportedOperationOnceLogger = LoggerUtils.logOnce(logger);
private static final ElasticsearchRestClientInstrumentationHelper INSTANCE = new ElasticsearchRestClientInstrumentationHelper(GlobalTracer.get());
public static final String SPAN_TYPE = "db";
public static final String ELASTICSEARCH = "elasticsearch";
public static final String SPAN_ACTION = "request";
private static final int MAX_POOLED_ELEMENTS = 256;
private final Tracer tracer;
private final ElasticsearchConfiguration config;
private final ObjectPool<ResponseListenerWrapper> responseListenerObjectPool;
public static ElasticsearchRestClientInstrumentationHelper get() {
return INSTANCE;
}
private ElasticsearchRestClientInstrumentationHelper(Tracer tracer) {
this.tracer = tracer;
this.responseListenerObjectPool = tracer.getObjectPoolFactory().createRecyclableObjectPool(MAX_POOLED_ELEMENTS, new ResponseListenerAllocator());
this.config = tracer.getConfig(ElasticsearchConfiguration.class);
}
private class ResponseListenerAllocator implements Allocator<ResponseListenerWrapper> {
@Override
public ResponseListenerWrapper createInstance() {
return new ResponseListenerWrapper(ElasticsearchRestClientInstrumentationHelper.this, ElasticsearchRestClientInstrumentationHelper.this.tracer);
}
}
public void setCurrentEndpoint(String endpointId) {
currentRequestEndpoint.set(ElasticsearchEndpointMap.get(endpointId));
}
public void clearCurrentEndpoint() {
currentRequestEndpoint.remove();
}
@Nullable
public Span<?> createClientSpan(String method, String httpPath, @Nullable HttpEntity httpEntity) {
ElasticsearchEndpointDefinition endpoint = currentRequestEndpoint.getAndRemove();
Span<?> span = tracer.currentContext().createExitSpan();
// Don't record nested spans. In 5.x clients the instrumented sync method is calling the instrumented async method
if (span == null) {
return null;
}
span.withType(SPAN_TYPE)
.withSubtype(ELASTICSEARCH)
.withAction(SPAN_ACTION);
StringBuilder name = span.getAndOverrideName(AbstractSpan.PRIORITY_HIGH_LEVEL_FRAMEWORK);
if (endpoint != null) {
if (name != null) {
name.append("Elasticsearch: ").append(endpoint.getEndpointName());
}
span.withOtelAttribute("db.operation", endpoint.getEndpointName());
endpoint.addPathPartAttributes(httpPath, span);
} else {
if (name != null) {
name.append("Elasticsearch: ").append(method).append(" ").append(httpPath);
}
}
span.getContext().getDb().withType(ELASTICSEARCH);
span.getContext().getServiceTarget().withType(ELASTICSEARCH);
span.activate();
if (span.isSampled()) {
span.getContext().getHttp().withMethod(method);
if (WildcardMatcher.isAnyMatch(config.getCaptureBodyUrls(), httpPath)) {
if (httpEntity != null && httpEntity.isRepeatable()) {
try {
IOUtils.readUtf8Stream(httpEntity.getContent(), span.getContext().getDb().withStatementBuffer());
} catch (UnsupportedOperationException e) {
// special case for hibernatesearch versions pre 6.0:
// those don't support httpEntity.getContent() and throw an UnsupportedException when called.
unsupportedOperationOnceLogger.error(
"Failed to read Elasticsearch client query from request body, most likely because you are using hibernatesearch pre 6.0", e);
} catch (Exception e) {
logger.error("Failed to read Elasticsearch client query from request body", e);
}
}
}
}
return span;
}
public void finishClientSpan(@Nullable Response response, Span<?> span, @Nullable Throwable t) {
try {
String url = null;
int statusCode = -1;
String address = null;
int port = -1;
String cluster = null;
if (response != null) {
HttpHost host = response.getHost();
address = host.getHostName();
port = host.getPort();
url = host.toURI();
statusCode = response.getStatusLine().getStatusCode();
cluster = response.getHeader("x-found-handling-cluster");
} else if (t != null) {
if (t instanceof ResponseException) {
ResponseException esre = (ResponseException) t;
HttpHost host = esre.getResponse().getHost();
address = host.getHostName();
port = host.getPort();
url = host.toURI();
statusCode = esre.getResponse().getStatusLine().getStatusCode();
} else if (t instanceof CancellationException) {
// We can't tell whether a cancelled search is related to a failure or not
span.withOutcome(Outcome.UNKNOWN);
}
span.captureException(t);
}
if (url != null && !url.isEmpty()) {
span.getContext().getHttp().withUrl(url);
}
span.getContext().getHttp().withStatusCode(statusCode);
span.getContext().getDestination().withAddress(address).withPort(port);
span.getContext().getServiceTarget().withName(cluster);
} finally {
span.end();
}
}
public ResponseListener wrapClientResponseListener(ResponseListener listener, Span<?> span) {
return responseListenerObjectPool.createInstance().withClientSpan(listener, span);
}
public ResponseListener wrapContextPropagationContextListener(ResponseListener listener, AbstractSpan<?> activeContext) {
return responseListenerObjectPool.createInstance().withContextPropagation(listener, activeContext);
}
void recycle(ResponseListenerWrapper listenerWrapper) {
responseListenerObjectPool.recycle(listenerWrapper);
}
}