-
Notifications
You must be signed in to change notification settings - Fork 226
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Update metrics sample to use OTLP and OTEL collector #606
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
cb57bf1
Update metrics sample to use OTLP and OTEL collector
JamesNK e1d0e5c
PR feedback
JamesNK 5ce58f3
PR feedback
JamesNK 91c3b08
Remove Prometheus OTEL package
JamesNK a7fb5ff
Update packages
JamesNK ab93b6c
PR feedback
JamesNK c217f0f
Update
JamesNK 95569f2
Update
JamesNK c0027c5
PR feedback
JamesNK File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
43 changes: 43 additions & 0 deletions
43
.../Metrics/MetricsApp.AppHost/OpenTelemetryCollector/OpenTelemetryCollectorLifecycleHook.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
using Aspire.Hosting.Lifecycle; | ||
using Microsoft.Extensions.Logging; | ||
|
||
namespace MetricsApp.AppHost.OpenTelemetryCollector; | ||
|
||
internal sealed class OpenTelemetryCollectorLifecycleHook : IDistributedApplicationLifecycleHook | ||
{ | ||
private readonly ILogger<OpenTelemetryCollectorLifecycleHook> _logger; | ||
|
||
public OpenTelemetryCollectorLifecycleHook(ILogger<OpenTelemetryCollectorLifecycleHook> logger) | ||
{ | ||
_logger = logger; | ||
} | ||
|
||
public Task AfterEndpointsAllocatedAsync(DistributedApplicationModel appModel, CancellationToken cancellationToken) | ||
{ | ||
var collectorResource = appModel.Resources.OfType<OpenTelemetryCollectorResource>().FirstOrDefault(); | ||
if (collectorResource == null) | ||
{ | ||
_logger.LogWarning($"No {nameof(OpenTelemetryCollectorResource)} resource found."); | ||
return Task.CompletedTask; | ||
} | ||
|
||
var endpoint = collectorResource.GetEndpoint(OpenTelemetryCollectorResource.OtlpGrpcEndpointName); | ||
if (!endpoint.Exists) | ||
{ | ||
_logger.LogWarning($"No {OpenTelemetryCollectorResource.OtlpGrpcEndpointName} endpoint for the collector."); | ||
return Task.CompletedTask; | ||
} | ||
|
||
foreach (var resource in appModel.GetProjectResources()) | ||
{ | ||
_logger.LogDebug("Forwarding telemetry for {ResourceName} to the collector.", resource.Name); | ||
|
||
resource.Annotations.Add(new EnvironmentCallbackAnnotation((EnvironmentCallbackContext context) => | ||
{ | ||
context.EnvironmentVariables["OTEL_EXPORTER_OTLP_ENDPOINT"] = endpoint; | ||
})); | ||
} | ||
|
||
return Task.CompletedTask; | ||
} | ||
} |
7 changes: 7 additions & 0 deletions
7
samples/Metrics/MetricsApp.AppHost/OpenTelemetryCollector/OpenTelemetryCollectorResource.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
namespace MetricsApp.AppHost.OpenTelemetryCollector; | ||
|
||
public class OpenTelemetryCollectorResource(string name) : ContainerResource(name) | ||
{ | ||
internal const string OtlpGrpcEndpointName = "grpc"; | ||
internal const string OtlpHttpEndpointName = "http"; | ||
} |
45 changes: 45 additions & 0 deletions
45
...ricsApp.AppHost/OpenTelemetryCollector/OpenTelemetryCollectorResourceBuilderExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
using Microsoft.Extensions.Hosting; | ||
|
||
namespace MetricsApp.AppHost.OpenTelemetryCollector; | ||
|
||
public static class OpenTelemetryCollectorResourceBuilderExtensions | ||
{ | ||
private const string DashboardOtlpUrlVariableName = "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL"; | ||
private const string DashboardOtlpApiKeyVariableName = "AppHost:OtlpApiKey"; | ||
private const string DashboardOtlpUrlDefaultValue = "http://localhost:18889"; | ||
|
||
public static IResourceBuilder<OpenTelemetryCollectorResource> AddOpenTelemetryCollector(this IDistributedApplicationBuilder builder, string name, string configFileLocation) | ||
{ | ||
builder.AddOpenTelemetryCollectorInfrastructure(); | ||
|
||
var url = builder.Configuration[DashboardOtlpUrlVariableName] ?? DashboardOtlpUrlDefaultValue; | ||
var isHttpsEnabled = url.StartsWith("https", StringComparison.OrdinalIgnoreCase); | ||
|
||
var dashboardOtlpEndpoint = new HostUrl(url); | ||
|
||
var resource = new OpenTelemetryCollectorResource(name); | ||
var resourceBuilder = builder.AddResource(resource) | ||
.WithImage("ghcr.io/open-telemetry/opentelemetry-collector-releases/opentelemetry-collector-contrib", "latest") | ||
.WithEndpoint(targetPort: 4317, name: OpenTelemetryCollectorResource.OtlpGrpcEndpointName, scheme: isHttpsEnabled ? "https" : "http") | ||
.WithEndpoint(targetPort: 4318, name: OpenTelemetryCollectorResource.OtlpHttpEndpointName, scheme: isHttpsEnabled ? "https" : "http") | ||
.WithBindMount(configFileLocation, "/etc/otelcol-contrib/config.yaml") | ||
.WithEnvironment("ASPIRE_ENDPOINT", $"{dashboardOtlpEndpoint}") | ||
.WithEnvironment("ASPIRE_API_KEY", builder.Configuration[DashboardOtlpApiKeyVariableName]) | ||
.WithEnvironment("ASPIRE_INSECURE", isHttpsEnabled ? "false" : "true"); | ||
|
||
if (isHttpsEnabled && builder.ExecutionContext.IsRunMode && builder.Environment.IsDevelopment()) | ||
{ | ||
DevCertHostingExtensions.RunWithHttpsDevCertificate(resourceBuilder, "HTTPS_CERT_FILE", "HTTPS_CERT_KEY_FILE", (certFilePath, certKeyPath) => | ||
{ | ||
// Set TLS details using YAML path via the command line. This allows the values to be added to the existing config file. | ||
// Setting the values in the config file doesn't work because adding the "tls" section always enables TLS, even if there is no cert provided. | ||
resourceBuilder.WithArgs( | ||
@"--config=yaml:receivers::otlp::protocols::grpc::tls::cert_file: ""dev-certs/dev-cert.pem""", | ||
@"--config=yaml:receivers::otlp::protocols::grpc::tls::key_file: ""dev-certs/dev-cert.key""", | ||
@"--config=/etc/otelcol-contrib/config.yaml"); | ||
}); | ||
} | ||
|
||
return resourceBuilder; | ||
} | ||
} |
13 changes: 13 additions & 0 deletions
13
...rics/MetricsApp.AppHost/OpenTelemetryCollector/OpenTelemetryCollectorServiceExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
using Aspire.Hosting.Lifecycle; | ||
|
||
namespace MetricsApp.AppHost.OpenTelemetryCollector; | ||
|
||
internal static class OpenTelemetryCollectorServiceExtensions | ||
{ | ||
public static IDistributedApplicationBuilder AddOpenTelemetryCollectorInfrastructure(this IDistributedApplicationBuilder builder) | ||
{ | ||
builder.Services.TryAddLifecycleHook<OpenTelemetryCollectorLifecycleHook>(); | ||
|
||
return builder; | ||
} | ||
} |
3 changes: 3 additions & 0 deletions
3
samples/Metrics/MetricsApp.AppHost/OpenTelemetryCollector/README.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# Aspire Hosting extension for the OpenTelemetry Collector | ||
|
||
Based on source from https://github.com/practical-otel/opentelemetry-aspire-collector by @martinjt. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,24 @@ | ||
var builder = DistributedApplication.CreateBuilder(args); | ||
using MetricsApp.AppHost.OpenTelemetryCollector; | ||
|
||
var builder = DistributedApplication.CreateBuilder(args); | ||
|
||
var prometheus = builder.AddContainer("prometheus", "prom/prometheus") | ||
.WithBindMount("../prometheus", "/etc/prometheus", isReadOnly: true) | ||
.WithArgs("--web.enable-otlp-receiver", "--config.file=/etc/prometheus/prometheus.yml") | ||
.WithHttpEndpoint(targetPort: 9090, name: "http"); | ||
|
||
var grafana = builder.AddContainer("grafana", "grafana/grafana") | ||
.WithBindMount("../grafana/config", "/etc/grafana", isReadOnly: true) | ||
.WithBindMount("../grafana/dashboards", "/var/lib/grafana/dashboards", isReadOnly: true) | ||
.WithEnvironment("PROMETHEUS_ENDPOINT", prometheus.GetEndpoint("http")) | ||
.WithHttpEndpoint(targetPort: 3000, name: "http"); | ||
|
||
builder.AddOpenTelemetryCollector("otelcollector", "../otelcollector/config.yaml") | ||
.WithEnvironment("PROMETHEUS_ENDPOINT", $"{prometheus.GetEndpoint("http")}/api/v1/otlp"); | ||
|
||
builder.AddProject<Projects.MetricsApp>("app") | ||
.WithEnvironment("GRAFANA_URL", grafana.GetEndpoint("http")); | ||
|
||
builder.AddContainer("prometheus", "prom/prometheus") | ||
.WithBindMount("../prometheus", "/etc/prometheus", isReadOnly: true) | ||
.WithHttpEndpoint(/* This port is fixed as it's referenced from the Grafana config */ port: 9090, targetPort: 9090); | ||
|
||
using var app = builder.Build(); | ||
|
||
await app.RunAsync(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
receivers: | ||
otlp: | ||
protocols: | ||
grpc: | ||
endpoint: 0.0.0.0:4317 | ||
http: | ||
endpoint: 0.0.0.0:4318 | ||
|
||
processors: | ||
batch: | ||
|
||
exporters: | ||
debug: | ||
verbosity: detailed | ||
otlp/aspire: | ||
endpoint: ${env:ASPIRE_ENDPOINT} | ||
headers: | ||
x-otlp-api-key: ${env:ASPIRE_API_KEY} | ||
tls: | ||
insecure: ${env:ASPIRE_INSECURE} | ||
insecure_skip_verify: true # Required in local development because cert is localhost and the endpoint is host.docker.internal | ||
otlphttp/prometheus: | ||
endpoint: ${env:PROMETHEUS_ENDPOINT} | ||
tls: | ||
insecure: true | ||
|
||
service: | ||
pipelines: | ||
traces: | ||
receivers: [otlp] | ||
processors: [batch] | ||
exporters: [otlp/aspire] | ||
logs: | ||
receivers: [otlp] | ||
processors: [batch] | ||
exporters: [otlp/aspire] | ||
metrics: | ||
receivers: [otlp] | ||
processors: [batch] | ||
exporters: | ||
- otlp/aspire | ||
- otlphttp/prometheus |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,5 @@ | ||
global: | ||
scrape_interval: 1s # makes for a good demo | ||
storage: | ||
tsdb: | ||
out_of_order_time_window: 30m | ||
|
||
scrape_configs: | ||
- job_name: 'metricsapp' | ||
static_configs: | ||
- targets: ['host.docker.internal:5048'] # hard-coded port matches launchSettings.json | ||
otlp: |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -46,8 +46,8 @@ public static IResourceBuilder<TResource> RunWithHttpsDevCertificate<TResource>( | |
|
||
var bindSource = Path.GetDirectoryName(certPath) ?? throw new UnreachableException(); | ||
|
||
var certFileDest = Path.Combine(DEV_CERT_BIND_MOUNT_DEST_DIR, certFileName); | ||
var certKeyFileDest = Path.Combine(DEV_CERT_BIND_MOUNT_DEST_DIR, certKeyFileName); | ||
var certFileDest = $"{DEV_CERT_BIND_MOUNT_DEST_DIR}/{certFileName}"; | ||
var certKeyFileDest = $"{DEV_CERT_BIND_MOUNT_DEST_DIR}/{certKeyFileName}"; | ||
Comment on lines
-49
to
+50
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. FYI e.g. The OpenTelemetry collector errored when given the bad path. Seems best to hardcode to forward slash. |
||
|
||
builder.ApplicationBuilder.CreateResourceBuilder(containerResource) | ||
.WithBindMount(bindSource, DEV_CERT_BIND_MOUNT_DEST_DIR, isReadOnly: true) | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shouldn't this check all resources? In the callback it would then check if
OTEL_EXPORTER_OTLP_ENDPOINT
is set and replace it with this value.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The problem is that OTEL_EXPORTER_OTLP_ENDPOINT env var is added by a callback. At the resource level we don't know exactly what env vars there are from a callback.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You can do work in the callback to look at what has been set.