From 1b3dd94a83c03ab981cdecea2b8f68497526c700 Mon Sep 17 00:00:00 2001 From: Mikel Blanchard Date: Mon, 10 Jun 2024 17:17:23 -0700 Subject: [PATCH 1/6] [onecollector] Add LoggerProviderBuilder registration extension (#1876) --- .../.publicApi/PublicAPI.Unshipped.txt | 8 + .../CHANGELOG.md | 6 + .../LogRecordCommonSchemaJsonSerializer.cs | 7 + .../OneCollectorLogExportProcessorBuilder.cs | 162 +++++++---- ...ollectorLoggerProviderBuilderExtensions.cs | 174 ++++++++++++ ...torOpenTelemetryLoggerOptionsExtensions.cs | 7 +- .../OneCollectorExporterTransportOptions.cs | 22 ++ ...OpenTelemetry.Exporter.OneCollector.csproj | 7 +- ...ecordCommonSchemaJsonHttpPostBenchmarks.cs | 3 + ...ogRecordCommonSchemaJsonSerializerTests.cs | 3 + ...torLoggerProviderBuilderExtensionsTests.cs | 265 ++++++++++++++++++ 11 files changed, 597 insertions(+), 67 deletions(-) create mode 100644 src/OpenTelemetry.Exporter.OneCollector/Logs/OneCollectorLoggerProviderBuilderExtensions.cs create mode 100644 test/OpenTelemetry.Exporter.OneCollector.Tests/OneCollectorLoggerProviderBuilderExtensionsTests.cs diff --git a/src/OpenTelemetry.Exporter.OneCollector/.publicApi/PublicAPI.Unshipped.txt b/src/OpenTelemetry.Exporter.OneCollector/.publicApi/PublicAPI.Unshipped.txt index e69de29bb2..9700b06ef0 100644 --- a/src/OpenTelemetry.Exporter.OneCollector/.publicApi/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry.Exporter.OneCollector/.publicApi/PublicAPI.Unshipped.txt @@ -0,0 +1,8 @@ +OpenTelemetry.Logs.OneCollectorLoggerProviderBuilderExtensions +static OpenTelemetry.Logs.OneCollectorLoggerProviderBuilderExtensions.AddOneCollectorExporter(this OpenTelemetry.Logs.LoggerProviderBuilder! builder) -> OpenTelemetry.Logs.LoggerProviderBuilder! +static OpenTelemetry.Logs.OneCollectorLoggerProviderBuilderExtensions.AddOneCollectorExporter(this OpenTelemetry.Logs.LoggerProviderBuilder! builder, Microsoft.Extensions.Configuration.IConfiguration! configuration) -> OpenTelemetry.Logs.LoggerProviderBuilder! +static OpenTelemetry.Logs.OneCollectorLoggerProviderBuilderExtensions.AddOneCollectorExporter(this OpenTelemetry.Logs.LoggerProviderBuilder! builder, Microsoft.Extensions.Configuration.IConfiguration! configuration, System.Action! configure) -> OpenTelemetry.Logs.LoggerProviderBuilder! +static OpenTelemetry.Logs.OneCollectorLoggerProviderBuilderExtensions.AddOneCollectorExporter(this OpenTelemetry.Logs.LoggerProviderBuilder! builder, string! connectionString) -> OpenTelemetry.Logs.LoggerProviderBuilder! +static OpenTelemetry.Logs.OneCollectorLoggerProviderBuilderExtensions.AddOneCollectorExporter(this OpenTelemetry.Logs.LoggerProviderBuilder! builder, string! connectionString, System.Action! configure) -> OpenTelemetry.Logs.LoggerProviderBuilder! +static OpenTelemetry.Logs.OneCollectorLoggerProviderBuilderExtensions.AddOneCollectorExporter(this OpenTelemetry.Logs.LoggerProviderBuilder! builder, string? name, string? connectionString, Microsoft.Extensions.Configuration.IConfiguration? configuration, System.Action? configure) -> OpenTelemetry.Logs.LoggerProviderBuilder! +static OpenTelemetry.Logs.OneCollectorLoggerProviderBuilderExtensions.AddOneCollectorExporter(this OpenTelemetry.Logs.LoggerProviderBuilder! builder, System.Action! configure) -> OpenTelemetry.Logs.LoggerProviderBuilder! diff --git a/src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md b/src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md index 6781b8e445..a0f00e0852 100644 --- a/src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md +++ b/src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +* Update OpenTelemetry SDK version to `1.9.0-rc.1`. + ([#1876](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1876)) + +* Added `LoggerProviderBuilder.AddOneCollectorExporter` registration extension. + ([#1876](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1876)) + ## 1.8.0 Released 2024-Apr-22 diff --git a/src/OpenTelemetry.Exporter.OneCollector/Internal/Serialization/LogRecordCommonSchemaJsonSerializer.cs b/src/OpenTelemetry.Exporter.OneCollector/Internal/Serialization/LogRecordCommonSchemaJsonSerializer.cs index 6edcaba58b..33ac460af9 100644 --- a/src/OpenTelemetry.Exporter.OneCollector/Internal/Serialization/LogRecordCommonSchemaJsonSerializer.cs +++ b/src/OpenTelemetry.Exporter.OneCollector/Internal/Serialization/LogRecordCommonSchemaJsonSerializer.cs @@ -114,7 +114,14 @@ protected override void SerializeItemToJson(Resource resource, LogRecord item, C writer.WriteNumber(EventIdProperty, item.EventId.Id); } +#if EXPOSE_EXPERIMENTAL_FEATURES +#pragma warning disable CS0618 // Type or member is obsolete + // TODO: Update to use LogRecord.Severity var logLevel = (int)item.LogLevel; +#pragma warning restore CS0618 // Type or member is obsolete +#else + var logLevel = (int)item.LogLevel; +#endif writer.WriteString(SeverityTextProperty, LogLevelToSeverityTextMappings[logLevel]); writer.WriteNumber(SeverityNumberProperty, LogLevelToSeverityNumberMappings[logLevel]); diff --git a/src/OpenTelemetry.Exporter.OneCollector/Logs/OneCollectorLogExportProcessorBuilder.cs b/src/OpenTelemetry.Exporter.OneCollector/Logs/OneCollectorLogExportProcessorBuilder.cs index 659a56e5c7..3e61545d34 100644 --- a/src/OpenTelemetry.Exporter.OneCollector/Logs/OneCollectorLogExportProcessorBuilder.cs +++ b/src/OpenTelemetry.Exporter.OneCollector/Logs/OneCollectorLogExportProcessorBuilder.cs @@ -1,10 +1,10 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#if NETFRAMEWORK -using System.Net.Http; -#endif +using System.Diagnostics; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using OpenTelemetry.Exporter.OneCollector; using OpenTelemetry.Internal; @@ -17,19 +17,34 @@ namespace OpenTelemetry.Logs; /// public sealed class OneCollectorLogExportProcessorBuilder { - private static readonly Func DefaultHttpClientFactory = () => new HttpClient(); - private readonly OneCollectorLogExporterOptions exporterOptions = new(); - private readonly BatchExportProcessorOptions batchOptions = new(); - private readonly List>> configureExporterActions = new(); - private Func? httpClientFactory; + private readonly string? name; + private readonly IServiceCollection services; + private readonly bool ownsServices; internal OneCollectorLogExportProcessorBuilder( + string? name, + IServiceCollection? services, IConfiguration? configuration) { + this.name = name; + + if (services == null) + { + this.services = new ServiceCollection(); + this.services.AddOptions(); + this.ownsServices = true; + } + else + { + this.services = services; + } + if (configuration != null) { - configuration.Bind(this.exporterOptions); - configuration.GetSection("BatchOptions").Bind(this.batchOptions); + this.services.Configure(this.name, configuration); + this.services.Configure( + this.name, + batchOptions => configuration.GetSection("BatchOptions").Bind(batchOptions)); } } @@ -47,7 +62,9 @@ public OneCollectorLogExportProcessorBuilder ConfigureBatchOptions( { Guard.ThrowIfNull(configure); - configure(this.batchOptions); + this.services.Configure( + this.name, + batchOptions => configure(batchOptions)); return this; } @@ -66,7 +83,10 @@ public OneCollectorLogExportProcessorBuilder ConfigureExporter( { Guard.ThrowIfNull(configure); - this.configureExporterActions.Add(configure); + this.services.AddSingleton( + new ConfigureOneCollectorExporter( + this.name, + (sp, e) => configure(e))); return this; } @@ -86,7 +106,9 @@ public OneCollectorLogExportProcessorBuilder ConfigureSerializationOptions( { Guard.ThrowIfNull(configure); - configure(this.exporterOptions.SerializationOptions); + this.services.Configure( + this.name, + exporterOptions => configure(exporterOptions.SerializationOptions)); return this; } @@ -105,7 +127,9 @@ public OneCollectorLogExportProcessorBuilder ConfigureTransportOptions( { Guard.ThrowIfNull(configure); - configure(this.exporterOptions.TransportOptions); + this.services.Configure( + this.name, + exporterOptions => configure(exporterOptions.TransportOptions)); return this; } @@ -126,7 +150,9 @@ public OneCollectorLogExportProcessorBuilder SetConnectionString( { Guard.ThrowIfNullOrWhitespace(connectionString); - this.exporterOptions.ConnectionString = connectionString; + this.services.Configure( + this.name, + exporterOptions => exporterOptions.ConnectionString = connectionString); return this; } @@ -148,61 +174,62 @@ public OneCollectorLogExportProcessorBuilder SetDefaultEventName( { Guard.ThrowIfNullOrWhitespace(defaultEventName); - this.exporterOptions.DefaultEventName = defaultEventName; + this.services.Configure( + this.name, + exporterOptions => exporterOptions.DefaultEventName = defaultEventName); return this; } - /// - /// Sets the factory function called to create the - /// instance that will be used at runtime to transmit telemetry over HTTP - /// transports. The returned instance will be reused for all export - /// invocations. - /// - /// - /// Note: The default behavior is an will be - /// instantiated directly. - /// - /// Factory function which returns the instance to use. - /// The supplied for call - /// chaining. - internal OneCollectorLogExportProcessorBuilder SetHttpClientFactory( - Func httpClientFactory) + internal BaseProcessor BuildProcessor( + IServiceProvider serviceProvider) { - Guard.ThrowIfNull(httpClientFactory); + Debug.Assert(serviceProvider != null, "serviceProvider was null"); - this.httpClientFactory = httpClientFactory; + ServiceProvider? ownedServiceProvider = null; + if (this.ownsServices) + { + ownedServiceProvider = this.services.BuildServiceProvider(); + } - return this; - } + var exporterOptions = (ownedServiceProvider ?? serviceProvider!).GetRequiredService>().Get(this.name); + var batchOptions = (ownedServiceProvider ?? serviceProvider!).GetRequiredService>().Get(this.name); - internal BaseProcessor BuildProcessor() - { + try + { #pragma warning disable CA2000 // Dispose objects before losing scope - return new BatchLogRecordExportProcessor( - this.BuildExporter(), - this.batchOptions.MaxQueueSize, - this.batchOptions.ScheduledDelayMilliseconds, - this.batchOptions.ExporterTimeoutMilliseconds, - this.batchOptions.MaxExportBatchSize); + return new BatchLogRecordExportProcessor( + CreateExporter(this.name, serviceProvider!, exporterOptions, (ownedServiceProvider ?? serviceProvider!).GetServices()), + batchOptions.MaxQueueSize, + batchOptions.ScheduledDelayMilliseconds, + batchOptions.ExporterTimeoutMilliseconds, + batchOptions.MaxExportBatchSize); #pragma warning restore CA2000 // Dispose objects before losing scope + } + finally + { + ownedServiceProvider?.Dispose(); + } } - private OneCollectorExporter BuildExporter() + private static OneCollectorExporter CreateExporter( + string? name, + IServiceProvider serviceProvider, + OneCollectorLogExporterOptions exporterOptions, + IEnumerable configurations) { #pragma warning disable CA2000 // Dispose objects before losing scope - var exporter = new OneCollectorExporter(this.CreateSink()); + var exporter = new OneCollectorExporter(CreateSink(exporterOptions)); #pragma warning restore CA2000 // Dispose objects before losing scope try { - int index = 0; - while (index < this.configureExporterActions.Count) + foreach (var configuration in configurations) { - var action = this.configureExporterActions[index++]; - action(exporter); + if (name == configuration.Name) + { + configuration.Configure(serviceProvider, exporter); + } } } catch @@ -214,27 +241,40 @@ private OneCollectorExporter BuildExporter() return exporter; } - private WriteDirectlyToTransportSink CreateSink() + private static WriteDirectlyToTransportSink CreateSink(OneCollectorLogExporterOptions exporterOptions) { - this.exporterOptions.Validate(); - - var transportOptions = this.exporterOptions.TransportOptions; + exporterOptions.Validate(); - var httpClient = (this.httpClientFactory ?? DefaultHttpClientFactory)() ?? throw new NotSupportedException("HttpClientFactory cannot return a null instance."); + var transportOptions = exporterOptions.TransportOptions; #pragma warning disable CA2000 // Dispose objects before losing scope return new WriteDirectlyToTransportSink( new LogRecordCommonSchemaJsonSerializer( - new EventNameManager(this.exporterOptions.DefaultEventNamespace, this.exporterOptions.DefaultEventName), - this.exporterOptions.TenantToken!, - this.exporterOptions.SerializationOptions.ExceptionStackTraceHandling, + new EventNameManager(exporterOptions.DefaultEventNamespace, exporterOptions.DefaultEventName), + exporterOptions.TenantToken!, + exporterOptions.SerializationOptions.ExceptionStackTraceHandling, transportOptions.MaxPayloadSizeInBytes == -1 ? int.MaxValue : transportOptions.MaxPayloadSizeInBytes, transportOptions.MaxNumberOfItemsPerPayload == -1 ? int.MaxValue : transportOptions.MaxNumberOfItemsPerPayload), new HttpJsonPostTransport( - this.exporterOptions.InstrumentationKey!, + exporterOptions.InstrumentationKey!, transportOptions.Endpoint, transportOptions.HttpCompression, - new HttpClientWrapper(httpClient))); + new HttpClientWrapper(transportOptions.GetHttpClient()))); #pragma warning restore CA2000 // Dispose objects before losing scope } + + private sealed class ConfigureOneCollectorExporter + { + public ConfigureOneCollectorExporter( + string? name, + Action> configure) + { + this.Name = name; + this.Configure = configure; + } + + public string? Name { get; } + + public Action> Configure { get; } + } } diff --git a/src/OpenTelemetry.Exporter.OneCollector/Logs/OneCollectorLoggerProviderBuilderExtensions.cs b/src/OpenTelemetry.Exporter.OneCollector/Logs/OneCollectorLoggerProviderBuilderExtensions.cs new file mode 100644 index 0000000000..5ac3e607c5 --- /dev/null +++ b/src/OpenTelemetry.Exporter.OneCollector/Logs/OneCollectorLoggerProviderBuilderExtensions.cs @@ -0,0 +1,174 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +using Microsoft.Extensions.Configuration; +using OpenTelemetry.Exporter.OneCollector; +using OpenTelemetry.Internal; + +namespace OpenTelemetry.Logs; + +/// +/// Contains extension methods to register the OneCollector log exporter. +/// +public static class OneCollectorLoggerProviderBuilderExtensions +{ + /// + /// Add OneCollector exporter to the . + /// + /// . + /// The supplied for call + /// chaining. + public static LoggerProviderBuilder AddOneCollectorExporter( + this LoggerProviderBuilder builder) + { + return AddOneCollectorExporter(builder, name: null, connectionString: null, configuration: null, configure: null); + } + + /// + /// Add OneCollector exporter to the . + /// + /// . + /// Callback action for configuring . + /// The supplied for call + /// chaining. + public static LoggerProviderBuilder AddOneCollectorExporter( + this LoggerProviderBuilder builder, + Action configure) + { + Guard.ThrowIfNull(configure); + + return AddOneCollectorExporter(builder, name: null, connectionString: null, configuration: null, configure); + } + + /// + /// Add OneCollector exporter to the . + /// + /// . + /// OneCollector connection string. + /// The supplied for call + /// chaining. + public static LoggerProviderBuilder AddOneCollectorExporter( + this LoggerProviderBuilder builder, + string connectionString) + { + Guard.ThrowIfNullOrWhitespace(connectionString); + + return AddOneCollectorExporter(builder, name: null, connectionString, configuration: null, configure: null); + } + + /// + /// Add OneCollector exporter to the . + /// + /// . + /// OneCollector connection string. + /// Callback action for configuring . + /// The supplied for call + /// chaining. + public static LoggerProviderBuilder AddOneCollectorExporter( + this LoggerProviderBuilder builder, + string connectionString, + Action configure) + { + Guard.ThrowIfNullOrWhitespace(connectionString); + Guard.ThrowIfNull(configure); + + return AddOneCollectorExporter(builder, name: null, connectionString, configuration: null, configure); + } + + /// + /// Add OneCollector exporter to the . + /// + /// Note: Batch options () are bound to the "BatchOptions" + /// sub-section of the supplied in the + /// parameter. + /// . + /// Configuration used to build and . + /// The supplied for call + /// chaining. + public static LoggerProviderBuilder AddOneCollectorExporter( + this LoggerProviderBuilder builder, + IConfiguration configuration) + { + Guard.ThrowIfNull(configuration); + + return AddOneCollectorExporter(builder, name: null, connectionString: null, configuration, configure: null); + } + + /// + /// Add OneCollector exporter to the . + /// + /// + /// . + /// + /// Callback action for configuring . + /// The supplied for call + /// chaining. + public static LoggerProviderBuilder AddOneCollectorExporter( + this LoggerProviderBuilder builder, + IConfiguration configuration, + Action configure) + { + Guard.ThrowIfNull(configuration); + Guard.ThrowIfNull(configure); + + return AddOneCollectorExporter(builder, name: null, connectionString: null, configuration, configure); + } + + /// + /// Add OneCollector exporter to the . + /// + /// + /// . + /// Optional name which is used when retrieving + /// options. + /// Optional OneCollector connection + /// string. + /// Optional configuration used to build and . + /// Optional callback action for configuring . + /// The supplied for call + /// chaining. + public static LoggerProviderBuilder AddOneCollectorExporter( + this LoggerProviderBuilder builder, + string? name, + string? connectionString, + IConfiguration? configuration, + Action? configure) + { + Guard.ThrowIfNull(builder); + + return builder.ConfigureServices(services => + { + var processorBuilder = new OneCollectorLogExportProcessorBuilder(name, services, configuration); + + if (!string.IsNullOrWhiteSpace(connectionString)) + { + processorBuilder.SetConnectionString(connectionString!); + } + + configure?.Invoke(processorBuilder); + + builder.AddProcessor(processorBuilder.BuildProcessor); + }); + } +} diff --git a/src/OpenTelemetry.Exporter.OneCollector/Logs/OneCollectorOpenTelemetryLoggerOptionsExtensions.cs b/src/OpenTelemetry.Exporter.OneCollector/Logs/OneCollectorOpenTelemetryLoggerOptionsExtensions.cs index 1b4287def2..36169f0cc5 100644 --- a/src/OpenTelemetry.Exporter.OneCollector/Logs/OneCollectorOpenTelemetryLoggerOptionsExtensions.cs +++ b/src/OpenTelemetry.Exporter.OneCollector/Logs/OneCollectorOpenTelemetryLoggerOptionsExtensions.cs @@ -123,7 +123,7 @@ private static OpenTelemetryLoggerOptions AddOneCollectorExporter( { Guard.ThrowIfNull(options); - var builder = new OneCollectorLogExportProcessorBuilder(configuration); + var builder = new OneCollectorLogExportProcessorBuilder(name: null, services: null, configuration); if (!string.IsNullOrWhiteSpace(connectionString)) { @@ -132,10 +132,7 @@ private static OpenTelemetryLoggerOptions AddOneCollectorExporter( configure?.Invoke(builder); -#pragma warning disable CA2000 // Dispose objects before losing scope - options.AddProcessor( - builder.BuildProcessor()); -#pragma warning restore CA2000 // Dispose objects before losing scope + options.AddProcessor(builder.BuildProcessor); return options; } diff --git a/src/OpenTelemetry.Exporter.OneCollector/OneCollectorExporterTransportOptions.cs b/src/OpenTelemetry.Exporter.OneCollector/OneCollectorExporterTransportOptions.cs index 6f818948a5..28a14abb53 100644 --- a/src/OpenTelemetry.Exporter.OneCollector/OneCollectorExporterTransportOptions.cs +++ b/src/OpenTelemetry.Exporter.OneCollector/OneCollectorExporterTransportOptions.cs @@ -2,6 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 using System.ComponentModel.DataAnnotations; +#if NETFRAMEWORK +using System.Net.Http; +#endif namespace OpenTelemetry.Exporter.OneCollector; @@ -14,6 +17,8 @@ public sealed class OneCollectorExporterTransportOptions internal const int DefaultMaxPayloadSizeInBytes = 1024 * 1024 * 4; internal const int DefaultMaxNumberOfItemsPerPayload = 1500; + private static readonly Func DefaultHttpClientFactory = () => new HttpClient(); + internal OneCollectorExporterTransportOptions() { } @@ -59,6 +64,23 @@ internal OneCollectorExporterTransportOptions() /// internal OneCollectorExporterHttpTransportCompressionType HttpCompression { get; set; } = OneCollectorExporterHttpTransportCompressionType.Deflate; + /// + /// Gets or sets the factory function called to create the instance that will be used at runtime to transmit + /// telemetry over HTTP transports. The returned instance will be reused for + /// all export invocations. + /// + /// + /// Note: The default behavior is an will be + /// instantiated directly. + /// + internal Func? HttpClientFactory { get; set; } + + internal HttpClient GetHttpClient() + { + return (this.HttpClientFactory ?? DefaultHttpClientFactory)() ?? throw new NotSupportedException("HttpClientFactory cannot return a null instance."); + } + internal void Validate() { if (this.Endpoint == null) diff --git a/src/OpenTelemetry.Exporter.OneCollector/OpenTelemetry.Exporter.OneCollector.csproj b/src/OpenTelemetry.Exporter.OneCollector/OpenTelemetry.Exporter.OneCollector.csproj index 8aceaff990..3a3a2cffb9 100644 --- a/src/OpenTelemetry.Exporter.OneCollector/OpenTelemetry.Exporter.OneCollector.csproj +++ b/src/OpenTelemetry.Exporter.OneCollector/OpenTelemetry.Exporter.OneCollector.csproj @@ -18,8 +18,13 @@ 1.8.0 + + $(OpenTelemetryCoreLatestPrereleaseVersion) + $(DefineConstants);EXPOSE_EXPERIMENTAL_FEATURES + + - + diff --git a/test/OpenTelemetry.Exporter.OneCollector.Benchmarks/LogRecordCommonSchemaJsonHttpPostBenchmarks.cs b/test/OpenTelemetry.Exporter.OneCollector.Benchmarks/LogRecordCommonSchemaJsonHttpPostBenchmarks.cs index 51643933c0..91ec2c8306 100644 --- a/test/OpenTelemetry.Exporter.OneCollector.Benchmarks/LogRecordCommonSchemaJsonHttpPostBenchmarks.cs +++ b/test/OpenTelemetry.Exporter.OneCollector.Benchmarks/LogRecordCommonSchemaJsonHttpPostBenchmarks.cs @@ -91,7 +91,10 @@ private static LogRecord CreateLogRecord(int index) logRecord.Timestamp = DateTime.UtcNow; logRecord.CategoryName = typeof(LogRecordCommonSchemaJsonHttpPostBenchmarks).FullName; +#pragma warning disable CS0618 // Type or member is obsolete + // TODO: Update to use LogRecord.Severity logRecord.LogLevel = LogLevel.Information; +#pragma warning restore CS0618 // Type or member is obsolete if (index % 2 == 0) { diff --git a/test/OpenTelemetry.Exporter.OneCollector.Tests/LogRecordCommonSchemaJsonSerializerTests.cs b/test/OpenTelemetry.Exporter.OneCollector.Tests/LogRecordCommonSchemaJsonSerializerTests.cs index d706e6355e..c3f2e75645 100644 --- a/test/OpenTelemetry.Exporter.OneCollector.Tests/LogRecordCommonSchemaJsonSerializerTests.cs +++ b/test/OpenTelemetry.Exporter.OneCollector.Tests/LogRecordCommonSchemaJsonSerializerTests.cs @@ -46,7 +46,10 @@ public void LogRecordLogLevelJsonTest(LogLevel logLevel, string severityText, in { string json = GetLogRecordJson(1, (index, logRecord) => { +#pragma warning disable CS0618 // Type or member is obsolete + // TODO: Update to use LogRecord.Severity logRecord.LogLevel = logLevel; +#pragma warning restore CS0618 // Type or member is obsolete }); Assert.Equal( diff --git a/test/OpenTelemetry.Exporter.OneCollector.Tests/OneCollectorLoggerProviderBuilderExtensionsTests.cs b/test/OpenTelemetry.Exporter.OneCollector.Tests/OneCollectorLoggerProviderBuilderExtensionsTests.cs new file mode 100644 index 0000000000..92218513cc --- /dev/null +++ b/test/OpenTelemetry.Exporter.OneCollector.Tests/OneCollectorLoggerProviderBuilderExtensionsTests.cs @@ -0,0 +1,265 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using OpenTelemetry.Logs; +using Xunit; + +namespace OpenTelemetry.Exporter.OneCollector.Tests; + +public class OneCollectorLoggerProviderBuilderExtensionsTests +{ + [Fact] + public void ConfigureBatchOptionsTest() + { + int configurationInvocations = 0; + + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter(builder => + { + builder.AddOneCollectorExporter( + "InstrumentationKey=token-extrainformation", + configure => configure.ConfigureBatchOptions(o => configurationInvocations++)); + }); + + Assert.Equal(1, configurationInvocations); + } + + [Fact] + public void ConfigureExporterTest() + { + OneCollectorExporter? exporterInstance = null; + + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter(builder => + { + builder.AddOneCollectorExporter( + "InstrumentationKey=token-extrainformation", + configure => configure.ConfigureExporter(exporter => exporterInstance = exporter)); + }); + + Assert.NotNull(exporterInstance); + + using var payloadTransmittedRegistration = exporterInstance.RegisterPayloadTransmittedCallback(OnPayloadTransmitted); + + Assert.NotNull(payloadTransmittedRegistration); + + static void OnPayloadTransmitted(in OneCollectorExporterPayloadTransmittedCallbackArguments args) + { + } + } + + [Fact] + public void ConfigureSerializationOptionsTest() + { + int configurationInvocations = 0; + + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter(builder => + { + builder.AddOneCollectorExporter( + "InstrumentationKey=token-extrainformation", + configure => configure.ConfigureSerializationOptions(o => configurationInvocations++)); + }); + + Assert.Equal(1, configurationInvocations); + } + + [Fact] + public void ConfigureTransportOptionsTest() + { + int configurationInvocations = 0; + + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter(builder => + { + builder.AddOneCollectorExporter( + "InstrumentationKey=token-extrainformation", + configure => configure.ConfigureTransportOptions(o => configurationInvocations++)); + }); + + Assert.Equal(1, configurationInvocations); + } + + [Fact] + public void SetConnectionStringTest() + { + OneCollectorLogExporterOptions? options = null; + + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter( + builder => + { + builder.AddOneCollectorExporter( + configure => configure.SetConnectionString("InstrumentationKey=token-extrainformation")); + }, + services => services.Configure(o => options = o)); + + Assert.NotNull(options); + Assert.Equal("InstrumentationKey=token-extrainformation", options.ConnectionString); + } + + [Fact] + public void SetDefaultEventNameTest() + { + OneCollectorLogExporterOptions? options = null; + + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter( + builder => + { + builder.AddOneCollectorExporter( + "InstrumentationKey=token-extrainformation", + configure => configure.SetDefaultEventName("MyDefaultEventName")); + }, + services => services.Configure(o => options = o)); + + Assert.NotNull(options); + Assert.Equal("MyDefaultEventName", options.DefaultEventName); + } + + [Theory] + [InlineData(null)] + [InlineData("CustomName")] + public void ConfigurationBindingTest(string? name) + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary() + { + ["ConnectionString"] = "InstrumentationKey=token-extrainformation", + ["SerializationOptions:ExceptionStackTraceHandling"] = "IncludeAsString", + ["TransportOptions:Endpoint"] = "http://myendpoint.com/", + ["BatchOptions:ScheduledDelayMilliseconds"] = "18", + }) + .Build(); + + OneCollectorLogExporterOptions? exporterOptions = null; + BatchExportLogRecordProcessorOptions? batchOptions = null; + + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter( + builder => builder.AddOneCollectorExporter(name, connectionString: null, configuration: configuration, configure: null), + services => + { + services.Configure(name, o => exporterOptions = o); + services.Configure(name, o => batchOptions = o); + }); + + Assert.NotNull(exporterOptions); + Assert.NotNull(batchOptions); + + Assert.Equal("InstrumentationKey=token-extrainformation", exporterOptions.ConnectionString); + Assert.Equal(OneCollectorExporterSerializationExceptionStackTraceHandlingType.IncludeAsString, exporterOptions.SerializationOptions.ExceptionStackTraceHandling); + Assert.Equal("http://myendpoint.com/", exporterOptions.TransportOptions.Endpoint.ToString()); + Assert.Equal(18, batchOptions.ScheduledDelayMilliseconds); + } + + [Fact] + public void InstrumentationKeyAndTenantTokenValidationTest() + { + { + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter(builder => + { + builder.AddOneCollectorExporter("InstrumentationKey=token-extrainformation"); + }); + } + + { + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter(builder => + { + builder.AddOneCollectorExporter(configure => configure.SetConnectionString("InstrumentationKey=token-extrainformation")); + }); + } + + Assert.Throws(() => + { + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter(builder => + { + builder.AddOneCollectorExporter(configure => { }); + }); + }); + + Assert.Throws(() => + { + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter(builder => + { + builder.AddOneCollectorExporter("InstrumentationKey=invalidinstrumentationkey"); + }); + }); + + Assert.Throws(() => + { + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter(builder => + { + builder.AddOneCollectorExporter("UnknownKey=invalidinstrumentationkey"); + }); + }); + } + + [Fact] + public void OptionsTest() + { + int configurationInvocations = 0; + + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter( + builder => + { + builder.AddOneCollectorExporter(); + }, + services => + { + services.Configure( + o => + { + o.ConnectionString = "InstrumentationKey=token-extrainformation"; + configurationInvocations++; + }); + + services.Configure( + o => configurationInvocations++); + }); + + Assert.Equal(2, configurationInvocations); + } + + [Fact] + public void NamedOptionsTest() + { + int configurationInvocations = 0; + + using var loggerFactory = CreateLoggerFactoryWithOneCollectorExporter( + builder => + { + builder.AddOneCollectorExporter( + name: "MyOneCollectorExporter", + connectionString: null, + configuration: null, + configure: null); + }, + services => + { + services.Configure( + "MyOneCollectorExporter", + o => + { + o.ConnectionString = "InstrumentationKey=token-extrainformation"; + configurationInvocations++; + }); + + services.Configure( + "MyOneCollectorExporter", + o => configurationInvocations++); + }); + + Assert.Equal(2, configurationInvocations); + } + + private static ILoggerFactory CreateLoggerFactoryWithOneCollectorExporter( + Action configureLogging, + Action? configureServices = null) + { + return LoggerFactory.Create(builder => + { + builder.AddOpenTelemetry(); + + builder.Services.ConfigureOpenTelemetryLoggerProvider(configureLogging); + + configureServices?.Invoke(builder.Services); + }); + } +} From a857d7d34147c290769c1fb42e13382f2c81c233 Mon Sep 17 00:00:00 2001 From: OpenTelemetry Bot <107717825+opentelemetrybot@users.noreply.github.com> Date: Tue, 11 Jun 2024 02:39:31 +0200 Subject: [PATCH 2/6] [repo] Prepare release Exporter.OneCollector-1.9.0-rc.1 (#1878) --- src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md b/src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md index a0f00e0852..f3ad78eb10 100644 --- a/src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md +++ b/src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +## 1.9.0-rc.1 + +Released 2024-Jun-11 + * Update OpenTelemetry SDK version to `1.9.0-rc.1`. ([#1876](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1876)) From e456b23a3d84c89a667439c853a25bebeaf8fff5 Mon Sep 17 00:00:00 2001 From: Mikel Blanchard Date: Mon, 10 Jun 2024 21:35:00 -0700 Subject: [PATCH 3/6] [repo] Fix automation creating releases without changelog content (#1879) --- build/scripts/post-release.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/scripts/post-release.psm1 b/build/scripts/post-release.psm1 index 0e5c6bc2b4..ff74519816 100644 --- a/build/scripts/post-release.psm1 +++ b/build/scripts/post-release.psm1 @@ -28,7 +28,7 @@ function CreateRelease { foreach ($line in $changelogContent) { - if ($line -like "## $packageVersion" -and $started -ne $true) + if ($line -like "## $version" -and $started -ne $true) { $started = $true } From cfda172f41d20a6fcef3f61868fe2e57321a05dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Wed, 12 Jun 2024 06:27:08 +0200 Subject: [PATCH 4/6] [repo] Bump test dependencies (#1872) --- build/Common.nonprod.props | 6 +-- .../HangfireInstrumentationOptions.cs | 2 +- .../ActivityInstrumentationHelperTest.cs | 2 +- .../GenevaLogExporterTests.cs | 4 +- .../GenevaMetricExporterTests.cs | 4 +- .../GenevaTraceExporterTests.cs | 4 +- ...ichmentServiceCollectionExtensionsTests.cs | 14 +++---- .../TestAWSClientInstrumentation.cs | 18 +++++++-- .../Implementation/AWSLambdaHttpUtilsTests.cs | 6 +-- .../Implementation/CommonExtensionsTests.cs | 2 +- .../ActivityHelperTest.cs | 6 +-- .../HttpInListenerTests.cs | 2 +- .../HttpInMetricsListenerTests.cs | 6 +-- .../BasicTests.cs | 2 +- .../DependencyInjectionConfigTests.cs | 2 +- ...stsCollectionsIsAccordingToTheSpecTests.cs | 6 +-- .../MetricTests.cs | 8 ++-- .../DependencyInjectionConfigTests.cs | 2 +- .../EventCountersMetricsTests.cs | 4 +- .../GrpcCoreClientInterceptorTests.cs | 30 +++++++------- .../GrpcCoreServerInterceptorTests.cs | 18 ++++----- .../GrpcTests.server.cs | 4 +- .../DependencyInjectionConfigTests.cs | 3 +- ...eInstrumentationJobFilterAttributeTests.cs | 4 +- .../HttpClientTests.Basic.cs | 4 +- .../HttpClientTests.cs | 2 +- ...HttpWebRequestActivitySourceTests.netfx.cs | 40 +++---------------- .../DiagnosticsMiddlewareTests.cs | 4 +- .../ProcessMetricsTests.cs | 10 ++--- .../RuntimeMetricsTests.cs | 4 +- ...try.Instrumentation.SqlClient.Tests.csproj | 4 +- .../SqlClientTests.cs | 1 + .../SqlEventSourceTests.netfx.cs | 3 +- ...kExchangeRedisCallsInstrumentationTests.cs | 4 +- .../AspNetParentSpanCorrectorTests.netfx.cs | 2 + .../TelemetryBindingElementForHttpTests.cs | 10 ++--- ...elemetryBindingElementForTcpTests.netfx.cs | 14 +++---- ...etryDispatchMessageInspectorTests.netfx.cs | 6 +-- .../TelemetryPropagationTests.netfx.cs | 4 +- .../AWSECSDetectorTests.cs | 4 +- .../TestAWSXRaySamplerClient.cs | 30 +++++--------- .../TestMatcher.cs | 4 +- 42 files changed, 142 insertions(+), 167 deletions(-) diff --git a/build/Common.nonprod.props b/build/Common.nonprod.props index 7e5700a3f8..17782e9532 100644 --- a/build/Common.nonprod.props +++ b/build/Common.nonprod.props @@ -27,9 +27,9 @@ $(OpenTelemetryCoreLatestVersion) $(OpenTelemetryCoreLatestPrereleaseVersion) net8.0;net7.0;net6.0 - [2.5.0,3.0) - [2.5.0,3.0) - [1.5.48,2.0) + [2.8.1,3.0) + [2.8.1,3.0) + [1.5.58,2.0) diff --git a/src/OpenTelemetry.Instrumentation.Hangfire/HangfireInstrumentationOptions.cs b/src/OpenTelemetry.Instrumentation.Hangfire/HangfireInstrumentationOptions.cs index baec4e1dba..562ee11878 100644 --- a/src/OpenTelemetry.Instrumentation.Hangfire/HangfireInstrumentationOptions.cs +++ b/src/OpenTelemetry.Instrumentation.Hangfire/HangfireInstrumentationOptions.cs @@ -30,7 +30,7 @@ public class HangfireInstrumentationOptions /// /// Gets or sets a filter function that determines whether or not to - /// collect telemetry about the the being executed. + /// collect telemetry about the being executed. /// /// /// Notes: diff --git a/test/OpenTelemetry.Contrib.Shared.Tests/ActivityInstrumentationHelperTest.cs b/test/OpenTelemetry.Contrib.Shared.Tests/ActivityInstrumentationHelperTest.cs index e5841f53e6..fd99bee0d2 100644 --- a/test/OpenTelemetry.Contrib.Shared.Tests/ActivityInstrumentationHelperTest.cs +++ b/test/OpenTelemetry.Contrib.Shared.Tests/ActivityInstrumentationHelperTest.cs @@ -11,7 +11,7 @@ public class ActivityInstrumentationHelperTest [Theory] [InlineData("TestActivitySource", null)] [InlineData("TestActivitySource", "1.0.0")] - public void SetActivitySource(string name, string version) + public void SetActivitySource(string name, string? version) { using var activity = new Activity("Test"); using var activitySource = new ActivitySource(name, version); diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaLogExporterTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaLogExporterTests.cs index 321eaae6c6..fb9ed3168e 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaLogExporterTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaLogExporterTests.cs @@ -1520,8 +1520,8 @@ private void AssertFluentdForwardModeForLogRecord(GenevaExporterOptions exporter } else { - _ = mapping.TryGetValue("env_properties", out object envProprties); - var envPropertiesMapping = envProprties as IDictionary; + _ = mapping.TryGetValue("env_properties", out object envProperties); + var envPropertiesMapping = envProperties as IDictionary; foreach (var item in stateKeyValuePairList) { diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaMetricExporterTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaMetricExporterTests.cs index 039651efa1..a552dc590a 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaMetricExporterTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaMetricExporterTests.cs @@ -114,7 +114,7 @@ public void CannotUseReservedDimensionsInPrepopulatedFields() } [Fact] - public void SuccessfulExportOnLinux() + public async Task SuccessfulExportOnLinux() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { @@ -198,7 +198,7 @@ public void SuccessfulExportOnLinux() out _); // Wait a little more than the ExportInterval for the exporter to export the data. - Task.Delay(5500).Wait(); + await Task.Delay(5500); // Read the data sent via socket. var receivedData = new byte[1024]; diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaTraceExporterTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaTraceExporterTests.cs index 5b2cd4a528..1f22dc0122 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaTraceExporterTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaTraceExporterTests.cs @@ -686,8 +686,8 @@ private void AssertFluentdForwardModeForActivity(GenevaExporterOptions exporterO #endregion #region Assert Activity Tags - _ = mapping.TryGetValue("env_properties", out object envProprties); - var envPropertiesMapping = envProprties as IDictionary; + _ = mapping.TryGetValue("env_properties", out object envProperties); + var envPropertiesMapping = envProperties as IDictionary; foreach (var tag in activity.TagObjects) { if (CS40_PART_B_MAPPING.TryGetValue(tag.Key, out string replacementKey)) diff --git a/test/OpenTelemetry.Extensions.Enrichment.Tests/OpenTelemetryEnrichmentServiceCollectionExtensionsTests.cs b/test/OpenTelemetry.Extensions.Enrichment.Tests/OpenTelemetryEnrichmentServiceCollectionExtensionsTests.cs index 61701c1ddb..dbad6bf253 100644 --- a/test/OpenTelemetry.Extensions.Enrichment.Tests/OpenTelemetryEnrichmentServiceCollectionExtensionsTests.cs +++ b/test/OpenTelemetry.Extensions.Enrichment.Tests/OpenTelemetryEnrichmentServiceCollectionExtensionsTests.cs @@ -32,7 +32,7 @@ public async Task AddTraceEnricherOfTRegistersEnricher() .AddTraceEnricher()) .Build(); - await host.StartAsync().ConfigureAwait(false); + await host.StartAsync(); var enrichers = host.Services.GetServices().ToArray(); Assert.NotNull(enrichers); @@ -61,7 +61,7 @@ public async Task AddTraceEnricherOfTRegistersEnricher() Assert.Equal(1, tagObject2.Single().Value); } - await host.StopAsync().ConfigureAwait(false); + await host.StopAsync(); } [Fact] @@ -80,7 +80,7 @@ public async Task AddTraceEnricherRegistersEnricher() .AddTraceEnricher(new MyTraceEnricher2())) .Build(); - await host.StartAsync().ConfigureAwait(false); + await host.StartAsync(); var enrichers = host.Services.GetServices().ToArray(); Assert.NotNull(enrichers); @@ -102,7 +102,7 @@ public async Task AddTraceEnricherRegistersEnricher() Assert.Equal(1, tagObject2.Single().Value); } - await host.StopAsync().ConfigureAwait(false); + await host.StopAsync(); } [Fact] @@ -126,7 +126,7 @@ public async Task AddTraceEnricherActionRegistersEnricher() .AddTraceEnricher(bag => bag.Add(testKey2, testValue2))) .Build(); - await host.StartAsync().ConfigureAwait(false); + await host.StartAsync(); using var source1 = new ActivitySource(SourceName); @@ -162,7 +162,7 @@ public async Task AddTraceEnricherFactoryRegistersEnricher() .AddTraceEnricher(sp => new MyTraceEnricher2())) .Build(); - await host.StartAsync().ConfigureAwait(false); + await host.StartAsync(); var enrichers = host.Services.GetServices().ToArray(); Assert.NotNull(enrichers); @@ -184,6 +184,6 @@ public async Task AddTraceEnricherFactoryRegistersEnricher() Assert.Equal(1, tagObject2.Single().Value); } - await host.StopAsync().ConfigureAwait(false); + await host.StopAsync(); } } diff --git a/test/OpenTelemetry.Instrumentation.AWS.Tests/TestAWSClientInstrumentation.cs b/test/OpenTelemetry.Instrumentation.AWS.Tests/TestAWSClientInstrumentation.cs index 81340c5764..4caa6339ad 100644 --- a/test/OpenTelemetry.Instrumentation.AWS.Tests/TestAWSClientInstrumentation.cs +++ b/test/OpenTelemetry.Instrumentation.AWS.Tests/TestAWSClientInstrumentation.cs @@ -22,7 +22,11 @@ namespace OpenTelemetry.Instrumentation.AWS.Tests; public class TestAWSClientInstrumentation { [Fact] +#if NETFRAMEWORK public void TestDDBScanSuccessful() +#else + public async Task TestDDBScanSuccessful() +#endif { var exportedItems = new List(); @@ -46,7 +50,7 @@ public void TestDDBScanSuccessful() #if NETFRAMEWORK ddb.Scan(scan_request); #else - ddb.ScanAsync(scan_request).Wait(); + await ddb.ScanAsync(scan_request); #endif Assert.Single(exportedItems); @@ -61,7 +65,11 @@ public void TestDDBScanSuccessful() } [Fact] +#if NETFRAMEWORK public void TestDDBSubtypeScanSuccessful() +#else + public async Task TestDDBSubtypeScanSuccessful() +#endif { var exportedItems = new List(); @@ -85,7 +93,7 @@ public void TestDDBSubtypeScanSuccessful() #if NETFRAMEWORK ddb.Scan(scan_request); #else - ddb.ScanAsync(scan_request).Wait(); + await ddb.ScanAsync(scan_request); #endif Assert.Single(exportedItems); @@ -154,7 +162,11 @@ public async Task TestDDBScanUnsuccessful() } [Fact] +#if NETFRAMEWORK public void TestSQSSendMessageSuccessful() +#else + public async Task TestSQSSendMessageSuccessful() +#endif { var exportedItems = new List(); @@ -178,7 +190,7 @@ public void TestSQSSendMessageSuccessful() #if NETFRAMEWORK sqs.SendMessage(send_msg_req); #else - sqs.SendMessageAsync(send_msg_req).Wait(); + await sqs.SendMessageAsync(send_msg_req); #endif Assert.Single(exportedItems); Activity awssdk_activity = exportedItems[0]; diff --git a/test/OpenTelemetry.Instrumentation.AWSLambda.Tests/Implementation/AWSLambdaHttpUtilsTests.cs b/test/OpenTelemetry.Instrumentation.AWSLambda.Tests/Implementation/AWSLambdaHttpUtilsTests.cs index ec2ff58713..6c69a93a0f 100644 --- a/test/OpenTelemetry.Instrumentation.AWSLambda.Tests/Implementation/AWSLambdaHttpUtilsTests.cs +++ b/test/OpenTelemetry.Instrumentation.AWSLambda.Tests/Implementation/AWSLambdaHttpUtilsTests.cs @@ -227,7 +227,7 @@ public void SetHttpTagsFromResult_APIGatewayHttpApiV2ProxyResponse_SetsCorrectTa [InlineData(null, "localhost", "localhost", null)] [InlineData("http", "localhost", "localhost", 80)] [InlineData("https", "localhost", "localhost", 443)] - public void GetHostAndPort_HostHeader_ReturnsCorrectHostAndPort(string httpSchema, string hostHeader, string expectedHost, int? expectedPort) + public void GetHostAndPort_HostHeader_ReturnsCorrectHostAndPort(string? httpSchema, string? hostHeader, string? expectedHost, int? expectedPort) { (var host, var port) = AWSLambdaHttpUtils.GetHostAndPort(httpSchema, hostHeader); @@ -244,7 +244,7 @@ public void GetHostAndPort_HostHeader_ReturnsCorrectHostAndPort(string httpSchem [InlineData(new[] { "value 1" }, "?name=value+1")] [InlineData(new[] { "value1", "value2" }, "?name=value1&name=value2")] #pragma warning restore CA1861 // Avoid constant arrays as arguments - public void GetQueryString_APIGatewayProxyRequest_CorrectQueryString(IList values, string expectedQueryString) + public void GetQueryString_APIGatewayProxyRequest_CorrectQueryString(IList? values, string expectedQueryString) { var request = new APIGatewayProxyRequest(); if (values != null) @@ -265,7 +265,7 @@ public void GetQueryString_APIGatewayProxyRequest_CorrectQueryString(IList>(); diff --git a/test/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule.Tests/ActivityHelperTest.cs b/test/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule.Tests/ActivityHelperTest.cs index 3a60303dba..5f8f18b3a4 100644 --- a/test/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule.Tests/ActivityHelperTest.cs +++ b/test/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule.Tests/ActivityHelperTest.cs @@ -80,7 +80,7 @@ public async Task Can_Restore_Activity() }); } - await testTask.ConfigureAwait(false); + await testTask; } [Fact(Skip = "Temporarily disable until stable.")] @@ -120,7 +120,7 @@ public async Task Can_Restore_Baggage() }); } - await testTask.ConfigureAwait(false); + await testTask; } [Fact] @@ -401,7 +401,7 @@ public void Can_Create_RootActivity_And_Start_Activity() using var rootActivity = ActivityHelper.StartAspNetActivity(this.noopTextMapPropagator, context, null); Assert.NotNull(rootActivity); - Assert.True(!string.IsNullOrEmpty(rootActivity.Id)); + Assert.False(string.IsNullOrEmpty(rootActivity.Id)); } [Fact] diff --git a/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInListenerTests.cs b/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInListenerTests.cs index e5b84675ad..e83249529c 100644 --- a/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInListenerTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInListenerTests.cs @@ -41,7 +41,7 @@ public void AspNetRequestsAreCollectedSuccessfully( string url, string expectedUrlScheme, string expectedUrlPath, - string expectedUrlQuery, + string? expectedUrlQuery, bool disableQueryRedaction, string expectedHost, int expectedPort, diff --git a/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInMetricsListenerTests.cs b/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInMetricsListenerTests.cs index 7cb3b0520e..5aeb4a2e8d 100644 --- a/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInMetricsListenerTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInMetricsListenerTests.cs @@ -34,11 +34,11 @@ public class HttpInMetricsListenerTests public void AspNetMetricTagsAreCollectedSuccessfully( string url, int routeType, - string routeTemplate, - string enrichMode, + string? routeTemplate, + string? enrichMode, string expectedScheme, string? expectedHost, - string expectedRoute, + string? expectedRoute, int? expectedPort, int expectedStatus, bool enableServerAttributesForRequestDuration = true) diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs index 37ba8b44bc..8cc9c62eb5 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs @@ -646,7 +646,7 @@ void ConfigureTestServices(IServiceCollection services) [InlineData("POST", "POST", null, "POST")] [InlineData("TRACE", "TRACE", null, "TRACE")] [InlineData("CUSTOM", "_OTHER", "CUSTOM", "HTTP")] - public async Task HttpRequestMethodAndActivityDisplayIsSetAsPerSpec(string originalMethod, string expectedMethod, string expectedOriginalMethod, string expectedDisplayName) + public async Task HttpRequestMethodAndActivityDisplayIsSetAsPerSpec(string originalMethod, string expectedMethod, string? expectedOriginalMethod, string expectedDisplayName) { var exportedItems = new List(); diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/DependencyInjectionConfigTests.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/DependencyInjectionConfigTests.cs index a877d060a3..b5c6db209c 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/DependencyInjectionConfigTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/DependencyInjectionConfigTests.cs @@ -24,7 +24,7 @@ public DependencyInjectionConfigTests(WebApplicationFactory factory) [Theory] [InlineData(null)] [InlineData("CustomName")] - public void TestTracingOptionsDIConfig(string name) + public void TestTracingOptionsDIConfig(string? name) { name ??= Options.DefaultName; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/IncomingRequestsCollectionsIsAccordingToTheSpecTests.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/IncomingRequestsCollectionsIsAccordingToTheSpecTests.cs index 62b8f5abbc..5873415469 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/IncomingRequestsCollectionsIsAccordingToTheSpecTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/IncomingRequestsCollectionsIsAccordingToTheSpecTests.cs @@ -32,8 +32,8 @@ public IncomingRequestsCollectionsIsAccordingToTheSpecTests(WebApplicationFactor [InlineData("/api/exception", null, null, 503, true)] public async Task SuccessfulTemplateControllerCallGeneratesASpan_New( string urlPath, - string query, - string userAgent, + string? query, + string? userAgent, int statusCode, bool recordException = false) { @@ -130,7 +130,7 @@ public async Task SuccessfulTemplateControllerCallGeneratesASpan_New( activity.Dispose(); } - private static void ValidateTagValue(Activity activity, string attribute, string expectedValue) + private static void ValidateTagValue(Activity activity, string attribute, string? expectedValue) { if (string.IsNullOrEmpty(expectedValue)) { diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/MetricTests.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/MetricTests.cs index 4711bd272b..413c335194 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/MetricTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/MetricTests.cs @@ -180,7 +180,7 @@ void ConfigureTestServices(IServiceCollection services) [Theory] [InlineData("/api/values/2", "api/Values/{id}", null, 200)] [InlineData("/api/Error", "api/Error", "System.Exception", 500)] - public async Task RequestMetricIsCaptured(string api, string expectedRoute, string expectedErrorType, int expectedStatusCode) + public async Task RequestMetricIsCaptured(string api, string expectedRoute, string? expectedErrorType, int expectedStatusCode) { var metricItems = new List(); @@ -312,7 +312,7 @@ public void Dispose() private static List GetMetricPoints(Metric metric) { Assert.NotNull(metric); - Assert.True(metric.MetricType == MetricType.Histogram); + Assert.Equal(MetricType.Histogram, metric.MetricType); var metricPoints = new List(); foreach (var p in metric.GetMetricPoints()) { @@ -325,7 +325,7 @@ private static List GetMetricPoints(Metric metric) private static void AssertMetricPoints( List metricPoints, List expectedRoutes, - string expectedErrorType, + string? expectedErrorType, int expectedStatusCode, int expectedTagsCount) { @@ -360,7 +360,7 @@ private static void AssertMetricPoint( MetricPoint metricPoint, int expectedStatusCode, string expectedRoute, - string expectedErrorType, + string? expectedErrorType, int expectedTagsCount) { var count = metricPoint.GetHistogramCount(); diff --git a/test/OpenTelemetry.Instrumentation.EntityFrameworkCore.Tests/DependencyInjectionConfigTests.cs b/test/OpenTelemetry.Instrumentation.EntityFrameworkCore.Tests/DependencyInjectionConfigTests.cs index ba4b859459..5592f45806 100644 --- a/test/OpenTelemetry.Instrumentation.EntityFrameworkCore.Tests/DependencyInjectionConfigTests.cs +++ b/test/OpenTelemetry.Instrumentation.EntityFrameworkCore.Tests/DependencyInjectionConfigTests.cs @@ -16,7 +16,7 @@ public class DependencyInjectionConfigTests [Theory] [InlineData(null)] [InlineData("CustomName")] - public async Task TestTracingOptionsDiConfig(string name) + public async Task TestTracingOptionsDiConfig(string? name) { bool optionsPickedFromDi = false; diff --git a/test/OpenTelemetry.Instrumentation.EventCounters.Tests/EventCountersMetricsTests.cs b/test/OpenTelemetry.Instrumentation.EventCounters.Tests/EventCountersMetricsTests.cs index 7e6b379d71..dc5226af7e 100644 --- a/test/OpenTelemetry.Instrumentation.EventCounters.Tests/EventCountersMetricsTests.cs +++ b/test/OpenTelemetry.Instrumentation.EventCounters.Tests/EventCountersMetricsTests.cs @@ -169,7 +169,7 @@ public void EventSourceNameShortening(string sourceName, string eventName, strin } [Fact(Skip = "This test should properly validate no metrics are exported from event counters with invalid names (too long)")] - public void InstrumentNameTooLong() + public async Task InstrumentNameTooLong() { // Arrange List metricItems = new(); @@ -190,7 +190,7 @@ public void InstrumentNameTooLong() // Act connections.Increment(1); - Task.Delay(1800).Wait(); + await Task.Delay(1800); meterProvider.ForceFlush(); // Assert diff --git a/test/OpenTelemetry.Instrumentation.GrpcCore.Tests/GrpcCoreClientInterceptorTests.cs b/test/OpenTelemetry.Instrumentation.GrpcCore.Tests/GrpcCoreClientInterceptorTests.cs index a8fd94ac87..e1ec20a73a 100644 --- a/test/OpenTelemetry.Instrumentation.GrpcCore.Tests/GrpcCoreClientInterceptorTests.cs +++ b/test/OpenTelemetry.Instrumentation.GrpcCore.Tests/GrpcCoreClientInterceptorTests.cs @@ -36,7 +36,7 @@ public class GrpcCoreClientInterceptorTests [Fact] public async Task AsyncUnarySuccess() { - await TestHandlerSuccess(FoobarService.MakeUnaryAsyncRequest, DefaultMetadataFunc()).ConfigureAwait(false); + await TestHandlerSuccess(FoobarService.MakeUnaryAsyncRequest, DefaultMetadataFunc()); } /// @@ -50,7 +50,7 @@ await TestHandlerFailure( FoobarService.MakeUnaryAsyncRequest, StatusCode.Unavailable, validateErrorDescription: false, - BogusServerUri).ConfigureAwait(false); + BogusServerUri); } /// @@ -60,7 +60,7 @@ await TestHandlerFailure( [Fact] public async Task AsyncUnaryFail() { - await TestHandlerFailure(FoobarService.MakeUnaryAsyncRequest).ConfigureAwait(false); + await TestHandlerFailure(FoobarService.MakeUnaryAsyncRequest); } /// @@ -84,7 +84,7 @@ static void MakeRequest(Foobar.FoobarClient client) [Fact] public async Task ClientStreamingSuccess() { - await TestHandlerSuccess(FoobarService.MakeClientStreamingRequest, DefaultMetadataFunc()).ConfigureAwait(false); + await TestHandlerSuccess(FoobarService.MakeClientStreamingRequest, DefaultMetadataFunc()); } /// @@ -98,7 +98,7 @@ await TestHandlerFailure( FoobarService.MakeClientStreamingRequest, StatusCode.Unavailable, validateErrorDescription: false, - BogusServerUri).ConfigureAwait(false); + BogusServerUri); } /// @@ -108,7 +108,7 @@ await TestHandlerFailure( [Fact] public async Task ClientStreamingFail() { - await TestHandlerFailure(FoobarService.MakeClientStreamingRequest).ConfigureAwait(false); + await TestHandlerFailure(FoobarService.MakeClientStreamingRequest); } /// @@ -132,7 +132,7 @@ static void MakeRequest(Foobar.FoobarClient client) [Fact] public async Task ServerStreamingSuccess() { - await TestHandlerSuccess(FoobarService.MakeServerStreamingRequest, DefaultMetadataFunc()).ConfigureAwait(false); + await TestHandlerSuccess(FoobarService.MakeServerStreamingRequest, DefaultMetadataFunc()); } /// @@ -142,7 +142,7 @@ public async Task ServerStreamingSuccess() [Fact] public async Task ServerStreamingFail() { - await TestHandlerFailure(FoobarService.MakeServerStreamingRequest).ConfigureAwait(false); + await TestHandlerFailure(FoobarService.MakeServerStreamingRequest); } /// @@ -166,7 +166,7 @@ static void MakeRequest(Foobar.FoobarClient client) [Fact] public async Task DuplexStreamingSuccess() { - await TestHandlerSuccess(FoobarService.MakeDuplexStreamingRequest, DefaultMetadataFunc()).ConfigureAwait(false); + await TestHandlerSuccess(FoobarService.MakeDuplexStreamingRequest, DefaultMetadataFunc()); } /// @@ -180,7 +180,7 @@ await TestHandlerFailure( FoobarService.MakeDuplexStreamingRequest, StatusCode.Unavailable, validateErrorDescription: false, - BogusServerUri).ConfigureAwait(false); + BogusServerUri); } /// @@ -190,7 +190,7 @@ await TestHandlerFailure( [Fact] public async Task DuplexStreamingFail() { - await TestHandlerFailure(FoobarService.MakeDuplexStreamingRequest).ConfigureAwait(false); + await TestHandlerFailure(FoobarService.MakeDuplexStreamingRequest); } /// @@ -266,7 +266,7 @@ static void ValidateNewTagOnActivity(InterceptorActivityListener listener) Assert.Equal(parentActivity, Activity.Current); - _ = await call.ResponseAsync.ConfigureAwait(false); + _ = await call.ResponseAsync; Assert.Equal(parentActivity, Activity.Current); @@ -281,15 +281,15 @@ static void ValidateNewTagOnActivity(InterceptorActivityListener listener) Assert.Equal(parentActivity, Activity.Current); - await call.RequestStream.WriteAsync(FoobarService.DefaultRequestMessage).ConfigureAwait(false); + await call.RequestStream.WriteAsync(FoobarService.DefaultRequestMessage); Assert.Equal(parentActivity, Activity.Current); - await call.RequestStream.CompleteAsync().ConfigureAwait(false); + await call.RequestStream.CompleteAsync(); Assert.Equal(parentActivity, Activity.Current); - while (await call.ResponseStream.MoveNext().ConfigureAwait(false)) + while (await call.ResponseStream.MoveNext()) { Assert.Equal(parentActivity, Activity.Current); } diff --git a/test/OpenTelemetry.Instrumentation.GrpcCore.Tests/GrpcCoreServerInterceptorTests.cs b/test/OpenTelemetry.Instrumentation.GrpcCore.Tests/GrpcCoreServerInterceptorTests.cs index 54837ad547..4357262e9e 100644 --- a/test/OpenTelemetry.Instrumentation.GrpcCore.Tests/GrpcCoreServerInterceptorTests.cs +++ b/test/OpenTelemetry.Instrumentation.GrpcCore.Tests/GrpcCoreServerInterceptorTests.cs @@ -22,7 +22,7 @@ public class GrpcCoreServerInterceptorTests [Fact] public async Task UnaryServerHandlerSuccess() { - await TestHandlerSuccess(FoobarService.MakeUnaryAsyncRequest).ConfigureAwait(false); + await TestHandlerSuccess(FoobarService.MakeUnaryAsyncRequest); } /// @@ -32,7 +32,7 @@ public async Task UnaryServerHandlerSuccess() [Fact] public async Task UnaryServerHandlerFail() { - await TestHandlerFailure(FoobarService.MakeUnaryAsyncRequest).ConfigureAwait(false); + await TestHandlerFailure(FoobarService.MakeUnaryAsyncRequest); } /// @@ -42,7 +42,7 @@ public async Task UnaryServerHandlerFail() [Fact] public async Task ClientStreamingServerHandlerSuccess() { - await TestHandlerSuccess(FoobarService.MakeClientStreamingRequest).ConfigureAwait(false); + await TestHandlerSuccess(FoobarService.MakeClientStreamingRequest); } /// @@ -52,7 +52,7 @@ public async Task ClientStreamingServerHandlerSuccess() [Fact] public async Task ClientStreamingServerHandlerFail() { - await TestHandlerFailure(FoobarService.MakeClientStreamingRequest).ConfigureAwait(false); + await TestHandlerFailure(FoobarService.MakeClientStreamingRequest); } /// @@ -62,7 +62,7 @@ public async Task ClientStreamingServerHandlerFail() [Fact] public async Task ServerStreamingServerHandlerSuccess() { - await TestHandlerSuccess(FoobarService.MakeServerStreamingRequest).ConfigureAwait(false); + await TestHandlerSuccess(FoobarService.MakeServerStreamingRequest); } /// @@ -72,7 +72,7 @@ public async Task ServerStreamingServerHandlerSuccess() [Fact] public async Task ServerStreamingServerHandlerFail() { - await TestHandlerFailure(FoobarService.MakeServerStreamingRequest).ConfigureAwait(false); + await TestHandlerFailure(FoobarService.MakeServerStreamingRequest); } /// @@ -82,7 +82,7 @@ public async Task ServerStreamingServerHandlerFail() [Fact] public async Task DuplexStreamingServerHandlerSuccess() { - await TestHandlerSuccess(FoobarService.MakeDuplexStreamingRequest).ConfigureAwait(false); + await TestHandlerSuccess(FoobarService.MakeDuplexStreamingRequest); } /// @@ -92,7 +92,7 @@ public async Task DuplexStreamingServerHandlerSuccess() [Fact] public async Task DuplexStreamingServerHandlerFail() { - await TestHandlerFailure(FoobarService.MakeDuplexStreamingRequest).ConfigureAwait(false); + await TestHandlerFailure(FoobarService.MakeDuplexStreamingRequest); } /// @@ -111,7 +111,7 @@ private static async Task TestHandlerSuccess(Func @@ -103,7 +103,7 @@ public void GrpcAspNetCoreInstrumentationAddsCorrectAttributes(string enableGrpc [InlineData("false")] [InlineData("True")] [InlineData("False")] - public void GrpcAspNetCoreInstrumentationAddsCorrectAttributesWhenItCreatesNewActivity(string enableGrpcAspNetCoreSupport) + public void GrpcAspNetCoreInstrumentationAddsCorrectAttributesWhenItCreatesNewActivity(string? enableGrpcAspNetCoreSupport) { try { diff --git a/test/OpenTelemetry.Instrumentation.Hangfire.Tests/DependencyInjectionConfigTests.cs b/test/OpenTelemetry.Instrumentation.Hangfire.Tests/DependencyInjectionConfigTests.cs index fdfd9488b4..e850dcebf6 100644 --- a/test/OpenTelemetry.Instrumentation.Hangfire.Tests/DependencyInjectionConfigTests.cs +++ b/test/OpenTelemetry.Instrumentation.Hangfire.Tests/DependencyInjectionConfigTests.cs @@ -11,12 +11,13 @@ namespace OpenTelemetry.Instrumentation.Hangfire.Tests; +[Collection("Hangfire")] public class DependencyInjectionConfigTests { [Theory] [InlineData(null)] [InlineData("CustomName")] - public async Task TestTracingOptionsDiConfig(string name) + public async Task TestTracingOptionsDiConfig(string? name) { bool optionsPickedFromDi = false; diff --git a/test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireInstrumentationJobFilterAttributeTests.cs b/test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireInstrumentationJobFilterAttributeTests.cs index 08e7d3cc6c..badd9b8cc6 100644 --- a/test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireInstrumentationJobFilterAttributeTests.cs +++ b/test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireInstrumentationJobFilterAttributeTests.cs @@ -13,9 +13,10 @@ namespace OpenTelemetry.Instrumentation.Hangfire.Tests; +[Collection("Hangfire")] public class HangfireInstrumentationJobFilterAttributeTests : IClassFixture { - private HangfireFixture hangfireFixture; + private readonly HangfireFixture hangfireFixture; public HangfireInstrumentationJobFilterAttributeTests(HangfireFixture hangfireFixture) { @@ -123,6 +124,7 @@ public async Task Should_Create_Activity_With_Custom_DisplayName() using var tel = Sdk.CreateTracerProviderBuilder() .AddHangfireInstrumentation(options => options.DisplayNameFunc = backgroundJob => $"JOB {backgroundJob.Id}") .AddInMemoryExporter(exportedItems) + .SetSampler() .Build(); // Act diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs index f3610c23e4..f9923b869a 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs @@ -522,7 +522,7 @@ public async Task RedirectTest() } [Fact] - public async void RequestNotCollectedWhenInstrumentationFilterApplied() + public async Task RequestNotCollectedWhenInstrumentationFilterApplied() { var exportedItems = new List(); @@ -563,7 +563,7 @@ public async void RequestNotCollectedWhenInstrumentationFilterApplied() } [Fact] - public async void RequestNotCollectedWhenInstrumentationFilterThrowsException() + public async Task RequestNotCollectedWhenInstrumentationFilterThrowsException() { var exportedItems = new List(); diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs index 97d15fd75c..bbd3908cc5 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs @@ -349,7 +349,7 @@ private static async Task HttpOutCallsAreCollectedSuccessfullyBodyAsync( var metric = requestMetrics.FirstOrDefault(m => m.Name == "http.client.request.duration"); Assert.NotNull(metric); Assert.Equal("s", metric.Unit); - Assert.True(metric.MetricType == MetricType.Histogram); + Assert.Equal(MetricType.Histogram, metric.MetricType); var metricPoints = new List(); foreach (var p in metric.GetMetricPoints()) diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs index bc86339834..ce30769a4a 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs @@ -524,7 +524,7 @@ public async Task TestRequestWithException(string method) // check that request failed because of the wrong domain name and not because of reflection var webException = (WebException)ex.InnerException; Assert.NotNull(webException); - Assert.True(webException.Status == WebExceptionStatus.NameResolutionFailure); + Assert.Equal(WebExceptionStatus.NameResolutionFailure, webException.Status); // We should have one Start event and one Stop event with an exception. Assert.Equal(2, eventRecords.Records.Count); @@ -538,7 +538,7 @@ public async Task TestRequestWithException(string method) Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair exceptionEvent)); Assert.Equal("Stop", exceptionEvent.Key); - Assert.True(activity.Status != ActivityStatusCode.Unset); + Assert.NotEqual(ActivityStatusCode.Unset, activity.Status); Assert.Null(activity.StatusDescription); } @@ -577,8 +577,8 @@ public async Task TestCanceledRequest(string method) Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair exceptionEvent)); Assert.Equal("Stop", exceptionEvent.Key); - Assert.True(exceptionEvent.Value.Status != ActivityStatusCode.Unset); - Assert.True(exceptionEvent.Value.StatusDescription == null); + Assert.NotEqual(ActivityStatusCode.Unset, exceptionEvent.Value.Status); + Assert.Null(exceptionEvent.Value.StatusDescription); } /// @@ -616,7 +616,7 @@ public async Task TestSecureTransportFailureRequest(string method) Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair exceptionEvent)); Assert.Equal("Stop", exceptionEvent.Key); - Assert.True(exceptionEvent.Value.Status != ActivityStatusCode.Unset); + Assert.NotEqual(ActivityStatusCode.Unset, exceptionEvent.Value.Status); Assert.Null(exceptionEvent.Value.StatusDescription); } @@ -658,7 +658,7 @@ public async Task TestSecureTransportRetryFailureRequest(string method) Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair exceptionEvent)); Assert.Equal("Stop", exceptionEvent.Key); - Assert.True(exceptionEvent.Value.Status != ActivityStatusCode.Unset); + Assert.NotEqual(ActivityStatusCode.Unset, exceptionEvent.Value.Status); Assert.Null(exceptionEvent.Value.StatusDescription); } @@ -782,34 +782,6 @@ private static void VerifyActivityStopTags(int statusCode, Activity activity) Assert.Equal(statusCode, activity.GetTagValue(SemanticConventions.AttributeHttpResponseStatusCode)); } - private static void ActivityEnrichment(Activity activity, string method, object obj) - { - switch (method) - { - case "OnStartActivity": - Assert.True(obj is HttpWebRequest); - VerifyHeaders(obj as HttpWebRequest); - - if (validateBaggage) - { - ValidateBaggage(obj as HttpWebRequest); - } - - break; - - case "OnStopActivity": - Assert.True(obj is HttpWebResponse); - break; - - case "OnException": - Assert.True(obj is Exception); - break; - - default: - break; - } - } - private static void ValidateBaggage(HttpWebRequest request) { string[] baggage = request.Headers["baggage"].Split(','); diff --git a/test/OpenTelemetry.Instrumentation.Owin.Tests/DiagnosticsMiddlewareTests.cs b/test/OpenTelemetry.Instrumentation.Owin.Tests/DiagnosticsMiddlewareTests.cs index 71e57081a1..240b8a5ee3 100644 --- a/test/OpenTelemetry.Instrumentation.Owin.Tests/DiagnosticsMiddlewareTests.cs +++ b/test/OpenTelemetry.Instrumentation.Owin.Tests/DiagnosticsMiddlewareTests.cs @@ -180,7 +180,7 @@ public async Task OutgoingRequestInstrumentationTest( this.requestCompleteHandle.Reset(); - using var response = await client.GetAsync(requestUri).ConfigureAwait(false); + using var response = await client.GetAsync(requestUri); /* Note: This code will continue executing as soon as the response is available but Owin could still be working. We need to wait until @@ -309,7 +309,7 @@ public async Task QueryParametersAreRedacted(string actualPath, string expectedP try { - using var response = await client.GetAsync(requestUri).ConfigureAwait(false); + using var response = await client.GetAsync(requestUri); } catch { diff --git a/test/OpenTelemetry.Instrumentation.Process.Tests/ProcessMetricsTests.cs b/test/OpenTelemetry.Instrumentation.Process.Tests/ProcessMetricsTests.cs index c766a13ec2..065ad01c33 100644 --- a/test/OpenTelemetry.Instrumentation.Process.Tests/ProcessMetricsTests.cs +++ b/test/OpenTelemetry.Instrumentation.Process.Tests/ProcessMetricsTests.cs @@ -25,7 +25,7 @@ public void ProcessMetricsAreCaptured() meterProviderA.ForceFlush(MaxTimeToAllowForFlush); - Assert.True(exportedItemsA.Count == 5); + Assert.Equal(5, exportedItemsA.Count); var physicalMemoryMetric = exportedItemsA.FirstOrDefault(i => i.Name == "process.memory.usage"); Assert.NotNull(physicalMemoryMetric); var virtualMemoryMetric = exportedItemsA.FirstOrDefault(i => i.Name == "process.memory.virtual"); @@ -55,8 +55,8 @@ public void ProcessMetricsAreCaptured() meterProviderB.ForceFlush(MaxTimeToAllowForFlush); - Assert.True(exportedItemsA.Count == 5); - Assert.True(exportedItemsB.Count == 5); + Assert.Equal(5, exportedItemsA.Count); + Assert.Equal(5, exportedItemsB.Count); } [Fact] @@ -99,7 +99,7 @@ public void CpuTimeMetricsAreCaptured() } [Fact] - public void ProcessMetricsAreCapturedWhenTasksOverlap() + public async Task ProcessMetricsAreCapturedWhenTasksOverlap() { var exportedItemsA = new List(); var exportedItemsB = new List(); @@ -131,7 +131,7 @@ public void ProcessMetricsAreCapturedWhenTasksOverlap() }), }; - Task.WaitAll(tasks.ToArray()); + await Task.WhenAll(tasks); Assert.Equal(5, exportedItemsA.Count); var physicalMemoryMetricA = exportedItemsA.FirstOrDefault(i => i.Name == "process.memory.usage"); diff --git a/test/OpenTelemetry.Instrumentation.Runtime.Tests/RuntimeMetricsTests.cs b/test/OpenTelemetry.Instrumentation.Runtime.Tests/RuntimeMetricsTests.cs index 25d8c9278e..f0b23686e7 100644 --- a/test/OpenTelemetry.Instrumentation.Runtime.Tests/RuntimeMetricsTests.cs +++ b/test/OpenTelemetry.Instrumentation.Runtime.Tests/RuntimeMetricsTests.cs @@ -111,7 +111,7 @@ public void JitRelatedMetricsTest() } [Fact] - public void ThreadingRelatedMetricsTest() + public async Task ThreadingRelatedMetricsTest() { var exportedItems = new List(); using var meterProvider = Sdk.CreateMeterProviderBuilder() @@ -127,7 +127,7 @@ public void ThreadingRelatedMetricsTest() tasks.Add(Task.Run(() => { })); } - Task.WaitAll(tasks.ToArray()); + await Task.WhenAll(tasks); meterProvider.ForceFlush(MaxTimeToAllowForFlush); diff --git a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/OpenTelemetry.Instrumentation.SqlClient.Tests.csproj b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/OpenTelemetry.Instrumentation.SqlClient.Tests.csproj index 5b515f5da9..0036dbd152 100644 --- a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/OpenTelemetry.Instrumentation.SqlClient.Tests.csproj +++ b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/OpenTelemetry.Instrumentation.SqlClient.Tests.csproj @@ -17,8 +17,8 @@ - - + + diff --git a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientTests.cs b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientTests.cs index 25d0252557..22dea15a54 100644 --- a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientTests.cs +++ b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientTests.cs @@ -14,6 +14,7 @@ namespace OpenTelemetry.Instrumentation.SqlClient.Tests; +[Collection("SqlClient")] public class SqlClientTests : IDisposable { #if !NETFRAMEWORK diff --git a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlEventSourceTests.netfx.cs b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlEventSourceTests.netfx.cs index 60e20b880a..fe89800745 100644 --- a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlEventSourceTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlEventSourceTests.netfx.cs @@ -13,6 +13,7 @@ namespace OpenTelemetry.Instrumentation.SqlClient.Tests; +[Collection("SqlClient")] public class SqlEventSourceTests { /* @@ -176,7 +177,7 @@ public void DefaultCaptureTextFalse(Type eventSourceType) using IFakeBehavingSqlEventSource fakeSqlEventSource = (IFakeBehavingSqlEventSource)Activator.CreateInstance(eventSourceType); var exportedItems = new List(); - using var shutdownSignal = Sdk.CreateTracerProviderBuilder() + var shutdownSignal = Sdk.CreateTracerProviderBuilder() .AddInMemoryExporter(exportedItems) .AddSqlClientInstrumentation() .Build(); diff --git a/test/OpenTelemetry.Instrumentation.StackExchangeRedis.Tests/StackExchangeRedisCallsInstrumentationTests.cs b/test/OpenTelemetry.Instrumentation.StackExchangeRedis.Tests/StackExchangeRedisCallsInstrumentationTests.cs index 0055b8be5d..0ee6e264bc 100644 --- a/test/OpenTelemetry.Instrumentation.StackExchangeRedis.Tests/StackExchangeRedisCallsInstrumentationTests.cs +++ b/test/OpenTelemetry.Instrumentation.StackExchangeRedis.Tests/StackExchangeRedisCallsInstrumentationTests.cs @@ -134,7 +134,7 @@ public void SuccessfulCommandTest(string value) } [Fact] - public async void ProfilerSessionUsesTheSameDefault() + public async Task ProfilerSessionUsesTheSameDefault() { var connectionOptions = new ConfigurationOptions { @@ -287,7 +287,7 @@ public async Task ProfilerSessionsHandleMultipleSpans() using (Activity.Current = new Activity("Child-Span-2").SetParentId(rootActivity.Id).Start()) { // lose async context on purpose - await Task.Delay(100).ConfigureAwait(false); + await Task.Delay(100); ProfilingSession? profiler2 = profilerFactory(); Assert.NotSame(profiler0, profiler2); diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/AspNetParentSpanCorrectorTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/AspNetParentSpanCorrectorTests.netfx.cs index d1f22c38b8..63113a4f8d 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/AspNetParentSpanCorrectorTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/AspNetParentSpanCorrectorTests.netfx.cs @@ -37,6 +37,8 @@ public void IncomingRequestHeadersAreOverwrittenWithAspNetParent() Assert.Contains(aspNetActivity.TraceId.ToString(), headerVal); Assert.Contains(aspNetActivity.SpanId.ToString(), headerVal); } + + WcfInstrumentationActivitySource.Options = null; } private class FakeHttpContext diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForHttpTests.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForHttpTests.cs index c5f48d326c..b52bf865ca 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForHttpTests.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForHttpTests.cs @@ -199,15 +199,13 @@ public async Task OutgoingRequestInstrumentationTest( { await client.ExecuteWithEmptyActionNameAsync( new ServiceRequest( - payload: "Hello Open Telemetry!")) - .ConfigureAwait(false); + payload: "Hello Open Telemetry!")); } else { await client.ExecuteAsync( new ServiceRequest( - payload: "Hello Open Telemetry!")) - .ConfigureAwait(false); + payload: "Hello Open Telemetry!")); } } finally @@ -295,7 +293,7 @@ await client.ExecuteAsync( } [Fact] - public async void ActivitiesHaveCorrectParentTest() + public async Task ActivitiesHaveCorrectParentTest() { var testSource = new ActivitySource("TestSource"); @@ -348,7 +346,7 @@ public async void ActivitiesHaveCorrectParentTest() } [Fact] - public async void ErrorsAreHandledProperlyTest() + public async Task ErrorsAreHandledProperlyTest() { var testSource = new ActivitySource("TestSource"); diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForTcpTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForTcpTests.netfx.cs index f2b2a2612c..f48f622724 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForTcpTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForTcpTests.netfx.cs @@ -112,15 +112,13 @@ public async Task OutgoingRequestInstrumentationTest( { await client.ExecuteWithEmptyActionNameAsync( new ServiceRequest( - payload: "Hello Open Telemetry!")) - .ConfigureAwait(false); + payload: "Hello Open Telemetry!")); } else { await client.ExecuteAsync( new ServiceRequest( - payload: "Hello Open Telemetry!")) - .ConfigureAwait(false); + payload: "Hello Open Telemetry!")); } } finally @@ -209,7 +207,7 @@ await client.ExecuteAsync( } [Fact] - public async void ActivitiesHaveCorrectParentTest() + public async Task ActivitiesHaveCorrectParentTest() { var testSource = new ActivitySource("TestSource"); @@ -262,7 +260,7 @@ public async void ActivitiesHaveCorrectParentTest() } [Fact] - public async void ErrorsAreHandledProperlyTest() + public async Task ErrorsAreHandledProperlyTest() { var testSource = new ActivitySource("TestSource"); @@ -329,7 +327,7 @@ public async void ErrorsAreHandledProperlyTest() } [Fact] - public async void OrphanedTelemetryTimesOut() + public async Task OrphanedTelemetryTimesOut() { var stoppedActivities = new List(); var tracerProvider = Sdk.CreateTracerProviderBuilder() @@ -377,7 +375,7 @@ public async void OrphanedTelemetryTimesOut() } [Fact] - public async void DynamicTimeoutValuesAreRespected() + public async Task DynamicTimeoutValuesAreRespected() { var stoppedActivities = new List(); var tracerProvider = Sdk.CreateTracerProviderBuilder() diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorTests.netfx.cs index 6d11e9eb35..0dcd95ad22 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorTests.netfx.cs @@ -153,15 +153,13 @@ public async Task IncomingRequestInstrumentationTest( { await client.ExecuteWithEmptyActionNameAsync( new ServiceRequest( - payload: "Hello Open Telemetry!")) - .ConfigureAwait(false); + payload: "Hello Open Telemetry!")); } else { await client.ExecuteAsync( new ServiceRequest( - payload: "Hello Open Telemetry!")) - .ConfigureAwait(false); + payload: "Hello Open Telemetry!")); } } finally diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryPropagationTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryPropagationTests.netfx.cs index 57df14f307..429c1d59fe 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryPropagationTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryPropagationTests.netfx.cs @@ -82,7 +82,7 @@ public void Dispose() [InlineData("rest", false, false)] public async Task TelemetryContextPropagatesTest( string endpoint, - bool suppressDownstreamInstrumenation = true, + bool suppressDownstreamInstrumentation = true, bool shouldPropagate = true) { var stoppedActivities = new List(); @@ -94,7 +94,7 @@ public async Task TelemetryContextPropagatesTest( ActivitySource.AddActivityListener(activityListener); var tracerProvider = Sdk.CreateTracerProviderBuilder() - .AddWcfInstrumentation(options => options.SuppressDownstreamInstrumentation = suppressDownstreamInstrumenation) + .AddWcfInstrumentation(options => options.SuppressDownstreamInstrumentation = suppressDownstreamInstrumentation) .Build(); var serviceBase = endpoint == "tcp" ? this.serviceBaseUriTcp : this.serviceBaseUriHttp; diff --git a/test/OpenTelemetry.Resources.AWS.Tests/AWSECSDetectorTests.cs b/test/OpenTelemetry.Resources.AWS.Tests/AWSECSDetectorTests.cs index adf8ff8437..b585a32250 100644 --- a/test/OpenTelemetry.Resources.AWS.Tests/AWSECSDetectorTests.cs +++ b/test/OpenTelemetry.Resources.AWS.Tests/AWSECSDetectorTests.cs @@ -61,7 +61,7 @@ public void TestEcsMetadataV3() } [Fact] - public async void TestEcsMetadataV4Ec2() + public async Task TestEcsMetadataV4Ec2() { var source = new CancellationTokenSource(); var token = source.Token; @@ -92,7 +92,7 @@ public async void TestEcsMetadataV4Ec2() } [Fact] - public async void TestEcsMetadataV4Fargate() + public async Task TestEcsMetadataV4Fargate() { var source = new CancellationTokenSource(); var token = source.Token; diff --git a/test/OpenTelemetry.Sampler.AWS.Tests/TestAWSXRaySamplerClient.cs b/test/OpenTelemetry.Sampler.AWS.Tests/TestAWSXRaySamplerClient.cs index bbec7fefec..e688d30539 100644 --- a/test/OpenTelemetry.Sampler.AWS.Tests/TestAWSXRaySamplerClient.cs +++ b/test/OpenTelemetry.Sampler.AWS.Tests/TestAWSXRaySamplerClient.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Threading.Tasks; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; using WireMock.Server; @@ -30,14 +31,11 @@ public void Dispose() } [Fact] - public void TestGetSamplingRules() + public async Task TestGetSamplingRules() { this.CreateResponse("/GetSamplingRules", "Data/GetSamplingRulesResponse.json"); - var responseTask = this.client.GetSamplingRules(); - responseTask.Wait(); - - List rules = responseTask.Result; + var rules = await this.client.GetSamplingRules(); Assert.Equal(3, rules.Count); @@ -81,23 +79,20 @@ public void TestGetSamplingRules() } [Fact] - public void TestGetSamplingRulesMalformed() + public async Task TestGetSamplingRulesMalformed() { this.mockServer .Given(Request.Create().WithPath("/GetSamplingRules").UsingPost()) .RespondWith( Response.Create().WithStatusCode(200).WithHeader("Content-Type", "application/json").WithBody("notJson")); - var responseTask = this.client.GetSamplingRules(); - responseTask.Wait(); - - List rules = responseTask.Result; + List rules = await this.client.GetSamplingRules(); Assert.Empty(rules); } [Fact] - public void TestGetSamplingTargets() + public async Task TestGetSamplingTargets() { TestClock clock = new TestClock(); @@ -128,10 +123,8 @@ public void TestGetSamplingTargets() clock.ToDouble(clock.Now())), }); - var responseTask = this.client.GetSamplingTargets(request); - responseTask.Wait(); - - GetSamplingTargetsResponse targetsResponse = responseTask.Result!; + var targetsResponse = await this.client.GetSamplingTargets(request); + Assert.NotNull(targetsResponse); Assert.Equal(2, targetsResponse.SamplingTargetDocuments.Count); Assert.Single(targetsResponse.UnprocessedStatistics); @@ -154,7 +147,7 @@ public void TestGetSamplingTargets() } [Fact] - public void TestGetSamplingTargetsWithMalformed() + public async Task TestGetSamplingTargetsWithMalformed() { TestClock clock = new TestClock(); this.mockServer @@ -173,10 +166,7 @@ public void TestGetSamplingTargetsWithMalformed() clock.ToDouble(clock.Now())), }); - var responseTask = this.client.GetSamplingTargets(request); - responseTask.Wait(); - - GetSamplingTargetsResponse? targetsResponse = responseTask.Result; + var targetsResponse = await this.client.GetSamplingTargets(request); Assert.Null(targetsResponse); } diff --git a/test/OpenTelemetry.Sampler.AWS.Tests/TestMatcher.cs b/test/OpenTelemetry.Sampler.AWS.Tests/TestMatcher.cs index 9c70983e7c..7ce3628e4f 100644 --- a/test/OpenTelemetry.Sampler.AWS.Tests/TestMatcher.cs +++ b/test/OpenTelemetry.Sampler.AWS.Tests/TestMatcher.cs @@ -19,7 +19,7 @@ public class TestMatcher [InlineData("HelloWorld", "Hell?W*d")] [InlineData("Hello.World", "*.World")] [InlineData("Bye.World", "*.World")] - public void TestWildcardMatch(string input, string pattern) + public void TestWildcardMatch(string? input, string pattern) { Assert.True(Matcher.WildcardMatch(input, pattern)); } @@ -27,7 +27,7 @@ public void TestWildcardMatch(string input, string pattern) [Theory] [InlineData(null, "Hello*")] [InlineData("HelloWorld", null)] - public void TestWildcardDoesNotMatch(string input, string pattern) + public void TestWildcardDoesNotMatch(string? input, string? pattern) { Assert.False(Matcher.WildcardMatch(input, pattern)); } From 4ade0e24615184d3f56999b3a62a859068fc51f8 Mon Sep 17 00:00:00 2001 From: yiranw Date: Tue, 11 Jun 2024 21:56:41 -0700 Subject: [PATCH 5/6] [Instrumentation.AWS] Update AWS SDK Activity Tags (#1857) (#1865) --- src/OpenTelemetry.Instrumentation.AWS/CHANGELOG.md | 4 ++++ .../Implementation/AWSSemanticConventions.cs | 4 ++++ .../Implementation/AWSTracingPipelineHandler.cs | 5 +++++ .../TestAWSClientInstrumentation.cs | 6 ++++++ 4 files changed, 19 insertions(+) diff --git a/src/OpenTelemetry.Instrumentation.AWS/CHANGELOG.md b/src/OpenTelemetry.Instrumentation.AWS/CHANGELOG.md index d1433f2e15..a8de77fcd7 100644 --- a/src/OpenTelemetry.Instrumentation.AWS/CHANGELOG.md +++ b/src/OpenTelemetry.Instrumentation.AWS/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +* Added `rpc.system`, `rpc.service`, and `rpc.method` to activity tags based on + [semantic convention v1.26.0](https://github.com/open-telemetry/semantic-conventions/blob/v1.26.0/docs/cloud-providers/aws-sdk.md#common-attributes). + ([#1865](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/1865)) + ## 1.1.0-beta.4 Released 2024-Apr-12 diff --git a/src/OpenTelemetry.Instrumentation.AWS/Implementation/AWSSemanticConventions.cs b/src/OpenTelemetry.Instrumentation.AWS/Implementation/AWSSemanticConventions.cs index dc5bbda9ad..ce6f1fe325 100644 --- a/src/OpenTelemetry.Instrumentation.AWS/Implementation/AWSSemanticConventions.cs +++ b/src/OpenTelemetry.Instrumentation.AWS/Implementation/AWSSemanticConventions.cs @@ -17,4 +17,8 @@ internal static class AWSSemanticConventions public const string AttributeHttpResponseContentLength = "http.response_content_length"; public const string AttributeValueDynamoDb = "dynamodb"; + + public const string AttributeValueRPCSystem = "rpc.system"; + public const string AttributeValueRPCService = "rpc.service"; + public const string AttributeValueRPCMethod = "rpc.method"; } diff --git a/src/OpenTelemetry.Instrumentation.AWS/Implementation/AWSTracingPipelineHandler.cs b/src/OpenTelemetry.Instrumentation.AWS/Implementation/AWSTracingPipelineHandler.cs index 84cbc01490..a58298b79a 100644 --- a/src/OpenTelemetry.Instrumentation.AWS/Implementation/AWSTracingPipelineHandler.cs +++ b/src/OpenTelemetry.Instrumentation.AWS/Implementation/AWSTracingPipelineHandler.cs @@ -233,6 +233,11 @@ private static string FetchRequestId(IRequestContext requestContext, IResponseCo { activity.SetTag(AWSSemanticConventions.AttributeAWSServiceName, service); activity.SetTag(AWSSemanticConventions.AttributeAWSOperationName, operation); + + // Follow: https://github.com/open-telemetry/semantic-conventions/blob/v1.26.0/docs/cloud-providers/aws-sdk.md#common-attributes + activity.SetTag(AWSSemanticConventions.AttributeValueRPCSystem, "aws-api"); + activity.SetTag(AWSSemanticConventions.AttributeValueRPCService, service); + activity.SetTag(AWSSemanticConventions.AttributeValueRPCMethod, operation); var client = executionContext.RequestContext.ClientConfig; if (client != null) { diff --git a/test/OpenTelemetry.Instrumentation.AWS.Tests/TestAWSClientInstrumentation.cs b/test/OpenTelemetry.Instrumentation.AWS.Tests/TestAWSClientInstrumentation.cs index 4caa6339ad..a89dee8240 100644 --- a/test/OpenTelemetry.Instrumentation.AWS.Tests/TestAWSClientInstrumentation.cs +++ b/test/OpenTelemetry.Instrumentation.AWS.Tests/TestAWSClientInstrumentation.cs @@ -217,6 +217,9 @@ private void ValidateDynamoActivityTags(Activity ddb_activity) Assert.Equal("us-east-1", Utils.GetTagValue(ddb_activity, "aws.region")); Assert.Equal("SampleProduct", Utils.GetTagValue(ddb_activity, "aws.table_name")); Assert.Equal("dynamodb", Utils.GetTagValue(ddb_activity, "db.system")); + Assert.Equal("aws-api", Utils.GetTagValue(ddb_activity, "rpc.system")); + Assert.Equal("DynamoDB", Utils.GetTagValue(ddb_activity, "rpc.service")); + Assert.Equal("Scan", Utils.GetTagValue(ddb_activity, "rpc.method")); } private void ValidateSqsActivityTags(Activity sqs_activity) @@ -226,5 +229,8 @@ private void ValidateSqsActivityTags(Activity sqs_activity) Assert.Equal("SendMessage", Utils.GetTagValue(sqs_activity, "aws.operation")); Assert.Equal("us-east-1", Utils.GetTagValue(sqs_activity, "aws.region")); Assert.Equal("https://sqs.us-east-1.amazonaws.com/123456789/MyTestQueue", Utils.GetTagValue(sqs_activity, "aws.queue_url")); + Assert.Equal("aws-api", Utils.GetTagValue(sqs_activity, "rpc.system")); + Assert.Equal("SQS", Utils.GetTagValue(sqs_activity, "rpc.service")); + Assert.Equal("SendMessage", Utils.GetTagValue(sqs_activity, "rpc.method")); } } From 269a99f94cbde8f97b47af51caa3e5c16d82b14f Mon Sep 17 00:00:00 2001 From: Mikel Blanchard Date: Wed, 12 Jun 2024 10:01:23 -0700 Subject: [PATCH 6/6] [repo] Automation improvements (#1873) --- .github/workflows/add-labels.yml | 42 ++++++- .github/workflows/automation.yml | 2 +- .github/workflows/prepare-release.yml | 4 +- .github/workflows/publish-packages.yml | 14 ++- build/scripts/add-labels.ps1 | 12 -- build/scripts/add-labels.psm1 | 148 +++++++++++++++++++++++++ build/scripts/post-release.psm1 | 17 +-- build/scripts/prepare-release.psm1 | 10 +- opentelemetry-dotnet-contrib.sln | 2 +- 9 files changed, 215 insertions(+), 36 deletions(-) delete mode 100644 build/scripts/add-labels.ps1 create mode 100644 build/scripts/add-labels.psm1 diff --git a/.github/workflows/add-labels.yml b/.github/workflows/add-labels.yml index 9c040eaaab..23137c1aa8 100644 --- a/.github/workflows/add-labels.yml +++ b/.github/workflows/add-labels.yml @@ -1,16 +1,21 @@ -name: 'Add labels for component found in bug issue descriptions' +name: 'Add labels to issues and pull requests' on: issues: - types: [opened] + types: [ opened ] + + pull_request_target: + branches: [ 'main*', 'instrumentation*', 'exporter*', 'extensions*' ] permissions: issues: write + pull-requests: write jobs: - add-labels: - if: ${{ !github.event.issue.pull_request }} + add-labels-on-issues: + if: github.event_name == 'issues' && !github.event.issue.pull_request runs-on: ubuntu-latest + steps: - name: check out code uses: actions/checkout@v4 @@ -18,8 +23,33 @@ jobs: - name: Add labels for component found in bug issue descriptions shell: pwsh run: | - .\build\scripts\add-labels.ps1 -issueNumber $env:ISSUE_NUMBER -issueBody $env:ISSUE_BODY + Import-Module .\build\scripts\add-labels.psm1 + + AddLabelsOnIssuesForComponentFoundInBody ` + -issueNumber ${{ github.event.issue.number }} ` + -issueBody $env:ISSUE_BODY env: GH_TOKEN: ${{ github.token }} - ISSUE_NUMBER: ${{ github.event.issue.number }} ISSUE_BODY: ${{ github.event.issue.body }} + + add-labels-on-pull-requests: + if: github.event_name == 'pull_request_target' + + runs-on: ubuntu-latest + + steps: + - name: check out code + uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} # Note: Do not run on the PR branch we want to execute add-labels.psm1 from main on the base repo only because pull_request_target can see secrets + + - name: Add labels for files changed on pull requests + shell: pwsh + run: | + Import-Module .\build\scripts\add-labels.psm1 + + AddLabelsOnPullRequestsBasedOnFilesChanged ` + -pullRequestNumber ${{ github.event.pull_request.number }} ` + -labelPackagePrefix 'comp:' + env: + GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml index e85a3720ab..1385474892 100644 --- a/.github/workflows/automation.yml +++ b/.github/workflows/automation.yml @@ -13,7 +13,7 @@ on: value: ${{ vars.AUTOMATION_EMAIL }} secrets: OPENTELEMETRYBOT_GITHUB_TOKEN: - required: true + required: false jobs: resolve-automation: diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index 0098bc82ed..eea3b61943 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -106,7 +106,7 @@ jobs: && github.event.action == 'closed' && github.event.pull_request.user.login == needs.automation.outputs.username && github.event.pull_request.merged == true - && startsWith(github.event.pull_request.title, '[repo] Prepare release ') + && startsWith(github.event.pull_request.title, '[release] Prepare release ') && needs.automation.outputs.enabled env: @@ -139,7 +139,7 @@ jobs: && github.event.issue.locked == true && github.event.comment.user.login != needs.automation.outputs.username && contains(github.event.comment.body, '/CreateReleaseTag') - && startsWith(github.event.issue.title, '[repo] Prepare release ') + && startsWith(github.event.issue.title, '[release] Prepare release ') && github.event.issue.pull_request.merged_at && needs.automation.outputs.enabled diff --git a/.github/workflows/publish-packages.yml b/.github/workflows/publish-packages.yml index 84d492fcff..f9cae34b57 100644 --- a/.github/workflows/publish-packages.yml +++ b/.github/workflows/publish-packages.yml @@ -26,6 +26,7 @@ jobs: outputs: artifact-url: ${{ steps.upload-artifacts.outputs.artifact-url }} + artifact-id: ${{ steps.upload-artifacts.outputs.artifact-id }} steps: - uses: actions/checkout@v4 @@ -120,6 +121,16 @@ jobs: with: token: ${{ secrets[needs.automation.outputs.token-secret-name] }} + - name: Download Artifacts + run: | + curl \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token ${{ github.token }}" \ + -L \ + -o '${{ github.workspace }}/artifacts/${{ github.ref_name }}-packages.zip' \ + --create-dirs \ + "https://api.github.com/repos/${{ github.repository }}/actions/artifacts/${{ needs.build-pack-publish.outputs.artifact-id }}/zip" + - name: Create GitHub Release if: github.ref_type == 'tag' shell: pwsh @@ -128,7 +139,8 @@ jobs: CreateRelease ` -gitRepository '${{ github.repository }}' ` - -tag '${{ github.ref_name }}' + -tag '${{ github.ref_name }}' ` + -releaseFiles '${{ github.workspace }}/artifacts/${{ github.ref_name }}-packages.zip#Packages' - name: Post notice when packages are ready shell: pwsh diff --git a/build/scripts/add-labels.ps1 b/build/scripts/add-labels.ps1 deleted file mode 100644 index 7d72236c11..0000000000 --- a/build/scripts/add-labels.ps1 +++ /dev/null @@ -1,12 +0,0 @@ -param( - [Parameter(Mandatory=$true)][int]$issueNumber, - [Parameter(Mandatory=$true)][string]$issueBody -) - -$match = [regex]::Match($issueBody, '^[#]+ Component\s*OpenTelemetry\.((?:.|\w+)+)') -if ($match.Success -eq $false) -{ - Return -} - -gh issue edit $issueNumber --add-label $("comp:" + $match.Groups[1].Value.ToLower()) diff --git a/build/scripts/add-labels.psm1 b/build/scripts/add-labels.psm1 new file mode 100644 index 0000000000..a064b150be --- /dev/null +++ b/build/scripts/add-labels.psm1 @@ -0,0 +1,148 @@ +function AddLabelsOnIssuesForComponentFoundInBody { + param( + [Parameter(Mandatory=$true)][int]$issueNumber, + [Parameter(Mandatory=$true)][string]$issueBody + ) + + $match = [regex]::Match($issueBody, '^[#]+ Component\s*OpenTelemetry\.((?:.|\w+)+)') + if ($match.Success -eq $false) + { + Return + } + + gh issue edit $issueNumber --add-label $("comp:" + $match.Groups[1].Value.ToLower()) +} + +Export-ModuleMember -Function AddLabelsOnIssuesForComponentFoundInBody + +function AddLabelsOnPullRequestsBasedOnFilesChanged { + param( + [Parameter(Mandatory=$true)][int]$pullRequestNumber, + [Parameter(Mandatory=$true)][string]$labelPackagePrefix # 'pkg:' on main repo, 'comp:' on contrib repo + ) + + # Note: This function is intended to work on main repo and on contrib. Please + # keep them in sync. + + $repoLabels = gh label list --json name,id | ConvertFrom-Json + + $filesChangedOnPullRequest = gh pr diff $pullRequestNumber --name-only + + $labelsOnPullRequest = (gh pr view $pullRequestNumber --json labels | ConvertFrom-Json).labels + + $visitedProjects = New-Object System.Collections.Generic.HashSet[string] + $labelsToAdd = New-Object System.Collections.Generic.HashSet[string] + $labelsToRemove = New-Object System.Collections.Generic.HashSet[string] + + # Note: perf label may be added but it is kind of a guess so we don't remove + # it automatically in order to also allow manual inclusion after reviewing files + $managedLabels = 'infra', 'documentation', 'dependencies' + $rootInfraFiles = 'global.json', 'NuGet.config', 'codeowners' + $documentationFiles = 'readme.md', 'contributing.md', 'releasing.md', 'versioning.md' + + foreach ($fileChanged in $filesChangedOnPullRequest) + { + $fileChanged = $fileChanged.ToLower() + $fullFileName = [System.IO.Path]::GetFileName($fileChanged) + $fileName = [System.IO.Path]::GetFileNameWithoutExtension($fileChanged) + $fileExtension = [System.IO.Path]::GetExtension($fileChanged) + + if ($fileChanged.StartsWith('src/') -or $fileChanged.StartsWith('test/')) + { + $match = [regex]::Match($fileChanged, '^(?:(?:src)|(?:test))\/(.*?)\/.+$') + if ($match.Success -eq $false) + { + continue + } + $rawProjectName = $match.Groups[1].Value + if ($rawProjectName.Contains(".benchmarks") -or $rawProjectName.Contains(".stress")) + { + $added = $labelsToAdd.Add("perf") + } + + $projectName = $rawProjectName.Replace(".tests", "").Replace(".benchmarks", "").Replace(".stress", "") + if ($visitedProjects.Contains($projectName)) + { + continue + } + + $added = $visitedProjects.Add($projectName); + + foreach ($repoLabel in $repoLabels) + { + if ($repoLabel.name.StartsWith($labelPackagePrefix)) + { + $package = $repoLabel.name.Substring($labelPackagePrefix.Length).ToLower() + if ($package.StartsWith('opentelemetry') -eq $false) + { + # Note: On contrib labels don't have "OpenTelemetry." prefix + $package = 'opentelemetry.' + $package + } + if ($package -eq $projectName) + { + $added = $labelsToAdd.Add($repoLabel.name) + break + } + } + } + } + + if ($documentationFiles.Contains($fullFileName) -or + $fileChanged.StartsWith('docs/') -or + $fileChanged.StartsWith('examples/')) + { + $added = $labelsToAdd.Add("documentation") + } + + if ($fileChanged.StartsWith('build/') -or + $fileChanged.StartsWith('.github/') -or + $rootInfraFiles.Contains($fullFileName) -or + $fileExtension -eq ".props" -or + $fileExtension -eq ".targets" -or + $fileChanged.StartsWith('test\openTelemetry.aotcompatibility')) + { + $added = $labelsToAdd.Add("infra") + } + + if ($fileChanged.StartsWith('test\benchmarks')) + { + $added = $labelsToAdd.Add("perf") + } + + if ($fullFileName -eq 'directory.packages.props') + { + $added = $labelsToAdd.Add("dependencies") + } + } + + foreach ($labelOnPullRequest in $labelsOnPullRequest) + { + if ($labelsToAdd.Contains($labelOnPullRequest.name)) + { + $removed = $labelsToAdd.Remove($labelOnPullRequest.name) + } + elseif ($labelOnPullRequest.name.StartsWith($labelPackagePrefix) -or + $managedLabels.Contains($labelOnPullRequest.name)) + { + $added = $labelsToRemove.Add($labelOnPullRequest.name) + } + } + + if ($labelsToAdd.Count -gt 0) + { + foreach ($label in $labelsToAdd) + { + gh pr edit $pullRequestNumber --add-label $label + } + } + + if ($labelsToRemove.Count -gt 0) + { + foreach ($label in $labelsToRemove) + { + gh pr edit $pullRequestNumber --remove-label $label + } + } +} + +Export-ModuleMember -Function AddLabelsOnPullRequestsBasedOnFilesChanged diff --git a/build/scripts/post-release.psm1 b/build/scripts/post-release.psm1 index ff74519816..5cdf7b5d85 100644 --- a/build/scripts/post-release.psm1 +++ b/build/scripts/post-release.psm1 @@ -1,7 +1,8 @@ function CreateRelease { param( [Parameter(Mandatory=$true)][string]$gitRepository, - [Parameter(Mandatory=$true)][string]$tag + [Parameter(Mandatory=$true)][string]$tag, + [Parameter()][string]$releaseFiles ) $match = [regex]::Match($tag, '^(.*?-)(.*)$') @@ -69,7 +70,7 @@ $content if ($version -match '-alpha' -or $version -match '-beta' -or $version -match '-rc') { - gh release create $tag ` + gh release create $tag $releaseFiles ` --title $tag ` --verify-tag ` --notes $notes ` @@ -77,7 +78,7 @@ $content } else { - gh release create $tag ` + gh release create $tag $releaseFiles ` --title $tag ` --verify-tag ` --notes $notes ` @@ -106,7 +107,7 @@ function TryPostPackagesReadyNoticeOnPrepareReleasePullRequest { foreach ($pr in $prListResponse) { - if ($pr.author.login -ne $botUserName -or $pr.title -ne "[repo] Prepare release $tag") + if ($pr.author.login -ne $botUserName -or $pr.title -ne "[release] Prepare release $tag") { continue } @@ -249,11 +250,11 @@ Merge once packages are available on NuGet and the build passes. "@ gh pr create ` - --title "[repo] $tagPrefix stable release $version updates" ` + --title "[release] $tagPrefix stable release $version updates" ` --body $body ` --base $targetBranch ` --head $branch ` - --label infra + --label release } Export-ModuleMember -Function CreatePackageValidationBaselineVersionUpdatePullRequest @@ -362,11 +363,11 @@ Merge once packages are available on NuGet and the build passes. "@ $createPullRequestResponse = gh pr create ` - --title "[repo] Core release $version updates" ` + --title "[release] Core release $version updates" ` --body $body ` --base $targetBranch ` --head $branch ` - --label infra + --label release $match = [regex]::Match($createPullRequestResponse, "\/pull\/(.*)$") if ($match.Success -eq $false) diff --git a/build/scripts/prepare-release.psm1 b/build/scripts/prepare-release.psm1 index 0db3cca47e..f567987878 100644 --- a/build/scripts/prepare-release.psm1 +++ b/build/scripts/prepare-release.psm1 @@ -68,11 +68,11 @@ Note: This PR was opened automatically by the [prepare release workflow](https:/ } gh pr create ` - --title "[repo] Prepare release $tag" ` + --title "[release] Prepare release $tag" ` --body $body ` --base $targetBranch ` --head $branch ` - --label infra + --label release } Export-ModuleMember -Function CreatePullRequestToUpdateChangelogsAndPublicApis @@ -91,7 +91,7 @@ function LockPullRequestAndPostNoticeToCreateReleaseTag { throw 'PR author was unexpected' } - $match = [regex]::Match($prViewResponse.title, '^\[repo\] Prepare release (.*)$') + $match = [regex]::Match($prViewResponse.title, '^\[release\] Prepare release (.*)$') if ($match.Success -eq $false) { throw 'Could not parse tag from PR title' @@ -109,7 +109,7 @@ function LockPullRequestAndPostNoticeToCreateReleaseTag { @" I noticed this PR was merged. -Post a comment with "/CreateReleaseTag" in the body if you would like me to create the release tag ``$tag`` for [the merge commit](https://github.com/$gitRepository/commit/$commit) and then trigger the package workflow. +Post a comment with "/CreateReleaseTag" in the body if you would like me to create the release tag ``$tag`` for [the merge commit](https://github.com/$gitRepository/commit/$commit) which will trigger the package workflow. "@ gh pr comment $pullRequestNumber --body $body @@ -135,7 +135,7 @@ function CreateReleaseTagAndPostNoticeOnPullRequest { throw 'PR author was unexpected' } - $match = [regex]::Match($prViewResponse.title, '^\[repo\] Prepare release (.*)$') + $match = [regex]::Match($prViewResponse.title, '^\[release\] Prepare release (.*)$') if ($match.Success -eq $false) { throw 'Could not parse tag from PR title' diff --git a/opentelemetry-dotnet-contrib.sln b/opentelemetry-dotnet-contrib.sln index 2d80d5dceb..f0a4560077 100644 --- a/opentelemetry-dotnet-contrib.sln +++ b/opentelemetry-dotnet-contrib.sln @@ -361,7 +361,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Shared", "Shared", "{70CA77 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "scripts", "scripts", "{45D29DAA-0DB9-4808-B879-1AECC37EF366}" ProjectSection(SolutionItems) = preProject - build\scripts\add-labels.ps1 = build\scripts\add-labels.ps1 + build\scripts\add-labels.psm1 = build\scripts\add-labels.psm1 build\scripts\build.psm1 = build\scripts\build.psm1 build\scripts\finalize-publicapi.ps1 = build\scripts\finalize-publicapi.ps1 build\scripts\post-release.psm1 = build\scripts\post-release.psm1