tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Add tazel dotnet daemon start|restart|terminate|kill and .NET daemon IPC
- Commit
f1767bcd75671f219b46cea44aa3a5a0a211f271- Author
- Leitwolf11 ·
- Parents
84aaa11943a8
Changes
CHANGELOG.md | 4 + docs/commands.md | 5 +- src/Progmasoft.Tazel/Cli/CommandMakers.cs | 44 +++- src/Progmasoft.Tazel/Cli/CommandTypes.cs | 11 +- src/Progmasoft.Tazel/Cli/Commands.cs | 27 ++- src/Progmasoft.Tazel/Cli/Help.cs | 15 +- src/Progmasoft.Tazel/Cli/LogCommands.cs | 15 ++ .../Cli/ShellCompletion.FishPowerShell.cs | 5 +- src/Progmasoft.Tazel/Cli/ShellCompletion.cs | 8 +- src/Progmasoft.Tazel/Daemon/DaemonClient.cs | 258 +++++++++++++++++++++ src/Progmasoft.Tazel/Daemon/DaemonConfig.cs | 164 +++++++++++++ src/Progmasoft.Tazel/Daemon/DaemonProtocol.cs | 101 ++++++++ src/Progmasoft.Tazel/Daemon/DaemonServer.cs | 175 ++++++++++++++ src/Progmasoft.Tazel/Program.cs | 13 +- src/Progmasoft.Tazel/Runtime/DotnetGlossary.cs | 5 +- tests/Progmasoft.Tazel.Tests/DaemonTests.cs | 146 ++++++++++++ .../Progmasoft.Tazel.Tests/DotnetSettingsTests.cs | 4 +- 17 files changed, 975 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17c57ff..0e85697 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ## Unreleased +- Added `tazel dotnet daemon start|restart|terminate|kill` (replacing `start-daemon|restart-daemon|stop-daemon`) with a + persistent .NET daemon over a user-private Unix domain socket (`TAZEL_DAEMON`, `TAZEL_DAEMON_IDLE_MINUTES`, + `TAZEL_DAEMON_MAX_HEAP`, `TAZEL_DAEMON_DIR`) and live status reporting in `tazel log daemon`. + - Removed `tazel portal-modules search` and `tazel portal-modules info` (and their `-e`/`--exact` flag); dependency resolution and `tazel vendor` continue to read Tazel Portal Modules. diff --git a/docs/commands.md b/docs/commands.md index 473f656..50169ed 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -273,7 +273,10 @@ tazel dotnet what-is CLI - `tazel dotnet get <setting>` prints what the process has: the GC's own report, or `default` where it reports none, and for heap limits the memory available to the GC. `tazel dotnet what-is <term>` explains GCHeapHardLimit, RyuJIT, .NET, CLI (the Common Language Infrastructure), CIL, CLR, C++/CLI, C#, WorkstationGC, BackgroundGC, daemon, CTS, - VES and ECMA-335, offline. Tazel has no daemon: `tazel dotnet start-daemon` and the like say so. + VES and ECMA-335, offline. +- `tazel dotnet daemon start|restart|terminate|kill` manages the persistent .NET daemon for the current installation + and user (`TAZEL_DAEMON=auto|start|off`, `TAZEL_DAEMON_IDLE_MINUTES=180`, `TAZEL_DAEMON_MAX_HEAP=2g`, + `TAZEL_DAEMON_DIR`). `terminate` stops gracefully (waiting up to 60 seconds); `kill` stops immediately. ## .tazelignore diff --git a/src/Progmasoft.Tazel/Cli/CommandMakers.cs b/src/Progmasoft.Tazel/Cli/CommandMakers.cs index c787617..f256b44 100644 --- a/src/Progmasoft.Tazel/Cli/CommandMakers.cs +++ b/src/Progmasoft.Tazel/Cli/CommandMakers.cs @@ -232,7 +232,6 @@ internal static class CommandMakers private static Command MakeDaemon(ScannedCommand scanned, OutputOptions output) { - var actions = new[] { "start-daemon", "restart-daemon", "stop-daemon", "get", "what-is" }; var positional = scanned.Positional; if (positional is ["get", var setting]) { @@ -249,16 +248,51 @@ internal static class CommandMakers throw new CommandLineException($"tazel dotnet {positional[0]} takes one {(positional[0] == "get" ? "setting" : "term")}"); } - if (positional.Count == 1 && actions.Contains(positional[0], StringComparer.Ordinal)) + if (positional is ["daemon", ..]) { - return new DaemonCommand(output, positional[0]); + return MakeDaemonAction(positional, output); } - var near = positional.Count == 1 ? Suggestions.Nearest(positional[0], actions) : null; + var legacy = positional.Count == 1 ? LegacyDaemonHint(positional[0]) : null; + if (legacy is not null) + { + throw new CommandLineException($"tazel dotnet {positional[0]} was replaced; use 'tazel dotnet daemon {legacy}'"); + } + + var topActions = new[] { "get", "what-is", "daemon" }; + var near = positional.Count >= 1 ? Suggestions.Nearest(positional[0], topActions) : null; throw new CommandLineException( - $"tazel dotnet takes get, what-is, start-daemon, restart-daemon or stop-daemon{(near is null ? "" : $"; did you mean {near}?")}"); + $"tazel dotnet takes get, what-is or daemon{(near is null ? "" : $"; did you mean {near}?")}"); + } + + private static DaemonCommand MakeDaemonAction(List<string> positional, OutputOptions output) + { + if (positional.Count != 2) + { + throw new CommandLineException("tazel dotnet daemon takes one action: start, restart, terminate or kill"); + } + + return positional[1] switch + { + "start" => new DaemonCommand(output, DaemonAction.Start), + "restart" => new DaemonCommand(output, DaemonAction.Restart), + "terminate" => new DaemonCommand(output, DaemonAction.Terminate), + "kill" => new DaemonCommand(output, DaemonAction.Kill), + "stop" => throw new CommandLineException("tazel dotnet daemon has no 'stop'; did you mean terminate?"), + var other => throw new CommandLineException( + $"tazel dotnet daemon takes start, restart, terminate or kill" + + (Suggestions.Nearest(other, ["start", "restart", "terminate", "kill"]) is { } near ? $"; did you mean {near}?" : "")), + }; } + private static string? LegacyDaemonHint(string action) => action switch + { + "start-daemon" or "start-deamon" => "start", + "restart-daemon" or "restart-deamon" => "restart", + "stop-daemon" or "stop-deamon" => "terminate", + _ => null, + }; + private static Command MakeCache(ScannedCommand scanned, OutputOptions output) { if (scanned.Positional is ["validate" or "repair"]) diff --git a/src/Progmasoft.Tazel/Cli/CommandTypes.cs b/src/Progmasoft.Tazel/Cli/CommandTypes.cs index 1a04323..a92dac5 100644 --- a/src/Progmasoft.Tazel/Cli/CommandTypes.cs +++ b/src/Progmasoft.Tazel/Cli/CommandTypes.cs @@ -144,7 +144,16 @@ internal sealed record MigrateCommand(OutputOptions Output) : Command(Output); internal sealed record VendorCommand(OutputOptions Output) : Command(Output); -internal sealed record DaemonCommand(OutputOptions Output, string Action) : Command(Output); +/// <summary>Lifecycle action of <c>tazel dotnet daemon</c>.</summary> +internal enum DaemonAction +{ + Start, + Restart, + Terminate, + Kill, +} + +internal sealed record DaemonCommand(OutputOptions Output, DaemonAction Action) : Command(Output); /// <summary><c>tazel new <name> [--force]</c>: creates a new module in a new directory.</summary> internal sealed record NewCommand(OutputOptions Output, string Name, bool Force) : Command(Output); diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 8f2abc9..322ee02 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -47,6 +47,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector NewCommand create => Task.FromResult(new NewInitCommands(reporter, workingDirectory).New(create.Name, create.Force)), InitCommand init => Task.FromResult(new NewInitCommands(reporter, workingDirectory).Init(init.Force)), LogCommand log => Task.FromResult(new LogCommands(reporter, workingDirectory, TazelVersion).Run(log.Action)), + DaemonCommand daemon => DaemonAsync(daemon, cancel), CustomCommandLine custom => CustomAsync(custom, cancel), CacheCheckCommand check => CacheCheckAsync(check, cancel), ToolLaunchCommand tool => Task.FromResult(LaunchTool(tool)), @@ -99,16 +100,32 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector return 0; } - case DaemonCommand daemon: - reporter.Error(ErrorCodes.NoDaemon, - $"tazel dotnet {daemon.Action}: this Tazel runs every command in a process of its own and has no daemon", null, - "Tazel is a morning person: awake at once, every time, no daemon needed."); - return 1; default: throw new InvalidOperationException($"no handler for {command.GetType().Name}"); } } + private async Task<int> DaemonAsync(DaemonCommand command, CancellationToken cancel) + { + var config = Daemon.DaemonConfig.FromEnvironment(); + var result = command.Action switch + { + DaemonAction.Start => await Daemon.DaemonClient.StartAsync(config, cancel).ConfigureAwait(false), + DaemonAction.Restart => await Daemon.DaemonClient.RestartAsync(config, cancel).ConfigureAwait(false), + DaemonAction.Terminate => await Daemon.DaemonClient.TerminateAsync(config, cancel).ConfigureAwait(false), + DaemonAction.Kill => await Daemon.DaemonClient.KillAsync(config, cancel).ConfigureAwait(false), + _ => throw new InvalidOperationException($"unknown daemon action {command.Action}"), + }; + if (!result.Ok) + { + reporter.Error(ErrorCodes.Project, result.Message, null, null); + return 1; + } + + reporter.Success(result.Message); + return 0; + } + private enum BuildKind { Build, diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index f202c0c..8fc93b6 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -279,16 +279,23 @@ internal static class Help The main module takes the layers around its root, a value of a higher layer replacing the one of the same name, and runs every value in its root; a module it depends on takes its own file alone. """), - ["dotnet"] = new("tazel dotnet get|what-is: the .NET runtime of this Tazel process and terms of .NET.", """ + ["dotnet"] = new("tazel dotnet get|what-is|daemon: the .NET runtime, terms, and daemon.", """ tazel dotnet get <setting> tazel dotnet what-is <term> - tazel dotnet start-daemon|restart-daemon|stop-daemon + tazel dotnet daemon start|restart|terminate|kill get prints what this process has for one of the settings below, as .NET reports it, and default where it reports none; --dotnet-settings of another command does not reach a later one. what-is explains a term of .NET, offline: GCHeapHardLimit, RyuJIT, .NET, CLI (the Common Language Infrastructure, never a command - line), CIL, CLR, C++/CLI, C#, WorkstationGC, BackgroundGC, daemon, CTS, VES, ECMA-335. This Tazel has no - daemon: start-daemon, restart-daemon and stop-daemon say so. + line), CIL, CLR, C++/CLI, C#, WorkstationGC, BackgroundGC, daemon, CTS, VES, ECMA-335. + + daemon manages the persistent .NET daemon for this installation and user: + start starts the daemon (does not duplicate an existing one) + restart terminates and restarts the daemon + terminate waits up to 60 seconds for running commands, then stops gracefully + kill stops the daemon process immediately + Environment variables: TAZEL_DAEMON (auto|start|off), TAZEL_DAEMON_IDLE_MINUTES (180, 0 never), + TAZEL_DAEMON_MAX_HEAP (2g), TAZEL_DAEMON_DIR. --dotnet-settings Name=Value[,Name=Value] sets, for the .NET runtime of this Tazel process alone, any of: GCHeapHardLimit, GCHeapHardLimitSOH, GCHeapHardLimitLOH, GCHeapHardLimitPOH bytes: 512M, 2G, 1048576 diff --git a/src/Progmasoft.Tazel/Cli/LogCommands.cs b/src/Progmasoft.Tazel/Cli/LogCommands.cs index 1239efc..0cf6906 100644 --- a/src/Progmasoft.Tazel/Cli/LogCommands.cs +++ b/src/Progmasoft.Tazel/Cli/LogCommands.cs @@ -71,6 +71,21 @@ internal sealed class LogCommands(Reporter reporter, string workingDirectory, Ve private int Daemon() { // Always answers, even when no daemon is running, and never starts one. + var config = Tazel.Daemon.DaemonConfig.FromEnvironment(); + var status = Tazel.Daemon.DaemonClient.TryStatusAsync(config, System.Threading.CancellationToken.None) + .GetAwaiter().GetResult(); + if (status is not null) + { + reporter.Plain("running: true"); + reporter.Plain($"pid: {status.Pid}"); + reporter.Plain($"uptime: {status.UptimeSeconds}s"); + reporter.Plain($"tazel: {status.TazelVersion}"); + reporter.Plain($"dotnet: {status.DotnetVersion}"); + reporter.Plain($"memory: {status.HeapBytes} bytes (limit {status.MaxHeapBytes} bytes)"); + reporter.Plain($"socket: {config.SocketPath}"); + return 0; + } + var heap = GC.GetTotalMemory(forceFullCollection: false); reporter.Plain("running: false"); reporter.Plain($"tazel: {tazelVersion.ToString(3)}"); diff --git a/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs b/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs index f484ecf..0f9a049 100644 --- a/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs +++ b/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs @@ -107,7 +107,8 @@ internal static class FishPowerShellCompletions sb.AppendLine("complete -c tazel -n '__tazel_needs_subcmd cache' -a 'keygen validate repair'"); AppendFishValueOption(sb, "__fish_seen_subcommand_from cache", "algorithm", "ed25519 rsa-4096 ml-dsa", "Signing algorithm"); sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from cache' -l remote -d 'Include remote cache'"); - sb.AppendLine("complete -c tazel -n '__tazel_needs_subcmd dotnet' -a 'get what-is start-daemon restart-daemon stop-daemon'"); + sb.AppendLine("complete -c tazel -n '__tazel_needs_subcmd dotnet' -a 'get what-is daemon'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from dotnet; and __fish_seen_subcommand_from daemon; and not __fish_seen_subcommand_from start restart terminate kill' -a 'start restart terminate kill'"); sb.AppendLine("complete -c tazel -n '__tazel_needs_subcmd options' -a 'validate get what-is update'"); sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from options custom-cmds envs' -l user -d 'User layer'"); sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from options custom-cmds envs' -l project -d 'Project layer'"); @@ -226,7 +227,7 @@ internal static class FishPowerShellCompletions 'license' { $candidates += @('--output', '-o') } 'shell-completion' { if ($null -eq $subcmd) { $candidates += @('bash', 'zsh', 'fish', 'powershell') } } 'cache' { $candidates += @('--algorithm', '--remote'); if ($null -eq $subcmd) { $candidates += @('keygen', 'validate', 'repair') } } - 'dotnet' { if ($null -eq $subcmd) { $candidates += @('get', 'what-is', 'start-daemon', 'restart-daemon', 'stop-daemon') } } + 'dotnet' { if ($null -eq $subcmd) { $candidates += @('get', 'what-is', 'daemon') } elseif ($subcmd -eq 'daemon') { $candidates += @('start', 'restart', 'terminate', 'kill') } } 'options' { $candidates += @('--user', '--project', '--local', '--create'); if ($null -eq $subcmd) { $candidates += @('validate', 'get', 'what-is', 'update') } } 'custom-cmds' { $candidates += @('--user', '--project', '--local'); if ($null -eq $subcmd) { $candidates += @('validate') } } 'envs' { $candidates += @('--user', '--project', '--local'); if ($null -eq $subcmd) { $candidates += @('validate') } } diff --git a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs index f3a7164..0b5f5fd 100644 --- a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs +++ b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs @@ -266,7 +266,11 @@ internal static class ShellCompletion if [[ -z "$subcmd" ]]; then words="$words keygen validate repair"; fi ;; dotnet) - if [[ -z "$subcmd" ]]; then words="$words get what-is start-daemon restart-daemon stop-daemon"; fi + if [[ -z "$subcmd" ]]; then + words="$words get what-is daemon" + elif [[ "$subcmd" == "daemon" ]]; then + words="$words start restart terminate kill" + fi ;; options) words="$words --user --project --local --create" @@ -380,7 +384,7 @@ internal static class ShellCompletion sb.AppendLine(" _arguments $global_opts '1:action:(keygen validate repair)' '--algorithm[Signing algorithm]:algorithm:(ed25519 rsa-4096 ml-dsa)' '--remote[Include remote cache]'"); sb.AppendLine(" ;;"); sb.AppendLine(" dotnet)"); - sb.AppendLine(" _arguments $global_opts '1:action:(get what-is start-daemon restart-daemon stop-daemon)'"); + sb.AppendLine(" _arguments $global_opts '1:action:(get what-is daemon)' '2:subaction:(start restart terminate kill)'"); sb.AppendLine(" ;;"); sb.AppendLine(" options)"); sb.AppendLine(" _arguments $global_opts '1:action:(validate get what-is update)' '--user' '--project' '--local' '--create'"); diff --git a/src/Progmasoft.Tazel/Daemon/DaemonClient.cs b/src/Progmasoft.Tazel/Daemon/DaemonClient.cs new file mode 100644 index 0000000..cfe9bd3 --- /dev/null +++ b/src/Progmasoft.Tazel/Daemon/DaemonClient.cs @@ -0,0 +1,258 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Net.Sockets; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace Progmasoft.Tazel.Daemon; + +/// <summary>Result of a daemon lifecycle action (<c>start</c>, <c>restart</c>, <c>terminate</c>, or <c>kill</c>).</summary> +internal sealed record DaemonActionResult(bool Ok, string Message, int? Pid = null); + +/// <summary>Client for managing and inspecting the persistent .NET daemon over its Unix domain socket.</summary> +internal static class DaemonClient +{ + private static readonly TimeSpan PingTimeout = TimeSpan.FromSeconds(2); + private static readonly TimeSpan StartTimeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan TerminateTimeout = TimeSpan.FromSeconds(60); + + /// <summary>Returns the live daemon's status if reachable, or <c>null</c> without starting one.</summary> + public static async Task<DaemonReply?> TryStatusAsync(DaemonConfig config, CancellationToken cancel) + { + if (!File.Exists(config.SocketPath)) + { + return null; + } + + try + { + var reply = await DaemonProtocol.SendAsync( + config.SocketPath, + new DaemonRequest(DaemonProtocol.ProtocolVersion, "status"), + PingTimeout, + cancel).ConfigureAwait(false); + return reply is { Ok: true } ? reply : null; + } + catch (Exception error) when (error is SocketException or IOException or OperationCanceledException or InvalidDataException) + { + return null; + } + } + + /// <summary>Starts the daemon if not already running; replaces a daemon from a different Tazel build.</summary> + public static async Task<DaemonActionResult> StartAsync(DaemonConfig config, CancellationToken cancel) + { + var existing = await TryStatusAsync(config, cancel).ConfigureAwait(false); + if (existing is not null) + { + if (string.Equals(existing.AssemblyMvid, config.AssemblyMvid, StringComparison.Ordinal)) + { + return new DaemonActionResult(true, $"daemon already running (pid {existing.Pid})", existing.Pid); + } + + await TerminateAsync(config, cancel).ConfigureAwait(false); + } + + config.EnsureDirectory(); + CleanupStale(config); + + var process = SpawnDaemon(config); + var deadline = DateTimeOffset.UtcNow + StartTimeout; + while (DateTimeOffset.UtcNow < deadline) + { + cancel.ThrowIfCancellationRequested(); + if (process.HasExited) + { + return new DaemonActionResult(false, $"daemon exited immediately with status {process.ExitCode}"); + } + + var status = await TryStatusAsync(config, cancel).ConfigureAwait(false); + if (status is not null) + { + return new DaemonActionResult(true, $"daemon started (pid {status.Pid})", status.Pid); + } + + await Task.Delay(TimeSpan.FromMilliseconds(50), cancel).ConfigureAwait(false); + } + + return new DaemonActionResult(false, "timed out waiting for the daemon to accept connections"); + } + + /// <summary>Stops any running daemon gracefully and starts a fresh one.</summary> + public static async Task<DaemonActionResult> RestartAsync(DaemonConfig config, CancellationToken cancel) + { + var existing = await TryStatusAsync(config, cancel).ConfigureAwait(false); + if (existing is not null) + { + var stopped = await TerminateAsync(config, cancel).ConfigureAwait(false); + if (!stopped.Ok) + { + return stopped; + } + } + + return await StartAsync(config, cancel).ConfigureAwait(false); + } + + /// <summary>Asks the daemon to finish running commands and exit gracefully (waiting up to 1 minute).</summary> + public static async Task<DaemonActionResult> TerminateAsync(DaemonConfig config, CancellationToken cancel) + { + var existing = await TryStatusAsync(config, cancel).ConfigureAwait(false); + if (existing is null) + { + CleanupStale(config); + return new DaemonActionResult(true, "daemon is not running"); + } + + try + { + await DaemonProtocol.SendAsync( + config.SocketPath, + new DaemonRequest(DaemonProtocol.ProtocolVersion, "shutdown", Graceful: true), + PingTimeout, + cancel).ConfigureAwait(false); + } + catch (Exception error) when (error is SocketException or IOException) + { + // Socket may close immediately as the daemon shuts down. + } + + var exited = await WaitForExitAsync(existing.Pid, TerminateTimeout, cancel).ConfigureAwait(false); + CleanupStale(config); + return exited + ? new DaemonActionResult(true, $"daemon terminated (pid {existing.Pid})", existing.Pid) + : new DaemonActionResult(false, $"daemon (pid {existing.Pid}) did not exit within 60 seconds; use 'tazel dotnet daemon kill'"); + } + + /// <summary>Stops the daemon process immediately.</summary> + public static async Task<DaemonActionResult> KillAsync(DaemonConfig config, CancellationToken cancel) + { + var pid = (await TryStatusAsync(config, cancel).ConfigureAwait(false))?.Pid ?? ReadMetadataPid(config); + if (pid is null) + { + CleanupStale(config); + return new DaemonActionResult(true, "daemon is not running"); + } + + try + { + using var process = Process.GetProcessById(pid.Value); + process.Kill(entireProcessTree: true); + await WaitForExitAsync(pid.Value, TimeSpan.FromSeconds(5), cancel).ConfigureAwait(false); + } + catch (ArgumentException) + { + // Already exited. + } + + CleanupStale(config); + return new DaemonActionResult(true, $"daemon killed (pid {pid.Value})", pid.Value); + } + + private static Process SpawnDaemon(DaemonConfig config) + { + var start = BuildStartInfo(config); + start.UseShellExecute = false; + start.CreateNoWindow = true; + start.RedirectStandardInput = false; + start.RedirectStandardOutput = false; + start.RedirectStandardError = false; + start.Environment["DOTNET_GCHeapHardLimit"] = config.MaxHeapBytes.ToString("X", CultureInfo.InvariantCulture); + return Process.Start(start) ?? throw new InvalidOperationException("failed to start Tazel daemon process"); + } + + private static ProcessStartInfo BuildStartInfo(DaemonConfig config) + { + var exeName = Path.GetFileNameWithoutExtension(config.ExecutablePath); + if (string.Equals(exeName, "dotnet", StringComparison.OrdinalIgnoreCase)) + { + var dll = typeof(DaemonClient).Assembly.Location; + var info = new ProcessStartInfo(config.ExecutablePath); + info.ArgumentList.Add(dll); + info.ArgumentList.Add("--internal-daemon-serve"); + info.ArgumentList.Add(config.SocketPath); + return info; + } + + var direct = new ProcessStartInfo(config.ExecutablePath); + direct.ArgumentList.Add("--internal-daemon-serve"); + direct.ArgumentList.Add(config.SocketPath); + return direct; + } + + private static int? ReadMetadataPid(DaemonConfig config) + { + if (!File.Exists(config.MetadataPath)) + { + return null; + } + + try + { + var meta = JsonSerializer.Deserialize<DaemonMetadata>(File.ReadAllText(config.MetadataPath), new JsonSerializerOptions(JsonSerializerDefaults.Web)); + return meta?.Pid; + } + catch (Exception error) when (error is IOException or JsonException) + { + return null; + } + } + + private static async Task<bool> WaitForExitAsync(int pid, TimeSpan timeout, CancellationToken cancel) + { + var deadline = DateTimeOffset.UtcNow + timeout; + while (DateTimeOffset.UtcNow < deadline) + { + if (!IsProcessAlive(pid)) + { + return true; + } + + await Task.Delay(TimeSpan.FromMilliseconds(50), cancel).ConfigureAwait(false); + } + + return !IsProcessAlive(pid); + } + + private static bool IsProcessAlive(int pid) + { + try + { + using var process = Process.GetProcessById(pid); + return !process.HasExited; + } + catch (ArgumentException) + { + return false; + } + } + + private static void CleanupStale(DaemonConfig config) + { + DeleteIfExists(config.SocketPath); + DeleteIfExists(config.MetadataPath); + } + + private static void DeleteIfExists(string path) + { + try + { + if (File.Exists(path)) + { + File.Delete(path); + } + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } +} diff --git a/src/Progmasoft.Tazel/Daemon/DaemonConfig.cs b/src/Progmasoft.Tazel/Daemon/DaemonConfig.cs new file mode 100644 index 0000000..5980a08 --- /dev/null +++ b/src/Progmasoft.Tazel/Daemon/DaemonConfig.cs @@ -0,0 +1,164 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Globalization; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Progmasoft.Tazel.Daemon; + +/// <summary>How <c>TAZEL_DAEMON</c> controls automatic daemon use.</summary> +internal enum DaemonMode +{ + Auto, + Start, + Off, +} + +/// <summary>Resolved daemon paths and limits for the current Tazel installation and user.</summary> +internal sealed record DaemonConfig( + string DirectoryPath, + string SocketPath, + string MetadataPath, + string ExecutablePath, + string AssemblyMvid, + DaemonMode Mode, + int IdleMinutes, + long MaxHeapBytes) +{ + public const int DefaultIdleMinutes = 180; + public const long DefaultMaxHeapBytes = 2L * 1024 * 1024 * 1024; + + /// <summary>Builds the daemon configuration from the current process environment.</summary> + public static DaemonConfig FromEnvironment(string? executableOverride = null) + { + var executable = Path.GetFullPath(executableOverride + ?? Environment.ProcessPath + ?? typeof(DaemonConfig).Assembly.Location); + var hash = HashInstallPath(executable); + var dir = ResolveDirectory(); + var mvid = typeof(DaemonConfig).Assembly.ManifestModule.ModuleVersionId.ToString("N"); + return new DaemonConfig( + dir, + Path.Combine(dir, $"{hash}.sock"), + Path.Combine(dir, $"{hash}.json"), + executable, + mvid, + ParseMode(Environment.GetEnvironmentVariable("TAZEL_DAEMON")), + ParseIdleMinutes(Environment.GetEnvironmentVariable("TAZEL_DAEMON_IDLE_MINUTES")), + ParseHeapSize(Environment.GetEnvironmentVariable("TAZEL_DAEMON_MAX_HEAP"))); + } + + /// <summary>Ensures the daemon directory exists with user-only (0700) permissions on Unix.</summary> + public void EnsureDirectory() + { + Directory.CreateDirectory(DirectoryPath); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(DirectoryPath, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + } + + /// <summary>Returns the first 16 lowercase hex characters of SHA-256 of <paramref name="installPath"/>.</summary> + public static string HashInstallPath(string installPath) + { + var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(installPath)); + return Convert.ToHexString(bytes.AsSpan(0, 8)).ToLowerInvariant(); + } + + /// <summary>Parses <c>TAZEL_DAEMON</c> (<c>auto</c>, <c>start</c>, or <c>off</c>).</summary> + public static DaemonMode ParseMode(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return DaemonMode.Auto; + } + + return value.Trim().ToLowerInvariant() switch + { + "auto" => DaemonMode.Auto, + "start" => DaemonMode.Start, + "off" => DaemonMode.Off, + _ => DaemonMode.Auto, + }; + } + + /// <summary>Parses <c>TAZEL_DAEMON_IDLE_MINUTES</c> (default 180; 0 disables idle exit).</summary> + public static int ParseIdleMinutes(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return DefaultIdleMinutes; + } + + return int.TryParse(value.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var minutes) && minutes >= 0 + ? minutes + : DefaultIdleMinutes; + } + + /// <summary>Parses <c>TAZEL_DAEMON_MAX_HEAP</c> (e.g. <c>2g</c>, <c>512m</c>, <c>1024k</c>, or bytes).</summary> + public static long ParseHeapSize(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return DefaultMaxHeapBytes; + } + + var text = value.Trim().ToLowerInvariant(); + long scale = 1; + if (text.EndsWith('g')) + { + scale = 1024L * 1024 * 1024; + text = text[..^1]; + } + else if (text.EndsWith('m')) + { + scale = 1024L * 1024; + text = text[..^1]; + } + else if (text.EndsWith('k')) + { + scale = 1024L; + text = text[..^1]; + } + + if (long.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) && number > 0) + { + try + { + return checked(number * scale); + } + catch (OverflowException) + { + return DefaultMaxHeapBytes; + } + } + + return DefaultMaxHeapBytes; + } + + private static string ResolveDirectory() + { + var explicitDir = Environment.GetEnvironmentVariable("TAZEL_DAEMON_DIR"); + if (!string.IsNullOrWhiteSpace(explicitDir)) + { + return Path.GetFullPath(explicitDir.Trim()); + } + + var tazelHome = Environment.GetEnvironmentVariable("TAZEL_HOME"); + if (!string.IsNullOrWhiteSpace(tazelHome)) + { + return Path.Combine(Path.GetFullPath(tazelHome.Trim()), "Daemon"); + } + + var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + if (!string.IsNullOrWhiteSpace(local)) + { + return Path.Combine(local, "Tazel", "Daemon"); + } + + return Path.Combine(Path.GetTempPath(), "tazel-daemon"); + } +} diff --git a/src/Progmasoft.Tazel/Daemon/DaemonProtocol.cs b/src/Progmasoft.Tazel/Daemon/DaemonProtocol.cs new file mode 100644 index 0000000..3a9cab1 --- /dev/null +++ b/src/Progmasoft.Tazel/Daemon/DaemonProtocol.cs @@ -0,0 +1,101 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace Progmasoft.Tazel.Daemon; + +/// <summary>Versioned, bounded JSON-line framing for daemon control requests and replies.</summary> +internal static class DaemonProtocol +{ + public const int ProtocolVersion = 1; + public const int MaxLineBytes = 64 * 1024; + + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + + public static async Task WriteAsync<T>(Stream stream, T payload, CancellationToken cancel) + { + var bytes = JsonSerializer.SerializeToUtf8Bytes(payload, JsonOptions); + if (bytes.Length > MaxLineBytes) + { + throw new InvalidDataException($"daemon message exceeds {MaxLineBytes} bytes"); + } + + await stream.WriteAsync(bytes, cancel).ConfigureAwait(false); + await stream.WriteAsync("\n"u8.ToArray(), cancel).ConfigureAwait(false); + await stream.FlushAsync(cancel).ConfigureAwait(false); + } + + public static async Task<T?> ReadAsync<T>(Stream stream, CancellationToken cancel) + { + var buffer = new byte[1]; + using var line = new MemoryStream(); + while (true) + { + var read = await stream.ReadAsync(buffer, cancel).ConfigureAwait(false); + if (read == 0) + { + break; + } + + if (buffer[0] == (byte)'\n') + { + break; + } + + if (line.Length >= MaxLineBytes) + { + throw new InvalidDataException($"daemon message exceeds {MaxLineBytes} bytes"); + } + + line.WriteByte(buffer[0]); + } + + if (line.Length == 0) + { + return default; + } + + return JsonSerializer.Deserialize<T>(Encoding.UTF8.GetString(line.GetBuffer(), 0, (int)line.Length), JsonOptions); + } + + public static async Task<DaemonReply?> SendAsync(string socketPath, DaemonRequest request, TimeSpan timeout, CancellationToken cancel) + { + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancel); + linked.CancelAfter(timeout); + using var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); + await socket.ConnectAsync(new UnixDomainSocketEndPoint(socketPath), linked.Token).ConfigureAwait(false); + await using var stream = new NetworkStream(socket, ownsSocket: false); + await WriteAsync(stream, request, linked.Token).ConfigureAwait(false); + return await ReadAsync<DaemonReply>(stream, linked.Token).ConfigureAwait(false); + } +} + +internal sealed record DaemonRequest(int Version, string Kind, bool Graceful = true); + +internal sealed record DaemonReply( + int Version, + bool Ok, + int Pid, + string AssemblyMvid, + string TazelVersion, + string DotnetVersion, + long HeapBytes, + long MaxHeapBytes, + long UptimeSeconds, + string? ActiveCommand, + string? Message); + +internal sealed record DaemonMetadata( + int Pid, + string AssemblyMvid, + string TazelVersion, + string SocketPath, + DateTimeOffset StartedUtc, + long MaxHeapBytes); diff --git a/src/Progmasoft.Tazel/Daemon/DaemonServer.cs b/src/Progmasoft.Tazel/Daemon/DaemonServer.cs new file mode 100644 index 0000000..9550c34 --- /dev/null +++ b/src/Progmasoft.Tazel/Daemon/DaemonServer.cs @@ -0,0 +1,175 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Net.Sockets; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace Progmasoft.Tazel.Daemon; + +/// <summary>Persistent .NET background daemon listening on a user-private Unix domain socket.</summary> +internal sealed class DaemonServer(DaemonConfig config, Version tazelVersion) +{ + private readonly DateTimeOffset _startedUtc = DateTimeOffset.UtcNow; + private DateTimeOffset _lastActivityUtc = DateTimeOffset.UtcNow; + + internal string? ActiveCommand { get; set; } + + /// <summary>Runs the daemon listener until shutdown, idle timeout, cancellation, or executable removal.</summary> + public async Task<int> RunAsync(CancellationToken cancel) + { + config.EnsureDirectory(); + DeleteIfExists(config.SocketPath); + + using var listener = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); + listener.Bind(new UnixDomainSocketEndPoint(config.SocketPath)); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(config.SocketPath, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + + listener.Listen(16); + WriteMetadata(); + + using var stop = CancellationTokenSource.CreateLinkedTokenSource(cancel); + var monitor = MonitorLifetimeAsync(stop); + try + { + while (!stop.IsCancellationRequested) + { + Socket client; + try + { + client = await listener.AcceptAsync(stop.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + break; + } + + await HandleClientAsync(client, stop).ConfigureAwait(false); + } + } + finally + { + await stop.CancelAsync().ConfigureAwait(false); + try + { + await monitor.ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + + DeleteIfExists(config.SocketPath); + DeleteIfExists(config.MetadataPath); + } + + return 0; + } + + private async Task HandleClientAsync(Socket client, CancellationTokenSource stop) + { + using (client) + { + try + { + await using var stream = new NetworkStream(client, ownsSocket: false); + var request = await DaemonProtocol.ReadAsync<DaemonRequest>(stream, stop.Token).ConfigureAwait(false); + _lastActivityUtc = DateTimeOffset.UtcNow; + if (request is null || request.Version != DaemonProtocol.ProtocolVersion) + { + await DaemonProtocol.WriteAsync(stream, BuildReply(ok: false, "unsupported daemon protocol version"), stop.Token) + .ConfigureAwait(false); + return; + } + + if (string.Equals(request.Kind, "shutdown", StringComparison.Ordinal)) + { + await DaemonProtocol.WriteAsync(stream, BuildReply(ok: true, "shutting down"), stop.Token).ConfigureAwait(false); + await stop.CancelAsync().ConfigureAwait(false); + return; + } + + await DaemonProtocol.WriteAsync(stream, BuildReply(ok: true, null), stop.Token).ConfigureAwait(false); + } + catch (Exception error) when (error is IOException or SocketException or InvalidDataException or JsonException or OperationCanceledException) + { + // Ignore malformed or disconnected clients without crashing the daemon. + } + } + } + + private DaemonReply BuildReply(bool ok, string? message) + { + var uptime = Math.Max(0L, (long)(DateTimeOffset.UtcNow - _startedUtc).TotalSeconds); + return new DaemonReply( + DaemonProtocol.ProtocolVersion, + ok, + Environment.ProcessId, + config.AssemblyMvid, + tazelVersion.ToString(3), + $".NET {Environment.Version}", + GC.GetTotalMemory(forceFullCollection: false), + config.MaxHeapBytes, + uptime, + ActiveCommand, + message); + } + + private async Task MonitorLifetimeAsync(CancellationTokenSource stop) + { + while (!stop.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromSeconds(5), stop.Token).ConfigureAwait(false); + if (!File.Exists(config.ExecutablePath)) + { + await stop.CancelAsync().ConfigureAwait(false); + return; + } + + if (config.IdleMinutes > 0 && DateTimeOffset.UtcNow - _lastActivityUtc >= TimeSpan.FromMinutes(config.IdleMinutes)) + { + await stop.CancelAsync().ConfigureAwait(false); + return; + } + } + } + + private void WriteMetadata() + { + var meta = new DaemonMetadata( + Environment.ProcessId, + config.AssemblyMvid, + tazelVersion.ToString(3), + config.SocketPath, + _startedUtc, + config.MaxHeapBytes); + var json = JsonSerializer.Serialize(meta, new JsonSerializerOptions(JsonSerializerDefaults.Web) { WriteIndented = true }); + File.WriteAllText(config.MetadataPath, json); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(config.MetadataPath, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + } + + private static void DeleteIfExists(string path) + { + try + { + if (File.Exists(path)) + { + File.Delete(path); + } + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } +} diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index 128a040..52b6212 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -29,6 +29,17 @@ internal static class Program press.Cancel = true; cancel.Cancel(); }; + if (arguments is ["--internal-daemon-serve", var socketPath]) + { + var config = Daemon.DaemonConfig.FromEnvironment() with + { + SocketPath = socketPath, + DirectoryPath = Path.GetDirectoryName(socketPath) ?? Daemon.DaemonConfig.FromEnvironment().DirectoryPath, + MetadataPath = Path.ChangeExtension(socketPath, ".json"), + }; + return await new Daemon.DaemonServer(config, Commands.TazelVersion).RunAsync(cancel.Token).ConfigureAwait(false); + } + return await RunAsync(arguments, Directory.GetCurrentDirectory(), null, cancel.Token).ConfigureAwait(false); } @@ -126,7 +137,7 @@ internal static class Program /// </summary> private static void ApplyDotnetSettings(Command command, string directory) { - if (command is HelpCommand or ExplainCommand or VersionCommand or LicenseCommand or ShellCompletionCommand or DotnetWhatIsCommand or NewCommand or InitCommand || + if (command is HelpCommand or ExplainCommand or VersionCommand or LicenseCommand or ShellCompletionCommand or DotnetWhatIsCommand or DaemonCommand or NewCommand or InitCommand || command is LogCommand { Action: "daemon" or "registries" or "what-up" or "snoop" }) { return; diff --git a/src/Progmasoft.Tazel/Runtime/DotnetGlossary.cs b/src/Progmasoft.Tazel/Runtime/DotnetGlossary.cs index efdba24..e23c5ab 100644 --- a/src/Progmasoft.Tazel/Runtime/DotnetGlossary.cs +++ b/src/Progmasoft.Tazel/Runtime/DotnetGlossary.cs @@ -55,8 +55,9 @@ internal static class DotnetGlossary "Garbage collection in which much of the work on generation 2, the oldest objects, runs on a thread of its " + "own while the program goes on, instead of stopping it for the whole collection."), new("daemon", null, - "A long-running background process that serves other processes. This Tazel starts every command in a process " + - "of its own and has no persistent daemon; tazel dotnet start-daemon says so."), + "A long-running background process that serves other processes. Tazel's .NET daemon is managed with " + + "tazel dotnet daemon start|restart|terminate|kill and configured via TAZEL_DAEMON, TAZEL_DAEMON_IDLE_MINUTES, " + + "TAZEL_DAEMON_MAX_HEAP, and TAZEL_DAEMON_DIR."), new("CTS", "Common Type System", "The rules of the CLI for defining types and how they relate: classes, value types, interfaces, inheritance, " + "and how one language's types are seen by another."), diff --git a/tests/Progmasoft.Tazel.Tests/DaemonTests.cs b/tests/Progmasoft.Tazel.Tests/DaemonTests.cs new file mode 100644 index 0000000..2ade608 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/DaemonTests.cs @@ -0,0 +1,146 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Daemon; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +[Collection("environment")] +public sealed class DaemonTests +{ + [Theory] + [InlineData("start", nameof(DaemonAction.Start))] + [InlineData("restart", nameof(DaemonAction.Restart))] + [InlineData("terminate", nameof(DaemonAction.Terminate))] + [InlineData("kill", nameof(DaemonAction.Kill))] + public void ParsesDotnetDaemonActions(string action, string expected) + { + var command = Assert.IsType<DaemonCommand>(CommandLine.Parse(["dotnet", "daemon", action])); + Assert.Equal(expected, command.Action.ToString()); + } + + [Theory] + [InlineData(new[] { "dotnet", "daemon" }, "takes one action: start, restart, terminate or kill")] + [InlineData(new[] { "dotnet", "daemon", "stop" }, "did you mean terminate?")] + [InlineData(new[] { "dotnet", "daemon", "strat" }, "did you mean start?")] + [InlineData(new[] { "dotnet", "deamon", "start" }, "did you mean daemon?")] + [InlineData(new[] { "dotnet", "start-daemon" }, "use 'tazel dotnet daemon start'")] + [InlineData(new[] { "dotnet", "restart-daemon" }, "use 'tazel dotnet daemon restart'")] + [InlineData(new[] { "dotnet", "stop-daemon" }, "use 'tazel dotnet daemon terminate'")] + public void RejectsInvalidDaemonCommandsWithHints(string[] arguments, string expectedHint) + { + var error = Assert.Throws<CommandLineException>(() => CommandLine.Parse(arguments)); + Assert.Contains(expectedHint, error.Message, StringComparison.Ordinal); + } + + [Fact] + public void ParsesConfigValuesAndProducesShortSocketHash() + { + Assert.Equal(DaemonMode.Auto, DaemonConfig.ParseMode(null)); + Assert.Equal(DaemonMode.Start, DaemonConfig.ParseMode("start")); + Assert.Equal(DaemonMode.Off, DaemonConfig.ParseMode("OFF")); + Assert.Equal(180, DaemonConfig.ParseIdleMinutes(null)); + Assert.Equal(0, DaemonConfig.ParseIdleMinutes("0")); + Assert.Equal(45, DaemonConfig.ParseIdleMinutes("45")); + Assert.Equal(2L * 1024 * 1024 * 1024, DaemonConfig.ParseHeapSize(null)); + Assert.Equal(512L * 1024 * 1024, DaemonConfig.ParseHeapSize("512m")); + Assert.Equal(1024L * 1024, DaemonConfig.ParseHeapSize("1024k")); + + var hash = DaemonConfig.HashInstallPath("/usr/local/bin/tazel"); + Assert.Equal(16, hash.Length); + Assert.Matches("^[0-9a-f]{16}$", hash); + } + + [Fact] + public async Task LiveDaemonRespondsToStatusLogAndGracefulShutdown() + { + var dir = Path.Combine(Path.GetTempPath(), $"tz-d-{Guid.NewGuid():N}"[..16]); + Directory.CreateDirectory(dir); + try + { + using var envDir = new EnvironmentVariable("TAZEL_DAEMON_DIR", dir); + var config = DaemonConfig.FromEnvironment(); + Assert.Equal(dir, config.DirectoryPath); + Assert.Null(await DaemonClient.TryStatusAsync(config, CancellationToken.None)); + + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + var server = new DaemonServer(config, new Version(0, 3, 0)); + var runTask = Task.Run(() => server.RunAsync(cts.Token), cts.Token); + + DaemonReply? status = null; + for (var i = 0; i < 60 && status is null; i++) + { + status = await DaemonClient.TryStatusAsync(config, cts.Token); + if (status is null) + { + await Task.Delay(25, cts.Token); + } + } + + Assert.NotNull(status); + Assert.True(status.Ok); + Assert.Equal(Environment.ProcessId, status.Pid); + Assert.Equal("0.3.0", status.TazelVersion); + + using var writer = new StringWriter(); + var exit = await Program.RunAsync(["--color", "never", "log", "daemon"], dir, writer, cts.Token); + Assert.Equal(0, exit); + var logOut = writer.ToString(); + Assert.Contains("running: true", logOut, StringComparison.Ordinal); + Assert.Contains($"pid: {Environment.ProcessId}", logOut, StringComparison.Ordinal); + + var reply = await DaemonProtocol.SendAsync( + config.SocketPath, + new DaemonRequest(DaemonProtocol.ProtocolVersion, "shutdown", Graceful: true), + TimeSpan.FromSeconds(2), + cts.Token); + Assert.NotNull(reply); + Assert.True(reply.Ok); + + var serverExit = await runTask; + Assert.Equal(0, serverExit); + Assert.False(File.Exists(config.SocketPath)); + Assert.Null(await DaemonClient.TryStatusAsync(config, CancellationToken.None)); + } + finally + { + if (Directory.Exists(dir)) + { + Directory.Delete(dir, recursive: true); + } + } + } + + [Fact] + public async Task TerminateAndKillWhenNotRunningSucceedCleanly() + { + var dir = Path.Combine(Path.GetTempPath(), $"tz-e-{Guid.NewGuid():N}"[..16]); + Directory.CreateDirectory(dir); + try + { + using var envDir = new EnvironmentVariable("TAZEL_DAEMON_DIR", dir); + using var outTerm = new StringWriter(); + var termExit = await Program.RunAsync(["--color", "never", "dotnet", "daemon", "terminate"], dir, outTerm, CancellationToken.None); + Assert.Equal(0, termExit); + Assert.Contains("not running", outTerm.ToString(), StringComparison.Ordinal); + + using var outKill = new StringWriter(); + var killExit = await Program.RunAsync(["--color", "never", "dotnet", "daemon", "kill"], dir, outKill, CancellationToken.None); + Assert.Equal(0, killExit); + Assert.Contains("not running", outKill.ToString(), StringComparison.Ordinal); + } + finally + { + if (Directory.Exists(dir)) + { + Directory.Delete(dir, recursive: true); + } + } + } +} diff --git a/tests/Progmasoft.Tazel.Tests/DotnetSettingsTests.cs b/tests/Progmasoft.Tazel.Tests/DotnetSettingsTests.cs index a515c78..926fc0e 100644 --- a/tests/Progmasoft.Tazel.Tests/DotnetSettingsTests.cs +++ b/tests/Progmasoft.Tazel.Tests/DotnetSettingsTests.cs @@ -209,7 +209,7 @@ public sealed class DotnetSettingsTests var cli = DotnetGlossary.Find("CLI")!; Assert.Equal("Common Language Infrastructure", cli.Title); Assert.DoesNotContain("Command-Line Interface", cli.Text, StringComparison.OrdinalIgnoreCase); - Assert.Contains("no persistent daemon", DotnetGlossary.Find("daemon")!.Text, StringComparison.Ordinal); + Assert.Contains("tazel dotnet daemon start|restart|terminate|kill", DotnetGlossary.Find("daemon")!.Text, StringComparison.Ordinal); Assert.Equal("CLI", DotnetGlossary.Nearest("cli")); Assert.Equal("RyuJIT", DotnetGlossary.Nearest("RyuJT")); } @@ -238,7 +238,7 @@ public sealed class DotnetSettingsTests Assert.Contains("tazel dotnet get <setting>", help, StringComparison.Ordinal); Assert.Contains("tazel dotnet what-is <term>", help, StringComparison.Ordinal); Assert.Contains("--dotnet-settings", help, StringComparison.Ordinal); - Assert.Contains("This Tazel has no", help, StringComparison.Ordinal); + Assert.Contains("tazel dotnet daemon start|restart|terminate|kill", help, StringComparison.Ordinal); Assert.Equal(ErrorCodes.DotnetSettingRefused, ErrorCodes.Find(ErrorCodes.DotnetSettingRefused)!.Code); } }