-
Notifications
You must be signed in to change notification settings - Fork 381
Expand file tree
/
Copy pathAWSECSDetector.cs
More file actions
223 lines (189 loc) · 9.39 KB
/
AWSECSDetector.cs
File metadata and controls
223 lines (189 loc) · 9.39 KB
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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#if NET
using System.Text.Json;
using System.Text.RegularExpressions;
using OpenTelemetry.AWS;
namespace OpenTelemetry.Resources.AWS;
/// <summary>
/// Resource detector for application running in AWS ECS.
/// </summary>
internal sealed partial class AWSECSDetector : IResourceDetector
{
private const string AWSECSMetadataPath = "/proc/self/cgroup";
private const string AWSECSMetadataURLKey = "ECS_CONTAINER_METADATA_URI";
private const string AWSECSMetadataURLV4Key = "ECS_CONTAINER_METADATA_URI_V4";
private readonly AWSSemanticConventions semanticConventionBuilder;
public AWSECSDetector(AWSSemanticConventions semanticConventionBuilder)
{
this.semanticConventionBuilder = semanticConventionBuilder;
}
/// <summary>
/// Detector the required and optional resource attributes from AWS ECS.
/// </summary>
/// <returns>Resource with key-value pairs of resource attributes.</returns>
public Resource Detect()
{
if (!IsECSProcess())
{
return Resource.Empty;
}
var resourceAttributes =
this.semanticConventionBuilder
.AttributeBuilder
.AddAttributeCloudProviderIsAWS()
.AddAttributeCloudPlatformIsAwsEcs();
try
{
var containerId = GetECSContainerId(AWSECSMetadataPath);
if (containerId != null)
{
resourceAttributes.AddAttributeContainerId(containerId);
}
}
catch (Exception ex)
{
AWSResourcesEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSDetector), ex);
}
try
{
this.ExtractMetadataV4ResourceAttributes(resourceAttributes);
}
catch (Exception ex)
{
AWSResourcesEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSDetector), ex);
}
return new Resource(resourceAttributes.Build());
}
internal static string? GetECSContainerId(string path)
{
string? containerId = null;
using (var streamReader = ResourceDetectorUtils.GetStreamReader(path))
{
while (!streamReader.EndOfStream)
{
var trimmedLine = streamReader.ReadLine()?.Trim();
if (trimmedLine?.Length > 64)
{
containerId = trimmedLine.Substring(trimmedLine.Length - 64);
return containerId;
}
}
}
return containerId;
}
internal static bool IsECSProcess() =>
Environment.GetEnvironmentVariable(AWSECSMetadataURLKey) != null ||
Environment.GetEnvironmentVariable(AWSECSMetadataURLV4Key) != null;
internal void ExtractMetadataV4ResourceAttributes(AWSSemanticConventions.AttributeBuilderImpl resourceAttributes)
{
var metadataV4Url = Environment.GetEnvironmentVariable(AWSECSMetadataURLV4Key);
if (metadataV4Url == null)
{
return;
}
using var scope = SuppressInstrumentationScope.Begin();
using var httpClientHandler = new HttpClientHandler();
#pragma warning disable CA2025 // Do not pass 'IDisposable' instances into unawaited tasks
var metadataV4ContainerResponse = AsyncHelper.RunSync(() => ResourceDetectorUtils.SendOutRequestAsync(metadataV4Url, HttpMethod.Get, null, httpClientHandler));
var metadataV4TaskResponse = AsyncHelper.RunSync(() => ResourceDetectorUtils.SendOutRequestAsync($"{metadataV4Url.TrimEnd('/')}/task", HttpMethod.Get, null, httpClientHandler));
#pragma warning restore CA2025 // Do not pass 'IDisposable' instances into unawaited tasks
using var containerResponse = JsonDocument.Parse(metadataV4ContainerResponse);
using var taskResponse = JsonDocument.Parse(metadataV4TaskResponse);
// On Linux the container ID is obtained from a file which does not exist on Windows.
// The ECS Metadata V4 container endpoint always carries the same ID in the "DockerId" field.
// See https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-metadata-endpoint-v4-response.html.
if (OperatingSystem.IsWindows() &&
containerResponse.RootElement.TryGetProperty("DockerId", out var dockerIdElement) &&
dockerIdElement.GetString() is string { Length: > 0 } dockerId)
{
resourceAttributes.AddAttributeContainerId(dockerId);
}
if (!containerResponse.RootElement.TryGetProperty("ContainerARN", out var containerArnElement)
|| containerArnElement.GetString() is not string containerArn)
{
AWSResourcesEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSDetector), new ArgumentException("The ECS Metadata V4 response did not contain the 'ContainerARN' field"));
return;
}
if (!taskResponse.RootElement.TryGetProperty("Cluster", out var clusterArnElement)
|| clusterArnElement.GetString() is not string clusterArn)
{
AWSResourcesEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSDetector), new ArgumentException("The ECS Metadata V4 response did not contain the 'Cluster' field"));
return;
}
resourceAttributes
.AddAttributeCloudResourceId(containerArn)
.AddAttributeEcsContainerArn(containerArn)
.AddAttributeEcsClusterArn(clusterArn);
if (taskResponse.RootElement.TryGetProperty("AvailabilityZone", out var availabilityZoneElement) && availabilityZoneElement.ValueKind == JsonValueKind.String)
{
resourceAttributes.AddAttributeCloudAvailabilityZone(availabilityZoneElement.GetString()!);
}
if (!taskResponse.RootElement.TryGetProperty("LaunchType", out var launchTypeElement))
{
launchTypeElement = default;
}
if (string.Equals("ec2", launchTypeElement.GetString(), StringComparison.OrdinalIgnoreCase))
{
resourceAttributes.AddAttributeEcsLaunchtypeIsEc2();
}
else if (string.Equals("fargate", launchTypeElement.GetString(), StringComparison.OrdinalIgnoreCase))
{
resourceAttributes.AddAttributeEcsLaunchtypeIsFargate();
}
else
{
AWSResourcesEventSource.Log.ResourceAttributesExtractException(nameof(AWSECSDetector), new ArgumentException($"The ECS Metadata V4 response contained the unrecognized launch type '{launchTypeElement}'"));
}
if (taskResponse.RootElement.TryGetProperty("TaskARN", out var taskArnElement) && taskArnElement.ValueKind == JsonValueKind.String)
{
var taskArn = taskArnElement.GetString()!;
resourceAttributes
.AddAttributeEcsTaskArn(taskArn);
var arnParts = taskArn.Split(':');
if (arnParts.Length > 5)
{
resourceAttributes.AddAttributeCloudAccountID(arnParts[4]);
resourceAttributes.AddAttributeCloudRegion(arnParts[3]);
}
}
if (taskResponse.RootElement.TryGetProperty("Family", out var familyElement) && familyElement.ValueKind == JsonValueKind.String)
{
resourceAttributes.AddAttributeEcsTaskFamily(familyElement.GetString()!);
}
if (taskResponse.RootElement.TryGetProperty("Revision", out var revisionElement) && revisionElement.ValueKind == JsonValueKind.String)
{
resourceAttributes.AddAttributeEcsTaskRevision(revisionElement.GetString()!);
}
if (containerResponse.RootElement.TryGetProperty("LogDriver", out var logDriverElement)
&& logDriverElement.ValueKind == JsonValueKind.String
&& logDriverElement.ValueEquals("awslogs"))
{
if (containerResponse.RootElement.TryGetProperty("LogOptions", out var logOptionsElement))
{
var match = ArnRegex().Match(containerArn);
if (!match.Success)
{
throw new ArgumentOutOfRangeException($"Cannot parse region and account from the container ARN '{containerArn}'");
}
var logsRegion = match.Groups[1];
var logsAccount = match.Groups[2];
if (logOptionsElement.TryGetProperty("awslogs-group", out var logGroupElement) && logGroupElement.ValueKind == JsonValueKind.String)
{
var logGroupName = logGroupElement.GetString()!;
resourceAttributes.AddAttributeLogGroupNames(new[] { logGroupName });
resourceAttributes.AddAttributeLogGroupArns(new[] { $"arn:aws:logs:{logsRegion}:{logsAccount}:log-group:{logGroupName}:*" });
if (logOptionsElement.TryGetProperty("awslogs-stream", out var logStreamElement) && logStreamElement.ValueKind == JsonValueKind.String)
{
var logStreamName = logStreamElement.GetString()!;
resourceAttributes.AddAttributeLogStreamNames(new[] { logStreamName });
resourceAttributes.AddAttributeLogStreamArns(new[] { $"arn:aws:logs:{logsRegion}:{logsAccount}:log-group:{logGroupName}:log-stream:{logStreamName}" });
}
}
}
}
}
[GeneratedRegex(@"arn:aws:ecs:([^:]+):([^:]+):.*")]
private static partial Regex ArnRegex();
}
#endif