// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Aspire.Cli.Commands;
using Aspire.Dashboard.Utils;
using Aspire.Hosting;
using Aspire.Otlp.Serialization;
using Microsoft.Extensions.Logging;
namespace Aspire.Cli.Backchannel;
/// <summary>
/// Tells whether resources whose AppHost configured OTLP export have sent any telemetry to the dashboard.
/// </summary>
/// <remarks>
/// The AppHost sets <c>OTEL_EXPORTER_OTLP_ENDPOINT</c> and related variables on resources, but only an
/// OpenTelemetry SDK running inside the app consumes them. A JavaScript app without an SDK, for example,
/// receives the variables and never exports anything. Surfacing "OTLP configured, nothing received" lets
/// agents and people tell such a resource apart from one whose telemetry is merely empty.
/// </remarks>
internal sealed class ResourceTelemetryStatus
{
private const string ServiceInstanceIdAttributeName = "service.instance.id";
// Describe and list_resources are interactive, one-shot reads. Bound the extra dashboard request so an
// unresponsive dashboard degrades to "status unknown" instead of delaying the resource listing.
private static readonly TimeSpan s_queryTimeout = TimeSpan.FromSeconds(5);
// Everything known about each service.name, from both the dashboard and the AppHost. service.name and
// service.instance.id stay separate: joining them can collide when either contains a hyphen.
private readonly Dictionary<string, ServiceTelemetryState> _services = new(StringComparers.ResourceName);
// Runtime names the dashboard derives from each telemetry identity, used only when a resource's configured
// identity is incomplete.
private readonly HashSet<string> _runtimeNames = new(StringComparers.ResourceName);
private ResourceTelemetryStatus(
IEnumerable<ResourceInfoJson> telemetryResources,
IEnumerable<ResourceSnapshot> appHostSnapshots)
{
foreach (var resource in telemetryResources)
{
GetOrAddService(resource.Name).ReportedInstanceIds.Add(resource.InstanceId);
_runtimeNames.Add(GetCompositeName(resource.Name, resource.InstanceId));
}
// Count workloads across the whole AppHost, hidden resources included, not only the resources being
// displayed: a service name shared with an unlisted replica must not look like a single workload.
foreach (var snapshot in appHostSnapshots)
{
var configuredServiceName = GetResolvedEnvironmentValue(snapshot, KnownOtelConfigNames.ServiceName);
if ((configuredServiceName ?? snapshot.DisplayName) is { } serviceName)
{
GetOrAddService(serviceName).WorkloadCount++;
}
if (configuredServiceName is not null)
{
var configuredInstanceIdCounts = GetOrAddService(configuredServiceName).ConfiguredInstanceIdCounts;
foreach (var instanceId in GetServiceInstanceIds(snapshot))
{
configuredInstanceIdCounts[instanceId] = configuredInstanceIdCounts.GetValueOrDefault(instanceId) + 1;
}
}
}
}
private static bool IsOtlpExporterConfigured(ResourceSnapshot snapshot) =>
// Only the AppHost's own setting counts. The snapshot carries the effective environment, which for executables
// includes variables inherited from the AppHost process (for example the endpoint `aspire run` profiling sets)
// and for containers includes ENV from the image; those are marked IsFromSpec = false. An explicitly empty
// endpoint disables export; a null value means the value wasn't captured.
snapshot.EnvironmentVariables.Any(e =>
e.IsFromSpec &&
string.Equals(e.Name, KnownOtelConfigNames.ExporterOtlpEndpoint, StringComparison.Ordinal) &&
e.Value is not { Length: 0 });
/// <summary>
/// Gets whether the dashboard has received telemetry from the resource.
/// </summary>
/// <returns>
/// <see langword="null"/> when the AppHost didn't configure OTLP export for the resource or telemetry
/// couldn't be matched to it unambiguously; otherwise whether telemetry from the resource reached the dashboard.
/// </returns>
internal bool? GetTelemetryReceived(ResourceSnapshot snapshot)
{
if (!IsOtlpExporterConfigured(snapshot))
{
return null;
}
// The dashboard keys telemetry by the service.name and service.instance.id the app reports. Prefer
// the values the resource was started with: they differ from the runtime resource name for persistent
// resources (whose instance ID is the full runtime name) and when the app overrides them.
var configuredServiceName = GetResolvedEnvironmentValue(snapshot, KnownOtelConfigNames.ServiceName);
var instanceIds = GetServiceInstanceIds(snapshot);
var hasConfiguredIdentity = false;
if (configuredServiceName is not null && instanceIds.Count > 0)
{
hasConfiguredIdentity = true;
if (_services.TryGetValue(configuredServiceName, out var configuredService) &&
instanceIds.Where(id => configuredService.ReportedInstanceIds.Contains(id)).ToList() is { Count: > 0 } matchedIds)
{
// A matched ID that another workload may also report (for example one replica configured as a%2F1 and
// another as a/1) doesn't tell which of them sent the telemetry.
return matchedIds.Any(id => configuredService.ConfiguredInstanceIdCounts.GetValueOrDefault(id) <= 1) ? true : null;
}
}
else if (_runtimeNames.Contains(snapshot.Name))
{
// Use the runtime name only when the configured identity is incomplete.
return true;
}
var serviceName = configuredServiceName ?? snapshot.DisplayName;
if (serviceName is null || !_services.TryGetValue(serviceName, out var service) || service.ReportedInstanceIds.Count == 0)
{
return false;
}
// Telemetry arrived under the service name but not under this resource's instance identity, for example
// because the app's SDK reported no instance ID or generated its own (.NET's ResourceBuilder.AddService does).
// It is this resource's telemetry when no other workload in the AppHost uses the service name.
if (service.WorkloadCount == 1)
{
return true;
}
// Replicas share the service name. The replica is silent only when every telemetry source under the name is
// another replica's configured instance. A source without an instance ID, or with one the SDK generated,
// can't be attributed to a replica.
return hasConfiguredIdentity &&
service.ReportedInstanceIds.All(id => id is not null && service.ConfiguredInstanceIdCounts.ContainsKey(id))
? false
: null;
}
/// <summary>
/// Reads which resources have sent telemetry from the dashboard of the given AppHost.
/// </summary>
/// <param name="dashboardInfo">
/// The dashboard info the caller already read for its dashboard links, so the lookup adds no backchannel round
/// trip; <see langword="null"/> when it wasn't available.
/// </param>
/// <param name="snapshots">The resources whose status is wanted; the dashboard is queried only when one has OTLP configured.</param>
/// <param name="appHostSnapshots">Every resource in the AppHost, hidden ones included, used to count workloads per service name.</param>
/// <param name="httpClientFactory">The factory for the dashboard API client.</param>
/// <param name="logger">The logger for lookup failures, which are reported only at debug level.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>
/// The telemetry status, or <see langword="null"/> when no snapshot has OTLP configured or the dashboard
/// telemetry API is unavailable, unreachable, or doesn't respond within a short timeout.
/// </returns>
internal static async Task<ResourceTelemetryStatus?> TryGetAsync(
GetDashboardInfoResponse? dashboardInfo,
IEnumerable<ResourceSnapshot> snapshots,
IEnumerable<ResourceSnapshot> appHostSnapshots,
IHttpClientFactory httpClientFactory,
ILogger logger,
CancellationToken cancellationToken)
{
if (!snapshots.Any(IsOtlpExporterConfigured))
{
return null;
}
// An AppHost that predates the v2 backchannel reports no API URL.
if (dashboardInfo is null ||
DashboardUrls.NormalizeDashboardRequestUrl(dashboardInfo.ApiBaseUrl, stripLoginPath: false) is not { } apiBaseUrl)
{
logger.LogDebug("Dashboard telemetry API is not available; resource telemetry status is unknown.");
return null;
}
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutCts.CancelAfter(s_queryTimeout);
try
{
// The API token is null when the dashboard allows anonymous access; CreateApiClient then sends no key.
using var client = TelemetryCommandHelpers.CreateApiClient(httpClientFactory, dashboardInfo.ApiToken);
var telemetryResources = await TelemetryCommandHelpers.GetAllResourcesAsync(client, apiBaseUrl, timeoutCts.Token).ConfigureAwait(false);
return new ResourceTelemetryStatus(telemetryResources, appHostSnapshots);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
// The status is supplementary: a missing, older, slow, or failing dashboard must not fail the listing.
logger.LogDebug(ex, "Unable to read resource telemetry status from the dashboard.");
return null;
}
}
private ServiceTelemetryState GetOrAddService(string serviceName)
{
if (!_services.TryGetValue(serviceName, out var service))
{
service = new ServiceTelemetryState();
_services.Add(serviceName, service);
}
return service;
}
private static string GetCompositeName(string name, string? instanceId) =>
instanceId is null ? name : $"{name}-{instanceId}";
private static string? GetResolvedEnvironmentValue(ResourceSnapshot snapshot, string name)
{
var value = snapshot.EnvironmentVariables
.FirstOrDefault(e => string.Equals(e.Name, name, StringComparison.Ordinal))?.Value;
// Before DCP reports the effective environment, the snapshot carries the spec value, which is an
// unresolved DCP template such as {{- index .Annotations "otel-service-name" -}}.
return string.IsNullOrEmpty(value) || value.Contains("{{", StringComparison.Ordinal) ? null : value;
}
private static IReadOnlyList<string> GetServiceInstanceIds(ResourceSnapshot snapshot)
{
// OTEL_RESOURCE_ATTRIBUTES is a comma-separated list of percent-encoded key=value pairs, for example
// deployment.environment=dev,service.instance.id=worker%2F1
// https://opentelemetry.io/docs/specs/otel/resource/sdk/#specifying-resource-information-via-an-environment-variable
// SDKs disagree on decoding: the OpenTelemetry .NET SDK reports the value as written (worker%2F1), while others
// follow the spec and report worker/1. Return the value as written first and, when it differs, the decoded value,
// so the dashboard's identity matches whichever form the app's SDK reported.
if (GetResolvedEnvironmentValue(snapshot, KnownOtelConfigNames.ResourceAttributes) is not { } attributes)
{
return [];
}
foreach (var attribute in attributes.Split(',', StringSplitOptions.TrimEntries))
{
var separator = attribute.IndexOf('=');
if (separator > 0 &&
string.Equals(attribute[..separator].Trim(), ServiceInstanceIdAttributeName, StringComparison.Ordinal) &&
attribute[(separator + 1)..].Trim() is { Length: > 0 } instanceId)
{
// UnescapeDataString leaves malformed sequences such as a trailing '%' as they are.
var decoded = Uri.UnescapeDataString(instanceId);
return decoded.Length == 0 || string.Equals(decoded, instanceId, StringComparison.Ordinal)
? [instanceId]
: [instanceId, decoded];
}
}
return [];
}
private sealed class ServiceTelemetryState
{
/// <summary>
/// Gets the instance IDs the dashboard reported telemetry under, with <see langword="null"/> for telemetry that
/// carried no instance ID. An empty set means the service sent no telemetry.
/// </summary>
public HashSet<string?> ReportedInstanceIds { get; } = new(StringComparers.ResourceName);
/// <summary>
/// Gets the number of AppHost workloads that report under the service name.
/// </summary>
public int WorkloadCount { get; set; }
/// <summary>
/// Gets every instance ID a workload may report (the configured value and, when it differs, its percent-decoded
/// form) with the number of workloads that may report it. A count above one means the ID can't be attributed
/// to a single workload.
/// </summary>
public Dictionary<string, int> ConfiguredInstanceIdCounts { get; } = new(StringComparers.ResourceName);
}
}