Skip to content
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

Add support for showing custom resources in the dashboard #2390

Merged
merged 10 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
12 changes: 11 additions & 1 deletion Aspire.sln
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DatabaseMigration.AppHost",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DatabaseMigration.MigrationService", "playground\DatabaseMigration\DatabaseMigration.MigrationService\DatabaseMigration.MigrationService.csproj", "{E7DB736B-C316-460E-A609-2200E58BF0C2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DatabaseMigration.ApiModel", "playground\DatabaseMigration\DatabaseMigration.ApiModel\DatabaseMigration.ApiModel.csproj", "{C15F3F13-AB63-47CF-AAFE-D319F02E7B33}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DatabaseMigration.ApiModel", "playground\DatabaseMigration\DatabaseMigration.ApiModel\DatabaseMigration.ApiModel.csproj", "{C15F3F13-AB63-47CF-AAFE-D319F02E7B33}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "signalr", "signalr", "{E6985EED-47E3-4EAC-8222-074E5410CEDC}"
EndProject
Expand All @@ -291,6 +291,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProxylessEndToEnd.ApiServic
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProxylessEndToEnd.AppHost", "playground\ProxylessEndToEnd\ProxylessEndToEnd.AppHost\ProxylessEndToEnd.AppHost.csproj", "{0244203D-7491-4414-9C88-10BFED9C5B2D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CustomResources", "CustomResources", "{867A00A7-AF8E-4396-9583-982FBB31762C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CustomResources.AppHost", "playground\CustomResources\CustomResources.AppHost\CustomResources.AppHost.csproj", "{4231B6F1-1110-4992-A727-8F1176A47440}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -761,6 +765,10 @@ Global
{0244203D-7491-4414-9C88-10BFED9C5B2D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0244203D-7491-4414-9C88-10BFED9C5B2D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0244203D-7491-4414-9C88-10BFED9C5B2D}.Release|Any CPU.Build.0 = Release|Any CPU
{4231B6F1-1110-4992-A727-8F1176A47440}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4231B6F1-1110-4992-A727-8F1176A47440}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4231B6F1-1110-4992-A727-8F1176A47440}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4231B6F1-1110-4992-A727-8F1176A47440}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -900,6 +908,8 @@ Global
{9C30FFD6-2262-45E7-B010-24B30E0433C2} = {D173887B-AF42-4576-B9C1-96B9E9B3D9C0}
{51654CD7-2E05-4664-B2EB-95308A300609} = {9C30FFD6-2262-45E7-B010-24B30E0433C2}
{0244203D-7491-4414-9C88-10BFED9C5B2D} = {9C30FFD6-2262-45E7-B010-24B30E0433C2}
{867A00A7-AF8E-4396-9583-982FBB31762C} = {D173887B-AF42-4576-B9C1-96B9E9B3D9C0}
{4231B6F1-1110-4992-A727-8F1176A47440} = {867A00A7-AF8E-4396-9583-982FBB31762C}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6DCEDFEC-988E-4CB3-B45B-191EB5086E0C}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

var builder = DistributedApplication.CreateBuilder(args);

var storage = builder.AddAzureStorage("storage").RunAsEmulator(container =>
Expand All @@ -21,3 +20,4 @@
builder.AddProject<Projects.Aspire_Dashboard>(KnownResourceNames.AspireDashboard);

builder.Build().Run();

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireHost>true</IsAspireHost>
</PropertyGroup>

<ItemGroup>
<Compile Include="$(SharedDir)KnownResourceNames.cs" Link="KnownResourceNames.cs" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\Aspire.Dashboard\Aspire.Dashboard.csproj" />
<ProjectReference Include="..\..\..\src\Aspire.Hosting\Aspire.Hosting.csproj" IsAspireProjectResource="false" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Project>

<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />

<!-- NOTE: This line is only required because we are using P2P references, not NuGet. It will not exist in real apps. -->
<Import Project="../../../src/Aspire.Hosting/build/Aspire.Hosting.props" />

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project>

<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.targets', '$(MSBuildThisFileDirectory)../'))" />

<!-- NOTE: These lines are only required because we are using P2P references, not NuGet. They will not exist in real apps. -->
<Import Project="..\..\..\src\Aspire.Hosting\build\Aspire.Hosting.targets" />
<Import Project="..\..\..\src\Aspire.Hosting.Sdk\SDK\Sdk.targets" />

</Project>
17 changes: 17 additions & 0 deletions playground/CustomResources/CustomResources.AppHost/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

var builder = DistributedApplication.CreateBuilder(args);

builder.AddTestResource("test");

builder.AddParameter("p0");

// This project is only added in playground projects to support development/debugging
// of the dashboard. It is not required in end developer code. Comment out this code
// to test end developer dashboard launch experience. Refer to Directory.Build.props
// for the path to the dashboard binary (defaults to the Aspire.Dashboard bin output
// in the artifacts dir).
builder.AddProject<Projects.Aspire_Dashboard>(KnownResourceNames.AspireDashboard);

builder.Build().Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:15888",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:16175",
"DOTNET_ASPIRE_SHOW_DASHBOARD_RESOURCES": "true"
}
},
"generate-manifest": {
"commandName": "Project",
"launchBrowser": true,
"dotnetRunMessages": true,
"commandLineArgs": "--publisher manifest --output-path aspire-manifest.json",
"applicationUrl": "http://localhost:15888",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:16175"
}
}
}
}
84 changes: 84 additions & 0 deletions playground/CustomResources/CustomResources.AppHost/TestResource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using Aspire.Hosting.Lifecycle;

static class TestResourceExtensions
{
public static IResourceBuilder<TestResource> AddTestResource(this IDistributedApplicationBuilder builder, string name)
{
builder.Services.AddLifecycleHook<TestResourceLifecycleHook>();

var rb = builder.AddResource(new TestResource(name))
.WithCustomResourceState(() => new()
{
ResourceType = "Test Resource",
State = "Starting",
Properties = [
("P1", "P2"),
(CustomResourceKnownProperties.Source, "Custom")
]
})
.ExcludeFromManifest();

return rb;
}
}

internal sealed class TestResourceLifecycleHook : IDistributedApplicationLifecycleHook, IAsyncDisposable
{
private readonly CancellationTokenSource _tokenSource = new();
JamesNK marked this conversation as resolved.
Show resolved Hide resolved

public Task BeforeStartAsync(DistributedApplicationModel appModel, CancellationToken cancellationToken = default)
{
foreach (var item in appModel.Resources.OfType<TestResource>())
{
if (item.TryGetLastAnnotation<CustomResourceAnnotation>(out var annotation))
{
var states = new[] { "Starting", "Running", "Finished" };
davidfowl marked this conversation as resolved.
Show resolved Hide resolved

Task.Run(async () =>
davidfowl marked this conversation as resolved.
Show resolved Hide resolved
{
// Simulate custom resource state changes
var state = annotation.GetInitialSnapshot();
var seconds = Random.Shared.Next(2, 12);

state = state with
{
Properties = [.. state.Properties, ("Interval", seconds.ToString(CultureInfo.InvariantCulture))]
};

// This might run before the dashboard is ready to receive updates, but it will be queued.
await annotation.UpdateStateAsync(state);

using var timer = new PeriodicTimer(TimeSpan.FromSeconds(seconds));

while (await timer.WaitForNextTickAsync(_tokenSource.Token))
{
state = state with
{
State = states[Random.Shared.Next(0, states.Length)]
};

await annotation.UpdateStateAsync(state);
}
},
cancellationToken);
}
}

return Task.CompletedTask;
}

public ValueTask DisposeAsync()
{
_tokenSource.Cancel();
return default;
}
}

sealed class TestResource(string name) : Resource(name)
{

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Aspire.Hosting.Dcp": "Warning"
}
}
}
4 changes: 2 additions & 2 deletions src/Aspire.Dashboard/Components/Pages/Resources.razor
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
ShowIndeterminate="false"
ThreeStateOrderUncheckToIntermediate="true"
@bind-CheckState="AreAllTypesVisible" />
@foreach (var resourceType in _allResourceTypes)
@foreach (var (resourceType, _) in _allResourceTypes)
{
var isChecked = _visibleResourceTypes.Contains(resourceType);
var isChecked = _visibleResourceTypes.ContainsKey(resourceType);
<FluentCheckbox
Label="@resourceType"
@bind-Value:get="isChecked"
Expand Down
47 changes: 36 additions & 11 deletions src/Aspire.Dashboard/Components/Pages/Resources.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Diagnostics;
using Aspire.Dashboard.Model;
using Aspire.Dashboard.Otlp.Model;
Expand All @@ -28,46 +27,65 @@ public partial class Resources : ComponentBase, IDisposable

private readonly CancellationTokenSource _watchTaskCancellationTokenSource = new();
private readonly ConcurrentDictionary<string, ResourceViewModel> _resourceByName = new(StringComparers.ResourceName);
// TODO populate resource types from server data
private readonly ImmutableArray<string> _allResourceTypes = [KnownResourceTypes.Project, KnownResourceTypes.Executable, KnownResourceTypes.Container];
private readonly HashSet<string> _visibleResourceTypes;
private readonly ConcurrentDictionary<string, bool> _allResourceTypes = [];
private readonly ConcurrentDictionary<string, bool> _visibleResourceTypes;
private string _filter = "";
private bool _isTypeFilterVisible;

public Resources()
{
_visibleResourceTypes = new HashSet<string>(_allResourceTypes, StringComparers.ResourceType);
_visibleResourceTypes = new(StringComparers.ResourceType);
}

private bool Filter(ResourceViewModel resource) => _visibleResourceTypes.Contains(resource.ResourceType) && (_filter.Length == 0 || resource.MatchesFilter(_filter));
private bool Filter(ResourceViewModel resource) => _visibleResourceTypes.ContainsKey(resource.ResourceType) && (_filter.Length == 0 || resource.MatchesFilter(_filter));

protected void OnResourceTypeVisibilityChanged(string resourceType, bool isVisible)
{
if (isVisible)
{
_visibleResourceTypes.Add(resourceType);
_visibleResourceTypes[resourceType] = true;
}
else
{
_visibleResourceTypes.Remove(resourceType);
_visibleResourceTypes.TryRemove(resourceType, out _);
}
}

private bool? AreAllTypesVisible
{
get
{
return _visibleResourceTypes.SetEquals(_allResourceTypes)
static bool SetEqualsKeys(ConcurrentDictionary<string, bool> left, ConcurrentDictionary<string, bool> right)
{
// PERF: This is inefficient since Keys locks and copies the keys.
var keysLeft = left.Keys;
var keysRight = right.Keys;

return keysLeft.Count == keysRight.Count && keysLeft.SequenceEqual(keysRight, StringComparers.ResourceType);
}

return SetEqualsKeys(_visibleResourceTypes, _allResourceTypes)
? true
: _visibleResourceTypes.Count == 0
: _visibleResourceTypes.IsEmpty
? false
: null;
}
set
{
static bool UnionWithKeys(ConcurrentDictionary<string, bool> left, ConcurrentDictionary<string, bool> right)
{
// .Keys locks and copies the keys so avoid it here.
foreach (var (key, _) in right)
{
left[key] = true;
}

return true;
}

if (value is true)
{
_visibleResourceTypes.UnionWith(_allResourceTypes);
UnionWithKeys(_visibleResourceTypes, _allResourceTypes);
}
else if (value is false)
{
Expand Down Expand Up @@ -105,6 +123,10 @@ void SubscribeResources()
foreach (var resource in snapshot)
{
var added = _resourceByName.TryAdd(resource.Name, resource);

_allResourceTypes.TryAdd(resource.ResourceType, true);
_visibleResourceTypes.TryAdd(resource.ResourceType, true);

Debug.Assert(added, "Should not receive duplicate resources in initial snapshot data.");
}

Expand All @@ -116,6 +138,9 @@ void SubscribeResources()
if (changeType == ResourceViewModelChangeType.Upsert)
{
_resourceByName[resource.Name] = resource;

_allResourceTypes[resource.ResourceType] = true;
_visibleResourceTypes[resource.ResourceType] = true;
}
else if (changeType == ResourceViewModelChangeType.Delete)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,13 @@ else if (Resource.TryGetContainerImage(out var containerImage))
PreCopyToolTip="@Loc[nameof(Columns.SourceColumnSourceCopyContainerToClipboard)]"
ToolTip="@containerImage" />
}
else
else if (Resource.Properties.TryGetValue(KnownProperties.Resource.Source, out var value) && value.HasStringValue)
{
// TODO we need to add support for arbitrary resource types. Until then, they'll just show an empty source column.
<GridValue Value="@value.StringValue"
EnableHighlighting="true"
HighlightText="@FilterText"
PreCopyToolTip="@Loc[nameof(Columns.SourceColumnSourceCopyContainerToClipboard)]"
ToolTip="@value.StringValue" />
}

@code {
Expand Down
Loading