1
0
mirror of https://github.com/chylex/Minecraft-Phantom-Panel.git synced 2024-10-18 15:42:50 +02:00

Compare commits

..

No commits in common. "2b4fa2c9025d6b836489888567d659a76058bf58" and "51d8585f05cb1c1cd89fe066f1e0aae71a5e81ee" have entirely different histories.

33 changed files with 199 additions and 317 deletions

View File

@ -1,7 +1,6 @@
using System.Collections.Immutable;
using Phantom.Agent.Minecraft.Java;
using Phantom.Agent.Minecraft.Properties;
using Phantom.Common.Data.Instance;
namespace Phantom.Agent.Minecraft.Instance;
@ -12,6 +11,5 @@ public sealed record InstanceProperties(
ImmutableArray<string> JvmArguments,
string InstanceFolder,
string ServerVersion,
ServerProperties ServerProperties,
InstanceLaunchProperties LaunchProperties
ServerProperties ServerProperties
);

View File

@ -11,8 +11,6 @@ namespace Phantom.Agent.Minecraft.Launcher;
public abstract class BaseLauncher {
private readonly InstanceProperties instanceProperties;
protected string MinecraftVersion => instanceProperties.ServerVersion;
private protected BaseLauncher(InstanceProperties instanceProperties) {
this.instanceProperties = instanceProperties;
@ -27,34 +25,11 @@ public abstract class BaseLauncher {
return new LaunchResult.InvalidJvmArguments();
}
var vanillaServerJarPath = await services.ServerExecutables.DownloadAndGetPath(instanceProperties.LaunchProperties.ServerDownloadInfo, MinecraftVersion, downloadProgressEventHandler, cancellationToken);
var vanillaServerJarPath = await services.ServerExecutables.DownloadAndGetPath(instanceProperties.ServerVersion, downloadProgressEventHandler, cancellationToken);
if (vanillaServerJarPath == null) {
return new LaunchResult.CouldNotDownloadMinecraftServer();
}
ServerJarInfo? serverJar;
try {
serverJar = await PrepareServerJar(logger, vanillaServerJarPath, instanceProperties.InstanceFolder, cancellationToken);
} catch (OperationCanceledException) {
throw;
} catch (Exception e) {
logger.Error(e, "Caught exception while preparing the server jar.");
return new LaunchResult.CouldNotPrepareMinecraftServerLauncher();
}
if (!File.Exists(serverJar.FilePath)) {
logger.Error("Missing prepared server or launcher jar: {FilePath}", serverJar.FilePath);
return new LaunchResult.CouldNotPrepareMinecraftServerLauncher();
}
try {
await AcceptEula(instanceProperties);
await UpdateServerProperties(instanceProperties);
} catch (Exception e) {
logger.Error(e, "Caught exception while configuring the server.");
return new LaunchResult.CouldNotConfigureMinecraftServer();
}
var startInfo = new ProcessStartInfo {
FileName = javaRuntimeExecutable.ExecutablePath,
WorkingDirectory = instanceProperties.InstanceFolder,
@ -68,20 +43,24 @@ public abstract class BaseLauncher {
var jvmArguments = new JvmArgumentBuilder(instanceProperties.JvmProperties, instanceProperties.JvmArguments);
CustomizeJvmArguments(jvmArguments);
var serverJarPath = await PrepareServerJar(vanillaServerJarPath, instanceProperties.InstanceFolder, cancellationToken);
var processArguments = startInfo.ArgumentList;
jvmArguments.Build(processArguments);
foreach (var extraArgument in serverJar.ExtraArgs) {
processArguments.Add(extraArgument);
}
processArguments.Add("-jar");
processArguments.Add(serverJar.FilePath);
processArguments.Add(serverJarPath);
processArguments.Add("nogui");
var process = new Process { StartInfo = startInfo };
var instanceProcess = new InstanceProcess(instanceProperties, process);
try {
await AcceptEula(instanceProperties);
await UpdateServerProperties(instanceProperties);
} catch (Exception e) {
logger.Error(e, "Caught exception while configuring the server.");
return new LaunchResult.CouldNotConfigureMinecraftServer();
}
try {
process.Start();
process.BeginOutputReadLine();
@ -103,8 +82,8 @@ public abstract class BaseLauncher {
private protected virtual void CustomizeJvmArguments(JvmArgumentBuilder arguments) {}
private protected virtual Task<ServerJarInfo> PrepareServerJar(ILogger logger, string serverJarPath, string instanceFolderPath, CancellationToken cancellationToken) {
return Task.FromResult(new ServerJarInfo(serverJarPath));
private protected virtual Task<string> PrepareServerJar(string serverJarPath, string instanceFolderPath, CancellationToken cancellationToken) {
return Task.FromResult(serverJarPath);
}
private static async Task AcceptEula(InstanceProperties instanceProperties) {

View File

@ -13,8 +13,6 @@ public abstract record LaunchResult {
public sealed record CouldNotDownloadMinecraftServer : LaunchResult;
public sealed record CouldNotPrepareMinecraftServerLauncher : LaunchResult;
public sealed record CouldNotConfigureMinecraftServer : LaunchResult;
public sealed record CouldNotStartMinecraftServer : LaunchResult;

View File

@ -1,7 +0,0 @@
using System.Collections.Immutable;
namespace Phantom.Agent.Minecraft.Launcher;
sealed record ServerJarInfo(string FilePath, ImmutableArray<string> ExtraArgs) {
public ServerJarInfo(string filePath) : this(filePath, ImmutableArray<string>.Empty) {}
}

View File

@ -17,7 +17,6 @@
<ProjectReference Include="..\..\Utils\Phantom.Utils.Collections\Phantom.Utils.Collections.csproj" />
<ProjectReference Include="..\..\Utils\Phantom.Utils.Cryptography\Phantom.Utils.Cryptography.csproj" />
<ProjectReference Include="..\..\Utils\Phantom.Utils.IO\Phantom.Utils.IO.csproj" />
<ProjectReference Include="..\..\Utils\Phantom.Utils.Runtime\Phantom.Utils.Runtime.csproj" />
</ItemGroup>
</Project>

View File

@ -1,6 +1,6 @@
using System.Security.Cryptography;
using Phantom.Common.Data.Minecraft;
using Phantom.Common.Logging;
using Phantom.Common.Minecraft;
using Phantom.Utils.Cryptography;
using Phantom.Utils.IO;
using Phantom.Utils.Runtime;
@ -11,6 +11,8 @@ namespace Phantom.Agent.Minecraft.Server;
sealed class MinecraftServerExecutableDownloader {
private static readonly ILogger Logger = PhantomLogger.Create<MinecraftServerExecutableDownloader>();
private readonly MinecraftVersions minecraftVersions;
public Task<string?> Task { get; }
public event EventHandler<DownloadProgressEventArgs>? DownloadProgress;
public event EventHandler? Completed;
@ -18,9 +20,11 @@ sealed class MinecraftServerExecutableDownloader {
private readonly CancellationTokenSource cancellationTokenSource = new ();
private int listeners = 0;
public MinecraftServerExecutableDownloader(FileDownloadInfo fileDownloadInfo, string minecraftVersion, string filePath, MinecraftServerExecutableDownloadListener listener) {
public MinecraftServerExecutableDownloader(MinecraftVersions minecraftVersions, string version, string filePath, MinecraftServerExecutableDownloadListener listener) {
this.minecraftVersions = minecraftVersions;
Register(listener);
Task = DownloadAndGetPath(fileDownloadInfo, minecraftVersion, filePath);
Task = DownloadAndGetPath(version, filePath);
Task.ContinueWith(OnCompleted, TaskScheduler.Default);
}
@ -68,26 +72,33 @@ sealed class MinecraftServerExecutableDownloader {
}
}
private async Task<string?> DownloadAndGetPath(FileDownloadInfo fileDownloadInfo, string minecraftVersion, string filePath) {
private async Task<string?> DownloadAndGetPath(string version, string filePath) {
Logger.Information("Downloading server version {Version}...", version);
string tmpFilePath = filePath + ".tmp";
var cancellationToken = cancellationTokenSource.Token;
try {
Logger.Information("Downloading server version {Version} from: {Url} ({Size})", minecraftVersion, fileDownloadInfo.DownloadUrl, fileDownloadInfo.Size.ToHumanReadable(decimalPlaces: 1));
var serverExecutableInfo = await minecraftVersions.GetServerExecutableInfo(version, cancellationToken);
if (serverExecutableInfo == null) {
return null;
}
Logger.Information("Downloading server executable from: {Url} ({Size})", serverExecutableInfo.DownloadUrl, serverExecutableInfo.Size.ToHumanReadable(decimalPlaces: 1));
try {
using var http = new HttpClient();
await FetchServerExecutableFile(http, new DownloadProgressCallback(this), fileDownloadInfo, tmpFilePath, cancellationToken);
await FetchServerExecutableFile(http, new DownloadProgressCallback(this), serverExecutableInfo, tmpFilePath, cancellationToken);
} catch (Exception) {
TryDeleteExecutableAfterFailure(tmpFilePath);
throw;
}
File.Move(tmpFilePath, filePath, true);
Logger.Information("Server version {Version} downloaded.", minecraftVersion);
Logger.Information("Server version {Version} downloaded.", version);
return filePath;
} catch (OperationCanceledException) {
Logger.Information("Download for server version {Version} was cancelled.", minecraftVersion);
Logger.Information("Download for server version {Version} was cancelled.", version);
throw;
} catch (StopProcedureException) {
return null;
@ -99,17 +110,17 @@ sealed class MinecraftServerExecutableDownloader {
}
}
private static async Task FetchServerExecutableFile(HttpClient http, DownloadProgressCallback progressCallback, FileDownloadInfo fileDownloadInfo, string filePath, CancellationToken cancellationToken) {
private static async Task FetchServerExecutableFile(HttpClient http, DownloadProgressCallback progressCallback, MinecraftServerExecutableInfo info, string filePath, CancellationToken cancellationToken) {
Sha1String downloadedFileHash;
try {
var response = await http.GetAsync(fileDownloadInfo.DownloadUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
var response = await http.GetAsync(info.DownloadUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
await using var fileStream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read);
await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken);
using var streamCopier = new MinecraftServerDownloadStreamCopier(progressCallback, fileDownloadInfo.Size.Bytes);
using var streamCopier = new MinecraftServerDownloadStreamCopier(progressCallback, info.Size.Bytes);
downloadedFileHash = await streamCopier.Copy(responseStream, fileStream, cancellationToken);
} catch (OperationCanceledException) {
throw;
@ -118,8 +129,8 @@ sealed class MinecraftServerExecutableDownloader {
throw StopProcedureException.Instance;
}
if (!downloadedFileHash.Equals(fileDownloadInfo.Hash)) {
Logger.Error("Downloaded server executable has mismatched SHA1 hash. Expected {Expected}, got {Actual}.", fileDownloadInfo.Hash, downloadedFileHash);
if (!downloadedFileHash.Equals(info.Hash)) {
Logger.Error("Downloaded server executable has mismatched SHA1 hash. Expected {Expected}, got {Actual}.", info.Hash, downloadedFileHash);
throw StopProcedureException.Instance;
}
}

View File

@ -1,37 +1,33 @@
using System.Text.RegularExpressions;
using Phantom.Common.Data.Minecraft;
using Phantom.Common.Logging;
using Phantom.Common.Minecraft;
using Phantom.Utils.IO;
using Serilog;
namespace Phantom.Agent.Minecraft.Server;
public sealed partial class MinecraftServerExecutables {
public sealed partial class MinecraftServerExecutables : IDisposable {
private static readonly ILogger Logger = PhantomLogger.Create<MinecraftServerExecutables>();
[GeneratedRegex(@"[^a-zA-Z0-9_\-\.]", RegexOptions.Compiled)]
private static partial Regex VersionFolderSanitizeRegex();
private readonly string basePath;
private readonly MinecraftVersions minecraftVersions = new ();
private readonly Dictionary<string, MinecraftServerExecutableDownloader> runningDownloadersByVersion = new ();
public MinecraftServerExecutables(string basePath) {
this.basePath = basePath;
}
internal async Task<string?> DownloadAndGetPath(FileDownloadInfo? fileDownloadInfo, string minecraftVersion, EventHandler<DownloadProgressEventArgs> progressEventHandler, CancellationToken cancellationToken) {
string serverExecutableFolderPath = Path.Combine(basePath, VersionFolderSanitizeRegex().Replace(minecraftVersion, "_"));
internal async Task<string?> DownloadAndGetPath(string version, EventHandler<DownloadProgressEventArgs> progressEventHandler, CancellationToken cancellationToken) {
string serverExecutableFolderPath = Path.Combine(basePath, VersionFolderSanitizeRegex().Replace(version, "_"));
string serverExecutableFilePath = Path.Combine(serverExecutableFolderPath, "server.jar");
if (File.Exists(serverExecutableFilePath)) {
return serverExecutableFilePath;
}
if (fileDownloadInfo == null) {
Logger.Error("Unable to download server executable for version {Version} because no download info was provided.", minecraftVersion);
return null;
}
try {
Directories.Create(serverExecutableFolderPath, Chmod.URWX_GRX);
} catch (Exception e) {
@ -43,22 +39,26 @@ public sealed partial class MinecraftServerExecutables {
MinecraftServerExecutableDownloadListener listener = new (progressEventHandler, cancellationToken);
lock (this) {
if (runningDownloadersByVersion.TryGetValue(minecraftVersion, out downloader)) {
Logger.Information("A download for server version {Version} is already running, waiting for it to finish...", minecraftVersion);
if (runningDownloadersByVersion.TryGetValue(version, out downloader)) {
Logger.Information("A download for server version {Version} is already running, waiting for it to finish...", version);
downloader.Register(listener);
}
else {
downloader = new MinecraftServerExecutableDownloader(fileDownloadInfo, minecraftVersion, serverExecutableFilePath, listener);
downloader = new MinecraftServerExecutableDownloader(minecraftVersions, version, serverExecutableFilePath, listener);
downloader.Completed += (_, _) => {
lock (this) {
runningDownloadersByVersion.Remove(minecraftVersion);
runningDownloadersByVersion.Remove(version);
}
};
runningDownloadersByVersion[minecraftVersion] = downloader;
runningDownloadersByVersion[version] = downloader;
}
}
return await downloader.Task.WaitAsync(cancellationToken);
}
public void Dispose() {
minecraftVersions.Dispose();
}
}

View File

@ -1,17 +1,15 @@
using System.Diagnostics;
using Phantom.Common.Logging;
using Phantom.Utils.Runtime;
using Serilog;
namespace Phantom.Agent.Services.Backups;
static class BackupCompressor {
private static ILogger Logger { get; } = PhantomLogger.Create(nameof(BackupCompressor));
private static ILogger ZstdLogger { get; } = PhantomLogger.Create(nameof(BackupCompressor), "Zstd");
private const string Quality = "-10";
private const string Memory = "--long=26";
private const string Threads = "-T3";
private const int Quality = 10;
private const int Memory = 26;
private const int Threads = 3;
public static async Task<string?> Compress(string sourceFilePath, CancellationToken cancellationToken) {
if (sourceFilePath.Contains('"')) {
@ -40,31 +38,66 @@ static class BackupCompressor {
Logger.Error("Invalid destination path: {Path}", destinationFilePath);
return false;
}
var startInfo = new ProcessStartInfo {
FileName = "zstd",
WorkingDirectory = workingDirectory,
ArgumentList = {
Quality,
Memory,
Threads,
"-c",
"--rm",
"--no-progress",
"-c",
"-o", destinationFilePath,
"--", sourceFilePath
}
Arguments = $"-{Quality} --long={Memory} -T{Threads} -c --rm --no-progress -c -o \"{destinationFilePath}\" -- \"{sourceFilePath}\"",
RedirectStandardOutput = true,
RedirectStandardError = true
};
static void OnZstdOutput(object? sender, DataReceivedEventArgs e) {
if (!string.IsNullOrWhiteSpace(e.Data)) {
ZstdLogger.Verbose("[Output] {Line}", e.Data);
}
using var process = new Process { StartInfo = startInfo };
process.OutputDataReceived += OnZstdProcessOutput;
process.ErrorDataReceived += OnZstdProcessOutput;
try {
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
} catch (Exception e) {
Logger.Error(e, "Caught exception launching zstd process.");
}
var process = new OneShotProcess(ZstdLogger, startInfo);
process.Output += OnZstdOutput;
return await process.Run(cancellationToken);
try {
await process.WaitForExitAsync(cancellationToken);
} catch (OperationCanceledException) {
await TryKillProcess(process);
return false;
} catch (Exception e) {
Logger.Error(e, "Caught exception waiting for zstd process to exit.");
return false;
}
if (!process.HasExited) {
await TryKillProcess(process);
return false;
}
if (process.ExitCode != 0) {
Logger.Error("Zstd process exited with code {ExitCode}.", process.ExitCode);
return false;
}
return true;
}
private static void OnZstdProcessOutput(object sender, DataReceivedEventArgs e) {
if (!string.IsNullOrWhiteSpace(e.Data)) {
Logger.Verbose("[Zstd] {Line}", e.Data);
}
}
private static async Task TryKillProcess(Process process) {
CancellationTokenSource timeout = new CancellationTokenSource(TimeSpan.FromSeconds(1));
try {
process.Kill();
await process.WaitForExitAsync(timeout.Token);
} catch (OperationCanceledException) {
Logger.Error("Timed out waiting for killed zstd process to exit.");
} catch (Exception e) {
Logger.Error(e, "Caught exception killing zstd process.");
}
}
}

View File

@ -71,7 +71,7 @@ sealed class InstanceSessionManager : IDisposable {
});
}
public async Task<InstanceActionResult<ConfigureInstanceResult>> Configure(InstanceConfiguration configuration, InstanceLaunchProperties launchProperties, bool launchNow) {
public async Task<InstanceActionResult<ConfigureInstanceResult>> Configure(InstanceConfiguration configuration) {
return await AcquireSemaphoreAndRun(async () => {
var instanceGuid = configuration.InstanceGuid;
var instanceFolder = Path.Combine(basePath, instanceGuid.ToString());
@ -90,8 +90,7 @@ sealed class InstanceSessionManager : IDisposable {
configuration.JvmArguments,
instanceFolder,
configuration.MinecraftVersion,
new ServerProperties(configuration.ServerPort, configuration.RconPort),
launchProperties
new ServerProperties(configuration.ServerPort, configuration.RconPort)
);
BaseLauncher launcher = new VanillaLauncher(properties);
@ -106,7 +105,7 @@ sealed class InstanceSessionManager : IDisposable {
Logger.Information("Created instance \"{Name}\" (GUID {Guid}).", configuration.InstanceName, configuration.InstanceGuid);
}
if (launchNow) {
if (configuration.LaunchAutomatically) {
await LaunchInternal(instance);
}
@ -180,6 +179,7 @@ sealed class InstanceSessionManager : IDisposable {
public void Dispose() {
DisposeAllInstances();
minecraftServerExecutables.Dispose();
shutdownCancellationTokenSource.Dispose();
semaphore.Dispose();
}

View File

@ -48,9 +48,6 @@ sealed class InstanceLaunchingState : IInstanceState, IDisposable {
else if (launchResult is LaunchResult.CouldNotDownloadMinecraftServer) {
throw new LaunchFailureException(InstanceLaunchFailReason.CouldNotDownloadMinecraftServer, "Session failed to launch, could not download Minecraft server.");
}
else if (launchResult is LaunchResult.CouldNotPrepareMinecraftServerLauncher) {
throw new LaunchFailureException(InstanceLaunchFailReason.CouldNotPrepareMinecraftServerLauncher, "Session failed to launch, could not prepare Minecraft server launcher.");
}
else if (launchResult is LaunchResult.CouldNotConfigureMinecraftServer) {
throw new LaunchFailureException(InstanceLaunchFailReason.CouldNotConfigureMinecraftServer, "Session failed to launch, could not configure Minecraft server.");
}

View File

@ -1,5 +1,4 @@
using Phantom.Agent.Rpc;
using Phantom.Common.Data.Instance;
using Phantom.Common.Data.Replies;
using Phantom.Common.Logging;
using Phantom.Common.Messages;
@ -27,15 +26,12 @@ public sealed class MessageListener : IMessageToAgentListener {
public async Task<NoReply> HandleRegisterAgentSuccess(RegisterAgentSuccessMessage message) {
Logger.Information("Agent authentication successful.");
void ShutdownAfterConfigurationFailed(InstanceConfiguration configuration) {
Logger.Fatal("Unable to configure instance \"{Name}\" (GUID {Guid}), shutting down.", configuration.InstanceName, configuration.InstanceGuid);
shutdownTokenSource.Cancel();
}
foreach (var configureInstanceMessage in message.InitialInstanceConfigurations) {
var result = await HandleConfigureInstance(configureInstanceMessage);
foreach (var instanceInfo in message.InitialInstances) {
var result = await agent.InstanceSessionManager.Configure(instanceInfo);
if (!result.Is(ConfigureInstanceResult.Success)) {
ShutdownAfterConfigurationFailed(configureInstanceMessage.Configuration);
Logger.Fatal("Unable to configure instance \"{Name}\" (GUID {Guid}), shutting down.", instanceInfo.InstanceName, instanceInfo.InstanceGuid);
shutdownTokenSource.Cancel();
return NoReply.Instance;
}
}
@ -60,7 +56,7 @@ public sealed class MessageListener : IMessageToAgentListener {
}
public async Task<InstanceActionResult<ConfigureInstanceResult>> HandleConfigureInstance(ConfigureInstanceMessage message) {
return await agent.InstanceSessionManager.Configure(message.Configuration, message.LaunchProperties, message.LaunchNow);
return await agent.InstanceSessionManager.Configure(message.Configuration);
}
public async Task<InstanceActionResult<LaunchInstanceResult>> HandleLaunchInstance(LaunchInstanceMessage message) {

View File

@ -15,5 +15,6 @@ public sealed partial record InstanceConfiguration(
[property: MemoryPackOrder(6)] MinecraftServerKind MinecraftServerKind,
[property: MemoryPackOrder(7)] RamAllocationUnits MemoryAllocation,
[property: MemoryPackOrder(8)] Guid JavaRuntimeGuid,
[property: MemoryPackOrder(9)] ImmutableArray<string> JvmArguments
[property: MemoryPackOrder(9)] ImmutableArray<string> JvmArguments,
[property: MemoryPackOrder(10)] bool LaunchAutomatically
);

View File

@ -10,24 +10,22 @@ public enum InstanceLaunchFailReason : byte {
InvalidJvmArguments,
CouldNotDownloadMinecraftServer,
CouldNotConfigureMinecraftServer,
CouldNotPrepareMinecraftServerLauncher,
CouldNotStartMinecraftServer
}
public static class InstanceLaunchFailReasonExtensions {
public static string ToSentence(this InstanceLaunchFailReason reason) {
return reason switch {
InstanceLaunchFailReason.ServerPortNotAllowed => "Server port not allowed.",
InstanceLaunchFailReason.ServerPortAlreadyInUse => "Server port already in use.",
InstanceLaunchFailReason.RconPortNotAllowed => "Rcon port not allowed.",
InstanceLaunchFailReason.RconPortAlreadyInUse => "Rcon port already in use.",
InstanceLaunchFailReason.JavaRuntimeNotFound => "Java runtime not found.",
InstanceLaunchFailReason.InvalidJvmArguments => "Invalid JVM arguments.",
InstanceLaunchFailReason.CouldNotDownloadMinecraftServer => "Could not download Minecraft server.",
InstanceLaunchFailReason.CouldNotConfigureMinecraftServer => "Could not configure Minecraft server.",
InstanceLaunchFailReason.CouldNotPrepareMinecraftServerLauncher => "Could not prepare Minecraft server launcher.",
InstanceLaunchFailReason.CouldNotStartMinecraftServer => "Could not start Minecraft server.",
_ => "Unknown error."
InstanceLaunchFailReason.ServerPortNotAllowed => "Server port not allowed.",
InstanceLaunchFailReason.ServerPortAlreadyInUse => "Server port already in use.",
InstanceLaunchFailReason.RconPortNotAllowed => "Rcon port not allowed.",
InstanceLaunchFailReason.RconPortAlreadyInUse => "Rcon port already in use.",
InstanceLaunchFailReason.JavaRuntimeNotFound => "Java runtime not found.",
InstanceLaunchFailReason.InvalidJvmArguments => "Invalid JVM arguments.",
InstanceLaunchFailReason.CouldNotDownloadMinecraftServer => "Could not download Minecraft server.",
InstanceLaunchFailReason.CouldNotConfigureMinecraftServer => "Could not configure Minecraft server.",
InstanceLaunchFailReason.CouldNotStartMinecraftServer => "Could not start Minecraft server.",
_ => "Unknown error."
};
}
}

View File

@ -1,9 +0,0 @@
using MemoryPack;
using Phantom.Common.Data.Minecraft;
namespace Phantom.Common.Data.Instance;
[MemoryPackable]
public sealed partial record InstanceLaunchProperties(
[property: MemoryPackOrder(0)] FileDownloadInfo? ServerDownloadInfo
);

View File

@ -1,30 +0,0 @@
using MemoryPack;
using Phantom.Utils.Cryptography;
using Phantom.Utils.IO;
namespace Phantom.Common.Data.Minecraft;
[MemoryPackable]
public sealed partial class FileDownloadInfo {
[MemoryPackOrder(0)]
public string DownloadUrl { get; }
[MemoryPackOrder(1)]
[MemoryPackInclude]
private readonly string hash;
[MemoryPackIgnore]
public Sha1String Hash => Sha1String.FromString(hash);
[MemoryPackOrder(2)]
public FileSize Size { get; }
public FileDownloadInfo(string downloadUrl, Sha1String hash, FileSize size) : this(downloadUrl, hash.ToString(), size) {}
[MemoryPackConstructor]
private FileDownloadInfo(string downloadUrl, string hash, FileSize size) {
this.DownloadUrl = downloadUrl;
this.hash = hash;
this.Size = size;
}
}

View File

@ -6,9 +6,7 @@ namespace Phantom.Common.Messages.ToAgent;
[MemoryPackable]
public sealed partial record ConfigureInstanceMessage(
[property: MemoryPackOrder(0)] InstanceConfiguration Configuration,
[property: MemoryPackOrder(1)] InstanceLaunchProperties LaunchProperties,
[property: MemoryPackOrder(2)] bool LaunchNow = false
[property: MemoryPackOrder(0)] InstanceConfiguration Configuration
) : IMessageToAgent<InstanceActionResult<ConfigureInstanceResult>> {
public Task<InstanceActionResult<ConfigureInstanceResult>> Accept(IMessageToAgentListener listener) {
return listener.HandleConfigureInstance(this);

View File

@ -1,12 +1,13 @@
using System.Collections.Immutable;
using MemoryPack;
using Phantom.Common.Data.Instance;
using Phantom.Utils.Rpc.Message;
namespace Phantom.Common.Messages.ToAgent;
[MemoryPackable]
public sealed partial record RegisterAgentSuccessMessage(
[property: MemoryPackOrder(0)] ImmutableArray<ConfigureInstanceMessage> InitialInstanceConfigurations
[property: MemoryPackOrder(0)] ImmutableArray<InstanceConfiguration> InitialInstances
) : IMessageToAgent {
public Task<NoReply> Accept(IMessageToAgentListener listener) {
return listener.HandleRegisterAgentSuccess(this);

View File

@ -0,0 +1,10 @@
using Phantom.Utils.Cryptography;
using Phantom.Utils.IO;
namespace Phantom.Common.Minecraft;
public sealed record MinecraftServerExecutableInfo(
string DownloadUrl,
Sha1String Hash,
FileSize Size
);

View File

@ -9,7 +9,7 @@ using Phantom.Utils.IO;
using Phantom.Utils.Runtime;
using Serilog;
namespace Phantom.Server.Minecraft;
namespace Phantom.Common.Minecraft;
public sealed class MinecraftVersions : IDisposable {
private static readonly ILogger Logger = PhantomLogger.Create<MinecraftVersions>();
@ -35,7 +35,12 @@ public sealed class MinecraftVersions : IDisposable {
return earlyResult;
}
await cachedVersionsSemaphore.WaitAsync(cancellationToken);
try {
await cachedVersionsSemaphore.WaitAsync(cancellationToken);
} catch (OperationCanceledException) {
return ImmutableArray<MinecraftVersion>.Empty;
}
try {
if (CachedVersionsUnlessExpired is {} racedResult) {
return racedResult;
@ -59,7 +64,7 @@ public sealed class MinecraftVersions : IDisposable {
});
}
public async Task<FileDownloadInfo?> GetServerExecutableInfo(string version, CancellationToken cancellationToken) {
public async Task<MinecraftServerExecutableInfo?> GetServerExecutableInfo(string version, CancellationToken cancellationToken) {
return await FetchOrFailSilently(async () => {
var versions = await GetVersions(cancellationToken);
var versionObject = versions.FirstOrDefault(v => v.Id == version);
@ -76,6 +81,8 @@ public sealed class MinecraftVersions : IDisposable {
private static async Task<T?> FetchOrFailSilently<T>(Func<Task<T?>> task) {
try {
return await task();
} catch (OperationCanceledException) {
return default;
} catch (StopProcedureException) {
return default;
} catch (Exception e) {
@ -89,7 +96,9 @@ public sealed class MinecraftVersions : IDisposable {
try {
return await http.GetFromJsonAsync<JsonElement>(url, cancellationToken);
} catch (HttpRequestException e) {
} catch (OperationCanceledException) {
throw StopProcedureException.Instance;
} catch (HttpRequestException e) {
Logger.Error(e, "Unable to download {Description}.", description);
throw StopProcedureException.Instance;
} catch (Exception e) {
@ -108,7 +117,7 @@ public sealed class MinecraftVersions : IDisposable {
} catch (StopProcedureException) {}
}
return foundVersions.MoveToImmutable();
return foundVersions.ToImmutable();
}
private static MinecraftVersion GetVersionFromManifestEntry(JsonElement versionElement) {
@ -139,7 +148,7 @@ public sealed class MinecraftVersions : IDisposable {
return new MinecraftVersion(id, type, url);
}
private static FileDownloadInfo GetServerExecutableInfoFromMetadata(JsonElement versionMetadata) {
private static MinecraftServerExecutableInfo GetServerExecutableInfoFromMetadata(JsonElement versionMetadata) {
JsonElement downloadsElement = GetJsonPropertyOrThrow(versionMetadata, "downloads", JsonValueKind.Object, "version metadata");
JsonElement serverElement = GetJsonPropertyOrThrow(downloadsElement, "server", JsonValueKind.Object, "downloads object in version metadata");
JsonElement urlElement = GetJsonPropertyOrThrow(serverElement, "url", JsonValueKind.String, "downloads.server object in version metadata");
@ -173,7 +182,7 @@ public sealed class MinecraftVersions : IDisposable {
throw StopProcedureException.Instance;
}
return new FileDownloadInfo(url, hash, new FileSize(size));
return new MinecraftServerExecutableInfo(url, hash, new FileSize(size));
}
private static JsonElement GetJsonPropertyOrThrow(JsonElement parentElement, string propertyKey, JsonValueKind expectedKind, string location) {

View File

@ -6,4 +6,11 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Utils\Phantom.Utils.IO\Phantom.Utils.IO.csproj" />
<ProjectReference Include="..\..\Utils\Phantom.Utils.Runtime\Phantom.Utils.Runtime.csproj" />
<ProjectReference Include="..\Phantom.Common.Data\Phantom.Common.Data.csproj" />
<ProjectReference Include="..\Phantom.Common.Logging\Phantom.Common.Logging.csproj" />
</ItemGroup>
</Project>

View File

@ -36,8 +36,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Phantom.Server.Database", "
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Phantom.Server.Database.Postgres", "Server\Phantom.Server.Database.Postgres\Phantom.Server.Database.Postgres.csproj", "{81625B4A-3DB6-48BD-A739-D23DA02107D1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Phantom.Server.Minecraft", "Server\Phantom.Server.Minecraft\Phantom.Server.Minecraft.csproj", "{4B3B73E6-48DD-4846-87FD-DFB86619B67C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Phantom.Server.Rpc", "Server\Phantom.Server.Rpc\Phantom.Server.Rpc.csproj", "{79312D72-44E0-431D-96A4-4C0A066B9671}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Phantom.Server.Services", "Server\Phantom.Server.Services\Phantom.Server.Services.csproj", "{90F0F1B1-EB0A-49C9-8DF0-1153A87F77C9}"
@ -120,10 +118,6 @@ Global
{81625B4A-3DB6-48BD-A739-D23DA02107D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{81625B4A-3DB6-48BD-A739-D23DA02107D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{81625B4A-3DB6-48BD-A739-D23DA02107D1}.Release|Any CPU.Build.0 = Release|Any CPU
{4B3B73E6-48DD-4846-87FD-DFB86619B67C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B3B73E6-48DD-4846-87FD-DFB86619B67C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B3B73E6-48DD-4846-87FD-DFB86619B67C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B3B73E6-48DD-4846-87FD-DFB86619B67C}.Release|Any CPU.Build.0 = Release|Any CPU
{79312D72-44E0-431D-96A4-4C0A066B9671}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{79312D72-44E0-431D-96A4-4C0A066B9671}.Debug|Any CPU.Build.0 = Debug|Any CPU
{79312D72-44E0-431D-96A4-4C0A066B9671}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -190,7 +184,6 @@ Global
{A0F1C595-96B6-4DBF-8C16-6B99223F8F35} = {8AC8FB6C-033A-4626-820F-ED0F908756B2}
{E3AD566F-384A-489A-A3BB-EA3BA400C18C} = {8AC8FB6C-033A-4626-820F-ED0F908756B2}
{81625B4A-3DB6-48BD-A739-D23DA02107D1} = {8AC8FB6C-033A-4626-820F-ED0F908756B2}
{4B3B73E6-48DD-4846-87FD-DFB86619B67C} = {8AC8FB6C-033A-4626-820F-ED0F908756B2}
{79312D72-44E0-431D-96A4-4C0A066B9671} = {8AC8FB6C-033A-4626-820F-ED0F908756B2}
{90F0F1B1-EB0A-49C9-8DF0-1153A87F77C9} = {8AC8FB6C-033A-4626-820F-ED0F908756B2}
{7CA2E5FE-E507-4DC6-930C-E18711A9F856} = {8AC8FB6C-033A-4626-820F-ED0F908756B2}

View File

@ -1,15 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Common\Phantom.Common.Data\Phantom.Common.Data.csproj" />
<ProjectReference Include="..\..\Common\Phantom.Common.Logging\Phantom.Common.Logging.csproj" />
<ProjectReference Include="..\..\Utils\Phantom.Utils.Runtime\Phantom.Utils.Runtime.csproj" />
</ItemGroup>
</Project>

View File

@ -82,9 +82,7 @@ public sealed class AgentManager {
Logger.Information("Registered agent \"{Name}\" (GUID {Guid}).", agent.Name, agent.Guid);
var instanceConfigurations = await instanceManager.GetInstanceConfigurationsForAgent(agent.Guid);
await connection.Send(new RegisterAgentSuccessMessage(instanceConfigurations));
await connection.Send(new RegisterAgentSuccessMessage(instanceManager.GetInstanceConfigurationsForAgent(agent.Guid)));
return true;
}

View File

@ -5,19 +5,17 @@ public enum AddOrEditInstanceResult : byte {
Success,
InstanceNameMustNotBeEmpty,
InstanceMemoryMustNotBeZero,
MinecraftVersionDownloadInfoNotFound,
AgentNotFound
}
public static class AddOrEditInstanceResultExtensions {
public static string ToSentence(this AddOrEditInstanceResult reason) {
return reason switch {
AddOrEditInstanceResult.Success => "Success.",
AddOrEditInstanceResult.InstanceNameMustNotBeEmpty => "Instance name must not be empty.",
AddOrEditInstanceResult.InstanceMemoryMustNotBeZero => "Memory must not be 0 MB.",
AddOrEditInstanceResult.MinecraftVersionDownloadInfoNotFound => "Could not find download information for the selected Minecraft version.",
AddOrEditInstanceResult.AgentNotFound => "Agent not found.",
_ => "Unknown error."
AddOrEditInstanceResult.Success => "Success.",
AddOrEditInstanceResult.InstanceNameMustNotBeEmpty => "Instance name must not be empty.",
AddOrEditInstanceResult.InstanceMemoryMustNotBeZero => "Memory must not be 0 MB.",
AddOrEditInstanceResult.AgentNotFound => "Agent not found.",
_ => "Unknown error."
};
}
}

View File

@ -4,8 +4,7 @@ namespace Phantom.Server.Services.Instances;
public sealed record Instance(
InstanceConfiguration Configuration,
IInstanceStatus Status,
bool LaunchAutomatically
IInstanceStatus Status
) {
internal Instance(InstanceConfiguration configuration, bool launchAutomatically = false) : this(configuration, InstanceStatus.Offline, launchAutomatically) {}
internal Instance(InstanceConfiguration configuration) : this(configuration, InstanceStatus.Offline) {}
}

View File

@ -10,7 +10,6 @@ using Phantom.Common.Messages.ToAgent;
using Phantom.Common.Minecraft;
using Phantom.Server.Database;
using Phantom.Server.Database.Entities;
using Phantom.Server.Minecraft;
using Phantom.Server.Services.Agents;
using Phantom.Utils.Collections;
using Phantom.Utils.Events;
@ -27,14 +26,12 @@ public sealed class InstanceManager {
private readonly CancellationToken cancellationToken;
private readonly AgentManager agentManager;
private readonly MinecraftVersions minecraftVersions;
private readonly DatabaseProvider databaseProvider;
private readonly SemaphoreSlim modifyInstancesSemaphore = new (1, 1);
public InstanceManager(ServiceConfiguration configuration, AgentManager agentManager, MinecraftVersions minecraftVersions, DatabaseProvider databaseProvider) {
public InstanceManager(ServiceConfiguration configuration, AgentManager agentManager, DatabaseProvider databaseProvider) {
this.cancellationToken = configuration.CancellationToken;
this.agentManager = agentManager;
this.minecraftVersions = minecraftVersions;
this.databaseProvider = databaseProvider;
}
@ -52,10 +49,11 @@ public sealed class InstanceManager {
entity.MinecraftServerKind,
entity.MemoryAllocation,
entity.JavaRuntimeGuid,
JvmArgumentsHelper.Split(entity.JvmArguments)
JvmArgumentsHelper.Split(entity.JvmArguments),
entity.LaunchAutomatically
);
var instance = new Instance(configuration, entity.LaunchAutomatically);
var instance = new Instance(configuration);
instances.ByGuid[instance.Configuration.InstanceGuid] = instance;
}
}
@ -75,28 +73,22 @@ public sealed class InstanceManager {
return InstanceActionResult.Concrete(AddOrEditInstanceResult.InstanceMemoryMustNotBeZero);
}
var serverExecutableInfo = await minecraftVersions.GetServerExecutableInfo(configuration.MinecraftVersion, cancellationToken);
if (serverExecutableInfo == null) {
return InstanceActionResult.Concrete(AddOrEditInstanceResult.MinecraftVersionDownloadInfoNotFound);
}
InstanceActionResult<AddOrEditInstanceResult> result;
bool isNewInstance;
await modifyInstancesSemaphore.WaitAsync(cancellationToken);
try {
isNewInstance = !instances.ByGuid.TryReplace(configuration.InstanceGuid, instance => instance with { Configuration = configuration });
if (isNewInstance) {
instances.ByGuid.TryAdd(configuration.InstanceGuid, new Instance(configuration));
}
var message = new ConfigureInstanceMessage(configuration, new InstanceLaunchProperties(serverExecutableInfo));
var reply = await agentManager.SendMessage<ConfigureInstanceMessage, InstanceActionResult<ConfigureInstanceResult>>(configuration.AgentGuid, message, TimeSpan.FromSeconds(10));
var instance = new Instance(configuration);
instances.ByGuid.AddOrReplace(instance.Configuration.InstanceGuid, instance, out var oldInstance);
var reply = await agentManager.SendMessage<ConfigureInstanceMessage, InstanceActionResult<ConfigureInstanceResult>>(configuration.AgentGuid, new ConfigureInstanceMessage(configuration), TimeSpan.FromSeconds(10));
result = reply.DidNotReplyIfNull().Map(static result => result switch {
ConfigureInstanceResult.Success => AddOrEditInstanceResult.Success,
_ => AddOrEditInstanceResult.UnknownError
});
isNewInstance = oldInstance == null;
if (result.Is(AddOrEditInstanceResult.Success)) {
using var scope = databaseProvider.CreateScope();
@ -111,6 +103,7 @@ public sealed class InstanceManager {
entity.MemoryAllocation = configuration.MemoryAllocation;
entity.JavaRuntimeGuid = configuration.JavaRuntimeGuid;
entity.JvmArguments = JvmArgumentsHelper.Join(configuration.JvmArguments);
entity.LaunchAutomatically = configuration.LaunchAutomatically;
await scope.Ctx.SaveChangesAsync(cancellationToken);
}
@ -187,7 +180,9 @@ public sealed class InstanceManager {
private async Task SetInstanceShouldLaunchAutomatically(Guid instanceGuid, bool shouldLaunchAutomatically) {
await modifyInstancesSemaphore.WaitAsync(cancellationToken);
try {
instances.ByGuid.TryReplace(instanceGuid, instance => instance with { LaunchAutomatically = shouldLaunchAutomatically });
instances.ByGuid.TryReplace(instanceGuid, instance => instance with {
Configuration = instance.Configuration with { LaunchAutomatically = shouldLaunchAutomatically }
});
using var scope = databaseProvider.CreateScope();
var entity = await scope.Ctx.Instances.FindAsync(instanceGuid, cancellationToken);
@ -204,15 +199,8 @@ public sealed class InstanceManager {
return await SendInstanceActionMessage<SendCommandToInstanceMessage, SendCommandToInstanceResult>(instanceGuid, new SendCommandToInstanceMessage(instanceGuid, command));
}
internal async Task<ImmutableArray<ConfigureInstanceMessage>> GetInstanceConfigurationsForAgent(Guid agentGuid) {
var configurationMessages = ImmutableArray.CreateBuilder<ConfigureInstanceMessage>();
foreach (var (configuration, _, launchAutomatically) in instances.ByGuid.ValuesCopy.Where(instance => instance.Configuration.AgentGuid == agentGuid)) {
var serverExecutableInfo = await minecraftVersions.GetServerExecutableInfo(configuration.MinecraftVersion, cancellationToken);
configurationMessages.Add(new ConfigureInstanceMessage(configuration, new InstanceLaunchProperties(serverExecutableInfo), launchAutomatically));
}
return configurationMessages.ToImmutable();
internal ImmutableArray<InstanceConfiguration> GetInstanceConfigurationsForAgent(Guid agentGuid) {
return instances.ByGuid.ValuesCopy.Select(static instance => instance.Configuration).Where(configuration => configuration.AgentGuid == agentGuid).ToImmutableArray();
}
private sealed class ObservableInstances : ObservableState<ImmutableDictionary<Guid, Instance>> {

View File

@ -16,7 +16,6 @@
<ProjectReference Include="..\..\Utils\Phantom.Utils.Collections\Phantom.Utils.Collections.csproj" />
<ProjectReference Include="..\..\Utils\Phantom.Utils.Events\Phantom.Utils.Events.csproj" />
<ProjectReference Include="..\Phantom.Server.Database\Phantom.Server.Database.csproj" />
<ProjectReference Include="..\Phantom.Server.Minecraft\Phantom.Server.Minecraft.csproj" />
<ProjectReference Include="..\Phantom.Server.Rpc\Phantom.Server.Rpc.csproj" />
</ItemGroup>

View File

@ -4,13 +4,15 @@
@using Phantom.Server.Services.Agents
@using Phantom.Server.Services.Events
@using Phantom.Server.Services.Instances
@using Microsoft.AspNetCore.Identity
@using Phantom.Server.Database.Enums
@implements IDisposable
@inject AgentManager AgentManager
@inject EventLog EventLog
@inject InstanceManager InstanceManager
@inject UserManager<IdentityUser> UserManager
<h1>Event Log</h1>
<h1>Audit Log</h1>
<table class="table">
<thead>

View File

@ -29,7 +29,7 @@
</thead>
@if (!instances.IsEmpty) {
<tbody>
@foreach (var (configuration, status, _) in instances) {
@foreach (var (configuration, status) in instances) {
var agentName = agentNames.TryGetValue(configuration.AgentGuid, out var name) ? name : string.Empty;
var instanceGuid = configuration.InstanceGuid.ToString();
<tr>

View File

@ -1,6 +1,5 @@
@using Phantom.Common.Data.Minecraft
@using Phantom.Common.Minecraft
@using Phantom.Server.Minecraft
@using Phantom.Server.Services.Agents
@using Phantom.Server.Services.Audit
@using Phantom.Server.Services.Instances
@ -325,7 +324,8 @@
form.MinecraftServerKind,
form.MemoryAllocation ?? RamAllocationUnits.Zero,
form.JavaRuntimeGuid.GetValueOrDefault(),
JvmArgumentsHelper.Split(form.JvmArguments)
JvmArgumentsHelper.Split(form.JvmArguments),
EditedInstanceConfiguration?.LaunchAutomatically ?? false
);
var result = await InstanceManager.AddOrEditInstance(instance);

View File

@ -14,10 +14,10 @@
<ItemGroup>
<ProjectReference Include="..\..\Common\Phantom.Common.Data\Phantom.Common.Data.csproj" />
<ProjectReference Include="..\..\Common\Phantom.Common.Logging\Phantom.Common.Logging.csproj" />
<ProjectReference Include="..\..\Common\Phantom.Common.Minecraft\Phantom.Common.Minecraft.csproj" />
<ProjectReference Include="..\..\Utils\Phantom.Utils.IO\Phantom.Utils.IO.csproj" />
<ProjectReference Include="..\..\Utils\Phantom.Utils.Runtime\Phantom.Utils.Runtime.csproj" />
<ProjectReference Include="..\Phantom.Server.Database.Postgres\Phantom.Server.Database.Postgres.csproj" />
<ProjectReference Include="..\Phantom.Server.Minecraft\Phantom.Server.Minecraft.csproj" />
<ProjectReference Include="..\Phantom.Server.Rpc\Phantom.Server.Rpc.csproj" />
<ProjectReference Include="..\Phantom.Server.Services\Phantom.Server.Services.csproj" />
<ProjectReference Include="..\Phantom.Server.Web\Phantom.Server.Web.csproj" />

View File

@ -1,6 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using Phantom.Common.Data.Agent;
using Phantom.Server.Minecraft;
using Phantom.Common.Minecraft;
using Phantom.Server.Services;
using Phantom.Server.Services.Agents;
using Phantom.Server.Services.Audit;

View File

@ -1,69 +0,0 @@
using System.Diagnostics;
using Serilog;
namespace Phantom.Utils.Runtime;
public sealed class OneShotProcess {
private readonly ILogger logger;
private readonly ProcessStartInfo startInfo;
public event DataReceivedEventHandler? Output;
public OneShotProcess(ILogger logger, ProcessStartInfo startInfo) {
this.logger = logger;
this.startInfo = startInfo;
this.startInfo.RedirectStandardOutput = true;
this.startInfo.RedirectStandardError = true;
}
public async Task<bool> Run(CancellationToken cancellationToken) {
using var process = new Process { StartInfo = startInfo };
process.OutputDataReceived += Output;
process.ErrorDataReceived += Output;
try {
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
} catch (Exception e) {
logger.Error(e, "Caught exception launching process.");
return false;
}
try {
await process.WaitForExitAsync(cancellationToken);
} catch (OperationCanceledException) {
await TryKillProcess(process);
return false;
} catch (Exception e) {
logger.Error(e, "Caught exception waiting for process to exit.");
return false;
}
if (!process.HasExited) {
await TryKillProcess(process);
return false;
}
if (process.ExitCode != 0) {
logger.Error("Process exited with code {ExitCode}.", process.ExitCode);
return false;
}
logger.Verbose("Process finished successfully.");
return true;
}
private async Task TryKillProcess(Process process) {
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
try {
process.Kill();
await process.WaitForExitAsync(timeout.Token);
} catch (OperationCanceledException) {
logger.Error("Timed out waiting for killed process to exit.");
} catch (Exception e) {
logger.Error(e, "Caught exception killing process.");
}
}
}