From 4505276f7a22a92966977ce25866f95d4bc694b2 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Fri, 12 Jan 2024 06:57:41 +0100 Subject: [PATCH 01/35] fixing Launcher not starting on Systemd --- .../Commands/HostCommand.cs | 1 + .../Commands/RunCommand.cs | 1 + .../Extensions/DataProtectionExtensions.cs | 11 +-------- .../Extensions/LifetimeExtensions.cs | 7 ++++++ .../ServiceInstallation/LinuxSystemD.cs | 24 +++++++------------ .../fiskaltrust.Launcher.csproj | 3 ++- 6 files changed, 20 insertions(+), 27 deletions(-) diff --git a/src/fiskaltrust.Launcher/Commands/HostCommand.cs b/src/fiskaltrust.Launcher/Commands/HostCommand.cs index d50a079a..9b7111d1 100644 --- a/src/fiskaltrust.Launcher/Commands/HostCommand.cs +++ b/src/fiskaltrust.Launcher/Commands/HostCommand.cs @@ -108,6 +108,7 @@ public static async Task HandleAsync(HostOptions hostOptions, HostServices var builder = Host.CreateDefaultBuilder() .UseSerilog() + .UseSystemd() .ConfigureServices(services => { services.Configure(opts => diff --git a/src/fiskaltrust.Launcher/Commands/RunCommand.cs b/src/fiskaltrust.Launcher/Commands/RunCommand.cs index ddbff447..5048d01d 100644 --- a/src/fiskaltrust.Launcher/Commands/RunCommand.cs +++ b/src/fiskaltrust.Launcher/Commands/RunCommand.cs @@ -70,6 +70,7 @@ public static async Task HandleAsync(CommonOptions commonOptions, CommonPro builder.Host .UseSerilog() + .UseSystemd() .ConfigureServices((_, services) => { services.Configure(opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(30)); diff --git a/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs b/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs index de0f389a..39f858a8 100644 --- a/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs @@ -200,16 +200,7 @@ public static IDataProtectionBuilder ProtectKeysCustom(this IDataProtectionBuild } else if (OperatingSystem.IsLinux()) { - try - { - Marshal.PrelinkAll(typeof(KeyUtils)); - builder.Services.Configure(options => options.XmlEncryptor = new KeyringXmlEncryptor()); - return builder; - } - catch (Exception e) - { - Log.Warning(e, "Fallback config encryption mechanism used."); - } + Log.Warning("Fallback config encryption mechanism is used on linux."); } else if (OperatingSystem.IsMacOS()) { diff --git a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs index 2ae00daa..3d39a619 100644 --- a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs @@ -1,5 +1,6 @@ using System.Runtime.Versioning; using System.Text; +using Microsoft.Extensions.Hosting.Systemd; using Microsoft.Extensions.Hosting.WindowsServices; using Microsoft.Extensions.Options; @@ -28,6 +29,12 @@ public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder) #pragma warning restore CA1416 }); } + else if (SystemdHelpers.IsSystemdService()) + { + builder.UseSystemd(); + builder.ConfigureServices(services => services.AddSingleton()); + return builder; + } else { Console.OutputEncoding = Encoding.UTF8; diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 97ccb82e..3a8ecd70 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -1,4 +1,5 @@ using fiskaltrust.Launcher.Helpers; +using Microsoft.Extensions.Hosting.Systemd; using Serilog; namespace fiskaltrust.Launcher.ServiceInstallation @@ -15,7 +16,7 @@ public LinuxSystemD(string? serviceName, LauncherExecutablePath launcherExecutab public override async Task InstallService(string commandArgs, string? displayName, bool delayedStart = false) { - if (!await IsSystemd()) + if (!SystemdHelpers.IsSystemdService()) { return -1; } @@ -32,7 +33,7 @@ public override async Task InstallService(string commandArgs, string? displ public override async Task UninstallService() { - if (!await IsSystemd()) + if (!SystemdHelpers.IsSystemdService()) { return -1; } @@ -49,30 +50,21 @@ public override async Task UninstallService() return (await ProcessHelper.RunProcess("systemctl", new[] { "reset-failed" })).exitCode; } - private static async Task IsSystemd() - { - var (exitCode, output) = await ProcessHelper.RunProcess("ps", new[] { "--no-headers", "-o", "comm", "1" }); - if (exitCode != 0 && output.Contains("systemd")) - { - Log.Error("Service installation works only for systemd setup."); - return false; - } - return true; - } - private string[] GetServiceFileContent(string serviceDescription, string commandArgs) { var processPath = _launcherExecutablePath.Path; - var command = $"{processPath} {commandArgs}"; + var command = $"sudo {processPath} {commandArgs}"; return new[] { "[Unit]", $"Description=\"{serviceDescription}\"", "", "[Service]", - "Type=simple", - $"ExecStart=\"{command}\"", + "Type=notify", + $"ExecStart={command}", + "TimeoutSec=0", + $"WorkingDirectory={Path.GetDirectoryName(_launcherExecutablePath.Path)}", "", "[Install]", "WantedBy = multi-user.target" diff --git a/src/fiskaltrust.Launcher/fiskaltrust.Launcher.csproj b/src/fiskaltrust.Launcher/fiskaltrust.Launcher.csproj index b213e97a..c3b11f08 100644 --- a/src/fiskaltrust.Launcher/fiskaltrust.Launcher.csproj +++ b/src/fiskaltrust.Launcher/fiskaltrust.Launcher.csproj @@ -22,6 +22,7 @@ + @@ -31,7 +32,7 @@ - + From b04c2e82d6d90b8b92b7353a82667e81cb9bfbe9 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Fri, 12 Jan 2024 07:19:54 +0100 Subject: [PATCH 02/35] as merge to main is againnot woking start logging again --- src/fiskaltrust.Launcher/Commands/RunCommand.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/fiskaltrust.Launcher/Commands/RunCommand.cs b/src/fiskaltrust.Launcher/Commands/RunCommand.cs index 5048d01d..700344e8 100644 --- a/src/fiskaltrust.Launcher/Commands/RunCommand.cs +++ b/src/fiskaltrust.Launcher/Commands/RunCommand.cs @@ -66,7 +66,9 @@ public static class RunHandler { public static async Task HandleAsync(CommonOptions commonOptions, CommonProperties commonProperties, RunOptions _, RunServices runServices) { + Log.Debug("RunHandler"); var builder = WebApplication.CreateBuilder(); + Log.Debug("WebApplication.CreateBuilde"); builder.Host .UseSerilog() From 1b9dd66af0c6dbb85615216983fa89e41a97df2e Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Fri, 12 Jan 2024 07:50:45 +0100 Subject: [PATCH 03/35] .. --- .../Extensions/DataProtectionExtensions.cs | 11 ++++++++++- .../ServiceInstallation/LinuxSystemD.cs | 1 + 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs b/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs index 39f858a8..de0f389a 100644 --- a/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs @@ -200,7 +200,16 @@ public static IDataProtectionBuilder ProtectKeysCustom(this IDataProtectionBuild } else if (OperatingSystem.IsLinux()) { - Log.Warning("Fallback config encryption mechanism is used on linux."); + try + { + Marshal.PrelinkAll(typeof(KeyUtils)); + builder.Services.Configure(options => options.XmlEncryptor = new KeyringXmlEncryptor()); + return builder; + } + catch (Exception e) + { + Log.Warning(e, "Fallback config encryption mechanism used."); + } } else if (OperatingSystem.IsMacOS()) { diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 3a8ecd70..066fca1c 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -16,6 +16,7 @@ public LinuxSystemD(string? serviceName, LauncherExecutablePath launcherExecutab public override async Task InstallService(string commandArgs, string? displayName, bool delayedStart = false) { + Log.Information($"SystemdHelpers.IsSystemdService() {SystemdHelpers.IsSystemdService()}"); if (!SystemdHelpers.IsSystemdService()) { return -1; From 855b34973249864a6d0e0cac28d12142fe86ae58 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Fri, 12 Jan 2024 09:23:44 +0100 Subject: [PATCH 04/35] readd isSystemd --- .../ServiceInstallation/LinuxSystemD.cs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 066fca1c..13b8a399 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -17,7 +17,7 @@ public LinuxSystemD(string? serviceName, LauncherExecutablePath launcherExecutab public override async Task InstallService(string commandArgs, string? displayName, bool delayedStart = false) { Log.Information($"SystemdHelpers.IsSystemdService() {SystemdHelpers.IsSystemdService()}"); - if (!SystemdHelpers.IsSystemdService()) + if (!await IsSystemd()) { return -1; } @@ -34,7 +34,7 @@ public override async Task InstallService(string commandArgs, string? displ public override async Task UninstallService() { - if (!SystemdHelpers.IsSystemdService()) + if (!await IsSystemd()) { return -1; } @@ -71,5 +71,17 @@ private string[] GetServiceFileContent(string serviceDescription, string command "WantedBy = multi-user.target" }; } + + private static async Task IsSystemd() + { + var (exitCode, output) = await ProcessHelper.RunProcess("ps", new[] { "--no-headers", "-o", "comm", "1" }); + if (exitCode != 0 && output.Contains("systemd")) + { + Log.Error("Service installation works only for systemd setup."); + return false; + } + return true; + } + } } From 2e8b9438cb4e92cb21fa825876d6597f5004ed79 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Fri, 12 Jan 2024 09:47:16 +0100 Subject: [PATCH 05/35] exclude linux --- .../Extensions/DataProtectionExtensions.cs | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs b/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs index de0f389a..39f858a8 100644 --- a/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs @@ -200,16 +200,7 @@ public static IDataProtectionBuilder ProtectKeysCustom(this IDataProtectionBuild } else if (OperatingSystem.IsLinux()) { - try - { - Marshal.PrelinkAll(typeof(KeyUtils)); - builder.Services.Configure(options => options.XmlEncryptor = new KeyringXmlEncryptor()); - return builder; - } - catch (Exception e) - { - Log.Warning(e, "Fallback config encryption mechanism used."); - } + Log.Warning("Fallback config encryption mechanism is used on linux."); } else if (OperatingSystem.IsMacOS()) { From 14bf566f4ebd9b15e1d1ebcb5fea20aed23fc1ed Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Fri, 12 Jan 2024 09:52:26 +0100 Subject: [PATCH 06/35] .. --- src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 13b8a399..609eb1c0 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -16,7 +16,6 @@ public LinuxSystemD(string? serviceName, LauncherExecutablePath launcherExecutab public override async Task InstallService(string commandArgs, string? displayName, bool delayedStart = false) { - Log.Information($"SystemdHelpers.IsSystemdService() {SystemdHelpers.IsSystemdService()}"); if (!await IsSystemd()) { return -1; From 8b650f81a00d847eefb6df2c5ab74a2d50161749 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Fri, 12 Jan 2024 10:39:32 +0100 Subject: [PATCH 07/35] add Systemd Lifetime --- .../Commands/RunCommand.cs | 9 ---- .../Extensions/LifetimeExtensions.cs | 50 ++++++++++++++++++- 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/src/fiskaltrust.Launcher/Commands/RunCommand.cs b/src/fiskaltrust.Launcher/Commands/RunCommand.cs index 700344e8..f21385f6 100644 --- a/src/fiskaltrust.Launcher/Commands/RunCommand.cs +++ b/src/fiskaltrust.Launcher/Commands/RunCommand.cs @@ -1,5 +1,4 @@ using System.CommandLine; -using System.CommandLine.Invocation; using fiskaltrust.Launcher.ProcessHost; using fiskaltrust.Launcher.Services; using Serilog; @@ -8,12 +7,6 @@ using fiskaltrust.Launcher.Extensions; using fiskaltrust.Launcher.Helpers; using Microsoft.AspNetCore.Server.Kestrel.Core; -using fiskaltrust.Launcher.Common.Configuration; -using fiskaltrust.storage.serialization.V0; -using System.Security.Cryptography; -using Microsoft.AspNetCore.DataProtection; -using Microsoft.AspNetCore.Hosting.Server; -using Microsoft.AspNetCore.Hosting.Server.Features; namespace fiskaltrust.Launcher.Commands @@ -66,9 +59,7 @@ public static class RunHandler { public static async Task HandleAsync(CommonOptions commonOptions, CommonProperties commonProperties, RunOptions _, RunServices runServices) { - Log.Debug("RunHandler"); var builder = WebApplication.CreateBuilder(); - Log.Debug("WebApplication.CreateBuilde"); builder.Host .UseSerilog() diff --git a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs index 3d39a619..071706ff 100644 --- a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs @@ -32,8 +32,21 @@ public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder) else if (SystemdHelpers.IsSystemdService()) { builder.UseSystemd(); - builder.ConfigureServices(services => services.AddSingleton()); - return builder; + + return builder.ConfigureServices(services => + { + var lifetime = services.FirstOrDefault(s => s.ImplementationType == typeof(SystemdLifetime)); + + if (lifetime != null) + { + services.Remove(lifetime); + } + +#pragma warning disable CA1416 + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); +#pragma warning restore CA1416 + }); } else { @@ -140,4 +153,37 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } } + [SupportedOSPlatform("linux")] + public class CustomSystemDServiceLifetime : SystemdLifetime, ILifetime + { + private readonly CancellationTokenSource _starting = new(); + private readonly ManualResetEventSlim _started = new(); + + public IHostApplicationLifetime ApplicationLifetime { get; init; } + + public CustomSystemDServiceLifetime( + IHostEnvironment environment, + IHostApplicationLifetime applicationLifetime, + ILoggerFactory loggerFactory, + ISystemdNotifier systemdNotifier) + : base(environment, applicationLifetime, systemdNotifier, loggerFactory) + { + ApplicationLifetime = applicationLifetime; + } + + public void ServiceStartupCompleted() + { + ApplicationLifetime.ApplicationStarted.Register(() => _started.Set()); + } + + public new async Task WaitForStartAsync(CancellationToken cancellationToken) + { + try + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(_starting.Token, cancellationToken); + await base.WaitForStartAsync(cts.Token); + } + catch (OperationCanceledException) when (_starting.IsCancellationRequested) { } + } + } } \ No newline at end of file From 54b3ed38d295cea3756ace750f8ffd6c69a5045a Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Mon, 15 Jan 2024 07:44:49 +0100 Subject: [PATCH 08/35] check service installed --- .../ServiceInstallation/LinuxSystemD.cs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 609eb1c0..fb30b11f 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -18,6 +18,13 @@ public override async Task InstallService(string commandArgs, string? displ { if (!await IsSystemd()) { + Log.Error("No SystemD on this machine. No service installation possible."); + return -1; + } + + if(await IsSystemdServiceInstalled(_serviceName)) + { + Log.Error("Service is already installed and cannot be installed twice to one cashbox."); return -1; } Log.Information("Installing service via systemd."); @@ -35,8 +42,16 @@ public override async Task UninstallService() { if (!await IsSystemd()) { + Log.Error("No SystemD on this machine. No service uninstallation possible."); + return -1; + } + + if (!await IsSystemdServiceInstalled(_serviceName)) + { + Log.Error("Service is not installed!"); return -1; } + Log.Information("Stop service on systemd."); await ProcessHelper.RunProcess("systemctl", new[] { "stop ", _serviceName }); Log.Information("Disable service."); @@ -82,5 +97,14 @@ private static async Task IsSystemd() return true; } + private static async Task IsSystemdServiceInstalled(string serviceName) + { + var (exitCode, output) = await ProcessHelper.RunProcess("systemctl", new[] { $"list -unit-files", "--type service", $" | grep -F \"{serviceName}.service\"" }); + if (exitCode != 0 && !output.Contains("serviceName")) + { + return false; + } + return true; + } } } From ae2c75cc837a51724a321e0f8798b25428635e8d Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Mon, 15 Jan 2024 10:05:33 +0100 Subject: [PATCH 09/35] .. --- .../ServiceInstallation/LinuxSystemD.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index fb30b11f..e26d023e 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -1,6 +1,7 @@ using fiskaltrust.Launcher.Helpers; using Microsoft.Extensions.Hosting.Systemd; using Serilog; +using System.CommandLine; namespace fiskaltrust.Launcher.ServiceInstallation { @@ -89,6 +90,7 @@ private string[] GetServiceFileContent(string serviceDescription, string command private static async Task IsSystemd() { var (exitCode, output) = await ProcessHelper.RunProcess("ps", new[] { "--no-headers", "-o", "comm", "1" }); + if (exitCode != 0 && output.Contains("systemd")) { Log.Error("Service installation works only for systemd setup."); @@ -99,7 +101,9 @@ private static async Task IsSystemd() private static async Task IsSystemdServiceInstalled(string serviceName) { - var (exitCode, output) = await ProcessHelper.RunProcess("systemctl", new[] { $"list -unit-files", "--type service", $" | grep -F \"{serviceName}.service\"" }); + Log.Information($"systemctl list-unit-files --type service | grep -F \"{serviceName}.service\""); + var (exitCode, output) = await ProcessHelper.RunProcess("systemctl", new[] { $"systemctl list-unit-files --type service | grep -F \"{serviceName}.service\"" }); + Log.Information($"exitCode: {exitCode}, output: {output}"); if (exitCode != 0 && !output.Contains("serviceName")) { return false; From debee08320707d0cd6a45c5f97b3ae1cd24fe5de Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Mon, 15 Jan 2024 10:21:45 +0100 Subject: [PATCH 10/35] .. --- src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index e26d023e..7908f8dd 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -101,8 +101,7 @@ private static async Task IsSystemd() private static async Task IsSystemdServiceInstalled(string serviceName) { - Log.Information($"systemctl list-unit-files --type service | grep -F \"{serviceName}.service\""); - var (exitCode, output) = await ProcessHelper.RunProcess("systemctl", new[] { $"systemctl list-unit-files --type service | grep -F \"{serviceName}.service\"" }); + var (exitCode, output) = await ProcessHelper.RunProcess("systemctl", new[] { $"list-unit-files --type service | grep -F \"{serviceName}.service\"" }); Log.Information($"exitCode: {exitCode}, output: {output}"); if (exitCode != 0 && !output.Contains("serviceName")) { From ee47ce327b9f793feb62961f322bf8d63a851ff0 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Mon, 15 Jan 2024 10:57:25 +0100 Subject: [PATCH 11/35] .. --- src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 7908f8dd..a17b977b 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -101,7 +101,7 @@ private static async Task IsSystemd() private static async Task IsSystemdServiceInstalled(string serviceName) { - var (exitCode, output) = await ProcessHelper.RunProcess("systemctl", new[] { $"list-unit-files --type service | grep -F \"{serviceName}.service\"" }); + var (exitCode, output) = await ProcessHelper.RunProcess("/usr/bin/systemctl", new[] { $"list-unit-files --type service | grep -F \"{serviceName}.service\"" }); Log.Information($"exitCode: {exitCode}, output: {output}"); if (exitCode != 0 && !output.Contains("serviceName")) { From 38b5983edbc1fc08be8aab9a771574ebb5fccfd7 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Mon, 15 Jan 2024 11:32:34 +0100 Subject: [PATCH 12/35] .. --- src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index a17b977b..2e114725 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -101,7 +101,7 @@ private static async Task IsSystemd() private static async Task IsSystemdServiceInstalled(string serviceName) { - var (exitCode, output) = await ProcessHelper.RunProcess("/usr/bin/systemctl", new[] { $"list-unit-files --type service | grep -F \"{serviceName}.service\"" }); + var (exitCode, output) = await ProcessHelper.RunProcess("systemctl", new[] { $"status {serviceName}" }); Log.Information($"exitCode: {exitCode}, output: {output}"); if (exitCode != 0 && !output.Contains("serviceName")) { From cdcb9cd5f649c2882271fae4d5bb2ac7d9b68e73 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Mon, 15 Jan 2024 12:00:57 +0100 Subject: [PATCH 13/35] exit code --- src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 2e114725..6efc19ac 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -103,7 +103,7 @@ private static async Task IsSystemdServiceInstalled(string serviceName) { var (exitCode, output) = await ProcessHelper.RunProcess("systemctl", new[] { $"status {serviceName}" }); Log.Information($"exitCode: {exitCode}, output: {output}"); - if (exitCode != 0 && !output.Contains("serviceName")) + if (exitCode != 4) { return false; } From 93c30d0504e69c91be29ba61afc8b18e67f7f91e Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Mon, 15 Jan 2024 12:43:30 +0100 Subject: [PATCH 14/35] .. --- src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 6efc19ac..bf4e0042 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -103,7 +103,7 @@ private static async Task IsSystemdServiceInstalled(string serviceName) { var (exitCode, output) = await ProcessHelper.RunProcess("systemctl", new[] { $"status {serviceName}" }); Log.Information($"exitCode: {exitCode}, output: {output}"); - if (exitCode != 4) + if (exitCode == 4) { return false; } From 0d86c0d7247143ab010cce3fa55300d1104182f0 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Mon, 15 Jan 2024 13:09:36 +0100 Subject: [PATCH 15/35] .. --- src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index bf4e0042..511f7b8d 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -25,7 +25,7 @@ public override async Task InstallService(string commandArgs, string? displ if(await IsSystemdServiceInstalled(_serviceName)) { - Log.Error("Service is already installed and cannot be installed twice to one cashbox."); + Log.Error("Service is already installed and cannot be installed twice for one cashbox."); return -1; } Log.Information("Installing service via systemd."); From 9318b3695ae57838d596977d3353690233af8245 Mon Sep 17 00:00:00 2001 From: Paul Volavsek Date: Wed, 17 Jan 2024 14:01:48 +0100 Subject: [PATCH 16/35] tmp remove timeout --- src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 511f7b8d..e1b9fcc7 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -23,7 +23,7 @@ public override async Task InstallService(string commandArgs, string? displ return -1; } - if(await IsSystemdServiceInstalled(_serviceName)) + if (await IsSystemdServiceInstalled(_serviceName)) { Log.Error("Service is already installed and cannot be installed twice for one cashbox."); return -1; @@ -79,7 +79,6 @@ private string[] GetServiceFileContent(string serviceDescription, string command "[Service]", "Type=notify", $"ExecStart={command}", - "TimeoutSec=0", $"WorkingDirectory={Path.GetDirectoryName(_launcherExecutablePath.Path)}", "", "[Install]", @@ -108,6 +107,6 @@ private static async Task IsSystemdServiceInstalled(string serviceName) return false; } return true; - } + } } } From cee31dc98a226b591904cb57286e4a4de753b201 Mon Sep 17 00:00:00 2001 From: Paul Volavsek Date: Wed, 17 Jan 2024 14:52:15 +0100 Subject: [PATCH 17/35] Revert "tmp remove timeout" This reverts commit 9318b3695ae57838d596977d3353690233af8245. --- src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index e1b9fcc7..511f7b8d 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -23,7 +23,7 @@ public override async Task InstallService(string commandArgs, string? displ return -1; } - if (await IsSystemdServiceInstalled(_serviceName)) + if(await IsSystemdServiceInstalled(_serviceName)) { Log.Error("Service is already installed and cannot be installed twice for one cashbox."); return -1; @@ -79,6 +79,7 @@ private string[] GetServiceFileContent(string serviceDescription, string command "[Service]", "Type=notify", $"ExecStart={command}", + "TimeoutSec=0", $"WorkingDirectory={Path.GetDirectoryName(_launcherExecutablePath.Path)}", "", "[Install]", @@ -107,6 +108,6 @@ private static async Task IsSystemdServiceInstalled(string serviceName) return false; } return true; - } + } } } From 367bf8051e755e8fe8a53d771f002b4f364b123a Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Thu, 18 Jan 2024 06:21:41 +0100 Subject: [PATCH 18/35] set timoustartSeec --- src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 511f7b8d..26288f15 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -80,6 +80,7 @@ private string[] GetServiceFileContent(string serviceDescription, string command "Type=notify", $"ExecStart={command}", "TimeoutSec=0", + "TimeoutStartSec=infinit", $"WorkingDirectory={Path.GetDirectoryName(_launcherExecutablePath.Path)}", "", "[Install]", From bfd3a589e916b9556a3e64ae7a91e807fcc21b34 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Thu, 18 Jan 2024 06:56:17 +0100 Subject: [PATCH 19/35] .. --- src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 26288f15..511f7b8d 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -80,7 +80,6 @@ private string[] GetServiceFileContent(string serviceDescription, string command "Type=notify", $"ExecStart={command}", "TimeoutSec=0", - "TimeoutStartSec=infinit", $"WorkingDirectory={Path.GetDirectoryName(_launcherExecutablePath.Path)}", "", "[Install]", From 0dd17697e4431074279f64f7d0e81e3eae036771 Mon Sep 17 00:00:00 2001 From: Paul Volavsek Date: Mon, 22 Jan 2024 13:38:45 +0100 Subject: [PATCH 20/35] added logging of service type --- src/fiskaltrust.Launcher/Commands/Common.cs | 1 + .../Extensions/LifetimeExtensions.cs | 16 ++++++++++- .../ServiceInstallation/LinuxSystemD.cs | 28 +++++++++---------- 3 files changed, 30 insertions(+), 15 deletions(-) diff --git a/src/fiskaltrust.Launcher/Commands/Common.cs b/src/fiskaltrust.Launcher/Commands/Common.cs index 9dddcc0d..747307f5 100644 --- a/src/fiskaltrust.Launcher/Commands/Common.cs +++ b/src/fiskaltrust.Launcher/Commands/Common.cs @@ -224,6 +224,7 @@ public static async Task HandleAsync( Log.Debug("Cashbox Configuration File: {CashboxConfigurationFile}", launcherConfiguration.CashboxConfigurationFile); Log.Debug("Launcher Configuration: {@LauncherConfiguration}", launcherConfiguration.Redacted()); + Log.Debug("Launcher running as {ServiceType}", Enum.GetName(typeof(ServiceTypes), host.Services.GetRequiredService().Type)); var dataProtectionProvider = DataProtectionExtensions.Create(launcherConfiguration.AccessToken, useFallback: launcherConfiguration.UseLegacyDataProtection!.Value); diff --git a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs index 071706ff..29168b5e 100644 --- a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs @@ -6,6 +6,15 @@ namespace fiskaltrust.Launcher.Extensions { + public record ServiceType(ServiceTypes Type); + + public enum ServiceTypes + { + WindowsService, + SystemdService, + ConsoleApplication + } + static class LifetimeExtensions { public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder) @@ -16,6 +25,7 @@ public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder) return builder.ConfigureServices(services => { + services.AddSingleton(new ServiceType(ServiceTypes.WindowsService)); var lifetime = services.FirstOrDefault(s => s.ImplementationType == typeof(WindowsServiceLifetime)); if (lifetime != null) @@ -35,6 +45,7 @@ public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder) return builder.ConfigureServices(services => { + services.AddSingleton(new ServiceType(ServiceTypes.SystemdService)); var lifetime = services.FirstOrDefault(s => s.ImplementationType == typeof(SystemdLifetime)); if (lifetime != null) @@ -51,7 +62,10 @@ public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder) else { Console.OutputEncoding = Encoding.UTF8; - builder.ConfigureServices(services => services.AddSingleton()); + builder.ConfigureServices(services => services + .AddSingleton() + .AddSingleton(new ServiceType(ServiceTypes.ConsoleApplication))); + builder.UseConsoleLifetime(); return builder; } diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 511f7b8d..d37519d7 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -23,7 +23,7 @@ public override async Task InstallService(string commandArgs, string? displ return -1; } - if(await IsSystemdServiceInstalled(_serviceName)) + if (await IsSystemdServiceInstalled(_serviceName)) { Log.Error("Service is already installed and cannot be installed twice for one cashbox."); return -1; @@ -33,9 +33,9 @@ public override async Task InstallService(string commandArgs, string? displ var serviceFilePath = Path.Combine(_servicePath, $"{_serviceName}.service"); await File.AppendAllLinesAsync(serviceFilePath, serviceFileContent).ConfigureAwait(false); await ProcessHelper.RunProcess("systemctl", new[] { "daemon-reload" }); - Log.Information("Starting service."); + Log.Information("Starting systemd service."); await ProcessHelper.RunProcess("systemctl", new[] { "start", _serviceName }); - Log.Information("Enable service."); + Log.Information("Enabling systemd service."); return (await ProcessHelper.RunProcess("systemctl", new[] { "enable", _serviceName, "-q" })).exitCode; } @@ -53,17 +53,17 @@ public override async Task UninstallService() return -1; } - Log.Information("Stop service on systemd."); - await ProcessHelper.RunProcess("systemctl", new[] { "stop ", _serviceName }); - Log.Information("Disable service."); - await ProcessHelper.RunProcess("systemctl", new[] { "disable ", _serviceName, "-q" }); - Log.Information("Remove service."); + Log.Information("Stoppig systemd service."); + await ProcessHelper.RunProcess("systemctl", ["stop ", _serviceName]); + Log.Information("Disabling systemd service."); + await ProcessHelper.RunProcess("systemctl", ["disable ", _serviceName, "-q"]); + Log.Information("Removing systemd service."); var serviceFilePath = Path.Combine(_servicePath, $"{_serviceName}.service"); - await ProcessHelper.RunProcess("rm", new[] { serviceFilePath }); - Log.Information("Reload daemon."); - await ProcessHelper.RunProcess("systemctl", new[] { "daemon-reload" }); - Log.Information("Reset failed."); - return (await ProcessHelper.RunProcess("systemctl", new[] { "reset-failed" })).exitCode; + await ProcessHelper.RunProcess("rm", [serviceFilePath]); + Log.Information("Reloading systemd daemon."); + await ProcessHelper.RunProcess("systemctl", ["daemon-reload"]); + Log.Information("Reseting state for failed systemd units."); + return (await ProcessHelper.RunProcess("systemctl", ["reset-failed"])).exitCode; } private string[] GetServiceFileContent(string serviceDescription, string commandArgs) @@ -108,6 +108,6 @@ private static async Task IsSystemdServiceInstalled(string serviceName) return false; } return true; - } + } } } From 5080556a9325b40516d46d40a431d6fecab97ec4 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Tue, 23 Jan 2024 11:15:46 +0100 Subject: [PATCH 21/35] add customized systemdHelper --- .../Extensions/LifetimeExtensions.cs | 21 +++++++----------- .../Helpers/CustomSystemdHelper.cs | 22 +++++++++++++++++++ 2 files changed, 30 insertions(+), 13 deletions(-) create mode 100644 src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs diff --git a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs index 29168b5e..886598ea 100644 --- a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs @@ -1,5 +1,6 @@ using System.Runtime.Versioning; using System.Text; +using fiskaltrust.Launcher.Helpers; using Microsoft.Extensions.Hosting.Systemd; using Microsoft.Extensions.Hosting.WindowsServices; using Microsoft.Extensions.Options; @@ -39,24 +40,15 @@ public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder) #pragma warning restore CA1416 }); } - else if (SystemdHelpers.IsSystemdService()) + else if (CustomSystemdHelper.IsSystemdService()) { - builder.UseSystemd(); - return builder.ConfigureServices(services => { - services.AddSingleton(new ServiceType(ServiceTypes.SystemdService)); - var lifetime = services.FirstOrDefault(s => s.ImplementationType == typeof(SystemdLifetime)); - - if (lifetime != null) - { - services.Remove(lifetime); - } - + services.AddSingleton(); + #pragma warning disable CA1416 services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); -#pragma warning restore CA1416 }); } else @@ -174,6 +166,7 @@ public class CustomSystemDServiceLifetime : SystemdLifetime, ILifetime private readonly ManualResetEventSlim _started = new(); public IHostApplicationLifetime ApplicationLifetime { get; init; } + private readonly ISystemdNotifier _systemdNotifier; public CustomSystemDServiceLifetime( IHostEnvironment environment, @@ -183,11 +176,13 @@ public CustomSystemDServiceLifetime( : base(environment, applicationLifetime, systemdNotifier, loggerFactory) { ApplicationLifetime = applicationLifetime; + _systemdNotifier = systemdNotifier; } public void ServiceStartupCompleted() { - ApplicationLifetime.ApplicationStarted.Register(() => _started.Set()); + _systemdNotifier.Notify(ServiceState.Ready); + ApplicationLifetime.ApplicationStarted.Register(_started.Set); } public new async Task WaitForStartAsync(CancellationToken cancellationToken) diff --git a/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs b/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs new file mode 100644 index 00000000..b2af5f19 --- /dev/null +++ b/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs @@ -0,0 +1,22 @@ + +namespace fiskaltrust.Launcher.Helpers +{ + public class CustomSystemdHelper + { + private static bool? _isSystemdService; + + public static bool IsSystemdService() + => _isSystemdService ??= GetIsSystemdService(); + + private static bool GetIsSystemdService() + { + if (Environment.OSVersion.Platform != PlatformID.Unix) + { + return false; + } + + return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("NOTIFY_SOCKET")) || + !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("LISTEN_PID")); + } + } +} From cfea3c102d619d7779df0fccff98fc13abb7fbc5 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Tue, 23 Jan 2024 11:57:02 +0100 Subject: [PATCH 22/35] use custom lifetime in run --- src/fiskaltrust.Launcher/Commands/RunCommand.cs | 3 ++- src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs | 1 + src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 3 +-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/fiskaltrust.Launcher/Commands/RunCommand.cs b/src/fiskaltrust.Launcher/Commands/RunCommand.cs index f21385f6..b8a8101e 100644 --- a/src/fiskaltrust.Launcher/Commands/RunCommand.cs +++ b/src/fiskaltrust.Launcher/Commands/RunCommand.cs @@ -7,6 +7,7 @@ using fiskaltrust.Launcher.Extensions; using fiskaltrust.Launcher.Helpers; using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Hosting; namespace fiskaltrust.Launcher.Commands @@ -62,8 +63,8 @@ public static async Task HandleAsync(CommonOptions commonOptions, CommonPro var builder = WebApplication.CreateBuilder(); builder.Host + .UseCustomHostLifetime() .UseSerilog() - .UseSystemd() .ConfigureServices((_, services) => { services.Configure(opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(30)); diff --git a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs index 886598ea..716259a7 100644 --- a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs @@ -49,6 +49,7 @@ public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder) #pragma warning disable CA1416 services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); +#pragma warning restore CA1416 }); } else diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index d37519d7..be868c36 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -101,8 +101,7 @@ private static async Task IsSystemd() private static async Task IsSystemdServiceInstalled(string serviceName) { - var (exitCode, output) = await ProcessHelper.RunProcess("systemctl", new[] { $"status {serviceName}" }); - Log.Information($"exitCode: {exitCode}, output: {output}"); + var (exitCode, _) = await ProcessHelper.RunProcess("systemctl", new[] { $"status {serviceName}" }); if (exitCode == 4) { return false; From db831be4b1294e1fc063a8a08b60f89df70aefe6 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Tue, 23 Jan 2024 12:41:09 +0100 Subject: [PATCH 23/35] .. --- src/fiskaltrust.Launcher/Commands/RunCommand.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/Commands/RunCommand.cs b/src/fiskaltrust.Launcher/Commands/RunCommand.cs index b8a8101e..308350c0 100644 --- a/src/fiskaltrust.Launcher/Commands/RunCommand.cs +++ b/src/fiskaltrust.Launcher/Commands/RunCommand.cs @@ -63,7 +63,6 @@ public static async Task HandleAsync(CommonOptions commonOptions, CommonPro var builder = WebApplication.CreateBuilder(); builder.Host - .UseCustomHostLifetime() .UseSerilog() .ConfigureServices((_, services) => { From 37448edf31577ce8188b6bd7a483793eb51ba318 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Wed, 24 Jan 2024 06:59:22 +0100 Subject: [PATCH 24/35] test --- .../Extensions/LifetimeExtensions.cs | 4 ++-- .../Helpers/CustomSystemdHelper.cs | 16 ++++++++++------ src/fiskaltrust.Launcher/Program.cs | 2 +- .../ServiceInstallation/LinuxSystemD.cs | 2 +- 4 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs index 716259a7..b43a6453 100644 --- a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs @@ -18,7 +18,7 @@ public enum ServiceTypes static class LifetimeExtensions { - public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder) + public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder, string[] args) { if (WindowsServiceHelpers.IsWindowsService()) { @@ -40,7 +40,7 @@ public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder) #pragma warning restore CA1416 }); } - else if (CustomSystemdHelper.IsSystemdService()) + else if (CustomSystemdHelper.IsSystemdService(args)) { return builder.ConfigureServices(services => { diff --git a/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs b/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs index b2af5f19..56abe07a 100644 --- a/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs +++ b/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs @@ -1,22 +1,26 @@  +using fiskaltrust.Launcher.ServiceInstallation; + namespace fiskaltrust.Launcher.Helpers { public class CustomSystemdHelper { private static bool? _isSystemdService; - public static bool IsSystemdService() - => _isSystemdService ??= GetIsSystemdService(); + public static bool IsSystemdService(string[] args) + => _isSystemdService ??= GetIsSystemdServiceAsync(args); - private static bool GetIsSystemdService() + private static bool GetIsSystemdServiceAsync(string[] args) { if (Environment.OSVersion.Platform != PlatformID.Unix) { return false; } - - return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("NOTIFY_SOCKET")) || - !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("LISTEN_PID")); + if (args[0] == "install") + { + return true; + } + return args.Contains("isSystemd"); } } } diff --git a/src/fiskaltrust.Launcher/Program.cs b/src/fiskaltrust.Launcher/Program.cs index 7efbafff..87009bad 100644 --- a/src/fiskaltrust.Launcher/Program.cs +++ b/src/fiskaltrust.Launcher/Program.cs @@ -49,7 +49,7 @@ .UseHost( host => { - host.UseCustomHostLifetime(); + host.UseCustomHostLifetime(args); host.ConfigureServices(services => services .Configure(opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(45)) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index be868c36..e50c4b23 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -70,7 +70,7 @@ private string[] GetServiceFileContent(string serviceDescription, string command { var processPath = _launcherExecutablePath.Path; - var command = $"sudo {processPath} {commandArgs}"; + var command = $"sudo {processPath} {commandArgs} isSystemd"; return new[] { "[Unit]", From aed63b519096262f95a10d176138b0d393800ad9 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Wed, 24 Jan 2024 07:19:45 +0100 Subject: [PATCH 25/35] add Servicetype --- src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs index b43a6453..48e61707 100644 --- a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs @@ -44,6 +44,7 @@ public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder, stri { return builder.ConfigureServices(services => { + services.AddSingleton(new ServiceType(ServiceTypes.SystemdService)); services.AddSingleton(); #pragma warning disable CA1416 From 2657ae85b1e39284c1cf1d853ad4ab175c59ffad Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Wed, 24 Jan 2024 07:54:52 +0100 Subject: [PATCH 26/35] .. --- src/fiskaltrust.Launcher/Commands/RunCommand.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/fiskaltrust.Launcher/Commands/RunCommand.cs b/src/fiskaltrust.Launcher/Commands/RunCommand.cs index 308350c0..eba47fe2 100644 --- a/src/fiskaltrust.Launcher/Commands/RunCommand.cs +++ b/src/fiskaltrust.Launcher/Commands/RunCommand.cs @@ -63,6 +63,7 @@ public static async Task HandleAsync(CommonOptions commonOptions, CommonPro var builder = WebApplication.CreateBuilder(); builder.Host + .UseSystemd() .UseSerilog() .ConfigureServices((_, services) => { From 713ec489bcd4ef9654bd756c5014865d65c1b47b Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Wed, 24 Jan 2024 07:58:06 +0100 Subject: [PATCH 27/35] .. --- src/fiskaltrust.Launcher/Commands/RunCommand.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/Commands/RunCommand.cs b/src/fiskaltrust.Launcher/Commands/RunCommand.cs index eba47fe2..78a9917d 100644 --- a/src/fiskaltrust.Launcher/Commands/RunCommand.cs +++ b/src/fiskaltrust.Launcher/Commands/RunCommand.cs @@ -8,6 +8,7 @@ using fiskaltrust.Launcher.Helpers; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Hosting.Systemd; namespace fiskaltrust.Launcher.Commands @@ -63,10 +64,10 @@ public static async Task HandleAsync(CommonOptions commonOptions, CommonPro var builder = WebApplication.CreateBuilder(); builder.Host - .UseSystemd() .UseSerilog() .ConfigureServices((_, services) => { + services.AddSingleton(); services.Configure(opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(30)); services.AddSingleton(_ => commonProperties.LauncherConfiguration); services.AddSingleton(_ => runServices.Lifetime); From 07479e3283ac71b75efcfc0d3ac417839e6ba51d Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Wed, 24 Jan 2024 09:36:39 +0100 Subject: [PATCH 28/35] .. --- src/fiskaltrust.Launcher/Commands/RunCommand.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/Commands/RunCommand.cs b/src/fiskaltrust.Launcher/Commands/RunCommand.cs index 78a9917d..4879d609 100644 --- a/src/fiskaltrust.Launcher/Commands/RunCommand.cs +++ b/src/fiskaltrust.Launcher/Commands/RunCommand.cs @@ -67,7 +67,6 @@ public static async Task HandleAsync(CommonOptions commonOptions, CommonPro .UseSerilog() .ConfigureServices((_, services) => { - services.AddSingleton(); services.Configure(opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(30)); services.AddSingleton(_ => commonProperties.LauncherConfiguration); services.AddSingleton(_ => runServices.Lifetime); From c1f49b87fb1048011226be372c400d7c6ad9eb49 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Wed, 24 Jan 2024 09:39:25 +0100 Subject: [PATCH 29/35] .. --- src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index e50c4b23..98ef8661 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -79,7 +79,7 @@ private string[] GetServiceFileContent(string serviceDescription, string command "[Service]", "Type=notify", $"ExecStart={command}", - "TimeoutSec=0", + // "TimeoutSec=0", $"WorkingDirectory={Path.GetDirectoryName(_launcherExecutablePath.Path)}", "", "[Install]", From 2297e11e780351feaf5544cba97bf31a88745400 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Wed, 24 Jan 2024 09:45:37 +0100 Subject: [PATCH 30/35] .. --- src/fiskaltrust.Launcher/Commands/RunCommand.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/fiskaltrust.Launcher/Commands/RunCommand.cs b/src/fiskaltrust.Launcher/Commands/RunCommand.cs index 4879d609..4b5051df 100644 --- a/src/fiskaltrust.Launcher/Commands/RunCommand.cs +++ b/src/fiskaltrust.Launcher/Commands/RunCommand.cs @@ -70,6 +70,7 @@ public static async Task HandleAsync(CommonOptions commonOptions, CommonPro services.Configure(opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(30)); services.AddSingleton(_ => commonProperties.LauncherConfiguration); services.AddSingleton(_ => runServices.Lifetime); + services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(_ => commonProperties.CashboxConfiguration); services.AddSingleton(_ => new Dictionary()); services.AddSingleton(); From 39cdd64df7dabf111f1b79a37b0f80b2b6e82c56 Mon Sep 17 00:00:00 2001 From: forsthug <85173816+forsthug@users.noreply.github.com> Date: Wed, 24 Jan 2024 10:00:52 +0100 Subject: [PATCH 31/35] .. --- src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs b/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs index 56abe07a..c1464962 100644 --- a/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs +++ b/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs @@ -16,10 +16,6 @@ private static bool GetIsSystemdServiceAsync(string[] args) { return false; } - if (args[0] == "install") - { - return true; - } return args.Contains("isSystemd"); } } From 928f23f86c2322cf623480a9f63ed3fc72a25953 Mon Sep 17 00:00:00 2001 From: Paul Volavsek Date: Wed, 24 Jan 2024 11:10:10 +0100 Subject: [PATCH 32/35] log env var --- src/fiskaltrust.Launcher/Commands/Common.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/fiskaltrust.Launcher/Commands/Common.cs b/src/fiskaltrust.Launcher/Commands/Common.cs index 747307f5..3d4ce035 100644 --- a/src/fiskaltrust.Launcher/Commands/Common.cs +++ b/src/fiskaltrust.Launcher/Commands/Common.cs @@ -225,6 +225,7 @@ public static async Task HandleAsync( Log.Debug("Launcher Configuration: {@LauncherConfiguration}", launcherConfiguration.Redacted()); Log.Debug("Launcher running as {ServiceType}", Enum.GetName(typeof(ServiceTypes), host.Services.GetRequiredService().Type)); + Log.Warning("NOTIFY_SOCKET envvar {nn}", Environment.GetEnvironmentVariable("NOTIFY_SOCKET")); var dataProtectionProvider = DataProtectionExtensions.Create(launcherConfiguration.AccessToken, useFallback: launcherConfiguration.UseLegacyDataProtection!.Value); From 44fd1865686e43fd1ca5a4ab2ddb2c1bfb275b80 Mon Sep 17 00:00:00 2001 From: Paul Volavsek Date: Wed, 24 Jan 2024 15:01:58 +0100 Subject: [PATCH 33/35] fix systemd spawning --- .../fiskaltrust.Launcher.Common.csproj | 8 +- src/fiskaltrust.Launcher/Commands/Common.cs | 26 ++++-- .../Commands/HostCommand.cs | 5 +- .../Commands/RunCommand.cs | 3 - .../Extensions/LifetimeExtensions.cs | 92 +++++++++++++------ .../Helpers/CustomSystemdHelper.cs | 22 ----- .../Helpers/ProcessHelper.cs | 8 +- .../ProcessHost/ProcessHostMonarch.cs | 14 +-- src/fiskaltrust.Launcher/Program.cs | 6 +- .../ServiceInstallation/LinuxSystemD.cs | 31 +++---- .../fiskaltrust.Launcher.csproj | 21 +++-- ...iskaltrust.Launcher.IntegrationTest.csproj | 20 ++-- .../fiskaltrust.Launcher.UnitTest.csproj | 20 ++-- 13 files changed, 150 insertions(+), 126 deletions(-) delete mode 100644 src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs diff --git a/src/fiskaltrust.Launcher.Common/fiskaltrust.Launcher.Common.csproj b/src/fiskaltrust.Launcher.Common/fiskaltrust.Launcher.Common.csproj index 7a3316a6..0645ad06 100644 --- a/src/fiskaltrust.Launcher.Common/fiskaltrust.Launcher.Common.csproj +++ b/src/fiskaltrust.Launcher.Common/fiskaltrust.Launcher.Common.csproj @@ -7,11 +7,11 @@ - - + + - + - + \ No newline at end of file diff --git a/src/fiskaltrust.Launcher/Commands/Common.cs b/src/fiskaltrust.Launcher/Commands/Common.cs index 3d4ce035..ef2f7a8f 100644 --- a/src/fiskaltrust.Launcher/Commands/Common.cs +++ b/src/fiskaltrust.Launcher/Commands/Common.cs @@ -158,11 +158,22 @@ public static async Task HandleAsync( try { clientEcdh = await LoadCurve(launcherConfiguration.CashboxId!.Value, launcherConfiguration.AccessToken!, launcherConfiguration.ServiceFolder!, launcherConfiguration.UseOffline!.Value); - using var downloader = new ConfigurationDownloader(launcherConfiguration); - var exists = await downloader.DownloadConfigurationAsync(clientEcdh); - if (launcherConfiguration.UseOffline!.Value && !exists) + } + catch (Exception e) + { + Log.Fatal(e, "Could not load client curve."); + } + + try + { + if (clientEcdh is not null) { - Log.Warning("Cashbox configuration was not downloaded because UseOffline is set."); + using var downloader = new ConfigurationDownloader(launcherConfiguration); + var exists = await downloader.DownloadConfigurationAsync(clientEcdh); + if (launcherConfiguration.UseOffline!.Value && !exists) + { + Log.Warning("Cashbox configuration was not downloaded because UseOffline is set."); + } } } catch (Exception e) @@ -192,7 +203,7 @@ public static async Task HandleAsync( try { cashboxConfiguration = CashBoxConfigurationExt.Deserialize(await File.ReadAllTextAsync(launcherConfiguration.CashboxConfigurationFile!)); - cashboxConfiguration.Decrypt(launcherConfiguration, clientEcdh); + if (clientEcdh is not null) { cashboxConfiguration.Decrypt(launcherConfiguration, clientEcdh); } } catch (Exception e) { @@ -225,7 +236,6 @@ public static async Task HandleAsync( Log.Debug("Launcher Configuration: {@LauncherConfiguration}", launcherConfiguration.Redacted()); Log.Debug("Launcher running as {ServiceType}", Enum.GetName(typeof(ServiceTypes), host.Services.GetRequiredService().Type)); - Log.Warning("NOTIFY_SOCKET envvar {nn}", Environment.GetEnvironmentVariable("NOTIFY_SOCKET")); var dataProtectionProvider = DataProtectionExtensions.Create(launcherConfiguration.AccessToken, useFallback: launcherConfiguration.UseLegacyDataProtection!.Value); @@ -238,12 +248,12 @@ public static async Task HandleAsync( Log.Warning(e, "Error decrypring launcher configuration file."); } - return await handler(options, new CommonProperties(launcherConfiguration, cashboxConfiguration, clientEcdh, dataProtectionProvider), specificOptions, host.Services.GetRequiredService()); + return await handler(options, new CommonProperties(launcherConfiguration, cashboxConfiguration, clientEcdh!, dataProtectionProvider), specificOptions, host.Services.GetRequiredService()); } private static async Task EnsureServiceDirectoryExists(LauncherConfiguration config) { - var serviceDirectory = config.ServiceFolder; + var serviceDirectory = config.ServiceFolder!; try { if (!Directory.Exists(serviceDirectory)) diff --git a/src/fiskaltrust.Launcher/Commands/HostCommand.cs b/src/fiskaltrust.Launcher/Commands/HostCommand.cs index 9b7111d1..26975e59 100644 --- a/src/fiskaltrust.Launcher/Commands/HostCommand.cs +++ b/src/fiskaltrust.Launcher/Commands/HostCommand.cs @@ -75,9 +75,9 @@ public static async Task HandleAsync(HostOptions hostOptions, HostServices } } - var launcherConfiguration = Common.Configuration.LauncherConfiguration.Deserialize(System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(hostOptions.LauncherConfiguration))); + var launcherConfiguration = LauncherConfiguration.Deserialize(System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(hostOptions.LauncherConfiguration))); - var plebeianConfiguration = Configuration.PlebeianConfiguration.Deserialize(System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(hostOptions.PlebeianConfiguration))); + var plebeianConfiguration = PlebeianConfiguration.Deserialize(System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(hostOptions.PlebeianConfiguration))); var cashboxConfiguration = CashBoxConfigurationExt.Deserialize(await File.ReadAllTextAsync(launcherConfiguration.CashboxConfigurationFile!)); @@ -108,7 +108,6 @@ public static async Task HandleAsync(HostOptions hostOptions, HostServices var builder = Host.CreateDefaultBuilder() .UseSerilog() - .UseSystemd() .ConfigureServices(services => { services.Configure(opts => diff --git a/src/fiskaltrust.Launcher/Commands/RunCommand.cs b/src/fiskaltrust.Launcher/Commands/RunCommand.cs index 4b5051df..022806de 100644 --- a/src/fiskaltrust.Launcher/Commands/RunCommand.cs +++ b/src/fiskaltrust.Launcher/Commands/RunCommand.cs @@ -7,8 +7,6 @@ using fiskaltrust.Launcher.Extensions; using fiskaltrust.Launcher.Helpers; using Microsoft.AspNetCore.Server.Kestrel.Core; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Hosting.Systemd; namespace fiskaltrust.Launcher.Commands @@ -70,7 +68,6 @@ public static async Task HandleAsync(CommonOptions commonOptions, CommonPro services.Configure(opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(30)); services.AddSingleton(_ => commonProperties.LauncherConfiguration); services.AddSingleton(_ => runServices.Lifetime); - services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(_ => commonProperties.CashboxConfiguration); services.AddSingleton(_ => new Dictionary()); services.AddSingleton(); diff --git a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs index 48e61707..4365a23f 100644 --- a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs @@ -1,6 +1,7 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; -using fiskaltrust.Launcher.Helpers; using Microsoft.Extensions.Hosting.Systemd; using Microsoft.Extensions.Hosting.WindowsServices; using Microsoft.Extensions.Options; @@ -18,7 +19,7 @@ public enum ServiceTypes static class LifetimeExtensions { - public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder, string[] args) + public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder) { if (WindowsServiceHelpers.IsWindowsService()) { @@ -40,17 +41,21 @@ public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder, stri #pragma warning restore CA1416 }); } - else if (CustomSystemdHelper.IsSystemdService(args)) + else if (SystemdHelpers.IsSystemdService()) { + builder.UseSystemd(); + return builder.ConfigureServices(services => { - services.AddSingleton(new ServiceType(ServiceTypes.SystemdService)); - services.AddSingleton(); - -#pragma warning disable CA1416 - services.AddSingleton(); - services.AddSingleton(sp => sp.GetRequiredService()); -#pragma warning restore CA1416 + services + .AddSingleton(new ServiceType(ServiceTypes.SystemdService)) + .AddSingleton() + .AddSingleton(); + +// #pragma warning disable CA1416 +// services.AddSingleton(); +// services.AddSingleton(sp => sp.GetRequiredService()); +// #pragma warning restore CA1416 }); } else @@ -124,7 +129,7 @@ public CustomWindowsServiceLifetime( public void ServiceStartupCompleted() { - ApplicationLifetime.ApplicationStarted.Register(() => _started.Set()); + ApplicationLifetime.ApplicationStarted.Register(_started.Set); } public new async Task WaitForStartAsync(CancellationToken cancellationToken) @@ -161,40 +166,71 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } } + [SupportedOSPlatform("linux")] - public class CustomSystemDServiceLifetime : SystemdLifetime, ILifetime + public class CustomSystemDServiceLifetime : ILifetime, IHostLifetime, IDisposable { - private readonly CancellationTokenSource _starting = new(); - private readonly ManualResetEventSlim _started = new(); - - public IHostApplicationLifetime ApplicationLifetime { get; init; } + private readonly CancellationTokenSource _started = new(); private readonly ISystemdNotifier _systemdNotifier; + public IHostApplicationLifetime ApplicationLifetime { get; init; } + + private CancellationTokenRegistration _applicationStartedRegistration; + private CancellationTokenRegistration _applicationStoppingRegistration; + private PosixSignalRegistration? _sigTermRegistration; public CustomSystemDServiceLifetime( - IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, - ILoggerFactory loggerFactory, ISystemdNotifier systemdNotifier) - : base(environment, applicationLifetime, systemdNotifier, loggerFactory) { ApplicationLifetime = applicationLifetime; _systemdNotifier = systemdNotifier; } - public void ServiceStartupCompleted() + public void ServiceStartupCompleted() => _started.Cancel(); + + public Task WaitForStartAsync(CancellationToken cancellationToken) { - _systemdNotifier.Notify(ServiceState.Ready); - ApplicationLifetime.ApplicationStarted.Register(_started.Set); + _applicationStartedRegistration = ApplicationLifetime.ApplicationStarted.Register(OnApplicationStarted); + _applicationStoppingRegistration = ApplicationLifetime.ApplicationStopping.Register(OnApplicationStopping); + + RegisterShutdownHandlers(); + + return Task.CompletedTask; } - public new async Task WaitForStartAsync(CancellationToken cancellationToken) + private void OnApplicationStarted() { - try + var cts = CancellationTokenSource.CreateLinkedTokenSource(_started.Token, ApplicationLifetime.ApplicationStopping); + + cts.Token.Register(() => { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(_starting.Token, cancellationToken); - await base.WaitForStartAsync(cts.Token); - } - catch (OperationCanceledException) when (_starting.IsCancellationRequested) { } + _systemdNotifier.Notify(ServiceState.Stopping); + }); + } + + private void OnApplicationStopping() => _systemdNotifier.Notify(ServiceState.Stopping); + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + private void RegisterShutdownHandlers() => _sigTermRegistration = PosixSignalRegistration.Create(PosixSignal.SIGTERM, HandlePosixSignal); + + private void HandlePosixSignal(PosixSignalContext context) + { + Debug.Assert(context.Signal == PosixSignal.SIGTERM); + + context.Cancel = true; + ApplicationLifetime.StopApplication(); + } + + private void UnregisterShutdownHandlers() => _sigTermRegistration?.Dispose(); + + public void Dispose() + { + _started.Cancel(); + + UnregisterShutdownHandlers(); + _applicationStartedRegistration.Dispose(); + _applicationStoppingRegistration.Dispose(); } } } \ No newline at end of file diff --git a/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs b/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs deleted file mode 100644 index c1464962..00000000 --- a/src/fiskaltrust.Launcher/Helpers/CustomSystemdHelper.cs +++ /dev/null @@ -1,22 +0,0 @@ - -using fiskaltrust.Launcher.ServiceInstallation; - -namespace fiskaltrust.Launcher.Helpers -{ - public class CustomSystemdHelper - { - private static bool? _isSystemdService; - - public static bool IsSystemdService(string[] args) - => _isSystemdService ??= GetIsSystemdServiceAsync(args); - - private static bool GetIsSystemdServiceAsync(string[] args) - { - if (Environment.OSVersion.Platform != PlatformID.Unix) - { - return false; - } - return args.Contains("isSystemd"); - } - } -} diff --git a/src/fiskaltrust.Launcher/Helpers/ProcessHelper.cs b/src/fiskaltrust.Launcher/Helpers/ProcessHelper.cs index 1e1cb9c3..4fbeef36 100644 --- a/src/fiskaltrust.Launcher/Helpers/ProcessHelper.cs +++ b/src/fiskaltrust.Launcher/Helpers/ProcessHelper.cs @@ -7,9 +7,9 @@ namespace fiskaltrust.Launcher.Helpers; public static class ProcessHelper { public static async Task<(int exitCode, string output)> RunProcess( - string fileName, - IEnumerable arguments, - LogEventLevel logLevel = LogEventLevel.Information) + string fileName, + IEnumerable arguments, + LogEventLevel? logLevel = LogEventLevel.Information) { var process = new Process { @@ -30,7 +30,7 @@ public static class ProcessHelper var stdOut = await process.StandardOutput.ReadToEndAsync(); if (!string.IsNullOrEmpty(stdOut)) { - Log.Write(logLevel, stdOut); + if (logLevel is not null) { Log.Write(logLevel.Value, stdOut); } } var stdErr = await process.StandardError.ReadToEndAsync(); diff --git a/src/fiskaltrust.Launcher/ProcessHost/ProcessHostMonarch.cs b/src/fiskaltrust.Launcher/ProcessHost/ProcessHostMonarch.cs index e1c0768a..64f521a0 100644 --- a/src/fiskaltrust.Launcher/ProcessHost/ProcessHostMonarch.cs +++ b/src/fiskaltrust.Launcher/ProcessHost/ProcessHostMonarch.cs @@ -45,11 +45,6 @@ public ProcessHostMonarch(ILogger logger, LauncherConfigurat _stopped = new TaskCompletionSource(); _started = new TaskCompletionSource(); - - // if (Debugger.IsAttached) - // { - // _process.StartInfo.Arguments += " --debugging"; - // } } private void Setup() @@ -61,11 +56,11 @@ private void Setup() UseShellExecute = false, FileName = _launcherExecutablePath.Path, CreateNoWindow = false, - Arguments = string.Join(" ", new string[] { + Arguments = string.Join(" ", [ "host", "--plebeian-configuration", $"\"{Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(new PlebeianConfiguration { PackageType = _packageType, PackageId = _packageConfiguration.Id }.Serialize()))}\"", "--launcher-configuration", $"\"{Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(_launcherConfiguration.Serialize()))}\"", - }), + ]), RedirectStandardInput = true, RedirectStandardError = true, RedirectStandardOutput = true @@ -75,6 +70,11 @@ private void Setup() _process.OutputDataReceived += ReceiveStdOut; _process.ErrorDataReceived += ReceiveStdOut; + + // if (Debugger.IsAttached && _packageType == PackageType.Helper) + // { + // _process.StartInfo.Arguments += " --debugging"; + // } } private void ReceiveStdOut(object sender, DataReceivedEventArgs e) diff --git a/src/fiskaltrust.Launcher/Program.cs b/src/fiskaltrust.Launcher/Program.cs index 87009bad..35141f1a 100644 --- a/src/fiskaltrust.Launcher/Program.cs +++ b/src/fiskaltrust.Launcher/Program.cs @@ -6,8 +6,6 @@ using fiskaltrust.Launcher.Extensions; using fiskaltrust.Launcher.Helpers; using System.CommandLine.NamingConventionBinder; -using fiskaltrust.Launcher.Common.Configuration; -using fiskaltrust.Launcher.Common.Constants; var runCommand = new RunCommand() { @@ -39,7 +37,7 @@ if (!args.Any()) { - args = new[] { runCommand.Name }; + args = [runCommand.Name]; } var subArguments = new SubArguments(args.SkipWhile(a => a != "--").Skip(1)); @@ -49,7 +47,7 @@ .UseHost( host => { - host.UseCustomHostLifetime(args); + host.UseCustomHostLifetime(); host.ConfigureServices(services => services .Configure(opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(45)) diff --git a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs index 98ef8661..50ba5fb4 100644 --- a/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs +++ b/src/fiskaltrust.Launcher/ServiceInstallation/LinuxSystemD.cs @@ -1,7 +1,5 @@ using fiskaltrust.Launcher.Helpers; -using Microsoft.Extensions.Hosting.Systemd; using Serilog; -using System.CommandLine; namespace fiskaltrust.Launcher.ServiceInstallation { @@ -17,9 +15,9 @@ public LinuxSystemD(string? serviceName, LauncherExecutablePath launcherExecutab public override async Task InstallService(string commandArgs, string? displayName, bool delayedStart = false) { - if (!await IsSystemd()) + if (!await IdSystemdAvailable()) { - Log.Error("No SystemD on this machine. No service installation possible."); + Log.Error("Systemd is not running on this machine. No service installation is possible."); return -1; } @@ -32,18 +30,18 @@ public override async Task InstallService(string commandArgs, string? displ var serviceFileContent = GetServiceFileContent(displayName ?? "Service installation of fiskaltrust launcher.", commandArgs); var serviceFilePath = Path.Combine(_servicePath, $"{_serviceName}.service"); await File.AppendAllLinesAsync(serviceFilePath, serviceFileContent).ConfigureAwait(false); - await ProcessHelper.RunProcess("systemctl", new[] { "daemon-reload" }); + await ProcessHelper.RunProcess("systemctl", ["daemon-reload"]); Log.Information("Starting systemd service."); - await ProcessHelper.RunProcess("systemctl", new[] { "start", _serviceName }); + await ProcessHelper.RunProcess("systemctl", ["start", _serviceName]); Log.Information("Enabling systemd service."); - return (await ProcessHelper.RunProcess("systemctl", new[] { "enable", _serviceName, "-q" })).exitCode; + return (await ProcessHelper.RunProcess("systemctl", ["enable", _serviceName, "-q"])).exitCode; } public override async Task UninstallService() { - if (!await IsSystemd()) + if (!await IdSystemdAvailable()) { - Log.Error("No SystemD on this machine. No service uninstallation possible."); + Log.Error("Systemd is not running on this machine. No service uninstallation is possible."); return -1; } @@ -70,26 +68,25 @@ private string[] GetServiceFileContent(string serviceDescription, string command { var processPath = _launcherExecutablePath.Path; - var command = $"sudo {processPath} {commandArgs} isSystemd"; - return new[] - { + var command = $"{processPath} {commandArgs}"; + + return [ "[Unit]", $"Description=\"{serviceDescription}\"", "", "[Service]", "Type=notify", $"ExecStart={command}", - // "TimeoutSec=0", $"WorkingDirectory={Path.GetDirectoryName(_launcherExecutablePath.Path)}", "", "[Install]", "WantedBy = multi-user.target" - }; + ]; } - private static async Task IsSystemd() + private static async Task IdSystemdAvailable() { - var (exitCode, output) = await ProcessHelper.RunProcess("ps", new[] { "--no-headers", "-o", "comm", "1" }); + var (exitCode, output) = await ProcessHelper.RunProcess("ps", ["--no-headers", "-o", "comm", "1"], logLevel: null); if (exitCode != 0 && output.Contains("systemd")) { @@ -101,7 +98,7 @@ private static async Task IsSystemd() private static async Task IsSystemdServiceInstalled(string serviceName) { - var (exitCode, _) = await ProcessHelper.RunProcess("systemctl", new[] { $"status {serviceName}" }); + var (exitCode, _) = await ProcessHelper.RunProcess("systemctl", [$"status {serviceName}"], logLevel: null); if (exitCode == 4) { return false; diff --git a/src/fiskaltrust.Launcher/fiskaltrust.Launcher.csproj b/src/fiskaltrust.Launcher/fiskaltrust.Launcher.csproj index c3b11f08..8deb18d9 100644 --- a/src/fiskaltrust.Launcher/fiskaltrust.Launcher.csproj +++ b/src/fiskaltrust.Launcher/fiskaltrust.Launcher.csproj @@ -9,12 +9,12 @@ - $(DefineConstants);EnableSelfUpdate + $(DefineConstants);EnableSelfUpdate - - + + @@ -23,11 +23,11 @@ - + - - - + + + @@ -35,10 +35,11 @@ - + - + - + \ No newline at end of file diff --git a/test/fiskaltrust.Launcher.IntegrationTest/fiskaltrust.Launcher.IntegrationTest.csproj b/test/fiskaltrust.Launcher.IntegrationTest/fiskaltrust.Launcher.IntegrationTest.csproj index 05cae015..48d35d7c 100644 --- a/test/fiskaltrust.Launcher.IntegrationTest/fiskaltrust.Launcher.IntegrationTest.csproj +++ b/test/fiskaltrust.Launcher.IntegrationTest/fiskaltrust.Launcher.IntegrationTest.csproj @@ -10,10 +10,10 @@ - - - - + + + + runtime; build; native; contentfiles; analyzers; buildtransitive all @@ -25,15 +25,19 @@ - + - + - + - + \ No newline at end of file diff --git a/test/fiskaltrust.Launcher.UnitTest/fiskaltrust.Launcher.UnitTest.csproj b/test/fiskaltrust.Launcher.UnitTest/fiskaltrust.Launcher.UnitTest.csproj index 8eacef9e..8f1987a0 100644 --- a/test/fiskaltrust.Launcher.UnitTest/fiskaltrust.Launcher.UnitTest.csproj +++ b/test/fiskaltrust.Launcher.UnitTest/fiskaltrust.Launcher.UnitTest.csproj @@ -11,10 +11,10 @@ - - - - + + + + runtime; build; native; contentfiles; analyzers; buildtransitive all @@ -25,15 +25,19 @@ - + - + - + - + \ No newline at end of file From 0abf2c3fc304bdd1e34ed4fc09cfc26073200114 Mon Sep 17 00:00:00 2001 From: Paul Volavsek Date: Wed, 24 Jan 2024 15:02:51 +0100 Subject: [PATCH 34/35] fix --- .../Extensions/LifetimeExtensions.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs index 4365a23f..0e449510 100644 --- a/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/LifetimeExtensions.cs @@ -49,13 +49,12 @@ public static IHostBuilder UseCustomHostLifetime(this IHostBuilder builder) { services .AddSingleton(new ServiceType(ServiceTypes.SystemdService)) - .AddSingleton() .AddSingleton(); -// #pragma warning disable CA1416 -// services.AddSingleton(); -// services.AddSingleton(sp => sp.GetRequiredService()); -// #pragma warning restore CA1416 + // #pragma warning disable CA1416 + // services.AddSingleton(); + // services.AddSingleton(sp => sp.GetRequiredService()); + // #pragma warning restore CA1416 }); } else From a4f2f4df74e7a718ddec0c38687ebcce656a0563 Mon Sep 17 00:00:00 2001 From: Paul Volavsek Date: Thu, 25 Jan 2024 09:56:58 +0100 Subject: [PATCH 35/35] still use keyring --- .../Extensions/DataProtectionExtensions.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs b/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs index 39f858a8..de0f389a 100644 --- a/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs +++ b/src/fiskaltrust.Launcher/Extensions/DataProtectionExtensions.cs @@ -200,7 +200,16 @@ public static IDataProtectionBuilder ProtectKeysCustom(this IDataProtectionBuild } else if (OperatingSystem.IsLinux()) { - Log.Warning("Fallback config encryption mechanism is used on linux."); + try + { + Marshal.PrelinkAll(typeof(KeyUtils)); + builder.Services.Configure(options => options.XmlEncryptor = new KeyringXmlEncryptor()); + return builder; + } + catch (Exception e) + { + Log.Warning(e, "Fallback config encryption mechanism used."); + } } else if (OperatingSystem.IsMacOS()) {