Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 6 additions & 14 deletions src/OpenTelemetry.Resources.AWS/AWSEC2Detector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,12 @@ public Resource Detect()
return Resource.Empty;
}

internal static AWSEC2IdentityDocumentModel? DeserializeResponse(string response)
{
internal static AWSEC2IdentityDocumentModel? DeserializeResponse(string response) =>
#if NETFRAMEWORK
return ResourceDetectorUtils.DeserializeFromString<AWSEC2IdentityDocumentModel>(response);
ResourceDetectorUtils.DeserializeFromString<AWSEC2IdentityDocumentModel>(response);
#else
return ResourceDetectorUtils.DeserializeFromString(response, SourceGenerationContext.Default.AWSEC2IdentityDocumentModel);
ResourceDetectorUtils.DeserializeFromString(response, SourceGenerationContext.Default.AWSEC2IdentityDocumentModel);
#endif
}

internal List<KeyValuePair<string, object>> ExtractResourceAttributes(AWSEC2IdentityDocumentModel? identity, string hostName)
{
Expand All @@ -79,9 +77,7 @@ internal List<KeyValuePair<string, object>> ExtractResourceAttributes(AWSEC2Iden
}

private static string GetAWSEC2Token()
{
return AsyncHelper.RunSync(() => ResourceDetectorUtils.SendOutRequestAsync(AWSEC2MetadataTokenUrl, HttpMethod.Put, new KeyValuePair<string, string>(AWSEC2MetadataTokenTTLHeader, "60")));
}
=> ResourceDetectorUtils.SendOutRequest(AWSEC2MetadataTokenUrl, HttpMethod.Put, new KeyValuePair<string, string>(AWSEC2MetadataTokenTTLHeader, "60"));

private static AWSEC2IdentityDocumentModel? GetAWSEC2Identity(string token)
{
Expand All @@ -92,12 +88,8 @@ private static string GetAWSEC2Token()
}

private static string GetIdentityResponse(string token)
{
return AsyncHelper.RunSync(() => ResourceDetectorUtils.SendOutRequestAsync(AWSEC2IdentityDocumentUrl, HttpMethod.Get, new KeyValuePair<string, string>(AWSEC2MetadataTokenHeader, token)));
}
=> ResourceDetectorUtils.SendOutRequest(AWSEC2IdentityDocumentUrl, HttpMethod.Get, new KeyValuePair<string, string>(AWSEC2MetadataTokenHeader, token));

private static string GetAWSEC2HostName(string token)
{
return AsyncHelper.RunSync(() => ResourceDetectorUtils.SendOutRequestAsync(AWSEC2HostNameUrl, HttpMethod.Get, new KeyValuePair<string, string>(AWSEC2MetadataTokenHeader, token)));
}
=> ResourceDetectorUtils.SendOutRequest(AWSEC2HostNameUrl, HttpMethod.Get, new KeyValuePair<string, string>(AWSEC2MetadataTokenHeader, token));
}
17 changes: 8 additions & 9 deletions src/OpenTelemetry.Resources.AWS/AWSECSDetector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,14 @@ public Resource Detect()

using (var streamReader = ResourceDetectorUtils.GetStreamReader(path))
Comment thread
martincostello marked this conversation as resolved.
Outdated
{
while (!streamReader.EndOfStream)
string? line = null;

while ((line = streamReader.ReadLine()) is not null)
{
var trimmedLine = streamReader.ReadLine()?.Trim();
if (trimmedLine?.Length > 64)
var trimmedLine = line.Trim();
if (trimmedLine.Length > 64)
{
containerId = trimmedLine.Substring(trimmedLine.Length - 64);
return containerId;
return trimmedLine.Substring(trimmedLine.Length - 64);
}
}
}
Expand All @@ -100,10 +101,8 @@ internal void ExtractMetadataV4ResourceAttributes(AWSSemanticConventions.Attribu
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
var metadataV4ContainerResponse = ResourceDetectorUtils.SendOutRequest(metadataV4Url, HttpMethod.Get, null, httpClientHandler);
var metadataV4TaskResponse = ResourceDetectorUtils.SendOutRequest($"{metadataV4Url.TrimEnd('/')}/task", HttpMethod.Get, null, httpClientHandler);
Comment thread
martincostello marked this conversation as resolved.

using var containerResponse = JsonDocument.Parse(metadataV4ContainerResponse);
using var taskResponse = JsonDocument.Parse(metadataV4TaskResponse);
Expand Down
26 changes: 12 additions & 14 deletions src/OpenTelemetry.Resources.AWS/AWSEKSDetector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,7 @@ public Resource Detect()

using (var streamReader = ResourceDetectorUtils.GetStreamReader(path))
{
while (!streamReader.EndOfStream)
{
stringBuilder.Append(streamReader.ReadLine()?.Trim());
}
stringBuilder.Append(streamReader.ReadToEnd().Trim());
}

return stringBuilder.ToString();
Expand All @@ -71,10 +68,13 @@ public Resource Detect()
try
{
using var streamReader = ResourceDetectorUtils.GetStreamReader(path);
while (!streamReader.EndOfStream)

string? line = null;

while ((line = streamReader.ReadLine()) is not null)
{
var trimmedLine = streamReader.ReadLine()?.Trim();
if (trimmedLine?.Length > 64)
var trimmedLine = line.Trim();
if (trimmedLine.Length > 64)
{
return trimmedLine.Substring(trimmedLine.Length - 64);
}
Expand All @@ -88,14 +88,12 @@ public Resource Detect()
return null;
}

internal static AWSEKSClusterInformationModel? DeserializeResponse(string response)
{
internal static AWSEKSClusterInformationModel? DeserializeResponse(string response) =>
#if NET
return ResourceDetectorUtils.DeserializeFromString(response, SourceGenerationContext.Default.AWSEKSClusterInformationModel);
ResourceDetectorUtils.DeserializeFromString(response, SourceGenerationContext.Default.AWSEKSClusterInformationModel);
#else
return ResourceDetectorUtils.DeserializeFromString<AWSEKSClusterInformationModel>(response);
ResourceDetectorUtils.DeserializeFromString<AWSEKSClusterInformationModel>(response);
#endif
}

internal List<KeyValuePair<string, object>> ExtractResourceAttributes(string? clusterName, string? containerId)
{
Expand Down Expand Up @@ -132,7 +130,7 @@ private static bool IsEKSProcess(string credentials, HttpClientHandler? httpClie
try
{
using var scope = SuppressInstrumentationScope.Begin();
awsAuth = AsyncHelper.RunSync(() => ResourceDetectorUtils.SendOutRequestAsync(AWSAuthUrl, HttpMethod.Get, new KeyValuePair<string, string>("Authorization", credentials), httpClientHandler));
awsAuth = ResourceDetectorUtils.SendOutRequest(AWSAuthUrl, HttpMethod.Get, new KeyValuePair<string, string>("Authorization", credentials), httpClientHandler);
}
catch (Exception ex)
{
Expand All @@ -145,7 +143,7 @@ private static bool IsEKSProcess(string credentials, HttpClientHandler? httpClie
private static string GetEKSClusterInfo(string credentials, HttpClientHandler? httpClientHandler)
{
using var scope = SuppressInstrumentationScope.Begin();
return AsyncHelper.RunSync(() => ResourceDetectorUtils.SendOutRequestAsync(AWSClusterInfoUrl, HttpMethod.Get, new KeyValuePair<string, string>("Authorization", credentials), httpClientHandler));
return ResourceDetectorUtils.SendOutRequest(AWSClusterInfoUrl, HttpMethod.Get, new KeyValuePair<string, string>("Authorization", credentials), httpClientHandler);
}
}
#endif
44 changes: 0 additions & 44 deletions src/OpenTelemetry.Resources.AWS/AsyncHelper.cs

This file was deleted.

3 changes: 3 additions & 0 deletions src/OpenTelemetry.Resources.AWS/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
Windows containers running on AWS ECS.
([#4028](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/4028))

* Limit how much of the response body is consumed from metadata service HTTP responses.
([#4122](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/4122))

## 1.15.0

Released 2026-Jan-21
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
<Compile Include="$(RepoRoot)\src\Shared\AWS\*.cs" Link="Includes\AWS\%(Filename).cs" />
<Compile Include="$(RepoRoot)\src\Shared\ExceptionExtensions.cs" Link="Includes\ExceptionExtensions.cs" />
<Compile Include="$(RepoRoot)\src\Shared\Guard.cs" Link="Includes\Guard.cs" />
<Compile Include="$(RepoRoot)\src\Shared\HttpClientHelpers.cs" Link="Includes\HttpClientHelpers.cs" />
<Compile Include="$(RepoRoot)\src\Shared\IServerCertificateValidationEventSource.cs" Link="Includes\IServerCertificateValidationEventSource.cs" />
<Compile Include="$(RepoRoot)\src\Shared\ServerCertificateValidationHandler.cs" Link="Includes\ServerCertificateValidationHandler.cs" />
<Compile Include="$(RepoRoot)\src\Shared\ServerCertificateValidationProvider.cs" Link="Includes\ServerCertificateValidationProvider.cs" />
Expand Down
77 changes: 39 additions & 38 deletions src/OpenTelemetry.Resources.AWS/ResourceDetectorUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,69 +21,70 @@ internal static class ResourceDetectorUtils
private static readonly JsonSerializerOptions JsonSerializerOptions = new(JsonSerializerDefaults.Web);
#endif

internal static async Task<string> SendOutRequestAsync(
internal static string SendOutRequest(
string url,
HttpMethod method,
KeyValuePair<string, string>? header,
HttpClientHandler? handler = null)
HttpClientHandler? handler = null,
CancellationToken cancellationToken = default)
{
using (var httpRequestMessage = new HttpRequestMessage())
using var httpRequestMessage = new HttpRequestMessage();

httpRequestMessage.RequestUri = new Uri(url);
httpRequestMessage.Method = method;

if (header is { } headerValue)
{
httpRequestMessage.RequestUri = new Uri(url);
httpRequestMessage.Method = method;
if (header.HasValue)
{
httpRequestMessage.Headers.Add(header.Value.Key, header.Value.Value);
}
httpRequestMessage.Headers.Add(headerValue.Key, headerValue.Value);
}

#pragma warning disable CA2000 // Dispose objects before losing scope
var httpClient = handler == null ? new HttpClient() : new HttpClient(handler);
var httpClient = handler == null ? new HttpClient() : new HttpClient(handler);
#pragma warning restore CA2000 // Dispose objects before losing scope
Comment thread
martincostello marked this conversation as resolved.
using (var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}

#if NET
using var response = httpClient.Send(httpRequestMessage, cancellationToken);
#else
#pragma warning disable CA2025 // Do not pass 'IDisposable' instances into unawaited tasks
using var response = httpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
Comment thread
martincostello marked this conversation as resolved.
Outdated
#pragma warning restore CA2025 // Do not pass 'IDisposable' instances into unawaited tasks
#endif

response.EnsureSuccessStatusCode();

return HttpClientHelpers.GetResponseBodyAsString(response, cancellationToken) ?? string.Empty;
}

#if NETFRAMEWORK
internal static T? DeserializeFromFile<T>(string filePath)
{
using (var stream = GetStream(filePath))
{
return JsonSerializer.Deserialize<T>(stream, JsonSerializerOptions);
}
using var stream = GetStream(filePath);
return JsonSerializer.Deserialize<T>(stream, JsonSerializerOptions);
}

internal static T? DeserializeFromString<T>(string json)
{
return JsonSerializer.Deserialize<T>(json, JsonSerializerOptions);
}
internal static T? DeserializeFromString<T>(string json) =>
JsonSerializer.Deserialize<T>(json, JsonSerializerOptions);
#else
internal static T? DeserializeFromFile<T>(string filePath, JsonTypeInfo<T> jsonTypeInfo)
{
using (var stream = GetStream(filePath))
{
return JsonSerializer.Deserialize(stream, jsonTypeInfo);
}
using var stream = GetStream(filePath);
return JsonSerializer.Deserialize(stream, jsonTypeInfo);
}

internal static T? DeserializeFromString<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
return JsonSerializer.Deserialize(json, jsonTypeInfo);
}
internal static T? DeserializeFromString<T>(string json, JsonTypeInfo<T> jsonTypeInfo) =>
JsonSerializer.Deserialize(json, jsonTypeInfo);
#endif

internal static Stream GetStream(string filePath)
{
return new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
internal static Stream GetStream(string filePath) =>
new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

internal static StreamReader GetStreamReader(string filePath)
{
var fileStream = GetStream(filePath);
var streamReader = new StreamReader(fileStream, Encoding.UTF8);
return streamReader;
#if NET
return new StreamReader(fileStream, Encoding.UTF8, leaveOpen: false);
Comment thread
martincostello marked this conversation as resolved.
#else
return new StreamReader(fileStream, Encoding.UTF8);
#endif
}
}
Loading
Loading