tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Stop only the processes Tazel started
- Commit
4a3192695ba4fda8cd050e16df404dca4240cc00- Author
- Leitwolf11 ·
- Parents
708d39f8ffa8
Changes
.github/workflows/ci.yml | 7 + src/Progmasoft.Tazel/Driver/ProcessTree.cs | 178 +++++++++++++++++++++++ src/Progmasoft.Tazel/Driver/Processes.cs | 2 +- src/Progmasoft.Tazel/MicroVM/Sandbox.cs | 3 +- tests/Progmasoft.Tazel.Tests/ProcessTreeTests.cs | 108 ++++++++++++++ 5 files changed, 296 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c5814c2..09a96bf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -247,6 +247,13 @@ jobs: dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed --filter-class Progmasoft.Tazel.Tests.PortalTests + - name: Test ProcessTreeTests (macOS) + if: runner.os == 'macOS' + timeout-minutes: 10 + run: >- + dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed + --filter-class Progmasoft.Tazel.Tests.ProcessTreeTests + - name: Test QueryTests (macOS) if: runner.os == 'macOS' timeout-minutes: 10 diff --git a/src/Progmasoft.Tazel/Driver/ProcessTree.cs b/src/Progmasoft.Tazel/Driver/ProcessTree.cs new file mode 100644 index 0000000..0d2b88c --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/ProcessTree.cs @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; + +namespace Progmasoft.Tazel.Driver; + +/// <summary> +/// Stops a process Tazel started and the processes it started in turn, and nothing else. +/// </summary> +/// <remarks> +/// On Windows this is <see cref="Process.Kill(bool)"/> with the whole tree. Elsewhere Tazel finds the descendants +/// itself, from one listing of every process and its parent made before the first signal, and signals only those: +/// on macOS the whole-tree kill of .NET has ended the processes of the CI runner that ran Tazel's tests. +/// </remarks> +internal static class ProcessTree +{ + /// <summary>Stops <paramref name="process"/> and its descendants; one that has already ended is left alone.</summary> + public static void Kill(Process process) + { + ArgumentNullException.ThrowIfNull(process); + if (OperatingSystem.IsWindows()) + { + KillQuietly(process, entireProcessTree: true); + return; + } + + int root; + try + { + if (process.HasExited) + { + return; + } + + root = process.Id; + } + catch (InvalidOperationException) + { + return; + } + + var descendants = Descendants(root, Parents()); + // The parent first, so that it starts nothing more; then what it had started. + KillQuietly(process, entireProcessTree: false); + foreach (var id in descendants) + { + try + { + using var child = Process.GetProcessById(id); + KillQuietly(child, entireProcessTree: false); + } + catch (ArgumentException) + { + // It ended in the meantime. + } + } + } + + /// <summary> + /// The descendants of <paramref name="root"/> in <paramref name="parents"/>, children before their children. The + /// listing gives each process its parent; Tazel itself, its ancestors and the first process are never among them. + /// </summary> + internal static List<int> Descendants(int root, IReadOnlyDictionary<int, int> parents) + { + ArgumentNullException.ThrowIfNull(parents); + var children = new Dictionary<int, List<int>>(); + foreach (var (id, parent) in parents) + { + if (!children.TryGetValue(parent, out var list)) + { + children[parent] = list = []; + } + + list.Add(id); + } + + var protectedIds = Protected(parents); + var found = new List<int>(); + var seen = new HashSet<int> { root }; + var queue = new Queue<int>([root]); + while (queue.Count > 0) + { + if (!children.TryGetValue(queue.Dequeue(), out var list)) + { + continue; + } + + foreach (var id in list) + { + if (id > 1 && !protectedIds.Contains(id) && seen.Add(id)) + { + found.Add(id); + queue.Enqueue(id); + } + } + } + + return found; + } + + /// <summary>Tazel's own process and its ancestors, which a stop never reaches.</summary> + private static HashSet<int> Protected(IReadOnlyDictionary<int, int> parents) + { + var ids = new HashSet<int>(); + var id = Environment.ProcessId; + while (id > 1 && ids.Add(id) && parents.TryGetValue(id, out var parent)) + { + id = parent; + } + + return ids; + } + + /// <summary>Every process and its parent, from <c>ps</c>; empty when <c>ps</c> cannot be run.</summary> + private static Dictionary<int, int> Parents() + { + var parents = new Dictionary<int, int>(); + var start = new ProcessStartInfo("ps") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + foreach (var argument in new[] { "-A", "-o", "pid=", "-o", "ppid=" }) + { + start.ArgumentList.Add(argument); + } + + try + { + using var ps = Process.Start(start); + if (ps is null) + { + return parents; + } + + var text = ps.StandardOutput.ReadToEnd(); + ps.WaitForExit(); + foreach (var line in text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 2 && int.TryParse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture, out var id) && + int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var parent)) + { + parents[id] = parent; + } + } + } + catch (Win32Exception) + { + // No ps: only the process itself is stopped. + } + + return parents; + } + + private static void KillQuietly(Process process, bool entireProcessTree) + { + try + { + process.Kill(entireProcessTree); + } + catch (InvalidOperationException) + { + // It ended by itself. + } + catch (Win32Exception) + { + // It ended, or it is not Tazel's to stop. + } + } +} diff --git a/src/Progmasoft.Tazel/Driver/Processes.cs b/src/Progmasoft.Tazel/Driver/Processes.cs index 623a790..cd081f1 100644 --- a/src/Progmasoft.Tazel/Driver/Processes.cs +++ b/src/Progmasoft.Tazel/Driver/Processes.cs @@ -82,7 +82,7 @@ internal static class Processes } catch (OperationCanceledException) { - process.Kill(entireProcessTree: true); + ProcessTree.Kill(process); await process.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false); var canceled = cancel.IsCancellationRequested; return new ProcessResult(-1, Text(output), TimedOut: !canceled, Canceled: canceled); diff --git a/src/Progmasoft.Tazel/MicroVM/Sandbox.cs b/src/Progmasoft.Tazel/MicroVM/Sandbox.cs index 03ac6ea..ef89495 100644 --- a/src/Progmasoft.Tazel/MicroVM/Sandbox.cs +++ b/src/Progmasoft.Tazel/MicroVM/Sandbox.cs @@ -11,6 +11,7 @@ using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; +using Progmasoft.Tazel.Driver; namespace Progmasoft.Tazel.MicroVM; @@ -351,7 +352,7 @@ internal sealed class Sandbox : IAsyncDisposable { if (!process.HasExited) { - process.Kill(entireProcessTree: true); + ProcessTree.Kill(process); process.WaitForExit(5000); } } diff --git a/tests/Progmasoft.Tazel.Tests/ProcessTreeTests.cs b/tests/Progmasoft.Tazel.Tests/ProcessTreeTests.cs new file mode 100644 index 0000000..b1756ec --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/ProcessTreeTests.cs @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading.Tasks; +using Progmasoft.Tazel.Driver; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class ProcessTreeTests +{ + [Fact] + public void TheDescendantsAreTheChildrenAndTheirChildrenOnly() + { + // 10 started 11 and 12, 11 started 13; 20 is a sibling of 10 and 21 its child. + var parents = new Dictionary<int, int> { [10] = 5, [11] = 10, [12] = 10, [13] = 11, [20] = 5, [21] = 20 }; + + Assert.Equal([11, 12, 13], ProcessTree.Descendants(10, parents)); + Assert.Empty(ProcessTree.Descendants(13, parents)); + } + + [Fact] + public void TazelItselfAndItsAncestorsAreNeverDescendants() + { + // A listing in which Tazel and its parent appear below the process to stop, as a confused one might. + var self = Environment.ProcessId; + var parents = new Dictionary<int, int> { [self] = 77, [77] = 50, [50] = 1, [60] = 77 }; + + var found = ProcessTree.Descendants(77, parents); + + Assert.DoesNotContain(self, found); + Assert.Contains(60, found); + Assert.DoesNotContain(1, ProcessTree.Descendants(0, new Dictionary<int, int> { [1] = 0 })); + } + + [Fact] + public async Task StoppingAProcessStopsWhatItStartedAndNothingBeside() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "the shell test needs /bin/sh"); + using var beside = Process.Start("/bin/sh", ["-c", "sleep 60"]); + using var parent = Process.Start(new ProcessStartInfo("/bin/sh", ["-c", "sleep 60 & sleep 60 & wait"]) + { + RedirectStandardOutput = true, + })!; + var children = new List<int>(); + for (var tries = 0; children.Count < 2 && tries < 50; tries++) + { + await Task.Delay(100, Xunit.TestContext.Current.CancellationToken); + children = ChildrenOf(parent.Id); + } + + Assert.Equal(2, children.Count); + + ProcessTree.Kill(parent); + await parent.WaitForExitAsync(Xunit.TestContext.Current.CancellationToken); + + for (var tries = 0; tries < 50 && ChildrenAlive(children); tries++) + { + await Task.Delay(100, Xunit.TestContext.Current.CancellationToken); + } + + Assert.False(ChildrenAlive(children)); + Assert.False(beside.HasExited); + beside.Kill(); + } + + private static List<int> ChildrenOf(int id) + { + var start = new ProcessStartInfo("pgrep", ["-P", id.ToString(System.Globalization.CultureInfo.InvariantCulture)]) + { + RedirectStandardOutput = true, + }; + using var pgrep = Process.Start(start)!; + var text = pgrep.StandardOutput.ReadToEnd(); + pgrep.WaitForExit(); + var ids = new List<int>(); + foreach (var line in text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + ids.Add(int.Parse(line, System.Globalization.CultureInfo.InvariantCulture)); + } + + return ids; + } + + private static bool ChildrenAlive(List<int> ids) + { + foreach (var id in ids) + { + try + { + using var process = Process.GetProcessById(id); + if (!process.HasExited) + { + return true; + } + } + catch (ArgumentException) + { + // It is gone. + } + } + + return false; + } +}