forked from open-telemetry/opentelemetry-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOtlpExporterOptionsExtensions.cs
More file actions
204 lines (184 loc) · 8.87 KB
/
OtlpExporterOptionsExtensions.cs
File metadata and controls
204 lines (184 loc) · 8.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// <copyright file="OtlpExporterOptionsExtensions.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Net.Http;
using System.Reflection;
using Grpc.Core;
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClient;
using OpenTelemetry.Internal;
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
using Grpc.Net.Client;
#endif
using MetricsOtlpCollector = Opentelemetry.Proto.Collector.Metrics.V1;
using TraceOtlpCollector = Opentelemetry.Proto.Collector.Trace.V1;
namespace OpenTelemetry.Exporter
{
internal static class OtlpExporterOptionsExtensions
{
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
public static GrpcChannel CreateChannel(this OtlpExporterOptions options)
#else
public static Channel CreateChannel(this OtlpExporterOptions options)
#endif
{
if (options.Endpoint.Scheme != Uri.UriSchemeHttp && options.Endpoint.Scheme != Uri.UriSchemeHttps)
{
throw new NotSupportedException($"Endpoint URI scheme ({options.Endpoint.Scheme}) is not supported. Currently only \"http\" and \"https\" are supported.");
}
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
return GrpcChannel.ForAddress(options.Endpoint);
#else
ChannelCredentials channelCredentials;
if (options.Endpoint.Scheme == Uri.UriSchemeHttps)
{
channelCredentials = new SslCredentials();
}
else
{
channelCredentials = ChannelCredentials.Insecure;
}
return new Channel(options.Endpoint.Authority, channelCredentials);
#endif
}
public static Metadata GetMetadataFromHeaders(this OtlpExporterOptions options)
{
return options.GetHeaders<Metadata>((m, k, v) => m.Add(k, v));
}
public static THeaders GetHeaders<THeaders>(this OtlpExporterOptions options, Action<THeaders, string, string> addHeader)
where THeaders : new()
{
var optionHeaders = options.Headers;
var headers = new THeaders();
if (!string.IsNullOrEmpty(optionHeaders))
{
Array.ForEach(
optionHeaders.Split(','),
(pair) =>
{
// Specify the maximum number of substrings to return to 2
// This treats everything that follows the first `=` in the string as the value to be added for the metadata key
var keyValueData = pair.Split(new char[] { '=' }, 2);
if (keyValueData.Length != 2)
{
throw new ArgumentException("Headers provided in an invalid format.");
}
var key = keyValueData[0].Trim();
var value = keyValueData[1].Trim();
addHeader(headers, key, value);
});
}
return headers;
}
public static IExportClient<TraceOtlpCollector.ExportTraceServiceRequest> GetTraceExportClient(this OtlpExporterOptions options) =>
options.Protocol switch
{
OtlpExportProtocol.Grpc => new OtlpGrpcTraceExportClient(options),
OtlpExportProtocol.HttpProtobuf => new OtlpHttpTraceExportClient(
options,
options.HttpClientFactory?.Invoke() ?? throw new InvalidOperationException("OtlpExporterOptions was missing HttpClientFactory or it returned null.")),
_ => throw new NotSupportedException($"Protocol {options.Protocol} is not supported."),
};
public static IExportClient<MetricsOtlpCollector.ExportMetricsServiceRequest> GetMetricsExportClient(this OtlpExporterOptions options) =>
options.Protocol switch
{
OtlpExportProtocol.Grpc => new OtlpGrpcMetricsExportClient(options),
OtlpExportProtocol.HttpProtobuf => new OtlpHttpMetricsExportClient(
options,
options.HttpClientFactory?.Invoke() ?? throw new InvalidOperationException("OtlpExporterOptions was missing HttpClientFactory or it returned null.")),
_ => throw new NotSupportedException($"Protocol {options.Protocol} is not supported."),
};
public static OtlpExportProtocol? ToOtlpExportProtocol(this string protocol) =>
protocol.Trim() switch
{
"grpc" => OtlpExportProtocol.Grpc,
"http/protobuf" => OtlpExportProtocol.HttpProtobuf,
_ => null,
};
public static void TryEnableIHttpClientFactoryIntegration(this OtlpExporterOptions options, IServiceProvider serviceProvider, string httpClientName)
{
if (serviceProvider != null
&& options.Protocol == OtlpExportProtocol.HttpProtobuf
&& options.HttpClientFactory == options.DefaultHttpClientFactory)
{
options.HttpClientFactory = () =>
{
Type httpClientFactoryType = Type.GetType("System.Net.Http.IHttpClientFactory, Microsoft.Extensions.Http", throwOnError: false);
if (httpClientFactoryType != null)
{
object httpClientFactory = serviceProvider.GetService(httpClientFactoryType);
if (httpClientFactory != null)
{
MethodInfo createClientMethod = httpClientFactoryType.GetMethod(
"CreateClient",
BindingFlags.Public | BindingFlags.Instance,
binder: null,
new Type[] { typeof(string) },
modifiers: null);
if (createClientMethod != null)
{
HttpClient client = (HttpClient)createClientMethod.Invoke(httpClientFactory, new object[] { httpClientName });
client.Timeout = TimeSpan.FromMilliseconds(options.TimeoutMilliseconds);
return client;
}
}
}
return options.DefaultHttpClientFactory();
};
}
}
internal static void AppendExportPath(this OtlpExporterOptions options, string exportRelativePath)
{
// The exportRelativePath is only appended when the options.Endpoint property wasn't set by the user,
// the protocol is HttpProtobuf and the OTEL_EXPORTER_OTLP_ENDPOINT environment variable
// is present. If the user provides a custom value for options.Endpoint that value is taken as is.
if (!options.ProgrammaticallyModifiedEndpoint)
{
if (options.Protocol == OtlpExportProtocol.HttpProtobuf)
{
if (EnvironmentVariableHelper.LoadUri(OtlpExporterOptions.EndpointEnvVarName, out Uri endpoint))
{
// At this point we can conclude that endpoint was initialized from OTEL_EXPORTER_OTLP_ENDPOINT
// and has to be appended by export relative path (traces/metrics).
options.Endpoint = endpoint.AppendPathIfNotPresent(exportRelativePath);
}
}
}
}
internal static Uri AppendPathIfNotPresent(this Uri uri, string path)
{
var absoluteUri = uri.AbsoluteUri;
var separator = string.Empty;
if (absoluteUri.EndsWith("/"))
{
// Endpoint already ends with 'path/'
if (absoluteUri.EndsWith(string.Concat(path, "/"), StringComparison.OrdinalIgnoreCase))
{
return uri;
}
}
else
{
// Endpoint already ends with 'path'
if (absoluteUri.EndsWith(path, StringComparison.OrdinalIgnoreCase))
{
return uri;
}
separator = "/";
}
return new Uri(string.Concat(uri.AbsoluteUri, separator, path));
}
}
}