-
Notifications
You must be signed in to change notification settings - Fork 720
feat: new extension API WithExecCommand
#10779
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
Closed
Closed
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
7a96637
init
DeagleGross d792a64
impl?
DeagleGross 90906df
cleanup resources as well
DeagleGross 878dd12
merge main
DeagleGross 14ab65e
cleanup ContainerExecsMap as well
DeagleGross fe2dfed
address PR comments x1
DeagleGross 7e645d9
revert backchannel type rename
DeagleGross cb38034
address PR comments x1
DeagleGross 87db4da
stabilize and refactor
DeagleGross File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
52 changes: 52 additions & 0 deletions
52
src/Aspire.Hosting/ApplicationModel/ResourceExecCommandAnnotation.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Diagnostics; | ||
|
|
||
| namespace Aspire.Hosting.ApplicationModel; | ||
|
|
||
| /// <summary> | ||
| /// Represents a command annotation for a resource. | ||
| /// </summary> | ||
| [DebuggerDisplay("Type = {GetType().Name,nq}, Name = {Name}")] | ||
| public sealed class ResourceExecCommandAnnotation : IResourceAnnotation | ||
| { | ||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="ResourceExecCommandAnnotation"/> class. | ||
| /// </summary> | ||
| public ResourceExecCommandAnnotation( | ||
| string name, | ||
| string displayName, | ||
| string command, | ||
| string? workingDirectory) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(name); | ||
| ArgumentNullException.ThrowIfNull(displayName); | ||
| ArgumentNullException.ThrowIfNull(command); | ||
|
|
||
| Name = name; | ||
| DisplayName = displayName; | ||
| Command = command; | ||
| WorkingDirectory = workingDirectory; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// The name of the command. | ||
| /// </summary> | ||
| public string Name { get; } | ||
|
|
||
| /// <summary> | ||
| /// The display name of the command. | ||
| /// </summary> | ||
| public string DisplayName { get; } | ||
|
|
||
| /// <summary> | ||
| /// The command to execute. | ||
| /// </summary> | ||
| public string Command { get; } | ||
|
|
||
| /// <summary> | ||
| /// The working directory in which the command will be executed. | ||
| /// </summary> | ||
| public string? WorkingDirectory { get; set; } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Runtime.CompilerServices; | ||
| using Aspire.Hosting.ApplicationModel; | ||
| using Aspire.Hosting.Dcp; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Aspire.Hosting.Exec; | ||
|
|
||
| /// <summary> | ||
| /// A service to execute container exec commands. | ||
| /// </summary> | ||
| internal class ContainerExecService : IContainerExecService | ||
| { | ||
| private readonly ResourceNotificationService _resourceNotificationService; | ||
| private readonly ResourceLoggerService _resourceLoggerService; | ||
|
|
||
| private readonly IDcpExecutor _dcpExecutor; | ||
| private readonly DcpNameGenerator _dcpNameGenerator; | ||
|
|
||
| public ContainerExecService( | ||
| ResourceNotificationService resourceNotificationService, | ||
| ResourceLoggerService resourceLoggerService, | ||
| IDcpExecutor dcpExecutor, | ||
| DcpNameGenerator dcpNameGenerator) | ||
| { | ||
| _resourceNotificationService = resourceNotificationService; | ||
| _resourceLoggerService = resourceLoggerService; | ||
|
|
||
| _dcpExecutor = dcpExecutor; | ||
| _dcpNameGenerator = dcpNameGenerator; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Execute a command for the specified resource. | ||
| /// </summary> | ||
| /// <param name="resourceId">The specific id of the resource instance.</param> | ||
| /// <param name="commandName">The command name.</param> | ||
| /// <returns>The <see cref="ExecuteCommandResult" /> indicates command success or failure.</returns> | ||
| public ExecCommandRun ExecuteCommand(string resourceId, string commandName) | ||
| { | ||
| if (!_resourceNotificationService.TryGetCurrentState(resourceId, out var resourceEvent)) | ||
| { | ||
| return new() | ||
| { | ||
| ExecuteCommand = token => Task.FromResult(CommandResults.Failure($"Failed to get the resource {resourceId}")) | ||
| }; | ||
| } | ||
|
|
||
| var resource = resourceEvent.Resource; | ||
| if (resource is not ContainerResource containerResource) | ||
| { | ||
| throw new ArgumentException("Resource is not a container resource.", nameof(resourceId)); | ||
| } | ||
|
|
||
| return ExecuteCommand(containerResource, commandName); | ||
| } | ||
|
|
||
| public ExecCommandRun ExecuteCommand(ContainerResource containerResource, string commandName) | ||
| { | ||
| var annotation = containerResource.Annotations.OfType<ResourceExecCommandAnnotation>().SingleOrDefault(a => a.Name == commandName); | ||
| if (annotation is null) | ||
| { | ||
| return new() | ||
| { | ||
| ExecuteCommand = token => Task.FromResult(CommandResults.Failure($"Failed to get the resource {containerResource.Name}")) | ||
| }; | ||
| } | ||
|
|
||
| return ExecuteCommandCore(containerResource, annotation.Name, annotation.Command, annotation.WorkingDirectory); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Executes a command for the specified resource. | ||
| /// </summary> | ||
| /// <param name="resource">The resource to execute a command in.</param> | ||
| /// <param name="commandName"></param> | ||
| /// <param name="command"></param> | ||
| /// <param name="workingDirectory"></param> | ||
| /// <returns></returns> | ||
| private ExecCommandRun ExecuteCommandCore( | ||
| ContainerResource resource, | ||
| string commandName, | ||
| string command, | ||
| string? workingDirectory) | ||
| { | ||
| var resourceId = resource.GetResolvedResourceNames().First(); | ||
|
|
||
| var logger = _resourceLoggerService.GetLogger(resourceId); | ||
| logger.LogInformation("Starting command '{Command}' on resource {ResourceId}", command, resourceId); | ||
|
|
||
| var containerExecResource = new ContainerExecutableResource(commandName, resource, command, workingDirectory); | ||
| _dcpNameGenerator.EnsureDcpInstancesPopulated(containerExecResource); | ||
| var dcpResourceName = containerExecResource.GetResolvedResourceName(); | ||
|
|
||
| Func<CancellationToken, Task<ExecuteCommandResult>> commandResultTask = async (CancellationToken cancellationToken) => | ||
| { | ||
| await _dcpExecutor.RunEphemeralResourceAsync(containerExecResource, cancellationToken).ConfigureAwait(false); | ||
| await _resourceNotificationService.WaitForResourceAsync(containerExecResource.Name, targetStates: KnownResourceStates.TerminalStates, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| if (!_resourceNotificationService.TryGetCurrentState(dcpResourceName, out var resourceEvent)) | ||
| { | ||
| return CommandResults.Failure("Failed to fetch command results."); | ||
| } | ||
|
|
||
| // resource completed execution, so we can complete the log stream | ||
| _resourceLoggerService.Complete(dcpResourceName); | ||
|
|
||
| var snapshot = resourceEvent.Snapshot; | ||
| return snapshot.ExitCode is 0 | ||
| ? CommandResults.Success() | ||
| : CommandResults.Failure($"Command failed with exit code {snapshot.ExitCode}. Final state: {resourceEvent.Snapshot.State?.Text}."); | ||
| }; | ||
|
|
||
| return new ExecCommandRun | ||
| { | ||
| ExecuteCommand = commandResultTask, | ||
| GetOutputStream = token => GetResourceLogsStreamAsync(dcpResourceName, token) | ||
| }; | ||
| } | ||
|
|
||
| private async IAsyncEnumerable<LogLine> GetResourceLogsStreamAsync(string dcpResourceName, [EnumeratorCancellation] CancellationToken cancellationToken) | ||
| { | ||
| IAsyncEnumerable<IReadOnlyList<LogLine>> source; | ||
| if (_resourceNotificationService.TryGetCurrentState(dcpResourceName, out var resourceEvent) | ||
| && resourceEvent.Snapshot.ExitCode is not null) | ||
| { | ||
| // If the resource is already in a terminal state, we can just return the logs that were already collected. | ||
| source = _resourceLoggerService.GetAllAsync(dcpResourceName); | ||
| } | ||
| else | ||
| { | ||
| // resource is still running, so we can stream the logs as they come in. | ||
| source = _resourceLoggerService.WatchAsync(dcpResourceName); | ||
| } | ||
|
|
||
| await foreach (var batch in source.WithCancellation(cancellationToken).ConfigureAwait(false)) | ||
| { | ||
| foreach (var logLine in batch) | ||
| { | ||
| yield return logLine; | ||
| } | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems awkward that the call to
ContainerExecService.ExecuteCommand()does not, in fact, executes the command.Consider making this method an async method and taking the call to
RunEphemenralResourceAsync()out of the result-producing task. This will guarantee that whenExecuteCommandCore()returns without exception, the command is started. The returned run object would then exposeGetResultAsync()method for waiting on the result.This change also guarantees that calling
GetOutputStream()on the returned run object always makes sense. Without it, it is possible to ask for output stream without actually starting the command, which will result in waiting forever (until the cancellation token expires)