-
Notifications
You must be signed in to change notification settings - Fork 96
/
TracingInterceptor.java
518 lines (445 loc) · 21.6 KB
/
TracingInterceptor.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 com.amazonaws.xray.interceptors;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.AWSXRayRecorder;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.EntityDataKeys;
import com.amazonaws.xray.entities.EntityHeaderKeys;
import com.amazonaws.xray.entities.Namespace;
import com.amazonaws.xray.entities.Subsegment;
import com.amazonaws.xray.entities.TraceHeader;
import com.amazonaws.xray.handlers.config.AWSOperationHandler;
import com.amazonaws.xray.handlers.config.AWSOperationHandlerManifest;
import com.amazonaws.xray.handlers.config.AWSServiceHandlerManifest;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import software.amazon.awssdk.awscore.AwsExecutionAttribute;
import software.amazon.awssdk.awscore.AwsResponse;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.regions.Region;
public class TracingInterceptor implements ExecutionInterceptor {
/**
* @deprecated For internal use only.
*/
@Deprecated
@SuppressWarnings("checkstyle:ConstantName")
// TODO(anuraaga): Make private in next major version and rename.
public static final ExecutionAttribute<Subsegment> entityKey = new ExecutionAttribute("AWS X-Ray Entity");
// Make sure only one xray interceptor takes effect.
private static final ExecutionAttribute<TracingInterceptor> XRAY_INTERCEPTOR_KEY =
new ExecutionAttribute("AWS X-Ray Interceptor");
private static final Log logger = LogFactory.getLog(TracingInterceptor.class);
private static final ObjectMapper MAPPER = new ObjectMapper()
.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
private static final PropertyNamingStrategies.NamingBase
SNAKE_CASE_NAMING_STRATEGY = (PropertyNamingStrategies.NamingBase) PropertyNamingStrategies.SNAKE_CASE;
private static final URL DEFAULT_OPERATION_PARAMETER_WHITELIST =
TracingInterceptor.class.getResource("/com/amazonaws/xray/interceptors/DefaultOperationParameterWhitelist.json");
private static final String UNKNOWN_REQUEST_ID = "UNKNOWN";
private static final List<String> REQUEST_ID_KEYS = Arrays.asList("x-amz-request-id", "x-amzn-requestid");
private AWSServiceHandlerManifest awsServiceHandlerManifest;
private AWSXRayRecorder recorder;
private final String accountId;
public TracingInterceptor() {
this(null, null, null);
}
public TracingInterceptor(AWSXRayRecorder recorder, String accountId, URL parameterWhitelist) {
this.recorder = recorder;
this.accountId = accountId;
initInterceptorManifest(parameterWhitelist);
}
private void initInterceptorManifest(URL parameterWhitelist) {
if (parameterWhitelist != null) {
try {
awsServiceHandlerManifest = MAPPER.readValue(parameterWhitelist, AWSServiceHandlerManifest.class);
return;
} catch (IOException e) {
logger.error(
"Unable to parse operation parameter whitelist at " + parameterWhitelist.getPath()
+ ". Falling back to default operation parameter whitelist at "
+ TracingInterceptor.DEFAULT_OPERATION_PARAMETER_WHITELIST.getPath() + ".",
e
);
}
}
try {
awsServiceHandlerManifest = MAPPER.readValue(
TracingInterceptor.DEFAULT_OPERATION_PARAMETER_WHITELIST, AWSServiceHandlerManifest.class);
} catch (IOException e) {
logger.error(
"Unable to parse default operation parameter whitelist at "
+ TracingInterceptor.DEFAULT_OPERATION_PARAMETER_WHITELIST.getPath()
+ ". This will affect this handler's ability to capture AWS operation parameter information.",
e
);
}
}
private AWSOperationHandler getOperationHandler(ExecutionAttributes executionAttributes) {
String serviceName = executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME);
String operationName = executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME);
if (awsServiceHandlerManifest == null) {
return null;
}
AWSOperationHandlerManifest operationManifest = awsServiceHandlerManifest.getOperationHandlerManifest(serviceName);
if (operationManifest == null) {
return null;
}
return operationManifest.getOperationHandler(operationName);
}
private HashMap<String, Object> extractRequestParameters(
Context.BeforeExecution context, ExecutionAttributes executionAttributes) {
HashMap<String, Object> parameters = new HashMap<>();
AWSOperationHandler operationHandler = getOperationHandler(executionAttributes);
if (operationHandler == null) {
return parameters;
}
if (operationHandler.getRequestParameters() != null) {
operationHandler.getRequestParameters().forEach((parameterName) -> {
SdkRequest request = context.request();
Optional<Object> parameterValue = request.getValueForField(parameterName, Object.class);
if (parameterValue.isPresent()) {
parameters.put(normalizeParameterName(
SNAKE_CASE_NAMING_STRATEGY.translate(parameterName)), parameterValue.get());
}
});
}
if (operationHandler.getRequestDescriptors() != null) {
operationHandler.getRequestDescriptors().forEach((key, descriptor) -> {
if (descriptor.isMap() && descriptor.shouldGetKeys()) {
SdkRequest request = context.request();
Optional<Map> parameterValue = request.getValueForField(key, Map.class);
if (parameterValue.isPresent()) {
String renameTo = descriptor.getRenameTo() != null ? descriptor.getRenameTo() : key;
parameters.put(normalizeParameterName(
SNAKE_CASE_NAMING_STRATEGY.translate(renameTo)), parameterValue.get().keySet());
}
} else if (descriptor.isList() && descriptor.shouldGetCount()) {
SdkRequest request = context.request();
Optional<List> parameterValue = request.getValueForField(key, List.class);
if (parameterValue.isPresent()) {
String renameTo = descriptor.getRenameTo() != null ? descriptor.getRenameTo() : key;
parameters.put(normalizeParameterName(
SNAKE_CASE_NAMING_STRATEGY.translate(renameTo)), parameterValue.get().size());
}
}
});
}
return parameters;
}
/**
* @param parameterName
* The name of the parameter to normalize.
* @return
* The field key for a parameter that the X-Ray backend expects.
*/
private String normalizeParameterName(String parameterName) {
// AWS SDK V2 changed the field name from BucketName to Bucket.
if (parameterName.equals("bucket")) {
return "bucket_name";
}
return parameterName;
}
private HashMap<String, Object> extractResponseParameters(
Context.AfterExecution context, ExecutionAttributes executionAttributes) {
HashMap<String, Object> parameters = new HashMap<>();
AWSOperationHandler operationHandler = getOperationHandler(executionAttributes);
if (operationHandler == null) {
return parameters;
}
if (operationHandler.getResponseParameters() != null) {
operationHandler.getResponseParameters().forEach((parameterName) -> {
SdkResponse response = context.response();
Optional<Object> parameterValue = response.getValueForField(parameterName, Object.class);
if (parameterValue.isPresent()) {
parameters.put(normalizeParameterName(
SNAKE_CASE_NAMING_STRATEGY.translate(parameterName)), parameterValue.get());
}
});
}
if (operationHandler.getResponseDescriptors() != null) {
operationHandler.getResponseDescriptors().forEach((key, descriptor) -> {
if (descriptor.isMap() && descriptor.shouldGetKeys()) {
SdkResponse response = context.response();
Optional<Map> parameterValue = response.getValueForField(key, Map.class);
if (parameterValue.isPresent()) {
String renameTo = descriptor.getRenameTo() != null ? descriptor.getRenameTo() : key;
parameters.put(normalizeParameterName(
SNAKE_CASE_NAMING_STRATEGY.translate(renameTo)), parameterValue.get().keySet());
}
} else if (descriptor.isList() && descriptor.shouldGetCount()) {
SdkResponse response = context.response();
Optional<List> parameterValue = response.getValueForField(key, List.class);
if (parameterValue.isPresent()) {
String renameTo = descriptor.getRenameTo() != null ? descriptor.getRenameTo() : key;
parameters.put(normalizeParameterName(
SNAKE_CASE_NAMING_STRATEGY.translate(renameTo)), parameterValue.get().size());
}
}
});
}
return parameters;
}
private boolean isDuplicateInterceptor(ExecutionAttributes executionAttributes) {
if (executionAttributes.getAttribute(XRAY_INTERCEPTOR_KEY) == null) {
executionAttributes.putAttribute(XRAY_INTERCEPTOR_KEY, this);
return false;
}
if (executionAttributes.getAttribute(XRAY_INTERCEPTOR_KEY) != this) {
return true;
}
return false;
}
@Override
public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) {
if (isDuplicateInterceptor(executionAttributes)) {
logger.debug("X-Ray TracingInterceptor already exists.");
return;
}
AWSXRayRecorder recorder = getRecorder();
Entity origin = recorder.getTraceEntity();
Subsegment subsegment = recorder.beginSubsegment(executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME));
subsegment.setNamespace(Namespace.AWS.toString());
subsegment.putAws(EntityDataKeys.AWS.OPERATION_KEY,
executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME));
Region region = executionAttributes.getAttribute(AwsExecutionAttribute.AWS_REGION);
if (region != null) {
subsegment.putAws(EntityDataKeys.AWS.REGION_KEY, region.id());
}
subsegment.putAllAws(extractRequestParameters(context, executionAttributes));
if (accountId != null) {
subsegment.putAws(EntityDataKeys.AWS.ACCOUNT_ID_SUBSEGMENT_KEY, accountId);
}
recorder.setTraceEntity(origin);
// store the subsegment in the AWS SDK's executionAttributes so it can be accessed across threads
executionAttributes.putAttribute(entityKey, subsegment);
}
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
SdkHttpRequest httpRequest = context.httpRequest();
if (isDuplicateInterceptor(executionAttributes)) {
return httpRequest;
}
Subsegment subsegment = executionAttributes.getAttribute(entityKey);
if (!subsegment.shouldPropagate()) {
return httpRequest;
}
return httpRequest.toBuilder().putHeader(
TraceHeader.HEADER_KEY,
TraceHeader.fromEntity(subsegment).toString()).build();
}
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
if (isDuplicateInterceptor(executionAttributes)) {
return;
}
Subsegment subsegment = executionAttributes.getAttribute(entityKey);
if (subsegment == null) {
return;
}
Map<String, Object> awsProperties = subsegment.getAws();
// beforeTransmission is run before every API call attempt
// default value is set to -1 and will always be -1 on the first API call attempt
// this value will be incremented by 1, so initial run will have a stored retryCount of 0
int retryCount = (int) awsProperties.getOrDefault(EntityDataKeys.AWS.RETRIES_KEY, -1);
awsProperties.put(EntityDataKeys.AWS.RETRIES_KEY, retryCount + 1);
}
@Override
public void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) {
if (isDuplicateInterceptor(executionAttributes)) {
return;
}
Subsegment subsegment = executionAttributes.getAttribute(entityKey);
if (subsegment == null) {
return;
}
populateRequestId(subsegment, context);
populateSubsegmentWithResponse(subsegment, context.httpResponse());
subsegment.putAllAws(extractResponseParameters(context, executionAttributes));
getRecorder().endSubsegment(subsegment);
}
@Override
public void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) {
if (isDuplicateInterceptor(executionAttributes)) {
return;
}
Subsegment subsegment = executionAttributes.getAttribute(entityKey);
if (subsegment == null) {
return;
}
populateSubsegmentException(subsegment, context);
populateRequestId(subsegment, context);
if (context.httpResponse().isPresent()) {
populateSubsegmentWithResponse(subsegment, context.httpResponse().get());
}
getRecorder().endSubsegment(subsegment);
}
private HashMap<String, Object> extractHttpResponseParameters(SdkHttpResponse httpResponse) {
HashMap<String, Object> parameters = new HashMap<>();
HashMap<String, Object> responseData = new HashMap<>();
responseData.put(EntityDataKeys.HTTP.STATUS_CODE_KEY, httpResponse.statusCode());
try {
if (httpResponse.headers().containsKey(EntityHeaderKeys.HTTP.CONTENT_LENGTH_HEADER)) {
responseData.put(EntityDataKeys.HTTP.CONTENT_LENGTH_KEY, Long.parseLong(
httpResponse.headers().get(EntityHeaderKeys.HTTP.CONTENT_LENGTH_HEADER).get(0))
);
}
} catch (NumberFormatException e) {
logger.warn("Unable to parse Content-Length header.", e);
}
parameters.put(EntityDataKeys.HTTP.RESPONSE_KEY, responseData);
return parameters;
}
private void setRemoteForException(Subsegment subsegment, Throwable exception) {
subsegment.getCause().getExceptions().forEach((e) -> {
if (e.getThrowable() == exception) {
e.setRemote(true);
}
});
}
private void populateSubsegmentException(Subsegment subsegment, Context.FailedExecution context) {
Throwable exception = context.exception();
subsegment.addException(exception);
int statusCode = -1;
if (exception instanceof SdkServiceException) {
statusCode = ((SdkServiceException) exception).statusCode();
subsegment.getCause().setMessage(exception.getMessage());
if (((SdkServiceException) exception).isThrottlingException()) {
subsegment.setThrottle(true);
// throttling errors are considered client-side errors
subsegment.setError(true);
}
setRemoteForException(subsegment, exception);
} else if (context.httpResponse().isPresent()) {
statusCode = context.httpResponse().get().statusCode();
}
if (statusCode == -1) {
return;
}
if (statusCode >= 400 && statusCode < 500) {
subsegment.setFault(false);
subsegment.setError(true);
if (statusCode == 429) {
subsegment.setThrottle(true);
}
} else if (statusCode >= 500) {
subsegment.setFault(true);
}
}
private void populateRequestId(
Subsegment subsegment,
Optional<SdkResponse> response,
Optional<SdkHttpResponse> httpResponse,
Throwable exception
) {
String requestId = null;
if (exception != null) {
requestId = extractRequestIdFromThrowable(exception);
}
if (requestId == null || requestId.equals(UNKNOWN_REQUEST_ID)) {
requestId = extractRequestIdFromResponse(response);
}
if (requestId == null || requestId.equals(UNKNOWN_REQUEST_ID)) {
requestId = extractRequestIdFromHttp(httpResponse);
}
if (requestId != null && !requestId.equals(UNKNOWN_REQUEST_ID)) {
subsegment.putAws(EntityDataKeys.AWS.REQUEST_ID_KEY, requestId);
}
}
private void populateRequestId(Subsegment subsegment, Context.FailedExecution context) {
populateRequestId(subsegment, context.response(), context.httpResponse(), context.exception());
}
private void populateRequestId(Subsegment subsegment, Context.AfterExecution context) {
populateRequestId(subsegment, Optional.of(context.response()), Optional.of(context.httpResponse()), null);
}
private String extractRequestIdFromHttp(Optional<SdkHttpResponse> httpResponse) {
if (!httpResponse.isPresent()) {
return null;
}
return extractRequestIdFromHttp(httpResponse.get());
}
private String extractRequestIdFromHttp(SdkHttpResponse httpResponse) {
Map<String, List<String>> headers = httpResponse.headers();
Set<String> headerKeys = headers.keySet();
String requestIdKey = headerKeys
.stream()
.filter(key -> REQUEST_ID_KEYS.contains(key.toLowerCase()))
.findFirst()
.orElse(null);
return requestIdKey != null ? headers.get(requestIdKey).get(0) : null;
}
private String extractExtendedRequestIdFromHttp(SdkHttpResponse httpResponse) {
Map<String, List<String>> headers = httpResponse.headers();
return headers.containsKey(EntityHeaderKeys.AWS.EXTENDED_REQUEST_ID_HEADER) ?
headers.get(EntityHeaderKeys.AWS.EXTENDED_REQUEST_ID_HEADER).get(0) : null;
}
private String extractRequestIdFromThrowable(Throwable exception) {
if (exception instanceof SdkServiceException) {
return ((SdkServiceException) exception).requestId();
}
return null;
}
private String extractRequestIdFromResponse(Optional<SdkResponse> response) {
if (response.isPresent()) {
return extractRequestIdFromResponse(response.get());
}
return null;
}
private String extractRequestIdFromResponse(SdkResponse response) {
if (response instanceof AwsResponse) {
return ((AwsResponse) response).responseMetadata().requestId();
}
return null;
}
private void populateSubsegmentWithResponse(Subsegment subsegment, SdkHttpResponse httpResponse) {
if (subsegment == null || httpResponse == null) {
return;
}
String extendedRequestId = extractExtendedRequestIdFromHttp(httpResponse);
if (extendedRequestId != null) {
subsegment.putAws(EntityDataKeys.AWS.EXTENDED_REQUEST_ID_KEY, extendedRequestId);
}
subsegment.putAllHttp(extractHttpResponseParameters(httpResponse));
}
private AWSXRayRecorder getRecorder() {
if (recorder == null) {
recorder = AWSXRay.getGlobalRecorder();
}
return recorder;
}
}