diff --git a/src/OpenTelemetry.Exporter.Geneva/Metrics/OtlpProtobuf/OtlpProtobufMetricExporter.cs b/src/OpenTelemetry.Exporter.Geneva/Metrics/OtlpProtobuf/OtlpProtobufMetricExporter.cs index 174e5ded5c..835c6cac1d 100644 --- a/src/OpenTelemetry.Exporter.Geneva/Metrics/OtlpProtobuf/OtlpProtobufMetricExporter.cs +++ b/src/OpenTelemetry.Exporter.Geneva/Metrics/OtlpProtobuf/OtlpProtobufMetricExporter.cs @@ -18,7 +18,7 @@ internal sealed class OtlpProtobufMetricExporter : IDisposable public OtlpProtobufMetricExporter( Func getResource, - ConnectionStringBuilder connectionStringBuilder, + ConnectionStringBuilder? connectionStringBuilder, IReadOnlyDictionary? prepopulatedMetricDimensions) { Debug.Assert(getResource != null, "getResource was null"); diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/Implementation/RedisProfilerEntryToActivityConverter.cs b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/Implementation/RedisProfilerEntryToActivityConverter.cs index 5b3a338383..a46574f451 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/Implementation/RedisProfilerEntryToActivityConverter.cs +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/Implementation/RedisProfilerEntryToActivityConverter.cs @@ -18,8 +18,8 @@ internal static class RedisProfilerEntryToActivityConverter { private static readonly Lazy> 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(profiledCommandType, "Message", BindingFlags.NonPublic | BindingFlags.Instance); var scriptDelegate = CreateFieldGetter(scriptMessageType, "script", BindingFlags.NonPublic | BindingFlags.Instance); @@ -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")] @@ -199,19 +194,19 @@ public static void DrainSession(Activity? parentActivity, IEnumerable> CreationTags = new[] - { - new KeyValuePair(SemanticConventions.AttributeDbSystem, "redis"), - }; + internal static readonly IEnumerable> CreationTags = + [ + new KeyValuePair(SemanticConventions.AttributeDbSystem, "redis") + ]; internal readonly ConcurrentDictionary<(ActivityTraceId TraceId, ActivitySpanId SpanId), (Activity Activity, ProfilingSession Session)> Cache = new(); @@ -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 _); } diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisInstrumentation.cs b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisInstrumentation.cs index 4436a42df4..41e6671ace 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisInstrumentation.cs +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisInstrumentation.cs @@ -20,7 +20,7 @@ internal StackExchangeRedisInstrumentation( this.options = options; } - internal List InstrumentedConnections { get; } = new(); + internal List InstrumentedConnections { get; } = []; /// /// Adds an to the instrumentation. diff --git a/src/OpenTelemetry.Resources.AWS/AWSECSDetector.cs b/src/OpenTelemetry.Resources.AWS/AWSECSDetector.cs index c992995072..ac43f694ff 100644 --- a/src/OpenTelemetry.Resources.AWS/AWSECSDetector.cs +++ b/src/OpenTelemetry.Resources.AWS/AWSECSDetector.cs @@ -63,7 +63,7 @@ internal static List> ExtractMetadataV4ResourceAttr var metadataV4Url = Environment.GetEnvironmentVariable(AWSECSMetadataURLV4Key); if (metadataV4Url == null) { - return new List>(); + return []; } using var httpClientHandler = new HttpClientHandler(); @@ -77,14 +77,14 @@ internal static List> 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>(); + 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>(); + return []; } if (!clusterArn.StartsWith("arn:", StringComparison.Ordinal)) @@ -95,9 +95,9 @@ internal static List> ExtractMetadataV4ResourceAttr var resourceAttributes = new List>() { - new KeyValuePair(AWSSemanticConventions.AttributeCloudResourceId, containerArn), - new KeyValuePair(AWSSemanticConventions.AttributeEcsContainerArn, containerArn), - new KeyValuePair(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) diff --git a/src/OpenTelemetry.Resources.AWS/AWSEKSDetector.cs b/src/OpenTelemetry.Resources.AWS/AWSEKSDetector.cs index c26e10571d..adf4a59632 100644 --- a/src/OpenTelemetry.Resources.AWS/AWSEKSDetector.cs +++ b/src/OpenTelemetry.Resources.AWS/AWSEKSDetector.cs @@ -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> ExtractResourceAttributes(string? clusterName, string? containerId) { var resourceAttributes = new List>() { - new KeyValuePair(AWSSemanticConventions.AttributeCloudProvider, "aws"), - new KeyValuePair(AWSSemanticConventions.AttributeCloudPlatform, "aws_eks"), + new(AWSSemanticConventions.AttributeCloudProvider, "aws"), + new(AWSSemanticConventions.AttributeCloudPlatform, "aws_eks"), }; if (!string.IsNullOrEmpty(clusterName)) @@ -86,15 +83,13 @@ internal static List> 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); } } } diff --git a/src/OpenTelemetry.Resources.AWS/AsyncHelper.cs b/src/OpenTelemetry.Resources.AWS/AsyncHelper.cs index f999beff0e..a75d5579c9 100644 --- a/src/OpenTelemetry.Resources.AWS/AsyncHelper.cs +++ b/src/OpenTelemetry.Resources.AWS/AsyncHelper.cs @@ -8,7 +8,7 @@ namespace OpenTelemetry.Resources.AWS; /// internal static class AsyncHelper { - private static readonly TaskFactory TaskFactory = new TaskFactory( + private static readonly TaskFactory TaskFactory = new( CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, diff --git a/src/OpenTelemetry.Resources.Azure/AppServiceResourceDetector.cs b/src/OpenTelemetry.Resources.Azure/AppServiceResourceDetector.cs index 71b0c03a5c..6163fed898 100644 --- a/src/OpenTelemetry.Resources.Azure/AppServiceResourceDetector.cs +++ b/src/OpenTelemetry.Resources.Azure/AppServiceResourceDetector.cs @@ -22,7 +22,7 @@ internal sealed class AppServiceResourceDetector : IResourceDetector /// public Resource Detect() { - List> attributeList = new(); + List> attributeList = []; try { @@ -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}"; } } diff --git a/src/OpenTelemetry.Resources.Azure/AzureContainerAppsResourceDetector.cs b/src/OpenTelemetry.Resources.Azure/AzureContainerAppsResourceDetector.cs index 58c11aa2bd..aa04c2b35c 100644 --- a/src/OpenTelemetry.Resources.Azure/AzureContainerAppsResourceDetector.cs +++ b/src/OpenTelemetry.Resources.Azure/AzureContainerAppsResourceDetector.cs @@ -25,7 +25,7 @@ internal sealed class AzureContainerAppsResourceDetector : IResourceDetector /// public Resource Detect() { - List> attributeList = new List>(); + List> attributeList = []; try { var containerAppName = Environment.GetEnvironmentVariable(ResourceAttributeConstants.AzureContainerAppsNameEnvVar); diff --git a/src/OpenTelemetry.Resources.Azure/AzureVMResourceDetector.cs b/src/OpenTelemetry.Resources.Azure/AzureVMResourceDetector.cs index 5553488629..3feeee3a99 100644 --- a/src/OpenTelemetry.Resources.Azure/AzureVMResourceDetector.cs +++ b/src/OpenTelemetry.Resources.Azure/AzureVMResourceDetector.cs @@ -10,8 +10,8 @@ namespace OpenTelemetry.Resources.Azure; /// internal sealed class AzureVMResourceDetector : IResourceDetector { - internal static readonly IReadOnlyCollection ExpectedAzureAmsFields = new string[] - { + internal static readonly IReadOnlyCollection ExpectedAzureAmsFields = + [ ResourceAttributeConstants.AzureVmScaleSetName, ResourceAttributeConstants.AzureVmSku, ResourceSemanticConventions.AttributeCloudPlatform, @@ -23,8 +23,8 @@ internal sealed class AzureVMResourceDetector : IResourceDetector ResourceSemanticConventions.AttributeHostType, ResourceSemanticConventions.AttributeOsType, ResourceSemanticConventions.AttributeOsVersion, - ResourceSemanticConventions.AttributeServiceInstance, - }; + ResourceSemanticConventions.AttributeServiceInstance + ]; private static Resource? vmResource; diff --git a/src/OpenTelemetry.Resources.Azure/AzureVmMetadataResponse.cs b/src/OpenTelemetry.Resources.Azure/AzureVmMetadataResponse.cs index 81418c8920..1282298fed 100644 --- a/src/OpenTelemetry.Resources.Azure/AzureVmMetadataResponse.cs +++ b/src/OpenTelemetry.Resources.Azure/AzureVmMetadataResponse.cs @@ -80,6 +80,8 @@ internal string GetValueForField(string fieldName) case ResourceAttributeConstants.AzureVmSku: amsValue = this.Sku; break; + default: + break; } amsValue ??= string.Empty; diff --git a/src/OpenTelemetry.Resources.Container/ContainerDetector.cs b/src/OpenTelemetry.Resources.Container/ContainerDetector.cs index 8b00d6776a..0f43e1495f 100644 --- a/src/OpenTelemetry.Resources.Container/ContainerDetector.cs +++ b/src/OpenTelemetry.Resources.Container/ContainerDetector.cs @@ -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>(1) { new(ContainerSemanticConventions.AttributeContainerId, containerId!) }); - } + return string.IsNullOrEmpty(containerId) ? Resource.Empty : new Resource([new(ContainerSemanticConventions.AttributeContainerId, containerId!)]); } /// @@ -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; } /// @@ -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) @@ -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)) diff --git a/src/OpenTelemetry.Resources.Container/Utils/EncodingUtils.cs b/src/OpenTelemetry.Resources.Container/Utils/EncodingUtils.cs index 3ad985bd95..f33ad70126 100644 --- a/src/OpenTelemetry.Resources.Container/Utils/EncodingUtils.cs +++ b/src/OpenTelemetry.Resources.Container/Utils/EncodingUtils.cs @@ -12,9 +12,6 @@ internal class EncodingUtils /// true if valid else false. public static bool IsValidHexString(IEnumerable 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')); } } diff --git a/src/OpenTelemetry.Resources.Gcp/GcpResourceDetector.cs b/src/OpenTelemetry.Resources.Gcp/GcpResourceDetector.cs index 99de6d8309..f2dd4da02b 100644 --- a/src/OpenTelemetry.Resources.Gcp/GcpResourceDetector.cs +++ b/src/OpenTelemetry.Resources.Gcp/GcpResourceDetector.cs @@ -27,6 +27,7 @@ public Resource Detect() PlatformType.CloudRun => ExtractCloudRunResourceAttributes(platform), PlatformType.Gae => ExtractGaeResourceAttributes(platform), PlatformType.Gce => ExtractGceResourceAttributes(platform), + PlatformType.Unknown => ExtractGceResourceAttributes(platform), _ => ExtractGceResourceAttributes(platform), }; @@ -35,8 +36,8 @@ public Resource Detect() internal static List> ExtractGkeResourceAttributes(Platform platform) { - List> attributeList = new() - { + List> attributeList = + [ new(ResourceSemanticConventions.AttributeCloudProvider, ResourceAttributeConstants.GcpCloudProviderValue), new(ResourceSemanticConventions.AttributeCloudAccount, platform.ProjectId), new(ResourceSemanticConventions.AttributeCloudPlatform, ResourceAttributeConstants.GcpGkePlatformValue), @@ -44,47 +45,47 @@ internal static List> ExtractGkeResourceAttributes( new(ResourceSemanticConventions.AttributeHostId, platform.GkeDetails.InstanceId), new(ResourceSemanticConventions.AttributeK8sCluster, platform.GkeDetails.ClusterName), new(ResourceSemanticConventions.AttributeK8sNamespace, platform.GkeDetails.NamespaceId), - new(ResourceSemanticConventions.AttributeK8sPod, platform.GkeDetails.HostName), - }; + new(ResourceSemanticConventions.AttributeK8sPod, platform.GkeDetails.HostName) + ]; return attributeList; } internal static List> ExtractCloudRunResourceAttributes(Platform platform) { - List> attributeList = new() - { + List> attributeList = + [ new(ResourceSemanticConventions.AttributeCloudProvider, ResourceAttributeConstants.GcpCloudProviderValue), new(ResourceSemanticConventions.AttributeCloudAccount, platform.ProjectId), new(ResourceSemanticConventions.AttributeCloudAvailabilityZone, platform.CloudRunDetails.Zone), new(ResourceSemanticConventions.AttributeCloudPlatform, ResourceAttributeConstants.GcpCloudRunPlatformValue), - new(ResourceSemanticConventions.AttributeCloudRegion, platform.CloudRunDetails.Region), - }; + new(ResourceSemanticConventions.AttributeCloudRegion, platform.CloudRunDetails.Region) + ]; return attributeList; } internal static List> ExtractGaeResourceAttributes(Platform platform) { - List> attributeList = new() - { + List> attributeList = + [ new(ResourceSemanticConventions.AttributeCloudProvider, ResourceAttributeConstants.GcpCloudProviderValue), new(ResourceSemanticConventions.AttributeCloudAccount, platform.ProjectId), - new(ResourceSemanticConventions.AttributeCloudPlatform, ResourceAttributeConstants.GcpGaePlatformValue), - }; + new(ResourceSemanticConventions.AttributeCloudPlatform, ResourceAttributeConstants.GcpGaePlatformValue) + ]; return attributeList; } internal static List> ExtractGceResourceAttributes(Platform platform) { - List> attributeList = new() - { + List> attributeList = + [ new(ResourceSemanticConventions.AttributeCloudProvider, ResourceAttributeConstants.GcpCloudProviderValue), new(ResourceSemanticConventions.AttributeCloudAccount, platform.ProjectId), new(ResourceSemanticConventions.AttributeCloudPlatform, ResourceAttributeConstants.GcpGcePlatformValue), new(ResourceSemanticConventions.AttributeHostId, platform.GceDetails.InstanceId), - new(ResourceSemanticConventions.AttributeCloudAvailabilityZone, platform.GceDetails.Location), - }; + new(ResourceSemanticConventions.AttributeCloudAvailabilityZone, platform.GceDetails.Location) + ]; return attributeList; } diff --git a/src/OpenTelemetry.Resources.Host/HostDetector.cs b/src/OpenTelemetry.Resources.Host/HostDetector.cs index a52e527e5a..1127e2037c 100644 --- a/src/OpenTelemetry.Resources.Host/HostDetector.cs +++ b/src/OpenTelemetry.Resources.Host/HostDetector.cs @@ -113,7 +113,7 @@ public Resource Detect() return null; } - var lines = output.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); + var lines = output.Split([Environment.NewLine], StringSplitOptions.None); foreach (var line in lines) { @@ -162,8 +162,8 @@ private static IEnumerable GetFilePaths() var isExited = process.WaitForExit(5000); if (isExited) { - string output = process.StandardOutput.ReadToEnd(); - string error = process.StandardError.ReadToEnd(); + var output = process.StandardOutput.ReadToEnd(); + var error = process.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(error)) { @@ -215,22 +215,10 @@ private static IEnumerable GetFilePaths() #if NETFRAMEWORK return this.getWindowsMachineId(); #else - if (this.isOsPlatform(OSPlatform.Windows)) - { - return this.getWindowsMachineId(); - } - - if (this.isOsPlatform(OSPlatform.Linux)) - { - return this.GetMachineIdLinux(); - } + return this.isOsPlatform(OSPlatform.Windows) ? this.getWindowsMachineId() : + this.isOsPlatform(OSPlatform.Linux) ? this.GetMachineIdLinux() : + this.isOsPlatform(OSPlatform.OSX) ? ParseMacOsOutput(this.getMacOsMachineId()) : null; - if (this.isOsPlatform(OSPlatform.OSX)) - { - return ParseMacOsOutput(this.getMacOsMachineId()); - } - - return null; #endif } diff --git a/src/OpenTelemetry.Resources.OperatingSystem/OperatingSystemDetector.cs b/src/OpenTelemetry.Resources.OperatingSystem/OperatingSystemDetector.cs index 1e018c25fd..8f01fa9f7c 100644 --- a/src/OpenTelemetry.Resources.OperatingSystem/OperatingSystemDetector.cs +++ b/src/OpenTelemetry.Resources.OperatingSystem/OperatingSystemDetector.cs @@ -17,6 +17,7 @@ namespace OpenTelemetry.Resources.OperatingSystem; internal sealed class OperatingSystemDetector : IResourceDetector { private const string RegistryKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion"; +#if NET private const string KernelOsRelease = "/proc/sys/kernel/osrelease"; private static readonly string[] DefaultEtcOsReleasePaths = [ @@ -29,23 +30,26 @@ internal sealed class OperatingSystemDetector : IResourceDetector "/System/Library/CoreServices/SystemVersion.plist", "/System/Library/CoreServices/ServerVersion.plist" ]; +#endif private readonly string? osType; private readonly string? registryKey; +#if NET private readonly string? kernelOsRelease; private readonly string[]? etcOsReleasePaths; private readonly string[]? plistFilePaths; +#endif internal OperatingSystemDetector() - : this( - GetOSType(), - RegistryKey, - KernelOsRelease, - DefaultEtcOsReleasePaths, - DefaultPlistFilePaths) +#if NET + : this(GetOSType(), RegistryKey, KernelOsRelease, DefaultEtcOsReleasePaths, DefaultPlistFilePaths) +#else + : this(GetOSType(), RegistryKey) +#endif { } +#if NET /// /// Initializes a new instance of the class for testing. /// @@ -55,12 +59,22 @@ internal OperatingSystemDetector() /// The string path to the file used to obtain Linux attributes. /// An array of file paths used to retrieve MacOS attributes from plist files. internal OperatingSystemDetector(string? osType, string? registryKey, string? kernelOsRelease, string[]? etcOsReleasePath, string[]? plistFilePaths) +#else + /// + /// Initializes a new instance of the class for testing. + /// + /// The target platform identifier, specifying the operating system type from SemanticConventions. + /// The string path in the Windows Registry to retrieve specific Windows attributes. + internal OperatingSystemDetector(string? osType, string? registryKey) +#endif { this.osType = osType; this.registryKey = registryKey; +#if NET this.kernelOsRelease = kernelOsRelease; this.etcOsReleasePaths = etcOsReleasePath; this.plistFilePaths = plistFilePaths; +#endif } /// @@ -93,6 +107,8 @@ public Resource Detect() this.AddMacOSAttributes(attributes); break; #endif + default: + break; } return new Resource(attributes); @@ -120,22 +136,9 @@ private static void AddAttributeIfNotNullOrEmpty(List> attributes) { try { - string? etcOsReleasePath = this.etcOsReleasePaths!.FirstOrDefault(File.Exists); + var etcOsReleasePath = this.etcOsReleasePaths!.FirstOrDefault(File.Exists); if (string.IsNullOrEmpty(etcOsReleasePath)) { OperatingSystemResourcesEventSource.Log.FailedToFindFile("Failed to find the os-release file"); @@ -187,22 +190,14 @@ private void AddLinuxAttributes(List> attributes) foreach (var line in osReleaseContent) { - ReadOnlySpan lineSpan = line.AsSpan(); + var lineSpan = line.AsSpan(); _ = TryGetFieldValue(lineSpan, "BUILD_ID=", ref buildId) || TryGetFieldValue(lineSpan, "NAME=", ref name) || TryGetFieldValue(lineSpan, "VERSION_ID=", ref version); } - string? buildIdContent = null; - if (buildId.IsEmpty) - { - buildIdContent = File.ReadAllText(this.kernelOsRelease!).Trim(); - } - else - { - buildIdContent = buildId.ToString(); - } + var buildIdContent = buildId.IsEmpty ? File.ReadAllText(this.kernelOsRelease!).Trim() : buildId.ToString(); AddAttributeIfNotNullOrEmpty(attributes, AttributeOperatingSystemBuildId, buildIdContent); AddAttributeIfNotNullOrEmpty(attributes, AttributeOperatingSystemName, name.IsEmpty ? "Linux" : name.ToString()); @@ -220,7 +215,7 @@ static bool TryGetFieldValue(ReadOnlySpan line, ReadOnlySpan prefix, return false; } - ReadOnlySpan fieldValue = line.Slice(prefix.Length); + var fieldValue = line.Slice(prefix.Length); // Remove enclosing quotes if present. if (fieldValue.Length >= 2 && @@ -239,14 +234,14 @@ private void AddMacOSAttributes(List> attributes) { try { - string? plistFilePath = this.plistFilePaths!.FirstOrDefault(File.Exists); + var plistFilePath = this.plistFilePaths!.FirstOrDefault(File.Exists); if (string.IsNullOrEmpty(plistFilePath)) { OperatingSystemResourcesEventSource.Log.FailedToFindFile("No suitable plist file found"); return; } - XDocument doc = XDocument.Load(plistFilePath); + var doc = XDocument.Load(plistFilePath); var dict = doc.Root?.Element("dict"); string? buildId = null, name = null, version = null; @@ -262,7 +257,7 @@ private void AddMacOSAttributes(List> attributes) return; } - for (int i = 0; i < keys.Count; i++) + for (var i = 0; i < keys.Count; i++) { switch (keys[i].Value) { @@ -275,6 +270,8 @@ private void AddMacOSAttributes(List> attributes) case "ProductVersion": version = values[i].Value; break; + default: + break; } } } diff --git a/src/OpenTelemetry.Resources.ProcessRuntime/ProcessRuntimeDetector.cs b/src/OpenTelemetry.Resources.ProcessRuntime/ProcessRuntimeDetector.cs index feac335fba..c2f43e2f6f 100644 --- a/src/OpenTelemetry.Resources.ProcessRuntime/ProcessRuntimeDetector.cs +++ b/src/OpenTelemetry.Resources.ProcessRuntime/ProcessRuntimeDetector.cs @@ -22,7 +22,7 @@ public Resource Detect() var frameworkDescription = RuntimeInformation.FrameworkDescription; string netRuntimeName; #if NETFRAMEWORK - string? netFrameworkVersion = GetNetFrameworkVersionFromRegistry(); + var netFrameworkVersion = GetNetFrameworkVersionFromRegistry(); #endif var lastSpace = frameworkDescription.LastIndexOf(' '); @@ -43,8 +43,8 @@ public Resource Detect() #endif } - return new Resource(new List>(3) - { + return new Resource( + [ new(ProcessRuntimeSemanticConventions.AttributeProcessRuntimeDescription, frameworkDescription), new(ProcessRuntimeSemanticConventions.AttributeProcessRuntimeName, netRuntimeName), #if NETFRAMEWORK @@ -52,7 +52,7 @@ public Resource Detect() #else new(ProcessRuntimeSemanticConventions.AttributeProcessRuntimeVersion, Environment.Version.ToString()), #endif - }); + ]); } #if NETFRAMEWORK @@ -64,12 +64,7 @@ public Resource Detect() using var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); using var ndpKey = baseKey.OpenSubKey(subKey); - if (ndpKey?.GetValue("Release") != null) - { - return CheckFor45PlusVersion((int)ndpKey.GetValue("Release")); - } - - return null; + return ndpKey?.GetValue("Release") != null ? CheckFor45PlusVersion((int)ndpKey.GetValue("Release")) : null; } catch { diff --git a/src/Shared/PropertyFetcher.AOT.cs b/src/Shared/PropertyFetcher.AOT.cs index 80bf4c9188..cb8ecb1b8b 100644 --- a/src/Shared/PropertyFetcher.AOT.cs +++ b/src/Shared/PropertyFetcher.AOT.cs @@ -142,7 +142,7 @@ private abstract class PropertyFetch return (PropertyFetch?)typeof(PropertyFetch) .GetMethod(nameof(CreateInstantiated), BindingFlags.NonPublic | BindingFlags.Static)! .MakeGenericMethod(declaringType) // This is validated in the earlier call chain to be a reference type. - .Invoke(null, new object[] { propertyInfo })!; + .Invoke(null, [propertyInfo])!; } } } diff --git a/src/Shared/ServerCertificateValidationProvider.cs b/src/Shared/ServerCertificateValidationProvider.cs index 232266ad3b..7b976c2119 100644 --- a/src/Shared/ServerCertificateValidationProvider.cs +++ b/src/Shared/ServerCertificateValidationProvider.cs @@ -77,8 +77,7 @@ private static bool HasCommonCertificate(X509Chain chain, X509Certificate2Collec private bool ValidateCertificate(X509Certificate2? cert, X509Chain? chain, SslPolicyErrors errors) { - var isSslPolicyPassed = errors == SslPolicyErrors.None || - errors == SslPolicyErrors.RemoteCertificateChainErrors; + var isSslPolicyPassed = errors is SslPolicyErrors.None or SslPolicyErrors.RemoteCertificateChainErrors; if (!isSslPolicyPassed) { if ((errors | SslPolicyErrors.RemoteCertificateNotAvailable) == errors) diff --git a/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/MetricExporterBenchmarks.cs b/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/MetricExporterBenchmarks.cs index 7c190a8005..0e45b72a37 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/MetricExporterBenchmarks.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/MetricExporterBenchmarks.cs @@ -51,16 +51,16 @@ namespace OpenTelemetry.Exporter.Geneva.Benchmarks; [MemoryDiagnoser] public class MetricExporterBenchmarks { - private Metric counterMetricWith3Dimensions; - private Metric counterMetricWith4Dimensions; + private Metric? counterMetricWith3Dimensions; + private Metric? counterMetricWith4Dimensions; private MetricPoint counterMetricPointWith3Dimensions; private MetricPoint counterMetricPointWith4Dimensions; private MetricData counterMetricDataWith3Dimensions; private MetricData counterMetricDataWith4Dimensions; private Batch counterMetricBatchWith3Dimensions; private Batch counterMetricBatchWith4Dimensions; - private Metric histogramMetricWith3Dimensions; - private Metric histogramMetricWith4Dimensions; + private Metric? histogramMetricWith3Dimensions; + private Metric? histogramMetricWith4Dimensions; private MetricPoint histogramMetricPointWith3Dimensions; private MetricPoint histogramMetricPointWith4Dimensions; private ulong histogramSumWith3Dimensions; @@ -77,23 +77,23 @@ public class MetricExporterBenchmarks private Meter meterWithListener = new Meter("MeterWithListener", "0.0.1"); private Meter meterWithDummyReader = new Meter("MeterWithDummyReader", "0.0.1"); private Meter meterWithGenevaMetricExporter = new Meter("MeterWithGenevaMetricExporter", "0.0.1"); - private Counter counterWithNoListener; - private Counter counterWithListener; - private Counter counterWithDummyReader; - private Counter counterWithGenevaMetricExporter; - private MeterListener listener; - private MeterProvider meterProviderWithDummyReader; - private MeterProvider meterProviderWithGenevaMetricExporter; - private MeterProvider meterProviderForCounterBatchWith3Dimensions; - private MeterProvider meterProviderForCounterBatchWith4Dimensions; - private MeterProvider meterProviderForHistogramBatchWith3Dimensions; - private MeterProvider meterProviderForHistogramBatchWith4Dimensions; - private TlvMetricExporter tlvMetricsExporter; - private OtlpProtobufMetricExporter otlpProtobufMetricExporter; - private OtlpProtobufSerializer otlpProtobufSerializer; - private Resource resource; - private byte[] buffer; - private ThreadLocal random = new ThreadLocal(() => new Random()); + private Counter? counterWithNoListener; + private Counter? counterWithListener; + private Counter? counterWithDummyReader; + private Counter? counterWithGenevaMetricExporter; + private MeterListener? listener; + private MeterProvider? meterProviderWithDummyReader; + private MeterProvider? meterProviderWithGenevaMetricExporter; + private MeterProvider? meterProviderForCounterBatchWith3Dimensions; + private MeterProvider? meterProviderForCounterBatchWith4Dimensions; + private MeterProvider? meterProviderForHistogramBatchWith3Dimensions; + private MeterProvider? meterProviderForHistogramBatchWith4Dimensions; + private TlvMetricExporter? tlvMetricsExporter; + private OtlpProtobufMetricExporter? otlpProtobufMetricExporter; + private OtlpProtobufSerializer? otlpProtobufSerializer; + private Resource? resource; + private byte[]? buffer; + private ThreadLocal random = new(() => new Random()); private static readonly Random randomForHistogram = new Random(); // Use the same seed for all the benchmarks to have the same data exported private static readonly string[] dimensionValues = new string[] { "DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10" }; @@ -192,7 +192,7 @@ private MetricPoint GenerateCounterMetricItemWith3Dimensions(out MetricData metr counter.Add( 100, - new("DimName1", dimensionValues[this.random.Value.Next(0, 10)]), + new("DimName1", dimensionValues[this.random.Value!.Next(0, 10)]), new("DimName2", dimensionValues[this.random.Value.Next(0, 10)]), new("DimName3", dimensionValues[this.random.Value.Next(0, 10)])); @@ -226,7 +226,7 @@ private MetricPoint GenerateCounterMetricItemWith4Dimensions(out MetricData metr var tags = new TagList { - { "DimName1", dimensionValues[this.random.Value.Next(0, 2)] }, + { "DimName1", dimensionValues[this.random.Value!.Next(0, 2)] }, { "DimName2", dimensionValues[this.random.Value.Next(0, 5)] }, { "DimName3", dimensionValues[this.random.Value.Next(0, 10)] }, { "DimName4", dimensionValues[this.random.Value.Next(0, 10)] }, @@ -264,7 +264,7 @@ private Batch GenerateCounterBatchWith3Dimensions() counter.Add( 100, - new("DimName1", dimensionValues[this.random.Value.Next(0, 10)]), + new("DimName1", dimensionValues[this.random.Value!.Next(0, 10)]), new("DimName2", dimensionValues[this.random.Value.Next(0, 10)]), new("DimName3", dimensionValues[this.random.Value.Next(0, 10)])); @@ -290,7 +290,7 @@ private Batch GenerateCounterBatchWith4Dimensions() var tags = new TagList { - { "DimName1", dimensionValues[this.random.Value.Next(0, 2)] }, + { "DimName1", dimensionValues[this.random.Value!.Next(0, 2)] }, { "DimName2", dimensionValues[this.random.Value.Next(0, 5)] }, { "DimName3", dimensionValues[this.random.Value.Next(0, 10)] }, { "DimName4", dimensionValues[this.random.Value.Next(0, 10)] }, @@ -318,9 +318,9 @@ private MetricPoint GenerateHistogramMetricItemWith3Dimensions(out ulong sum, ou .AddReader(inMemoryReader) .Build(); - var tag1 = new KeyValuePair("DimName1", dimensionValues[this.random.Value.Next(0, 10)]); - var tag2 = new KeyValuePair("DimName2", dimensionValues[this.random.Value.Next(0, 10)]); - var tag3 = new KeyValuePair("DimName3", dimensionValues[this.random.Value.Next(0, 10)]); + var tag1 = new KeyValuePair("DimName1", dimensionValues[this.random.Value!.Next(0, 10)]); + var tag2 = new KeyValuePair("DimName2", dimensionValues[this.random.Value.Next(0, 10)]); + var tag3 = new KeyValuePair("DimName3", dimensionValues[this.random.Value.Next(0, 10)]); for (int i = 0; i < 1000; i++) { @@ -363,7 +363,7 @@ private MetricPoint GenerateHistogramMetricItemWith4Dimensions(out ulong sum, ou var tags = new TagList { - { "DimName1", dimensionValues[this.random.Value.Next(0, 2)] }, + { "DimName1", dimensionValues[this.random.Value!.Next(0, 2)] }, { "DimName2", dimensionValues[this.random.Value.Next(0, 5)] }, { "DimName3", dimensionValues[this.random.Value.Next(0, 10)] }, { "DimName4", dimensionValues[this.random.Value.Next(0, 10)] }, @@ -408,9 +408,9 @@ private Batch GenerateHistogramBatchWith3Dimensions() .AddReader(batchGeneratorReader) .Build(); - var tag1 = new KeyValuePair("DimName1", dimensionValues[this.random.Value.Next(0, 10)]); - var tag2 = new KeyValuePair("DimName2", dimensionValues[this.random.Value.Next(0, 10)]); - var tag3 = new KeyValuePair("DimName3", dimensionValues[this.random.Value.Next(0, 10)]); + var tag1 = new KeyValuePair("DimName1", dimensionValues[this.random.Value!.Next(0, 10)]); + var tag2 = new KeyValuePair("DimName2", dimensionValues[this.random.Value.Next(0, 10)]); + var tag3 = new KeyValuePair("DimName3", dimensionValues[this.random.Value.Next(0, 10)]); for (int i = 0; i < 1000; i++) { @@ -439,7 +439,7 @@ private Batch GenerateHistogramBatchWith4Dimensions() var tags = new TagList { - { "DimName1", dimensionValues[this.random.Value.Next(0, 2)] }, + { "DimName1", dimensionValues[this.random.Value!.Next(0, 2)] }, { "DimName2", dimensionValues[this.random.Value.Next(0, 5)] }, { "DimName3", dimensionValues[this.random.Value.Next(0, 10)] }, { "DimName4", dimensionValues[this.random.Value.Next(0, 10)] }, @@ -475,9 +475,9 @@ public void Cleanup() [Benchmark] public void InstrumentWithNoListener3Dimensions() { - var tag1 = new KeyValuePair("DimName1", dimensionValues[this.random.Value.Next(0, 10)]); - var tag2 = new KeyValuePair("DimName2", dimensionValues[this.random.Value.Next(0, 10)]); - var tag3 = new KeyValuePair("DimName3", dimensionValues[this.random.Value.Next(0, 10)]); + var tag1 = new KeyValuePair("DimName1", dimensionValues[this.random.Value!.Next(0, 10)]); + var tag2 = new KeyValuePair("DimName2", dimensionValues[this.random.Value.Next(0, 10)]); + var tag3 = new KeyValuePair("DimName3", dimensionValues[this.random.Value.Next(0, 10)]); this.counterWithNoListener?.Add(100, tag1, tag2, tag3); } @@ -486,7 +486,7 @@ public void InstrumentWithNoListener4Dimensions() { var tags = new TagList { - { "DimName1", dimensionValues[this.random.Value.Next(0, 2)] }, + { "DimName1", dimensionValues[this.random.Value!.Next(0, 2)] }, { "DimName2", dimensionValues[this.random.Value.Next(0, 5)] }, { "DimName3", dimensionValues[this.random.Value.Next(0, 10)] }, { "DimName4", dimensionValues[this.random.Value.Next(0, 10)] }, @@ -499,9 +499,9 @@ public void InstrumentWithNoListener4Dimensions() [Benchmark] public void InstrumentWithWithListener3Dimensions() { - var tag1 = new KeyValuePair("DimName1", dimensionValues[this.random.Value.Next(0, 10)]); - var tag2 = new KeyValuePair("DimName2", dimensionValues[this.random.Value.Next(0, 10)]); - var tag3 = new KeyValuePair("DimName3", dimensionValues[this.random.Value.Next(0, 10)]); + var tag1 = new KeyValuePair("DimName1", dimensionValues[this.random.Value!.Next(0, 10)]); + var tag2 = new KeyValuePair("DimName2", dimensionValues[this.random.Value.Next(0, 10)]); + var tag3 = new KeyValuePair("DimName3", dimensionValues[this.random.Value.Next(0, 10)]); this.counterWithListener?.Add(100, tag1, tag2, tag3); } @@ -510,7 +510,7 @@ public void InstrumentWithWithListener4Dimensions() { var tags = new TagList { - { "DimName1", dimensionValues[this.random.Value.Next(0, 2)] }, + { "DimName1", dimensionValues[this.random.Value!.Next(0, 2)] }, { "DimName2", dimensionValues[this.random.Value.Next(0, 5)] }, { "DimName3", dimensionValues[this.random.Value.Next(0, 10)] }, { "DimName4", dimensionValues[this.random.Value.Next(0, 10)] }, @@ -523,9 +523,9 @@ public void InstrumentWithWithListener4Dimensions() [Benchmark] public void InstrumentWithWithDummyReader3Dimensions() { - var tag1 = new KeyValuePair("DimName1", dimensionValues[this.random.Value.Next(0, 10)]); - var tag2 = new KeyValuePair("DimName2", dimensionValues[this.random.Value.Next(0, 10)]); - var tag3 = new KeyValuePair("DimName3", dimensionValues[this.random.Value.Next(0, 10)]); + var tag1 = new KeyValuePair("DimName1", dimensionValues[this.random.Value!.Next(0, 10)]); + var tag2 = new KeyValuePair("DimName2", dimensionValues[this.random.Value.Next(0, 10)]); + var tag3 = new KeyValuePair("DimName3", dimensionValues[this.random.Value.Next(0, 10)]); this.counterWithDummyReader?.Add(100, tag1, tag2, tag3); } @@ -534,7 +534,7 @@ public void InstrumentWithWithDummyReader4Dimensions() { var tags = new TagList { - { "DimName1", dimensionValues[this.random.Value.Next(0, 2)] }, + { "DimName1", dimensionValues[this.random.Value!.Next(0, 2)] }, { "DimName2", dimensionValues[this.random.Value.Next(0, 5)] }, { "DimName3", dimensionValues[this.random.Value.Next(0, 10)] }, { "DimName4", dimensionValues[this.random.Value.Next(0, 10)] }, @@ -547,9 +547,9 @@ public void InstrumentWithWithDummyReader4Dimensions() [Benchmark] public void InstrumentWithWithGenevaCounterMetricExporter3Dimensions() { - var tag1 = new KeyValuePair("DimName1", dimensionValues[this.random.Value.Next(0, 10)]); - var tag2 = new KeyValuePair("DimName2", dimensionValues[this.random.Value.Next(0, 10)]); - var tag3 = new KeyValuePair("DimName3", dimensionValues[this.random.Value.Next(0, 10)]); + var tag1 = new KeyValuePair("DimName1", dimensionValues[this.random.Value!.Next(0, 10)]); + var tag2 = new KeyValuePair("DimName2", dimensionValues[this.random.Value.Next(0, 10)]); + var tag3 = new KeyValuePair("DimName3", dimensionValues[this.random.Value.Next(0, 10)]); this.counterWithGenevaMetricExporter?.Add(100, tag1, tag2, tag3); } @@ -558,7 +558,7 @@ public void InstrumentWithWithGenevaCounterMetricExporter4Dimensions() { var tags = new TagList { - { "DimName1", dimensionValues[this.random.Value.Next(0, 2)] }, + { "DimName1", dimensionValues[this.random.Value!.Next(0, 2)] }, { "DimName2", dimensionValues[this.random.Value.Next(0, 5)] }, { "DimName3", dimensionValues[this.random.Value.Next(0, 10)] }, { "DimName4", dimensionValues[this.random.Value.Next(0, 10)] }, @@ -573,9 +573,9 @@ public void SerializeCounterMetricItemWith3Dimensions() { this.counterMetricPointWith3Dimensions.TryGetExemplars(out var exemplars); - this.tlvMetricsExporter.SerializeMetricWithTLV( + this.tlvMetricsExporter!.SerializeMetricWithTLV( MetricEventType.ULongMetric, - this.counterMetricWith3Dimensions.Name, + this.counterMetricWith3Dimensions!.Name, this.counterMetricPointWith3Dimensions.EndTime.ToFileTime(), this.counterMetricPointWith3Dimensions.Tags, this.counterMetricDataWith3Dimensions, @@ -589,9 +589,9 @@ public void SerializeCounterMetricItemWith3Dimensions() public void SerializeCounterMetricItemWith4Dimensions() { this.counterMetricPointWith4Dimensions.TryGetExemplars(out var exemplars); - this.tlvMetricsExporter.SerializeMetricWithTLV( + this.tlvMetricsExporter!.SerializeMetricWithTLV( MetricEventType.ULongMetric, - this.counterMetricWith4Dimensions.Name, + this.counterMetricWith4Dimensions!.Name, this.counterMetricPointWith4Dimensions.EndTime.ToFileTime(), this.counterMetricPointWith4Dimensions.Tags, this.counterMetricDataWith4Dimensions, @@ -604,21 +604,21 @@ public void SerializeCounterMetricItemWith4Dimensions() [Benchmark] public void ExportCounterMetricItemWith3Dimensions() { - this.tlvMetricsExporter.Export(this.counterMetricBatchWith3Dimensions); + this.tlvMetricsExporter!.Export(this.counterMetricBatchWith3Dimensions); } [Benchmark] public void ExportCounterMetricItemWith4Dimensions() { - this.tlvMetricsExporter.Export(this.counterMetricBatchWith4Dimensions); + this.tlvMetricsExporter!.Export(this.counterMetricBatchWith4Dimensions); } [Benchmark] public void SerializeHistogramMetricItemWith3Dimensions() { this.histogramMetricPointWith3Dimensions.TryGetExemplars(out var exemplars); - this.tlvMetricsExporter.SerializeHistogramMetricWithTLV( - this.histogramMetricWith3Dimensions.Name, + this.tlvMetricsExporter!.SerializeHistogramMetricWithTLV( + this.histogramMetricWith3Dimensions!.Name, this.histogramMetricPointWith3Dimensions.EndTime.ToFileTime(), this.histogramMetricPointWith3Dimensions.Tags, this.histogramMetricPointWith3Dimensions.GetHistogramBuckets(), @@ -636,8 +636,8 @@ public void SerializeHistogramMetricItemWith3Dimensions() public void SerializeHistogramMetricItemWith4Dimensions() { this.histogramMetricPointWith4Dimensions.TryGetExemplars(out var exemplars); - this.tlvMetricsExporter.SerializeHistogramMetricWithTLV( - this.histogramMetricWith4Dimensions.Name, + this.tlvMetricsExporter!.SerializeHistogramMetricWithTLV( + this.histogramMetricWith4Dimensions!.Name, this.histogramMetricPointWith4Dimensions.EndTime.ToFileTime(), this.histogramMetricPointWith4Dimensions.Tags, this.histogramMetricPointWith4Dimensions.GetHistogramBuckets(), @@ -654,61 +654,61 @@ public void SerializeHistogramMetricItemWith4Dimensions() [Benchmark] public void ExportHistogramMetricItemWith3Dimensions() { - this.tlvMetricsExporter.Export(this.histogramMetricBatchWith3Dimensions); + this.tlvMetricsExporter!.Export(this.histogramMetricBatchWith3Dimensions); } [Benchmark] public void ExportHistogramMetricItemWith4Dimensions() { - this.tlvMetricsExporter.Export(this.histogramMetricBatchWith4Dimensions); + this.tlvMetricsExporter!.Export(this.histogramMetricBatchWith4Dimensions); } [Benchmark] public void SerializeCounterMetricItemWith3Dimensions_Otlp() { - this.otlpProtobufSerializer.SerializeAndSendMetrics(this.buffer, this.resource, this.counterMetricBatchWith3Dimensions); + this.otlpProtobufSerializer!.SerializeAndSendMetrics(this.buffer!, this.resource!, this.counterMetricBatchWith3Dimensions); } [Benchmark] public void SerializeCounterMetricItemWith4Dimensions_Otlp() { - this.otlpProtobufSerializer.SerializeAndSendMetrics(this.buffer, this.resource, this.counterMetricBatchWith4Dimensions); + this.otlpProtobufSerializer!.SerializeAndSendMetrics(this.buffer!, this.resource!, this.counterMetricBatchWith4Dimensions); } [Benchmark] public void ExportCounterMetricItemWith3Dimensions_Otlp() { - this.otlpProtobufMetricExporter.Export(this.counterMetricBatchWith3Dimensions); + this.otlpProtobufMetricExporter!.Export(this.counterMetricBatchWith3Dimensions); } [Benchmark] public void ExportCounterMetricItemWith4Dimensions_Otlp() { - this.otlpProtobufMetricExporter.Export(this.counterMetricBatchWith4Dimensions); + this.otlpProtobufMetricExporter!.Export(this.counterMetricBatchWith4Dimensions); } [Benchmark] public void SerializeHistogramMetricItemWith3Dimensions_Otlp() { - this.otlpProtobufSerializer.SerializeAndSendMetrics(this.buffer, this.resource, this.histogramMetricBatchWith3Dimensions); + this.otlpProtobufSerializer!.SerializeAndSendMetrics(this.buffer!, this.resource!, this.histogramMetricBatchWith3Dimensions); } [Benchmark] public void SerializeHistogramMetricItemWith4Dimensions_Otlp() { - this.otlpProtobufSerializer.SerializeAndSendMetrics(this.buffer, this.resource, this.histogramMetricBatchWith4Dimensions); + this.otlpProtobufSerializer!.SerializeAndSendMetrics(this.buffer!, this.resource!, this.histogramMetricBatchWith4Dimensions); } [Benchmark] public void ExportHistogramMetricItemWith3Dimensions_Otlp() { - this.otlpProtobufMetricExporter.Export(this.histogramMetricBatchWith3Dimensions); + this.otlpProtobufMetricExporter!.Export(this.histogramMetricBatchWith3Dimensions); } [Benchmark] public void ExportHistogramMetricItemWith4Dimensions_Otlp() { - this.otlpProtobufMetricExporter.Export(this.histogramMetricBatchWith4Dimensions); + this.otlpProtobufMetricExporter!.Export(this.histogramMetricBatchWith4Dimensions); } private class DummyReader : BaseExportingMetricReader diff --git a/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TLDTraceExporterBenchmarks.cs b/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TLDTraceExporterBenchmarks.cs index 2175a2a250..479026a277 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TLDTraceExporterBenchmarks.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TLDTraceExporterBenchmarks.cs @@ -28,7 +28,7 @@ namespace OpenTelemetry.Exporter.Geneva.Benchmarks; [MemoryDiagnoser] public class TLDTraceExporterBenchmarks { - private readonly Activity activity; + private readonly Activity? activity; private readonly Batch batch; private readonly MsgPackTraceExporter msgPackExporter; private readonly TldTraceExporter tldExporter; @@ -52,10 +52,10 @@ public TLDTraceExporterBenchmarks() using (var testActivity = this.activitySource.StartActivity("Benchmark")) { - this.activity = testActivity; - this.activity?.SetTag("tagString", "value"); - this.activity?.SetTag("tagInt", 100); - this.activity?.SetStatus(Status.Error); + this.activity = testActivity!; + this.activity.SetTag("tagString", "value"); + this.activity.SetTag("tagInt", 100); + this.activity.SetStatus(Status.Error); } this.msgPackExporter = new MsgPackTraceExporter(new GenevaExporterOptions @@ -84,13 +84,13 @@ public TLDTraceExporterBenchmarks() [Benchmark] public void MsgPack_SerializeActivity() { - this.msgPackExporter.SerializeActivity(this.activity); + this.msgPackExporter.SerializeActivity(this.activity!); } [Benchmark] public void TLD_SerializeActivity() { - this.tldExporter.SerializeActivity(this.activity); + this.tldExporter.SerializeActivity(this.activity!); } [Benchmark] @@ -108,7 +108,7 @@ public void TLD_ExportActivity() [GlobalCleanup] public void Cleanup() { - this.activity.Dispose(); + this.activity?.Dispose(); this.batch.Dispose(); this.activitySource.Dispose(); this.msgPackExporter.Dispose(); @@ -124,7 +124,7 @@ private Batch CreateBatch() .AddProcessor(new SimpleActivityExportProcessor(batchGeneratorExporter)) .Build(); - using (var activity = this.activitySource.StartActivity("Benchmark")) + using (var activity = this.activitySource.StartActivity("Benchmark")!) { activity.SetTag("tagString", "value"); activity.SetTag("tagInt", 100); diff --git a/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TraceExporterBenchmarks.cs b/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TraceExporterBenchmarks.cs index 223cbd111c..cfec940e3f 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TraceExporterBenchmarks.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TraceExporterBenchmarks.cs @@ -51,7 +51,7 @@ public TraceExporterBenchmarks() using (var testActivity = this.activitySource.StartActivity("Benchmark")) { - this.activity = testActivity; + this.activity = testActivity!; this.activity.SetTag("tagString", "value"); this.activity.SetTag("tagInt", 100); this.activity.SetStatus(Status.Error); @@ -125,7 +125,7 @@ private Batch CreateBatch() .AddProcessor(new SimpleActivityExportProcessor(batchGeneratorExporter)) .Build(); - using (var activity = this.activitySource.StartActivity("Benchmark")) + using (var activity = this.activitySource.StartActivity("Benchmark")!) { activity.SetTag("tagString", "value"); activity.SetTag("tagInt", 100); diff --git a/test/OpenTelemetry.Exporter.Geneva.Benchmarks/OpenTelemetry.Exporter.Geneva.Benchmarks.csproj b/test/OpenTelemetry.Exporter.Geneva.Benchmarks/OpenTelemetry.Exporter.Geneva.Benchmarks.csproj index 6a758c273f..3a6871c3b7 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Benchmarks/OpenTelemetry.Exporter.Geneva.Benchmarks.csproj +++ b/test/OpenTelemetry.Exporter.Geneva.Benchmarks/OpenTelemetry.Exporter.Geneva.Benchmarks.csproj @@ -8,7 +8,6 @@ $(TargetFrameworks);net48;net472;net471;net47;net462 Exe $(NoWarn);SA1201;SA1202;SA1204;SA1311;SA1123 - disable diff --git a/test/OpenTelemetry.Exporter.Geneva.Stress/DummyServer.cs b/test/OpenTelemetry.Exporter.Geneva.Stress/DummyServer.cs index 675b26b9b1..c6cdb17609 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Stress/DummyServer.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Stress/DummyServer.cs @@ -33,7 +33,7 @@ public void Start() this.serverSocket.Bind(this.endpoint); this.serverSocket.Listen(20); - Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs args) => + Console.CancelKeyPress += (object? sender, ConsoleCancelEventArgs args) => { Console.WriteLine("Program is terminating."); this.serverSocket.Close(); diff --git a/test/OpenTelemetry.Exporter.Geneva.Stress/OpenTelemetry.Exporter.Geneva.Stress.csproj b/test/OpenTelemetry.Exporter.Geneva.Stress/OpenTelemetry.Exporter.Geneva.Stress.csproj index e307744bc8..435acd8b5d 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Stress/OpenTelemetry.Exporter.Geneva.Stress.csproj +++ b/test/OpenTelemetry.Exporter.Geneva.Stress/OpenTelemetry.Exporter.Geneva.Stress.csproj @@ -6,7 +6,6 @@ $(TargetFrameworks);net48;net472;net471;net47;net462 Exe $(NoWarn);SA1308;SA1201 - disable diff --git a/test/OpenTelemetry.Exporter.Geneva.Stress/Program.cs b/test/OpenTelemetry.Exporter.Geneva.Stress/Program.cs index 1a6c97297d..71877c8c94 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Stress/Program.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Stress/Program.cs @@ -39,14 +39,14 @@ private class WindowsOptions private class LinuxOptions { [Option('p', "path", Default = "/var/run/default_fluent.socket", HelpText = "Specify a path for Unix domain socket.")] - public string Path { get; set; } + public string? Path { get; set; } } [Verb("server", HelpText = "Start a dummy server on Linux.")] private class ServerOptions { [Option('p', "path", HelpText = "Specify a path for Unix domain socket.", Required = true)] - public string Path { get; set; } + public string? Path { get; set; } } [Verb("ExporterCreation", HelpText = "Validate exporter dispose behavior")] @@ -78,12 +78,12 @@ private static int RunExporterCreation() private static int RunLinux(LinuxOptions options) { - return EntryPoint(() => InitTracesOnLinux(options.Path), RunTraces); + return EntryPoint(() => InitTracesOnLinux(options.Path!), RunTraces); } private static int RunServer(ServerOptions options) { - var server = new DummyServer(options.Path); + var server = new DummyServer(options.Path!); server.Start(); return 0; } diff --git a/test/OpenTelemetry.PersistentStorage.FileSystem.Tests/FileBlobTests.cs b/test/OpenTelemetry.PersistentStorage.FileSystem.Tests/FileBlobTests.cs index cde187fcc3..706dae983f 100644 --- a/test/OpenTelemetry.PersistentStorage.FileSystem.Tests/FileBlobTests.cs +++ b/test/OpenTelemetry.PersistentStorage.FileSystem.Tests/FileBlobTests.cs @@ -172,6 +172,6 @@ public void FileBlobTests_FailedWrite() var nonExistingPath = Path.Combine("FakePath:/", Path.GetRandomFileName()); FileBlob blob = new FileBlob(nonExistingPath); - Assert.False(blob.TryWrite(Array.Empty())); + Assert.False(blob.TryWrite([])); } } diff --git a/test/OpenTelemetry.Resources.AWS.Tests/AsyncHelperTests.cs b/test/OpenTelemetry.Resources.AWS.Tests/AsyncHelperTests.cs index 1bf9aafd6b..fe0efe2a81 100644 --- a/test/OpenTelemetry.Resources.AWS.Tests/AsyncHelperTests.cs +++ b/test/OpenTelemetry.Resources.AWS.Tests/AsyncHelperTests.cs @@ -11,13 +11,13 @@ public class AsyncHelperTests public void RunSyncTaskCompletesSuccessfully() { // Arrange - Func task = async () => + static async Task Task() { - await Task.Delay(100); - }; + await System.Threading.Tasks.Task.Delay(100); + } // Act - var exception = Record.Exception(() => AsyncHelper.RunSync(task)); + var exception = Record.Exception(() => AsyncHelper.RunSync(Task)); // Assert Assert.Null(exception); @@ -27,14 +27,14 @@ public void RunSyncTaskCompletesSuccessfully() public void RunSyncTaskThrowsException() { // Arrange - Func task = async () => + static async Task Task() { - await Task.Delay(100); + await System.Threading.Tasks.Task.Delay(100); throw new InvalidOperationException("Test exception"); - }; + } // Act & Assert - var exception = Assert.Throws(() => AsyncHelper.RunSync(task)); + var exception = Assert.Throws(() => AsyncHelper.RunSync(Task)); Assert.Equal("Test exception", exception.Message); } @@ -45,13 +45,13 @@ public void RunSyncTaskCancellationThrowsTaskCanceledException() var cts = new CancellationTokenSource(); cts.Cancel(); - Func task = async () => + async Task Task() { - await Task.Delay(100, cts.Token); - }; + await System.Threading.Tasks.Task.Delay(100, cts.Token); + } // Act & Assert - var exception = Assert.Throws(() => AsyncHelper.RunSync(task)); + var exception = Assert.Throws(() => AsyncHelper.RunSync(Task)); Assert.Equal(cts.Token, exception.CancellationToken); } @@ -59,14 +59,14 @@ public void RunSyncTaskCancellationThrowsTaskCanceledException() public void RunSyncTaskWithResultCompletesSuccessfully() { // Arrange - Func> task = async () => + static async Task Task() { - await Task.Delay(100); + await System.Threading.Tasks.Task.Delay(100); return "Completed"; - }; + } // Act - var result = AsyncHelper.RunSync(task); + var result = AsyncHelper.RunSync(Task); // Assert Assert.Equal("Completed", result); @@ -76,14 +76,14 @@ public void RunSyncTaskWithResultCompletesSuccessfully() public void RunSyncTaskWithResultThrowsException() { // Arrange - Func> task = async () => + static async Task Task() { - await Task.Delay(100); + await System.Threading.Tasks.Task.Delay(100); throw new InvalidOperationException("Test exception"); - }; + } // Act & Assert - var exception = Assert.Throws(() => AsyncHelper.RunSync(task)); + var exception = Assert.Throws(() => AsyncHelper.RunSync(Task)); Assert.Equal("Test exception", exception.Message); } @@ -94,14 +94,14 @@ public void RunSyncTaskWithResultCancellationThrowsTaskCanceledException() var cts = new CancellationTokenSource(); cts.Cancel(); - Func> task = async () => + async Task Task() { - await Task.Delay(100, cts.Token); + await System.Threading.Tasks.Task.Delay(100, cts.Token); return "Completed"; - }; + } // Act & Assert - var exception = Assert.Throws(() => AsyncHelper.RunSync(task)); + var exception = Assert.Throws(() => AsyncHelper.RunSync(Task)); Assert.Equal(cts.Token, exception.CancellationToken); } } diff --git a/test/OpenTelemetry.Resources.Container.Tests/ContainerDetectorTests.cs b/test/OpenTelemetry.Resources.Container.Tests/ContainerDetectorTests.cs index 1174a24e81..47b43b329b 100644 --- a/test/OpenTelemetry.Resources.Container.Tests/ContainerDetectorTests.cs +++ b/test/OpenTelemetry.Resources.Container.Tests/ContainerDetectorTests.cs @@ -7,75 +7,87 @@ namespace OpenTelemetry.Resources.Container.Tests; public class ContainerDetectorTests { - private readonly List testValidCasesV1 = new() - { + private readonly List testValidCasesV1 = + [ new( name: "cgroupv1 with prefix", line: "13:name=systemd:/podruntime/docker/kubepods/crio-e2cc29debdf85dde404998aa128997a819ff", expectedContainerId: "e2cc29debdf85dde404998aa128997a819ff", cgroupVersion: ContainerDetector.ParseMode.V1), + new( name: "cgroupv1 with suffix", line: "13:name=systemd:/podruntime/docker/kubepods/ac679f8a8319c8cf7d38e1adf263bc08d23.aaaa", expectedContainerId: "ac679f8a8319c8cf7d38e1adf263bc08d23", cgroupVersion: ContainerDetector.ParseMode.V1), + new( name: "cgroupv1 with prefix and suffix", line: "13:name=systemd:/podruntime/docker/kubepods/crio-dc679f8a8319c8cf7d38e1adf263bc08d23.stuff", expectedContainerId: "dc679f8a8319c8cf7d38e1adf263bc08d23", cgroupVersion: ContainerDetector.ParseMode.V1), + new( name: "cgroupv1 with container Id", line: "13:name=systemd:/pod/d86d75589bf6cc254f3e2cc29debdf85dde404998aa128997a819ff991827356", expectedContainerId: "d86d75589bf6cc254f3e2cc29debdf85dde404998aa128997a819ff991827356", - cgroupVersion: ContainerDetector.ParseMode.V1), - }; + cgroupVersion: ContainerDetector.ParseMode.V1) - private readonly List testValidCasesV2 = new() - { + ]; + + private readonly List testValidCasesV2 = + [ new( name: "cgroupv2 with container Id", line: "13:name=systemd:/pod/d86d75589bf6cc254f3e2cc29debdf85dde404998aa128997a819ff991827356/hostname", expectedContainerId: "d86d75589bf6cc254f3e2cc29debdf85dde404998aa128997a819ff991827356", cgroupVersion: ContainerDetector.ParseMode.V2), + new( name: "cgroupv2 with full line", line: "473 456 254:1 /docker/containers/dc64b5743252dbaef6e30521c34d6bbd1620c8ce65bdb7bf9e7143b61bb5b183/hostname /etc/hostname rw,relatime - ext4 /dev/vda1 rw", expectedContainerId: "dc64b5743252dbaef6e30521c34d6bbd1620c8ce65bdb7bf9e7143b61bb5b183", cgroupVersion: ContainerDetector.ParseMode.V2), + new( name: "cgroupv2 with minikube containerd mountinfo", line: "1537 1517 8:1 /var/lib/containerd/io.containerd.grpc.v1.cri/sandboxes/fb5916a02feca96bdeecd8e062df9e5e51d6617c8214b5e1f3ff9320f4402ae6/hostname /etc/hostname rw,relatime - ext4 /dev/sda1 rw", expectedContainerId: "fb5916a02feca96bdeecd8e062df9e5e51d6617c8214b5e1f3ff9320f4402ae6", cgroupVersion: ContainerDetector.ParseMode.V2), + new( name: "cgroupv2 with minikube docker mountinfo", line: "2327 2307 8:1 /var/lib/docker/containers/a1551a1d7e1881d6c18d2c9ec462cab6ad3666825f0adb2098e9d5b198fd7e19/hostname /etc/hostname rw,relatime - ext4 /dev/sda1 rw", expectedContainerId: "a1551a1d7e1881d6c18d2c9ec462cab6ad3666825f0adb2098e9d5b198fd7e19", cgroupVersion: ContainerDetector.ParseMode.V2), + new( name: "cgroupv2 with minikube docker mountinfo2", line: "929 920 254:1 /docker/volumes/minikube/_data/lib/docker/containers/0eaa6718003210b6520f7e82d14b4c8d4743057a958a503626240f8d1900bc33/hostname /etc/hostname rw,relatime - ext4 /dev/vda1 rw", expectedContainerId: "0eaa6718003210b6520f7e82d14b4c8d4743057a958a503626240f8d1900bc33", cgroupVersion: ContainerDetector.ParseMode.V2), + new( name: "cgroupv2 with podman mountinfo", line: "1096 1088 0:104 /containers/overlay-containers/1a2de27e7157106568f7e081e42a8c14858c02bd9df30d6e352b298178b46809/userdata/hostname /etc/hostname rw,nosuid,nodev,relatime - tmpfs tmpfs rw,size=813800k,nr_inodes=203450,mode=700,uid=1000,gid=1000", expectedContainerId: "1a2de27e7157106568f7e081e42a8c14858c02bd9df30d6e352b298178b46809", - cgroupVersion: ContainerDetector.ParseMode.V2), - }; + cgroupVersion: ContainerDetector.ParseMode.V2) - private readonly List testInvalidCases = new() - { + ]; + + private readonly List testInvalidCases = + [ new( name: "Invalid cgroupv1 line", line: "13:name=systemd:/podruntime/docker/kubepods/ac679f8a8319c8cf7d38e1adf263bc08d23zzzz", cgroupVersion: ContainerDetector.ParseMode.V1), + new( name: "Invalid hex cgroupv2 line (contains a z)", line: "13:name=systemd:/var/lib/containerd/io.containerd.grpc.v1.cri/sandboxes/fb5916a02feca96bdeecd8e062df9e5e51d6617c8214b5e1f3fz9320f4402ae6/hostname", - cgroupVersion: ContainerDetector.ParseMode.V2), - }; + cgroupVersion: ContainerDetector.ParseMode.V2) + + ]; [Fact] public void TestValidContainer() diff --git a/test/OpenTelemetry.Resources.Host.Tests/HostDetectorTests.cs b/test/OpenTelemetry.Resources.Host.Tests/HostDetectorTests.cs index baf15769ff..d6c9ea9add 100644 --- a/test/OpenTelemetry.Resources.Host.Tests/HostDetectorTests.cs +++ b/test/OpenTelemetry.Resources.Host.Tests/HostDetectorTests.cs @@ -40,8 +40,8 @@ public class HostDetectorTests }"; #if NET - private static readonly IEnumerable ETCMACHINEID = new[] { "Samples/etc_machineid" }; - private static readonly IEnumerable ETCVARDBUSMACHINEID = new[] { "Samples/etc_var_dbus_machineid" }; + private static readonly IEnumerable ETCMACHINEID = ["Samples/etc_machineid"]; + private static readonly IEnumerable ETCVARDBUSMACHINEID = ["Samples/etc_var_dbus_machineid"]; #endif [Fact] @@ -63,7 +63,7 @@ public void TestHostMachineIdLinux() { var combos = new[] { - (Enumerable.Empty(), null), + ([], null), (ETCMACHINEID, "etc_machineid"), (ETCVARDBUSMACHINEID, "etc_var_dbus_machineid"), (Enumerable.Concat(ETCMACHINEID, ETCVARDBUSMACHINEID), "etc_machineid"), @@ -95,7 +95,7 @@ public void TestHostMachineIdMacOs() { var detector = new HostDetector( osPlatform => osPlatform == OSPlatform.OSX, - () => Enumerable.Empty(), + () => [], () => MacOSMachineIdOutput, () => throw new Exception("should not be called")); var resource = ResourceBuilder.CreateEmpty().AddDetector(detector).Build(); @@ -116,9 +116,9 @@ public void TestParseMacOsOutput() public void TestHostMachineIdWindows() { #if NET - var detector = new HostDetector(osPlatform => osPlatform == OSPlatform.Windows, () => Enumerable.Empty(), () => throw new Exception("should not be called"), () => "windows-machine-id"); + var detector = new HostDetector(osPlatform => osPlatform == OSPlatform.Windows, () => [], () => throw new Exception("should not be called"), () => "windows-machine-id"); #else - var detector = new HostDetector(() => Enumerable.Empty(), () => throw new Exception("should not be called"), () => "windows-machine-id"); + var detector = new HostDetector(() => [], () => throw new Exception("should not be called"), () => "windows-machine-id"); #endif var resource = ResourceBuilder.CreateEmpty().AddDetector(detector).Build(); @@ -131,14 +131,14 @@ public void TestHostMachineIdWindows() [Fact] public void TestPlatformSpecificMethodInvocation() { - bool linuxMethodCalled = false; - bool macOsMethodCalled = false; - bool windowsMethodCalled = false; + var linuxMethodCalled = false; + var macOsMethodCalled = false; + var windowsMethodCalled = false; var detector = new HostDetector( () => { linuxMethodCalled = true; - return Array.Empty(); + return []; }, () => {