Skip to content

Commit

Permalink
Azure provisioning in the dashboard (#2552)
Browse files Browse the repository at this point in the history
This change makes it possible (and cleaner IMO) to publish and log data about a resource to the dashboard and does that to show errors when creating resources and for showing provisioning progress when using the Aspire.Hosting.Azure.Provisioning package.  This change consolidates the previously made annotations for publishing and subscribing to both resource updates and logs general purpose services instead of annotations.
  • Loading branch information
davidfowl committed Mar 2, 2024
1 parent 20d98e3 commit 53d0fe3
Show file tree
Hide file tree
Showing 52 changed files with 1,621 additions and 968 deletions.
62 changes: 26 additions & 36 deletions playground/CustomResources/CustomResources.AppHost/TestResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,10 @@ static class TestResourceExtensions
{
public static IResourceBuilder<TestResource> AddTestResource(this IDistributedApplicationBuilder builder, string name)
{
builder.Services.AddLifecycleHook<TestResourceLifecycleHook>();
builder.Services.TryAddLifecycleHook<TestResourceLifecycleHook>();

var rb = builder.AddResource(new TestResource(name))
.WithResourceLogger()
.WithResourceUpdates(() => new()
.WithInitialState(new()
{
ResourceType = "Test Resource",
State = "Starting",
Expand All @@ -28,53 +27,44 @@ public static IResourceBuilder<TestResource> AddTestResource(this IDistributedAp
}
}

internal sealed class TestResourceLifecycleHook : IDistributedApplicationLifecycleHook, IAsyncDisposable
internal sealed class TestResourceLifecycleHook(ResourceNotificationService notificationService, ResourceLoggerService loggerService) : IDistributedApplicationLifecycleHook, IAsyncDisposable
{
private readonly CancellationTokenSource _tokenSource = new();

public Task BeforeStartAsync(DistributedApplicationModel appModel, CancellationToken cancellationToken = default)
{
foreach (var item in appModel.Resources.OfType<TestResource>())
foreach (var resource in appModel.Resources.OfType<TestResource>())
{
if (item.TryGetLastAnnotation<ResourceUpdatesAnnotation>(out var resourceUpdates) &&
item.TryGetLastAnnotation<ResourceLoggerAnnotation>(out var loggerAnnotation))
{
var states = new[] { "Starting", "Running", "Finished" };
var states = new[] { "Starting", "Running", "Finished" };

Task.Run(async () =>
{
// Simulate custom resource state changes
var state = await resourceUpdates.GetInitialSnapshotAsync(_tokenSource.Token);
var seconds = Random.Shared.Next(2, 12);
var logger = loggerService.GetLogger(resource);

state = state with
{
Properties = [.. state.Properties, ("Interval", seconds.ToString(CultureInfo.InvariantCulture))]
};
loggerAnnotation.Logger.LogInformation("Starting test resource {ResourceName} with update interval {Interval} seconds", item.Name, seconds);
Task.Run(async () =>
{
var seconds = Random.Shared.Next(2, 12);
// This might run before the dashboard is ready to receive updates, but it will be queued.
await resourceUpdates.UpdateStateAsync(state);
logger.LogInformation("Starting test resource {ResourceName} with update interval {Interval} seconds", resource.Name, seconds);
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(seconds));
await notificationService.PublishUpdateAsync(resource, state => state with
{
Properties = [.. state.Properties, ("Interval", seconds.ToString(CultureInfo.InvariantCulture))]
});
while (await timer.WaitForNextTickAsync(_tokenSource.Token))
{
var randomState = states[Random.Shared.Next(0, states.Length)];
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(seconds));
state = state with
{
State = randomState
};
while (await timer.WaitForNextTickAsync(_tokenSource.Token))
{
var randomState = states[Random.Shared.Next(0, states.Length)];
loggerAnnotation.Logger.LogInformation("Test resource {ResourceName} is now in state {State}", item.Name, randomState);
await notificationService.PublishUpdateAsync(resource, state => state with
{
State = randomState
});
await resourceUpdates.UpdateStateAsync(state);
}
},
cancellationToken);
}
logger.LogInformation("Test resource {ResourceName} is now in state {State}", resource.Name, randomState);
}
},
cancellationToken);
}

return Task.CompletedTask;
Expand Down
2 changes: 1 addition & 1 deletion playground/bicep/BicepSample.ApiService/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

builder.AddSqlServerDbContext<MyDbContext>("db");
builder.AddNpgsqlDbContext<MyPgDbContext>("db2");
builder.AddAzureCosmosDB("db3");
builder.AddAzureCosmosDB("cosmos");
builder.AddRedis("redis");
builder.AddAzureBlobService("blob");
builder.AddAzureTableService("table");
Expand Down
2 changes: 1 addition & 1 deletion playground/bicep/BicepSample.AppHost/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
.WithParameter("test", parameter)
.WithParameter("values", ["one", "two"]);

var kv = builder.AddAzureKeyVault("kv");
var kv = builder.AddAzureKeyVault("kv3");
var appConfig = builder.AddAzureAppConfiguration("appConfig").WithParameter("sku", "standard");
var storage = builder.AddAzureStorage("storage");
// .RunAsEmulator();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
<li>
@if (displayedEndpoint.Url != null)
{
<a href="@displayedEndpoint.Url" target="_blank">@displayedEndpoint.Url</a>
<a href="@displayedEndpoint.Url" target="_blank">@displayedEndpoint.Text</a>
}
else
{
Expand Down
61 changes: 48 additions & 13 deletions src/Aspire.Dashboard/Model/ResourceEndpointHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,63 @@ internal static class ResourceEndpointHelpers
/// </summary>
public static List<DisplayedEndpoint> GetEndpoints(ILogger logger, ResourceViewModel resource, bool excludeServices = false, bool includeEndpointUrl = false)
{
var isKnownResourceType = resource.IsContainer() || resource.IsExecutable(allowSubtypes: false) || resource.IsProject();

var displayedEndpoints = new List<DisplayedEndpoint>();

if (!excludeServices)
if (isKnownResourceType)
{
foreach (var service in resource.Services)
if (!excludeServices)
{
displayedEndpoints.Add(new DisplayedEndpoint
foreach (var service in resource.Services)
{
Name = service.Name,
Text = service.AddressAndPort,
Address = service.AllocatedAddress,
Port = service.AllocatedPort
});
displayedEndpoints.Add(new DisplayedEndpoint
{
Name = service.Name,
Text = service.AddressAndPort,
Address = service.AllocatedAddress,
Port = service.AllocatedPort
});
}
}
}

foreach (var endpoint in resource.Endpoints)
foreach (var endpoint in resource.Endpoints)
{
ProcessUrl(logger, resource, displayedEndpoints, endpoint.ProxyUrl, "ProxyUrl");
if (includeEndpointUrl)
{
ProcessUrl(logger, resource, displayedEndpoints, endpoint.EndpointUrl, "EndpointUrl");
}
}
}
else
{
ProcessUrl(logger, resource, displayedEndpoints, endpoint.ProxyUrl, "ProxyUrl");
if (includeEndpointUrl)
// Look for services with an address (which might be a URL) and use that to match up with endpoints.
// otherwise, just display the endpoints.
var addressLookup = resource.Services.Where(s => s.AllocatedAddress is not null)
.ToDictionary(s => s.AllocatedAddress!);

foreach (var endpoint in resource.Endpoints)
{
ProcessUrl(logger, resource, displayedEndpoints, endpoint.EndpointUrl, "EndpointUrl");
if (addressLookup.TryGetValue(endpoint.EndpointUrl, out var service))
{
displayedEndpoints.Add(new DisplayedEndpoint
{
Name = service.Name,
Url = endpoint.EndpointUrl,
Text = service.Name,
Address = service.AllocatedAddress,
Port = service.AllocatedPort
});
}
else
{
displayedEndpoints.Add(new DisplayedEndpoint
{
Name = endpoint.EndpointUrl,
Text = endpoint.EndpointUrl
});
}
}
}

Expand Down
56 changes: 28 additions & 28 deletions src/Aspire.Dashboard/Resources/Resources.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -215,4 +215,4 @@
<data name="ResourcesDetailsStateProperty" xml:space="preserve">
<value>State</value>
</data>
</root>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public static class AzureProvisionerExtensions
/// </summary>
public static IDistributedApplicationBuilder AddAzureProvisioning(this IDistributedApplicationBuilder builder)
{
builder.Services.AddLifecycleHook<AzureProvisioner>();
builder.Services.TryAddLifecycleHook<AzureProvisioner>();

// Attempt to read azure configuration from configuration
builder.Services.AddOptions<AzureProvisionerOptions>()
Expand Down
Loading

0 comments on commit 53d0fe3

Please sign in to comment.