|
| 1 | +/* |
| 2 | + * Copyright The OpenTelemetry Authors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package io.opentelemetry.contrib.aws.resource; |
| 7 | + |
| 8 | +import com.fasterxml.jackson.core.JsonFactory; |
| 9 | +import com.fasterxml.jackson.core.JsonParser; |
| 10 | +import com.fasterxml.jackson.core.JsonToken; |
| 11 | +import io.opentelemetry.api.common.Attributes; |
| 12 | +import io.opentelemetry.api.common.AttributesBuilder; |
| 13 | +import io.opentelemetry.sdk.resources.Resource; |
| 14 | +import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; |
| 15 | +import java.io.IOException; |
| 16 | +import java.net.MalformedURLException; |
| 17 | +import java.net.URL; |
| 18 | +import java.util.HashMap; |
| 19 | +import java.util.Map; |
| 20 | +import java.util.logging.Level; |
| 21 | +import java.util.logging.Logger; |
| 22 | + |
| 23 | +/** |
| 24 | + * A factory for a {@link Resource} which provides information about the current EC2 instance if |
| 25 | + * running on AWS EC2. |
| 26 | + */ |
| 27 | +public final class Ec2Resource { |
| 28 | + |
| 29 | + private static final Logger logger = Logger.getLogger(Ec2Resource.class.getName()); |
| 30 | + |
| 31 | + private static final JsonFactory JSON_FACTORY = new JsonFactory(); |
| 32 | + |
| 33 | + private static final String DEFAULT_IMDS_ENDPOINT = "169.254.169.254"; |
| 34 | + |
| 35 | + private static final Resource INSTANCE = buildResource(); |
| 36 | + |
| 37 | + /** |
| 38 | + * Returns a @link Resource} which provides information about the current EC2 instance if running |
| 39 | + * on AWS EC2. |
| 40 | + */ |
| 41 | + public static Resource get() { |
| 42 | + return INSTANCE; |
| 43 | + } |
| 44 | + |
| 45 | + private static Resource buildResource() { |
| 46 | + // This property is only for testing e.g., with a mock IMDS server and never in production so we |
| 47 | + // just |
| 48 | + // read from a system property. This is similar to the AWS SDK. |
| 49 | + return buildResource( |
| 50 | + System.getProperty("otel.aws.imds.endpointOverride", DEFAULT_IMDS_ENDPOINT)); |
| 51 | + } |
| 52 | + |
| 53 | + // Visible for testing |
| 54 | + static Resource buildResource(String endpoint) { |
| 55 | + String urlBase = "http://" + endpoint; |
| 56 | + URL identityDocumentUrl; |
| 57 | + URL hostnameUrl; |
| 58 | + URL tokenUrl; |
| 59 | + try { |
| 60 | + identityDocumentUrl = new URL(urlBase + "/latest/dynamic/instance-identity/document"); |
| 61 | + hostnameUrl = new URL(urlBase + "/latest/meta-data/hostname"); |
| 62 | + tokenUrl = new URL(urlBase + "/latest/api/token"); |
| 63 | + } catch (MalformedURLException e) { |
| 64 | + // Can only happen when overriding the endpoint in testing so just throw. |
| 65 | + throw new IllegalArgumentException("Illegal endpoint: " + endpoint, e); |
| 66 | + } |
| 67 | + |
| 68 | + String token = fetchToken(tokenUrl); |
| 69 | + |
| 70 | + // If token is empty, either IMDSv2 isn't enabled or an unexpected failure happened. We can |
| 71 | + // still get data if IMDSv1 is enabled. |
| 72 | + String identity = fetchIdentity(identityDocumentUrl, token); |
| 73 | + if (identity.isEmpty()) { |
| 74 | + // If no identity document, assume we are not actually running on EC2. |
| 75 | + return Resource.empty(); |
| 76 | + } |
| 77 | + |
| 78 | + String hostname = fetchHostname(hostnameUrl, token); |
| 79 | + |
| 80 | + AttributesBuilder attrBuilders = Attributes.builder(); |
| 81 | + attrBuilders.put(ResourceAttributes.CLOUD_PROVIDER, ResourceAttributes.CloudProviderValues.AWS); |
| 82 | + attrBuilders.put( |
| 83 | + ResourceAttributes.CLOUD_PLATFORM, ResourceAttributes.CloudPlatformValues.AWS_EC2); |
| 84 | + |
| 85 | + try (JsonParser parser = JSON_FACTORY.createParser(identity)) { |
| 86 | + parser.nextToken(); |
| 87 | + |
| 88 | + if (!parser.isExpectedStartObjectToken()) { |
| 89 | + throw new IOException("Invalid JSON:" + identity); |
| 90 | + } |
| 91 | + |
| 92 | + while (parser.nextToken() != JsonToken.END_OBJECT) { |
| 93 | + String value = parser.nextTextValue(); |
| 94 | + switch (parser.getCurrentName()) { |
| 95 | + case "instanceId": |
| 96 | + attrBuilders.put(ResourceAttributes.HOST_ID, value); |
| 97 | + break; |
| 98 | + case "availabilityZone": |
| 99 | + attrBuilders.put(ResourceAttributes.CLOUD_AVAILABILITY_ZONE, value); |
| 100 | + break; |
| 101 | + case "instanceType": |
| 102 | + attrBuilders.put(ResourceAttributes.HOST_TYPE, value); |
| 103 | + break; |
| 104 | + case "imageId": |
| 105 | + attrBuilders.put(ResourceAttributes.HOST_IMAGE_ID, value); |
| 106 | + break; |
| 107 | + case "accountId": |
| 108 | + attrBuilders.put(ResourceAttributes.CLOUD_ACCOUNT_ID, value); |
| 109 | + break; |
| 110 | + case "region": |
| 111 | + attrBuilders.put(ResourceAttributes.CLOUD_REGION, value); |
| 112 | + break; |
| 113 | + default: |
| 114 | + parser.skipChildren(); |
| 115 | + } |
| 116 | + } |
| 117 | + } catch (IOException e) { |
| 118 | + logger.log(Level.WARNING, "Could not parse identity document, resource not filled.", e); |
| 119 | + return Resource.empty(); |
| 120 | + } |
| 121 | + |
| 122 | + attrBuilders.put(ResourceAttributes.HOST_NAME, hostname); |
| 123 | + |
| 124 | + return Resource.create(attrBuilders.build(), ResourceAttributes.SCHEMA_URL); |
| 125 | + } |
| 126 | + |
| 127 | + private static String fetchToken(URL tokenUrl) { |
| 128 | + return fetchString("PUT", tokenUrl, "", /* includeTtl= */ true); |
| 129 | + } |
| 130 | + |
| 131 | + private static String fetchIdentity(URL identityDocumentUrl, String token) { |
| 132 | + return fetchString("GET", identityDocumentUrl, token, /* includeTtl= */ false); |
| 133 | + } |
| 134 | + |
| 135 | + private static String fetchHostname(URL hostnameUrl, String token) { |
| 136 | + return fetchString("GET", hostnameUrl, token, /* includeTtl= */ false); |
| 137 | + } |
| 138 | + |
| 139 | + // Generic HTTP fetch function for IMDS. |
| 140 | + private static String fetchString(String httpMethod, URL url, String token, boolean includeTtl) { |
| 141 | + SimpleHttpClient client = new SimpleHttpClient(); |
| 142 | + Map<String, String> headers = new HashMap<>(); |
| 143 | + |
| 144 | + if (includeTtl) { |
| 145 | + headers.put("X-aws-ec2-metadata-token-ttl-seconds", "60"); |
| 146 | + } |
| 147 | + if (!token.isEmpty()) { |
| 148 | + headers.put("X-aws-ec2-metadata-token", token); |
| 149 | + } |
| 150 | + |
| 151 | + return client.fetchString(httpMethod, url.toString(), headers, null); |
| 152 | + } |
| 153 | + |
| 154 | + private Ec2Resource() {} |
| 155 | +} |
0 commit comments