Skip to content
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Aspire.Hosting/Ats/CreateBuilderOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ internal sealed class CreateBuilderOptions
public string? ContainerRegistryOverride { get; set; }

/// <summary>
/// Determines whether the dashboard is disabled.
/// Determines whether the dashboard should be disabled at app host startup.
Comment thread
afscrome marked this conversation as resolved.
Resolved
Comment thread
afscrome marked this conversation as resolved.
Resolved
/// </summary>
public bool DisableDashboard { get; set; }

Expand Down
8 changes: 0 additions & 8 deletions src/Aspire.Hosting/Backchannel/AppHostRpcTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ internal class AppHostRpcTarget(
ProfilingTelemetry profilingTelemetry,
PipelineActivityReporter activityReporter,
IHostApplicationLifetime lifetime,
DistributedApplicationOptions options,
AppHostStartupState startupState,
IFileUploadStore fileUploadStore,
IConfiguration configuration)
Expand Down Expand Up @@ -178,13 +177,6 @@ public void CancelInflightRpcCalls()
public async Task<DashboardUrlsState> GetDashboardUrlsAsync(CancellationToken cancellationToken)
{
using var activity = profilingTelemetry.StartJsonRpcServerCall(nameof(GetDashboardUrlsAsync), streaming: false);
if (!options.DashboardEnabled)
{
logger.LogDebug("Dashboard URL requested but dashboard is disabled.");
activity.SetDashboardHealthy(false);
return new DashboardUrlsState { DashboardHealthy = false };
}

try
{
var urls = await DashboardUrlsHelper.GetDashboardUrlsAsync(serviceProvider, logger, cancellationToken).ConfigureAwait(false);
Expand Down
14 changes: 11 additions & 3 deletions src/Aspire.Hosting/Backchannel/DashboardUrlsHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,8 @@ public static async Task<DashboardConnectionInfo> GetDashboardConnectionInfoAsyn
ILogger logger,
CancellationToken cancellationToken = default)
{
// Check whether the dashboard resource is registered at all. If it isn't (e.g. the user
// called DisableDashboard()), return immediately rather than waiting forever for a resource
// event that will never arrive.
// Check whether the dashboard resource is registered at all. If it isn't, return
// immediately rather than waiting forever for a resource event that will never arrive.
var appModel = serviceProvider.GetService<DistributedApplicationModel>();
var dashboardResource = appModel?.Resources.SingleOrDefault(
r => string.Equals(r.Name, KnownResourceNames.AspireDashboard, StringComparisons.ResourceName)) as IResourceWithEndpoints;
Expand All @@ -48,6 +47,15 @@ public static async Task<DashboardConnectionInfo> GetDashboardConnectionInfoAsyn
using var activity = profilingTelemetry.StartDashboardGetConnectionInfo();
var resourceNotificationService = serviceProvider.GetRequiredService<ResourceNotificationService>();

if (dashboardResource.TryGetLastAnnotation<ExplicitStartupAnnotation>(out _) &&
resourceNotificationService.TryGetCurrentState(KnownResourceNames.AspireDashboard, out var dashboardEvent) &&
dashboardEvent.Snapshot.State?.Text == KnownResourceStates.NotStarted)
Comment thread
afscrome marked this conversation as resolved.
Resolved
{
logger.LogDebug("Dashboard resource is in NotStarted explicit-start state. Returning unavailable state.");
activity.SetDashboardHealthy(false);
return DashboardConnectionInfo.Unhealthy;
}
Comment thread
afscrome marked this conversation as resolved.
Resolved

// Wait for the dashboard to be healthy
using (var waitActivity = profilingTelemetry.StartDashboardWaitHealthy())
{
Expand Down
64 changes: 64 additions & 0 deletions src/Aspire.Hosting/Dashboard/DashboardEventHandlers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
using Aspire.Hosting.Devcontainers.Codespaces;
using Aspire.Hosting.Eventing;
using Aspire.Hosting.Lifecycle;
using Aspire.Hosting.Orchestrator;
using Aspire.Hosting.Resources;
using Aspire.Hosting.Utils;
using Aspire.Shared;
using Aspire.Shared.ConsoleLogs;
Expand All @@ -34,6 +36,7 @@ internal sealed class DashboardEventHandlers(IConfiguration configuration,
ILogger<DistributedApplication> distributedApplicationLogger,
IDashboardEndpointProvider dashboardEndpointProvider,
DistributedApplicationExecutionContext executionContext,
DistributedApplicationOptions distributedApplicationOptions,
ResourceNotificationService resourceNotificationService,
ResourceLoggerService resourceLoggerService,
ILoggerFactory loggerFactory,
Expand Down Expand Up @@ -343,9 +346,20 @@ private void AddDashboardResource(DistributedApplicationModel model)

private void ConfigureAspireDashboardResource(IResource dashboardResource)
{
var isDashboardExplicitStart = distributedApplicationOptions.DisableDashboard;
if (isDashboardExplicitStart &&
!dashboardResource.TryGetLastAnnotation<ExplicitStartupAnnotation>(out _))
{
dashboardResource.Annotations.Add(new ExplicitStartupAnnotation());
}

// The dashboard resource can be visible during development. We don't want people to be able to stop the dashboard from inside the dashboard.
// Exclude the lifecycle commands from the dashboard resource so they're not accidently clicked during development.
dashboardResource.Annotations.Add(new ExcludeLifecycleCommandsAnnotation());
if (isDashboardExplicitStart)
{
AddDisabledDashboardStartCommand(dashboardResource);
Comment thread
afscrome marked this conversation as resolved.
Resolved
}

// Add the ContentView icon to the dashboard resource
dashboardResource.Annotations.Add(new ResourceIconAnnotation("ContentView"));
Expand Down Expand Up @@ -500,6 +514,56 @@ private void ConfigureAspireDashboardResource(IResource dashboardResource)
eventing.Subscribe<ResourceReadyEvent>(dashboardResource, DashboardStarted);
}

private static void AddDisabledDashboardStartCommand(IResource dashboardResource)
{
if (dashboardResource.TryGetAnnotationsOfType<ResourceCommandAnnotation>(out var commands) &&
commands.Any(command => string.Equals(command.Name, KnownResourceCommands.StartCommand, StringComparison.Ordinal)))
{
return;
}

dashboardResource.Annotations.Add(new ResourceCommandAnnotation(
name: KnownResourceCommands.StartCommand,
displayName: CommandStrings.StartName,
executeCommand: async context =>
{
var orchestrator = context.Services.GetRequiredService<ApplicationOrchestrator>();
await orchestrator.StartResourceAsync(context.ResourceName, context.CancellationToken).ConfigureAwait(false);
Comment thread
afscrome marked this conversation as resolved.
Resolved
return new ExecuteCommandResult
{
Success = true,
Message = string.Format(CultureInfo.InvariantCulture, CommandStrings.ResourceStarted, dashboardResource.GetResolvedDisplayResourceName(context.ResourceName))
};
},
updateState: context =>
{
var state = context.ResourceSnapshot.State?.Text;
if (state == KnownResourceStates.Starting ||
state == KnownResourceStates.Building ||
state == KnownResourceStates.RuntimeUnhealthy ||
string.IsNullOrEmpty(state))
{
return ResourceCommandState.Disabled;
}

if (KnownResourceStates.TerminalStates.Contains(state) ||
state == KnownResourceStates.NotStarted ||
state == KnownResourceStates.Waiting ||
state == "Unknown")
{
return ResourceCommandState.Enabled;
}

return ResourceCommandState.Hidden;
},
displayDescription: CommandStrings.StartDescription,
arguments: null,
confirmationMessage: null,
iconName: "Play",
iconVariant: IconVariant.Filled,
isHighlighted: true));
}

private async Task DashboardStarted(ResourceReadyEvent @event, CancellationToken cancellationToken)
{
var options = dashboardOptions.Value;
Expand Down
7 changes: 3 additions & 4 deletions src/Aspire.Hosting/Dashboard/DashboardServiceHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,12 @@ internal sealed class DashboardServiceHost : IHostedService
private readonly TaskCompletionSource<string> _resourceServiceUri = new();

/// <summary>
/// <see langword="null"/> if <see cref="DistributedApplicationOptions.DashboardEnabled"/> is <see langword="false"/>.
/// <see langword="null"/> in publish mode.
/// </summary>
private readonly WebApplication? _app;
private readonly ILogger<DashboardServiceHost> _logger;

public DashboardServiceHost(
DistributedApplicationOptions options,
DistributedApplicationModel applicationModel,
IConfiguration configuration,
DistributedApplicationExecutionContext executionContext,
Expand All @@ -54,9 +53,9 @@ public DashboardServiceHost(
{
_logger = loggerFactory.CreateLogger<DashboardServiceHost>();

if (!options.DashboardEnabled || executionContext.IsPublishMode)
if (executionContext.IsPublishMode)
{
_logger.LogDebug("Dashboard is not enabled so skipping hosting the resource service.");
_logger.LogDebug("Skipping hosting the resource service in publish mode.");
_resourceServiceUri.SetCanceled();
return;
Comment thread
afscrome marked this conversation as resolved.
Resolved
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ internal class TransportOptionsValidator(IConfiguration configuration, Distribut
{
public ValidateOptionsResult Validate(string? name, TransportOptions transportOptions)
{
var effectiveAllowUnsecureTransport = transportOptions.AllowUnsecureTransport || distributedApplicationOptions.DisableDashboard || distributedApplicationOptions.AllowUnsecuredTransport;
var effectiveAllowUnsecureTransport = transportOptions.AllowUnsecureTransport || distributedApplicationOptions.AllowUnsecuredTransport;
Comment thread
afscrome marked this conversation as resolved.
Resolved
Comment thread
afscrome marked this conversation as resolved.
Resolved

if (executionContext.IsPublishMode || effectiveAllowUnsecureTransport)
{
Expand Down
109 changes: 53 additions & 56 deletions src/Aspire.Hosting/DistributedApplicationBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -421,69 +421,66 @@ public DistributedApplicationBuilder(DistributedApplicationOptions options)
if (ExecutionContext.IsRunMode)
{
// Dashboard
if (!options.DisableDashboard)
if (!IsDashboardUnsecured(_innerBuilder.Configuration))
{
if (!IsDashboardUnsecured(_innerBuilder.Configuration))
// Passed to apps as a standard OTEL attribute to include in OTLP requests and the dashboard to validate.
// Set a random API key for the OTLP exporter if one isn't already present in configuration.
// If a key is generated, it's stored in the user secrets store so that it will be auto-loaded
// on subsequent runs and not recreated. This is important to ensure it doesn't change the state
// of persistent containers (as a new key would be a spec change).
_userSecretsManager.GetOrSetSecret(_innerBuilder.Configuration, "AppHost:OtlpApiKey", TokenGenerator.GenerateToken);

// Set a random API key for the Dashboard Telemetry API if one isn't already present in configuration.
_userSecretsManager.GetOrSetSecret(_innerBuilder.Configuration, "AppHost:DashboardApiKey", TokenGenerator.GenerateToken);

// Determine the frontend browser token.
if (_innerBuilder.Configuration.GetString(KnownConfigNames.DashboardFrontendBrowserToken,
KnownConfigNames.Legacy.DashboardFrontendBrowserToken, fallbackOnEmpty: true) is not { } browserToken)
{
// Passed to apps as a standard OTEL attribute to include in OTLP requests and the dashboard to validate.
// Set a random API key for the OTLP exporter if one isn't already present in configuration.
// If a key is generated, it's stored in the user secrets store so that it will be auto-loaded
// on subsequent runs and not recreated. This is important to ensure it doesn't change the state
// of persistent containers (as a new key would be a spec change).
_userSecretsManager.GetOrSetSecret(_innerBuilder.Configuration, "AppHost:OtlpApiKey", TokenGenerator.GenerateToken);

// Set a random API key for the Dashboard Telemetry API if one isn't already present in configuration.
_userSecretsManager.GetOrSetSecret(_innerBuilder.Configuration, "AppHost:DashboardApiKey", TokenGenerator.GenerateToken);

// Determine the frontend browser token.
if (_innerBuilder.Configuration.GetString(KnownConfigNames.DashboardFrontendBrowserToken,
KnownConfigNames.Legacy.DashboardFrontendBrowserToken, fallbackOnEmpty: true) is not { } browserToken)
// No browser token was specified in configuration, so generate one.
browserToken = TokenGenerator.GenerateToken();
}

_innerBuilder.Configuration.AddInMemoryCollection(
new Dictionary<string, string?>
{
// No browser token was specified in configuration, so generate one.
browserToken = TokenGenerator.GenerateToken();
["AppHost:BrowserToken"] = browserToken
}
);

// Determine the resource service API key.
var apiKey = _innerBuilder.Configuration.GetString(KnownConfigNames.DashboardResourceServiceClientApiKey,
KnownConfigNames.Legacy.DashboardResourceServiceClientApiKey, fallbackOnEmpty: true);

_innerBuilder.Configuration.AddInMemoryCollection(
new Dictionary<string, string?>
{
["AppHost:BrowserToken"] = browserToken
}
);

// Determine the resource service API key.
var apiKey = _innerBuilder.Configuration.GetString(KnownConfigNames.DashboardResourceServiceClientApiKey,
KnownConfigNames.Legacy.DashboardResourceServiceClientApiKey, fallbackOnEmpty: true);

// If no API key was specified in configuration, generate one.
apiKey ??= TokenGenerator.GenerateToken();

_innerBuilder.Configuration.AddInMemoryCollection(
new Dictionary<string, string?>
{
["AppHost:ResourceService:AuthMode"] = nameof(ResourceServiceAuthMode.ApiKey),
["AppHost:ResourceService:ApiKey"] = apiKey
}
);
}
else
{
// The dashboard is enabled but is unsecured. Set auth mode config setting to reflect this state.
_innerBuilder.Configuration.AddInMemoryCollection(
new Dictionary<string, string?>
{
["AppHost:ResourceService:AuthMode"] = nameof(ResourceServiceAuthMode.Unsecured)
}
);
}
// If no API key was specified in configuration, generate one.
apiKey ??= TokenGenerator.GenerateToken();

_innerBuilder.Services.AddOptions<TransportOptions>().ValidateOnStart().PostConfigure(MapTransportOptionsFromCustomKeys);
_innerBuilder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IValidateOptions<TransportOptions>, TransportOptionsValidator>());
_innerBuilder.Services.AddSingleton<DashboardServiceHost>();
_innerBuilder.Services.AddHostedService(sp => sp.GetRequiredService<DashboardServiceHost>());
_innerBuilder.Services.AddSingleton<IDashboardEndpointProvider, HostDashboardEndpointProvider>();
_innerBuilder.Services.AddEventingSubscriber<DashboardEventHandlers>();
_innerBuilder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<DashboardOptions>, ConfigureDefaultDashboardOptions>());
_innerBuilder.Configuration.AddInMemoryCollection(
new Dictionary<string, string?>
{
["AppHost:ResourceService:AuthMode"] = nameof(ResourceServiceAuthMode.ApiKey),
["AppHost:ResourceService:ApiKey"] = apiKey
}
);
}
else
{
// The dashboard is enabled but is unsecured. Set auth mode config setting to reflect this state.
_innerBuilder.Configuration.AddInMemoryCollection(
new Dictionary<string, string?>
{
["AppHost:ResourceService:AuthMode"] = nameof(ResourceServiceAuthMode.Unsecured)
}
);
}

_innerBuilder.Services.AddOptions<TransportOptions>().ValidateOnStart().PostConfigure(MapTransportOptionsFromCustomKeys);
_innerBuilder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IValidateOptions<TransportOptions>, TransportOptionsValidator>());
_innerBuilder.Services.AddSingleton<DashboardServiceHost>();
_innerBuilder.Services.AddHostedService(sp => sp.GetRequiredService<DashboardServiceHost>());
_innerBuilder.Services.AddSingleton<IDashboardEndpointProvider, HostDashboardEndpointProvider>();
_innerBuilder.Services.AddEventingSubscriber<DashboardEventHandlers>();
_innerBuilder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<DashboardOptions>, ConfigureDefaultDashboardOptions>());

if (options.EnableResourceLogging)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Aspire.Hosting/DistributedApplicationOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public DistributedApplicationOptions()
public string? AssemblyName { get; set; }

/// <summary>
/// Determines whether the dashboard is disabled.
/// Determines whether the dashboard should be disabled at app host startup.
Comment thread
afscrome marked this conversation as resolved.
Resolved
/// </summary>
public bool DisableDashboard { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,13 @@ private static void ValidateComputeEnvironmentBindings(DistributedApplicationMod

var unboundResources = model.Resources
.OfType<IComputeResource>()
.Where(resource => resource.GetComputeEnvironment() is null)
.Where(resource =>
resource.GetComputeEnvironment() is null &&
// When DisableDashboard=true, the dashboard resource remains in the model with
// ExplicitStartupAnnotation so users can start it on demand. It is intentionally
// not auto-assigned to publish compute environments and should not block validation.
!(string.Equals(resource.Name, KnownResourceNames.AspireDashboard, StringComparisons.ResourceName) &&
resource.TryGetLastAnnotation<ExplicitStartupAnnotation>(out _)))
Comment thread
afscrome marked this conversation as resolved.
Resolved
.ToList();

if (unboundResources.Count == 0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -899,7 +899,7 @@ export interface CreateBuilderOptions {
appHostFilePath?: string | null;
/** When containers are used, use this value to override the container registry. */
containerRegistryOverride?: string | null;
/** Determines whether the dashboard is disabled. */
/** Determines whether the dashboard should be disabled at app host startup. */
Comment thread
afscrome marked this conversation as resolved.
Resolved
disableDashboard?: boolean;
/** The application name to display in the dashboard. */
dashboardApplicationName?: string | null;
Expand Down
Loading
Loading