From 3c0d25ceed2a7de6fee66f9475e4c990919352ea Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Mon, 2 Jun 2025 10:57:12 -0400 Subject: [PATCH 01/24] rebase main --- Directory.Packages.props | 10 +- ...tyToolkit.Aspire.PowerShell.AppHost.csproj | 24 ++ .../Program.cs | 39 +++ .../Properties/launchSettings.json | 29 ++ .../Scripts/script.ps1 | 3 + .../appsettings.json | 9 + ...tyToolkit.Aspire.Hosting.PowerShell.csproj | 19 ++ ...DistributedApplicationBuilderExtensions.cs | 99 +++++++ .../PowerShellRunspacePoolResource.cs | 149 ++++++++++ ...llRunspacePoolResourceBuilderExtensions.cs | 124 ++++++++ .../PowerShellScriptResource.cs | 269 ++++++++++++++++++ ...werShellScriptResourceBuilderExtensions.cs | 29 ++ .../README.md | 54 ++++ .../AppHostTests.cs | 84 ++++++ ...kit.Aspire.Hosting.PowerShell.Tests.csproj | 9 + 15 files changed, 944 insertions(+), 6 deletions(-) create mode 100644 examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/CommunityToolkit.Aspire.PowerShell.AppHost.csproj create mode 100644 examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs create mode 100644 examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Properties/launchSettings.json create mode 100644 examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Scripts/script.ps1 create mode 100644 examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/appsettings.json create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResourceBuilderExtensions.cs create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/README.md create mode 100644 tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs create mode 100644 tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests.csproj diff --git a/Directory.Packages.props b/Directory.Packages.props index 9fba0aaf1..aa9a6fb8e 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -6,8 +6,9 @@ + - + @@ -17,6 +18,7 @@ + @@ -54,11 +56,9 @@ - - @@ -83,7 +83,6 @@ - @@ -99,9 +98,8 @@ - - + \ No newline at end of file diff --git a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/CommunityToolkit.Aspire.PowerShell.AppHost.csproj b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/CommunityToolkit.Aspire.PowerShell.AppHost.csproj new file mode 100644 index 000000000..63aed919d --- /dev/null +++ b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/CommunityToolkit.Aspire.PowerShell.AppHost.csproj @@ -0,0 +1,24 @@ + + + + + + Exe + net8.0 + enable + enable + true + bc193f31-c9f7-4e3d-b70a-0dc39ec3047f + + + + + + + + + + + + + diff --git a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs new file mode 100644 index 000000000..b335604d6 --- /dev/null +++ b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs @@ -0,0 +1,39 @@ +using CommunityToolkit.Aspire.Hosting.PowerShell; + +var builder = DistributedApplication.CreateBuilder(args); + +var storage = builder.AddAzureStorage("storage").RunAsEmulator(); +var blob = storage.AddBlobs("myblob"); + +var ps = builder.AddPowerShell("ps") + .WithReference(blob) + .WaitFor(storage); + +// uploads the script in scripts/ +var script1 = ps.AddScript("script1", """ + param($name) + + write-information "Hello, $name" + + # uncommenting this will hang the script if you don't attach the pwsh debugger + # wait-debugger + + write-information "`$myblob is $myblob" + + az storage container create --connection-string $myblob -n demo + az storage blob upload --connection-string $myblob -c demo --file ./scripts/script.ps1 + + write-information $pwd + + write-information "Blob uploaded" +""").WithArgs("world"); + +// outputs "the sum of 2 and 3 is 5" +var script2 = ps.AddScript("script2", """ + & ./scripts/script.ps1 @args + """) + .WithArgs(2, 3) + .WaitForCompletion(script1); + +builder.Build().Run(); + diff --git a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Properties/launchSettings.json b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Properties/launchSettings.json new file mode 100644 index 000000000..80e6457ea --- /dev/null +++ b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17118;http://localhost:15215", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21165", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22038" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15215", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19175", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20201" + } + } + } +} diff --git a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Scripts/script.ps1 b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Scripts/script.ps1 new file mode 100644 index 000000000..4749399b3 --- /dev/null +++ b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Scripts/script.ps1 @@ -0,0 +1,3 @@ +param($a, $b) + +Write-Information "The sum of $a and $b is: $($a + $b)" \ No newline at end of file diff --git a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/appsettings.json b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/appsettings.json new file mode 100644 index 000000000..31c092aa4 --- /dev/null +++ b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj b/src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj new file mode 100644 index 000000000..045a19c73 --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + powershell; pwsh; scripting; script; hosting + Run powershell scripts in-process with your Aspire AppHost, injecting aspire resources and/or object instances as variables, using the command lines tools of your choice like azure cli, azd, or any other terminal tools. + + + + + + + + + + + diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs new file mode 100644 index 000000000..953ddde90 --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs @@ -0,0 +1,99 @@ +using Aspire.Hosting; +using Aspire.Hosting.ApplicationModel; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Runspaces; + +namespace CommunityToolkit.Aspire.Hosting.PowerShell; + +/// +/// Extensions for the to add PowerShell runspace pool resources. +/// +public static class DistributedApplicationBuilderExtensions +{ + /// + /// Adds a PowerShell runspace pool resource to the distributed application. + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static IResourceBuilder AddPowerShell( + this IDistributedApplicationBuilder builder, + [ResourceName] string name, + PSLanguageMode languageMode = PSLanguageMode.ConstrainedLanguage, + int minRunspaces = 1, + int maxRunspaces = 5) + { + if (string.IsNullOrWhiteSpace(name)) + throw new ArgumentException("Value cannot be null or whitespace.", nameof(name)); + + if (builder.Resources.OfType().Any( + rsp => rsp.Name == name)) + { + throw new DistributedApplicationException("AddPowerShell failed", + new InvalidOperationException( + string.Format( + CultureInfo.InvariantCulture, + "A PowerShell resource with the name '{0}' already exists.", name))); + } + + var pool = new PowerShellRunspacePoolResource(name, languageMode, minRunspaces, maxRunspaces); + + builder.Eventing.Subscribe(async (e, ct) => + { + var pools = e.Model.Resources.OfType().ToList(); + + foreach (var poolResource in pools) + { + Debug.Assert(poolResource is not null); + + var loggerService = e.Services.GetRequiredService(); + var notificationService = e.Services.GetRequiredService(); + + var sessionState = InitialSessionState.CreateDefault(); + + foreach (var annotation in poolResource.Annotations) + { + if (annotation is PowerShellVariableReferenceAnnotation reference) + { + var connectionString = await reference.Value.Resource.GetConnectionStringAsync(ct); + sessionState.Variables.Add( + new SessionStateVariableEntry(reference.Name, connectionString, + $"ConnectionString for {reference.Value.Resource.GetType().Name} '{reference.Name}'", + ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope)); + } + } + + var poolName = poolResource.Name; + var poolLogger = loggerService.GetLogger(poolName); + + _ = notificationService.WaitForDependenciesAsync(poolResource, ct) + .ContinueWith( + async _ => + await poolResource.StartAsync(sessionState, notificationService, poolLogger, ct), + ct); + } + }); + + return builder.AddResource(pool) + .WithInitialState(new() + { + ResourceType = "PowerShellRunspacePool", + State = KnownResourceStates.NotStarted, + Properties = [ + + new ("LanguageMode", pool.LanguageMode.ToString()), + new ("MinRunspaces", pool.MinRunspaces.ToString()), + new ("MaxRunspaces", pool.MaxRunspaces.ToString()) + ] + }) + .ExcludeFromManifest(); + } +} \ No newline at end of file diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs new file mode 100644 index 000000000..605e0409c --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs @@ -0,0 +1,149 @@ +using Aspire.Hosting.ApplicationModel; +using Microsoft.Extensions.Logging; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Runspaces; + +namespace CommunityToolkit.Aspire.Hosting.PowerShell; + +/// +/// Represents a PowerShell runspace pool resource. +/// +public class PowerShellRunspacePoolResource( + [ResourceName] string name, + PSLanguageMode languageMode = PSLanguageMode.ConstrainedLanguage, + int minRunspaces = 1, + int maxRunspaces = 5) + : Resource(name), IDisposable, IResourceWithWaitSupport +{ + /// + /// Specifies the language mode for the PowerShell runspace pool. + /// + public PSLanguageMode LanguageMode { get; } = languageMode; + + /// + /// Specifies the minimum number of runspaces in the pool. + /// + public int MinRunspaces { get; } = minRunspaces; + + /// + /// Specifies the maximum number of runspaces in the pool. + /// + public int MaxRunspaces { get; } = maxRunspaces; + + /// + /// A reference to the runspace pool created by this resource. + /// + public RunspacePool? Pool { get; private set; } + + internal Task StartAsync(InitialSessionState sessionState, ResourceNotificationService notificationService, ILogger logger, CancellationToken token = default) + { + sessionState.LanguageMode = this.LanguageMode; + sessionState.AuthorizationManager = new AuthorizationManager("Aspire"); + Pool = RunspaceFactory.CreateRunspacePool(MinRunspaces, MaxRunspaces, sessionState, new AspirePSHost(logger)); + + ConfigureStateChangeNotifications(notificationService, logger); + + return Task.Factory.FromAsync(Pool.BeginOpen, Pool.EndOpen, null); + } + + private void ConfigureStateChangeNotifications(ResourceNotificationService notificationService, ILogger logger) + { + Pool!.StateChanged += async (_, args) => + { + var poolState = args.RunspacePoolStateInfo.State; + var reason = args.RunspacePoolStateInfo.Reason; + + logger.LogInformation( + "Runspace pool '{PoolName}' state changed to '{RunspacePoolState}'", Name, poolState); + + // map args.RunspacePoolStateInfo.State to a KnownResourceState + // and publish the update + + var knownState = poolState switch + { + RunspacePoolState.BeforeOpen => KnownResourceStates.NotStarted, + RunspacePoolState.Opening => KnownResourceStates.Starting, + RunspacePoolState.Opened => KnownResourceStates.Running, + RunspacePoolState.Closing => KnownResourceStates.Stopping, + RunspacePoolState.Closed => KnownResourceStates.Exited, + RunspacePoolState.Broken => KnownResourceStates.FailedToStart, + _ => throw new ArgumentOutOfRangeException( + nameof(poolState), poolState, $"Unexpected runspace pool state {poolState}") + }; + + await notificationService.PublishUpdateAsync(this, + state => { + state = state with + { + State = knownState, + Properties = [.. state.Properties, + new("RunspacePoolState", poolState.ToString()), + new("Reason", reason?.ToString() ?? string.Empty) + ] + }; + + if (knownState == KnownResourceStates.Running) + { + state = state with + { + StartTimeStamp = DateTime.Now, + }; + } + + if (KnownResourceStates.TerminalStates.Contains(knownState)) + { + state = state with + { + StopTimeStamp = DateTime.Now, + }; + } + + return state; + }); + }; + } + + // absolutely brain dead and deficient (minimal) PSHost implementation + private class AspirePSHost(ILogger logger) : PSHost + { + public override void SetShouldExit(int exitCode) + { + logger.LogInformation("AspirePSHost: SetShouldExit({ExitCode})", exitCode); + } + + public override void EnterNestedPrompt() + { + throw new NotSupportedException(); + } + + public override void ExitNestedPrompt() + { + throw new NotSupportedException(); + } + + public override void NotifyBeginApplication() + { + logger.LogInformation("AspirePSHost: NotifyBeginApplication"); + } + + public override void NotifyEndApplication() + { + logger.LogInformation("AspirePSHost: NotifyEndApplication"); + } + + public override string Name { get; } = "AspirePSHost"; + public override Version Version { get; } = new (0, 1); + public override Guid InstanceId { get; } = Guid.NewGuid(); + public override PSHostUserInterface UI => null!; // interaction not supported + public override CultureInfo CurrentCulture { get; } = CultureInfo.CurrentCulture; + public override CultureInfo CurrentUICulture { get; } = CultureInfo.CurrentUICulture; + } + + void IDisposable.Dispose() + { + Pool?.Close(); + Pool?.Dispose(); + } +} \ No newline at end of file diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs new file mode 100644 index 000000000..bf0fdc4dd --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs @@ -0,0 +1,124 @@ +using Aspire.Hosting; +using Aspire.Hosting.ApplicationModel; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +namespace CommunityToolkit.Aspire.Hosting.PowerShell; + +/// +/// Extensions for the PowerShellRunspacePoolResourceBuilder. +/// +public static class PowerShellRunspacePoolResourceBuilderExtensions +{ + /// + /// Adds a PowerShell script resource to the distributed application. + /// + /// + /// + /// + /// + public static IResourceBuilder AddScript( + this IResourceBuilder builder, + [ResourceName] string name, + [StringSyntax("PowerShell")] string script) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentException.ThrowIfNullOrWhiteSpace(script); + + // parse to force an early exception if the script is invalid + var scriptBlock = ScriptBlock.Create(script); + + var scriptResource = new PowerShellScriptResource(name, scriptBlock, builder.Resource); + + builder.ApplicationBuilder.Eventing.Subscribe(scriptResource, (e, ct) => + { + var loggerService = e.Services.GetRequiredService(); + var notificationService = e.Services.GetRequiredService(); + + var scriptName = scriptResource.Name; + var scriptLogger = loggerService.GetLogger(scriptName); + try + { + // TODO: capture script streams and log them + scriptLogger.LogInformation("Starting script '{ScriptName}'", scriptName); + + _ = notificationService + .WaitForDependenciesAsync(scriptResource, ct) + .ContinueWith( + async (_) => await scriptResource.StartAsync(scriptLogger, notificationService, ct), + ct); + } + catch (Exception ex) + { + scriptLogger.LogError(ex, "Failed to start script '{ScriptName}'", scriptName); + } + + return Task.CompletedTask; + }); + + return builder.ApplicationBuilder + .AddResource(scriptResource) + .WaitFor(builder) // wait for pool resource + .WithParentRelationship(builder.Resource) // owned by pool + .WithInitialState(new() + { + ResourceType = "PowerShellScript", + State = KnownResourceStates.NotStarted, + Properties = [ + new ("Script", script), + new("RunspacePool", builder.Resource.Name) + ] + }) + .ExcludeFromManifest() + .WithCommand("break", "Stop script execution", + async _ => + { + await scriptResource.BreakAsync(); + return CommandResults.Success(); + }, + new CommandOptions + { + ConfirmationMessage = "Are you sure you want to stop the script?", + Description = "Stop script execution", + IconName = "Stop", + IsHighlighted = true, + IconVariant = IconVariant.Filled, + UpdateState = updateContext => + updateContext.ResourceSnapshot.State?.Text != KnownResourceStates.Running ? + ResourceCommandState.Disabled : + ResourceCommandState.Enabled + }); + } + + /// + /// Adds a reference to an Aspire resource that implements IResourceWithConnectionString. + /// The resource will be exposed as a PowerShell variable in the runspace that is named after the resource name. + /// + /// + /// + /// + /// + /// + public static IResourceBuilder WithReference(this IResourceBuilder builder, IResourceBuilder source, string? connectionName = null, bool optional = false) + { + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(source); + + var resource = source.Resource; + + builder.WithReferenceRelationship(resource); + + return builder.WithAnnotation(new PowerShellVariableReferenceAnnotation( + resource.Name, new ConnectionStringReference(resource, optional))); + } +} + +/// +/// Represents a PowerShell variable reference annotation. +/// +/// +/// +/// +public record PowerShellVariableReferenceAnnotation(string Name, T Value) : IResourceAnnotation; \ No newline at end of file diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs new file mode 100644 index 000000000..1d13b028e --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs @@ -0,0 +1,269 @@ +using Aspire.Hosting.ApplicationModel; +using Microsoft.Extensions.Logging; +using System.Diagnostics; +using System.Management.Automation; + +namespace CommunityToolkit.Aspire.Hosting.PowerShell +{ + /// + /// Represents a PowerShell script resource. + /// + public class PowerShellScriptResource : Resource, IDisposable, + IResourceWithEnvironment, + IResourceWithWaitSupport, + IResourceWithArgs + { + private readonly System.Management.Automation.PowerShell _ps; + private readonly CancellationTokenSource _cts; + private readonly PowerShellRunspacePoolResource _parent; + private readonly PSDataCollection _output; + private readonly PSDataCollection _emptyInput; + private ILogger? _scriptLogger; + private bool _isDisposed; + + /// + /// Initializes a new instance of the class, representing a resource for + /// executing PowerShell scripts. + /// + /// This class is designed to manage the execution of PowerShell scripts within a + /// specified runspace pool. The script execution is tied to a cancellation token, allowing the script to be + /// stopped when requested. + /// The name of the resource. This must be a valid resource name. + /// The ScriptBlock to be executed. + /// The parent that provides the runspace pool for script + /// execution. Cannot be null. + public PowerShellScriptResource([ResourceName] string name, + ScriptBlock script, + PowerShellRunspacePoolResource parent) : base(name) + { + _parent = parent; + _cts = new CancellationTokenSource(); + _ps = System.Management.Automation.PowerShell.Create(); + + // stop the powershell instance when _cts is cancelled + _cts.Token.Register(() => + { + _scriptLogger?.LogInformation("Stopping PowerShell script execution"); + _ps.Stop(); + }); + + _output = new PSDataCollection(); + _emptyInput = new PSDataCollection(); + _emptyInput.Complete(); + + _ps.AddScript(script.ToString()); + } + + /// + /// Initializes a new instance of the class, representing a resource for + /// executing PowerShell scripts. + /// + /// This class is designed to manage the execution of PowerShell scripts within a + /// specified runspace pool. The script execution is tied to a cancellation token, allowing the script to be + /// stopped when requested. + /// The name of the resource. This must be a valid resource name. + /// The file containing the PowerShell script to be executed. Must be a valid file path and not null. + /// The parent that provides the runspace pool for script + /// execution. Cannot be null. + public PowerShellScriptResource([ResourceName] string name, + FileInfo scriptFile, + PowerShellRunspacePoolResource parent) : base(name) + { + _parent = parent; + _cts = new CancellationTokenSource(); + _ps = System.Management.Automation.PowerShell.Create(); + + // stop the powershell instance when _cts is cancelled + _cts.Token.Register(() => + { + _scriptLogger?.LogInformation("Stopping PowerShell script execution"); + _ps.Stop(); + }); + + _output = new PSDataCollection(); + _emptyInput = new PSDataCollection(); + _emptyInput.Complete(); + + // add scriptFile to the PowerShell instance to be executed + _ps.AddCommand(scriptFile.FullName); + } + + /// + /// Breaks the PowerShell script execution. + /// + /// + public async Task BreakAsync() + { + if (_isDisposed) + { + throw new ObjectDisposedException(nameof(PowerShellScriptResource)); + } + + if (_ps.InvocationStateInfo.State != PSInvocationState.Running) + { + return false; + } + + await _cts.CancelAsync(); + + return true; + } + + /// + /// Starts the PowerShell script execution. + /// + /// + /// + /// + /// + /// + public async Task StartAsync(ILogger scriptLogger, + ResourceNotificationService notificationService, + CancellationToken cancellationToken = default) + { + Debug.Assert(scriptLogger != null); + _scriptLogger = scriptLogger; + + Debug.Assert(_parent.Pool != null); + _ps.RunspacePool = _parent.Pool; + + ConfigurePSDataStreams(scriptLogger, notificationService); + + _ps.InvocationStateChanged += async (_, args) => + { + var knownState = args.InvocationStateInfo.State switch + { + PSInvocationState.NotStarted => KnownResourceStates.NotStarted, + PSInvocationState.Running => KnownResourceStates.Running, + PSInvocationState.Completed => KnownResourceStates.Finished, + PSInvocationState.Stopped => KnownResourceStates.Exited, + PSInvocationState.Failed => KnownResourceStates.FailedToStart, + PSInvocationState.Stopping => KnownResourceStates.Stopping, + _ => throw new ArgumentOutOfRangeException( // probably should be assertion + nameof(args.InvocationStateInfo.State), + args.InvocationStateInfo.State, + "Unknown PowerShell invocation state") + }; + + await notificationService.PublishUpdateAsync(this, + state => + { + state = state with + { + State = knownState, + Properties = [ + .. state.Properties, + new( "PSInvocationState", args.InvocationStateInfo.State.ToString() ), + new( "Reason", args.InvocationStateInfo.Reason?.Message ?? string.Empty ), + ] + }; + + if (knownState == KnownResourceStates.Running) + { + state = state with + { + StartTimeStamp = DateTime.Now, + }; + } + + if (KnownResourceStates.TerminalStates.Contains(knownState)) + { + state = state with + { + StopTimeStamp = DateTime.Now, + }; + } + + return state; + }); + }; + + if (this.TryGetLastAnnotation(out var scriptArgsAnnotation)) + { + foreach (var scriptArg in scriptArgsAnnotation.Args) + { + if (scriptArg is IValueProvider valueProvider) + { + var value = await valueProvider.GetValueAsync(cancellationToken); + _ps.AddArgument(value); + } + else + { + _ps.AddArgument(scriptArg); + } + } + } + + try + { + _ = await _ps.InvokeAsync(_emptyInput, _output); + } + catch (PipelineStoppedException) + { + // This is expected when the pipeline is stopped (i.e. via BreakAsync), so we can ignore it. + // The pipeline will be stopped when the PowerShell instance is disposed. + } + catch (Exception ex) + { + scriptLogger.LogError(ex, "Error invoking PowerShell script: {Message}", ex.Message); + throw; + } + } + + private void ConfigurePSDataStreams(ILogger logger, ResourceNotificationService notifications) + { + _output.DataAdded += (_, args) => + { + var psObject = _output[args.Index]; + logger.LogInformation("Output: {Output}", psObject.ToString()); + }; + _output.Completed += async (_, _) => + { + await notifications.PublishUpdateAsync(this, state => state with + { + State = KnownResourceStates.Finished, + StopTimeStamp = DateTime.Now, + ExitCode = _ps.HadErrors ? 1 : 0, + }); + + logger.LogInformation("Output completed"); + }; + _ps.Streams.Error.DataAdded += (_, args) => + { + var error = _ps.Streams.Error[args.Index]; + logger.LogError(error.Exception, "Error: {Error}", error.ToString()); + }; + _ps.Streams.Warning.DataAdded += (_, args) => + { + var warning = _ps.Streams.Warning[args.Index]; + logger.LogWarning("Warning: {Warning}", warning); + }; + _ps.Streams.Information.DataAdded += (_, args) => + { + var info = _ps.Streams.Information[args.Index]; + logger.LogInformation("Information: {Info}", info); + }; + _ps.Streams.Verbose.DataAdded += (_, args) => + { + var verbose = _ps.Streams.Verbose[args.Index]; + logger.LogInformation("Verbose: {Verbose}", verbose); + }; + _ps.Streams.Debug.DataAdded += (_, args) => + { + var debug = _ps.Streams.Debug[args.Index]; + logger.LogInformation("Debug: {Debug}", debug); + }; + } + + void IDisposable.Dispose() + { + if (_isDisposed) + { + throw new ObjectDisposedException(nameof(PowerShellScriptResource)); + } + _isDisposed = true; + _ps.Stop(); + _ps.Dispose(); + } + } +} diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResourceBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResourceBuilderExtensions.cs new file mode 100644 index 000000000..41861d478 --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResourceBuilderExtensions.cs @@ -0,0 +1,29 @@ +using Aspire.Hosting.ApplicationModel; + +namespace CommunityToolkit.Aspire.Hosting.PowerShell; + + +/// +/// PowerShell script resource builder extensions. +/// +public static class PowerShellScriptResourceBuilderExtensions +{ + /// + /// Provide arguments to the PowerShell script. + /// + /// + /// + /// + public static IResourceBuilder WithArgs( + this IResourceBuilder builder, params object[] args) + { + return builder.WithAnnotation(new PowerShellScriptArgsAnnotation(args)); + } +} + +/// +/// Represents the arguments for a PowerShell script resource. +/// +/// +public record PowerShellScriptArgsAnnotation(object[] Args) : IResourceAnnotation; + diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/README.md b/src/CommunityToolkit.Aspire.Hosting.PowerShell/README.md new file mode 100644 index 000000000..1d2b1aaf9 --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/README.md @@ -0,0 +1,54 @@ +# CommunityToolkit Aspire PowerShell Scripting + +## About + +Script your resources, use the pwsh (powershell core) engine and reference connectionstring expressions, live resources, dotnet instances or whatever else is in scope for your AppHost. + + +```csharp +using CommunityToolkit.Aspire.Hosting.PowerShell; + +var builder = DistributedApplication.CreateBuilder(args); + +var storage = builder.AddAzureStorage("storage").RunAsEmulator(); +var blob = storage.AddBlobs("myblob"); + +var ps = builder.AddPowerShell("ps") + .WithReference(blob) + .WaitFor(storage); + +// uploads the script in scripts/ +var script1 = ps.AddScript("script1", """ + param($name) + + write-information "Hello, $name" + + # uncommenting this will hang the script if you don't attach the pwsh debugger + # wait-debugger + + write-information "`$myblob is $myblob" + + az storage container create --connection-string $myblob -n demo + az storage blob upload --connection-string $myblob -c demo --file ./scripts/script.ps1 + + write-information $pwd + + write-information "Blob uploaded" +""").WithArgs("world"); + +// outputs "the sum of 2 and 3 is 5" +var script2 = ps.AddScript("script2", """ + & ./scripts/script.ps1 @args + """) + .WithArgs(2, 3) + .WaitForCompletion(script1); + +builder.Build().Run(); + +``` + +## Debugging + +While your Apphost is running a script that is waiting via `Wait-Debugger`, open a terminal with powershell (pwsh) 7.4 or later (win, osx, linux) and use `Get-PSHostProcessInfo`, `Enter-PSHostProcess`, `Get-Runspace` and `Debug-Runspace` to connect the debugger. + +See https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/enter-pshostprocess?view=powershell-7.5 for more information. diff --git a/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs b/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs new file mode 100644 index 000000000..b651f0f80 --- /dev/null +++ b/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs @@ -0,0 +1,84 @@ +using Aspire.Components.Common.Tests; +using CommunityToolkit.Aspire.Testing; +using Microsoft.Extensions.Logging; +using Xunit.Abstractions; + +namespace CommunityToolkit.Aspire.Hosting.PowerShell.Tests; + +[RequiresDocker] +public class AppHostTests(AspireIntegrationTestFixture fixture) : + IClassFixture> +{ + [Fact] + public async Task ResourceStartsAndRespondsOk() + { + var resourceName = "ps"; + await fixture.ResourceNotificationService.WaitForResourceAsync(resourceName, KnownResourceStates.Running).WaitAsync(TimeSpan.FromMinutes(5)); + var httpClient = fixture.CreateHttpClient(resourceName); + + var response = await httpClient.GetAsync("/"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + //[Fact] + //public async Task OllamaListsAvailableModels() + //{ + // var distributedAppModel = fixture.App.Services.GetRequiredService(); + // var modelResources = distributedAppModel.Resources.OfType().ToList(); + // var rns = fixture.ResourceNotificationService; + + // await Task.WhenAll([ + // rns.WaitForResourceHealthyAsync("ollama"), + // .. modelResources.Select(m => rns.WaitForResourceHealthyAsync(m.Name)) + // ]).WaitAsync(TimeSpan.FromMinutes(10)); + // var httpClient = fixture.CreateHttpClient("ollama"); + + // var models = (await new OllamaApiClient(httpClient).ListLocalModelsAsync()).ToList(); + + // Assert.NotEmpty(models); + // Assert.Equal(modelResources.Count, models.Count); + //} +} + +public class AppHostTestsX +{ + private readonly ITestOutputHelper _testOutputHelper; + + public AppHostTestsX(ITestOutputHelper testOutputHelper) + { + _testOutputHelper = testOutputHelper; + } + + private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(90); + + + //[Fact] + //public async Task EnsureScriptExecutes() + //{ + // var cancellationToken = new CancellationTokenSource(DefaultTimeout).Token; + // var appHost = await DistributedApplicationTestingBuilder.CreateAsync(cancellationToken); + + // appHost.Services.AddLogging(logging => + // { + // logging.SetMinimumLevel(LogLevel.Debug); + + // // Override the logging filters from the app's configuration + // logging.AddFilter(appHost.Environment.ApplicationName, LogLevel.Debug); + // logging.AddFilter("Aspire.", LogLevel.Debug); + + // logging.AddXUnit(_testOutputHelper); + // }); + + // await using var app = await appHost.BuildAsync(cancellationToken).WaitAsync(DefaultTimeout, cancellationToken); + + // await app.StartAsync(cancellationToken).WaitAsync(DefaultTimeout, cancellationToken); + + // await foreach (var notification in app.ResourceNotifications.WatchAsync(cancellationToken)) + // { + // _testOutputHelper.WriteLine($"Notification: {notification.Resource.Name} - {notification.Snapshot.State} - {notification.Snapshot.HealthStatus}"); + // } + + // Assert.True(true); + //} +} diff --git a/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests.csproj b/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests.csproj new file mode 100644 index 000000000..1080a2c14 --- /dev/null +++ b/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests.csproj @@ -0,0 +1,9 @@ + + + + + + + + + From fa49eaf8e338091b1220506382c402cc9ad5cd55 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Fri, 30 May 2025 20:15:11 -0400 Subject: [PATCH 02/24] add tests --- .../AppHostTests.cs | 87 +++++-------------- 1 file changed, 24 insertions(+), 63 deletions(-) diff --git a/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs b/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs index b651f0f80..284d5c7bd 100644 --- a/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs +++ b/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs @@ -1,7 +1,5 @@ using Aspire.Components.Common.Tests; using CommunityToolkit.Aspire.Testing; -using Microsoft.Extensions.Logging; -using Xunit.Abstractions; namespace CommunityToolkit.Aspire.Hosting.PowerShell.Tests; @@ -10,75 +8,38 @@ public class AppHostTests(AspireIntegrationTestFixture> { [Fact] - public async Task ResourceStartsAndRespondsOk() + public async Task PowerShellResourceStarts() { var resourceName = "ps"; - await fixture.ResourceNotificationService.WaitForResourceAsync(resourceName, KnownResourceStates.Running).WaitAsync(TimeSpan.FromMinutes(5)); - var httpClient = fixture.CreateHttpClient(resourceName); - - var response = await httpClient.GetAsync("/"); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + await fixture.ResourceNotificationService + .WaitForResourceAsync(resourceName, KnownResourceStates.Running) + .WaitAsync(TimeSpan.FromSeconds(60)); + + Assert.True(true); } - //[Fact] - //public async Task OllamaListsAvailableModels() - //{ - // var distributedAppModel = fixture.App.Services.GetRequiredService(); - // var modelResources = distributedAppModel.Resources.OfType().ToList(); - // var rns = fixture.ResourceNotificationService; - - // await Task.WhenAll([ - // rns.WaitForResourceHealthyAsync("ollama"), - // .. modelResources.Select(m => rns.WaitForResourceHealthyAsync(m.Name)) - // ]).WaitAsync(TimeSpan.FromMinutes(10)); - // var httpClient = fixture.CreateHttpClient("ollama"); - - // var models = (await new OllamaApiClient(httpClient).ListLocalModelsAsync()).ToList(); - - // Assert.NotEmpty(models); - // Assert.Equal(modelResources.Count, models.Count); - //} -} - -public class AppHostTestsX -{ - private readonly ITestOutputHelper _testOutputHelper; - - public AppHostTestsX(ITestOutputHelper testOutputHelper) + [Fact] + public async Task ScriptsExecuteSuccessfully() { - _testOutputHelper = testOutputHelper; - } - - private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(90); + var model = fixture.App.Services.GetRequiredService(); + var script1 = model.Resources + .OfType() + .Single(r => r.Name == "script1"); - //[Fact] - //public async Task EnsureScriptExecutes() - //{ - // var cancellationToken = new CancellationTokenSource(DefaultTimeout).Token; - // var appHost = await DistributedApplicationTestingBuilder.CreateAsync(cancellationToken); + var ready1 = fixture.ResourceNotificationService + .WaitForResourceAsync(script1.Name, KnownResourceStates.Finished) + .WaitAsync(TimeSpan.FromSeconds(90)); - // appHost.Services.AddLogging(logging => - // { - // logging.SetMinimumLevel(LogLevel.Debug); - - // // Override the logging filters from the app's configuration - // logging.AddFilter(appHost.Environment.ApplicationName, LogLevel.Debug); - // logging.AddFilter("Aspire.", LogLevel.Debug); - - // logging.AddXUnit(_testOutputHelper); - // }); + var script2 = model.Resources + .OfType() + .Single(r => r.Name == "script2"); - // await using var app = await appHost.BuildAsync(cancellationToken).WaitAsync(DefaultTimeout, cancellationToken); + var ready2 = fixture.ResourceNotificationService + .WaitForResourceAsync(script2.Name, KnownResourceStates.Finished) + .WaitAsync(TimeSpan.FromSeconds(90)); - // await app.StartAsync(cancellationToken).WaitAsync(DefaultTimeout, cancellationToken); - - // await foreach (var notification in app.ResourceNotifications.WatchAsync(cancellationToken)) - // { - // _testOutputHelper.WriteLine($"Notification: {notification.Resource.Name} - {notification.Snapshot.State} - {notification.Snapshot.HealthStatus}"); - // } - - // Assert.True(true); - //} + await Task.WhenAll([ready1, ready2]); + } } + From 57830591727ab7d95db9ebe2db72243f88917128 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Fri, 30 May 2025 20:36:49 -0400 Subject: [PATCH 03/24] fix up directory.packages.props, oops --- Directory.Packages.props | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index aa9a6fb8e..adce744aa 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -6,7 +6,7 @@ - + @@ -17,8 +17,7 @@ - - + @@ -82,6 +81,7 @@ + From 3a4fca9dc9215fc68d14396610cda024904cebb3 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Tue, 3 Jun 2025 09:48:49 -0400 Subject: [PATCH 04/24] Update src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs Co-authored-by: Aaron Powell --- .../DistributedApplicationBuilderExtensions.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs index 953ddde90..e67eabaa1 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs @@ -31,8 +31,7 @@ public static IResourceBuilder AddPowerShell( int minRunspaces = 1, int maxRunspaces = 5) { - if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Value cannot be null or whitespace.", nameof(name)); + ArgumentNullException.ThrowIfNullOrEmpty(name); if (builder.Resources.OfType().Any( rsp => rsp.Name == name)) From a71bec5e7a7f0c4da61511eccadfbc7f52687ca9 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Tue, 3 Jun 2025 09:50:04 -0400 Subject: [PATCH 05/24] Update src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs Co-authored-by: Aaron Powell --- .../PowerShellRunspacePoolResourceBuilderExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs index bf0fdc4dd..b4bea5163 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs @@ -47,7 +47,7 @@ public static IResourceBuilder AddScript( _ = notificationService .WaitForDependenciesAsync(scriptResource, ct) .ContinueWith( - async (_) => await scriptResource.StartAsync(scriptLogger, notificationService, ct), + _ => scriptResource.StartAsync(scriptLogger, notificationService, ct), ct); } catch (Exception ex) From a0ffe832456b9a5326eab6552f3f92afe4bb7db8 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Tue, 3 Jun 2025 09:59:40 -0400 Subject: [PATCH 06/24] Update src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs Co-authored-by: Aaron Powell --- .../DistributedApplicationBuilderExtensions.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs index e67eabaa1..09393830c 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs @@ -74,9 +74,7 @@ public static IResourceBuilder AddPowerShell( var poolLogger = loggerService.GetLogger(poolName); _ = notificationService.WaitForDependenciesAsync(poolResource, ct) - .ContinueWith( - async _ => - await poolResource.StartAsync(sessionState, notificationService, poolLogger, ct), + .ContinueWith(_ => poolResource.StartAsync(sessionState, notificationService, poolLogger, ct), ct); } }); From 8c18cde711e937161cc9e99111fe8ca8e9079337 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Tue, 10 Jun 2025 17:26:12 -0400 Subject: [PATCH 07/24] address nits and completely restructure lifecycle management --- CommunityToolkit.Aspire.slnx | 474 +++++++++--------- ...DistributedApplicationBuilderExtensions.cs | 44 +- .../PowerShellRunspacePoolResource.cs | 42 +- ...llRunspacePoolResourceBuilderExtensions.cs | 20 +- .../PowerShellScriptResource.cs | 51 +- 5 files changed, 304 insertions(+), 327 deletions(-) diff --git a/CommunityToolkit.Aspire.slnx b/CommunityToolkit.Aspire.slnx index 0c14a6f9a..fdffae1d3 100644 --- a/CommunityToolkit.Aspire.slnx +++ b/CommunityToolkit.Aspire.slnx @@ -1,240 +1,236 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs index 09393830c..b7b9d79c8 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs @@ -2,7 +2,6 @@ using Aspire.Hosting.ApplicationModel; using Microsoft.Extensions.DependencyInjection; using System.Diagnostics; -using System.Globalization; using System.Management.Automation; using System.Management.Automation.Runspaces; @@ -13,6 +12,8 @@ namespace CommunityToolkit.Aspire.Hosting.PowerShell; /// public static class DistributedApplicationBuilderExtensions { + private static bool _eventingSubscribed = false; + /// /// Adds a PowerShell runspace pool resource to the distributed application. /// @@ -31,26 +32,22 @@ public static IResourceBuilder AddPowerShell( int minRunspaces = 1, int maxRunspaces = 5) { - ArgumentNullException.ThrowIfNullOrEmpty(name); - - if (builder.Resources.OfType().Any( - rsp => rsp.Name == name)) - { - throw new DistributedApplicationException("AddPowerShell failed", - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "A PowerShell resource with the name '{0}' already exists.", name))); - } + ArgumentException.ThrowIfNullOrWhiteSpace(name); var pool = new PowerShellRunspacePoolResource(name, languageMode, minRunspaces, maxRunspaces); - builder.Eventing.Subscribe(async (e, ct) => + if (!_eventingSubscribed) { - var pools = e.Model.Resources.OfType().ToList(); + _eventingSubscribed = true; - foreach (var poolResource in pools) + builder.Eventing.Subscribe(pool, async (e, ct) => { + //var pools = e..Resources.OfType().ToList(); + + //foreach (var poolResource in pools) + //{ + var poolResource = e.Resource as PowerShellRunspacePoolResource; + Debug.Assert(poolResource is not null); var loggerService = e.Services.GetRequiredService(); @@ -58,6 +55,10 @@ public static IResourceBuilder AddPowerShell( var sessionState = InitialSessionState.CreateDefault(); + // publish the BeforeResourceStartedEvent to allow other resources to prepare + await builder.Eventing.PublishAsync( + new BeforeResourceStartedEvent(poolResource, e.Services), ct); + foreach (var annotation in poolResource.Annotations) { if (annotation is PowerShellVariableReferenceAnnotation reference) @@ -73,11 +74,14 @@ public static IResourceBuilder AddPowerShell( var poolName = poolResource.Name; var poolLogger = loggerService.GetLogger(poolName); - _ = notificationService.WaitForDependenciesAsync(poolResource, ct) - .ContinueWith(_ => poolResource.StartAsync(sessionState, notificationService, poolLogger, ct), - ct); - } - }); + //_ = notificationService.WaitForDependenciesAsync(poolResource, ct) + // .ContinueWith(_ => poolResource.StartAsync(sessionState, notificationService, poolLogger, ct), + // ct); + + _ = poolResource.StartAsync(sessionState, notificationService, poolLogger, ct); + //} + }); + } return builder.AddResource(pool) .WithInitialState(new() diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs index 605e0409c..7ee418424 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs @@ -39,6 +39,10 @@ public class PowerShellRunspacePoolResource( internal Task StartAsync(InitialSessionState sessionState, ResourceNotificationService notificationService, ILogger logger, CancellationToken token = default) { + logger.LogInformation( + "Starting PowerShell runspace pool '{PoolName}' with {MinRunspaces} to {MaxRunspaces} runspaces", + Name, MinRunspaces, MaxRunspaces); + sessionState.LanguageMode = this.LanguageMode; sessionState.AuthorizationManager = new AuthorizationManager("Aspire"); Pool = RunspaceFactory.CreateRunspacePool(MinRunspaces, MaxRunspaces, sessionState, new AspirePSHost(logger)); @@ -73,39 +77,25 @@ private void ConfigureStateChangeNotifications(ResourceNotificationService notif nameof(poolState), poolState, $"Unexpected runspace pool state {poolState}") }; + logger.LogInformation( + "Runspace pool '{PoolName}' state mapped to known state '{KnownState}'", Name, knownState); + await notificationService.PublishUpdateAsync(this, - state => { - state = state with - { - State = knownState, - Properties = [.. state.Properties, + state => state with + { + State = knownState, + Properties = [ + .. state.Properties, new("RunspacePoolState", poolState.ToString()), new("Reason", reason?.ToString() ?? string.Empty) - ] - }; - - if (knownState == KnownResourceStates.Running) - { - state = state with - { - StartTimeStamp = DateTime.Now, - }; - } - - if (KnownResourceStates.TerminalStates.Contains(knownState)) - { - state = state with - { - StopTimeStamp = DateTime.Now, - }; - } - - return state; + ], + StartTimeStamp = knownState == KnownResourceStates.Running ? DateTime.Now : state.StartTimeStamp, + StopTimeStamp = KnownResourceStates.TerminalStates.Contains(knownState) ? DateTime.Now : state.StopTimeStamp, }); }; } - // absolutely brain dead and deficient (minimal) PSHost implementation + // minimal PSHost implementation (aspire does not support interaction with the host, yet) private class AspirePSHost(ILogger logger) : PSHost { public override void SetShouldExit(int exitCode) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs index b4bea5163..5ab6437b6 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs @@ -32,36 +32,34 @@ public static IResourceBuilder AddScript( var scriptResource = new PowerShellScriptResource(name, scriptBlock, builder.Resource); - builder.ApplicationBuilder.Eventing.Subscribe(scriptResource, (e, ct) => + builder.ApplicationBuilder.Eventing.Subscribe(scriptResource, async (e, ct) => { var loggerService = e.Services.GetRequiredService(); var notificationService = e.Services.GetRequiredService(); var scriptName = scriptResource.Name; var scriptLogger = loggerService.GetLogger(scriptName); + try { - // TODO: capture script streams and log them + // this will block until the runspace pool is started, which is implied by the WaitFor call + await builder.ApplicationBuilder.Eventing.PublishAsync( + new BeforeResourceStartedEvent(scriptResource, e.Services), ct); + scriptLogger.LogInformation("Starting script '{ScriptName}'", scriptName); - _ = notificationService - .WaitForDependenciesAsync(scriptResource, ct) - .ContinueWith( - _ => scriptResource.StartAsync(scriptLogger, notificationService, ct), - ct); + _ = scriptResource.StartAsync(scriptLogger, notificationService, ct); } catch (Exception ex) { scriptLogger.LogError(ex, "Failed to start script '{ScriptName}'", scriptName); } - - return Task.CompletedTask; }); return builder.ApplicationBuilder .AddResource(scriptResource) - .WaitFor(builder) // wait for pool resource - .WithParentRelationship(builder.Resource) // owned by pool + .WithParentRelationship(builder.Resource) + .WaitFor(builder) .WithInitialState(new() { ResourceType = "PowerShellScript", diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs index 1d13b028e..d7988e5db 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs @@ -15,7 +15,6 @@ public class PowerShellScriptResource : Resource, IDisposable, { private readonly System.Management.Automation.PowerShell _ps; private readonly CancellationTokenSource _cts; - private readonly PowerShellRunspacePoolResource _parent; private readonly PSDataCollection _output; private readonly PSDataCollection _emptyInput; private ILogger? _scriptLogger; @@ -31,12 +30,12 @@ public class PowerShellScriptResource : Resource, IDisposable, /// The name of the resource. This must be a valid resource name. /// The ScriptBlock to be executed. /// The parent that provides the runspace pool for script - /// execution. Cannot be null. + /// execution. Cannot be null. public PowerShellScriptResource([ResourceName] string name, ScriptBlock script, PowerShellRunspacePoolResource parent) : base(name) { - _parent = parent; + Parent = parent; _cts = new CancellationTokenSource(); _ps = System.Management.Automation.PowerShell.Create(); @@ -69,7 +68,7 @@ public PowerShellScriptResource([ResourceName] string name, FileInfo scriptFile, PowerShellRunspacePoolResource parent) : base(name) { - _parent = parent; + Parent = parent; _cts = new CancellationTokenSource(); _ps = System.Management.Automation.PowerShell.Create(); @@ -88,6 +87,11 @@ public PowerShellScriptResource([ResourceName] string name, _ps.AddCommand(scriptFile.FullName); } + /// + /// Parent PowerShell runspace pool resource that provides the runspace pool for script execution. + /// + public PowerShellRunspacePoolResource Parent { get; } + /// /// Breaks the PowerShell script execution. /// @@ -121,11 +125,13 @@ public async Task StartAsync(ILogger scriptLogger, ResourceNotificationService notificationService, CancellationToken cancellationToken = default) { + scriptLogger.LogInformation("Starting PowerShell script '{ScriptName}'", Name); + Debug.Assert(scriptLogger != null); _scriptLogger = scriptLogger; - Debug.Assert(_parent.Pool != null); - _ps.RunspacePool = _parent.Pool; + Debug.Assert(Parent.Pool != null); + _ps.RunspacePool = Parent.Pool; ConfigurePSDataStreams(scriptLogger, notificationService); @@ -145,36 +151,19 @@ public async Task StartAsync(ILogger scriptLogger, "Unknown PowerShell invocation state") }; + scriptLogger.LogInformation("Publishing script {ScriptName} state as known state: {ScriptState}", Name, knownState); + await notificationService.PublishUpdateAsync(this, - state => + state => state with { - state = state with - { - State = knownState, - Properties = [ + State = knownState, + Properties = [ .. state.Properties, new( "PSInvocationState", args.InvocationStateInfo.State.ToString() ), new( "Reason", args.InvocationStateInfo.Reason?.Message ?? string.Empty ), - ] - }; - - if (knownState == KnownResourceStates.Running) - { - state = state with - { - StartTimeStamp = DateTime.Now, - }; - } - - if (KnownResourceStates.TerminalStates.Contains(knownState)) - { - state = state with - { - StopTimeStamp = DateTime.Now, - }; - } - - return state; + ], + StartTimeStamp = knownState == KnownResourceStates.Running ? DateTime.Now : state.StartTimeStamp, + StopTimeStamp = KnownResourceStates.TerminalStates.Contains(knownState) ? DateTime.Now : state.StopTimeStamp, }); }; From 194165baf127b8ecc4f70c7b660d00bbcb5cdb40 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Tue, 10 Jun 2025 17:35:32 -0400 Subject: [PATCH 08/24] conditionally use az cli in apphost sample; remove dead code --- .../Program.cs | 17 +++++++++++++---- .../DistributedApplicationBuilderExtensions.cs | 12 ++---------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs index b335604d6..57f4bb348 100644 --- a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs +++ b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs @@ -20,12 +20,21 @@ write-information "`$myblob is $myblob" - az storage container create --connection-string $myblob -n demo - az storage blob upload --connection-string $myblob -c demo --file ./scripts/script.ps1 - + # only run this if Azure CLI is installed + if ((gcm az -ErrorAction SilentlyContinue) -ne $null) { + + az storage container create --connection-string $myblob -n demo + az storage blob upload --connection-string $myblob -c demo --file ./scripts/script.ps1 + write-information "Blob uploaded" + + } else { + + write-warning "Azure CLI not found, skipping blob upload" + + } write-information $pwd - write-information "Blob uploaded" + """).WithArgs("world"); // outputs "the sum of 2 and 3 is 5" diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs index b7b9d79c8..99e24b0db 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs @@ -42,10 +42,6 @@ public static IResourceBuilder AddPowerShell( builder.Eventing.Subscribe(pool, async (e, ct) => { - //var pools = e..Resources.OfType().ToList(); - - //foreach (var poolResource in pools) - //{ var poolResource = e.Resource as PowerShellRunspacePoolResource; Debug.Assert(poolResource is not null); @@ -55,7 +51,7 @@ public static IResourceBuilder AddPowerShell( var sessionState = InitialSessionState.CreateDefault(); - // publish the BeforeResourceStartedEvent to allow other resources to prepare + // This will block until explicit and implied WaitFor calls are completed await builder.Eventing.PublishAsync( new BeforeResourceStartedEvent(poolResource, e.Services), ct); @@ -74,12 +70,8 @@ await builder.Eventing.PublishAsync( var poolName = poolResource.Name; var poolLogger = loggerService.GetLogger(poolName); - //_ = notificationService.WaitForDependenciesAsync(poolResource, ct) - // .ContinueWith(_ => poolResource.StartAsync(sessionState, notificationService, poolLogger, ct), - // ct); - _ = poolResource.StartAsync(sessionState, notificationService, poolLogger, ct); - //} + }); } From 32ec6dc85882ea7e16b1aeb4e03172adef9cd67d Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Tue, 10 Jun 2025 17:37:10 -0400 Subject: [PATCH 09/24] Update src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../PowerShellScriptResource.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs index d7988e5db..91c83343d 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs @@ -253,6 +253,7 @@ void IDisposable.Dispose() _isDisposed = true; _ps.Stop(); _ps.Dispose(); + _cts?.Dispose(); } } } From 0947edf2ed6d0c5df30ca37bb02f72fd7173bcf5 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Mon, 2 Jun 2025 10:57:12 -0400 Subject: [PATCH 10/24] rebase main --- Directory.Packages.props | 10 +- ...tyToolkit.Aspire.PowerShell.AppHost.csproj | 24 ++ .../Program.cs | 39 +++ .../Properties/launchSettings.json | 29 ++ .../Scripts/script.ps1 | 3 + .../appsettings.json | 9 + ...tyToolkit.Aspire.Hosting.PowerShell.csproj | 19 ++ ...DistributedApplicationBuilderExtensions.cs | 99 +++++++ .../PowerShellRunspacePoolResource.cs | 149 ++++++++++ ...llRunspacePoolResourceBuilderExtensions.cs | 124 ++++++++ .../PowerShellScriptResource.cs | 269 ++++++++++++++++++ ...werShellScriptResourceBuilderExtensions.cs | 29 ++ .../README.md | 54 ++++ .../AppHostTests.cs | 84 ++++++ ...kit.Aspire.Hosting.PowerShell.Tests.csproj | 9 + 15 files changed, 944 insertions(+), 6 deletions(-) create mode 100644 examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/CommunityToolkit.Aspire.PowerShell.AppHost.csproj create mode 100644 examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs create mode 100644 examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Properties/launchSettings.json create mode 100644 examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Scripts/script.ps1 create mode 100644 examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/appsettings.json create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResourceBuilderExtensions.cs create mode 100644 src/CommunityToolkit.Aspire.Hosting.PowerShell/README.md create mode 100644 tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs create mode 100644 tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests.csproj diff --git a/Directory.Packages.props b/Directory.Packages.props index 014416418..b77d5f51e 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -6,8 +6,9 @@ + - + @@ -17,6 +18,7 @@ + @@ -54,11 +56,9 @@ - - @@ -84,7 +84,6 @@ - @@ -100,9 +99,8 @@ - - + \ No newline at end of file diff --git a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/CommunityToolkit.Aspire.PowerShell.AppHost.csproj b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/CommunityToolkit.Aspire.PowerShell.AppHost.csproj new file mode 100644 index 000000000..63aed919d --- /dev/null +++ b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/CommunityToolkit.Aspire.PowerShell.AppHost.csproj @@ -0,0 +1,24 @@ + + + + + + Exe + net8.0 + enable + enable + true + bc193f31-c9f7-4e3d-b70a-0dc39ec3047f + + + + + + + + + + + + + diff --git a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs new file mode 100644 index 000000000..b335604d6 --- /dev/null +++ b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs @@ -0,0 +1,39 @@ +using CommunityToolkit.Aspire.Hosting.PowerShell; + +var builder = DistributedApplication.CreateBuilder(args); + +var storage = builder.AddAzureStorage("storage").RunAsEmulator(); +var blob = storage.AddBlobs("myblob"); + +var ps = builder.AddPowerShell("ps") + .WithReference(blob) + .WaitFor(storage); + +// uploads the script in scripts/ +var script1 = ps.AddScript("script1", """ + param($name) + + write-information "Hello, $name" + + # uncommenting this will hang the script if you don't attach the pwsh debugger + # wait-debugger + + write-information "`$myblob is $myblob" + + az storage container create --connection-string $myblob -n demo + az storage blob upload --connection-string $myblob -c demo --file ./scripts/script.ps1 + + write-information $pwd + + write-information "Blob uploaded" +""").WithArgs("world"); + +// outputs "the sum of 2 and 3 is 5" +var script2 = ps.AddScript("script2", """ + & ./scripts/script.ps1 @args + """) + .WithArgs(2, 3) + .WaitForCompletion(script1); + +builder.Build().Run(); + diff --git a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Properties/launchSettings.json b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Properties/launchSettings.json new file mode 100644 index 000000000..80e6457ea --- /dev/null +++ b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17118;http://localhost:15215", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21165", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22038" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15215", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19175", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20201" + } + } + } +} diff --git a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Scripts/script.ps1 b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Scripts/script.ps1 new file mode 100644 index 000000000..4749399b3 --- /dev/null +++ b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Scripts/script.ps1 @@ -0,0 +1,3 @@ +param($a, $b) + +Write-Information "The sum of $a and $b is: $($a + $b)" \ No newline at end of file diff --git a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/appsettings.json b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/appsettings.json new file mode 100644 index 000000000..31c092aa4 --- /dev/null +++ b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj b/src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj new file mode 100644 index 000000000..045a19c73 --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + powershell; pwsh; scripting; script; hosting + Run powershell scripts in-process with your Aspire AppHost, injecting aspire resources and/or object instances as variables, using the command lines tools of your choice like azure cli, azd, or any other terminal tools. + + + + + + + + + + + diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs new file mode 100644 index 000000000..953ddde90 --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs @@ -0,0 +1,99 @@ +using Aspire.Hosting; +using Aspire.Hosting.ApplicationModel; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Runspaces; + +namespace CommunityToolkit.Aspire.Hosting.PowerShell; + +/// +/// Extensions for the to add PowerShell runspace pool resources. +/// +public static class DistributedApplicationBuilderExtensions +{ + /// + /// Adds a PowerShell runspace pool resource to the distributed application. + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static IResourceBuilder AddPowerShell( + this IDistributedApplicationBuilder builder, + [ResourceName] string name, + PSLanguageMode languageMode = PSLanguageMode.ConstrainedLanguage, + int minRunspaces = 1, + int maxRunspaces = 5) + { + if (string.IsNullOrWhiteSpace(name)) + throw new ArgumentException("Value cannot be null or whitespace.", nameof(name)); + + if (builder.Resources.OfType().Any( + rsp => rsp.Name == name)) + { + throw new DistributedApplicationException("AddPowerShell failed", + new InvalidOperationException( + string.Format( + CultureInfo.InvariantCulture, + "A PowerShell resource with the name '{0}' already exists.", name))); + } + + var pool = new PowerShellRunspacePoolResource(name, languageMode, minRunspaces, maxRunspaces); + + builder.Eventing.Subscribe(async (e, ct) => + { + var pools = e.Model.Resources.OfType().ToList(); + + foreach (var poolResource in pools) + { + Debug.Assert(poolResource is not null); + + var loggerService = e.Services.GetRequiredService(); + var notificationService = e.Services.GetRequiredService(); + + var sessionState = InitialSessionState.CreateDefault(); + + foreach (var annotation in poolResource.Annotations) + { + if (annotation is PowerShellVariableReferenceAnnotation reference) + { + var connectionString = await reference.Value.Resource.GetConnectionStringAsync(ct); + sessionState.Variables.Add( + new SessionStateVariableEntry(reference.Name, connectionString, + $"ConnectionString for {reference.Value.Resource.GetType().Name} '{reference.Name}'", + ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope)); + } + } + + var poolName = poolResource.Name; + var poolLogger = loggerService.GetLogger(poolName); + + _ = notificationService.WaitForDependenciesAsync(poolResource, ct) + .ContinueWith( + async _ => + await poolResource.StartAsync(sessionState, notificationService, poolLogger, ct), + ct); + } + }); + + return builder.AddResource(pool) + .WithInitialState(new() + { + ResourceType = "PowerShellRunspacePool", + State = KnownResourceStates.NotStarted, + Properties = [ + + new ("LanguageMode", pool.LanguageMode.ToString()), + new ("MinRunspaces", pool.MinRunspaces.ToString()), + new ("MaxRunspaces", pool.MaxRunspaces.ToString()) + ] + }) + .ExcludeFromManifest(); + } +} \ No newline at end of file diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs new file mode 100644 index 000000000..605e0409c --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs @@ -0,0 +1,149 @@ +using Aspire.Hosting.ApplicationModel; +using Microsoft.Extensions.Logging; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Runspaces; + +namespace CommunityToolkit.Aspire.Hosting.PowerShell; + +/// +/// Represents a PowerShell runspace pool resource. +/// +public class PowerShellRunspacePoolResource( + [ResourceName] string name, + PSLanguageMode languageMode = PSLanguageMode.ConstrainedLanguage, + int minRunspaces = 1, + int maxRunspaces = 5) + : Resource(name), IDisposable, IResourceWithWaitSupport +{ + /// + /// Specifies the language mode for the PowerShell runspace pool. + /// + public PSLanguageMode LanguageMode { get; } = languageMode; + + /// + /// Specifies the minimum number of runspaces in the pool. + /// + public int MinRunspaces { get; } = minRunspaces; + + /// + /// Specifies the maximum number of runspaces in the pool. + /// + public int MaxRunspaces { get; } = maxRunspaces; + + /// + /// A reference to the runspace pool created by this resource. + /// + public RunspacePool? Pool { get; private set; } + + internal Task StartAsync(InitialSessionState sessionState, ResourceNotificationService notificationService, ILogger logger, CancellationToken token = default) + { + sessionState.LanguageMode = this.LanguageMode; + sessionState.AuthorizationManager = new AuthorizationManager("Aspire"); + Pool = RunspaceFactory.CreateRunspacePool(MinRunspaces, MaxRunspaces, sessionState, new AspirePSHost(logger)); + + ConfigureStateChangeNotifications(notificationService, logger); + + return Task.Factory.FromAsync(Pool.BeginOpen, Pool.EndOpen, null); + } + + private void ConfigureStateChangeNotifications(ResourceNotificationService notificationService, ILogger logger) + { + Pool!.StateChanged += async (_, args) => + { + var poolState = args.RunspacePoolStateInfo.State; + var reason = args.RunspacePoolStateInfo.Reason; + + logger.LogInformation( + "Runspace pool '{PoolName}' state changed to '{RunspacePoolState}'", Name, poolState); + + // map args.RunspacePoolStateInfo.State to a KnownResourceState + // and publish the update + + var knownState = poolState switch + { + RunspacePoolState.BeforeOpen => KnownResourceStates.NotStarted, + RunspacePoolState.Opening => KnownResourceStates.Starting, + RunspacePoolState.Opened => KnownResourceStates.Running, + RunspacePoolState.Closing => KnownResourceStates.Stopping, + RunspacePoolState.Closed => KnownResourceStates.Exited, + RunspacePoolState.Broken => KnownResourceStates.FailedToStart, + _ => throw new ArgumentOutOfRangeException( + nameof(poolState), poolState, $"Unexpected runspace pool state {poolState}") + }; + + await notificationService.PublishUpdateAsync(this, + state => { + state = state with + { + State = knownState, + Properties = [.. state.Properties, + new("RunspacePoolState", poolState.ToString()), + new("Reason", reason?.ToString() ?? string.Empty) + ] + }; + + if (knownState == KnownResourceStates.Running) + { + state = state with + { + StartTimeStamp = DateTime.Now, + }; + } + + if (KnownResourceStates.TerminalStates.Contains(knownState)) + { + state = state with + { + StopTimeStamp = DateTime.Now, + }; + } + + return state; + }); + }; + } + + // absolutely brain dead and deficient (minimal) PSHost implementation + private class AspirePSHost(ILogger logger) : PSHost + { + public override void SetShouldExit(int exitCode) + { + logger.LogInformation("AspirePSHost: SetShouldExit({ExitCode})", exitCode); + } + + public override void EnterNestedPrompt() + { + throw new NotSupportedException(); + } + + public override void ExitNestedPrompt() + { + throw new NotSupportedException(); + } + + public override void NotifyBeginApplication() + { + logger.LogInformation("AspirePSHost: NotifyBeginApplication"); + } + + public override void NotifyEndApplication() + { + logger.LogInformation("AspirePSHost: NotifyEndApplication"); + } + + public override string Name { get; } = "AspirePSHost"; + public override Version Version { get; } = new (0, 1); + public override Guid InstanceId { get; } = Guid.NewGuid(); + public override PSHostUserInterface UI => null!; // interaction not supported + public override CultureInfo CurrentCulture { get; } = CultureInfo.CurrentCulture; + public override CultureInfo CurrentUICulture { get; } = CultureInfo.CurrentUICulture; + } + + void IDisposable.Dispose() + { + Pool?.Close(); + Pool?.Dispose(); + } +} \ No newline at end of file diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs new file mode 100644 index 000000000..bf0fdc4dd --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs @@ -0,0 +1,124 @@ +using Aspire.Hosting; +using Aspire.Hosting.ApplicationModel; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation; + +namespace CommunityToolkit.Aspire.Hosting.PowerShell; + +/// +/// Extensions for the PowerShellRunspacePoolResourceBuilder. +/// +public static class PowerShellRunspacePoolResourceBuilderExtensions +{ + /// + /// Adds a PowerShell script resource to the distributed application. + /// + /// + /// + /// + /// + public static IResourceBuilder AddScript( + this IResourceBuilder builder, + [ResourceName] string name, + [StringSyntax("PowerShell")] string script) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentException.ThrowIfNullOrWhiteSpace(script); + + // parse to force an early exception if the script is invalid + var scriptBlock = ScriptBlock.Create(script); + + var scriptResource = new PowerShellScriptResource(name, scriptBlock, builder.Resource); + + builder.ApplicationBuilder.Eventing.Subscribe(scriptResource, (e, ct) => + { + var loggerService = e.Services.GetRequiredService(); + var notificationService = e.Services.GetRequiredService(); + + var scriptName = scriptResource.Name; + var scriptLogger = loggerService.GetLogger(scriptName); + try + { + // TODO: capture script streams and log them + scriptLogger.LogInformation("Starting script '{ScriptName}'", scriptName); + + _ = notificationService + .WaitForDependenciesAsync(scriptResource, ct) + .ContinueWith( + async (_) => await scriptResource.StartAsync(scriptLogger, notificationService, ct), + ct); + } + catch (Exception ex) + { + scriptLogger.LogError(ex, "Failed to start script '{ScriptName}'", scriptName); + } + + return Task.CompletedTask; + }); + + return builder.ApplicationBuilder + .AddResource(scriptResource) + .WaitFor(builder) // wait for pool resource + .WithParentRelationship(builder.Resource) // owned by pool + .WithInitialState(new() + { + ResourceType = "PowerShellScript", + State = KnownResourceStates.NotStarted, + Properties = [ + new ("Script", script), + new("RunspacePool", builder.Resource.Name) + ] + }) + .ExcludeFromManifest() + .WithCommand("break", "Stop script execution", + async _ => + { + await scriptResource.BreakAsync(); + return CommandResults.Success(); + }, + new CommandOptions + { + ConfirmationMessage = "Are you sure you want to stop the script?", + Description = "Stop script execution", + IconName = "Stop", + IsHighlighted = true, + IconVariant = IconVariant.Filled, + UpdateState = updateContext => + updateContext.ResourceSnapshot.State?.Text != KnownResourceStates.Running ? + ResourceCommandState.Disabled : + ResourceCommandState.Enabled + }); + } + + /// + /// Adds a reference to an Aspire resource that implements IResourceWithConnectionString. + /// The resource will be exposed as a PowerShell variable in the runspace that is named after the resource name. + /// + /// + /// + /// + /// + /// + public static IResourceBuilder WithReference(this IResourceBuilder builder, IResourceBuilder source, string? connectionName = null, bool optional = false) + { + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(source); + + var resource = source.Resource; + + builder.WithReferenceRelationship(resource); + + return builder.WithAnnotation(new PowerShellVariableReferenceAnnotation( + resource.Name, new ConnectionStringReference(resource, optional))); + } +} + +/// +/// Represents a PowerShell variable reference annotation. +/// +/// +/// +/// +public record PowerShellVariableReferenceAnnotation(string Name, T Value) : IResourceAnnotation; \ No newline at end of file diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs new file mode 100644 index 000000000..1d13b028e --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs @@ -0,0 +1,269 @@ +using Aspire.Hosting.ApplicationModel; +using Microsoft.Extensions.Logging; +using System.Diagnostics; +using System.Management.Automation; + +namespace CommunityToolkit.Aspire.Hosting.PowerShell +{ + /// + /// Represents a PowerShell script resource. + /// + public class PowerShellScriptResource : Resource, IDisposable, + IResourceWithEnvironment, + IResourceWithWaitSupport, + IResourceWithArgs + { + private readonly System.Management.Automation.PowerShell _ps; + private readonly CancellationTokenSource _cts; + private readonly PowerShellRunspacePoolResource _parent; + private readonly PSDataCollection _output; + private readonly PSDataCollection _emptyInput; + private ILogger? _scriptLogger; + private bool _isDisposed; + + /// + /// Initializes a new instance of the class, representing a resource for + /// executing PowerShell scripts. + /// + /// This class is designed to manage the execution of PowerShell scripts within a + /// specified runspace pool. The script execution is tied to a cancellation token, allowing the script to be + /// stopped when requested. + /// The name of the resource. This must be a valid resource name. + /// The ScriptBlock to be executed. + /// The parent that provides the runspace pool for script + /// execution. Cannot be null. + public PowerShellScriptResource([ResourceName] string name, + ScriptBlock script, + PowerShellRunspacePoolResource parent) : base(name) + { + _parent = parent; + _cts = new CancellationTokenSource(); + _ps = System.Management.Automation.PowerShell.Create(); + + // stop the powershell instance when _cts is cancelled + _cts.Token.Register(() => + { + _scriptLogger?.LogInformation("Stopping PowerShell script execution"); + _ps.Stop(); + }); + + _output = new PSDataCollection(); + _emptyInput = new PSDataCollection(); + _emptyInput.Complete(); + + _ps.AddScript(script.ToString()); + } + + /// + /// Initializes a new instance of the class, representing a resource for + /// executing PowerShell scripts. + /// + /// This class is designed to manage the execution of PowerShell scripts within a + /// specified runspace pool. The script execution is tied to a cancellation token, allowing the script to be + /// stopped when requested. + /// The name of the resource. This must be a valid resource name. + /// The file containing the PowerShell script to be executed. Must be a valid file path and not null. + /// The parent that provides the runspace pool for script + /// execution. Cannot be null. + public PowerShellScriptResource([ResourceName] string name, + FileInfo scriptFile, + PowerShellRunspacePoolResource parent) : base(name) + { + _parent = parent; + _cts = new CancellationTokenSource(); + _ps = System.Management.Automation.PowerShell.Create(); + + // stop the powershell instance when _cts is cancelled + _cts.Token.Register(() => + { + _scriptLogger?.LogInformation("Stopping PowerShell script execution"); + _ps.Stop(); + }); + + _output = new PSDataCollection(); + _emptyInput = new PSDataCollection(); + _emptyInput.Complete(); + + // add scriptFile to the PowerShell instance to be executed + _ps.AddCommand(scriptFile.FullName); + } + + /// + /// Breaks the PowerShell script execution. + /// + /// + public async Task BreakAsync() + { + if (_isDisposed) + { + throw new ObjectDisposedException(nameof(PowerShellScriptResource)); + } + + if (_ps.InvocationStateInfo.State != PSInvocationState.Running) + { + return false; + } + + await _cts.CancelAsync(); + + return true; + } + + /// + /// Starts the PowerShell script execution. + /// + /// + /// + /// + /// + /// + public async Task StartAsync(ILogger scriptLogger, + ResourceNotificationService notificationService, + CancellationToken cancellationToken = default) + { + Debug.Assert(scriptLogger != null); + _scriptLogger = scriptLogger; + + Debug.Assert(_parent.Pool != null); + _ps.RunspacePool = _parent.Pool; + + ConfigurePSDataStreams(scriptLogger, notificationService); + + _ps.InvocationStateChanged += async (_, args) => + { + var knownState = args.InvocationStateInfo.State switch + { + PSInvocationState.NotStarted => KnownResourceStates.NotStarted, + PSInvocationState.Running => KnownResourceStates.Running, + PSInvocationState.Completed => KnownResourceStates.Finished, + PSInvocationState.Stopped => KnownResourceStates.Exited, + PSInvocationState.Failed => KnownResourceStates.FailedToStart, + PSInvocationState.Stopping => KnownResourceStates.Stopping, + _ => throw new ArgumentOutOfRangeException( // probably should be assertion + nameof(args.InvocationStateInfo.State), + args.InvocationStateInfo.State, + "Unknown PowerShell invocation state") + }; + + await notificationService.PublishUpdateAsync(this, + state => + { + state = state with + { + State = knownState, + Properties = [ + .. state.Properties, + new( "PSInvocationState", args.InvocationStateInfo.State.ToString() ), + new( "Reason", args.InvocationStateInfo.Reason?.Message ?? string.Empty ), + ] + }; + + if (knownState == KnownResourceStates.Running) + { + state = state with + { + StartTimeStamp = DateTime.Now, + }; + } + + if (KnownResourceStates.TerminalStates.Contains(knownState)) + { + state = state with + { + StopTimeStamp = DateTime.Now, + }; + } + + return state; + }); + }; + + if (this.TryGetLastAnnotation(out var scriptArgsAnnotation)) + { + foreach (var scriptArg in scriptArgsAnnotation.Args) + { + if (scriptArg is IValueProvider valueProvider) + { + var value = await valueProvider.GetValueAsync(cancellationToken); + _ps.AddArgument(value); + } + else + { + _ps.AddArgument(scriptArg); + } + } + } + + try + { + _ = await _ps.InvokeAsync(_emptyInput, _output); + } + catch (PipelineStoppedException) + { + // This is expected when the pipeline is stopped (i.e. via BreakAsync), so we can ignore it. + // The pipeline will be stopped when the PowerShell instance is disposed. + } + catch (Exception ex) + { + scriptLogger.LogError(ex, "Error invoking PowerShell script: {Message}", ex.Message); + throw; + } + } + + private void ConfigurePSDataStreams(ILogger logger, ResourceNotificationService notifications) + { + _output.DataAdded += (_, args) => + { + var psObject = _output[args.Index]; + logger.LogInformation("Output: {Output}", psObject.ToString()); + }; + _output.Completed += async (_, _) => + { + await notifications.PublishUpdateAsync(this, state => state with + { + State = KnownResourceStates.Finished, + StopTimeStamp = DateTime.Now, + ExitCode = _ps.HadErrors ? 1 : 0, + }); + + logger.LogInformation("Output completed"); + }; + _ps.Streams.Error.DataAdded += (_, args) => + { + var error = _ps.Streams.Error[args.Index]; + logger.LogError(error.Exception, "Error: {Error}", error.ToString()); + }; + _ps.Streams.Warning.DataAdded += (_, args) => + { + var warning = _ps.Streams.Warning[args.Index]; + logger.LogWarning("Warning: {Warning}", warning); + }; + _ps.Streams.Information.DataAdded += (_, args) => + { + var info = _ps.Streams.Information[args.Index]; + logger.LogInformation("Information: {Info}", info); + }; + _ps.Streams.Verbose.DataAdded += (_, args) => + { + var verbose = _ps.Streams.Verbose[args.Index]; + logger.LogInformation("Verbose: {Verbose}", verbose); + }; + _ps.Streams.Debug.DataAdded += (_, args) => + { + var debug = _ps.Streams.Debug[args.Index]; + logger.LogInformation("Debug: {Debug}", debug); + }; + } + + void IDisposable.Dispose() + { + if (_isDisposed) + { + throw new ObjectDisposedException(nameof(PowerShellScriptResource)); + } + _isDisposed = true; + _ps.Stop(); + _ps.Dispose(); + } + } +} diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResourceBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResourceBuilderExtensions.cs new file mode 100644 index 000000000..41861d478 --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResourceBuilderExtensions.cs @@ -0,0 +1,29 @@ +using Aspire.Hosting.ApplicationModel; + +namespace CommunityToolkit.Aspire.Hosting.PowerShell; + + +/// +/// PowerShell script resource builder extensions. +/// +public static class PowerShellScriptResourceBuilderExtensions +{ + /// + /// Provide arguments to the PowerShell script. + /// + /// + /// + /// + public static IResourceBuilder WithArgs( + this IResourceBuilder builder, params object[] args) + { + return builder.WithAnnotation(new PowerShellScriptArgsAnnotation(args)); + } +} + +/// +/// Represents the arguments for a PowerShell script resource. +/// +/// +public record PowerShellScriptArgsAnnotation(object[] Args) : IResourceAnnotation; + diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/README.md b/src/CommunityToolkit.Aspire.Hosting.PowerShell/README.md new file mode 100644 index 000000000..1d2b1aaf9 --- /dev/null +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/README.md @@ -0,0 +1,54 @@ +# CommunityToolkit Aspire PowerShell Scripting + +## About + +Script your resources, use the pwsh (powershell core) engine and reference connectionstring expressions, live resources, dotnet instances or whatever else is in scope for your AppHost. + + +```csharp +using CommunityToolkit.Aspire.Hosting.PowerShell; + +var builder = DistributedApplication.CreateBuilder(args); + +var storage = builder.AddAzureStorage("storage").RunAsEmulator(); +var blob = storage.AddBlobs("myblob"); + +var ps = builder.AddPowerShell("ps") + .WithReference(blob) + .WaitFor(storage); + +// uploads the script in scripts/ +var script1 = ps.AddScript("script1", """ + param($name) + + write-information "Hello, $name" + + # uncommenting this will hang the script if you don't attach the pwsh debugger + # wait-debugger + + write-information "`$myblob is $myblob" + + az storage container create --connection-string $myblob -n demo + az storage blob upload --connection-string $myblob -c demo --file ./scripts/script.ps1 + + write-information $pwd + + write-information "Blob uploaded" +""").WithArgs("world"); + +// outputs "the sum of 2 and 3 is 5" +var script2 = ps.AddScript("script2", """ + & ./scripts/script.ps1 @args + """) + .WithArgs(2, 3) + .WaitForCompletion(script1); + +builder.Build().Run(); + +``` + +## Debugging + +While your Apphost is running a script that is waiting via `Wait-Debugger`, open a terminal with powershell (pwsh) 7.4 or later (win, osx, linux) and use `Get-PSHostProcessInfo`, `Enter-PSHostProcess`, `Get-Runspace` and `Debug-Runspace` to connect the debugger. + +See https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/enter-pshostprocess?view=powershell-7.5 for more information. diff --git a/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs b/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs new file mode 100644 index 000000000..b651f0f80 --- /dev/null +++ b/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs @@ -0,0 +1,84 @@ +using Aspire.Components.Common.Tests; +using CommunityToolkit.Aspire.Testing; +using Microsoft.Extensions.Logging; +using Xunit.Abstractions; + +namespace CommunityToolkit.Aspire.Hosting.PowerShell.Tests; + +[RequiresDocker] +public class AppHostTests(AspireIntegrationTestFixture fixture) : + IClassFixture> +{ + [Fact] + public async Task ResourceStartsAndRespondsOk() + { + var resourceName = "ps"; + await fixture.ResourceNotificationService.WaitForResourceAsync(resourceName, KnownResourceStates.Running).WaitAsync(TimeSpan.FromMinutes(5)); + var httpClient = fixture.CreateHttpClient(resourceName); + + var response = await httpClient.GetAsync("/"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + //[Fact] + //public async Task OllamaListsAvailableModels() + //{ + // var distributedAppModel = fixture.App.Services.GetRequiredService(); + // var modelResources = distributedAppModel.Resources.OfType().ToList(); + // var rns = fixture.ResourceNotificationService; + + // await Task.WhenAll([ + // rns.WaitForResourceHealthyAsync("ollama"), + // .. modelResources.Select(m => rns.WaitForResourceHealthyAsync(m.Name)) + // ]).WaitAsync(TimeSpan.FromMinutes(10)); + // var httpClient = fixture.CreateHttpClient("ollama"); + + // var models = (await new OllamaApiClient(httpClient).ListLocalModelsAsync()).ToList(); + + // Assert.NotEmpty(models); + // Assert.Equal(modelResources.Count, models.Count); + //} +} + +public class AppHostTestsX +{ + private readonly ITestOutputHelper _testOutputHelper; + + public AppHostTestsX(ITestOutputHelper testOutputHelper) + { + _testOutputHelper = testOutputHelper; + } + + private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(90); + + + //[Fact] + //public async Task EnsureScriptExecutes() + //{ + // var cancellationToken = new CancellationTokenSource(DefaultTimeout).Token; + // var appHost = await DistributedApplicationTestingBuilder.CreateAsync(cancellationToken); + + // appHost.Services.AddLogging(logging => + // { + // logging.SetMinimumLevel(LogLevel.Debug); + + // // Override the logging filters from the app's configuration + // logging.AddFilter(appHost.Environment.ApplicationName, LogLevel.Debug); + // logging.AddFilter("Aspire.", LogLevel.Debug); + + // logging.AddXUnit(_testOutputHelper); + // }); + + // await using var app = await appHost.BuildAsync(cancellationToken).WaitAsync(DefaultTimeout, cancellationToken); + + // await app.StartAsync(cancellationToken).WaitAsync(DefaultTimeout, cancellationToken); + + // await foreach (var notification in app.ResourceNotifications.WatchAsync(cancellationToken)) + // { + // _testOutputHelper.WriteLine($"Notification: {notification.Resource.Name} - {notification.Snapshot.State} - {notification.Snapshot.HealthStatus}"); + // } + + // Assert.True(true); + //} +} diff --git a/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests.csproj b/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests.csproj new file mode 100644 index 000000000..1080a2c14 --- /dev/null +++ b/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests.csproj @@ -0,0 +1,9 @@ + + + + + + + + + From 8c039a79157d34582f0238dc591b3c4c3bc71383 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Fri, 30 May 2025 20:15:11 -0400 Subject: [PATCH 11/24] add tests --- .../AppHostTests.cs | 87 +++++-------------- 1 file changed, 24 insertions(+), 63 deletions(-) diff --git a/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs b/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs index b651f0f80..284d5c7bd 100644 --- a/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs +++ b/tests/CommunityToolkit.Aspire.Hosting.PowerShell.Tests/AppHostTests.cs @@ -1,7 +1,5 @@ using Aspire.Components.Common.Tests; using CommunityToolkit.Aspire.Testing; -using Microsoft.Extensions.Logging; -using Xunit.Abstractions; namespace CommunityToolkit.Aspire.Hosting.PowerShell.Tests; @@ -10,75 +8,38 @@ public class AppHostTests(AspireIntegrationTestFixture> { [Fact] - public async Task ResourceStartsAndRespondsOk() + public async Task PowerShellResourceStarts() { var resourceName = "ps"; - await fixture.ResourceNotificationService.WaitForResourceAsync(resourceName, KnownResourceStates.Running).WaitAsync(TimeSpan.FromMinutes(5)); - var httpClient = fixture.CreateHttpClient(resourceName); - - var response = await httpClient.GetAsync("/"); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + await fixture.ResourceNotificationService + .WaitForResourceAsync(resourceName, KnownResourceStates.Running) + .WaitAsync(TimeSpan.FromSeconds(60)); + + Assert.True(true); } - //[Fact] - //public async Task OllamaListsAvailableModels() - //{ - // var distributedAppModel = fixture.App.Services.GetRequiredService(); - // var modelResources = distributedAppModel.Resources.OfType().ToList(); - // var rns = fixture.ResourceNotificationService; - - // await Task.WhenAll([ - // rns.WaitForResourceHealthyAsync("ollama"), - // .. modelResources.Select(m => rns.WaitForResourceHealthyAsync(m.Name)) - // ]).WaitAsync(TimeSpan.FromMinutes(10)); - // var httpClient = fixture.CreateHttpClient("ollama"); - - // var models = (await new OllamaApiClient(httpClient).ListLocalModelsAsync()).ToList(); - - // Assert.NotEmpty(models); - // Assert.Equal(modelResources.Count, models.Count); - //} -} - -public class AppHostTestsX -{ - private readonly ITestOutputHelper _testOutputHelper; - - public AppHostTestsX(ITestOutputHelper testOutputHelper) + [Fact] + public async Task ScriptsExecuteSuccessfully() { - _testOutputHelper = testOutputHelper; - } - - private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(90); + var model = fixture.App.Services.GetRequiredService(); + var script1 = model.Resources + .OfType() + .Single(r => r.Name == "script1"); - //[Fact] - //public async Task EnsureScriptExecutes() - //{ - // var cancellationToken = new CancellationTokenSource(DefaultTimeout).Token; - // var appHost = await DistributedApplicationTestingBuilder.CreateAsync(cancellationToken); + var ready1 = fixture.ResourceNotificationService + .WaitForResourceAsync(script1.Name, KnownResourceStates.Finished) + .WaitAsync(TimeSpan.FromSeconds(90)); - // appHost.Services.AddLogging(logging => - // { - // logging.SetMinimumLevel(LogLevel.Debug); - - // // Override the logging filters from the app's configuration - // logging.AddFilter(appHost.Environment.ApplicationName, LogLevel.Debug); - // logging.AddFilter("Aspire.", LogLevel.Debug); - - // logging.AddXUnit(_testOutputHelper); - // }); + var script2 = model.Resources + .OfType() + .Single(r => r.Name == "script2"); - // await using var app = await appHost.BuildAsync(cancellationToken).WaitAsync(DefaultTimeout, cancellationToken); + var ready2 = fixture.ResourceNotificationService + .WaitForResourceAsync(script2.Name, KnownResourceStates.Finished) + .WaitAsync(TimeSpan.FromSeconds(90)); - // await app.StartAsync(cancellationToken).WaitAsync(DefaultTimeout, cancellationToken); - - // await foreach (var notification in app.ResourceNotifications.WatchAsync(cancellationToken)) - // { - // _testOutputHelper.WriteLine($"Notification: {notification.Resource.Name} - {notification.Snapshot.State} - {notification.Snapshot.HealthStatus}"); - // } - - // Assert.True(true); - //} + await Task.WhenAll([ready1, ready2]); + } } + From bb34f88c5dc049275be383583b0c956e1a0086fc Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Fri, 30 May 2025 20:36:49 -0400 Subject: [PATCH 12/24] fix up directory.packages.props, oops --- Directory.Packages.props | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index b77d5f51e..95f5bab4e 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -6,7 +6,7 @@ - + @@ -17,8 +17,7 @@ - - + @@ -83,6 +82,7 @@ + From a9d32527fe94428e7d5dc93ae7c25af6ae9a8e7e Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Tue, 3 Jun 2025 09:48:49 -0400 Subject: [PATCH 13/24] Update src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs Co-authored-by: Aaron Powell --- .../DistributedApplicationBuilderExtensions.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs index 953ddde90..e67eabaa1 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs @@ -31,8 +31,7 @@ public static IResourceBuilder AddPowerShell( int minRunspaces = 1, int maxRunspaces = 5) { - if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Value cannot be null or whitespace.", nameof(name)); + ArgumentNullException.ThrowIfNullOrEmpty(name); if (builder.Resources.OfType().Any( rsp => rsp.Name == name)) From e68d7cefed869a59326dd81f648cb519c99d182d Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Tue, 3 Jun 2025 09:50:04 -0400 Subject: [PATCH 14/24] Update src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs Co-authored-by: Aaron Powell --- .../PowerShellRunspacePoolResourceBuilderExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs index bf0fdc4dd..b4bea5163 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs @@ -47,7 +47,7 @@ public static IResourceBuilder AddScript( _ = notificationService .WaitForDependenciesAsync(scriptResource, ct) .ContinueWith( - async (_) => await scriptResource.StartAsync(scriptLogger, notificationService, ct), + _ => scriptResource.StartAsync(scriptLogger, notificationService, ct), ct); } catch (Exception ex) From 84529c685c6eed2233df671abd41dbb2e54a92ee Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Tue, 3 Jun 2025 09:59:40 -0400 Subject: [PATCH 15/24] Update src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs Co-authored-by: Aaron Powell --- .../DistributedApplicationBuilderExtensions.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs index e67eabaa1..09393830c 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs @@ -74,9 +74,7 @@ public static IResourceBuilder AddPowerShell( var poolLogger = loggerService.GetLogger(poolName); _ = notificationService.WaitForDependenciesAsync(poolResource, ct) - .ContinueWith( - async _ => - await poolResource.StartAsync(sessionState, notificationService, poolLogger, ct), + .ContinueWith(_ => poolResource.StartAsync(sessionState, notificationService, poolLogger, ct), ct); } }); From 35396da483d63f69e4714bffaff4fd52dfd73db9 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Tue, 10 Jun 2025 17:26:12 -0400 Subject: [PATCH 16/24] address nits and completely restructure lifecycle management --- CommunityToolkit.Aspire.slnx | 474 +++++++++--------- ...DistributedApplicationBuilderExtensions.cs | 44 +- .../PowerShellRunspacePoolResource.cs | 42 +- ...llRunspacePoolResourceBuilderExtensions.cs | 20 +- .../PowerShellScriptResource.cs | 51 +- 5 files changed, 304 insertions(+), 327 deletions(-) diff --git a/CommunityToolkit.Aspire.slnx b/CommunityToolkit.Aspire.slnx index 0c14a6f9a..fdffae1d3 100644 --- a/CommunityToolkit.Aspire.slnx +++ b/CommunityToolkit.Aspire.slnx @@ -1,240 +1,236 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs index 09393830c..b7b9d79c8 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs @@ -2,7 +2,6 @@ using Aspire.Hosting.ApplicationModel; using Microsoft.Extensions.DependencyInjection; using System.Diagnostics; -using System.Globalization; using System.Management.Automation; using System.Management.Automation.Runspaces; @@ -13,6 +12,8 @@ namespace CommunityToolkit.Aspire.Hosting.PowerShell; /// public static class DistributedApplicationBuilderExtensions { + private static bool _eventingSubscribed = false; + /// /// Adds a PowerShell runspace pool resource to the distributed application. /// @@ -31,26 +32,22 @@ public static IResourceBuilder AddPowerShell( int minRunspaces = 1, int maxRunspaces = 5) { - ArgumentNullException.ThrowIfNullOrEmpty(name); - - if (builder.Resources.OfType().Any( - rsp => rsp.Name == name)) - { - throw new DistributedApplicationException("AddPowerShell failed", - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "A PowerShell resource with the name '{0}' already exists.", name))); - } + ArgumentException.ThrowIfNullOrWhiteSpace(name); var pool = new PowerShellRunspacePoolResource(name, languageMode, minRunspaces, maxRunspaces); - builder.Eventing.Subscribe(async (e, ct) => + if (!_eventingSubscribed) { - var pools = e.Model.Resources.OfType().ToList(); + _eventingSubscribed = true; - foreach (var poolResource in pools) + builder.Eventing.Subscribe(pool, async (e, ct) => { + //var pools = e..Resources.OfType().ToList(); + + //foreach (var poolResource in pools) + //{ + var poolResource = e.Resource as PowerShellRunspacePoolResource; + Debug.Assert(poolResource is not null); var loggerService = e.Services.GetRequiredService(); @@ -58,6 +55,10 @@ public static IResourceBuilder AddPowerShell( var sessionState = InitialSessionState.CreateDefault(); + // publish the BeforeResourceStartedEvent to allow other resources to prepare + await builder.Eventing.PublishAsync( + new BeforeResourceStartedEvent(poolResource, e.Services), ct); + foreach (var annotation in poolResource.Annotations) { if (annotation is PowerShellVariableReferenceAnnotation reference) @@ -73,11 +74,14 @@ public static IResourceBuilder AddPowerShell( var poolName = poolResource.Name; var poolLogger = loggerService.GetLogger(poolName); - _ = notificationService.WaitForDependenciesAsync(poolResource, ct) - .ContinueWith(_ => poolResource.StartAsync(sessionState, notificationService, poolLogger, ct), - ct); - } - }); + //_ = notificationService.WaitForDependenciesAsync(poolResource, ct) + // .ContinueWith(_ => poolResource.StartAsync(sessionState, notificationService, poolLogger, ct), + // ct); + + _ = poolResource.StartAsync(sessionState, notificationService, poolLogger, ct); + //} + }); + } return builder.AddResource(pool) .WithInitialState(new() diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs index 605e0409c..7ee418424 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs @@ -39,6 +39,10 @@ public class PowerShellRunspacePoolResource( internal Task StartAsync(InitialSessionState sessionState, ResourceNotificationService notificationService, ILogger logger, CancellationToken token = default) { + logger.LogInformation( + "Starting PowerShell runspace pool '{PoolName}' with {MinRunspaces} to {MaxRunspaces} runspaces", + Name, MinRunspaces, MaxRunspaces); + sessionState.LanguageMode = this.LanguageMode; sessionState.AuthorizationManager = new AuthorizationManager("Aspire"); Pool = RunspaceFactory.CreateRunspacePool(MinRunspaces, MaxRunspaces, sessionState, new AspirePSHost(logger)); @@ -73,39 +77,25 @@ private void ConfigureStateChangeNotifications(ResourceNotificationService notif nameof(poolState), poolState, $"Unexpected runspace pool state {poolState}") }; + logger.LogInformation( + "Runspace pool '{PoolName}' state mapped to known state '{KnownState}'", Name, knownState); + await notificationService.PublishUpdateAsync(this, - state => { - state = state with - { - State = knownState, - Properties = [.. state.Properties, + state => state with + { + State = knownState, + Properties = [ + .. state.Properties, new("RunspacePoolState", poolState.ToString()), new("Reason", reason?.ToString() ?? string.Empty) - ] - }; - - if (knownState == KnownResourceStates.Running) - { - state = state with - { - StartTimeStamp = DateTime.Now, - }; - } - - if (KnownResourceStates.TerminalStates.Contains(knownState)) - { - state = state with - { - StopTimeStamp = DateTime.Now, - }; - } - - return state; + ], + StartTimeStamp = knownState == KnownResourceStates.Running ? DateTime.Now : state.StartTimeStamp, + StopTimeStamp = KnownResourceStates.TerminalStates.Contains(knownState) ? DateTime.Now : state.StopTimeStamp, }); }; } - // absolutely brain dead and deficient (minimal) PSHost implementation + // minimal PSHost implementation (aspire does not support interaction with the host, yet) private class AspirePSHost(ILogger logger) : PSHost { public override void SetShouldExit(int exitCode) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs index b4bea5163..5ab6437b6 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResourceBuilderExtensions.cs @@ -32,36 +32,34 @@ public static IResourceBuilder AddScript( var scriptResource = new PowerShellScriptResource(name, scriptBlock, builder.Resource); - builder.ApplicationBuilder.Eventing.Subscribe(scriptResource, (e, ct) => + builder.ApplicationBuilder.Eventing.Subscribe(scriptResource, async (e, ct) => { var loggerService = e.Services.GetRequiredService(); var notificationService = e.Services.GetRequiredService(); var scriptName = scriptResource.Name; var scriptLogger = loggerService.GetLogger(scriptName); + try { - // TODO: capture script streams and log them + // this will block until the runspace pool is started, which is implied by the WaitFor call + await builder.ApplicationBuilder.Eventing.PublishAsync( + new BeforeResourceStartedEvent(scriptResource, e.Services), ct); + scriptLogger.LogInformation("Starting script '{ScriptName}'", scriptName); - _ = notificationService - .WaitForDependenciesAsync(scriptResource, ct) - .ContinueWith( - _ => scriptResource.StartAsync(scriptLogger, notificationService, ct), - ct); + _ = scriptResource.StartAsync(scriptLogger, notificationService, ct); } catch (Exception ex) { scriptLogger.LogError(ex, "Failed to start script '{ScriptName}'", scriptName); } - - return Task.CompletedTask; }); return builder.ApplicationBuilder .AddResource(scriptResource) - .WaitFor(builder) // wait for pool resource - .WithParentRelationship(builder.Resource) // owned by pool + .WithParentRelationship(builder.Resource) + .WaitFor(builder) .WithInitialState(new() { ResourceType = "PowerShellScript", diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs index 1d13b028e..d7988e5db 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs @@ -15,7 +15,6 @@ public class PowerShellScriptResource : Resource, IDisposable, { private readonly System.Management.Automation.PowerShell _ps; private readonly CancellationTokenSource _cts; - private readonly PowerShellRunspacePoolResource _parent; private readonly PSDataCollection _output; private readonly PSDataCollection _emptyInput; private ILogger? _scriptLogger; @@ -31,12 +30,12 @@ public class PowerShellScriptResource : Resource, IDisposable, /// The name of the resource. This must be a valid resource name. /// The ScriptBlock to be executed. /// The parent that provides the runspace pool for script - /// execution. Cannot be null. + /// execution. Cannot be null. public PowerShellScriptResource([ResourceName] string name, ScriptBlock script, PowerShellRunspacePoolResource parent) : base(name) { - _parent = parent; + Parent = parent; _cts = new CancellationTokenSource(); _ps = System.Management.Automation.PowerShell.Create(); @@ -69,7 +68,7 @@ public PowerShellScriptResource([ResourceName] string name, FileInfo scriptFile, PowerShellRunspacePoolResource parent) : base(name) { - _parent = parent; + Parent = parent; _cts = new CancellationTokenSource(); _ps = System.Management.Automation.PowerShell.Create(); @@ -88,6 +87,11 @@ public PowerShellScriptResource([ResourceName] string name, _ps.AddCommand(scriptFile.FullName); } + /// + /// Parent PowerShell runspace pool resource that provides the runspace pool for script execution. + /// + public PowerShellRunspacePoolResource Parent { get; } + /// /// Breaks the PowerShell script execution. /// @@ -121,11 +125,13 @@ public async Task StartAsync(ILogger scriptLogger, ResourceNotificationService notificationService, CancellationToken cancellationToken = default) { + scriptLogger.LogInformation("Starting PowerShell script '{ScriptName}'", Name); + Debug.Assert(scriptLogger != null); _scriptLogger = scriptLogger; - Debug.Assert(_parent.Pool != null); - _ps.RunspacePool = _parent.Pool; + Debug.Assert(Parent.Pool != null); + _ps.RunspacePool = Parent.Pool; ConfigurePSDataStreams(scriptLogger, notificationService); @@ -145,36 +151,19 @@ public async Task StartAsync(ILogger scriptLogger, "Unknown PowerShell invocation state") }; + scriptLogger.LogInformation("Publishing script {ScriptName} state as known state: {ScriptState}", Name, knownState); + await notificationService.PublishUpdateAsync(this, - state => + state => state with { - state = state with - { - State = knownState, - Properties = [ + State = knownState, + Properties = [ .. state.Properties, new( "PSInvocationState", args.InvocationStateInfo.State.ToString() ), new( "Reason", args.InvocationStateInfo.Reason?.Message ?? string.Empty ), - ] - }; - - if (knownState == KnownResourceStates.Running) - { - state = state with - { - StartTimeStamp = DateTime.Now, - }; - } - - if (KnownResourceStates.TerminalStates.Contains(knownState)) - { - state = state with - { - StopTimeStamp = DateTime.Now, - }; - } - - return state; + ], + StartTimeStamp = knownState == KnownResourceStates.Running ? DateTime.Now : state.StartTimeStamp, + StopTimeStamp = KnownResourceStates.TerminalStates.Contains(knownState) ? DateTime.Now : state.StopTimeStamp, }); }; From 9afd47b8007041633f2a4c703b63983d0d6d7af8 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Tue, 10 Jun 2025 17:35:32 -0400 Subject: [PATCH 17/24] conditionally use az cli in apphost sample; remove dead code --- .../Program.cs | 17 +++++++++++++---- .../DistributedApplicationBuilderExtensions.cs | 12 ++---------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs index b335604d6..57f4bb348 100644 --- a/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs +++ b/examples/powershell/CommunityToolkit.Aspire.PowerShell.AppHost/Program.cs @@ -20,12 +20,21 @@ write-information "`$myblob is $myblob" - az storage container create --connection-string $myblob -n demo - az storage blob upload --connection-string $myblob -c demo --file ./scripts/script.ps1 - + # only run this if Azure CLI is installed + if ((gcm az -ErrorAction SilentlyContinue) -ne $null) { + + az storage container create --connection-string $myblob -n demo + az storage blob upload --connection-string $myblob -c demo --file ./scripts/script.ps1 + write-information "Blob uploaded" + + } else { + + write-warning "Azure CLI not found, skipping blob upload" + + } write-information $pwd - write-information "Blob uploaded" + """).WithArgs("world"); // outputs "the sum of 2 and 3 is 5" diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs index b7b9d79c8..99e24b0db 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs @@ -42,10 +42,6 @@ public static IResourceBuilder AddPowerShell( builder.Eventing.Subscribe(pool, async (e, ct) => { - //var pools = e..Resources.OfType().ToList(); - - //foreach (var poolResource in pools) - //{ var poolResource = e.Resource as PowerShellRunspacePoolResource; Debug.Assert(poolResource is not null); @@ -55,7 +51,7 @@ public static IResourceBuilder AddPowerShell( var sessionState = InitialSessionState.CreateDefault(); - // publish the BeforeResourceStartedEvent to allow other resources to prepare + // This will block until explicit and implied WaitFor calls are completed await builder.Eventing.PublishAsync( new BeforeResourceStartedEvent(poolResource, e.Services), ct); @@ -74,12 +70,8 @@ await builder.Eventing.PublishAsync( var poolName = poolResource.Name; var poolLogger = loggerService.GetLogger(poolName); - //_ = notificationService.WaitForDependenciesAsync(poolResource, ct) - // .ContinueWith(_ => poolResource.StartAsync(sessionState, notificationService, poolLogger, ct), - // ct); - _ = poolResource.StartAsync(sessionState, notificationService, poolLogger, ct); - //} + }); } From f4b6c05a861236422a6a864aa5a9ec118cd21351 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Tue, 10 Jun 2025 17:37:10 -0400 Subject: [PATCH 18/24] Update src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../PowerShellScriptResource.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs index d7988e5db..91c83343d 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs @@ -253,6 +253,7 @@ void IDisposable.Dispose() _isDisposed = true; _ps.Stop(); _ps.Dispose(); + _cts?.Dispose(); } } } From cf0dfd458b304b44cabb4de3b5fcc5a7e49e44d3 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Wed, 11 Jun 2025 09:19:15 -0400 Subject: [PATCH 19/24] address aaron's comments --- ...DistributedApplicationBuilderExtensions.cs | 53 ++++++++----------- 1 file changed, 23 insertions(+), 30 deletions(-) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs index 99e24b0db..ebda7a5b8 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs @@ -12,8 +12,6 @@ namespace CommunityToolkit.Aspire.Hosting.PowerShell; /// public static class DistributedApplicationBuilderExtensions { - private static bool _eventingSubscribed = false; - /// /// Adds a PowerShell runspace pool resource to the distributed application. /// @@ -36,44 +34,39 @@ public static IResourceBuilder AddPowerShell( var pool = new PowerShellRunspacePoolResource(name, languageMode, minRunspaces, maxRunspaces); - if (!_eventingSubscribed) + builder.Eventing.Subscribe(pool, async (e, ct) => { - _eventingSubscribed = true; - - builder.Eventing.Subscribe(pool, async (e, ct) => - { - var poolResource = e.Resource as PowerShellRunspacePoolResource; + var poolResource = e.Resource as PowerShellRunspacePoolResource; - Debug.Assert(poolResource is not null); + Debug.Assert(poolResource is not null); - var loggerService = e.Services.GetRequiredService(); - var notificationService = e.Services.GetRequiredService(); + var loggerService = e.Services.GetRequiredService(); + var notificationService = e.Services.GetRequiredService(); - var sessionState = InitialSessionState.CreateDefault(); + var sessionState = InitialSessionState.CreateDefault(); - // This will block until explicit and implied WaitFor calls are completed - await builder.Eventing.PublishAsync( - new BeforeResourceStartedEvent(poolResource, e.Services), ct); + // This will block until explicit and implied WaitFor calls are completed + await builder.Eventing.PublishAsync( + new BeforeResourceStartedEvent(poolResource, e.Services), ct); - foreach (var annotation in poolResource.Annotations) + foreach (var annotation in poolResource.Annotations.OfType>()) + { + if (annotation is { } reference) { - if (annotation is PowerShellVariableReferenceAnnotation reference) - { - var connectionString = await reference.Value.Resource.GetConnectionStringAsync(ct); - sessionState.Variables.Add( - new SessionStateVariableEntry(reference.Name, connectionString, - $"ConnectionString for {reference.Value.Resource.GetType().Name} '{reference.Name}'", - ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope)); - } + var connectionString = await reference.Value.Resource.GetConnectionStringAsync(ct); + sessionState.Variables.Add( + new SessionStateVariableEntry(reference.Name, connectionString, + $"ConnectionString for {reference.Value.Resource.GetType().Name} '{reference.Name}'", + ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope)); } + } - var poolName = poolResource.Name; - var poolLogger = loggerService.GetLogger(poolName); - - _ = poolResource.StartAsync(sessionState, notificationService, poolLogger, ct); + var poolName = poolResource.Name; + var poolLogger = loggerService.GetLogger(poolName); - }); - } + _ = poolResource.StartAsync(sessionState, notificationService, poolLogger, ct); + }); + return builder.AddResource(pool) .WithInitialState(new() From dd67233ff8abf67b99cb8792b9486e9bbc4f2492 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Wed, 11 Jun 2025 09:29:01 -0400 Subject: [PATCH 20/24] what --- ...DistributedApplicationBuilderExtensions.cs | 50 ++++++++----------- 1 file changed, 21 insertions(+), 29 deletions(-) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs index b0a504c3f..baf5ce2b1 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/DistributedApplicationBuilderExtensions.cs @@ -12,8 +12,6 @@ namespace CommunityToolkit.Aspire.Hosting.PowerShell; /// public static class DistributedApplicationBuilderExtensions { - private static bool _eventingSubscribed = false; - /// /// Adds a PowerShell runspace pool resource to the distributed application. /// @@ -36,46 +34,40 @@ public static IResourceBuilder AddPowerShell( var pool = new PowerShellRunspacePoolResource(name, languageMode, minRunspaces, maxRunspaces); - if (!_eventingSubscribed) - { - _eventingSubscribed = true; - builder.Eventing.Subscribe(pool, async (e, ct) => - { - var poolResource = e.Resource as PowerShellRunspacePoolResource; + builder.Eventing.Subscribe(pool, async (e, ct) => + { + var poolResource = e.Resource as PowerShellRunspacePoolResource; - Debug.Assert(poolResource is not null); + Debug.Assert(poolResource is not null); - var loggerService = e.Services.GetRequiredService(); - var notificationService = e.Services.GetRequiredService(); + var loggerService = e.Services.GetRequiredService(); + var notificationService = e.Services.GetRequiredService(); - var sessionState = InitialSessionState.CreateDefault(); + var sessionState = InitialSessionState.CreateDefault(); - // This will block until explicit and implied WaitFor calls are completed - await builder.Eventing.PublishAsync( - new BeforeResourceStartedEvent(poolResource, e.Services), ct); + // This will block until explicit and implied WaitFor calls are completed + await builder.Eventing.PublishAsync( + new BeforeResourceStartedEvent(poolResource, e.Services), ct); foreach (var annotation in poolResource.Annotations.OfType>()) - { + { if (annotation is { } reference) - { - var connectionString = await reference.Value.Resource.GetConnectionStringAsync(ct); - sessionState.Variables.Add( - new SessionStateVariableEntry(reference.Name, connectionString, - $"ConnectionString for {reference.Value.Resource.GetType().Name} '{reference.Name}'", - ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope)); - } + { + var connectionString = await reference.Value.Resource.GetConnectionStringAsync(ct); + sessionState.Variables.Add( + new SessionStateVariableEntry(reference.Name, connectionString, + $"ConnectionString for {reference.Value.Resource.GetType().Name} '{reference.Name}'", + ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope)); } + } - var poolName = poolResource.Name; - var poolLogger = loggerService.GetLogger(poolName); + var poolName = poolResource.Name; + var poolLogger = loggerService.GetLogger(poolName); - _ = poolResource.StartAsync(sessionState, notificationService, poolLogger, ct); + _ = poolResource.StartAsync(sessionState, notificationService, poolLogger, ct); }); - }); - } - return builder.AddResource(pool) .WithInitialState(new() { From ee58e7e087c07c22e030876c7c25cc1e0994dc58 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Wed, 11 Jun 2025 09:37:03 -0400 Subject: [PATCH 21/24] drop some informational messages to debug level to reduce noise --- .../PowerShellRunspacePoolResource.cs | 2 +- .../PowerShellScriptResource.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs index 7ee418424..a0a90156d 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellRunspacePoolResource.cs @@ -77,7 +77,7 @@ private void ConfigureStateChangeNotifications(ResourceNotificationService notif nameof(poolState), poolState, $"Unexpected runspace pool state {poolState}") }; - logger.LogInformation( + logger.LogDebug( "Runspace pool '{PoolName}' state mapped to known state '{KnownState}'", Name, knownState); await notificationService.PublishUpdateAsync(this, diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs index 91c83343d..f51de936c 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs @@ -151,7 +151,7 @@ public async Task StartAsync(ILogger scriptLogger, "Unknown PowerShell invocation state") }; - scriptLogger.LogInformation("Publishing script {ScriptName} state as known state: {ScriptState}", Name, knownState); + scriptLogger.LogDebug("Publishing script {ScriptName} state as known state: {ScriptState}", Name, knownState); await notificationService.PublishUpdateAsync(this, state => state with From 6784a3ffce6eeba552d57bec310e85332de6af4e Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Thu, 12 Jun 2025 09:24:27 +1000 Subject: [PATCH 22/24] Apply suggestions from code review --- .../PowerShellScriptResource.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs index f51de936c..7e2236d3d 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/PowerShellScriptResource.cs @@ -127,10 +127,10 @@ public async Task StartAsync(ILogger scriptLogger, { scriptLogger.LogInformation("Starting PowerShell script '{ScriptName}'", Name); - Debug.Assert(scriptLogger != null); + Debug.Assert(scriptLogger is not null); _scriptLogger = scriptLogger; - Debug.Assert(Parent.Pool != null); + Debug.Assert(Parent.Pool is not null); _ps.RunspacePool = Parent.Pool; ConfigurePSDataStreams(scriptLogger, notificationService); From 1389a65aa1ca597a26c165e81b0eb0b3412f33c8 Mon Sep 17 00:00:00 2001 From: Oisin Grehan Date: Mon, 16 Jun 2025 09:59:47 -0400 Subject: [PATCH 23/24] Update tests.yaml --- .github/workflows/tests.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 54fc6a43a..cfb4a519c 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -43,6 +43,7 @@ jobs: Hosting.Ollama.Tests, Hosting.PapercutSmtp.Tests, Hosting.PostgreSQL.Extensions.Tests, + Hosting.PowerShell.Tests, Hosting.Python.Extensions.Tests, Hosting.RavenDB.Tests, Hosting.Redis.Extensions.Tests, From d11ae45dbceb5629a121bceb51c3a00820183a7c Mon Sep 17 00:00:00 2001 From: Aaron Powell Date: Tue, 17 Jun 2025 10:34:10 +1000 Subject: [PATCH 24/24] Update src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj --- .../CommunityToolkit.Aspire.Hosting.PowerShell.csproj | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj b/src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj index 045a19c73..9513fc8e1 100644 --- a/src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj +++ b/src/CommunityToolkit.Aspire.Hosting.PowerShell/CommunityToolkit.Aspire.Hosting.PowerShell.csproj @@ -1,9 +1,6 @@  - net8.0 - enable - enable powershell; pwsh; scripting; script; hosting Run powershell scripts in-process with your Aspire AppHost, injecting aspire resources and/or object instances as variables, using the command lines tools of your choice like azure cli, azd, or any other terminal tools.