/
AwsEc2Detector.ts
163 lines (153 loc) · 5.4 KB
/
AwsEc2Detector.ts
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
/*
* Copyright The OpenTelemetry Authors
*
* 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
*
* https://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.
*/
import {
Detector,
Resource,
ResourceDetectionConfig,
} from '@opentelemetry/resources';
import {
CloudProviderValues,
CloudPlatformValues,
SemanticResourceAttributes,
} from '@opentelemetry/semantic-conventions';
import * as http from 'http';
/**
* The AwsEc2Detector can be used to detect if a process is running in AWS EC2
* and return a {@link Resource} populated with metadata about the EC2
* instance. Returns an empty Resource if detection fails.
*/
class AwsEc2Detector implements Detector {
/**
* See https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-identity-documents.html
* for documentation about the AWS instance identity document
* and standard of IMDSv2.
*/
readonly AWS_IDMS_ENDPOINT = '169.254.169.254';
readonly AWS_INSTANCE_TOKEN_DOCUMENT_PATH = '/latest/api/token';
readonly AWS_INSTANCE_IDENTITY_DOCUMENT_PATH =
'/latest/dynamic/instance-identity/document';
readonly AWS_INSTANCE_HOST_DOCUMENT_PATH = '/latest/meta-data/hostname';
readonly AWS_METADATA_TTL_HEADER = 'X-aws-ec2-metadata-token-ttl-seconds';
readonly AWS_METADATA_TOKEN_HEADER = 'X-aws-ec2-metadata-token';
readonly MILLISECOND_TIME_OUT = 1000;
/**
* Attempts to connect and obtain an AWS instance Identity document. If the
* connection is successful it returns a promise containing a {@link Resource}
* populated with instance metadata. Returns a promise containing an
* empty {@link Resource} if the connection or parsing of the identity
* document fails.
*
* @param config (unused) The resource detection config
*/
async detect(_config?: ResourceDetectionConfig): Promise<Resource> {
const token = await this._fetchToken();
const {
accountId,
instanceId,
instanceType,
region,
availabilityZone,
} = await this._fetchIdentity(token);
const hostname = await this._fetchHost(token);
return new Resource({
[SemanticResourceAttributes.CLOUD_PROVIDER]: CloudProviderValues.AWS,
[SemanticResourceAttributes.CLOUD_PLATFORM]: CloudPlatformValues.AWS_EC2,
[SemanticResourceAttributes.CLOUD_ACCOUNT_ID]: accountId,
[SemanticResourceAttributes.CLOUD_REGION]: region,
[SemanticResourceAttributes.CLOUD_AVAILABILITY_ZONE]: availabilityZone,
[SemanticResourceAttributes.HOST_ID]: instanceId,
[SemanticResourceAttributes.HOST_TYPE]: instanceType,
[SemanticResourceAttributes.HOST_NAME]: hostname,
});
}
private async _fetchToken(): Promise<string> {
const options = {
host: this.AWS_IDMS_ENDPOINT,
path: this.AWS_INSTANCE_TOKEN_DOCUMENT_PATH,
method: 'PUT',
timeout: this.MILLISECOND_TIME_OUT,
headers: {
[this.AWS_METADATA_TTL_HEADER]: '60',
},
};
return await this._fetchString(options);
}
private async _fetchIdentity(token: string): Promise<any> {
const options = {
host: this.AWS_IDMS_ENDPOINT,
path: this.AWS_INSTANCE_IDENTITY_DOCUMENT_PATH,
method: 'GET',
timeout: this.MILLISECOND_TIME_OUT,
headers: {
[this.AWS_METADATA_TOKEN_HEADER]: token,
},
};
const identity = await this._fetchString(options);
return JSON.parse(identity);
}
private async _fetchHost(token: string): Promise<string> {
const options = {
host: this.AWS_IDMS_ENDPOINT,
path: this.AWS_INSTANCE_HOST_DOCUMENT_PATH,
method: 'GET',
timeout: this.MILLISECOND_TIME_OUT,
headers: {
[this.AWS_METADATA_TOKEN_HEADER]: token,
},
};
return await this._fetchString(options);
}
/**
* Establishes an HTTP connection to AWS instance document url.
* If the application is running on an EC2 instance, we should be able
* to get back a valid JSON document. Parses that document and stores
* the identity properties in a local map.
*/
private async _fetchString(options: http.RequestOptions): Promise<string> {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
req.abort();
reject(new Error('EC2 metadata api request timed out.'));
}, 1000);
const req = http.request(options, res => {
clearTimeout(timeoutId);
const { statusCode } = res;
res.setEncoding('utf8');
let rawData = '';
res.on('data', chunk => (rawData += chunk));
res.on('end', () => {
if (statusCode && statusCode >= 200 && statusCode < 300) {
try {
resolve(rawData);
} catch (e) {
reject(e);
}
} else {
reject(
new Error('Failed to load page, status code: ' + statusCode)
);
}
});
});
req.on('error', err => {
clearTimeout(timeoutId);
reject(err);
});
req.end();
});
}
}
export const awsEc2Detector = new AwsEc2Detector();