mirror of
https://github.com/chylex/Minecraft-Phantom-Panel.git
synced 2025-09-15 06:32:10 +02:00
Compare commits
6 Commits
9971855bf8
...
wip-launch
Author | SHA1 | Date | |
---|---|---|---|
101ca865fe
|
|||
dd57c442af
|
|||
dacd786b4c
|
|||
89e67e1690
|
|||
33de01f564
|
|||
dd0d9b3ddb
|
@@ -1,5 +1,4 @@
|
||||
using System.Diagnostics;
|
||||
using Phantom.Utils.Collections;
|
||||
using Phantom.Utils.Collections;
|
||||
using Phantom.Utils.Runtime;
|
||||
|
||||
namespace Phantom.Agent.Minecraft.Instance;
|
||||
@@ -19,10 +18,8 @@ public sealed class InstanceProcess : IDisposable {
|
||||
internal InstanceProcess(InstanceProperties instanceProperties, Process process) {
|
||||
this.InstanceProperties = instanceProperties;
|
||||
this.process = process;
|
||||
this.process.EnableRaisingEvents = true;
|
||||
this.process.Exited += ProcessOnExited;
|
||||
this.process.OutputDataReceived += HandleOutputLine;
|
||||
this.process.ErrorDataReceived += HandleOutputLine;
|
||||
this.process.OutputReceived += ProcessOutputReceived;
|
||||
}
|
||||
|
||||
public async Task SendCommand(string command, CancellationToken cancellationToken) {
|
||||
@@ -41,11 +38,9 @@ public sealed class InstanceProcess : IDisposable {
|
||||
OutputEvent -= listener;
|
||||
}
|
||||
|
||||
private void HandleOutputLine(object sender, DataReceivedEventArgs args) {
|
||||
if (args.Data is {} line) {
|
||||
outputBuffer.Add(line);
|
||||
OutputEvent?.Invoke(this, line);
|
||||
}
|
||||
private void ProcessOutputReceived(object? sender, Process.Output output) {
|
||||
outputBuffer.Add(output.Line);
|
||||
OutputEvent?.Invoke(this, output.Line);
|
||||
}
|
||||
|
||||
private void ProcessOnExited(object? sender, EventArgs e) {
|
||||
|
@@ -1,17 +1,17 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Text;
|
||||
using Kajabity.Tools.Java;
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Agent.Minecraft.Java;
|
||||
using Phantom.Agent.Minecraft.Server;
|
||||
using Phantom.Common.Minecraft;
|
||||
using Phantom.Utils.Runtime;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Minecraft.Launcher;
|
||||
|
||||
public abstract class BaseLauncher {
|
||||
public abstract class BaseLauncher : IServerLauncher {
|
||||
private readonly InstanceProperties instanceProperties;
|
||||
|
||||
|
||||
protected string MinecraftVersion => instanceProperties.ServerVersion;
|
||||
|
||||
private protected BaseLauncher(InstanceProperties instanceProperties) {
|
||||
@@ -34,7 +34,7 @@ public abstract class BaseLauncher {
|
||||
|
||||
ServerJarInfo? serverJar;
|
||||
try {
|
||||
serverJar = await PrepareServerJar(logger, vanillaServerJarPath, instanceProperties.InstanceFolder, cancellationToken);
|
||||
serverJar = await PrepareServerJar(logger, vanillaServerJarPath, cancellationToken);
|
||||
} catch (OperationCanceledException) {
|
||||
throw;
|
||||
} catch (Exception e) {
|
||||
@@ -55,20 +55,17 @@ public abstract class BaseLauncher {
|
||||
return new LaunchResult.CouldNotConfigureMinecraftServer();
|
||||
}
|
||||
|
||||
var startInfo = new ProcessStartInfo {
|
||||
var processConfigurator = new ProcessConfigurator {
|
||||
FileName = javaRuntimeExecutable.ExecutablePath,
|
||||
WorkingDirectory = instanceProperties.InstanceFolder,
|
||||
RedirectStandardInput = true,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = false
|
||||
RedirectInput = true,
|
||||
UseShellExecute = false
|
||||
};
|
||||
|
||||
var jvmArguments = new JvmArgumentBuilder(instanceProperties.JvmProperties, instanceProperties.JvmArguments);
|
||||
CustomizeJvmArguments(jvmArguments);
|
||||
|
||||
var processArguments = startInfo.ArgumentList;
|
||||
var processArguments = processConfigurator.ArgumentList;
|
||||
jvmArguments.Build(processArguments);
|
||||
|
||||
foreach (var extraArgument in serverJar.ExtraArgs) {
|
||||
@@ -79,13 +76,11 @@ public abstract class BaseLauncher {
|
||||
processArguments.Add(serverJar.FilePath);
|
||||
processArguments.Add("nogui");
|
||||
|
||||
var process = new Process { StartInfo = startInfo };
|
||||
var process = processConfigurator.CreateProcess();
|
||||
var instanceProcess = new InstanceProcess(instanceProperties, process);
|
||||
|
||||
try {
|
||||
process.Start();
|
||||
process.BeginOutputReadLine();
|
||||
process.BeginErrorReadLine();
|
||||
} catch (Exception launchException) {
|
||||
logger.Error(launchException, "Caught exception launching the server process.");
|
||||
|
||||
@@ -103,7 +98,7 @@ 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) {
|
||||
private protected virtual Task<ServerJarInfo> PrepareServerJar(ILogger logger, string serverJarPath, CancellationToken cancellationToken) {
|
||||
return Task.FromResult(new ServerJarInfo(serverJarPath));
|
||||
}
|
||||
|
||||
|
@@ -0,0 +1,8 @@
|
||||
using Phantom.Agent.Minecraft.Server;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Minecraft.Launcher;
|
||||
|
||||
public interface IServerLauncher {
|
||||
Task<LaunchResult> Launch(ILogger logger, LaunchServices services, EventHandler<DownloadProgressEventArgs> downloadProgressEventHandler, CancellationToken cancellationToken);
|
||||
}
|
@@ -0,0 +1,55 @@
|
||||
using System.Collections.Immutable;
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Utils.IO;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Minecraft.Launcher.Types;
|
||||
|
||||
public sealed class FabricLauncher : BaseLauncher {
|
||||
public FabricLauncher(InstanceProperties instanceProperties) : base(instanceProperties) {}
|
||||
|
||||
private protected override async Task<ServerJarInfo> PrepareServerJar(ILogger logger, string serverJarPath, CancellationToken cancellationToken) {
|
||||
var serverJarParentFolderPath = Directory.GetParent(serverJarPath);
|
||||
if (serverJarParentFolderPath == null) {
|
||||
throw new ArgumentException("Could not get parent folder from: " + serverJarPath, nameof(serverJarPath));
|
||||
}
|
||||
|
||||
var launcherJarPath = Path.Combine(serverJarParentFolderPath.FullName, "fabric.jar");
|
||||
|
||||
if (!File.Exists(launcherJarPath)) {
|
||||
await DownloadLauncher(logger, launcherJarPath, cancellationToken);
|
||||
}
|
||||
|
||||
return new ServerJarInfo(launcherJarPath, ImmutableArray.Create("-Dfabric.installer.server.gameJar=" + Paths.NormalizeSlashes(serverJarPath)));
|
||||
}
|
||||
|
||||
private async Task DownloadLauncher(ILogger logger, string targetFilePath, CancellationToken cancellationToken) {
|
||||
// TODO customizable loader version, probably with a dedicated temporary folder
|
||||
string installerUrl = $"https://meta.fabricmc.net/v2/versions/loader/{MinecraftVersion}/stable/stable/server/jar";
|
||||
logger.Information("Downloading Fabric launcher from: {Url}", installerUrl);
|
||||
|
||||
using var http = new HttpClient();
|
||||
|
||||
var response = await http.GetAsync(installerUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
try {
|
||||
await using var fileStream = new FileStream(targetFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read);
|
||||
await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken);
|
||||
await responseStream.CopyToAsync(fileStream, cancellationToken);
|
||||
} catch (Exception) {
|
||||
TryDeleteLauncherAfterFailure(logger, targetFilePath);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryDeleteLauncherAfterFailure(ILogger logger, string filePath) {
|
||||
if (File.Exists(filePath)) {
|
||||
try {
|
||||
File.Delete(filePath);
|
||||
} catch (Exception e) {
|
||||
logger.Warning(e, "Could not clean up partially downloaded Fabric launcher: {FilePath}", filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,12 @@
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Agent.Minecraft.Java;
|
||||
|
||||
namespace Phantom.Agent.Minecraft.Launcher.Types;
|
||||
|
||||
public class ForgeLauncher : BaseLauncher {
|
||||
public ForgeLauncher(InstanceProperties instanceProperties) : base(instanceProperties) {}
|
||||
|
||||
private protected override void CustomizeJvmArguments(JvmArgumentBuilder arguments) {
|
||||
arguments.AddProperty("terminal.ansi", "true"); // TODO
|
||||
}
|
||||
}
|
@@ -0,0 +1,14 @@
|
||||
using Phantom.Agent.Minecraft.Server;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Minecraft.Launcher.Types;
|
||||
|
||||
public sealed class InvalidLauncher : IServerLauncher {
|
||||
public static InvalidLauncher Instance { get; } = new ();
|
||||
|
||||
private InvalidLauncher() {}
|
||||
|
||||
public Task<LaunchResult> Launch(ILogger logger, LaunchServices services, EventHandler<DownloadProgressEventArgs> downloadProgressEventHandler, CancellationToken cancellationToken) {
|
||||
return Task.FromResult<LaunchResult>(new LaunchResult.CouldNotPrepareMinecraftServerLauncher());
|
||||
}
|
||||
}
|
@@ -1,5 +1,4 @@
|
||||
using System.Diagnostics;
|
||||
using Phantom.Common.Logging;
|
||||
using Phantom.Common.Logging;
|
||||
using Phantom.Utils.Runtime;
|
||||
using Serilog;
|
||||
|
||||
@@ -41,7 +40,7 @@ static class BackupCompressor {
|
||||
return false;
|
||||
}
|
||||
|
||||
var startInfo = new ProcessStartInfo {
|
||||
var launcher = new ProcessConfigurator {
|
||||
FileName = "zstd",
|
||||
WorkingDirectory = workingDirectory,
|
||||
ArgumentList = {
|
||||
@@ -57,14 +56,14 @@ static class BackupCompressor {
|
||||
}
|
||||
};
|
||||
|
||||
static void OnZstdOutput(object? sender, DataReceivedEventArgs e) {
|
||||
if (!string.IsNullOrWhiteSpace(e.Data)) {
|
||||
ZstdLogger.Debug("[Output] {Line}", e.Data);
|
||||
static void OnZstdOutput(object? sender, Process.Output output) {
|
||||
if (!string.IsNullOrWhiteSpace(output.Line)) {
|
||||
ZstdLogger.Debug("[Output] {Line}", output.Line);
|
||||
}
|
||||
}
|
||||
|
||||
var process = new OneShotProcess(ZstdLogger, startInfo);
|
||||
process.Output += OnZstdOutput;
|
||||
var process = new OneShotProcess(ZstdLogger, launcher);
|
||||
process.OutputReceived += OnZstdOutput;
|
||||
return await process.Run(cancellationToken);
|
||||
}
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Phantom.Agent.Minecraft.Command;
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Utils.Runtime;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Services.Backups;
|
||||
@@ -13,9 +14,9 @@ sealed partial class BackupServerCommandDispatcher : IDisposable {
|
||||
private readonly InstanceProcess process;
|
||||
private readonly CancellationToken cancellationToken;
|
||||
|
||||
private readonly TaskCompletionSource automaticSavingDisabled = new ();
|
||||
private readonly TaskCompletionSource savedTheGame = new ();
|
||||
private readonly TaskCompletionSource automaticSavingEnabled = new ();
|
||||
private readonly TaskCompletionSource automaticSavingDisabled = Tasks.CreateCompletionSource();
|
||||
private readonly TaskCompletionSource savedTheGame = Tasks.CreateCompletionSource();
|
||||
private readonly TaskCompletionSource automaticSavingEnabled = Tasks.CreateCompletionSource();
|
||||
|
||||
public BackupServerCommandDispatcher(ILogger logger, InstanceProcess process, CancellationToken cancellationToken) {
|
||||
this.logger = logger;
|
||||
|
@@ -18,15 +18,10 @@ sealed class Instance : IDisposable {
|
||||
return prefix[..prefix.IndexOf('-')] + "/" + Interlocked.Increment(ref loggerSequenceId);
|
||||
}
|
||||
|
||||
public static Instance Create(InstanceConfiguration configuration, InstanceServices services, BaseLauncher launcher) {
|
||||
var instance = new Instance(configuration, services, launcher);
|
||||
instance.SetStatus(instance.currentStatus);
|
||||
return instance;
|
||||
}
|
||||
|
||||
public InstanceConfiguration Configuration { get; private set; }
|
||||
private InstanceServices Services { get; }
|
||||
private BaseLauncher Launcher { get; set; }
|
||||
|
||||
public InstanceConfiguration Configuration { get; private set; }
|
||||
private IServerLauncher Launcher { get; set; }
|
||||
|
||||
private readonly string shortName;
|
||||
private readonly ILogger logger;
|
||||
@@ -41,29 +36,41 @@ sealed class Instance : IDisposable {
|
||||
|
||||
public event EventHandler? IsRunningChanged;
|
||||
|
||||
private Instance(InstanceConfiguration configuration, InstanceServices services, BaseLauncher launcher) {
|
||||
public Instance(InstanceServices services, InstanceConfiguration configuration, IServerLauncher launcher) {
|
||||
this.shortName = GetLoggerName(configuration.InstanceGuid);
|
||||
this.logger = PhantomLogger.Create<Instance>(shortName);
|
||||
|
||||
this.Configuration = configuration;
|
||||
this.Services = services;
|
||||
this.Configuration = configuration;
|
||||
this.Launcher = launcher;
|
||||
|
||||
this.currentState = new InstanceNotRunningState();
|
||||
this.currentStatus = InstanceStatus.NotRunning;
|
||||
}
|
||||
|
||||
private void SetStatus(IInstanceStatus status) {
|
||||
private void TryUpdateStatus(string taskName, Func<Task> getUpdateTask) {
|
||||
int myStatusUpdateCounter = Interlocked.Increment(ref statusUpdateCounter);
|
||||
|
||||
Services.TaskManager.Run("Report status of instance " + shortName + " as " + status.GetType().Name, async () => {
|
||||
Services.TaskManager.Run(taskName, async () => {
|
||||
if (myStatusUpdateCounter == statusUpdateCounter) {
|
||||
currentStatus = status;
|
||||
await ServerMessaging.Send(new ReportInstanceStatusMessage(Configuration.InstanceGuid, status));
|
||||
await getUpdateTask();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void ReportLastStatus() {
|
||||
TryUpdateStatus("Report last status of instance " + shortName, async () => {
|
||||
await ServerMessaging.Send(new ReportInstanceStatusMessage(Configuration.InstanceGuid, currentStatus));
|
||||
});
|
||||
}
|
||||
|
||||
private void ReportAndSetStatus(IInstanceStatus status) {
|
||||
TryUpdateStatus("Report status of instance " + shortName + " as " + status.GetType().Name, async () => {
|
||||
currentStatus = status;
|
||||
await ServerMessaging.Send(new ReportInstanceStatusMessage(Configuration.InstanceGuid, status));
|
||||
});
|
||||
}
|
||||
|
||||
private void ReportEvent(IInstanceEvent instanceEvent) {
|
||||
var message = new ReportInstanceEventMessage(Guid.NewGuid(), DateTime.UtcNow, Configuration.InstanceGuid, instanceEvent);
|
||||
Services.TaskManager.Run("Report event for instance " + shortName, async () => await ServerMessaging.Send(message));
|
||||
@@ -94,7 +101,7 @@ sealed class Instance : IDisposable {
|
||||
return newStateAndResult.Result;
|
||||
}
|
||||
|
||||
public async Task Reconfigure(InstanceConfiguration configuration, BaseLauncher launcher, CancellationToken cancellationToken) {
|
||||
public async Task Reconfigure(InstanceConfiguration configuration, IServerLauncher launcher, CancellationToken cancellationToken) {
|
||||
await stateTransitioningActionSemaphore.WaitAsync(cancellationToken);
|
||||
try {
|
||||
Configuration = configuration;
|
||||
@@ -147,7 +154,7 @@ sealed class Instance : IDisposable {
|
||||
private readonly Instance instance;
|
||||
private readonly CancellationToken shutdownCancellationToken;
|
||||
|
||||
public InstanceContextImpl(Instance instance, CancellationToken shutdownCancellationToken) : base(instance.Configuration, instance.Launcher, instance.Services) {
|
||||
public InstanceContextImpl(Instance instance, CancellationToken shutdownCancellationToken) : base(instance.Services, instance.Configuration, instance.Launcher) {
|
||||
this.instance = instance;
|
||||
this.shutdownCancellationToken = shutdownCancellationToken;
|
||||
}
|
||||
@@ -156,7 +163,7 @@ sealed class Instance : IDisposable {
|
||||
public override string ShortName => instance.shortName;
|
||||
|
||||
public override void SetStatus(IInstanceStatus newStatus) {
|
||||
instance.SetStatus(newStatus);
|
||||
instance.ReportAndSetStatus(newStatus);
|
||||
}
|
||||
|
||||
public override void ReportEvent(IInstanceEvent instanceEvent) {
|
||||
|
@@ -6,17 +6,17 @@ using Serilog;
|
||||
namespace Phantom.Agent.Services.Instances;
|
||||
|
||||
abstract class InstanceContext {
|
||||
public InstanceConfiguration Configuration { get; }
|
||||
public BaseLauncher Launcher { get; }
|
||||
public InstanceServices Services { get; }
|
||||
public InstanceConfiguration Configuration { get; }
|
||||
public IServerLauncher Launcher { get; }
|
||||
|
||||
public abstract ILogger Logger { get; }
|
||||
public abstract string ShortName { get; }
|
||||
|
||||
protected InstanceContext(InstanceConfiguration configuration, BaseLauncher launcher, InstanceServices services) {
|
||||
protected InstanceContext(InstanceServices services, InstanceConfiguration configuration, IServerLauncher launcher) {
|
||||
Services = services;
|
||||
Configuration = configuration;
|
||||
Launcher = launcher;
|
||||
Services = services;
|
||||
}
|
||||
|
||||
public abstract void SetStatus(IInstanceStatus newStatus);
|
||||
|
@@ -27,7 +27,6 @@ sealed class InstanceSessionManager : IDisposable {
|
||||
private readonly AgentInfo agentInfo;
|
||||
private readonly string basePath;
|
||||
|
||||
private readonly MinecraftServerExecutables minecraftServerExecutables;
|
||||
private readonly InstanceServices instanceServices;
|
||||
private readonly Dictionary<Guid, Instance> instances = new ();
|
||||
|
||||
@@ -38,11 +37,12 @@ sealed class InstanceSessionManager : IDisposable {
|
||||
public InstanceSessionManager(AgentInfo agentInfo, AgentFolders agentFolders, JavaRuntimeRepository javaRuntimeRepository, TaskManager taskManager, BackupManager backupManager) {
|
||||
this.agentInfo = agentInfo;
|
||||
this.basePath = agentFolders.InstancesFolderPath;
|
||||
this.minecraftServerExecutables = new MinecraftServerExecutables(agentFolders.ServerExecutableFolderPath);
|
||||
this.shutdownCancellationToken = shutdownCancellationTokenSource.Token;
|
||||
|
||||
var minecraftServerExecutables = new MinecraftServerExecutables(agentFolders.ServerExecutableFolderPath);
|
||||
var launchServices = new LaunchServices(minecraftServerExecutables, javaRuntimeRepository);
|
||||
var portManager = new PortManager(agentInfo.AllowedServerPorts, agentInfo.AllowedRconPorts);
|
||||
|
||||
this.instanceServices = new InstanceServices(taskManager, portManager, backupManager, launchServices);
|
||||
}
|
||||
|
||||
@@ -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, InstanceLaunchProperties launchProperties, bool launchNow, bool alwaysReportStatus) {
|
||||
return await AcquireSemaphoreAndRun(async () => {
|
||||
var instanceGuid = configuration.InstanceGuid;
|
||||
var instanceFolder = Path.Combine(basePath, instanceGuid.ToString());
|
||||
@@ -94,16 +94,26 @@ sealed class InstanceSessionManager : IDisposable {
|
||||
launchProperties
|
||||
);
|
||||
|
||||
BaseLauncher launcher = new VanillaLauncher(properties);
|
||||
IServerLauncher launcher = configuration.MinecraftServerKind switch {
|
||||
MinecraftServerKind.Vanilla => new VanillaLauncher(properties),
|
||||
MinecraftServerKind.Fabric => new FabricLauncher(properties),
|
||||
_ => InvalidLauncher.Instance
|
||||
};
|
||||
|
||||
if (instances.TryGetValue(instanceGuid, out var instance)) {
|
||||
await instance.Reconfigure(configuration, launcher, shutdownCancellationToken);
|
||||
Logger.Information("Reconfigured instance \"{Name}\" (GUID {Guid}).", configuration.InstanceName, configuration.InstanceGuid);
|
||||
|
||||
if (alwaysReportStatus) {
|
||||
instance.ReportLastStatus();
|
||||
}
|
||||
}
|
||||
else {
|
||||
instances[instanceGuid] = instance = Instance.Create(configuration, instanceServices, launcher);
|
||||
instance.IsRunningChanged += OnInstanceIsRunningChanged;
|
||||
instances[instanceGuid] = instance = new Instance(instanceServices, configuration, launcher);
|
||||
Logger.Information("Created instance \"{Name}\" (GUID {Guid}).", configuration.InstanceName, configuration.InstanceGuid);
|
||||
|
||||
instance.ReportLastStatus();
|
||||
instance.IsRunningChanged += OnInstanceIsRunningChanged;
|
||||
}
|
||||
|
||||
if (launchNow) {
|
||||
|
@@ -33,7 +33,7 @@ public sealed class MessageListener : IMessageToAgentListener {
|
||||
}
|
||||
|
||||
foreach (var configureInstanceMessage in message.InitialInstanceConfigurations) {
|
||||
var result = await HandleConfigureInstance(configureInstanceMessage);
|
||||
var result = await HandleConfigureInstance(configureInstanceMessage, alwaysReportStatus: true);
|
||||
if (!result.Is(ConfigureInstanceResult.Success)) {
|
||||
ShutdownAfterConfigurationFailed(configureInstanceMessage.Configuration);
|
||||
return NoReply.Instance;
|
||||
@@ -59,8 +59,12 @@ public sealed class MessageListener : IMessageToAgentListener {
|
||||
return Task.FromResult(NoReply.Instance);
|
||||
}
|
||||
|
||||
private Task<InstanceActionResult<ConfigureInstanceResult>> HandleConfigureInstance(ConfigureInstanceMessage message, bool alwaysReportStatus) {
|
||||
return agent.InstanceSessionManager.Configure(message.Configuration, message.LaunchProperties, message.LaunchNow, alwaysReportStatus);
|
||||
}
|
||||
|
||||
public async Task<InstanceActionResult<ConfigureInstanceResult>> HandleConfigureInstance(ConfigureInstanceMessage message) {
|
||||
return await agent.InstanceSessionManager.Configure(message.Configuration, message.LaunchProperties, message.LaunchNow);
|
||||
return await HandleConfigureInstance(message, alwaysReportStatus: false);
|
||||
}
|
||||
|
||||
public async Task<InstanceActionResult<LaunchInstanceResult>> HandleLaunchInstance(LaunchInstanceMessage message) {
|
||||
|
@@ -1,5 +1,6 @@
|
||||
namespace Phantom.Common.Data.Minecraft;
|
||||
|
||||
public enum MinecraftServerKind : ushort {
|
||||
Vanilla = 1
|
||||
Vanilla = 1,
|
||||
Fabric = 2
|
||||
}
|
||||
|
@@ -8,6 +8,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Serilog" />
|
||||
<PackageReference Include="Serilog.Sinks.Async" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" />
|
||||
</ItemGroup>
|
||||
|
||||
|
@@ -18,7 +18,7 @@ public static class PhantomLogger {
|
||||
.MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", DefaultLogLevel.Coerce(LogEventLevel.Warning))
|
||||
.Filter.ByExcluding(static e => e.Exception is OperationCanceledException)
|
||||
.Enrich.FromLogContext()
|
||||
.WriteTo.Console(outputTemplate: template, formatProvider: CultureInfo.InvariantCulture, theme: AnsiConsoleTheme.Literate)
|
||||
.WriteTo.Async(c => c.Console(outputTemplate: template, formatProvider: CultureInfo.InvariantCulture, theme: AnsiConsoleTheme.Literate))
|
||||
.CreateLogger();
|
||||
}
|
||||
|
||||
|
@@ -20,6 +20,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Update="Serilog" Version="2.12.0" />
|
||||
<PackageReference Update="Serilog.AspNetCore" Version="6.1.0" />
|
||||
<PackageReference Update="Serilog.Sinks.Async" Version="1.5.0" />
|
||||
<PackageReference Update="Serilog.Sinks.Console" Version="4.1.0" />
|
||||
</ItemGroup>
|
||||
|
||||
|
@@ -9,6 +9,7 @@ using Phantom.Server.Services.Agents;
|
||||
using Phantom.Server.Services.Events;
|
||||
using Phantom.Server.Services.Instances;
|
||||
using Phantom.Utils.Rpc.Message;
|
||||
using Phantom.Utils.Runtime;
|
||||
|
||||
namespace Phantom.Server.Services.Rpc;
|
||||
|
||||
@@ -21,7 +22,7 @@ public sealed class MessageToServerListener : IMessageToServerListener {
|
||||
private readonly InstanceLogManager instanceLogManager;
|
||||
private readonly EventLog eventLog;
|
||||
|
||||
private readonly TaskCompletionSource<Guid> agentGuidWaiter = new ();
|
||||
private readonly TaskCompletionSource<Guid> agentGuidWaiter = Tasks.CreateCompletionSource<Guid>();
|
||||
|
||||
public bool IsDisposed { get; private set; }
|
||||
|
||||
|
@@ -1,4 +1,5 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Phantom.Utils.Runtime;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Utils.Rpc.Message;
|
||||
@@ -15,7 +16,7 @@ public sealed class MessageReplyTracker {
|
||||
|
||||
public uint RegisterReply() {
|
||||
var sequenceId = Interlocked.Increment(ref lastSequenceId);
|
||||
replyTasks[sequenceId] = new TaskCompletionSource<byte[]>(TaskCreationOptions.None);
|
||||
replyTasks[sequenceId] = Tasks.CreateCompletionSource<byte[]>();
|
||||
return sequenceId;
|
||||
}
|
||||
|
||||
|
@@ -43,7 +43,11 @@ public abstract class RpcRuntime<TSocket> where TSocket : ThreadSafeSocket, new(
|
||||
Connect(socket);
|
||||
|
||||
void RunTask() {
|
||||
Run(socket, replyTracker, taskManager);
|
||||
try {
|
||||
Run(socket, replyTracker, taskManager);
|
||||
} catch (Exception e) {
|
||||
runtimeLogger.Error(e, "Caught exception in RPC thread.");
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
|
@@ -1,30 +1,24 @@
|
||||
using System.Diagnostics;
|
||||
using Serilog;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Utils.Runtime;
|
||||
|
||||
public sealed class OneShotProcess {
|
||||
private readonly ILogger logger;
|
||||
private readonly ProcessStartInfo startInfo;
|
||||
private readonly ProcessConfigurator configurator;
|
||||
|
||||
public event DataReceivedEventHandler? Output;
|
||||
public event EventHandler<Process.Output>? OutputReceived;
|
||||
|
||||
public OneShotProcess(ILogger logger, ProcessStartInfo startInfo) {
|
||||
public OneShotProcess(ILogger logger, ProcessConfigurator configurator) {
|
||||
this.logger = logger;
|
||||
this.startInfo = startInfo;
|
||||
this.startInfo.RedirectStandardOutput = true;
|
||||
this.startInfo.RedirectStandardError = true;
|
||||
this.configurator = configurator;
|
||||
}
|
||||
|
||||
public async Task<bool> Run(CancellationToken cancellationToken) {
|
||||
using var process = new Process { StartInfo = startInfo };
|
||||
process.OutputDataReceived += Output;
|
||||
process.ErrorDataReceived += Output;
|
||||
using var process = configurator.CreateProcess();
|
||||
process.OutputReceived += OutputReceived;
|
||||
|
||||
try {
|
||||
process.Start();
|
||||
process.BeginOutputReadLine();
|
||||
process.BeginErrorReadLine();
|
||||
} catch (Exception e) {
|
||||
logger.Error(e, "Caught exception launching process.");
|
||||
return false;
|
||||
|
92
Utils/Phantom.Utils.Runtime/Process.cs
Normal file
92
Utils/Phantom.Utils.Runtime/Process.cs
Normal file
@@ -0,0 +1,92 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Phantom.Utils.Runtime;
|
||||
|
||||
public sealed class Process : IDisposable {
|
||||
public readonly record struct Output(string Line, bool IsError);
|
||||
|
||||
public event EventHandler<Output>? OutputReceived;
|
||||
|
||||
public event EventHandler Exited {
|
||||
add {
|
||||
wrapped.EnableRaisingEvents = true;
|
||||
wrapped.Exited += value;
|
||||
}
|
||||
remove {
|
||||
wrapped.Exited -= value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasExited => wrapped.HasExited;
|
||||
public int ExitCode => wrapped.ExitCode;
|
||||
public StreamWriter StandardInput => wrapped.StandardInput;
|
||||
|
||||
private readonly System.Diagnostics.Process wrapped;
|
||||
|
||||
internal Process(System.Diagnostics.Process wrapped) {
|
||||
this.wrapped = wrapped;
|
||||
}
|
||||
|
||||
public void Start() {
|
||||
if (!OperatingSystem.IsWindows()) {
|
||||
this.wrapped.OutputDataReceived += OnStandardOutputDataReceived;
|
||||
this.wrapped.ErrorDataReceived += OnStandardErrorDataReceived;
|
||||
}
|
||||
|
||||
this.wrapped.Start();
|
||||
|
||||
// https://github.com/dotnet/runtime/issues/81896
|
||||
if (OperatingSystem.IsWindows()) {
|
||||
Task.Factory.StartNew(ReadStandardOutputSynchronously, TaskCreationOptions.LongRunning);
|
||||
Task.Factory.StartNew(ReadStandardErrorSynchronously, TaskCreationOptions.LongRunning);
|
||||
}
|
||||
else {
|
||||
this.wrapped.BeginOutputReadLine();
|
||||
this.wrapped.BeginErrorReadLine();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnStandardOutputDataReceived(object sender, DataReceivedEventArgs e) {
|
||||
OnStandardStreamDataReceived(e.Data, isError: false);
|
||||
}
|
||||
|
||||
private void OnStandardErrorDataReceived(object sender, DataReceivedEventArgs e) {
|
||||
OnStandardStreamDataReceived(e.Data, isError: true);
|
||||
}
|
||||
|
||||
private void OnStandardStreamDataReceived(string? line, bool isError) {
|
||||
if (line != null) {
|
||||
OutputReceived?.Invoke(this, new Output(line, isError));
|
||||
}
|
||||
}
|
||||
|
||||
private void ReadStandardOutputSynchronously() {
|
||||
ReadStandardStreamSynchronously(wrapped.StandardOutput, isError: false);
|
||||
}
|
||||
|
||||
private void ReadStandardErrorSynchronously() {
|
||||
ReadStandardStreamSynchronously(wrapped.StandardError, isError: true);
|
||||
}
|
||||
|
||||
private void ReadStandardStreamSynchronously(StreamReader reader, bool isError) {
|
||||
try {
|
||||
while (reader.ReadLine() is {} line) {
|
||||
OutputReceived?.Invoke(this, new Output(line, isError));
|
||||
}
|
||||
} catch (ObjectDisposedException) {
|
||||
// Ignore.
|
||||
}
|
||||
}
|
||||
|
||||
public Task WaitForExitAsync(CancellationToken cancellationToken) {
|
||||
return wrapped.WaitForExitAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public void Kill(bool entireProcessTree = false) {
|
||||
wrapped.Kill(entireProcessTree);
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
wrapped.Dispose();
|
||||
}
|
||||
}
|
37
Utils/Phantom.Utils.Runtime/ProcessConfigurator.cs
Normal file
37
Utils/Phantom.Utils.Runtime/ProcessConfigurator.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Phantom.Utils.Runtime;
|
||||
|
||||
public sealed class ProcessConfigurator {
|
||||
private readonly ProcessStartInfo startInfo = new () {
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true
|
||||
};
|
||||
|
||||
public string FileName {
|
||||
get => startInfo.FileName;
|
||||
set => startInfo.FileName = value;
|
||||
}
|
||||
|
||||
public Collection<string> ArgumentList => startInfo.ArgumentList;
|
||||
|
||||
public string WorkingDirectory {
|
||||
get => startInfo.WorkingDirectory;
|
||||
set => startInfo.WorkingDirectory = value;
|
||||
}
|
||||
|
||||
public bool RedirectInput {
|
||||
get => startInfo.RedirectStandardInput;
|
||||
set => startInfo.RedirectStandardInput = value;
|
||||
}
|
||||
|
||||
public bool UseShellExecute {
|
||||
get => startInfo.UseShellExecute;
|
||||
set => startInfo.UseShellExecute = value;
|
||||
}
|
||||
|
||||
public Process CreateProcess() {
|
||||
return new Process(new System.Diagnostics.Process { StartInfo = startInfo });
|
||||
}
|
||||
}
|
11
Utils/Phantom.Utils.Runtime/Tasks.cs
Normal file
11
Utils/Phantom.Utils.Runtime/Tasks.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace Phantom.Utils.Runtime;
|
||||
|
||||
public static class Tasks {
|
||||
public static TaskCompletionSource CreateCompletionSource() {
|
||||
return new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
|
||||
public static TaskCompletionSource<T> CreateCompletionSource<T>() {
|
||||
return new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user