-
Notifications
You must be signed in to change notification settings - Fork 531
/
AwsEksDetectorSync.ts
244 lines (229 loc) · 7.81 KB
/
AwsEksDetectorSync.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
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
/*
* 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 { context } from '@opentelemetry/api';
import { suppressTracing } from '@opentelemetry/core';
import {
DetectorSync,
IResource,
Resource,
ResourceAttributes,
ResourceDetectionConfig,
} from '@opentelemetry/resources';
import {
SEMRESATTRS_CLOUD_PROVIDER,
SEMRESATTRS_CLOUD_PLATFORM,
SEMRESATTRS_K8S_CLUSTER_NAME,
SEMRESATTRS_CONTAINER_ID,
CLOUDPROVIDERVALUES_AWS,
CLOUDPLATFORMVALUES_AWS_EKS,
} from '@opentelemetry/semantic-conventions';
import * as https from 'https';
import * as fs from 'fs';
import * as util from 'util';
import { diag } from '@opentelemetry/api';
/**
* The AwsEksDetectorSync can be used to detect if a process is running in AWS Elastic
* Kubernetes and return a {@link Resource} populated with data about the Kubernetes
* plugins of AWS X-Ray. Returns an empty Resource if detection fails.
*
* See https://docs.amazonaws.cn/en_us/xray/latest/devguide/xray-guide.pdf
* for more details about detecting information for Elastic Kubernetes plugins
*/
export class AwsEksDetectorSync implements DetectorSync {
readonly K8S_SVC_URL = 'kubernetes.default.svc';
readonly K8S_TOKEN_PATH =
'/var/run/secrets/kubernetes.io/serviceaccount/token';
readonly K8S_CERT_PATH =
'/var/run/secrets/kubernetes.io/serviceaccount/ca.crt';
readonly AUTH_CONFIGMAP_PATH =
'/api/v1/namespaces/kube-system/configmaps/aws-auth';
readonly CW_CONFIGMAP_PATH =
'/api/v1/namespaces/amazon-cloudwatch/configmaps/cluster-info';
readonly CONTAINER_ID_LENGTH = 64;
readonly DEFAULT_CGROUP_PATH = '/proc/self/cgroup';
readonly TIMEOUT_MS = 2000;
readonly UTF8_UNICODE = 'utf8';
private static readFileAsync = util.promisify(fs.readFile);
private static fileAccessAsync = util.promisify(fs.access);
detect(_config?: ResourceDetectionConfig): IResource {
const attributes = context.with(suppressTracing(context.active()), () =>
this._getAttributes()
);
return new Resource({}, attributes);
}
/**
* The AwsEksDetector can be used to detect if a process is running on Amazon
* Elastic Kubernetes and returns a promise containing a {@link ResourceAttributes}
* object with instance metadata. Returns a promise containing an
* empty {@link ResourceAttributes} if the connection to kubernetes process
* or aws config maps fails
*/
private async _getAttributes(): Promise<ResourceAttributes> {
try {
await AwsEksDetectorSync.fileAccessAsync(this.K8S_TOKEN_PATH);
const k8scert = await AwsEksDetectorSync.readFileAsync(
this.K8S_CERT_PATH
);
if (!(await this._isEks(k8scert))) {
return {};
}
const containerId = await this._getContainerId();
const clusterName = await this._getClusterName(k8scert);
return !containerId && !clusterName
? {}
: {
[SEMRESATTRS_CLOUD_PROVIDER]: CLOUDPROVIDERVALUES_AWS,
[SEMRESATTRS_CLOUD_PLATFORM]: CLOUDPLATFORMVALUES_AWS_EKS,
[SEMRESATTRS_K8S_CLUSTER_NAME]: clusterName || '',
[SEMRESATTRS_CONTAINER_ID]: containerId || '',
};
} catch (e) {
diag.debug('Process is not running on K8S', e);
return {};
}
}
/**
* Attempts to make a connection to AWS Config map which will
* determine whether the process is running on an EKS
* process if the config map is empty or not
*/
private async _isEks(cert: Buffer): Promise<boolean> {
const options = {
ca: cert,
headers: {
Authorization: await this._getK8sCredHeader(),
},
hostname: this.K8S_SVC_URL,
method: 'GET',
path: this.AUTH_CONFIGMAP_PATH,
timeout: this.TIMEOUT_MS,
};
return !!(await this._fetchString(options));
}
/**
* Attempts to make a connection to Amazon Cloudwatch
* Config Maps to grab cluster name
*/
private async _getClusterName(cert: Buffer): Promise<string | undefined> {
const options = {
ca: cert,
headers: {
Authorization: await this._getK8sCredHeader(),
},
host: this.K8S_SVC_URL,
method: 'GET',
path: this.CW_CONFIGMAP_PATH,
timeout: this.TIMEOUT_MS,
};
const response = await this._fetchString(options);
try {
return JSON.parse(response).data['cluster.name'];
} catch (e) {
diag.debug('Cannot get cluster name on EKS', e);
}
return '';
}
/**
* Reads the Kubernetes token path and returns kubernetes
* credential header
*/
private async _getK8sCredHeader(): Promise<string> {
try {
const content = await AwsEksDetectorSync.readFileAsync(
this.K8S_TOKEN_PATH,
this.UTF8_UNICODE
);
return 'Bearer ' + content;
} catch (e) {
diag.debug('Unable to read Kubernetes client token.', e);
}
return '';
}
/**
* Read container ID from cgroup file generated from docker which lists the full
* untruncated docker container ID at the end of each line.
*
* The predefined structure of calling /proc/self/cgroup when in a docker container has the structure:
*
* #:xxxxxx:/
*
* or
*
* #:xxxxxx:/docker/64characterID
*
* This function takes advantage of that fact by just reading the 64-character ID from the end of the
* first line. In EKS, even if we fail to find target file or target file does
* not contain container ID we do not throw an error but throw warning message
* and then return null string
*/
private async _getContainerId(): Promise<string | undefined> {
try {
const rawData = await AwsEksDetectorSync.readFileAsync(
this.DEFAULT_CGROUP_PATH,
this.UTF8_UNICODE
);
const splitData = rawData.trim().split('\n');
for (const str of splitData) {
if (str.length > this.CONTAINER_ID_LENGTH) {
return str.substring(str.length - this.CONTAINER_ID_LENGTH);
}
}
} catch (e: any) {
diag.debug(`AwsEksDetector failed to read container ID: ${e.message}`);
}
return undefined;
}
/**
* Establishes an HTTP connection to AWS instance document url.
* If the application is running on an EKS 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: https.RequestOptions): Promise<string> {
return await new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
req.abort();
reject(new Error('EKS metadata api request timed out.'));
}, 2000);
const req = https.request(options, res => {
clearTimeout(timeoutId);
const { statusCode } = res;
res.setEncoding(this.UTF8_UNICODE);
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 awsEksDetectorSync = new AwsEksDetectorSync();