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

Inject commands on all DCP based resources #5802

Merged
merged 5 commits into from
Sep 21, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ internal static class CommandsConfigurationExtensions
internal const string StopType = "stop";
internal const string RestartType = "restart";

internal static IResourceBuilder<T> WithLifeCycleCommands<T>(this IResourceBuilder<T> builder) where T : IResource
internal static void AddLifeCycleCommands(this IResource resource)
JamesNK marked this conversation as resolved.
Show resolved Hide resolved
{
builder.WithCommand(
resource.Annotations.Add(new ResourceCommandAnnotation(
type: StartType,
displayName: "Start",
executeCommand: async context =>
Expand All @@ -40,9 +40,9 @@ internal static IResourceBuilder<T> WithLifeCycleCommands<T>(this IResourceBuild
}
},
iconName: "Play",
isHighlighted: true);
isHighlighted: true));

builder.WithCommand(
resource.Annotations.Add(new ResourceCommandAnnotation(
type: StopType,
displayName: "Stop",
executeCommand: async context =>
Expand All @@ -68,9 +68,9 @@ internal static IResourceBuilder<T> WithLifeCycleCommands<T>(this IResourceBuild
}
},
iconName: "Stop",
isHighlighted: true);
isHighlighted: true));

builder.WithCommand(
resource.Annotations.Add(new ResourceCommandAnnotation(
type: RestartType,
displayName: "Restart",
executeCommand: async context =>
Expand All @@ -93,9 +93,7 @@ internal static IResourceBuilder<T> WithLifeCycleCommands<T>(this IResourceBuild
}
},
iconName: "ArrowCounterclockwise",
isHighlighted: false);

return builder;
isHighlighted: false));

static bool IsStopped(string? state) => state is "Exited" or "Finished" or "FailedToStart";
static bool IsStopping(string? state) => state is "Stopping";
Expand Down
1 change: 0 additions & 1 deletion src/Aspire.Hosting/ContainerResourceBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@ public static IResourceBuilder<T> WithImage<T>(this IResourceBuilder<T> builder,
// if the annotation doesn't exist, create it with the given image and add it to the collection
var containerImageAnnotation = new ContainerImageAnnotation() { Image = image, Tag = tag };
builder.Resource.Annotations.Add(containerImageAnnotation);
builder.WithLifeCycleCommands();
return builder;
}

Expand Down
11 changes: 7 additions & 4 deletions src/Aspire.Hosting/Dcp/ApplicationExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1044,7 +1044,7 @@ private void PreparePlainExecutables()

foreach (var executable in modelExecutableResources)
{
EnsureReplicaInstancesAnnotation(executable);
EnsureRequiredAnnotations(executable);

var nameSuffix = GetRandomNameSuffix();
var exeName = GetObjectNameForResource(executable, nameSuffix);
Expand Down Expand Up @@ -1076,7 +1076,7 @@ private void PrepareProjectExecutables()
throw new InvalidOperationException("A project resource is missing required metadata"); // Should never happen.
}

EnsureReplicaInstancesAnnotation(project);
EnsureRequiredAnnotations(project);

var replicas = project.GetReplicaCount();

Expand Down Expand Up @@ -1165,8 +1165,11 @@ private void PrepareProjectExecutables()
}
}

private static void EnsureReplicaInstancesAnnotation(IResource resource)
private static void EnsureRequiredAnnotations(IResource resource)
{
// Add the default lifecycle commands (start/stop/restart)
resource.AddLifeCycleCommands();
davidfowl marked this conversation as resolved.
Show resolved Hide resolved

// Make sure we have a replica annotation on the resource.
// this is so that we can populate the running instance ids
if (!resource.TryGetLastAnnotation<ReplicaInstancesAnnotation>(out _))
Expand Down Expand Up @@ -1411,7 +1414,7 @@ private void PrepareContainers()
throw new InvalidOperationException();
}

EnsureReplicaInstancesAnnotation(container);
EnsureRequiredAnnotations(container);

var nameSuffix = container.GetContainerLifetimeType() switch
{
Expand Down
3 changes: 1 addition & 2 deletions src/Aspire.Hosting/ExecutableResourceBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ public static IResourceBuilder<ExecutableResource> AddExecutable(this IDistribut
{
context.Args.AddRange(args);
}
})
.WithLifeCycleCommands();
});
}

/// <summary>
Expand Down
1 change: 0 additions & 1 deletion src/Aspire.Hosting/ProjectResourceBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,6 @@ private static IResourceBuilder<ProjectResource> WithProjectDefaults(this IResou

builder.WithOtlpExporter();
builder.ConfigureConsoleLogs();
builder.WithLifeCycleCommands();

var projectResource = builder.Resource;

Expand Down
34 changes: 34 additions & 0 deletions tests/Aspire.Hosting.Tests/Dcp/ApplicationExecutorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -913,6 +913,34 @@ public async Task ErrorIfResourceNotDeletedBeforeRestart()
Assert.Equal($"Failed to delete '{dcpCtr.Metadata.Name}' successfully before restart.", ex.Message);
}

[Fact]
public async Task AddsDefaultsCommandsToResources()
{
var builder = DistributedApplication.CreateBuilder();
var container = builder.AddContainer("database", "image");
var exe = builder.AddExecutable("node", "node.exe", ".");
var project = builder.AddProject<TestProject>("project");

var kubernetesService = new TestKubernetesService();
using var app = builder.Build();
var distributedAppModel = app.Services.GetRequiredService<DistributedApplicationModel>();
var appExecutor = CreateAppExecutor(distributedAppModel, app.Services, kubernetesService: kubernetesService);
await appExecutor.RunApplicationAsync();

HasKnownCommandAnnotations(exe.Resource);
HasKnownCommandAnnotations(container.Resource);
HasKnownCommandAnnotations(project.Resource);
}

private static void HasKnownCommandAnnotations(IResource resource)
{
var commandAnnotations = resource.Annotations.OfType<ResourceCommandAnnotation>().ToList();
Assert.Collection(commandAnnotations,
a => Assert.Equal(CommandsConfigurationExtensions.StartType, a.Type),
a => Assert.Equal(CommandsConfigurationExtensions.StopType, a.Type),
a => Assert.Equal(CommandsConfigurationExtensions.RestartType, a.Type));
}

private static ApplicationExecutor CreateAppExecutor(
DistributedApplicationModel distributedAppModel,
IServiceProvider serviceProvider,
Expand Down Expand Up @@ -954,4 +982,10 @@ private static ApplicationExecutor CreateAppExecutor(
serviceProvider
);
}

private sealed class TestProject : IProjectMetadata
{
public string ProjectPath => "TestProject";
public LaunchSettings LaunchSettings { get; } = new();
}
}
35 changes: 1 addition & 34 deletions tests/Aspire.Hosting.Tests/ResourceCommandAnnotationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,6 @@ namespace Aspire.Hosting.Tests;

public class ResourceCommandAnnotationTests
{
[Fact]
public void AddContainer_HasKnownCommandAnnotations()
{
HasKnownCommandAnnotationsCore(builder => builder.AddContainer("name", "image"));
}

[Fact]
public void AddProject_HasKnownCommandAnnotations()
{
HasKnownCommandAnnotationsCore(builder => builder.AddProject("name", "path", o => o.ExcludeLaunchProfile = true));
}

[Fact]
public void AddExecutable_HasKnownCommandAnnotations()
{
HasKnownCommandAnnotationsCore(builder => builder.AddExecutable("name", "command", "workingDirectory"));
}

[Theory]
[InlineData(CommandsConfigurationExtensions.StartType, "Starting", ResourceCommandState.Disabled)]
[InlineData(CommandsConfigurationExtensions.StartType, "Stopping", ResourceCommandState.Hidden)]
Expand Down Expand Up @@ -53,6 +35,7 @@ public void LifeCycleCommands_CommandState(string commandType, string resourceSt
// Arrange
var builder = DistributedApplication.CreateBuilder();
var resourceBuilder = builder.AddContainer("name", "image");
resourceBuilder.Resource.AddLifeCycleCommands();

var startCommand = resourceBuilder.Resource.Annotations.OfType<ResourceCommandAnnotation>().Single(a => a.Type == commandType);

Expand All @@ -71,20 +54,4 @@ public void LifeCycleCommands_CommandState(string commandType, string resourceSt
// Assert
Assert.Equal(commandState, state);
}

private static void HasKnownCommandAnnotationsCore<T>(Func<IDistributedApplicationBuilder, IResourceBuilder<T>> createResourceBuilder) where T : IResource
{
// Arrange
var builder = DistributedApplication.CreateBuilder();

// Act
var resourceBuilder = createResourceBuilder(builder);

// Assert
var commandAnnotations = resourceBuilder.Resource.Annotations.OfType<ResourceCommandAnnotation>().ToList();
Assert.Collection(commandAnnotations,
a => Assert.Equal(CommandsConfigurationExtensions.StartType, a.Type),
a => Assert.Equal(CommandsConfigurationExtensions.StopType, a.Type),
a => Assert.Equal(CommandsConfigurationExtensions.RestartType, a.Type));
}
}
Loading