Skip to content

Commit 13ed63a

Browse files
authored
[Exporter.OpenTelemetryProtocol] enable analysis (#6251)
1 parent 0252f6c commit 13ed63a

23 files changed

+62
-22
lines changed

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Builder/OpenTelemetryBuilderOtlpExporterExtensions.cs

+4
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ public static class OpenTelemetryBuilderOtlpExporterExtensions
3636
/// <returns>Supplied <see cref="IOpenTelemetryBuilder"/> for chaining calls.</returns>
3737
public static IOpenTelemetryBuilder UseOtlpExporter(
3838
this IOpenTelemetryBuilder builder)
39+
#pragma warning disable CA1062 // Validate arguments of public methods
3940
=> UseOtlpExporter(builder, name: null, configuration: null, configure: null);
41+
#pragma warning restore CA1062 // Validate arguments of public methods
4042

4143
/// <summary><inheritdoc cref="UseOtlpExporter(IOpenTelemetryBuilder)"/></summary>
4244
/// <remarks><inheritdoc cref="UseOtlpExporter(IOpenTelemetryBuilder)" path="/remarks"/></remarks>
@@ -56,7 +58,9 @@ public static IOpenTelemetryBuilder UseOtlpExporter(
5658
{
5759
Guard.ThrowIfNull(baseUrl);
5860

61+
#pragma warning disable CA1062 // Validate arguments of public methods
5962
return UseOtlpExporter(builder, name: null, configuration: null, configure: otlpBuilder =>
63+
#pragma warning restore CA1062 // Validate arguments of public methods
6064
{
6165
otlpBuilder.ConfigureDefaultExporterOptions(o =>
6266
{
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[*.cs]
2+
generated_code = true

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/Grpc/GrpcProtocolHelpers.cs

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Copyright The OpenTelemetry Authors
22
// SPDX-License-Identifier: Apache-2.0
33

4+
#nullable enable
5+
46
// Copyright 2019 The gRPC Authors
57
//
68
// Licensed under the Apache License, Version 2.0 (the "License");

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/Grpc/GrpcStatusDeserializer.cs

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Copyright The OpenTelemetry Authors
22
// SPDX-License-Identifier: Apache-2.0
33

4+
#nullable enable
5+
46
using System.Text;
57

68
namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClient.Grpc;

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/Grpc/Status.cs

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Copyright The OpenTelemetry Authors
22
// SPDX-License-Identifier: Apache-2.0
33

4+
#nullable enable
5+
46
// Copyright 2015 gRPC authors.
57
//
68
// Licensed under the Apache License, Version 2.0 (the "License");

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/Grpc/StatusCode.cs

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Copyright The OpenTelemetry Authors
22
// SPDX-License-Identifier: Apache-2.0
33

4+
#nullable enable
5+
46
// Copyright 2015 gRPC authors.
57
//
68
// Licensed under the Apache License, Version 2.0 (the "License");

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/Grpc/TrailingHeadersHelpers.cs

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Copyright The OpenTelemetry Authors
22
// SPDX-License-Identifier: Apache-2.0
33

4+
#nullable enable
5+
46
// Copyright 2019 The gRPC Authors
57
//
68
// Licensed under the Apache License, Version 2.0 (the "License");

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/OtlpExportClient.cs

+2-9
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,12 @@ internal abstract class OtlpExportClient : IExportClient
1414
private static readonly Version Http2RequestVersion = new(2, 0);
1515

1616
#if NET
17-
private static readonly bool SynchronousSendSupportedByCurrentPlatform;
18-
19-
static OtlpExportClient()
20-
{
21-
#if NET
22-
// See: https://github.com/dotnet/runtime/blob/280f2a0c60ce0378b8db49adc0eecc463d00fe5d/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs#L767
23-
SynchronousSendSupportedByCurrentPlatform = !OperatingSystem.IsAndroid()
17+
// See: https://github.com/dotnet/runtime/blob/280f2a0c60ce0378b8db49adc0eecc463d00fe5d/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs#L767
18+
private static readonly bool SynchronousSendSupportedByCurrentPlatform = !OperatingSystem.IsAndroid()
2419
&& !OperatingSystem.IsIOS()
2520
&& !OperatingSystem.IsTvOS()
2621
&& !OperatingSystem.IsBrowser();
2722
#endif
28-
}
29-
#endif
3023

3124
protected OtlpExportClient(OtlpExporterOptions options, HttpClient httpClient, string signalPath)
3225
{

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/OtlpGrpcExportClient.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ public override ExportClientResponse SendExportRequest(byte[] buffer, int conten
4646
var trailingHeaders = httpResponse.TrailingHeaders();
4747
Status status = GrpcProtocolHelpers.GetResponseStatus(httpResponse, trailingHeaders);
4848

49-
if (status.Detail.Equals(Status.NoReplyDetailMessage))
49+
if (status.Detail.Equals(Status.NoReplyDetailMessage, StringComparison.Ordinal))
5050
{
5151
#if NET
5252
using var responseStream = httpResponse.Content.ReadAsStream(cancellationToken);

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/OtlpRetry.cs

+8-6
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33

44
using System.Net;
55
using System.Net.Http.Headers;
6+
#if NET
7+
using System.Security.Cryptography;
8+
#endif
69
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClient.Grpc;
710

811
namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClient;
@@ -40,13 +43,12 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClie
4043
/// </summary>
4144
internal static class OtlpRetry
4245
{
43-
public const string GrpcStatusDetailsHeader = "grpc-status-details-bin";
4446
public const int InitialBackoffMilliseconds = 1000;
4547
private const int MaxBackoffMilliseconds = 5000;
4648
private const double BackoffMultiplier = 1.5;
4749

4850
#if !NET
49-
private static readonly Random Random = new Random();
51+
private static readonly Random Random = new();
5052
#endif
5153

5254
public static bool TryGetHttpRetryResult(ExportClientHttpResponse response, int retryDelayInMilliSeconds, out RetryResult retryResult)
@@ -156,9 +158,7 @@ private static bool TryGetRetryResult<TStatusCode, TCarrier>(TStatusCode statusC
156158
return false;
157159
}
158160

159-
var delayDuration = throttleDelay.HasValue
160-
? throttleDelay.Value
161-
: TimeSpan.FromMilliseconds(GetRandomNumber(0, nextRetryDelayMilliseconds));
161+
var delayDuration = throttleDelay ?? TimeSpan.FromMilliseconds(GetRandomNumber(0, nextRetryDelayMilliseconds));
162162

163163
if (deadline.HasValue && IsDeadlineExceeded(deadline + delayDuration))
164164
{
@@ -246,13 +246,15 @@ private static bool IsHttpStatusCodeRetryable(HttpStatusCode statusCode, bool ha
246246
private static int GetRandomNumber(int min, int max)
247247
{
248248
#if NET
249-
return Random.Shared.Next(min, max);
249+
return RandomNumberGenerator.GetInt32(min, max);
250250
#else
251251
// TODO: Implement this better to minimize lock contention.
252252
// Consider pulling in Random.Shared implementation.
253253
lock (Random)
254254
{
255+
#pragma warning disable CA5394 // Do not use insecure randomness
255256
return Random.Next(min, max);
257+
#pragma warning restore CA5394 // Do not use insecure randomness
256258
}
257259
#endif
258260
}

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/Serializer/ProtobufOtlpLogSerializer.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ internal static int WriteLogRecord(byte[] buffer, int writePosition, SdkLimitOpt
223223
// Special casing {OriginalFormat}
224224
// See https://github.com/open-telemetry/opentelemetry-dotnet/pull/3182
225225
// for explanation.
226-
if (attribute.Key.Equals("{OriginalFormat}") && !bodyPopulatedFromFormattedMessage)
226+
if (attribute.Key.Equals("{OriginalFormat}", StringComparison.Ordinal) && !bodyPopulatedFromFormattedMessage)
227227
{
228228
otlpTagWriterState.WritePosition = WriteLogRecordBody(otlpTagWriterState.Buffer, otlpTagWriterState.WritePosition, (attribute.Value as string).AsSpan());
229229
isLogRecordBodySet = true;
@@ -270,7 +270,7 @@ static void ProcessScope(LogRecordScope scope, SerializationState state)
270270
{
271271
foreach (var scopeItem in scope)
272272
{
273-
if (scopeItem.Key.Equals("{OriginalFormat}") || string.IsNullOrEmpty(scopeItem.Key))
273+
if (scopeItem.Key.Equals("{OriginalFormat}", StringComparison.Ordinal) || string.IsNullOrEmpty(scopeItem.Key))
274274
{
275275
// Ignore if the scope key is empty.
276276
// Ignore if the scope key is {OriginalFormat}

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/Serializer/ProtobufOtlpMetricSerializer.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ internal static int WriteMetricsData(ref byte[] buffer, int writePosition, Resou
2929
var metricName = metric.MeterName;
3030
if (!scopeMetricsList.TryGetValue(metricName, out var metrics))
3131
{
32-
metrics = metricListPool.Count > 0 ? metricListPool.Pop() : new List<Metric>();
32+
metrics = metricListPool.Count > 0 ? metricListPool.Pop() : [];
3333
scopeMetricsList[metricName] = metrics;
3434
}
3535

@@ -117,7 +117,7 @@ private static int WriteScopeMetric(byte[] buffer, int writePosition, string met
117117
int instrumentationScopeLengthPosition = writePosition;
118118
writePosition += ReserveSizeForLength;
119119

120-
Debug.Assert(metrics.Any(), "Metrics collection is not expected to be empty.");
120+
Debug.Assert(metrics.Count > 0, "Metrics collection is not expected to be empty.");
121121
var meterVersion = metrics[0].MeterVersion;
122122
var meterTags = metrics[0].MeterTags;
123123

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/Serializer/ProtobufSerializer.cs

+2
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,9 @@ internal static int WriteStringWithTag(byte[] buffer, int writePosition, int fie
325325
{
326326
// Note: Validate there is enough space in the buffer to hold the
327327
// string otherwise throw to trigger a resize of the buffer.
328+
#pragma warning disable CA2201 // Do not raise reserved exception types
328329
throw new IndexOutOfRangeException();
330+
#pragma warning restore CA2201 // Do not raise reserved exception types
329331
}
330332

331333
unsafe

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/Transmission/OtlpExporterPersistentStorageTransmissionHandler.cs

+4
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ internal sealed class OtlpExporterPersistentStorageTransmissionHandler : OtlpExp
1919
private bool disposed;
2020

2121
public OtlpExporterPersistentStorageTransmissionHandler(IExportClient exportClient, double timeoutMilliseconds, string storagePath)
22+
#pragma warning disable CA2000 // Dispose objects before losing scope
2223
: this(new FileBlobProvider(storagePath), exportClient, timeoutMilliseconds)
24+
#pragma warning restore CA2000 // Dispose objects before losing scope
2325
{
2426
}
2527

@@ -93,6 +95,8 @@ protected override void Dispose(bool disposing)
9395

9496
this.disposed = true;
9597
}
98+
99+
base.Dispose(disposing);
96100
}
97101

98102
private void RetryStoredRequests()

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OpenTelemetry.Exporter.OpenTelemetryProtocol.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
and https://github.com/dotnet/runtime/issues/92509 -->
1818
<NoWarn>$(NoWarn);SYSLIB1100;SYSLIB1101</NoWarn>
1919
<AllowUnsafeBlocks Condition="'$(TargetFramework)' == 'netstandard2.0' OR '$(TargetFramework)' == '$(NetFrameworkMinimumSupportedVersion)'">true</AllowUnsafeBlocks>
20+
<AnalysisLevel>latest-all</AnalysisLevel>
2021
</PropertyGroup>
2122

2223
<ItemGroup>

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExportProtocol.cs

+2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ namespace OpenTelemetry.Exporter;
66
/// <summary>
77
/// Supported by OTLP exporter protocol types according to the specification https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md.
88
/// </summary>
9+
#pragma warning disable CA1028 // Enum storage should be Int32
910
public enum OtlpExportProtocol : byte
11+
#pragma warning restore CA1028 // Enum storage should be Int32
1012
{
1113
/// <summary>
1214
/// OTLP over gRPC (corresponds to 'grpc' Protocol configuration option). Used as default.

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptionsExtensions.cs

+6-2
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public static THeaders GetHeaders<THeaders>(this OtlpExporterOptions options, Ac
4040
if (commaIndex == -1)
4141
{
4242
pair = headersSpan;
43-
headersSpan = ReadOnlySpan<char>.Empty;
43+
headersSpan = [];
4444
}
4545
else
4646
{
@@ -171,7 +171,11 @@ internal static Uri AppendPathIfNotPresent(this Uri uri, string path)
171171
var absoluteUri = uri.AbsoluteUri;
172172
var separator = string.Empty;
173173

174-
if (absoluteUri.EndsWith("/"))
174+
#if NET || NETSTANDARD2_1_OR_GREATER
175+
if (absoluteUri.EndsWith('/'))
176+
#else
177+
if (absoluteUri.EndsWith("/", StringComparison.Ordinal))
178+
#endif
175179
{
176180
// Endpoint already ends with 'path/'
177181
if (absoluteUri.EndsWith(string.Concat(path, "/"), StringComparison.OrdinalIgnoreCase))

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpLogExporter.cs

+2
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,9 @@ internal OtlpLogExporter(
6969
internal Resource Resource => this.resource ??= this.ParentProvider.GetResource();
7070

7171
/// <inheritdoc/>
72+
#pragma warning disable CA1725 // Parameter names should match base declaration
7273
public override ExportResult Export(in Batch<LogRecord> logRecordBatch)
74+
#pragma warning restore CA1725 // Parameter names should match base declaration
7375
{
7476
// Prevents the exporter's gRPC and HTTP operations from being instrumented.
7577
using var scope = SuppressInstrumentationScope.Begin();

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpLogExporterHelperExtensions.cs

+6
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,9 @@ public static OpenTelemetryLoggerOptions AddOtlpExporter(
5656

5757
var finalOptionsName = name ?? Options.DefaultName;
5858

59+
#pragma warning disable CA1062 // Validate arguments of public methods
5960
return loggerOptions.AddProcessor(sp =>
61+
#pragma warning restore CA1062 // Validate arguments of public methods
6062
{
6163
var exporterOptions = GetOptions(sp, name, finalOptionsName, OtlpExporterOptions.CreateOtlpExporterOptions);
6264

@@ -102,7 +104,9 @@ public static OpenTelemetryLoggerOptions AddOtlpExporter(
102104

103105
var finalOptionsName = name ?? Options.DefaultName;
104106

107+
#pragma warning disable CA1062 // Validate arguments of public methods
105108
return loggerOptions.AddProcessor(sp =>
109+
#pragma warning restore CA1062 // Validate arguments of public methods
106110
{
107111
var exporterOptions = GetOptions(sp, name, finalOptionsName, OtlpExporterOptions.CreateOtlpExporterOptions);
108112

@@ -316,10 +320,12 @@ internal static BaseProcessor<LogRecord> BuildOtlpLogExporter(
316320
* "OtlpLogExporter");
317321
*/
318322

323+
#pragma warning disable CA2000 // Dispose objects before losing scope
319324
BaseExporter<LogRecord> otlpExporter = new OtlpLogExporter(
320325
exporterOptions!,
321326
sdkLimitOptions!,
322327
experimentalOptions!);
328+
#pragma warning restore CA2000 // Dispose objects before losing scope
323329

324330
if (configureExporterInstance != null)
325331
{

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpMetricExporter.cs

+2
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ internal OtlpMetricExporter(
6262
internal Resource Resource => this.resource ??= this.ParentProvider.GetResource();
6363

6464
/// <inheritdoc />
65+
#pragma warning disable CA1725 // Parameter names should match base declaration
6566
public override ExportResult Export(in Batch<Metric> metrics)
67+
#pragma warning restore CA1725 // Parameter names should match base declaration
6668
{
6769
// Prevents the exporter's gRPC and HTTP operations from being instrumented.
6870
using var scope = SuppressInstrumentationScope.Begin();

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpMetricExporterExtensions.cs

+2
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,9 @@ internal static MetricReader BuildOtlpExporterMetricReader(
186186

187187
exporterOptions!.TryEnableIHttpClientFactoryIntegration(serviceProvider!, "OtlpMetricExporter");
188188

189+
#pragma warning disable CA2000 // Dispose objects before losing scope
189190
BaseExporter<Metric> metricExporter = new OtlpMetricExporter(exporterOptions!, experimentalOptions!);
191+
#pragma warning restore CA2000 // Dispose objects before losing scope
190192

191193
if (configureExporterInstance != null)
192194
{

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporter.cs

+2
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,9 @@ internal OtlpTraceExporter(
6565
internal Resource Resource => this.resource ??= this.ParentProvider.GetResource();
6666

6767
/// <inheritdoc/>
68+
#pragma warning disable CA1725 // Parameter names should match base declaration
6869
public override ExportResult Export(in Batch<Activity> activityBatch)
70+
#pragma warning restore CA1725 // Parameter names should match base declaration
6971
{
7072
// Prevents the exporter's gRPC and HTTP operations from being instrumented.
7173
using var scope = SuppressInstrumentationScope.Begin();

src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporterHelperExtensions.cs

+2
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,9 @@ internal static BaseProcessor<Activity> BuildOtlpExporterProcessor(
147147

148148
exporterOptions!.TryEnableIHttpClientFactoryIntegration(serviceProvider!, "OtlpTraceExporter");
149149

150+
#pragma warning disable CA2000 // Dispose objects before losing scope
150151
BaseExporter<Activity> otlpExporter = new OtlpTraceExporter(exporterOptions!, sdkLimitOptions!, experimentalOptions!);
152+
#pragma warning restore CA2000 // Dispose objects before losing scope
151153

152154
if (configureExporterInstance != null)
153155
{

0 commit comments

Comments
 (0)