Skip to content

Commit

Permalink
Merge branch 'main' into wcf-net-target
Browse files Browse the repository at this point in the history
  • Loading branch information
Kielek authored Oct 28, 2024
2 parents 927b36c + 3f5d91c commit 3643194
Show file tree
Hide file tree
Showing 30 changed files with 267 additions and 308 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ internal sealed class OtlpProtobufMetricExporter : IDisposable

public OtlpProtobufMetricExporter(
Func<Resource> getResource,
ConnectionStringBuilder connectionStringBuilder,
ConnectionStringBuilder? connectionStringBuilder,
IReadOnlyDictionary<string, object>? prepopulatedMetricDimensions)
{
Debug.Assert(getResource != null, "getResource was null");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ internal static class RedisProfilerEntryToActivityConverter
{
private static readonly Lazy<Func<object, (string?, string?)>> MessageDataGetter = new(() =>
{
Type profiledCommandType = Type.GetType("StackExchange.Redis.Profiling.ProfiledCommand, StackExchange.Redis", throwOnError: true)!;
Type scriptMessageType = Type.GetType("StackExchange.Redis.RedisDatabase+ScriptEvalMessage, StackExchange.Redis", throwOnError: true)!;
var profiledCommandType = Type.GetType("StackExchange.Redis.Profiling.ProfiledCommand, StackExchange.Redis", throwOnError: true)!;
var scriptMessageType = Type.GetType("StackExchange.Redis.RedisDatabase+ScriptEvalMessage, StackExchange.Redis", throwOnError: true)!;

var messageDelegate = CreateFieldGetter<object>(profiledCommandType, "Message", BindingFlags.NonPublic | BindingFlags.Instance);
var scriptDelegate = CreateFieldGetter<string>(scriptMessageType, "script", BindingFlags.NonPublic | BindingFlags.Instance);
Expand Down Expand Up @@ -49,12 +49,7 @@ internal static class RedisProfilerEntryToActivityConverter
script = scriptDelegate?.Invoke(message);
}

if (GetCommandAndKey(commandAndKeyFetcher, message, out var value))
{
return (value, script);
}

return (null, script);
return GetCommandAndKey(commandAndKeyFetcher, message, out var value) ? (value, script) : (null, script);

#if NET
[DynamicDependency("CommandAndKey", "StackExchange.Redis.Message", "StackExchange.Redis")]
Expand Down Expand Up @@ -199,19 +194,19 @@ public static void DrainSession(Activity? parentActivity, IEnumerable<IProfiledC
string fieldName,
BindingFlags flags)
{
FieldInfo? field = classType.GetField(fieldName, flags);
var field = classType.GetField(fieldName, flags);
if (field != null)
{
#if NET
if (RuntimeFeature.IsDynamicCodeSupported)
#endif
{
string methodName = classType.FullName + ".get_" + field.Name;
var methodName = classType.FullName + ".get_" + field.Name;
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
// TODO: Remove the above disable when the AOT analyzer being used has the fix for https://github.com/dotnet/linker/issues/2715.
DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new[] { typeof(object) }, true);
var getterMethod = new DynamicMethod(methodName, typeof(TField), [typeof(object)], true);
#pragma warning restore IL3050
ILGenerator generator = getterMethod.GetILGenerator();
var generator = getterMethod.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Castclass, classType);
generator.Emit(OpCodes.Ldfld, field);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ internal sealed class StackExchangeRedisConnectionInstrumentation : IDisposable
internal static readonly string ActivitySourceName = Assembly.GetName().Name!;
internal static readonly string ActivityName = ActivitySourceName + ".Execute";
internal static readonly ActivitySource ActivitySource = new(ActivitySourceName, Assembly.GetPackageVersion());
internal static readonly IEnumerable<KeyValuePair<string, object?>> CreationTags = new[]
{
new KeyValuePair<string, object?>(SemanticConventions.AttributeDbSystem, "redis"),
};
internal static readonly IEnumerable<KeyValuePair<string, object?>> CreationTags =
[
new KeyValuePair<string, object?>(SemanticConventions.AttributeDbSystem, "redis")
];

internal readonly ConcurrentDictionary<(ActivityTraceId TraceId, ActivitySpanId SpanId), (Activity Activity, ProfilingSession Session)> Cache
= new();
Expand Down Expand Up @@ -119,7 +119,7 @@ internal void Flush()
continue;
}

ProfilingSession session = entry.Value.Session;
var session = entry.Value.Session;
RedisProfilerEntryToActivityConverter.DrainSession(parent, session.FinishProfiling(), this.options);
this.Cache.TryRemove((entry.Key.TraceId, entry.Key.SpanId), out _);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ internal StackExchangeRedisInstrumentation(
this.options = options;
}

internal List<StackExchangeRedisConnectionInstrumentation> InstrumentedConnections { get; } = new();
internal List<StackExchangeRedisConnectionInstrumentation> InstrumentedConnections { get; } = [];

/// <summary>
/// Adds an <see cref="IConnectionMultiplexer"/> to the instrumentation.
Expand Down
12 changes: 6 additions & 6 deletions src/OpenTelemetry.Resources.AWS/AWSECSDetector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ internal static List<KeyValuePair<string, object>> ExtractMetadataV4ResourceAttr
var metadataV4Url = Environment.GetEnvironmentVariable(AWSECSMetadataURLV4Key);
if (metadataV4Url == null)
{
return new List<KeyValuePair<string, object>>();
return [];
}

using var httpClientHandler = new HttpClientHandler();
Expand All @@ -77,14 +77,14 @@ internal static List<KeyValuePair<string, object>> ExtractMetadataV4ResourceAttr
|| 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 new List<KeyValuePair<string, object>>();
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 new List<KeyValuePair<string, object>>();
return [];
}

if (!clusterArn.StartsWith("arn:", StringComparison.Ordinal))
Expand All @@ -95,9 +95,9 @@ internal static List<KeyValuePair<string, object>> ExtractMetadataV4ResourceAttr

var resourceAttributes = new List<KeyValuePair<string, object>>()
{
new KeyValuePair<string, object>(AWSSemanticConventions.AttributeCloudResourceId, containerArn),
new KeyValuePair<string, object>(AWSSemanticConventions.AttributeEcsContainerArn, containerArn),
new KeyValuePair<string, object>(AWSSemanticConventions.AttributeEcsClusterArn, clusterArn),
new(AWSSemanticConventions.AttributeCloudResourceId, containerArn),
new(AWSSemanticConventions.AttributeEcsContainerArn, containerArn),
new(AWSSemanticConventions.AttributeEcsClusterArn, clusterArn),
};

if (taskResponse.RootElement.TryGetProperty("AvailabilityZone", out var availabilityZoneElement) && availabilityZoneElement.ValueKind == JsonValueKind.String)
Expand Down
29 changes: 12 additions & 17 deletions src/OpenTelemetry.Resources.AWS/AWSEKSDetector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,19 @@ public Resource Detect()
var credentials = GetEKSCredentials(AWSEKSCredentialPath);
using var httpClientHandler = ServerCertificateValidationHandler.Create(AWSEKSCertificatePath, AWSResourcesEventSource.Log);

if (credentials == null || !IsEKSProcess(credentials, httpClientHandler))
{
return Resource.Empty;
}

return new Resource(ExtractResourceAttributes(
GetEKSClusterName(credentials, httpClientHandler),
GetEKSContainerId(AWSEKSMetadataFilePath)));
return credentials == null || !IsEKSProcess(credentials, httpClientHandler)
? Resource.Empty
: new Resource(ExtractResourceAttributes(
GetEKSClusterName(credentials, httpClientHandler),
GetEKSContainerId(AWSEKSMetadataFilePath)));
}

internal static List<KeyValuePair<string, object>> ExtractResourceAttributes(string? clusterName, string? containerId)
{
var resourceAttributes = new List<KeyValuePair<string, object>>()
{
new KeyValuePair<string, object>(AWSSemanticConventions.AttributeCloudProvider, "aws"),
new KeyValuePair<string, object>(AWSSemanticConventions.AttributeCloudPlatform, "aws_eks"),
new(AWSSemanticConventions.AttributeCloudProvider, "aws"),
new(AWSSemanticConventions.AttributeCloudPlatform, "aws_eks"),
};

if (!string.IsNullOrEmpty(clusterName))
Expand Down Expand Up @@ -86,15 +83,13 @@ internal static List<KeyValuePair<string, object>> ExtractResourceAttributes(str
{
try
{
using (var streamReader = ResourceDetectorUtils.GetStreamReader(path))
using var streamReader = ResourceDetectorUtils.GetStreamReader(path);
while (!streamReader.EndOfStream)
{
while (!streamReader.EndOfStream)
var trimmedLine = streamReader.ReadLine()?.Trim();
if (trimmedLine?.Length > 64)
{
var trimmedLine = streamReader.ReadLine()?.Trim();
if (trimmedLine?.Length > 64)
{
return trimmedLine.Substring(trimmedLine.Length - 64);
}
return trimmedLine.Substring(trimmedLine.Length - 64);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/OpenTelemetry.Resources.AWS/AsyncHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace OpenTelemetry.Resources.AWS;
/// </summary>
internal static class AsyncHelper
{
private static readonly TaskFactory TaskFactory = new TaskFactory(
private static readonly TaskFactory TaskFactory = new(
CancellationToken.None,
TaskCreationOptions.None,
TaskContinuationOptions.None,
Expand Down
21 changes: 9 additions & 12 deletions src/OpenTelemetry.Resources.Azure/AppServiceResourceDetector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ internal sealed class AppServiceResourceDetector : IResourceDetector
/// <inheritdoc/>
public Resource Detect()
{
List<KeyValuePair<string, object>> attributeList = new();
List<KeyValuePair<string, object>> attributeList = [];

try
{
Expand Down Expand Up @@ -61,21 +61,18 @@ public Resource Detect()

private static string? GetAzureResourceURI(string websiteSiteName)
{
string? websiteResourceGroup = Environment.GetEnvironmentVariable(ResourceAttributeConstants.AppServiceResourceGroupEnvVar);
string websiteOwnerName = Environment.GetEnvironmentVariable(ResourceAttributeConstants.AppServiceOwnerNameEnvVar) ?? string.Empty;
var websiteResourceGroup = Environment.GetEnvironmentVariable(ResourceAttributeConstants.AppServiceResourceGroupEnvVar);
var websiteOwnerName = Environment.GetEnvironmentVariable(ResourceAttributeConstants.AppServiceOwnerNameEnvVar) ?? string.Empty;

#if NET
int idx = websiteOwnerName.IndexOf('+', StringComparison.Ordinal);
var idx = websiteOwnerName.IndexOf('+', StringComparison.Ordinal);
#else
int idx = websiteOwnerName.IndexOf("+", StringComparison.Ordinal);
var idx = websiteOwnerName.IndexOf("+", StringComparison.Ordinal);
#endif
string subscriptionId = idx > 0 ? websiteOwnerName.Substring(0, idx) : websiteOwnerName;
var subscriptionId = idx > 0 ? websiteOwnerName.Substring(0, idx) : websiteOwnerName;

if (string.IsNullOrEmpty(websiteResourceGroup) || string.IsNullOrEmpty(subscriptionId))
{
return null;
}

return $"/subscriptions/{subscriptionId}/resourceGroups/{websiteResourceGroup}/providers/Microsoft.Web/sites/{websiteSiteName}";
return string.IsNullOrEmpty(websiteResourceGroup) || string.IsNullOrEmpty(subscriptionId)
? null
: $"/subscriptions/{subscriptionId}/resourceGroups/{websiteResourceGroup}/providers/Microsoft.Web/sites/{websiteSiteName}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ internal sealed class AzureContainerAppsResourceDetector : IResourceDetector
/// <inheritdoc/>
public Resource Detect()
{
List<KeyValuePair<string, object>> attributeList = new List<KeyValuePair<string, object>>();
List<KeyValuePair<string, object>> attributeList = [];
try
{
var containerAppName = Environment.GetEnvironmentVariable(ResourceAttributeConstants.AzureContainerAppsNameEnvVar);
Expand Down
8 changes: 4 additions & 4 deletions src/OpenTelemetry.Resources.Azure/AzureVMResourceDetector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ namespace OpenTelemetry.Resources.Azure;
/// </summary>
internal sealed class AzureVMResourceDetector : IResourceDetector
{
internal static readonly IReadOnlyCollection<string> ExpectedAzureAmsFields = new string[]
{
internal static readonly IReadOnlyCollection<string> ExpectedAzureAmsFields =
[
ResourceAttributeConstants.AzureVmScaleSetName,
ResourceAttributeConstants.AzureVmSku,
ResourceSemanticConventions.AttributeCloudPlatform,
Expand All @@ -23,8 +23,8 @@ internal sealed class AzureVMResourceDetector : IResourceDetector
ResourceSemanticConventions.AttributeHostType,
ResourceSemanticConventions.AttributeOsType,
ResourceSemanticConventions.AttributeOsVersion,
ResourceSemanticConventions.AttributeServiceInstance,
};
ResourceSemanticConventions.AttributeServiceInstance
];

private static Resource? vmResource;

Expand Down
2 changes: 2 additions & 0 deletions src/OpenTelemetry.Resources.Azure/AzureVmMetadataResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ internal string GetValueForField(string fieldName)
case ResourceAttributeConstants.AzureVmSku:
amsValue = this.Sku;
break;
default:
break;
}

amsValue ??= string.Empty;
Expand Down
35 changes: 9 additions & 26 deletions src/OpenTelemetry.Resources.Container/ContainerDetector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,7 @@ internal Resource BuildResource(string path, ParseMode cgroupVersion)
{
var containerId = this.ExtractContainerId(path, cgroupVersion);

if (string.IsNullOrEmpty(containerId))
{
return Resource.Empty;
}
else
{
return new Resource(new List<KeyValuePair<string, object>>(1) { new(ContainerSemanticConventions.AttributeContainerId, containerId!) });
}
return string.IsNullOrEmpty(containerId) ? Resource.Empty : new Resource([new(ContainerSemanticConventions.AttributeContainerId, containerId!)]);
}

/// <summary>
Expand All @@ -74,24 +67,19 @@ internal Resource BuildResource(string path, ParseMode cgroupVersion)
private static string? GetIdFromLineV1(string line)
{
// This cgroup output line should have the container id in it
int lastSlashIndex = line.LastIndexOf('/');
var lastSlashIndex = line.LastIndexOf('/');
if (lastSlashIndex < 0)
{
return null;
}

string lastSection = line.Substring(lastSlashIndex + 1);
int startIndex = lastSection.LastIndexOf('-');
int endIndex = lastSection.LastIndexOf('.');

string containerId = RemovePrefixAndSuffixIfNeeded(lastSection, startIndex, endIndex);
var lastSection = line.Substring(lastSlashIndex + 1);
var startIndex = lastSection.LastIndexOf('-');
var endIndex = lastSection.LastIndexOf('.');

if (string.IsNullOrEmpty(containerId) || !EncodingUtils.IsValidHexString(containerId))
{
return null;
}
var containerId = RemovePrefixAndSuffixIfNeeded(lastSection, startIndex, endIndex);

return containerId;
return string.IsNullOrEmpty(containerId) || !EncodingUtils.IsValidHexString(containerId) ? null : containerId;
}

/// <summary>
Expand All @@ -108,12 +96,7 @@ internal Resource BuildResource(string path, ParseMode cgroupVersion)
containerId = match.Groups[1].Value;
}

if (string.IsNullOrEmpty(containerId) || !EncodingUtils.IsValidHexString(containerId!))
{
return null;
}

return containerId;
return string.IsNullOrEmpty(containerId) || !EncodingUtils.IsValidHexString(containerId!) ? null : containerId;
}

private static string RemovePrefixAndSuffixIfNeeded(string input, int startIndex, int endIndex)
Expand Down Expand Up @@ -143,7 +126,7 @@ private static string RemovePrefixAndSuffixIfNeeded(string input, int startIndex
return null;
}

foreach (string line in File.ReadLines(path))
foreach (var line in File.ReadLines(path))
{
string? containerId = null;
if (!string.IsNullOrEmpty(line))
Expand Down
5 changes: 1 addition & 4 deletions src/OpenTelemetry.Resources.Container/Utils/EncodingUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ internal class EncodingUtils
/// <returns>true if valid else false.</returns>
public static bool IsValidHexString(IEnumerable<char> hexString)
{
return hexString.All(currentCharacter =>
(currentCharacter >= '0' && currentCharacter <= '9') ||
(currentCharacter >= 'a' && currentCharacter <= 'f') ||
(currentCharacter >= 'A' && currentCharacter <= 'F'));
return hexString.All(currentCharacter => currentCharacter is (>= '0' and <= '9') or (>= 'a' and <= 'f') or (>= 'A' and <= 'F'));
}
}
Loading

0 comments on commit 3643194

Please sign in to comment.