diff --git a/LocalInstaller.Core.Tests/Features/MacOsInstallation/Model/MacOsInstallerManifestEnvironmentVariablesTests.cs b/LocalInstaller.Core.Tests/Features/MacOsInstallation/Model/MacOsInstallerManifestEnvironmentVariablesTests.cs new file mode 100644 index 0000000..a38d9c6 --- /dev/null +++ b/LocalInstaller.Core.Tests/Features/MacOsInstallation/Model/MacOsInstallerManifestEnvironmentVariablesTests.cs @@ -0,0 +1,44 @@ +using LocalInstaller.Core.Features.Installation.Models; +using LocalInstaller.Core.Features.MacOsInstallation.Models; + +namespace LocalInstaller.Core.Tests.Features.MacOsInstallation.Model; + +[TestFixture] +public class MacOsInstallerManifestEnvironmentVariablesTests +{ + [Test] + public void LaunchDaemonPlist_includesServerComponentEnvironmentVariables() + { + var product = new ProductManifest("Acme Studio", "acme-studio", "ACMESTUDIO") + { + Components = + [ + ProductComponent.Server with + { + EnvironmentVariables = new Dictionary { ["EXAMPLE_FLAG"] = "true" } + } + ] + }; + + var manifest = MacOsInstallerManifest.From(product, "1.0.0"); + var plist = new MacOsInstallerPlistGenerator(manifest).LaunchDaemonPlist(); + + Assert.That(plist, Does.Contain("EXAMPLE_FLAG")); + Assert.That(plist, Does.Contain("true")); + } + + [Test] + public void LaunchDaemonPlist_omitsExtraEnvironmentVariablesWhenNoneDeclared() + { + var product = new ProductManifest("Acme Studio", "acme-studio", "ACMESTUDIO") + { + Components = [ProductComponent.Server] + }; + + var manifest = MacOsInstallerManifest.From(product, "1.0.0"); + var plist = new MacOsInstallerPlistGenerator(manifest).LaunchDaemonPlist(); + + Assert.That(plist, Does.Contain("ASPNETCORE_URLS")); + Assert.That(plist, Does.Not.Contain("EXAMPLE_FLAG")); + } +} diff --git a/LocalInstaller.Core.Tests/Features/UbuntuInstallation/Provider/UbuntuInstallerPlatformAdapterTests.cs b/LocalInstaller.Core.Tests/Features/UbuntuInstallation/Provider/UbuntuInstallerPlatformAdapterTests.cs index 5ec2593..f7f555c 100644 --- a/LocalInstaller.Core.Tests/Features/UbuntuInstallation/Provider/UbuntuInstallerPlatformAdapterTests.cs +++ b/LocalInstaller.Core.Tests/Features/UbuntuInstallation/Provider/UbuntuInstallerPlatformAdapterTests.cs @@ -69,7 +69,8 @@ public async Task ExecuteInstallAsync_runsElevatedScriptContainingAllComponents( Assert.That(script, Does.Contain("cp -r '/payload/server'/.")); Assert.That(script, Does.Contain("cp '/payload/agent-up-server.service' '/etc/systemd/system/agent-up-server.service'")); Assert.That(script, Does.Contain("systemctl daemon-reload")); - Assert.That(script, Does.Contain("systemctl enable --now 'agent-up-server.service'")); + Assert.That(script, Does.Contain("systemctl enable 'agent-up-server.service'")); + Assert.That(script, Does.Contain("systemctl restart 'agent-up-server.service'")); // CLI operations Assert.That(script, Does.Contain("rm -rf '/opt/agent-up/cli'")); @@ -78,6 +79,43 @@ public async Task ExecuteInstallAsync_runsElevatedScriptContainingAllComponents( Assert.That(script, Does.Contain("ln -sf '/opt/agent-up/cli/AgentUp.CLI' '/usr/bin/agent-up'")); } + [Test] + public async Task ExecuteInstallAsync_writesSystemdDropInWhenManifestDeclaresServerEnvironmentVariables() + { + var commands = new ScriptCapturingCommandRunner(); + var manifest = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()) with + { + EnvironmentVariables = new Dictionary { ["EXAMPLE_FLAG"] = "true" } + }; + var options = Options() with { Manifest = manifest }; + var adapter = new UbuntuInstallerPlatformAdapter( + commands, + new RecordingUbuntuFileSystem(), + options, + new RequiredCommandRunner(commands), + new DockerPrerequisite(new DockerPrerequisiteProvider(commands), new Version(27, 0, 0))); + + await adapter.ExecuteInstallAsync(Session()).DrainAsync(); + + var script = commands.CapturedScript; + Assert.That(script, Does.Contain("mkdir -p '/etc/systemd/system/agent-up-server.service.d'")); + Assert.That(script, Does.Contain("[Service]")); + Assert.That(script, Does.Contain("Environment=\"EXAMPLE_FLAG=true\"")); + } + + [Test] + public async Task ExecuteInstallAsync_writesNoDropInWhenManifestDeclaresNoServerEnvironmentVariables() + { + var commands = new ScriptCapturingCommandRunner(); + var adapter = Adapter(commands, new RecordingUbuntuFileSystem()); + + await adapter.ExecuteInstallAsync(Session()).DrainAsync(); + + var script = commands.CapturedScript; + Assert.That(script, Does.Not.Contain("mkdir -p '/etc/systemd/system/agent-up-server.service.d'")); + Assert.That(script, Does.Not.Contain("[Service]")); + } + [Test] public async Task ValidateInstalledStateAsync_reportsSuccessFromUbuntuState() { @@ -130,7 +168,8 @@ public async Task ExecuteComponentActionAsync_installServer_copiesTrayPayloadAnd { // Server payload is installed Assert.That(script, Does.Contain("cp -r '/payload/server'/.")); - Assert.That(script, Does.Contain("systemctl enable --now 'agent-up-server.service'")); + Assert.That(script, Does.Contain("systemctl enable 'agent-up-server.service'")); + Assert.That(script, Does.Contain("systemctl restart 'agent-up-server.service'")); // Tray payload is bundled with server Assert.That(script, Does.Contain("cp -r '/payload/tray'/.")); Assert.That(script, Does.Contain("chmod +x '/opt/agent-up/tray/AgentUp.Tray'")); diff --git a/LocalInstaller.Core.Tests/Features/UbuntuInstallation/Unit/UbuntuInstallerManifestTests.cs b/LocalInstaller.Core.Tests/Features/UbuntuInstallation/Unit/UbuntuInstallerManifestTests.cs index 1de3580..7fd6c7b 100644 --- a/LocalInstaller.Core.Tests/Features/UbuntuInstallation/Unit/UbuntuInstallerManifestTests.cs +++ b/LocalInstaller.Core.Tests/Features/UbuntuInstallation/Unit/UbuntuInstallerManifestTests.cs @@ -22,6 +22,76 @@ public void PostInstallScript_doesNotRunInstallCore() Assert.That(script, Does.Not.Contain("--install-core")); } + [Test] + public void EnvironmentOverrideConf_isEmptyWhenNoVariablesDeclared() + { + var conf = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()).EnvironmentOverrideConf(); + + Assert.That(conf, Is.Empty); + } + + [Test] + public void EnvironmentOverrideConf_quotesValuesContainingSpaces() + { + var manifest = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()) with + { + EnvironmentVariables = new Dictionary { ["EXAMPLE_MESSAGE"] = "hello world" } + }; + + var conf = manifest.EnvironmentOverrideConf(); + + Assert.That(conf, Does.Contain("Environment=\"EXAMPLE_MESSAGE=hello world\"")); + } + + [Test] + public void EnvironmentOverrideConf_doublesEmbeddedBackslashes() + { + var manifest = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()) with + { + EnvironmentVariables = new Dictionary { ["EXAMPLE_PATH"] = @"C:\tools" } + }; + + var conf = manifest.EnvironmentOverrideConf(); + + Assert.That(conf, Does.Contain(@"Environment=""EXAMPLE_PATH=C:\\tools""")); + } + + [Test] + public void EnvironmentOverrideConf_escapesEmbeddedQuotes() + { + var manifest = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()) with + { + EnvironmentVariables = new Dictionary { ["EXAMPLE_MESSAGE"] = "say \"hi\"" } + }; + + var conf = manifest.EnvironmentOverrideConf(); + + const string q = "\""; + Assert.That(conf, Does.Contain($"Environment={q}EXAMPLE_MESSAGE=say \\{q}hi\\{q}{q}")); + } + + [Test] + public void EnvironmentOverrideConf_rejectsValuesContainingNewlines() + { + var manifest = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()) with + { + EnvironmentVariables = new Dictionary { ["EXAMPLE_FLAG"] = "line1\nline2" } + }; + + Assert.That(() => manifest.EnvironmentOverrideConf(), Throws.ArgumentException); + } + + [Test] + public void EnvironmentOverrideConf_rejectsKeysContainingNewlines() + { + var manifest = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()) with + { + EnvironmentVariables = new Dictionary { ["EXAMPLE_FLAG\nSERVICE_ENVIRONMENT"] = "true" } + }; + + Assert.That(() => manifest.EnvironmentOverrideConf(), Throws.ArgumentException); + } + [Test] public void DesktopEntryText_declaresStartupWmClassForUbuntuTaskbarIcon() { diff --git a/LocalInstaller.Core.Tests/Features/WindowsInstallation/Service/WindowsInstallerCommandsEnvironmentTests.cs b/LocalInstaller.Core.Tests/Features/WindowsInstallation/Service/WindowsInstallerCommandsEnvironmentTests.cs new file mode 100644 index 0000000..ce89687 --- /dev/null +++ b/LocalInstaller.Core.Tests/Features/WindowsInstallation/Service/WindowsInstallerCommandsEnvironmentTests.cs @@ -0,0 +1,42 @@ +using LocalInstaller.Core.Features.WindowsInstallation.Models; +using LocalInstaller.Core.Features.WindowsInstallation.Services; + +namespace LocalInstaller.Core.Tests.Features.WindowsInstallation.Service; + +[TestFixture] +public class WindowsInstallerCommandsEnvironmentTests +{ + [Test] + public void ServiceEnvironmentPowerShell_returnsNullWhenManifestDeclaresNoEnvironmentVariables() + { + var manifest = Manifest(null); + + Assert.That(WindowsInstallerCommands.ServiceEnvironmentPowerShell(manifest), Is.Null); + } + + [Test] + public void ServiceEnvironmentPowerShell_writesRegistryEnvironmentValueWhenDeclared() + { + var manifest = Manifest(new Dictionary { ["EXAMPLE_FLAG"] = "true" }); + + var script = WindowsInstallerCommands.ServiceEnvironmentPowerShell(manifest); + + Assert.That(script, Is.Not.Null); + Assert.That(script, Does.Contain($"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\{manifest.ServiceName}")); + Assert.That(script, Does.Contain("-Name Environment")); + Assert.That(script, Does.Contain("-PropertyType MultiString")); + Assert.That(script, Does.Contain("EXAMPLE_FLAG=true")); + } + + private static WindowsInstallerManifest Manifest(IReadOnlyDictionary? environmentVariables) + => new( + ProductName: "Acme Studio", + Manufacturer: "Acme Labs", + Version: "1.0.0", + UpgradeCode: "16357A7B-6C17-4635-85D5-28E74D12F4F3", + ServiceName: "acme-studio-server", + CliShimName: "acme-studio.cmd", + BundleName: "Acme Studio", + ServerUrl: "http://127.0.0.1:5000", + EnvironmentVariables: environmentVariables); +} diff --git a/LocalInstaller.Core/Features/Installation/Models/LocalInstallerManifestComponentExtensions.cs b/LocalInstaller.Core/Features/Installation/Models/LocalInstallerManifestComponentExtensions.cs index 0ab995d..950d1b2 100644 --- a/LocalInstaller.Core/Features/Installation/Models/LocalInstallerManifestComponentExtensions.cs +++ b/LocalInstaller.Core/Features/Installation/Models/LocalInstallerManifestComponentExtensions.cs @@ -15,7 +15,8 @@ public static ProductComponent ToProductComponent(this LocalInstallerArtifactDes TargetFor(descriptor.Target), descriptor.ExecutableName, descriptor.PayloadDirectoryName, - descriptor.SourceProjectPath); + descriptor.SourceProjectPath, + descriptor.EnvironmentVariables); private static InstallerComponentTarget TargetFor(LocalInstallerArtifactTarget target) => target switch diff --git a/LocalInstaller.Core/Features/Installation/Models/ProductComponent.cs b/LocalInstaller.Core/Features/Installation/Models/ProductComponent.cs index 3214a01..be07455 100644 --- a/LocalInstaller.Core/Features/Installation/Models/ProductComponent.cs +++ b/LocalInstaller.Core/Features/Installation/Models/ProductComponent.cs @@ -7,7 +7,8 @@ public sealed record ProductComponent( InstallerComponentTarget? Target = null, string? ExecutableName = null, string? PayloadDirectoryName = null, - string? SourceProjectPath = null) + string? SourceProjectPath = null, + IReadOnlyDictionary? EnvironmentVariables = null) { public static ProductComponent Desktop => new("desktop", "Desktop", "Desktop application.", InstallerComponentTarget.Desktop, "desktop", "desktop"); diff --git a/LocalInstaller.Core/Features/Installation/Models/ProductManifest.cs b/LocalInstaller.Core/Features/Installation/Models/ProductManifest.cs index d88102b..4417c87 100644 --- a/LocalInstaller.Core/Features/Installation/Models/ProductManifest.cs +++ b/LocalInstaller.Core/Features/Installation/Models/ProductManifest.cs @@ -33,4 +33,13 @@ public string DefaultInstallRoot() public IReadOnlyList InstallableComponents => InstallerOptions.Count == 0 ? Components : InstallerOptions; + + /// + /// Extra environment variables the Server component's manifest declared, applied when the platform + /// adapter registers the native service. Empty when the Server component declares none. + /// + public IReadOnlyDictionary ServerEnvironmentVariables + => InstallableComponents.FirstOrDefault(component => component.Target == InstallerComponentTarget.Server) + ?.EnvironmentVariables + ?? new Dictionary(); } diff --git a/LocalInstaller.Core/Features/MacOsInstallation/Models/MacOsInstallerManifest.cs b/LocalInstaller.Core/Features/MacOsInstallation/Models/MacOsInstallerManifest.cs index 718a951..87cb28c 100644 --- a/LocalInstaller.Core/Features/MacOsInstallation/Models/MacOsInstallerManifest.cs +++ b/LocalInstaller.Core/Features/MacOsInstallation/Models/MacOsInstallerManifest.cs @@ -15,7 +15,8 @@ public sealed partial record MacOsInstallerManifest( string ServerUrl, string DesktopExecutableName = "desktop", string InstallerExecutableName = "installer", - string ServerExecutableName = "server") + string ServerExecutableName = "server", + IReadOnlyDictionary? EnvironmentVariables = null) { private static readonly Regex SafeSlug = new(@"^[a-z][a-z0-9-]+$", RegexOptions.Compiled); private static readonly Regex SafeName = new(@"^[A-Za-z][A-Za-z0-9 -]*$", RegexOptions.Compiled); @@ -29,7 +30,8 @@ public static MacOsInstallerManifest From( return manifest with { DesktopExecutableName = ExecutableName(product, InstallerComponentTarget.Desktop, "desktop"), - ServerExecutableName = ExecutableName(product, InstallerComponentTarget.Server, "server") + ServerExecutableName = ExecutableName(product, InstallerComponentTarget.Server, "server"), + EnvironmentVariables = product.ServerEnvironmentVariables }; } @@ -130,7 +132,10 @@ public string LaunchDaemonPlist() new XElement("dict", KeyString("ASPNETCORE_URLS", _manifest.ServerUrl), KeyString("Storage__DataDirectory", $"/Library/Application Support/{_manifest.ProductName}"), - KeyString("DOTNET_BUNDLE_EXTRACT_BASE_DIR", $"/Library/Application Support/{_manifest.ProductName}/bundle-cache")), + KeyString("DOTNET_BUNDLE_EXTRACT_BASE_DIR", $"/Library/Application Support/{_manifest.ProductName}/bundle-cache"), + (_manifest.EnvironmentVariables ?? new Dictionary()) + .SelectMany(pair => KeyString(pair.Key, pair.Value)) + .ToArray()), new XElement("key", "RunAtLoad"), new XElement("true"), new XElement("key", "KeepAlive"), diff --git a/LocalInstaller.Core/Features/UbuntuInstallation/Models/UbuntuInstallerManifest.cs b/LocalInstaller.Core/Features/UbuntuInstallation/Models/UbuntuInstallerManifest.cs index 212b156..22d3c51 100644 --- a/LocalInstaller.Core/Features/UbuntuInstallation/Models/UbuntuInstallerManifest.cs +++ b/LocalInstaller.Core/Features/UbuntuInstallation/Models/UbuntuInstallerManifest.cs @@ -10,7 +10,8 @@ public sealed partial record UbuntuInstallerManifest( string DesktopExecutableName, string ServerExecutableName, string CliExecutableName, - string TrayExecutableName) + string TrayExecutableName, + IReadOnlyDictionary? EnvironmentVariables = null) { public static UbuntuInstallerManifest ForProduct(ProductManifest manifest) => new( @@ -21,7 +22,30 @@ public static UbuntuInstallerManifest ForProduct(ProductManifest manifest) DesktopExecutableName: ExecutableName(manifest, InstallerComponentTarget.Desktop, "desktop"), ServerExecutableName: ExecutableName(manifest, InstallerComponentTarget.Server, "server"), CliExecutableName: ExecutableName(manifest, InstallerComponentTarget.Cli, "cli"), - TrayExecutableName: ExecutableName(manifest, InstallerComponentTarget.Tray, "tray")); + TrayExecutableName: ExecutableName(manifest, InstallerComponentTarget.Tray, "tray"), + EnvironmentVariables: manifest.ServerEnvironmentVariables); + + /// + /// Extra systemd drop-in `Environment=` lines for , empty when the + /// Server manifest declared none. Each assignment is quoted per systemd.exec(5) config quoting rules + /// so values containing spaces, quotes, or backslashes parse as a single assignment. + /// + public string EnvironmentOverrideConf() + => string.Concat((EnvironmentVariables ?? new Dictionary()) + .Select(pair => $"Environment={SystemdAssignment(pair.Key, pair.Value)}" + Environment.NewLine)); + + private static string SystemdAssignment(string key, string value) + { + if (string.IsNullOrEmpty(key) || key.Contains('=') || key.Any(c => c is '\n' or '\r' || char.IsControl(c))) + throw new ArgumentException($"Environment variable key '{key}' is invalid.", nameof(key)); + + if (value.Any(c => c is '\n' or '\r' || char.IsControl(c))) + throw new ArgumentException( + $"Environment variable '{key}' value must not contain control characters.", nameof(value)); + + var escaped = $"{key}={value}".Replace("\\", "\\\\").Replace("\"", "\\\""); + return $"\"{escaped}\""; + } public string DesktopEntryText(string executablePath, string version) { diff --git a/LocalInstaller.Core/Features/UbuntuInstallation/Providers/UbuntuInstallerPlatformAdapter.cs b/LocalInstaller.Core/Features/UbuntuInstallation/Providers/UbuntuInstallerPlatformAdapter.cs index aee6242..35d7af5 100644 --- a/LocalInstaller.Core/Features/UbuntuInstallation/Providers/UbuntuInstallerPlatformAdapter.cs +++ b/LocalInstaller.Core/Features/UbuntuInstallation/Providers/UbuntuInstallerPlatformAdapter.cs @@ -12,6 +12,8 @@ namespace LocalInstaller.Core.Features.UbuntuInstallation.Providers; public sealed class UbuntuInstallerPlatformAdapter : IInstallerPlatformAdapter { + private const string EnvironmentDropInFileName = "10-environment.conf"; + private readonly ICommandRunner _commands; private readonly IUbuntuInstallerFileSystem _files; private readonly UbuntuInstallerOptions _options; @@ -186,8 +188,26 @@ private string BuildInstallScript(InstallSummary summary, Dictionary {Q(environmentDropIn)} << 'SERVICE_ENVIRONMENT'"); + sb.AppendLine("[Service]"); + sb.Append(environmentOverride); + sb.AppendLine("SERVICE_ENVIRONMENT"); + } + sb.AppendLine("systemctl daemon-reload"); - sb.AppendLine($"systemctl enable --now {Q(_options.Manifest.ServiceUnitName)}"); + sb.AppendLine($"systemctl enable {Q(_options.Manifest.ServiceUnitName)}"); + // enable --now would not restart an already-active unit, so an upgrade's new + // drop-in environment would not take effect; restart always applies it and + // still starts a stopped unit. + sb.AppendLine($"systemctl restart {Q(_options.Manifest.ServiceUnitName)}"); } if (summary.Includes(InstallerComponent.Tray)) @@ -233,6 +253,7 @@ private string BuildUninstallScript(InstallerComponentTarget target) case InstallerComponentTarget.Server: sb.AppendLine($"systemctl disable --now {Q(_options.Manifest.ServiceUnitName)} 2>/dev/null || true"); sb.AppendLine($"rm -f {Q(_options.Paths.ServicePath)}"); + sb.AppendLine($"rm -f {Q(Path.Join($"{_options.Paths.ServicePath}.d", EnvironmentDropInFileName))}"); sb.AppendLine("systemctl daemon-reload"); sb.AppendLine($"rm -rf {Q(_options.Paths.ServerDirectory)}"); sb.AppendLine($"rm -f {Q(_options.Paths.XdgAutostartPath)}"); diff --git a/LocalInstaller.Core/Features/WindowsInstallation/Models/WindowsInstallerManifest.cs b/LocalInstaller.Core/Features/WindowsInstallation/Models/WindowsInstallerManifest.cs index 61142a2..8591275 100644 --- a/LocalInstaller.Core/Features/WindowsInstallation/Models/WindowsInstallerManifest.cs +++ b/LocalInstaller.Core/Features/WindowsInstallation/Models/WindowsInstallerManifest.cs @@ -18,7 +18,8 @@ public sealed partial record WindowsInstallerManifest( string DesktopExecutableName = "desktop.exe", string ServerExecutableName = "server.exe", string CliExecutableName = "cli.exe", - string TrayExecutableName = "tray.exe") + string TrayExecutableName = "tray.exe", + IReadOnlyDictionary? EnvironmentVariables = null) { private static readonly char[] WindowsInvalidFileNameChars = ['<', '>', '"', '|', '?', '*']; private static readonly string[] WindowsReservedDeviceNames = @@ -72,7 +73,8 @@ public static WindowsInstallerManifest From(ProductManifest product, string vers DesktopExecutableName: WindowsExecutableName(product, InstallerComponentTarget.Desktop, "desktop"), ServerExecutableName: WindowsExecutableName(product, InstallerComponentTarget.Server, "server"), CliExecutableName: WindowsExecutableName(product, InstallerComponentTarget.Cli, "cli"), - TrayExecutableName: WindowsExecutableName(product, InstallerComponentTarget.Tray, "tray")); + TrayExecutableName: WindowsExecutableName(product, InstallerComponentTarget.Tray, "tray"), + EnvironmentVariables: product.ServerEnvironmentVariables); private static string StableUpgradeCode(string slug) { diff --git a/LocalInstaller.Core/Features/WindowsInstallation/Providers/WindowsInstallerPlatformAdapter.cs b/LocalInstaller.Core/Features/WindowsInstallation/Providers/WindowsInstallerPlatformAdapter.cs index c7c33cb..99a734b 100644 --- a/LocalInstaller.Core/Features/WindowsInstallation/Providers/WindowsInstallerPlatformAdapter.cs +++ b/LocalInstaller.Core/Features/WindowsInstallation/Providers/WindowsInstallerPlatformAdapter.cs @@ -194,6 +194,9 @@ public async IAsyncEnumerable ExecuteInstallAsync( { await _requiredCommands.RunAsync("sc.exe", WindowsInstallerCommands.ServiceCreateArguments(manifest, _options.Paths), cancellationToken); await _requiredCommands.RunAsync("sc.exe", WindowsInstallerCommands.ServiceFailureArguments(manifest), cancellationToken); + var environmentPowerShell = WindowsInstallerCommands.ServiceEnvironmentPowerShell(manifest); + if (environmentPowerShell is not null) + await _requiredCommands.RunPowerShellAsync(environmentPowerShell, cancellationToken); await _requiredCommands.RunAsync("sc.exe", ["start", manifest.ServiceName], cancellationToken); yield return progress.Complete(InstallOperationKind.RegisterService); } diff --git a/LocalInstaller.Core/Features/WindowsInstallation/Services/WindowsInstallerCommands.cs b/LocalInstaller.Core/Features/WindowsInstallation/Services/WindowsInstallerCommands.cs index 9136a6d..392cef1 100644 --- a/LocalInstaller.Core/Features/WindowsInstallation/Services/WindowsInstallerCommands.cs +++ b/LocalInstaller.Core/Features/WindowsInstallation/Services/WindowsInstallerCommands.cs @@ -20,6 +20,29 @@ public static IReadOnlyList ServiceCreateArguments(WindowsInstallerManif public static IReadOnlyList ServiceFailureArguments(WindowsInstallerManifest manifest) => ["failure", manifest.ServiceName, "reset=", "60", "actions=", "restart/5000/restart/5000/\"\"/5000"]; + /// + /// PowerShell that writes the service's registry `Environment` value (the standard mechanism + /// Windows Services use for extra process environment variables), or null when the manifest + /// declares none. Must run after the service is created and before it is started. + /// + public static string? ServiceEnvironmentPowerShell(WindowsInstallerManifest manifest) + { + var variables = manifest.EnvironmentVariables; + if (variables is null || variables.Count == 0) + return null; + + var entries = string.Join( + "," + Environment.NewLine, + variables.Select(pair => $"'{Ps($"{pair.Key}={pair.Value}")}'")); + + return $$""" + $servicePath = 'HKLM:\SYSTEM\CurrentControlSet\Services\{{Ps(manifest.ServiceName)}}' + New-ItemProperty -Force -Path $servicePath -Name Environment -PropertyType MultiString -Value @( + {{entries}} + ) | Out-Null + """; + } + public static string PrepareExistingServicePowerShell(WindowsInstallerManifest manifest) => $$""" $serviceName = '{{Ps(manifest.ServiceName)}}' diff --git a/LocalInstaller.Core/Shared/Interfaces/LocalInstallerManifests.cs b/LocalInstaller.Core/Shared/Interfaces/LocalInstallerManifests.cs index f386b99..661d2b2 100644 --- a/LocalInstaller.Core/Shared/Interfaces/LocalInstallerManifests.cs +++ b/LocalInstaller.Core/Shared/Interfaces/LocalInstallerManifests.cs @@ -16,7 +16,8 @@ public sealed record LocalInstallerArtifactDescriptor( string ExecutableName, string SourceProjectPath, string PayloadDirectoryName, - LocalInstallerArtifactTarget Target); + LocalInstallerArtifactTarget Target, + IReadOnlyDictionary? EnvironmentVariables = null); public abstract class LocalInstallerProductManifest { @@ -36,8 +37,16 @@ public abstract class LocalInstallerArtifactManifest public virtual string PayloadDirectoryName => Id; public abstract LocalInstallerArtifactTarget Target { get; } + /// + /// Extra environment variables the platform install/service registration should apply for this + /// artifact. Empty by default; a product manifest overrides this to declare variables it needs at + /// service-start time (for example, a product-specific opt-out flag for automated validation runs). + /// LocalInstaller has no opinion on the keys or values here. + /// + public virtual IReadOnlyDictionary EnvironmentVariables => new Dictionary(); + public LocalInstallerArtifactDescriptor ToDescriptor() - => new(Id, DisplayName, Description, ExecutableName, SourceProjectPath, PayloadDirectoryName, Target); + => new(Id, DisplayName, Description, ExecutableName, SourceProjectPath, PayloadDirectoryName, Target, EnvironmentVariables); } public abstract class LocalInstallerCliManifest : LocalInstallerArtifactManifest