// Copyright Epic Games, Inc. All Rights Reserved. using EpicGames.Core; using Microsoft.Extensions.Logging; namespace JobDriver.Utility { /// /// Flags for processes to terminate /// [Flags] public enum TerminateCondition { /// /// Not specified; terminate in all circumstances /// None = 0, /// /// Before running a conform /// BeforeConform = 2, /// /// Before executing a batch /// BeforeBatch = 4, /// /// Terminate at the end of a batch /// AfterBatch = 8, /// /// After a step completes /// AfterStep = 16, } /// /// Utility methods for terminating processes /// public static class TerminateProcessHelper { /// /// Terminate processes matching certain criteria /// public static Task TerminateProcessesAsync(TerminateCondition condition, DirectoryReference workingDir, IReadOnlyList? processesToTerminate, ILogger logger, CancellationToken cancellationToken) { // Terminate child processes from any previous runs ProcessUtils.TerminateProcesses(x => ShouldTerminateProcess(x, condition, workingDir, processesToTerminate), logger, cancellationToken); return Task.CompletedTask; } /// /// Callback for determining whether a process should be terminated /// static bool ShouldTerminateProcess(FileReference imageFile, TerminateCondition condition, DirectoryReference workingDir, IReadOnlyList? processesToTerminate) { if (imageFile.IsUnderDirectory(workingDir)) { return true; } if (processesToTerminate != null) { string fileName = imageFile.GetFileName(); foreach (ProcessToTerminate processToTerminate in processesToTerminate) { if (String.Equals(processToTerminate.Name, fileName, StringComparison.OrdinalIgnoreCase)) { TerminateCondition terminateFlags = TerminateCondition.None; foreach (TerminateCondition when in processToTerminate.When ?? Enumerable.Empty()) { terminateFlags |= when; } if (terminateFlags == TerminateCondition.None || (terminateFlags & condition) != 0) { return true; } } } } return false; } } }