mirror of
https://github.com/chylex/Minecraft-Phantom-Panel.git
synced 2026-03-01 05:07:53 +01:00
Compare commits
4 Commits
1983748036
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
21bfdf90ee
|
|||
|
298f9adac2
|
|||
|
e1e8963ff4
|
|||
|
59bcc7d538
|
@@ -6,7 +6,7 @@
|
|||||||
<option name="PASS_PARENT_ENVS" value="1" />
|
<option name="PASS_PARENT_ENVS" value="1" />
|
||||||
<envs>
|
<envs>
|
||||||
<env name="AGENT_KEY_FILE" value="./key" />
|
<env name="AGENT_KEY_FILE" value="./key" />
|
||||||
<env name="ALLOWED_RCON_PORTS" value="25575,27000,27001" />
|
<env name="ALLOWED_ADDITIONAL_PORTS" value="25575,27000,27001" />
|
||||||
<env name="ALLOWED_SERVER_PORTS" value="25565,26000,26001" />
|
<env name="ALLOWED_SERVER_PORTS" value="25565,26000,26001" />
|
||||||
<env name="CONTROLLER_HOST" value="localhost" />
|
<env name="CONTROLLER_HOST" value="localhost" />
|
||||||
<env name="JAVA_SEARCH_PATH" value="~/.jdks" />
|
<env name="JAVA_SEARCH_PATH" value="~/.jdks" />
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
|
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
|
||||||
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="0" />
|
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="0" />
|
||||||
<option name="PROJECT_KIND" value="DotNetCore" />
|
<option name="PROJECT_KIND" value="DotNetCore" />
|
||||||
<option name="PROJECT_TFM" value="net9.0" />
|
<option name="PROJECT_TFM" value="net10.0" />
|
||||||
<method v="2">
|
<method v="2">
|
||||||
<option name="Build" />
|
<option name="Build" />
|
||||||
</method>
|
</method>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
<option name="PASS_PARENT_ENVS" value="1" />
|
<option name="PASS_PARENT_ENVS" value="1" />
|
||||||
<envs>
|
<envs>
|
||||||
<env name="AGENT_KEY_FILE" value="./key" />
|
<env name="AGENT_KEY_FILE" value="./key" />
|
||||||
<env name="ALLOWED_RCON_PORTS" value="27002-27006" />
|
<env name="ALLOWED_ADDITIONAL_PORTS" value="27002-27006" />
|
||||||
<env name="ALLOWED_SERVER_PORTS" value="26002-26006" />
|
<env name="ALLOWED_SERVER_PORTS" value="26002-26006" />
|
||||||
<env name="CONTROLLER_HOST" value="localhost" />
|
<env name="CONTROLLER_HOST" value="localhost" />
|
||||||
<env name="JAVA_SEARCH_PATH" value="~/.jdks" />
|
<env name="JAVA_SEARCH_PATH" value="~/.jdks" />
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
|
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
|
||||||
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="0" />
|
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="0" />
|
||||||
<option name="PROJECT_KIND" value="DotNetCore" />
|
<option name="PROJECT_KIND" value="DotNetCore" />
|
||||||
<option name="PROJECT_TFM" value="net9.0" />
|
<option name="PROJECT_TFM" value="net10.0" />
|
||||||
<method v="2">
|
<method v="2">
|
||||||
<option name="Build" />
|
<option name="Build" />
|
||||||
</method>
|
</method>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
<option name="PASS_PARENT_ENVS" value="1" />
|
<option name="PASS_PARENT_ENVS" value="1" />
|
||||||
<envs>
|
<envs>
|
||||||
<env name="AGENT_KEY_FILE" value="./key" />
|
<env name="AGENT_KEY_FILE" value="./key" />
|
||||||
<env name="ALLOWED_RCON_PORTS" value="27007" />
|
<env name="ALLOWED_ADDITIONAL_PORTS" value="27007" />
|
||||||
<env name="ALLOWED_SERVER_PORTS" value="26007" />
|
<env name="ALLOWED_SERVER_PORTS" value="26007" />
|
||||||
<env name="CONTROLLER_HOST" value="localhost" />
|
<env name="CONTROLLER_HOST" value="localhost" />
|
||||||
<env name="JAVA_SEARCH_PATH" value="~/.jdks" />
|
<env name="JAVA_SEARCH_PATH" value="~/.jdks" />
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
|
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
|
||||||
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="0" />
|
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="0" />
|
||||||
<option name="PROJECT_KIND" value="DotNetCore" />
|
<option name="PROJECT_KIND" value="DotNetCore" />
|
||||||
<option name="PROJECT_TFM" value="net9.0" />
|
<option name="PROJECT_TFM" value="net10.0" />
|
||||||
<method v="2">
|
<method v="2">
|
||||||
<option name="Build" />
|
<option name="Build" />
|
||||||
</method>
|
</method>
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
namespace Phantom.Agent.Minecraft.Command;
|
|
||||||
|
|
||||||
public static class MinecraftCommand {
|
|
||||||
public const string SaveOn = "save-on";
|
|
||||||
public const string SaveOff = "save-off";
|
|
||||||
public const string Stop = "stop";
|
|
||||||
|
|
||||||
public static string Say(string message) {
|
|
||||||
return "say " + message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static string SaveAll(bool flush) {
|
|
||||||
return flush ? "save-all flush" : "save-all";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
namespace Phantom.Agent.Minecraft.Instance;
|
|
||||||
|
|
||||||
public sealed record InstanceProperties(
|
|
||||||
Guid InstanceGuid,
|
|
||||||
string InstanceFolder
|
|
||||||
);
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
using Phantom.Common.Data.Java;
|
|
||||||
|
|
||||||
namespace Phantom.Agent.Minecraft.Java;
|
|
||||||
|
|
||||||
public sealed record JavaRuntimeExecutable(string ExecutablePath, JavaRuntime Runtime);
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
using System.Collections.ObjectModel;
|
|
||||||
|
|
||||||
namespace Phantom.Agent.Minecraft.Java;
|
|
||||||
|
|
||||||
sealed class JvmArgumentBuilder(JvmProperties basicProperties) {
|
|
||||||
private readonly List<string> customArguments = [];
|
|
||||||
|
|
||||||
public void Add(string argument) {
|
|
||||||
customArguments.Add(argument);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void AddProperty(string key, string value) {
|
|
||||||
customArguments.Add("-D" + key + "=\"" + value + "\""); // TODO test quoting?
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Build(Collection<string> target) {
|
|
||||||
foreach (var property in customArguments) {
|
|
||||||
target.Add(property);
|
|
||||||
}
|
|
||||||
|
|
||||||
// In case of duplicate JVM arguments, typically the last one wins.
|
|
||||||
target.Add("-Xms" + basicProperties.InitialHeapMegabytes + "M");
|
|
||||||
target.Add("-Xmx" + basicProperties.MaximumHeapMegabytes + "M");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
namespace Phantom.Agent.Minecraft.Java;
|
|
||||||
|
|
||||||
public sealed record JvmProperties(
|
|
||||||
uint InitialHeapMegabytes,
|
|
||||||
uint MaximumHeapMegabytes
|
|
||||||
);
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
using System.Collections.Immutable;
|
|
||||||
using Phantom.Agent.Minecraft.Instance;
|
|
||||||
using Phantom.Agent.Minecraft.Java;
|
|
||||||
using Phantom.Agent.Minecraft.Server;
|
|
||||||
using Phantom.Common.Data.Instance;
|
|
||||||
using Phantom.Common.Data.Instance.Launch;
|
|
||||||
using Phantom.Common.Data.Minecraft;
|
|
||||||
using Phantom.Utils.Processes;
|
|
||||||
using Serilog;
|
|
||||||
|
|
||||||
namespace Phantom.Agent.Minecraft.Launcher;
|
|
||||||
|
|
||||||
public sealed class InstanceLauncher(
|
|
||||||
FileDownloadManager downloadManager,
|
|
||||||
IInstancePathResolver pathResolver,
|
|
||||||
IInstanceValueResolver valueResolver,
|
|
||||||
InstanceProperties instanceProperties,
|
|
||||||
InstanceLaunchRecipe launchRecipe
|
|
||||||
) {
|
|
||||||
public async Task<LaunchResult> Launch(ILogger logger, Action<IInstanceStatus?> reportStatus, CancellationToken cancellationToken) {
|
|
||||||
string? executablePath = launchRecipe.Executable.Resolve(pathResolver);
|
|
||||||
if (executablePath == null) {
|
|
||||||
logger.Error("Could not resolve server executable: {Path}", launchRecipe.Executable);
|
|
||||||
return new LaunchResult.CouldNotFindServerExecutable();
|
|
||||||
}
|
|
||||||
|
|
||||||
var stepVisitor = new StepExecutor(downloadManager, pathResolver, reportStatus, cancellationToken);
|
|
||||||
var steps = launchRecipe.Preparation;
|
|
||||||
|
|
||||||
for (int stepIndex = 0; stepIndex < steps.Length; stepIndex++) {
|
|
||||||
var step = steps[stepIndex];
|
|
||||||
try {
|
|
||||||
await step.Run(stepVisitor);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.Error(e, "Failed preparation step {StepIndex} out of {StepCount}: {Step}", stepIndex, steps.Length, step);
|
|
||||||
return new LaunchResult.CouldNotPrepareServerInstance();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var processConfigurator = new ProcessConfigurator {
|
|
||||||
FileName = executablePath,
|
|
||||||
WorkingDirectory = instanceProperties.InstanceFolder,
|
|
||||||
RedirectInput = true,
|
|
||||||
UseShellExecute = false,
|
|
||||||
};
|
|
||||||
|
|
||||||
var processArguments = processConfigurator.ArgumentList;
|
|
||||||
|
|
||||||
foreach (var value in launchRecipe.Arguments) {
|
|
||||||
if (value.Resolve(valueResolver) is {} resolved) {
|
|
||||||
processArguments.Add(resolved);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
logger.Error("Could not resolve server executable argument: {Value}", value);
|
|
||||||
return new LaunchResult.CouldNotPrepareServerInstance();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var process = processConfigurator.CreateProcess();
|
|
||||||
var instanceProcess = new InstanceProcess(instanceProperties, process);
|
|
||||||
|
|
||||||
try {
|
|
||||||
process.Start();
|
|
||||||
} catch (Exception launchException) {
|
|
||||||
logger.Error(launchException, "Caught exception launching the server process.");
|
|
||||||
|
|
||||||
try {
|
|
||||||
process.Kill();
|
|
||||||
} catch (Exception killException) {
|
|
||||||
logger.Error(killException, "Caught exception trying to kill the server process after a failed launch.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return new LaunchResult.CouldNotStartServerExecutable();
|
|
||||||
}
|
|
||||||
|
|
||||||
return new LaunchResult.Success(instanceProcess);
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class StepExecutor(FileDownloadManager downloadManager, IInstancePathResolver pathResolver, Action<IInstanceStatus?> reportStatus, CancellationToken cancellationToken) : IInstanceLaunchStepExecutor {
|
|
||||||
public async Task DownloadFile(FileDownloadInfo downloadInfo, IInstancePath path) {
|
|
||||||
string? filePath = path.Resolve(pathResolver);
|
|
||||||
if (filePath == null) {
|
|
||||||
throw new FileNotFoundException("Could not resolve path");
|
|
||||||
}
|
|
||||||
|
|
||||||
byte? lastDownloadProgress = null;
|
|
||||||
|
|
||||||
void OnDownloadProgress(object? sender, DownloadProgressEventArgs args) {
|
|
||||||
byte? progress = args.TotalBytes is not {} totalBytes ? null : (byte) Math.Min(args.DownloadedBytes * 100 / totalBytes, val2: 100);
|
|
||||||
|
|
||||||
if (lastDownloadProgress != progress) {
|
|
||||||
lastDownloadProgress = progress;
|
|
||||||
reportStatus(InstanceStatus.Downloading(progress));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (await downloadManager.DownloadAndGetPath(downloadInfo, filePath, OnDownloadProgress, cancellationToken) == null) {
|
|
||||||
throw new FileNotFoundException("Could not download file");
|
|
||||||
}
|
|
||||||
|
|
||||||
reportStatus(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task EditPropertiesFile(InstancePath.Local path, string comment, ImmutableDictionary<string, string> newValues) {
|
|
||||||
string? filePath = path.Resolve(pathResolver);
|
|
||||||
if (filePath == null) {
|
|
||||||
throw new FileNotFoundException("Could not resolve path");
|
|
||||||
}
|
|
||||||
|
|
||||||
var editor = new JavaPropertiesFileEditor();
|
|
||||||
editor.SetAll(newValues);
|
|
||||||
await editor.EditOrCreate(filePath, comment, cancellationToken);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
using Phantom.Agent.Minecraft.Instance;
|
|
||||||
|
|
||||||
namespace Phantom.Agent.Minecraft.Launcher;
|
|
||||||
|
|
||||||
public abstract record LaunchResult {
|
|
||||||
private LaunchResult() {}
|
|
||||||
|
|
||||||
public sealed record Success(InstanceProcess Process) : LaunchResult;
|
|
||||||
|
|
||||||
public sealed record CouldNotPrepareServerInstance : LaunchResult;
|
|
||||||
|
|
||||||
public sealed record CouldNotFindServerExecutable : LaunchResult;
|
|
||||||
|
|
||||||
public sealed record CouldNotStartServerExecutable : LaunchResult;
|
|
||||||
}
|
|
||||||
@@ -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) {}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<InternalsVisibleTo Include="Phantom.Agent.Minecraft.Tests" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\..\Common\Phantom.Common.Data\Phantom.Common.Data.csproj" />
|
|
||||||
<ProjectReference Include="..\..\Utils\Phantom.Utils\Phantom.Utils.csproj" />
|
|
||||||
<ProjectReference Include="..\..\Utils\Phantom.Utils.Logging\Phantom.Utils.Logging.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using NUnit.Framework;
|
using NUnit.Framework;
|
||||||
using Phantom.Agent.Minecraft.Java;
|
using Phantom.Agent.Services.Java;
|
||||||
using Phantom.Utils.Collections;
|
using Phantom.Utils.Collections;
|
||||||
|
|
||||||
namespace Phantom.Agent.Minecraft.Tests.Java;
|
namespace Phantom.Agent.Services.Tests.Java;
|
||||||
|
|
||||||
[TestFixture]
|
[TestFixture]
|
||||||
public sealed class JavaPropertiesStreamTests {
|
public sealed class JavaPropertiesStreamTests {
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Phantom.Agent.Minecraft\Phantom.Agent.Minecraft.csproj" />
|
<ProjectReference Include="..\Phantom.Agent.Services\Phantom.Agent.Services.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -79,6 +79,7 @@ public sealed class AgentRegistrationHandler {
|
|||||||
configureInstanceMessage.Info,
|
configureInstanceMessage.Info,
|
||||||
configureInstanceMessage.LaunchRecipe,
|
configureInstanceMessage.LaunchRecipe,
|
||||||
configureInstanceMessage.LaunchNow,
|
configureInstanceMessage.LaunchNow,
|
||||||
|
configureInstanceMessage.StopRecipe,
|
||||||
AlwaysReportStatus: true
|
AlwaysReportStatus: true
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
using Akka.Actor;
|
using Akka.Actor;
|
||||||
using Phantom.Agent.Minecraft.Java;
|
|
||||||
using Phantom.Agent.Services.Backups;
|
using Phantom.Agent.Services.Backups;
|
||||||
using Phantom.Agent.Services.Instances;
|
using Phantom.Agent.Services.Instances;
|
||||||
|
using Phantom.Agent.Services.Java;
|
||||||
using Phantom.Agent.Services.Rpc;
|
using Phantom.Agent.Services.Rpc;
|
||||||
using Phantom.Common.Data.Agent;
|
using Phantom.Common.Data.Agent;
|
||||||
using Phantom.Utils.Actor;
|
using Phantom.Utils.Actor;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.Formats.Tar;
|
using System.Formats.Tar;
|
||||||
using Phantom.Agent.Minecraft.Instance;
|
using Phantom.Agent.Services.Instances;
|
||||||
using Phantom.Common.Data.Backups;
|
using Phantom.Common.Data.Backups;
|
||||||
using Phantom.Utils.IO;
|
using Phantom.Utils.IO;
|
||||||
using Phantom.Utils.Logging;
|
using Phantom.Utils.Logging;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
using Phantom.Agent.Minecraft.Instance;
|
using Phantom.Agent.Services.Instances.State;
|
||||||
using Phantom.Common.Data.Backups;
|
using Phantom.Common.Data.Backups;
|
||||||
using Phantom.Utils.Logging;
|
using Phantom.Utils.Logging;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using Phantom.Agent.Minecraft.Command;
|
using Phantom.Agent.Services.Games;
|
||||||
using Phantom.Agent.Minecraft.Instance;
|
using Phantom.Agent.Services.Instances.State;
|
||||||
using Phantom.Utils.Tasks;
|
using Phantom.Utils.Tasks;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
namespace Phantom.Agent.Minecraft.Server;
|
namespace Phantom.Agent.Services.Downloads;
|
||||||
|
|
||||||
public sealed class DownloadProgressEventArgs : EventArgs {
|
sealed class DownloadProgressEventArgs : EventArgs {
|
||||||
public ulong DownloadedBytes { get; }
|
public ulong DownloadedBytes { get; }
|
||||||
public ulong? TotalBytes { get; }
|
public ulong? TotalBytes { get; }
|
||||||
|
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
namespace Phantom.Agent.Minecraft.Server;
|
namespace Phantom.Agent.Services.Downloads;
|
||||||
|
|
||||||
sealed record FileDownloadListener(EventHandler<DownloadProgressEventArgs> DownloadProgressEventHandler, CancellationToken CancellationToken);
|
sealed record FileDownloadListener(EventHandler<DownloadProgressEventArgs> DownloadProgressEventHandler, CancellationToken CancellationToken);
|
||||||
@@ -1,16 +1,16 @@
|
|||||||
using Phantom.Common.Data.Minecraft;
|
using Phantom.Common.Data.Agent;
|
||||||
using Phantom.Utils.IO;
|
using Phantom.Utils.IO;
|
||||||
using Phantom.Utils.Logging;
|
using Phantom.Utils.Logging;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
|
|
||||||
namespace Phantom.Agent.Minecraft.Server;
|
namespace Phantom.Agent.Services.Downloads;
|
||||||
|
|
||||||
public sealed class FileDownloadManager {
|
sealed class FileDownloadManager {
|
||||||
private static readonly ILogger Logger = PhantomLogger.Create<FileDownloadManager>();
|
private static readonly ILogger Logger = PhantomLogger.Create<FileDownloadManager>();
|
||||||
|
|
||||||
private readonly Dictionary<string, FileDownloader> runningDownloadersByPath = new ();
|
private readonly Dictionary<string, FileDownloader> runningDownloadersByPath = new ();
|
||||||
|
|
||||||
internal async Task<string?> DownloadAndGetPath(FileDownloadInfo fileDownloadInfo, string filePath, EventHandler<DownloadProgressEventArgs> progressEventHandler, CancellationToken cancellationToken) {
|
public async Task<string?> DownloadAndGetPath(FileDownloadInfo fileDownloadInfo, string filePath, EventHandler<DownloadProgressEventArgs> progressEventHandler, CancellationToken cancellationToken) {
|
||||||
var fileInfo = new FileInfo(filePath);
|
var fileInfo = new FileInfo(filePath);
|
||||||
if (fileInfo.Exists) {
|
if (fileInfo.Exists) {
|
||||||
return filePath;
|
return filePath;
|
||||||
@@ -1,13 +1,12 @@
|
|||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using Phantom.Common.Data.Minecraft;
|
using Phantom.Common.Data.Agent;
|
||||||
using Phantom.Utils.Cryptography;
|
using Phantom.Utils.Cryptography;
|
||||||
using Phantom.Utils.IO;
|
using Phantom.Utils.IO;
|
||||||
using Phantom.Utils.Logging;
|
using Phantom.Utils.Logging;
|
||||||
using Phantom.Utils.Net;
|
|
||||||
using Phantom.Utils.Runtime;
|
using Phantom.Utils.Runtime;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
|
|
||||||
namespace Phantom.Agent.Minecraft.Server;
|
namespace Phantom.Agent.Services.Downloads;
|
||||||
|
|
||||||
sealed class FileDownloader {
|
sealed class FileDownloader {
|
||||||
private static readonly ILogger Logger = PhantomLogger.Create<FileDownloader>();
|
private static readonly ILogger Logger = PhantomLogger.Create<FileDownloader>();
|
||||||
@@ -103,7 +102,7 @@ sealed class FileDownloader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static async Task DownloadFile(string filePath, FileDownloadInfo fileDownloadInfo, DownloadProgressCallback progressCallback, CancellationToken cancellationToken) {
|
private static async Task DownloadFile(string filePath, FileDownloadInfo fileDownloadInfo, DownloadProgressCallback progressCallback, CancellationToken cancellationToken) {
|
||||||
string downloadUrl = fileDownloadInfo.DownloadUrl;
|
string downloadUrl = fileDownloadInfo.Url;
|
||||||
|
|
||||||
DownloadResult result;
|
DownloadResult result;
|
||||||
try {
|
try {
|
||||||
@@ -111,7 +110,7 @@ sealed class FileDownloader {
|
|||||||
var response = await httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
var response = await httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||||
response.EnsureSuccessStatusCode();
|
response.EnsureSuccessStatusCode();
|
||||||
|
|
||||||
FileSize? fileSize = response.Headers.ContentLength;
|
FileSize? fileSize = response.Content.Headers.ContentLength is {} length and >= 0 ? new FileSize((ulong) length) : null;
|
||||||
ulong? fileSizeBytes = fileSize?.Bytes;
|
ulong? fileSizeBytes = fileSize?.Bytes;
|
||||||
|
|
||||||
Logger.Information("Downloading {Url} ({Size})...", downloadUrl, FormatFileSize(fileSize));
|
Logger.Information("Downloading {Url} ({Size})...", downloadUrl, FormatFileSize(fileSize));
|
||||||
10
Agent/Phantom.Agent.Services/Games/MinecraftCommand.cs
Normal file
10
Agent/Phantom.Agent.Services/Games/MinecraftCommand.cs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
namespace Phantom.Agent.Services.Games;
|
||||||
|
|
||||||
|
static class MinecraftCommand {
|
||||||
|
public const string SaveOn = "save-on";
|
||||||
|
public const string SaveOff = "save-off";
|
||||||
|
|
||||||
|
public static string SaveAll(bool flush) {
|
||||||
|
return flush ? "save-all flush" : "save-all";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,9 +5,9 @@ using System.Net.Sockets;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using Phantom.Common.Data.Instance;
|
using Phantom.Common.Data.Instance;
|
||||||
|
|
||||||
namespace Phantom.Agent.Minecraft.Server;
|
namespace Phantom.Agent.Services.Games;
|
||||||
|
|
||||||
public static class ServerStatusProtocol {
|
static class MinecraftServerStatusProtocol {
|
||||||
public static async Task<InstancePlayerCounts> GetPlayerCounts(ushort serverPort, CancellationToken cancellationToken) {
|
public static async Task<InstancePlayerCounts> GetPlayerCounts(ushort serverPort, CancellationToken cancellationToken) {
|
||||||
using var tcpClient = new TcpClient();
|
using var tcpClient = new TcpClient();
|
||||||
await tcpClient.ConnectAsync(IPAddress.Loopback, serverPort, cancellationToken);
|
await tcpClient.ConnectAsync(IPAddress.Loopback, serverPort, cancellationToken);
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
using Phantom.Agent.Minecraft.Launcher;
|
using Phantom.Agent.Services.Backups;
|
||||||
using Phantom.Agent.Services.Backups;
|
using Phantom.Agent.Services.Instances.Launch;
|
||||||
using Phantom.Agent.Services.Instances.State;
|
using Phantom.Agent.Services.Instances.State;
|
||||||
using Phantom.Agent.Services.Rpc;
|
using Phantom.Agent.Services.Rpc;
|
||||||
|
using Phantom.Common.Data.Agent.Instance;
|
||||||
|
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||||
using Phantom.Common.Data.Backups;
|
using Phantom.Common.Data.Backups;
|
||||||
using Phantom.Common.Data.Instance;
|
using Phantom.Common.Data.Instance;
|
||||||
using Phantom.Common.Data.Minecraft;
|
|
||||||
using Phantom.Common.Data.Replies;
|
using Phantom.Common.Data.Replies;
|
||||||
using Phantom.Common.Messages.Agent.ToController;
|
using Phantom.Common.Messages.Agent.ToController;
|
||||||
using Phantom.Utils.Actor;
|
using Phantom.Utils.Actor;
|
||||||
@@ -84,7 +85,7 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
|||||||
|
|
||||||
public sealed record LaunchInstanceCommand(InstanceInfo Info, InstanceLauncher Launcher, InstanceTicketManager.Ticket Ticket, bool IsRestarting) : ICommand;
|
public sealed record LaunchInstanceCommand(InstanceInfo Info, InstanceLauncher Launcher, InstanceTicketManager.Ticket Ticket, bool IsRestarting) : ICommand;
|
||||||
|
|
||||||
public sealed record StopInstanceCommand(MinecraftStopStrategy StopStrategy) : ICommand;
|
public sealed record StopInstanceCommand(InstanceStopRecipe StopRecipe) : ICommand;
|
||||||
|
|
||||||
public sealed record SendCommandToInstanceCommand(string Command) : ICommand, ICanReply<SendCommandToInstanceResult>;
|
public sealed record SendCommandToInstanceCommand(string Command) : ICommand, ICanReply<SendCommandToInstanceResult>;
|
||||||
|
|
||||||
@@ -92,7 +93,7 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
|||||||
|
|
||||||
public sealed record HandleProcessEndedCommand(IInstanceStatus Status) : ICommand, IJumpAhead;
|
public sealed record HandleProcessEndedCommand(IInstanceStatus Status) : ICommand, IJumpAhead;
|
||||||
|
|
||||||
public sealed record ShutdownCommand : ICommand;
|
public sealed record ShutdownCommand(InstanceStopRecipe StopRecipe) : ICommand;
|
||||||
|
|
||||||
private void ReportInstanceStatus(ReportInstanceStatusCommand command) {
|
private void ReportInstanceStatus(ReportInstanceStatusCommand command) {
|
||||||
ReportCurrentStatus();
|
ReportCurrentStatus();
|
||||||
@@ -124,7 +125,7 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
|||||||
IInstanceStatus oldStatus = currentStatus;
|
IInstanceStatus oldStatus = currentStatus;
|
||||||
SetAndReportStatus(InstanceStatus.Stopping);
|
SetAndReportStatus(InstanceStatus.Stopping);
|
||||||
|
|
||||||
if (await InstanceStopProcedure.Run(context, command.StopStrategy, runningState, SetAndReportStatus, shutdownCancellationToken)) {
|
if (await InstanceStopProcedure.Run(context, command.StopRecipe, runningState, SetAndReportStatus, shutdownCancellationToken)) {
|
||||||
instanceTicketManager.Release(runningState.Ticket);
|
instanceTicketManager.Release(runningState.Ticket);
|
||||||
TransitionState(null);
|
TransitionState(null);
|
||||||
}
|
}
|
||||||
@@ -166,7 +167,7 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async Task Shutdown(ShutdownCommand command) {
|
private async Task Shutdown(ShutdownCommand command) {
|
||||||
await StopInstance(new StopInstanceCommand(MinecraftStopStrategy.Instant));
|
await StopInstance(new StopInstanceCommand(command.StopRecipe));
|
||||||
await actorCancellationTokenSource.CancelAsync();
|
await actorCancellationTokenSource.CancelAsync();
|
||||||
|
|
||||||
await Task.WhenAll(
|
await Task.WhenAll(
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
using Phantom.Agent.Minecraft.Instance;
|
using Phantom.Agent.Services.Backups;
|
||||||
using Phantom.Agent.Minecraft.Java;
|
using Phantom.Agent.Services.Downloads;
|
||||||
using Phantom.Agent.Minecraft.Launcher;
|
using Phantom.Agent.Services.Instances.Launch;
|
||||||
using Phantom.Agent.Minecraft.Server;
|
using Phantom.Agent.Services.Java;
|
||||||
using Phantom.Agent.Services.Backups;
|
|
||||||
using Phantom.Agent.Services.Rpc;
|
using Phantom.Agent.Services.Rpc;
|
||||||
using Phantom.Common.Data;
|
using Phantom.Common.Data;
|
||||||
|
using Phantom.Common.Data.Agent.Instance;
|
||||||
|
using Phantom.Common.Data.Agent.Instance.Launch;
|
||||||
|
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||||
using Phantom.Common.Data.Instance;
|
using Phantom.Common.Data.Instance;
|
||||||
using Phantom.Common.Data.Instance.Launch;
|
|
||||||
using Phantom.Common.Data.Minecraft;
|
|
||||||
using Phantom.Common.Data.Replies;
|
using Phantom.Common.Data.Replies;
|
||||||
using Phantom.Utils.Actor;
|
using Phantom.Utils.Actor;
|
||||||
using Phantom.Utils.IO;
|
using Phantom.Utils.IO;
|
||||||
@@ -52,15 +52,15 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
|||||||
ReceiveAsync<ShutdownCommand>(Shutdown);
|
ReceiveAsync<ShutdownCommand>(Shutdown);
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed record Instance(ActorRef<InstanceActor.ICommand> Actor, InstanceInfo Info, InstanceProperties Properties, InstanceLaunchRecipe? LaunchRecipe);
|
private sealed record Instance(ActorRef<InstanceActor.ICommand> Actor, InstanceInfo Info, InstanceProperties Properties, InstanceLaunchRecipe? LaunchRecipe, InstanceStopRecipe StopRecipe);
|
||||||
|
|
||||||
public interface ICommand;
|
public interface ICommand;
|
||||||
|
|
||||||
public sealed record ConfigureInstanceCommand(Guid InstanceGuid, InstanceInfo Info, InstanceLaunchRecipe? LaunchRecipe, bool LaunchNow, bool AlwaysReportStatus) : ICommand, ICanReply<Result<ConfigureInstanceResult, InstanceActionFailure>>;
|
public sealed record ConfigureInstanceCommand(Guid InstanceGuid, InstanceInfo InstanceInfo, InstanceLaunchRecipe? LaunchRecipe, bool LaunchNow, InstanceStopRecipe StopRecipe, bool AlwaysReportStatus) : ICommand, ICanReply<Result<ConfigureInstanceResult, InstanceActionFailure>>;
|
||||||
|
|
||||||
public sealed record LaunchInstanceCommand(Guid InstanceGuid) : ICommand, ICanReply<Result<LaunchInstanceResult, InstanceActionFailure>>;
|
public sealed record LaunchInstanceCommand(Guid InstanceGuid) : ICommand, ICanReply<Result<LaunchInstanceResult, InstanceActionFailure>>;
|
||||||
|
|
||||||
public sealed record StopInstanceCommand(Guid InstanceGuid, MinecraftStopStrategy StopStrategy) : ICommand, ICanReply<Result<StopInstanceResult, InstanceActionFailure>>;
|
public sealed record StopInstanceCommand(Guid InstanceGuid, InstanceStopRecipe StopRecipe) : ICommand, ICanReply<Result<StopInstanceResult, InstanceActionFailure>>;
|
||||||
|
|
||||||
public sealed record SendCommandToInstanceCommand(Guid InstanceGuid, string Command) : ICommand, ICanReply<Result<SendCommandToInstanceResult, InstanceActionFailure>>;
|
public sealed record SendCommandToInstanceCommand(Guid InstanceGuid, string Command) : ICommand, ICanReply<Result<SendCommandToInstanceResult, InstanceActionFailure>>;
|
||||||
|
|
||||||
@@ -68,13 +68,15 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
|||||||
|
|
||||||
private Result<ConfigureInstanceResult, InstanceActionFailure> ConfigureInstance(ConfigureInstanceCommand command) {
|
private Result<ConfigureInstanceResult, InstanceActionFailure> ConfigureInstance(ConfigureInstanceCommand command) {
|
||||||
var instanceGuid = command.InstanceGuid;
|
var instanceGuid = command.InstanceGuid;
|
||||||
var instanceInfo = command.Info;
|
var instanceInfo = command.InstanceInfo;
|
||||||
var launchRecipe = command.LaunchRecipe;
|
var launchRecipe = command.LaunchRecipe;
|
||||||
|
var stopRecipe = command.StopRecipe;
|
||||||
|
|
||||||
if (instances.TryGetValue(instanceGuid, out var instance)) {
|
if (instances.TryGetValue(instanceGuid, out var instance)) {
|
||||||
instances[instanceGuid] = instance with {
|
instances[instanceGuid] = instance with {
|
||||||
Info = instanceInfo,
|
Info = instanceInfo,
|
||||||
LaunchRecipe = launchRecipe,
|
LaunchRecipe = launchRecipe,
|
||||||
|
StopRecipe = stopRecipe,
|
||||||
};
|
};
|
||||||
|
|
||||||
Logger.Information("Reconfigured instance \"{Name}\" (GUID {Guid}).", instanceInfo.InstanceName, instanceGuid);
|
Logger.Information("Reconfigured instance \"{Name}\" (GUID {Guid}).", instanceInfo.InstanceName, instanceGuid);
|
||||||
@@ -85,20 +87,20 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
|||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
var instanceLoggerName = PhantomLogger.ShortenGuid(instanceGuid) + "/" + Interlocked.Increment(ref instanceLoggerSequenceId);
|
var instanceLoggerName = PhantomLogger.ShortenGuid(instanceGuid) + "/" + Interlocked.Increment(ref instanceLoggerSequenceId);
|
||||||
var instanceProperties = new InstanceProperties(instanceGuid, Path.Combine(agentFolders.InstancesFolderPath, instanceGuid.ToString()));
|
var instanceFolder = Path.Combine(agentFolders.InstancesFolderPath, instanceGuid.ToString());
|
||||||
|
var instanceProperties = new InstanceProperties(instanceGuid, instanceFolder);
|
||||||
var instanceInit = new InstanceActor.Init(agentState, instanceGuid, instanceLoggerName, instanceServices, instanceTicketManager, shutdownCancellationToken);
|
var instanceInit = new InstanceActor.Init(agentState, instanceGuid, instanceLoggerName, instanceServices, instanceTicketManager, shutdownCancellationToken);
|
||||||
instances[instanceGuid] = instance = new Instance(Context.ActorOf(InstanceActor.Factory(instanceInit), "Instance-" + instanceGuid), instanceInfo, instanceProperties, launchRecipe);
|
instances[instanceGuid] = instance = new Instance(Context.ActorOf(InstanceActor.Factory(instanceInit), "Instance-" + instanceGuid), instanceInfo, instanceProperties, launchRecipe, stopRecipe);
|
||||||
|
|
||||||
Logger.Information("Created instance \"{Name}\" (GUID {Guid}).", instanceInfo.InstanceName, instanceGuid);
|
Logger.Information("Created instance \"{Name}\" (GUID {Guid}).", instanceInfo.InstanceName, instanceGuid);
|
||||||
|
|
||||||
instance.Actor.Tell(new InstanceActor.ReportInstanceStatusCommand());
|
instance.Actor.Tell(new InstanceActor.ReportInstanceStatusCommand());
|
||||||
}
|
}
|
||||||
|
|
||||||
string instanceFolder = instance.Properties.InstanceFolder;
|
|
||||||
try {
|
try {
|
||||||
Directories.Create(instanceFolder, Chmod.URWX_GRX);
|
Directories.Create(instance.Properties.InstanceFolder, Chmod.URWX_GRX);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Logger.Error(e, "Could not create instance folder: {Path}", instanceFolder);
|
Logger.Error(e, "Could not create instance folder: {Path}", instance.Properties.InstanceFolder);
|
||||||
return ConfigureInstanceResult.CouldNotCreateInstanceFolder;
|
return ConfigureInstanceResult.CouldNotCreateInstanceFolder;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,7 +161,7 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
instanceInfo.Actor.Tell(new InstanceActor.StopInstanceCommand(command.StopStrategy));
|
instanceInfo.Actor.Tell(new InstanceActor.StopInstanceCommand(command.StopRecipe));
|
||||||
return StopInstanceResult.StopInitiated;
|
return StopInstanceResult.StopInitiated;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,7 +183,7 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
|||||||
|
|
||||||
await shutdownCancellationTokenSource.CancelAsync();
|
await shutdownCancellationTokenSource.CancelAsync();
|
||||||
|
|
||||||
await Task.WhenAll(instances.Values.Select(static instance => instance.Actor.Stop(new InstanceActor.ShutdownCommand())));
|
await Task.WhenAll(instances.Values.Select(static instance => instance.Actor.Stop(new InstanceActor.ShutdownCommand(instance.StopRecipe))));
|
||||||
instances.Clear();
|
instances.Clear();
|
||||||
|
|
||||||
shutdownCancellationTokenSource.Dispose();
|
shutdownCancellationTokenSource.Dispose();
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
using System.Collections.Immutable;
|
|
||||||
using Phantom.Agent.Minecraft.Instance;
|
|
||||||
using Phantom.Agent.Minecraft.Java;
|
|
||||||
using Phantom.Common.Data.Instance;
|
|
||||||
|
|
||||||
namespace Phantom.Agent.Services.Instances;
|
|
||||||
|
|
||||||
sealed class InstancePathResolver(AgentFolders agentFolders, JavaRuntimeRepository javaRuntimeRepository, InstanceProperties instanceProperties) : IInstancePathResolver {
|
|
||||||
public string Global(ImmutableArray<string> path) {
|
|
||||||
return CombinePath(agentFolders.ServerExecutableFolderPath, path);
|
|
||||||
}
|
|
||||||
|
|
||||||
public string Local(ImmutableArray<string> path) {
|
|
||||||
return CombinePath(instanceProperties.InstanceFolder, path);
|
|
||||||
}
|
|
||||||
|
|
||||||
public string? Runtime(Guid guid) {
|
|
||||||
if (javaRuntimeRepository.TryGetByGuid(guid, out var runtime)) {
|
|
||||||
return runtime.ExecutablePath;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private string CombinePath(string basePath, ImmutableArray<string> additionalParts) {
|
|
||||||
// TODO validation
|
|
||||||
return Path.Combine([basePath, ..additionalParts]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace Phantom.Agent.Services.Instances;
|
||||||
|
|
||||||
|
sealed record InstanceProperties(
|
||||||
|
Guid InstanceGuid,
|
||||||
|
string InstanceFolder
|
||||||
|
);
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
using Phantom.Agent.Minecraft.Java;
|
using Phantom.Agent.Services.Backups;
|
||||||
using Phantom.Agent.Minecraft.Server;
|
using Phantom.Agent.Services.Downloads;
|
||||||
using Phantom.Agent.Services.Backups;
|
using Phantom.Agent.Services.Java;
|
||||||
using Phantom.Agent.Services.Rpc;
|
using Phantom.Agent.Services.Rpc;
|
||||||
|
|
||||||
namespace Phantom.Agent.Services.Instances;
|
namespace Phantom.Agent.Services.Instances;
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
using Phantom.Agent.Services.Rpc;
|
using Phantom.Agent.Services.Rpc;
|
||||||
using Phantom.Common.Data;
|
using Phantom.Common.Data;
|
||||||
using Phantom.Common.Data.Agent;
|
using Phantom.Common.Data.Agent;
|
||||||
using Phantom.Common.Data.Instance;
|
using Phantom.Common.Data.Agent.Instance;
|
||||||
using Phantom.Common.Data.Replies;
|
using Phantom.Common.Data.Replies;
|
||||||
using Phantom.Common.Messages.Agent.ToController;
|
using Phantom.Common.Messages.Agent.ToController;
|
||||||
using Phantom.Utils.Logging;
|
using Phantom.Utils.Logging;
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
using Phantom.Agent.Minecraft.Instance;
|
using Phantom.Agent.Services.Instances.State;
|
||||||
using Phantom.Agent.Minecraft.Launcher;
|
|
||||||
using Phantom.Common.Data;
|
using Phantom.Common.Data;
|
||||||
|
using Phantom.Common.Data.Agent.Instance;
|
||||||
using Phantom.Common.Data.Instance;
|
using Phantom.Common.Data.Instance;
|
||||||
using Phantom.Common.Data.Instance.Launch;
|
|
||||||
|
|
||||||
namespace Phantom.Agent.Services.Instances.State;
|
namespace Phantom.Agent.Services.Instances.Launch;
|
||||||
|
|
||||||
static class InstanceLaunchProcedure {
|
static class InstanceLaunchProcedure {
|
||||||
public static async Task<InstanceRunningState?> Run(InstanceContext context, InstanceInfo info, InstanceLauncher launcher, InstanceTicketManager ticketManager, InstanceTicketManager.Ticket ticket, Action<IInstanceStatus?> reportStatus, CancellationToken cancellationToken) {
|
public static async Task<InstanceRunningState?> Run(InstanceContext context, InstanceInfo info, InstanceLauncher launcher, InstanceTicketManager ticketManager, InstanceTicketManager.Ticket ticket, Action<IInstanceStatus?> reportStatus, CancellationToken cancellationToken) {
|
||||||
@@ -44,18 +43,18 @@ static class InstanceLaunchProcedure {
|
|||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
switch (await launcher.Launch(context.Logger, reportStatus, cancellationToken)) {
|
switch (await launcher.Launch(context.Logger, reportStatus, cancellationToken)) {
|
||||||
case LaunchResult.Success launchSuccess:
|
case InstanceLaunchResult.Success launchSuccess:
|
||||||
return launchSuccess.Process;
|
return launchSuccess.Process;
|
||||||
|
|
||||||
case LaunchResult.CouldNotPrepareServerInstance:
|
case InstanceLaunchResult.CouldNotPrepareServerInstance:
|
||||||
context.Logger.Error("Session failed to launch, could not prepare server instance.");
|
context.Logger.Error("Session failed to launch, could not prepare server instance.");
|
||||||
return InstanceLaunchFailReason.CouldNotPrepareServerInstance;
|
return InstanceLaunchFailReason.CouldNotPrepareServerInstance;
|
||||||
|
|
||||||
case LaunchResult.CouldNotFindServerExecutable:
|
case InstanceLaunchResult.CouldNotFindServerExecutable:
|
||||||
context.Logger.Error("Session failed to launch, could not find server executable.");
|
context.Logger.Error("Session failed to launch, could not find server executable.");
|
||||||
return InstanceLaunchFailReason.CouldNotFindServerExecutable;
|
return InstanceLaunchFailReason.CouldNotFindServerExecutable;
|
||||||
|
|
||||||
case LaunchResult.CouldNotStartServerExecutable:
|
case InstanceLaunchResult.CouldNotStartServerExecutable:
|
||||||
context.Logger.Error("Session failed to launch, could not start server executable.");
|
context.Logger.Error("Session failed to launch, could not start server executable.");
|
||||||
return InstanceLaunchFailReason.CouldNotStartServerExecutable;
|
return InstanceLaunchFailReason.CouldNotStartServerExecutable;
|
||||||
|
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
using Phantom.Agent.Services.Instances.State;
|
||||||
|
|
||||||
|
namespace Phantom.Agent.Services.Instances.Launch;
|
||||||
|
|
||||||
|
abstract record InstanceLaunchResult {
|
||||||
|
private InstanceLaunchResult() {}
|
||||||
|
|
||||||
|
public sealed record Success(InstanceProcess Process) : InstanceLaunchResult;
|
||||||
|
|
||||||
|
public sealed record CouldNotPrepareServerInstance : InstanceLaunchResult;
|
||||||
|
|
||||||
|
public sealed record CouldNotFindServerExecutable : InstanceLaunchResult;
|
||||||
|
|
||||||
|
public sealed record CouldNotStartServerExecutable : InstanceLaunchResult;
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
using System.Collections.Immutable;
|
||||||
|
using Phantom.Agent.Services.Downloads;
|
||||||
|
using Phantom.Agent.Services.Instances.State;
|
||||||
|
using Phantom.Agent.Services.Java;
|
||||||
|
using Phantom.Common.Data.Agent;
|
||||||
|
using Phantom.Common.Data.Agent.Instance;
|
||||||
|
using Phantom.Common.Data.Agent.Instance.Launch;
|
||||||
|
using Phantom.Common.Data.Instance;
|
||||||
|
using Phantom.Utils.Processes;
|
||||||
|
using Serilog;
|
||||||
|
|
||||||
|
namespace Phantom.Agent.Services.Instances.Launch;
|
||||||
|
|
||||||
|
sealed class InstanceLauncher(
|
||||||
|
FileDownloadManager downloadManager,
|
||||||
|
IInstancePathResolver pathResolver,
|
||||||
|
IInstanceValueResolver valueResolver,
|
||||||
|
InstanceProperties instanceProperties,
|
||||||
|
InstanceLaunchRecipe launchRecipe
|
||||||
|
) {
|
||||||
|
public IInstanceValueResolver ValueResolver => valueResolver;
|
||||||
|
|
||||||
|
public async Task<InstanceLaunchResult> Launch(ILogger logger, Action<IInstanceStatus?> reportStatus, CancellationToken cancellationToken) {
|
||||||
|
string? executablePath = launchRecipe.Executable.Resolve(pathResolver);
|
||||||
|
if (executablePath == null) {
|
||||||
|
logger.Error("Could not resolve server executable path: {Path}", launchRecipe.Executable);
|
||||||
|
return new InstanceLaunchResult.CouldNotFindServerExecutable();
|
||||||
|
}
|
||||||
|
|
||||||
|
var stepExecutor = new StepExecutor(logger, downloadManager, pathResolver, reportStatus, cancellationToken);
|
||||||
|
if (!await RunPreparationSteps(logger, stepExecutor)) {
|
||||||
|
return new InstanceLaunchResult.CouldNotPrepareServerInstance();
|
||||||
|
}
|
||||||
|
|
||||||
|
var processConfigurator = new ProcessConfigurator {
|
||||||
|
FileName = executablePath,
|
||||||
|
WorkingDirectory = instanceProperties.InstanceFolder,
|
||||||
|
RedirectInput = true,
|
||||||
|
UseShellExecute = false,
|
||||||
|
};
|
||||||
|
|
||||||
|
var processArguments = processConfigurator.ArgumentList;
|
||||||
|
|
||||||
|
foreach (IInstanceValue value in launchRecipe.Arguments) {
|
||||||
|
if (value.Resolve(valueResolver) is {} resolved) {
|
||||||
|
processArguments.Add(resolved);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
logger.Error("Could not resolve server executable argument: {Value}", value);
|
||||||
|
return new InstanceLaunchResult.CouldNotPrepareServerInstance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var process = processConfigurator.CreateProcess();
|
||||||
|
var instanceProcess = new InstanceProcess(instanceProperties, process);
|
||||||
|
|
||||||
|
try {
|
||||||
|
process.Start();
|
||||||
|
} catch (Exception launchException) {
|
||||||
|
logger.Error(launchException, "Caught exception launching the server process.");
|
||||||
|
|
||||||
|
try {
|
||||||
|
process.Kill();
|
||||||
|
} catch (Exception killException) {
|
||||||
|
logger.Error(killException, "Caught exception trying to kill the server process after a failed launch.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new InstanceLaunchResult.CouldNotStartServerExecutable();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new InstanceLaunchResult.Success(instanceProcess);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<bool> RunPreparationSteps(ILogger logger, StepExecutor stepExecutor) {
|
||||||
|
var steps = launchRecipe.Preparation;
|
||||||
|
|
||||||
|
for (int stepIndex = 0; stepIndex < steps.Length; stepIndex++) {
|
||||||
|
var step = steps[stepIndex];
|
||||||
|
try {
|
||||||
|
if (await step.Run(stepExecutor)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} catch (OperationCanceledException) {
|
||||||
|
throw;
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.Error(e, "Failed preparation step {StepIndex} out of {StepCount}: {StepName}", stepIndex, steps.Length, step.GetType().Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class StepExecutor(ILogger logger, FileDownloadManager downloadManager, IInstancePathResolver pathResolver, Action<IInstanceStatus?> reportStatus, CancellationToken cancellationToken) : IInstanceLaunchStepExecutor<bool> {
|
||||||
|
public async Task<bool> DownloadFile(FileDownloadInfo downloadInfo, IInstancePath path) {
|
||||||
|
string? filePath = path.Resolve(pathResolver);
|
||||||
|
if (filePath == null) {
|
||||||
|
logger.Error("Could not resolve download file path: {Path}", path);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
byte? lastDownloadProgress = null;
|
||||||
|
|
||||||
|
void OnDownloadProgress(object? sender, DownloadProgressEventArgs args) {
|
||||||
|
byte? progress = args.TotalBytes is not {} totalBytes ? null : (byte) Math.Min(args.DownloadedBytes * 100 / totalBytes, val2: 100);
|
||||||
|
|
||||||
|
if (lastDownloadProgress != progress) {
|
||||||
|
lastDownloadProgress = progress;
|
||||||
|
reportStatus(InstanceStatus.Downloading(progress));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
reportStatus(InstanceStatus.Downloading(null));
|
||||||
|
|
||||||
|
if (await downloadManager.DownloadAndGetPath(downloadInfo, filePath, OnDownloadProgress, cancellationToken) == null) {
|
||||||
|
logger.Error("Could not download file: {Url}", downloadInfo.Url);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
reportStatus(null);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> EditPropertiesFile(InstancePath.Local path, string comment, ImmutableDictionary<string, string> newValues) {
|
||||||
|
string? filePath = path.Resolve(pathResolver);
|
||||||
|
if (filePath == null) {
|
||||||
|
logger.Error("Could not resolve properties file path: {Path}", path);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var editor = new JavaPropertiesFileEditor();
|
||||||
|
editor.SetAll(newValues);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await editor.EditOrCreate(filePath, comment, cancellationToken);
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.Error(e, "Could not edit properties file: {Path}", filePath);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Collections.Immutable;
|
||||||
|
using Phantom.Agent.Services.Java;
|
||||||
|
using Phantom.Common.Data.Agent.Instance;
|
||||||
|
|
||||||
|
namespace Phantom.Agent.Services.Instances.Launch;
|
||||||
|
|
||||||
|
sealed class InstancePathResolver(AgentFolders agentFolders, JavaRuntimeRepository javaRuntimeRepository, InstanceProperties instanceProperties) : IInstancePathResolver {
|
||||||
|
public string? Global(ImmutableArray<string> segments) {
|
||||||
|
return ValidateAndCombinePath(agentFolders.ServerExecutableFolderPath, segments);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string? Local(ImmutableArray<string> segments) {
|
||||||
|
return ValidateAndCombinePath(instanceProperties.InstanceFolder, segments);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string? Runtime(Guid guid) {
|
||||||
|
return javaRuntimeRepository.TryGetByGuid(guid, out var runtime) ? runtime.ExecutablePath : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly SearchValues<char> InvalidPathPartChars = SearchValues.Create([
|
||||||
|
Path.DirectorySeparatorChar,
|
||||||
|
Path.AltDirectorySeparatorChar,
|
||||||
|
..Path.GetInvalidPathChars(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
private string? ValidateAndCombinePath(string basePath, ImmutableArray<string> pathSegments) {
|
||||||
|
string path = basePath;
|
||||||
|
|
||||||
|
foreach (string segment in pathSegments) {
|
||||||
|
if (segment == "." || segment == ".." || segment.ContainsAny(InvalidPathPartChars) || Path.IsPathRooted(segment)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
path = Path.Combine(path, segment);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Path.GetFullPath(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,9 @@
|
|||||||
using Phantom.Common.Data.Instance;
|
using Phantom.Common.Data.Agent.Instance;
|
||||||
|
|
||||||
namespace Phantom.Agent.Services.Instances;
|
namespace Phantom.Agent.Services.Instances.Launch;
|
||||||
|
|
||||||
sealed class InstanceValueResolver(IInstancePathResolver pathResolver) : IInstanceValueResolver {
|
sealed class InstanceValueResolver(IInstancePathResolver pathResolver) : IInstanceValueResolver {
|
||||||
public string? Path(IInstancePath value) {
|
public string? Path(IInstancePath value) {
|
||||||
return value.Resolve(pathResolver);
|
return value.Resolve(pathResolver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public string? Variable(InstanceVariable value) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
using System.Net.Sockets;
|
using System.Net.Sockets;
|
||||||
using Phantom.Agent.Minecraft.Instance;
|
using Phantom.Agent.Services.Games;
|
||||||
using Phantom.Agent.Minecraft.Server;
|
|
||||||
using Phantom.Agent.Services.Rpc;
|
using Phantom.Agent.Services.Rpc;
|
||||||
using Phantom.Common.Data.Instance;
|
using Phantom.Common.Data.Instance;
|
||||||
using Phantom.Common.Messages.Agent.ToController;
|
using Phantom.Common.Messages.Agent.ToController;
|
||||||
@@ -60,8 +59,8 @@ sealed class InstancePlayerCountTracker : CancellableBackgroundTask {
|
|||||||
|
|
||||||
private async Task<InstancePlayerCounts?> TryGetPlayerCounts() {
|
private async Task<InstancePlayerCounts?> TryGetPlayerCounts() {
|
||||||
try {
|
try {
|
||||||
return await ServerStatusProtocol.GetPlayerCounts(serverPort, CancellationToken);
|
return await MinecraftServerStatusProtocol.GetPlayerCounts(serverPort, CancellationToken);
|
||||||
} catch (ServerStatusProtocol.ProtocolException e) {
|
} catch (MinecraftServerStatusProtocol.ProtocolException e) {
|
||||||
Logger.Error("{Message}", e.Message);
|
Logger.Error("{Message}", e.Message);
|
||||||
return null;
|
return null;
|
||||||
} catch (SocketException e) {
|
} catch (SocketException e) {
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
using Phantom.Utils.Processes;
|
using Phantom.Utils.Processes;
|
||||||
using Phantom.Utils.Tasks;
|
using Phantom.Utils.Tasks;
|
||||||
|
|
||||||
namespace Phantom.Agent.Minecraft.Instance;
|
namespace Phantom.Agent.Services.Instances.State;
|
||||||
|
|
||||||
public sealed class InstanceProcess : IDisposable {
|
sealed class InstanceProcess : IDisposable {
|
||||||
public InstanceProperties InstanceProperties { get; }
|
public InstanceProperties InstanceProperties { get; }
|
||||||
|
|
||||||
private readonly RingBuffer<string> outputBuffer = new (100);
|
private readonly RingBuffer<string> outputBuffer = new (100);
|
||||||
@@ -27,6 +27,15 @@ public sealed class InstanceProcess : IDisposable {
|
|||||||
await process.StandardInput.WriteLineAsync(command.AsMemory(), cancellationToken);
|
await process.StandardInput.WriteLineAsync(command.AsMemory(), cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<bool> TrySendCommand(string command, TimeSpan timeout, CancellationToken cancellationToken) {
|
||||||
|
try {
|
||||||
|
await SendCommand(command, cancellationToken).WaitAsync(timeout, cancellationToken);
|
||||||
|
return true;
|
||||||
|
} catch (TimeoutException) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public void AddOutputListener(EventHandler<string> listener, uint maxLinesToReadFromHistory = uint.MaxValue) {
|
public void AddOutputListener(EventHandler<string> listener, uint maxLinesToReadFromHistory = uint.MaxValue) {
|
||||||
OutputEvent += listener;
|
OutputEvent += listener;
|
||||||
|
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
using Phantom.Agent.Minecraft.Instance;
|
using Phantom.Agent.Services.Backups;
|
||||||
using Phantom.Agent.Minecraft.Launcher;
|
using Phantom.Agent.Services.Instances.Launch;
|
||||||
using Phantom.Agent.Services.Backups;
|
using Phantom.Common.Data.Agent.Instance;
|
||||||
using Phantom.Common.Data.Backups;
|
using Phantom.Common.Data.Backups;
|
||||||
using Phantom.Common.Data.Instance;
|
using Phantom.Common.Data.Instance;
|
||||||
using Phantom.Common.Data.Instance.Launch;
|
|
||||||
using Phantom.Common.Data.Replies;
|
using Phantom.Common.Data.Replies;
|
||||||
|
|
||||||
namespace Phantom.Agent.Services.Instances.State;
|
namespace Phantom.Agent.Services.Instances.State;
|
||||||
@@ -12,6 +11,7 @@ sealed class InstanceRunningState : IDisposable {
|
|||||||
public InstanceTicketManager.Ticket Ticket { get; }
|
public InstanceTicketManager.Ticket Ticket { get; }
|
||||||
public InstanceProcess Process { get; }
|
public InstanceProcess Process { get; }
|
||||||
|
|
||||||
|
internal IInstanceValueResolver ValueResolver => launcher.ValueResolver;
|
||||||
internal bool IsStopping { get; set; }
|
internal bool IsStopping { get; set; }
|
||||||
|
|
||||||
private readonly InstanceContext context;
|
private readonly InstanceContext context;
|
||||||
|
|||||||
@@ -1,38 +1,50 @@
|
|||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using Phantom.Agent.Minecraft.Command;
|
using Phantom.Common.Data.Agent.Instance;
|
||||||
using Phantom.Agent.Minecraft.Instance;
|
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||||
using Phantom.Common.Data.Instance;
|
using Phantom.Common.Data.Instance;
|
||||||
using Phantom.Common.Data.Minecraft;
|
using Serilog;
|
||||||
|
|
||||||
namespace Phantom.Agent.Services.Instances.State;
|
namespace Phantom.Agent.Services.Instances.State;
|
||||||
|
|
||||||
static class InstanceStopProcedure {
|
static class InstanceStopProcedure {
|
||||||
private static readonly ushort[] Stops = [60, 30, 10, 5, 4, 3, 2, 1, 0];
|
public static async Task<bool> Run(InstanceContext context, InstanceStopRecipe stopRecipe, InstanceRunningState runningState, Action<IInstanceStatus> reportStatus, CancellationToken cancellationToken) {
|
||||||
|
var logger = context.Logger;
|
||||||
|
|
||||||
public static async Task<bool> Run(InstanceContext context, MinecraftStopStrategy stopStrategy, InstanceRunningState runningState, Action<IInstanceStatus> reportStatus, CancellationToken cancellationToken) {
|
var stopCommand = stopRecipe.StopCommand.Resolve(runningState.ValueResolver);
|
||||||
var process = runningState.Process;
|
if (stopCommand == null) {
|
||||||
runningState.IsStopping = true;
|
logger.Error("Could not resolve stop command");
|
||||||
|
|
||||||
var seconds = stopStrategy.Seconds;
|
|
||||||
if (seconds > 0) {
|
|
||||||
try {
|
|
||||||
await CountDownWithAnnouncements(context, process, seconds, cancellationToken);
|
|
||||||
} catch (OperationCanceledException) {
|
|
||||||
runningState.IsStopping = false;
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
runningState.IsStopping = true;
|
||||||
|
|
||||||
|
bool continueStopping = false;
|
||||||
|
try {
|
||||||
|
var stepExecutor = new StepExecutor(logger, runningState.ValueResolver, runningState.Process, cancellationToken);
|
||||||
|
continueStopping = await RunPreparationSteps(context, stopRecipe, stepExecutor);
|
||||||
|
} finally {
|
||||||
|
if (!continueStopping) {
|
||||||
|
runningState.IsStopping = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!continueStopping) {
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Too late to cancel the stop procedure now.
|
// Too late to cancel the stop procedure now.
|
||||||
runningState.OnStopInitiated();
|
runningState.OnStopInitiated();
|
||||||
|
|
||||||
if (!process.HasEnded) {
|
if (!runningState.Process.HasEnded) {
|
||||||
context.Logger.Information("Session stopping now.");
|
logger.Information("Sending stop command...");
|
||||||
await DoStop(context, process);
|
await TrySendStopCommand(context, runningState.Process, stopCommand);
|
||||||
|
|
||||||
|
logger.Information("Waiting for session to end...");
|
||||||
|
await WaitForSessionToEnd(context, runningState.Process);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
context.Logger.Information("Session stopped.");
|
logger.Information("Session stopped.");
|
||||||
reportStatus(InstanceStatus.NotRunning);
|
reportStatus(InstanceStatus.NotRunning);
|
||||||
context.ReportEvent(InstanceEvent.Stopped);
|
context.ReportEvent(InstanceEvent.Stopped);
|
||||||
}
|
}
|
||||||
@@ -40,39 +52,51 @@ static class InstanceStopProcedure {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task CountDownWithAnnouncements(InstanceContext context, InstanceProcess process, ushort seconds, CancellationToken cancellationToken) {
|
private static async Task<bool> RunPreparationSteps(InstanceContext context, InstanceStopRecipe stopRecipe, StepExecutor executor) {
|
||||||
context.Logger.Information("Session stopping in {Seconds} seconds.", seconds);
|
var steps = stopRecipe.Preparation;
|
||||||
|
|
||||||
foreach (var stop in Stops) {
|
for (int stepIndex = 0; stepIndex < steps.Length; stepIndex++) {
|
||||||
// TODO change to event-based cancellation
|
var step = steps[stepIndex];
|
||||||
if (process.HasEnded) {
|
try {
|
||||||
return;
|
if (await step.Run(executor)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} catch (OperationCanceledException) {
|
||||||
|
throw;
|
||||||
|
} catch (Exception e) {
|
||||||
|
context.Logger.Error(e, "Failed preparation step {StepIndex} out of {StepCount}: {StepName}", stepIndex, steps.Length, step.GetType().Name);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (seconds > stop) {
|
return false;
|
||||||
await process.SendCommand(GetCountDownAnnouncementCommand(seconds), cancellationToken);
|
|
||||||
await Task.Delay(TimeSpan.FromSeconds(seconds - stop), cancellationToken);
|
|
||||||
seconds = stop;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class StepExecutor(ILogger logger, IInstanceValueResolver valueResolver, InstanceProcess process, CancellationToken cancellationToken) : IInstanceStopStepExecutor<bool> {
|
||||||
|
public async Task<bool> Wait(TimeSpan duration) {
|
||||||
|
await Task.Delay(duration, cancellationToken);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> SendToStandardInput(IInstanceValue line) {
|
||||||
|
string? command = line.Resolve(valueResolver);
|
||||||
|
if (command == null) {
|
||||||
|
logger.Error("Could not resolve standard input line: {Value}", line);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the process can't process standard input, wait a bit but don't block or fail the whole stop procedure.
|
||||||
|
await process.TrySendCommand(command, TimeSpan.FromMilliseconds(500), cancellationToken);
|
||||||
|
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string GetCountDownAnnouncementCommand(ushort seconds) {
|
private static async Task TrySendStopCommand(InstanceContext context, InstanceProcess process, string command) {
|
||||||
return MinecraftCommand.Say("Server shutting down in " + seconds + (seconds == 1 ? " second." : " seconds."));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task DoStop(InstanceContext context, InstanceProcess process) {
|
|
||||||
context.Logger.Information("Sending stop command...");
|
|
||||||
await TrySendStopCommand(context, process);
|
|
||||||
|
|
||||||
context.Logger.Information("Waiting for session to end...");
|
|
||||||
await WaitForSessionToEnd(context, process);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task TrySendStopCommand(InstanceContext context, InstanceProcess process) {
|
|
||||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||||
try {
|
try {
|
||||||
await process.SendCommand(MinecraftCommand.Stop, timeout.Token);
|
await process.SendCommand(command, timeout.Token);
|
||||||
} catch (OperationCanceledException) {
|
} catch (OperationCanceledException) {
|
||||||
// Ignore.
|
// Ignore.
|
||||||
} catch (ObjectDisposedException e) when (e.ObjectName == typeof(Process).FullName && process.HasEnded) {
|
} catch (ObjectDisposedException e) when (e.ObjectName == typeof(Process).FullName && process.HasEnded) {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace Phantom.Agent.Minecraft.Java;
|
namespace Phantom.Agent.Services.Java;
|
||||||
|
|
||||||
sealed class JavaPropertiesFileEditor {
|
sealed class JavaPropertiesFileEditor {
|
||||||
private readonly Dictionary<string, string> overriddenProperties = new ();
|
private readonly Dictionary<string, string> overriddenProperties = new ();
|
||||||
@@ -4,7 +4,7 @@ using System.Runtime.CompilerServices;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using Phantom.Utils.Collections;
|
using Phantom.Utils.Collections;
|
||||||
|
|
||||||
namespace Phantom.Agent.Minecraft.Java;
|
namespace Phantom.Agent.Services.Java;
|
||||||
|
|
||||||
static class JavaPropertiesStream {
|
static class JavaPropertiesStream {
|
||||||
internal static readonly Encoding Encoding = Encoding.GetEncoding("ISO-8859-1");
|
internal static readonly Encoding Encoding = Encoding.GetEncoding("ISO-8859-1");
|
||||||
@@ -30,7 +30,7 @@ static class JavaPropertiesStream {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Reader(string path) {
|
public Reader(string path) {
|
||||||
this.reader = new StreamReader(path, Encoding, detectEncodingFromByteOrderMarks: false, CreateFileStreamOptions(FileMode.Open, FileAccess.Read));
|
this.reader = new StreamReader(path, Encoding, detectEncodingFromByteOrderMarks: true, CreateFileStreamOptions(FileMode.Open, FileAccess.Read));
|
||||||
}
|
}
|
||||||
|
|
||||||
public async IAsyncEnumerable<KeyValuePair<string, string>> ReadProperties([EnumeratorCancellation] CancellationToken cancellationToken) {
|
public async IAsyncEnumerable<KeyValuePair<string, string>> ReadProperties([EnumeratorCancellation] CancellationToken cancellationToken) {
|
||||||
@@ -6,7 +6,7 @@ using Phantom.Utils.IO;
|
|||||||
using Phantom.Utils.Logging;
|
using Phantom.Utils.Logging;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
|
|
||||||
namespace Phantom.Agent.Minecraft.Java;
|
namespace Phantom.Agent.Services.Java;
|
||||||
|
|
||||||
public sealed class JavaRuntimeDiscovery {
|
public sealed class JavaRuntimeDiscovery {
|
||||||
private static readonly ILogger Logger = PhantomLogger.Create(nameof(JavaRuntimeDiscovery));
|
private static readonly ILogger Logger = PhantomLogger.Create(nameof(JavaRuntimeDiscovery));
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
using Phantom.Common.Data.Java;
|
||||||
|
|
||||||
|
namespace Phantom.Agent.Services.Java;
|
||||||
|
|
||||||
|
sealed record JavaRuntimeExecutable(string ExecutablePath, JavaRuntime Runtime);
|
||||||
@@ -3,7 +3,7 @@ using System.Diagnostics.CodeAnalysis;
|
|||||||
using Phantom.Common.Data.Java;
|
using Phantom.Common.Data.Java;
|
||||||
using Phantom.Utils.Cryptography;
|
using Phantom.Utils.Cryptography;
|
||||||
|
|
||||||
namespace Phantom.Agent.Minecraft.Java;
|
namespace Phantom.Agent.Services.Java;
|
||||||
|
|
||||||
public sealed class JavaRuntimeRepository {
|
public sealed class JavaRuntimeRepository {
|
||||||
private readonly ImmutableDictionary<Guid, JavaRuntimeExecutable> runtimesByGuid;
|
private readonly ImmutableDictionary<Guid, JavaRuntimeExecutable> runtimesByGuid;
|
||||||
@@ -25,7 +25,7 @@ public sealed class JavaRuntimeRepository {
|
|||||||
.ToImmutableArray();
|
.ToImmutableArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool TryGetByGuid(Guid guid, [MaybeNullWhen(false)] out JavaRuntimeExecutable runtime) {
|
internal bool TryGetByGuid(Guid guid, [MaybeNullWhen(false)] out JavaRuntimeExecutable runtime) {
|
||||||
return runtimesByGuid.TryGetValue(guid, out runtime);
|
return runtimesByGuid.TryGetValue(guid, out runtime);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5,9 +5,12 @@
|
|||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<InternalsVisibleTo Include="Phantom.Agent.Services.Tests" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\Common\Phantom.Common.Messages.Agent\Phantom.Common.Messages.Agent.csproj" />
|
<ProjectReference Include="..\..\Common\Phantom.Common.Messages.Agent\Phantom.Common.Messages.Agent.csproj" />
|
||||||
<ProjectReference Include="..\Phantom.Agent.Minecraft\Phantom.Agent.Minecraft.csproj" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ public sealed class ControllerMessageHandlerActor : ReceiveActor<IMessageToAgent
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async Task<Result<ConfigureInstanceResult, InstanceActionFailure>> HandleConfigureInstance(ConfigureInstanceMessage message) {
|
private async Task<Result<ConfigureInstanceResult, InstanceActionFailure>> HandleConfigureInstance(ConfigureInstanceMessage message) {
|
||||||
return await agent.InstanceManager.Request(new InstanceManagerActor.ConfigureInstanceCommand(message.InstanceGuid, message.Info, message.LaunchRecipe, message.LaunchNow, AlwaysReportStatus: false));
|
return await agent.InstanceManager.Request(new InstanceManagerActor.ConfigureInstanceCommand(message.InstanceGuid, message.Info, message.LaunchRecipe, message.LaunchNow, message.StopRecipe, AlwaysReportStatus: false));
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<Result<LaunchInstanceResult, InstanceActionFailure>> HandleLaunchInstance(LaunchInstanceMessage message) {
|
private async Task<Result<LaunchInstanceResult, InstanceActionFailure>> HandleLaunchInstance(LaunchInstanceMessage message) {
|
||||||
@@ -34,7 +34,7 @@ public sealed class ControllerMessageHandlerActor : ReceiveActor<IMessageToAgent
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async Task<Result<StopInstanceResult, InstanceActionFailure>> HandleStopInstance(StopInstanceMessage message) {
|
private async Task<Result<StopInstanceResult, InstanceActionFailure>> HandleStopInstance(StopInstanceMessage message) {
|
||||||
return await agent.InstanceManager.Request(new InstanceManagerActor.StopInstanceCommand(message.InstanceGuid, message.StopStrategy));
|
return await agent.InstanceManager.Request(new InstanceManagerActor.StopInstanceCommand(message.InstanceGuid, message.StopRecipe));
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<Result<SendCommandToInstanceResult, InstanceActionFailure>> HandleSendCommandToInstance(SendCommandToInstanceMessage message) {
|
private async Task<Result<SendCommandToInstanceResult, InstanceActionFailure>> HandleSendCommandToInstance(SendCommandToInstanceMessage message) {
|
||||||
|
|||||||
@@ -12,7 +12,6 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\Utils\Phantom.Utils\Phantom.Utils.csproj" />
|
<ProjectReference Include="..\..\Utils\Phantom.Utils\Phantom.Utils.csproj" />
|
||||||
<ProjectReference Include="..\Phantom.Agent.Minecraft\Phantom.Agent.Minecraft.csproj" />
|
|
||||||
<ProjectReference Include="..\Phantom.Agent.Services\Phantom.Agent.Services.csproj" />
|
<ProjectReference Include="..\Phantom.Agent.Services\Phantom.Agent.Services.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using Phantom.Agent;
|
using Phantom.Agent;
|
||||||
using Phantom.Agent.Minecraft.Java;
|
|
||||||
using Phantom.Agent.Services;
|
using Phantom.Agent.Services;
|
||||||
|
using Phantom.Agent.Services.Java;
|
||||||
using Phantom.Agent.Services.Rpc;
|
using Phantom.Agent.Services.Rpc;
|
||||||
using Phantom.Common.Data.Agent;
|
using Phantom.Common.Data.Agent;
|
||||||
using Phantom.Common.Messages.Agent;
|
using Phantom.Common.Messages.Agent;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
using Phantom.Agent.Minecraft.Java;
|
using Phantom.Agent.Services.Java;
|
||||||
using Phantom.Common.Data;
|
using Phantom.Common.Data;
|
||||||
using Phantom.Utils.Logging;
|
using Phantom.Utils.Logging;
|
||||||
using Phantom.Utils.Runtime;
|
using Phantom.Utils.Runtime;
|
||||||
@@ -43,7 +43,7 @@ sealed record Variables(
|
|||||||
try {
|
try {
|
||||||
return LoadOrThrow();
|
return LoadOrThrow();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
PhantomLogger.Root.Fatal("{}", e.Message);
|
PhantomLogger.Root.Fatal("{Error}", e.Message);
|
||||||
throw StopProcedureException.Instance;
|
throw StopProcedureException.Instance;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Utils.Cryptography;
|
using Phantom.Utils.Cryptography;
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Minecraft;
|
namespace Phantom.Common.Data.Agent;
|
||||||
|
|
||||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||||
public sealed partial class FileDownloadInfo {
|
public sealed partial class FileDownloadInfo {
|
||||||
[MemoryPackOrder(0)]
|
[MemoryPackOrder(0)]
|
||||||
public string DownloadUrl { get; }
|
public string Url { get; }
|
||||||
|
|
||||||
[MemoryPackOrder(1)]
|
[MemoryPackOrder(1)]
|
||||||
[MemoryPackInclude]
|
[MemoryPackInclude]
|
||||||
@@ -15,11 +15,11 @@ public sealed partial class FileDownloadInfo {
|
|||||||
[MemoryPackIgnore]
|
[MemoryPackIgnore]
|
||||||
public Sha1String? Hash => hash == null ? null : Sha1String.FromString(hash);
|
public Sha1String? Hash => hash == null ? null : Sha1String.FromString(hash);
|
||||||
|
|
||||||
public FileDownloadInfo(string downloadUrl, Sha1String? hash = null) : this(downloadUrl, hash?.ToString()) {}
|
public FileDownloadInfo(string url, Sha1String? hash = null) : this(url, hash?.ToString()) {}
|
||||||
|
|
||||||
[MemoryPackConstructor]
|
[MemoryPackConstructor]
|
||||||
private FileDownloadInfo(string downloadUrl, string? hash) {
|
private FileDownloadInfo(string url, string? hash) {
|
||||||
this.DownloadUrl = downloadUrl;
|
this.Url = url;
|
||||||
this.hash = hash;
|
this.hash = hash;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Instance;
|
namespace Phantom.Common.Data.Agent.Instance;
|
||||||
|
|
||||||
[MemoryPackable]
|
[MemoryPackable]
|
||||||
[MemoryPackUnion(tag: 0, typeof(InstancePath.Global))]
|
[MemoryPackUnion(tag: 0, typeof(InstancePath.Global))]
|
||||||
@@ -14,19 +14,27 @@ public partial interface IInstancePath {
|
|||||||
public static partial class InstancePath {
|
public static partial class InstancePath {
|
||||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||||
public sealed partial record Global(
|
public sealed partial record Global(
|
||||||
[property: MemoryPackOrder(0)] ImmutableArray<string> Path
|
[property: MemoryPackOrder(0)] ImmutableArray<string> Segments
|
||||||
) : IInstancePath {
|
) : IInstancePath {
|
||||||
public string? Resolve(IInstancePathResolver resolver) {
|
public string? Resolve(IInstancePathResolver resolver) {
|
||||||
return resolver.Global(Path);
|
return resolver.Global(Segments);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString() {
|
||||||
|
return "Global[" + string.Join(separator: '/', Segments) + "]";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||||
public sealed partial record Local(
|
public sealed partial record Local(
|
||||||
[property: MemoryPackOrder(0)] ImmutableArray<string> Path
|
[property: MemoryPackOrder(0)] ImmutableArray<string> Segments
|
||||||
) : IInstancePath {
|
) : IInstancePath {
|
||||||
public string? Resolve(IInstancePathResolver resolver) {
|
public string? Resolve(IInstancePathResolver resolver) {
|
||||||
return resolver.Local(Path);
|
return resolver.Local(Segments);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString() {
|
||||||
|
return "Local[" + string.Join(separator: '/', Segments) + "]";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,5 +45,9 @@ public static partial class InstancePath {
|
|||||||
public string? Resolve(IInstancePathResolver resolver) {
|
public string? Resolve(IInstancePathResolver resolver) {
|
||||||
return resolver.Runtime(Guid);
|
return resolver.Runtime(Guid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public override string ToString() {
|
||||||
|
return "Runtime[" + Guid + "]";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
using System.Collections.Immutable;
|
||||||
|
|
||||||
|
namespace Phantom.Common.Data.Agent.Instance;
|
||||||
|
|
||||||
|
public interface IInstancePathResolver {
|
||||||
|
string? Global(ImmutableArray<string> segments);
|
||||||
|
string? Local(ImmutableArray<string> segments);
|
||||||
|
string? Runtime(Guid guid);
|
||||||
|
}
|
||||||
@@ -2,13 +2,12 @@
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Instance;
|
namespace Phantom.Common.Data.Agent.Instance;
|
||||||
|
|
||||||
[MemoryPackable]
|
[MemoryPackable]
|
||||||
[MemoryPackUnion(tag: 0, typeof(InstanceValues.Concatenation))]
|
[MemoryPackUnion(tag: 0, typeof(InstanceValues.Concatenation))]
|
||||||
[MemoryPackUnion(tag: 1, typeof(InstanceValues.Text))]
|
[MemoryPackUnion(tag: 1, typeof(InstanceValues.Text))]
|
||||||
[MemoryPackUnion(tag: 2, typeof(InstanceValues.Path))]
|
[MemoryPackUnion(tag: 2, typeof(InstanceValues.Path))]
|
||||||
[MemoryPackUnion(tag: 3, typeof(InstanceValues.Variable))]
|
|
||||||
public partial interface IInstanceValue {
|
public partial interface IInstanceValue {
|
||||||
string? Resolve(IInstanceValueResolver resolver);
|
string? Resolve(IInstanceValueResolver resolver);
|
||||||
}
|
}
|
||||||
@@ -30,6 +29,10 @@ public static partial class InstanceValues {
|
|||||||
|
|
||||||
return result.ToString();
|
return result.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public override string ToString() {
|
||||||
|
return "Concatenation[" + string.Join(",", Values) + "]";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[MemoryPackable]
|
[MemoryPackable]
|
||||||
@@ -37,6 +40,10 @@ public static partial class InstanceValues {
|
|||||||
public string Resolve(IInstanceValueResolver resolver) {
|
public string Resolve(IInstanceValueResolver resolver) {
|
||||||
return Value;
|
return Value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public override string ToString() {
|
||||||
|
return "Text[" + Value + "]";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[MemoryPackable]
|
[MemoryPackable]
|
||||||
@@ -44,14 +51,9 @@ public static partial class InstanceValues {
|
|||||||
public string? Resolve(IInstanceValueResolver resolver) {
|
public string? Resolve(IInstanceValueResolver resolver) {
|
||||||
return resolver.Path(Value);
|
return resolver.Path(Value);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
[MemoryPackable]
|
public override string ToString() {
|
||||||
public sealed partial record Variable(InstanceVariable Value) : IInstanceValue {
|
return "Path[" + Value + "]";
|
||||||
public string? Resolve(IInstanceValueResolver resolver) {
|
|
||||||
return resolver.Variable(Value);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum InstanceVariable {}
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
namespace Phantom.Common.Data.Agent.Instance;
|
||||||
|
|
||||||
|
public interface IInstanceValueResolver {
|
||||||
|
string? Path(IInstancePath value);
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Instance;
|
namespace Phantom.Common.Data.Agent.Instance;
|
||||||
|
|
||||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||||
public sealed partial record InstanceInfo(
|
public sealed partial record InstanceInfo(
|
||||||
@@ -1,14 +1,13 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Common.Data.Minecraft;
|
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Instance.Launch;
|
namespace Phantom.Common.Data.Agent.Instance.Launch;
|
||||||
|
|
||||||
[MemoryPackable]
|
[MemoryPackable]
|
||||||
[MemoryPackUnion(tag: 0, typeof(InstanceLaunchStep.DownloadFile))]
|
[MemoryPackUnion(tag: 0, typeof(InstanceLaunchStep.DownloadFile))]
|
||||||
[MemoryPackUnion(tag: 1, typeof(InstanceLaunchStep.EditPropertiesFile))]
|
[MemoryPackUnion(tag: 1, typeof(InstanceLaunchStep.EditPropertiesFile))]
|
||||||
public partial interface IInstanceLaunchStep {
|
public partial interface IInstanceLaunchStep {
|
||||||
Task Run(IInstanceLaunchStepExecutor executor);
|
Task<TResult> Run<TResult>(IInstanceLaunchStepExecutor<TResult> executor);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static partial class InstanceLaunchStep {
|
public static partial class InstanceLaunchStep {
|
||||||
@@ -17,7 +16,7 @@ public static partial class InstanceLaunchStep {
|
|||||||
[property: MemoryPackOrder(0)] FileDownloadInfo DownloadInfo,
|
[property: MemoryPackOrder(0)] FileDownloadInfo DownloadInfo,
|
||||||
[property: MemoryPackOrder(1)] IInstancePath Path
|
[property: MemoryPackOrder(1)] IInstancePath Path
|
||||||
) : IInstanceLaunchStep {
|
) : IInstanceLaunchStep {
|
||||||
public Task Run(IInstanceLaunchStepExecutor executor) {
|
public Task<TResult> Run<TResult>(IInstanceLaunchStepExecutor<TResult> executor) {
|
||||||
return executor.DownloadFile(DownloadInfo, Path);
|
return executor.DownloadFile(DownloadInfo, Path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -28,7 +27,7 @@ public static partial class InstanceLaunchStep {
|
|||||||
[property: MemoryPackOrder(1)] string Comment,
|
[property: MemoryPackOrder(1)] string Comment,
|
||||||
[property: MemoryPackOrder(2)] ImmutableDictionary<string, string> NewValues
|
[property: MemoryPackOrder(2)] ImmutableDictionary<string, string> NewValues
|
||||||
) : IInstanceLaunchStep {
|
) : IInstanceLaunchStep {
|
||||||
public Task Run(IInstanceLaunchStepExecutor executor) {
|
public Task<TResult> Run<TResult>(IInstanceLaunchStepExecutor<TResult> executor) {
|
||||||
return executor.EditPropertiesFile(Path, Comment, NewValues);
|
return executor.EditPropertiesFile(Path, Comment, NewValues);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using System.Collections.Immutable;
|
||||||
|
|
||||||
|
namespace Phantom.Common.Data.Agent.Instance.Launch;
|
||||||
|
|
||||||
|
public interface IInstanceLaunchStepExecutor<TResult> {
|
||||||
|
Task<TResult> DownloadFile(FileDownloadInfo downloadInfo, IInstancePath path);
|
||||||
|
Task<TResult> EditPropertiesFile(InstancePath.Local path, string comment, ImmutableDictionary<string, string> newValues);
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Instance.Launch;
|
namespace Phantom.Common.Data.Agent.Instance.Launch;
|
||||||
|
|
||||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||||
public sealed partial record InstanceLaunchRecipe(
|
public sealed partial record InstanceLaunchRecipe(
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace Phantom.Common.Data.Agent.Instance.Stop;
|
||||||
|
|
||||||
|
public interface IInstanceStopStepExecutor<TResult> {
|
||||||
|
Task<TResult> Wait(TimeSpan duration);
|
||||||
|
Task<TResult> SendToStandardInput(IInstanceValue line);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using MemoryPack;
|
||||||
|
|
||||||
|
namespace Phantom.Common.Data.Agent.Instance.Stop;
|
||||||
|
|
||||||
|
[MemoryPackable]
|
||||||
|
[MemoryPackUnion(tag: 0, typeof(InstanceStopStep.Wait))]
|
||||||
|
[MemoryPackUnion(tag: 1, typeof(InstanceStopStep.SendToStandardInput))]
|
||||||
|
public partial interface IInstanceStopStep {
|
||||||
|
Task<TResult> Run<TResult>(IInstanceStopStepExecutor<TResult> executor);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static partial class InstanceStopStep {
|
||||||
|
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||||
|
public sealed partial record Wait(
|
||||||
|
[property: MemoryPackOrder(0)] TimeSpan Duration
|
||||||
|
) : IInstanceStopStep {
|
||||||
|
public Task<TResult> Run<TResult>(IInstanceStopStepExecutor<TResult> executor) {
|
||||||
|
return executor.Wait(Duration);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||||
|
public sealed partial record SendToStandardInput(
|
||||||
|
[property: MemoryPackOrder(0)] IInstanceValue Line
|
||||||
|
) : IInstanceStopStep {
|
||||||
|
public Task<TResult> Run<TResult>(IInstanceStopStepExecutor<TResult> executor) {
|
||||||
|
return executor.SendToStandardInput(Line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
using System.Collections.Immutable;
|
||||||
|
using MemoryPack;
|
||||||
|
|
||||||
|
namespace Phantom.Common.Data.Agent.Instance.Stop;
|
||||||
|
|
||||||
|
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||||
|
public sealed partial record InstanceStopRecipe(
|
||||||
|
[property: MemoryPackOrder(0)] ImmutableArray<IInstanceStopStep> Preparation,
|
||||||
|
[property: MemoryPackOrder(1)] IInstanceValue StopCommand
|
||||||
|
);
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="MemoryPack" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\Phantom.Common.Data\Phantom.Common.Data.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Common.Data.Agent;
|
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Web.Agent;
|
namespace Phantom.Common.Data.Web.Agent;
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Common.Data.Agent;
|
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Web.Agent;
|
namespace Phantom.Common.Data.Web.Agent;
|
||||||
|
|
||||||
@@ -10,8 +9,4 @@ public sealed partial record AgentRuntimeInfo(
|
|||||||
[property: MemoryPackOrder(2)] RamAllocationUnits? MaxMemory = null,
|
[property: MemoryPackOrder(2)] RamAllocationUnits? MaxMemory = null,
|
||||||
[property: MemoryPackOrder(3)] AllowedPorts? AllowedServerPorts = null,
|
[property: MemoryPackOrder(3)] AllowedPorts? AllowedServerPorts = null,
|
||||||
[property: MemoryPackOrder(4)] AllowedPorts? AllowedAdditionalPorts = null
|
[property: MemoryPackOrder(4)] AllowedPorts? AllowedAdditionalPorts = null
|
||||||
) {
|
);
|
||||||
public static AgentRuntimeInfo From(AgentInfo agentInfo) {
|
|
||||||
return new AgentRuntimeInfo(new AgentVersionInfo(agentInfo.ProtocolVersion, agentInfo.BuildVersion), agentInfo.MaxInstances, agentInfo.MaxMemory, agentInfo.AllowedServerPorts, agentInfo.AllowedAdditionalPorts);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Agent;
|
namespace Phantom.Common.Data.Web.Agent;
|
||||||
|
|
||||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||||
public sealed partial record AgentStats(
|
public sealed partial record AgentStats(
|
||||||
@@ -5,7 +5,7 @@ public enum CreateOrUpdateInstanceResult : byte {
|
|||||||
Success,
|
Success,
|
||||||
InstanceNameMustNotBeEmpty,
|
InstanceNameMustNotBeEmpty,
|
||||||
InstanceMemoryMustNotBeZero,
|
InstanceMemoryMustNotBeZero,
|
||||||
MinecraftVersionDownloadInfoNotFound,
|
MinecraftVersionNotFound,
|
||||||
AgentNotFound,
|
AgentNotFound,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@ public static class CreateOrUpdateInstanceResultExtensions {
|
|||||||
CreateOrUpdateInstanceResult.Success => "Success.",
|
CreateOrUpdateInstanceResult.Success => "Success.",
|
||||||
CreateOrUpdateInstanceResult.InstanceNameMustNotBeEmpty => "Instance name must not be empty.",
|
CreateOrUpdateInstanceResult.InstanceNameMustNotBeEmpty => "Instance name must not be empty.",
|
||||||
CreateOrUpdateInstanceResult.InstanceMemoryMustNotBeZero => "Memory must not be 0 MB.",
|
CreateOrUpdateInstanceResult.InstanceMemoryMustNotBeZero => "Memory must not be 0 MB.",
|
||||||
CreateOrUpdateInstanceResult.MinecraftVersionDownloadInfoNotFound => "Could not find download information for the selected Minecraft version.",
|
CreateOrUpdateInstanceResult.MinecraftVersionNotFound => "Minecraft version not found.",
|
||||||
CreateOrUpdateInstanceResult.AgentNotFound => "Agent not found.",
|
CreateOrUpdateInstanceResult.AgentNotFound => "Agent not found.",
|
||||||
_ => "Unknown error.",
|
_ => "Unknown error.",
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Common.Data.Minecraft;
|
using Phantom.Common.Data.Web.Minecraft;
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Instance;
|
namespace Phantom.Common.Data.Web.Instance;
|
||||||
|
|
||||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||||
public sealed partial record InstanceConfiguration(
|
public sealed partial record InstanceConfiguration(
|
||||||
@@ -15,7 +15,4 @@ public sealed partial record InstanceConfiguration(
|
|||||||
[property: MemoryPackOrder(6)] RamAllocationUnits MemoryAllocation,
|
[property: MemoryPackOrder(6)] RamAllocationUnits MemoryAllocation,
|
||||||
[property: MemoryPackOrder(7)] Guid JavaRuntimeGuid,
|
[property: MemoryPackOrder(7)] Guid JavaRuntimeGuid,
|
||||||
[property: MemoryPackOrder(8)] ImmutableArray<string> JvmArguments
|
[property: MemoryPackOrder(8)] ImmutableArray<string> JvmArguments
|
||||||
) {
|
);
|
||||||
[MemoryPackIgnore]
|
|
||||||
public InstanceInfo AsInfo => new (InstanceName, ServerPort, [RconPort], MemoryAllocation);
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Web.Minecraft;
|
namespace Phantom.Common.Data.Web.Java;
|
||||||
|
|
||||||
public static class JvmArgumentsHelper {
|
public static class JvmArgumentsHelper {
|
||||||
public static ImmutableArray<string> Split(string arguments) {
|
public static ImmutableArray<string> Split(string arguments) {
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace Phantom.Common.Data.Minecraft;
|
namespace Phantom.Common.Data.Web.Minecraft;
|
||||||
|
|
||||||
public enum MinecraftServerKind : ushort {
|
public enum MinecraftServerKind : ushort {
|
||||||
Vanilla = 1,
|
Vanilla = 1,
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Minecraft;
|
namespace Phantom.Common.Data.Web.Minecraft;
|
||||||
|
|
||||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||||
public sealed partial record MinecraftVersion(
|
public sealed partial record MinecraftVersion(
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Minecraft;
|
namespace Phantom.Common.Data.Web.Minecraft;
|
||||||
|
|
||||||
public enum MinecraftVersionType : ushort {
|
public enum MinecraftVersionType : ushort {
|
||||||
Other = 0,
|
Other = 0,
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Common.Data.Backups;
|
using Phantom.Common.Data.Backups;
|
||||||
using Phantom.Common.Data.Instance.Launch;
|
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Instance;
|
namespace Phantom.Common.Data.Instance;
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
using System.Collections.Immutable;
|
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Instance;
|
|
||||||
|
|
||||||
public interface IInstancePathResolver {
|
|
||||||
string? Global(ImmutableArray<string> path);
|
|
||||||
string? Local(ImmutableArray<string> path);
|
|
||||||
string? Runtime(Guid guid);
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Common.Data.Instance.Launch;
|
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Instance;
|
namespace Phantom.Common.Data.Instance;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
namespace Phantom.Common.Data.Instance;
|
|
||||||
|
|
||||||
public interface IInstanceValueResolver {
|
|
||||||
string? Path(IInstancePath value);
|
|
||||||
string? Variable(InstanceVariable value);
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace Phantom.Common.Data.Instance.Launch;
|
namespace Phantom.Common.Data.Instance;
|
||||||
|
|
||||||
public enum InstanceLaunchFailReason : byte {
|
public enum InstanceLaunchFailReason : byte {
|
||||||
UnknownError = 0,
|
UnknownError = 0,
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
using System.Collections.Immutable;
|
|
||||||
using Phantom.Common.Data.Minecraft;
|
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Instance.Launch;
|
|
||||||
|
|
||||||
public interface IInstanceLaunchStepExecutor {
|
|
||||||
Task DownloadFile(FileDownloadInfo downloadInfo, IInstancePath path);
|
|
||||||
Task EditPropertiesFile(InstancePath.Local path, string comment, ImmutableDictionary<string, string> newValues);
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
using MemoryPack;
|
|
||||||
|
|
||||||
namespace Phantom.Common.Data.Minecraft;
|
|
||||||
|
|
||||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
|
||||||
public sealed partial record MinecraftStopStrategy(
|
|
||||||
[property: MemoryPackOrder(0)] ushort Seconds
|
|
||||||
) {
|
|
||||||
public static MinecraftStopStrategy Instant => new (0);
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Utils.Monads;
|
|
||||||
using Phantom.Utils.Result;
|
using Phantom.Utils.Result;
|
||||||
|
|
||||||
namespace Phantom.Common.Data;
|
namespace Phantom.Common.Data;
|
||||||
@@ -25,9 +24,6 @@ public sealed partial class Result<TValue, TError> {
|
|||||||
[MemoryPackIgnore]
|
[MemoryPackIgnore]
|
||||||
public TError Error => !hasValue ? error! : throw new InvalidOperationException("Attempted to get error from a success result.");
|
public TError Error => !hasValue ? error! : throw new InvalidOperationException("Attempted to get error from a success result.");
|
||||||
|
|
||||||
[MemoryPackIgnore]
|
|
||||||
public Either<TValue, TError> AsEither => hasValue ? Either.Left(value!) : Either.Right(error!);
|
|
||||||
|
|
||||||
private Result(bool hasValue, TValue? value, TError? error) {
|
private Result(bool hasValue, TValue? value, TError? error) {
|
||||||
this.hasValue = hasValue;
|
this.hasValue = hasValue;
|
||||||
this.value = value;
|
this.value = value;
|
||||||
@@ -38,6 +34,11 @@ public sealed partial class Result<TValue, TError> {
|
|||||||
return hasValue && EqualityComparer<TValue>.Default.Equals(value, expectedValue);
|
return hasValue && EqualityComparer<TValue>.Default.Equals(value, expectedValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[return: NotNullIfNotNull(nameof(valueIfError))]
|
||||||
|
public TValue? OrElse(TValue? valueIfError) {
|
||||||
|
return hasValue ? Value : valueIfError;
|
||||||
|
}
|
||||||
|
|
||||||
public TOutput Into<TOutput>(Func<TValue, TOutput> valueConverter, Func<TError, TOutput> errorConverter) {
|
public TOutput Into<TOutput>(Func<TValue, TOutput> valueConverter, Func<TError, TOutput> errorConverter) {
|
||||||
return hasValue ? valueConverter(value!) : errorConverter(error!);
|
return hasValue ? valueConverter(value!) : errorConverter(error!);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Phantom.Common.Data\Phantom.Common.Data.csproj" />
|
<ProjectReference Include="..\Phantom.Common.Data.Agent\Phantom.Common.Data.Agent.csproj" />
|
||||||
<ProjectReference Include="..\..\Utils\Phantom.Utils.Logging\Phantom.Utils.Logging.csproj" />
|
<ProjectReference Include="..\..\Utils\Phantom.Utils.Logging\Phantom.Utils.Logging.csproj" />
|
||||||
<ProjectReference Include="..\..\Utils\Phantom.Utils.Rpc\Phantom.Utils.Rpc.csproj" />
|
<ProjectReference Include="..\..\Utils\Phantom.Utils.Rpc\Phantom.Utils.Rpc.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Common.Data;
|
using Phantom.Common.Data;
|
||||||
using Phantom.Common.Data.Instance;
|
using Phantom.Common.Data.Agent.Instance;
|
||||||
using Phantom.Common.Data.Instance.Launch;
|
using Phantom.Common.Data.Agent.Instance.Launch;
|
||||||
|
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||||
using Phantom.Common.Data.Replies;
|
using Phantom.Common.Data.Replies;
|
||||||
using Phantom.Utils.Actor;
|
using Phantom.Utils.Actor;
|
||||||
|
|
||||||
@@ -12,5 +13,6 @@ public sealed partial record ConfigureInstanceMessage(
|
|||||||
[property: MemoryPackOrder(0)] Guid InstanceGuid,
|
[property: MemoryPackOrder(0)] Guid InstanceGuid,
|
||||||
[property: MemoryPackOrder(1)] InstanceInfo Info,
|
[property: MemoryPackOrder(1)] InstanceInfo Info,
|
||||||
[property: MemoryPackOrder(2)] InstanceLaunchRecipe? LaunchRecipe,
|
[property: MemoryPackOrder(2)] InstanceLaunchRecipe? LaunchRecipe,
|
||||||
[property: MemoryPackOrder(3)] bool LaunchNow = false
|
[property: MemoryPackOrder(3)] bool LaunchNow,
|
||||||
|
[property: MemoryPackOrder(4)] InstanceStopRecipe StopRecipe
|
||||||
) : IMessageToAgent, ICanReply<Result<ConfigureInstanceResult, InstanceActionFailure>>;
|
) : IMessageToAgent, ICanReply<Result<ConfigureInstanceResult, InstanceActionFailure>>;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Common.Data;
|
using Phantom.Common.Data;
|
||||||
using Phantom.Common.Data.Minecraft;
|
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||||
using Phantom.Common.Data.Replies;
|
using Phantom.Common.Data.Replies;
|
||||||
using Phantom.Utils.Actor;
|
using Phantom.Utils.Actor;
|
||||||
|
|
||||||
@@ -9,5 +9,5 @@ namespace Phantom.Common.Messages.Agent.ToAgent;
|
|||||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||||
public sealed partial record StopInstanceMessage(
|
public sealed partial record StopInstanceMessage(
|
||||||
[property: MemoryPackOrder(0)] Guid InstanceGuid,
|
[property: MemoryPackOrder(0)] Guid InstanceGuid,
|
||||||
[property: MemoryPackOrder(1)] MinecraftStopStrategy StopStrategy
|
[property: MemoryPackOrder(1)] InstanceStopRecipe StopRecipe
|
||||||
) : IMessageToAgent, ICanReply<Result<StopInstanceResult, InstanceActionFailure>>;
|
) : IMessageToAgent, ICanReply<Result<StopInstanceResult, InstanceActionFailure>>;
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Common.Data;
|
using Phantom.Common.Data;
|
||||||
using Phantom.Common.Data.Instance;
|
|
||||||
using Phantom.Common.Data.Web.Instance;
|
using Phantom.Common.Data.Web.Instance;
|
||||||
using Phantom.Common.Data.Web.Users;
|
using Phantom.Common.Data.Web.Users;
|
||||||
using Phantom.Utils.Actor;
|
using Phantom.Utils.Actor;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Common.Data.Minecraft;
|
using Phantom.Common.Data.Web.Minecraft;
|
||||||
using Phantom.Utils.Actor;
|
using Phantom.Utils.Actor;
|
||||||
|
|
||||||
namespace Phantom.Common.Messages.Web.ToController;
|
namespace Phantom.Common.Messages.Web.ToController;
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using MemoryPack;
|
using MemoryPack;
|
||||||
using Phantom.Common.Data;
|
using Phantom.Common.Data;
|
||||||
using Phantom.Common.Data.Minecraft;
|
|
||||||
using Phantom.Common.Data.Replies;
|
using Phantom.Common.Data.Replies;
|
||||||
using Phantom.Common.Data.Web.Users;
|
using Phantom.Common.Data.Web.Users;
|
||||||
using Phantom.Utils.Actor;
|
using Phantom.Utils.Actor;
|
||||||
@@ -13,5 +12,5 @@ public sealed partial record StopInstanceMessage(
|
|||||||
[property: MemoryPackOrder(0)] ImmutableArray<byte> AuthToken,
|
[property: MemoryPackOrder(0)] ImmutableArray<byte> AuthToken,
|
||||||
[property: MemoryPackOrder(1)] Guid AgentGuid,
|
[property: MemoryPackOrder(1)] Guid AgentGuid,
|
||||||
[property: MemoryPackOrder(2)] Guid InstanceGuid,
|
[property: MemoryPackOrder(2)] Guid InstanceGuid,
|
||||||
[property: MemoryPackOrder(3)] MinecraftStopStrategy StopStrategy
|
[property: MemoryPackOrder(3)] ushort AfterSeconds
|
||||||
) : IMessageToController, ICanReply<Result<StopInstanceResult, UserInstanceActionFailure>>;
|
) : IMessageToController, ICanReply<Result<StopInstanceResult, UserInstanceActionFailure>>;
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using Phantom.Common.Data;
|
using Phantom.Common.Data;
|
||||||
using Phantom.Common.Data.Java;
|
using Phantom.Common.Data.Java;
|
||||||
using Phantom.Common.Data.Minecraft;
|
|
||||||
using Phantom.Common.Data.Replies;
|
using Phantom.Common.Data.Replies;
|
||||||
using Phantom.Common.Data.Web.Agent;
|
using Phantom.Common.Data.Web.Agent;
|
||||||
using Phantom.Common.Data.Web.AuditLog;
|
using Phantom.Common.Data.Web.AuditLog;
|
||||||
using Phantom.Common.Data.Web.EventLog;
|
using Phantom.Common.Data.Web.EventLog;
|
||||||
using Phantom.Common.Data.Web.Instance;
|
using Phantom.Common.Data.Web.Instance;
|
||||||
|
using Phantom.Common.Data.Web.Minecraft;
|
||||||
using Phantom.Common.Data.Web.Users;
|
using Phantom.Common.Data.Web.Users;
|
||||||
using Phantom.Common.Messages.Web.ToController;
|
using Phantom.Common.Messages.Web.ToController;
|
||||||
using Phantom.Common.Messages.Web.ToWeb;
|
using Phantom.Common.Messages.Web.ToWeb;
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
using Phantom.Common.Data;
|
using Phantom.Common.Data;
|
||||||
using Phantom.Common.Data.Minecraft;
|
|
||||||
using Phantom.Common.Data.Web.AuditLog;
|
using Phantom.Common.Data.Web.AuditLog;
|
||||||
using Phantom.Common.Data.Web.EventLog;
|
using Phantom.Common.Data.Web.EventLog;
|
||||||
|
using Phantom.Common.Data.Web.Minecraft;
|
||||||
using Phantom.Controller.Database.Converters;
|
using Phantom.Controller.Database.Converters;
|
||||||
using Phantom.Controller.Database.Entities;
|
using Phantom.Controller.Database.Entities;
|
||||||
using Phantom.Controller.Database.Factories;
|
using Phantom.Controller.Database.Factories;
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
using System.ComponentModel.DataAnnotations.Schema;
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using Phantom.Common.Data;
|
using Phantom.Common.Data;
|
||||||
using Phantom.Common.Data.Minecraft;
|
using Phantom.Common.Data.Web.Minecraft;
|
||||||
|
|
||||||
namespace Phantom.Controller.Database.Entities;
|
namespace Phantom.Controller.Database.Entities;
|
||||||
|
|
||||||
|
|||||||
@@ -87,10 +87,8 @@ sealed partial class AuditLogRepository {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public void InstanceStopped(Guid instanceGuid, int stopInSeconds) {
|
public void InstanceStopped(Guid instanceGuid) {
|
||||||
AddItem(AuditLogEventType.InstanceStopped, instanceGuid.ToString(), new Dictionary<string, object?> {
|
AddItem(AuditLogEventType.InstanceStopped, instanceGuid.ToString());
|
||||||
{ "stop_in_seconds", stopInSeconds.ToString() },
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,34 +1,29 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using Phantom.Common.Data.Instance;
|
using Phantom.Common.Data;
|
||||||
using Phantom.Common.Data.Instance.Launch;
|
using Phantom.Common.Data.Agent;
|
||||||
using Phantom.Common.Data.Minecraft;
|
using Phantom.Common.Data.Agent.Instance;
|
||||||
|
using Phantom.Common.Data.Agent.Instance.Launch;
|
||||||
|
using Phantom.Common.Data.Web.Instance;
|
||||||
|
using Phantom.Common.Data.Web.Minecraft;
|
||||||
using Phantom.Utils.Collections;
|
using Phantom.Utils.Collections;
|
||||||
|
|
||||||
namespace Phantom.Controller.Minecraft;
|
namespace Phantom.Controller.Minecraft;
|
||||||
|
|
||||||
public sealed partial class MinecraftLaunchRecipes(MinecraftVersions minecraftVersions) {
|
public sealed partial class MinecraftInstanceRecipes(MinecraftVersions minecraftVersions) {
|
||||||
[GeneratedRegex(@"[^a-zA-Z0-9_\-\.]", RegexOptions.Compiled)]
|
public async Task<Result<InstanceLaunchRecipe, MinecraftLaunchRecipeCreationFailReason>> Launch(InstanceConfiguration configuration, CancellationToken cancellationToken) {
|
||||||
private static partial Regex SanitizePathRegex();
|
|
||||||
|
|
||||||
private static readonly ImmutableDictionary<string, string> Eula = ImmutableDictionary.From([
|
|
||||||
("eula", "true"),
|
|
||||||
]);
|
|
||||||
|
|
||||||
public async Task<InstanceLaunchRecipe?> Create(InstanceConfiguration configuration, CancellationToken cancellationToken) {
|
|
||||||
string minecraftVersion = configuration.MinecraftVersion;
|
string minecraftVersion = configuration.MinecraftVersion;
|
||||||
string minecraftVersionPath = SanitizePathRegex().IsMatch(minecraftVersion) ? SanitizePathRegex().Replace(minecraftVersion, "_") : minecraftVersion;
|
|
||||||
|
var serverExecutableInfo = await minecraftVersions.GetServerExecutableInfo(minecraftVersion, cancellationToken);
|
||||||
|
if (serverExecutableInfo == null) {
|
||||||
|
return MinecraftLaunchRecipeCreationFailReason.MinecraftVersionNotFound;
|
||||||
|
}
|
||||||
|
|
||||||
uint maximumHeapSizeMegabvtes = configuration.MemoryAllocation.InMegabytes;
|
uint maximumHeapSizeMegabvtes = configuration.MemoryAllocation.InMegabytes;
|
||||||
uint initialHeapSizeMegabytes = maximumHeapSizeMegabvtes / 2;
|
uint initialHeapSizeMegabytes = maximumHeapSizeMegabvtes / 2;
|
||||||
|
|
||||||
var serverExecutableInfo = await minecraftVersions.GetServerExecutableInfo(minecraftVersion, cancellationToken);
|
var minecraftVersionPathSegment = SanitizePath(minecraftVersion);
|
||||||
if (serverExecutableInfo == null) {
|
var vanillaJarFilePath = new InstancePath.Global(["minecraft", "vanilla", minecraftVersionPathSegment, "server.jar"]);
|
||||||
// TODO
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var vanillaJarFilePath = new InstancePath.Global(["minecraft", "vanilla", minecraftVersionPath, "server.jar"]);
|
|
||||||
|
|
||||||
var steps = ImmutableArray.CreateBuilder<IInstanceLaunchStep>();
|
var steps = ImmutableArray.CreateBuilder<IInstanceLaunchStep>();
|
||||||
|
|
||||||
@@ -40,12 +35,8 @@ public sealed partial class MinecraftLaunchRecipes(MinecraftVersions minecraftVe
|
|||||||
var additionalJvmArguments = new List<IInstanceValue>();
|
var additionalJvmArguments = new List<IInstanceValue>();
|
||||||
|
|
||||||
if (configuration.MinecraftServerKind == MinecraftServerKind.Fabric) {
|
if (configuration.MinecraftServerKind == MinecraftServerKind.Fabric) {
|
||||||
// TODO customizable loader version
|
var fabricLauncherFilePath = new InstancePath.Global(["minecraft", "fabric", minecraftVersionPathSegment, "loader.jar"]);
|
||||||
string fabricLauncherUrl = $"https://meta.fabricmc.net/v2/versions/loader/{minecraftVersion}/stable/stable/server/jar";
|
AddFabricDownloadStep(steps, configuration, fabricLauncherFilePath);
|
||||||
|
|
||||||
var fabricLauncherFilePath = new InstancePath.Global(["minecraft", "fabric", minecraftVersionPath, "loader.jar"]);
|
|
||||||
|
|
||||||
steps.Add(new InstanceLaunchStep.DownloadFile(new FileDownloadInfo(fabricLauncherUrl), fabricLauncherFilePath));
|
|
||||||
|
|
||||||
serverExecutableFilePath = fabricLauncherFilePath;
|
serverExecutableFilePath = fabricLauncherFilePath;
|
||||||
|
|
||||||
@@ -58,14 +49,25 @@ public sealed partial class MinecraftLaunchRecipes(MinecraftVersions minecraftVe
|
|||||||
return new InstanceLaunchRecipe(steps.ToImmutable(), new InstancePath.Runtime(configuration.JavaRuntimeGuid), [
|
return new InstanceLaunchRecipe(steps.ToImmutable(), new InstancePath.Runtime(configuration.JavaRuntimeGuid), [
|
||||||
..configuration.JvmArguments.Select(static arg => new InstanceValues.Text(arg)),
|
..configuration.JvmArguments.Select(static arg => new InstanceValues.Text(arg)),
|
||||||
..additionalJvmArguments,
|
..additionalJvmArguments,
|
||||||
new InstanceValues.Text("-Xms" + initialHeapSizeMegabytes + "M"),
|
new InstanceValues.Text($"-Xms{initialHeapSizeMegabytes}M"),
|
||||||
new InstanceValues.Text("-Xmx" + maximumHeapSizeMegabvtes + "M"),
|
new InstanceValues.Text($"-Xmx{maximumHeapSizeMegabvtes}M"),
|
||||||
new InstanceValues.Text("-jar"),
|
new InstanceValues.Text("-jar"),
|
||||||
new InstanceValues.Path(serverExecutableFilePath),
|
new InstanceValues.Path(serverExecutableFilePath),
|
||||||
new InstanceValues.Text("-nogui"),
|
new InstanceValues.Text("-nogui"),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[GeneratedRegex(@"[^a-zA-Z0-9_\-\.]", RegexOptions.Compiled)]
|
||||||
|
private static partial Regex SanitizePathRegex();
|
||||||
|
|
||||||
|
private static string SanitizePath(string path) {
|
||||||
|
return SanitizePathRegex().IsMatch(path) ? SanitizePathRegex().Replace(path, "_") : path;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly ImmutableDictionary<string, string> Eula = ImmutableDictionary.From([
|
||||||
|
("eula", "true"),
|
||||||
|
]);
|
||||||
|
|
||||||
private static ImmutableDictionary<string, string> ServerProperties(InstanceConfiguration configuration) {
|
private static ImmutableDictionary<string, string> ServerProperties(InstanceConfiguration configuration) {
|
||||||
return ImmutableDictionary.From([
|
return ImmutableDictionary.From([
|
||||||
("server-port", configuration.ServerPort.ToString()),
|
("server-port", configuration.ServerPort.ToString()),
|
||||||
@@ -74,4 +76,11 @@ public sealed partial class MinecraftLaunchRecipes(MinecraftVersions minecraftVe
|
|||||||
("sync-chunk-writes", "false"),
|
("sync-chunk-writes", "false"),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void AddFabricDownloadStep(ImmutableArray<IInstanceLaunchStep>.Builder steps, InstanceConfiguration configuration, InstancePath.Global filePath) {
|
||||||
|
// TODO customizable loader version
|
||||||
|
string minecraftVersion = configuration.MinecraftVersion;
|
||||||
|
string fabricLauncherUrl = $"https://meta.fabricmc.net/v2/versions/loader/{minecraftVersion}/stable/stable/server/jar";
|
||||||
|
steps.Add(new InstanceLaunchStep.DownloadFile(new FileDownloadInfo(fabricLauncherUrl), filePath));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
using System.Collections.Immutable;
|
||||||
|
using Phantom.Common.Data.Agent.Instance;
|
||||||
|
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||||
|
|
||||||
|
namespace Phantom.Controller.Minecraft;
|
||||||
|
|
||||||
|
public sealed partial class MinecraftInstanceRecipes {
|
||||||
|
private static readonly ushort[] Stops = [60, 30, 10, 5, 4, 3, 2, 1];
|
||||||
|
private static readonly IInstanceValue StopCommand = new InstanceValues.Text("stop");
|
||||||
|
|
||||||
|
private static InstanceValues.Text SayCommand(string message) {
|
||||||
|
return new InstanceValues.Text($"say {message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static InstanceValues.Text SayCountDownAnnouncementCommand(ushort seconds) {
|
||||||
|
return SayCommand("Server shutting down in " + seconds + (seconds == 1 ? " second." : " seconds."));
|
||||||
|
}
|
||||||
|
|
||||||
|
public InstanceStopRecipe Stop(ushort afterSeconds) {
|
||||||
|
var steps = ImmutableArray.CreateBuilder<IInstanceStopStep>();
|
||||||
|
|
||||||
|
if (afterSeconds > 0) {
|
||||||
|
steps.Add(new InstanceStopStep.SendToStandardInput(SayCountDownAnnouncementCommand(afterSeconds)));
|
||||||
|
|
||||||
|
int remainingSeconds = afterSeconds;
|
||||||
|
|
||||||
|
for (int stopIndex = Array.FindIndex(Stops, stop => stop < afterSeconds); stopIndex != -1 && stopIndex < Stops.Length; stopIndex++) {
|
||||||
|
ushort currentStop = Stops[stopIndex];
|
||||||
|
|
||||||
|
steps.Add(new InstanceStopStep.Wait(TimeSpan.FromSeconds(remainingSeconds - currentStop)));
|
||||||
|
steps.Add(new InstanceStopStep.SendToStandardInput(SayCountDownAnnouncementCommand(currentStop)));
|
||||||
|
|
||||||
|
remainingSeconds = currentStop;
|
||||||
|
}
|
||||||
|
|
||||||
|
steps.Add(new InstanceStopStep.Wait(TimeSpan.FromSeconds(remainingSeconds)));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new InstanceStopRecipe(steps.ToImmutable(), StopCommand);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace Phantom.Controller.Minecraft;
|
||||||
|
|
||||||
|
public enum MinecraftLaunchRecipeCreationFailReason : byte {
|
||||||
|
UnknownError = 0,
|
||||||
|
MinecraftVersionNotFound = 1,
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using System.Net.Http.Json;
|
using System.Net.Http.Json;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Phantom.Common.Data.Minecraft;
|
using Phantom.Common.Data.Agent;
|
||||||
|
using Phantom.Common.Data.Web.Minecraft;
|
||||||
using Phantom.Utils.Cryptography;
|
using Phantom.Utils.Cryptography;
|
||||||
using Phantom.Utils.Logging;
|
using Phantom.Utils.Logging;
|
||||||
using Phantom.Utils.Runtime;
|
using Phantom.Utils.Runtime;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using Phantom.Common.Data.Minecraft;
|
using Phantom.Common.Data.Agent;
|
||||||
|
using Phantom.Common.Data.Web.Minecraft;
|
||||||
using Phantom.Utils.Logging;
|
using Phantom.Utils.Logging;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
|
|
||||||
@@ -34,7 +35,7 @@ public sealed class MinecraftVersions : IDisposable {
|
|||||||
return versions;
|
return versions;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<FileDownloadInfo?> GetServerExecutableInfo(string version, CancellationToken cancellationToken) {
|
internal async Task<FileDownloadInfo?> GetServerExecutableInfo(string version, CancellationToken cancellationToken) {
|
||||||
var versions = await GetVersions(cancellationToken);
|
var versions = await GetVersions(cancellationToken);
|
||||||
return await GetCachedObject(() => cachedServerExecutables.ContainsKey(version), () => cachedServerExecutables[version], v => cachedServerExecutables[version] = v, ct => LoadServerExecutableInfo(versions, version, ct), cancellationToken);
|
return await GetCachedObject(() => cachedServerExecutables.ContainsKey(version), () => cachedServerExecutables[version], v => cachedServerExecutables[version] = v, ct => LoadServerExecutableInfo(versions, version, ct), cancellationToken);
|
||||||
}
|
}
|
||||||
@@ -46,7 +47,7 @@ public sealed class MinecraftVersions : IDisposable {
|
|||||||
Logger.Information("Refreshed Minecraft {Version} server executable cache, no file found.", version);
|
Logger.Information("Refreshed Minecraft {Version} server executable cache, no file found.", version);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
Logger.Information("Refreshed Minecraft {Version} server executable cache, found file: {Url}.", version, info.DownloadUrl);
|
Logger.Information("Refreshed Minecraft {Version} server executable cache, found file: {Url}.", version, info.Url);
|
||||||
}
|
}
|
||||||
|
|
||||||
return info;
|
return info;
|
||||||
|
|||||||
@@ -6,7 +6,8 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\Common\Phantom.Common.Data\Phantom.Common.Data.csproj" />
|
<ProjectReference Include="..\..\Common\Phantom.Common.Data.Agent\Phantom.Common.Data.Agent.csproj" />
|
||||||
|
<ProjectReference Include="..\..\Common\Phantom.Common.Data.Web\Phantom.Common.Data.Web.csproj" />
|
||||||
<ProjectReference Include="..\..\Utils\Phantom.Utils\Phantom.Utils.csproj" />
|
<ProjectReference Include="..\..\Utils\Phantom.Utils\Phantom.Utils.csproj" />
|
||||||
<ProjectReference Include="..\..\Utils\Phantom.Utils.Logging\Phantom.Utils.Logging.csproj" />
|
<ProjectReference Include="..\..\Utils\Phantom.Utils.Logging\Phantom.Utils.Logging.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -2,15 +2,13 @@
|
|||||||
using Akka.Actor;
|
using Akka.Actor;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Phantom.Common.Data;
|
using Phantom.Common.Data;
|
||||||
using Phantom.Common.Data.Agent;
|
using Phantom.Common.Data.Agent.Instance.Launch;
|
||||||
using Phantom.Common.Data.Instance;
|
using Phantom.Common.Data.Instance;
|
||||||
using Phantom.Common.Data.Instance.Launch;
|
|
||||||
using Phantom.Common.Data.Java;
|
using Phantom.Common.Data.Java;
|
||||||
using Phantom.Common.Data.Minecraft;
|
|
||||||
using Phantom.Common.Data.Replies;
|
using Phantom.Common.Data.Replies;
|
||||||
using Phantom.Common.Data.Web.Agent;
|
using Phantom.Common.Data.Web.Agent;
|
||||||
using Phantom.Common.Data.Web.Instance;
|
using Phantom.Common.Data.Web.Instance;
|
||||||
using Phantom.Common.Data.Web.Minecraft;
|
using Phantom.Common.Data.Web.Java;
|
||||||
using Phantom.Common.Messages.Agent;
|
using Phantom.Common.Messages.Agent;
|
||||||
using Phantom.Common.Messages.Agent.ToAgent;
|
using Phantom.Common.Messages.Agent.ToAgent;
|
||||||
using Phantom.Controller.Database;
|
using Phantom.Controller.Database;
|
||||||
@@ -42,7 +40,7 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
|||||||
AgentRuntimeInfo AgentRuntimeInfo,
|
AgentRuntimeInfo AgentRuntimeInfo,
|
||||||
AgentConnectionKeys AgentConnectionKeys,
|
AgentConnectionKeys AgentConnectionKeys,
|
||||||
ControllerState ControllerState,
|
ControllerState ControllerState,
|
||||||
MinecraftLaunchRecipes LaunchRecipes,
|
MinecraftInstanceRecipes MinecraftInstanceRecipes,
|
||||||
IDbContextProvider DbProvider,
|
IDbContextProvider DbProvider,
|
||||||
CancellationToken CancellationToken
|
CancellationToken CancellationToken
|
||||||
);
|
);
|
||||||
@@ -55,7 +53,7 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
|||||||
|
|
||||||
private readonly AgentConnectionKeys agentConnectionKeys;
|
private readonly AgentConnectionKeys agentConnectionKeys;
|
||||||
private readonly ControllerState controllerState;
|
private readonly ControllerState controllerState;
|
||||||
private readonly MinecraftLaunchRecipes launchRecipes;
|
private readonly MinecraftInstanceRecipes minecraftInstanceRecipes;
|
||||||
private readonly IDbContextProvider dbProvider;
|
private readonly IDbContextProvider dbProvider;
|
||||||
private readonly CancellationToken cancellationToken;
|
private readonly CancellationToken cancellationToken;
|
||||||
|
|
||||||
@@ -96,7 +94,7 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
|||||||
private AgentActor(Init init) {
|
private AgentActor(Init init) {
|
||||||
this.agentConnectionKeys = init.AgentConnectionKeys;
|
this.agentConnectionKeys = init.AgentConnectionKeys;
|
||||||
this.controllerState = init.ControllerState;
|
this.controllerState = init.ControllerState;
|
||||||
this.launchRecipes = init.LaunchRecipes;
|
this.minecraftInstanceRecipes = init.MinecraftInstanceRecipes;
|
||||||
this.dbProvider = init.DbProvider;
|
this.dbProvider = init.DbProvider;
|
||||||
this.cancellationToken = init.CancellationToken;
|
this.cancellationToken = init.CancellationToken;
|
||||||
|
|
||||||
@@ -191,17 +189,15 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
|||||||
var configurationMessages = ImmutableArray.CreateBuilder<ConfigureInstanceMessage>();
|
var configurationMessages = ImmutableArray.CreateBuilder<ConfigureInstanceMessage>();
|
||||||
|
|
||||||
foreach (var (instanceGuid, instanceConfiguration, _, _, launchAutomatically) in instanceDataByGuid.Values.ToImmutableArray()) {
|
foreach (var (instanceGuid, instanceConfiguration, _, _, launchAutomatically) in instanceDataByGuid.Values.ToImmutableArray()) {
|
||||||
var launchRecipe = await CreateInstanceLaunchRecipe(instanceConfiguration);
|
var launchRecipe = await minecraftInstanceRecipes.Launch(instanceConfiguration, cancellationToken);
|
||||||
configurationMessages.Add(new ConfigureInstanceMessage(instanceGuid, instanceConfiguration.AsInfo, launchRecipe, launchAutomatically));
|
var stopRecipe = minecraftInstanceRecipes.Stop(0);
|
||||||
|
var configurationMessage = new ConfigureInstanceMessage(instanceGuid, instanceConfiguration.AsInfo, launchRecipe.OrElse(null), launchAutomatically, stopRecipe);
|
||||||
|
configurationMessages.Add(configurationMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
return configurationMessages.ToImmutable();
|
return configurationMessages.ToImmutable();
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<InstanceLaunchRecipe?> CreateInstanceLaunchRecipe(InstanceConfiguration configuration) {
|
|
||||||
return await launchRecipes.Create(configuration, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public interface ICommand;
|
public interface ICommand;
|
||||||
|
|
||||||
private sealed record InitializeCommand : ICommand;
|
private sealed record InitializeCommand : ICommand;
|
||||||
@@ -230,7 +226,7 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
|||||||
|
|
||||||
public sealed record LaunchInstanceCommand(Guid LoggedInUserGuid, Guid InstanceGuid) : ICommand, ICanReply<Result<LaunchInstanceResult, InstanceActionFailure>>;
|
public sealed record LaunchInstanceCommand(Guid LoggedInUserGuid, Guid InstanceGuid) : ICommand, ICanReply<Result<LaunchInstanceResult, InstanceActionFailure>>;
|
||||||
|
|
||||||
public sealed record StopInstanceCommand(Guid LoggedInUserGuid, Guid InstanceGuid, MinecraftStopStrategy StopStrategy) : ICommand, ICanReply<Result<StopInstanceResult, InstanceActionFailure>>;
|
public sealed record StopInstanceCommand(Guid LoggedInUserGuid, Guid InstanceGuid, ushort AfterSeconds) : ICommand, ICanReply<Result<StopInstanceResult, InstanceActionFailure>>;
|
||||||
|
|
||||||
public sealed record SendCommandToInstanceCommand(Guid LoggedInUserGuid, Guid InstanceGuid, string Command) : ICommand, ICanReply<Result<SendCommandToInstanceResult, InstanceActionFailure>>;
|
public sealed record SendCommandToInstanceCommand(Guid LoggedInUserGuid, Guid InstanceGuid, string Command) : ICommand, ICanReply<Result<SendCommandToInstanceResult, InstanceActionFailure>>;
|
||||||
|
|
||||||
@@ -345,30 +341,35 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
|||||||
return Task.FromResult<Result<CreateOrUpdateInstanceResult, InstanceActionFailure>>(CreateOrUpdateInstanceResult.InstanceMemoryMustNotBeZero);
|
return Task.FromResult<Result<CreateOrUpdateInstanceResult, InstanceActionFailure>>(CreateOrUpdateInstanceResult.InstanceMemoryMustNotBeZero);
|
||||||
}
|
}
|
||||||
|
|
||||||
return launchRecipes.Create(instanceConfiguration, cancellationToken)
|
return minecraftInstanceRecipes.Launch(instanceConfiguration, cancellationToken)
|
||||||
.ContinueOnActor(CreateOrUpdateInstance1, command)
|
.ContinueOnActor(CreateOrUpdateInstance1, command)
|
||||||
.Unwrap();
|
.Unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task<Result<CreateOrUpdateInstanceResult, InstanceActionFailure>> CreateOrUpdateInstance1(InstanceLaunchRecipe? launchRecipe, CreateOrUpdateInstanceCommand command) {
|
private Task<Result<CreateOrUpdateInstanceResult, InstanceActionFailure>> CreateOrUpdateInstance1(Result<InstanceLaunchRecipe, MinecraftLaunchRecipeCreationFailReason> launchRecipe, CreateOrUpdateInstanceCommand command) {
|
||||||
if (launchRecipe == null) {
|
if (!launchRecipe) {
|
||||||
// TODO
|
return Task.FromResult<Result<CreateOrUpdateInstanceResult, InstanceActionFailure>>(launchRecipe.Error switch {
|
||||||
return Task.FromResult<Result<CreateOrUpdateInstanceResult, InstanceActionFailure>>(CreateOrUpdateInstanceResult.MinecraftVersionDownloadInfoNotFound);
|
MinecraftLaunchRecipeCreationFailReason.MinecraftVersionNotFound => CreateOrUpdateInstanceResult.MinecraftVersionNotFound,
|
||||||
|
_ => CreateOrUpdateInstanceResult.UnknownError,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var instanceGuid = command.InstanceGuid;
|
||||||
var instanceConfiguration = command.Configuration;
|
var instanceConfiguration = command.Configuration;
|
||||||
|
|
||||||
bool isCreatingInstance = !instanceActorByGuid.TryGetValue(command.InstanceGuid, out var instanceActorRef);
|
bool isCreatingInstance = !instanceActorByGuid.TryGetValue(instanceGuid, out var instanceActorRef);
|
||||||
if (isCreatingInstance) {
|
if (isCreatingInstance) {
|
||||||
instanceActorRef = CreateNewInstance(Instance.Offline(command.InstanceGuid, instanceConfiguration));
|
instanceActorRef = CreateNewInstance(Instance.Offline(instanceGuid, instanceConfiguration));
|
||||||
}
|
}
|
||||||
|
|
||||||
var configureInstanceCommand = new InstanceActor.ConfigureInstanceCommand(command.LoggedInUserGuid, command.InstanceGuid, instanceConfiguration, launchRecipe, isCreatingInstance);
|
var stopRecipe = minecraftInstanceRecipes.Stop(afterSeconds: 0);
|
||||||
|
var configureInstanceCommand = new InstanceActor.ConfigureInstanceCommand(command.LoggedInUserGuid, instanceGuid, instanceConfiguration, launchRecipe.Value, stopRecipe, isCreatingInstance);
|
||||||
|
|
||||||
return instanceActorRef.Request(configureInstanceCommand, cancellationToken)
|
return instanceActorRef.Request(configureInstanceCommand, cancellationToken)
|
||||||
.ContinueOnActor(CreateOrUpdateInstance2, configureInstanceCommand);
|
.ContinueOnActor(CreateOrUpdateInstance2, configureInstanceCommand);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#pragma warning disable CA2254
|
||||||
private Result<CreateOrUpdateInstanceResult, InstanceActionFailure> CreateOrUpdateInstance2(Result<ConfigureInstanceResult, InstanceActionFailure> result, InstanceActor.ConfigureInstanceCommand command) {
|
private Result<CreateOrUpdateInstanceResult, InstanceActionFailure> CreateOrUpdateInstance2(Result<ConfigureInstanceResult, InstanceActionFailure> result, InstanceActor.ConfigureInstanceCommand command) {
|
||||||
var instanceGuid = command.InstanceGuid;
|
var instanceGuid = command.InstanceGuid;
|
||||||
var instanceName = command.Configuration.InstanceName;
|
var instanceName = command.Configuration.InstanceName;
|
||||||
@@ -388,6 +389,7 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
|||||||
return CreateOrUpdateInstanceResult.UnknownError;
|
return CreateOrUpdateInstanceResult.UnknownError;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#pragma warning restore CA2254
|
||||||
|
|
||||||
private void UpdateInstanceStatus(UpdateInstanceStatusCommand command) {
|
private void UpdateInstanceStatus(UpdateInstanceStatusCommand command) {
|
||||||
TellInstance(command.InstanceGuid, new InstanceActor.SetStatusCommand(command.Status));
|
TellInstance(command.InstanceGuid, new InstanceActor.SetStatusCommand(command.Status));
|
||||||
@@ -402,7 +404,8 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Task<Result<StopInstanceResult, InstanceActionFailure>> StopInstance(StopInstanceCommand command) {
|
private Task<Result<StopInstanceResult, InstanceActionFailure>> StopInstance(StopInstanceCommand command) {
|
||||||
return RequestInstance<InstanceActor.StopInstanceCommand, StopInstanceResult>(command.InstanceGuid, new InstanceActor.StopInstanceCommand(command.LoggedInUserGuid, command.StopStrategy));
|
var stopRecipe = minecraftInstanceRecipes.Stop(command.AfterSeconds);
|
||||||
|
return RequestInstance<InstanceActor.StopInstanceCommand, StopInstanceResult>(command.InstanceGuid, new InstanceActor.StopInstanceCommand(command.LoggedInUserGuid, stopRecipe));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task<Result<SendCommandToInstanceResult, InstanceActionFailure>> SendMinecraftCommand(SendCommandToInstanceCommand command) {
|
private Task<Result<SendCommandToInstanceResult, InstanceActionFailure>> SendMinecraftCommand(SendCommandToInstanceCommand command) {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ sealed class AgentManager(
|
|||||||
IActorRefFactory actorSystem,
|
IActorRefFactory actorSystem,
|
||||||
AgentConnectionKeys agentConnectionKeys,
|
AgentConnectionKeys agentConnectionKeys,
|
||||||
ControllerState controllerState,
|
ControllerState controllerState,
|
||||||
MinecraftLaunchRecipes launchRecipes,
|
MinecraftInstanceRecipes minecraftInstanceRecipes,
|
||||||
IDbContextProvider dbProvider,
|
IDbContextProvider dbProvider,
|
||||||
CancellationToken cancellationToken
|
CancellationToken cancellationToken
|
||||||
) {
|
) {
|
||||||
@@ -42,7 +42,7 @@ sealed class AgentManager(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private bool AddAgent(Guid? loggedInUserGuid, Guid agentGuid, AgentConfiguration configuration, AuthSecret authSecret, AgentRuntimeInfo runtimeInfo) {
|
private bool AddAgent(Guid? loggedInUserGuid, Guid agentGuid, AgentConfiguration configuration, AuthSecret authSecret, AgentRuntimeInfo runtimeInfo) {
|
||||||
var init = new AgentActor.Init(loggedInUserGuid, agentGuid, configuration, authSecret, runtimeInfo, agentConnectionKeys, controllerState, launchRecipes, dbProvider, cancellationToken);
|
var init = new AgentActor.Init(loggedInUserGuid, agentGuid, configuration, authSecret, runtimeInfo, agentConnectionKeys, controllerState, minecraftInstanceRecipes, dbProvider, cancellationToken);
|
||||||
var name = "Agent:" + agentGuid;
|
var name = "Agent:" + agentGuid;
|
||||||
return agentsByAgentGuid.TryAdd(agentGuid, actorSystem.ActorOf(AgentActor.Factory(init), name));
|
return agentsByAgentGuid.TryAdd(agentGuid, actorSystem.ActorOf(AgentActor.Factory(init), name));
|
||||||
}
|
}
|
||||||
@@ -52,8 +52,11 @@ sealed class AgentManager(
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var runtimeInfo = AgentRuntimeInfo.From(registration.AgentInfo);
|
var agentInfo = registration.AgentInfo;
|
||||||
return await agentActor.Request(new AgentActor.RegisterCommand(runtimeInfo, registration.JavaRuntimes), cancellationToken);
|
var agentVersionInfo = new AgentVersionInfo(agentInfo.ProtocolVersion, agentInfo.BuildVersion);
|
||||||
|
var agentRuntimeInfo = new AgentRuntimeInfo(agentVersionInfo, agentInfo.MaxInstances, agentInfo.MaxMemory, agentInfo.AllowedServerPorts, agentInfo.AllowedAdditionalPorts);
|
||||||
|
|
||||||
|
return await agentActor.Request(new AgentActor.RegisterCommand(agentRuntimeInfo, registration.JavaRuntimes), cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<AuthSecret?> GetAgentAuthSecret(Guid agentGuid) {
|
public async Task<AuthSecret?> GetAgentAuthSecret(Guid agentGuid) {
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public sealed class ControllerServices : IDisposable {
|
|||||||
|
|
||||||
private ControllerState ControllerState { get; }
|
private ControllerState ControllerState { get; }
|
||||||
private MinecraftVersions MinecraftVersions { get; }
|
private MinecraftVersions MinecraftVersions { get; }
|
||||||
private MinecraftLaunchRecipes LaunchRecipes { get; }
|
private MinecraftInstanceRecipes MinecraftInstanceRecipes { get; }
|
||||||
|
|
||||||
private AuthenticatedUserCache AuthenticatedUserCache { get; }
|
private AuthenticatedUserCache AuthenticatedUserCache { get; }
|
||||||
private UserManager UserManager { get; }
|
private UserManager UserManager { get; }
|
||||||
@@ -51,7 +51,7 @@ public sealed class ControllerServices : IDisposable {
|
|||||||
|
|
||||||
this.ControllerState = new ControllerState();
|
this.ControllerState = new ControllerState();
|
||||||
this.MinecraftVersions = new MinecraftVersions();
|
this.MinecraftVersions = new MinecraftVersions();
|
||||||
this.LaunchRecipes = new MinecraftLaunchRecipes(MinecraftVersions);
|
this.MinecraftInstanceRecipes = new MinecraftInstanceRecipes(MinecraftVersions);
|
||||||
|
|
||||||
this.AuthenticatedUserCache = new AuthenticatedUserCache();
|
this.AuthenticatedUserCache = new AuthenticatedUserCache();
|
||||||
this.UserManager = new UserManager(AuthenticatedUserCache, ControllerState, dbProvider);
|
this.UserManager = new UserManager(AuthenticatedUserCache, ControllerState, dbProvider);
|
||||||
@@ -60,7 +60,7 @@ public sealed class ControllerServices : IDisposable {
|
|||||||
this.UserLoginManager = new UserLoginManager(AuthenticatedUserCache, dbProvider);
|
this.UserLoginManager = new UserLoginManager(AuthenticatedUserCache, dbProvider);
|
||||||
this.PermissionManager = new PermissionManager(dbProvider);
|
this.PermissionManager = new PermissionManager(dbProvider);
|
||||||
|
|
||||||
this.AgentManager = new AgentManager(ActorSystem, new AgentConnectionKeys(agentCertificateThumbprint), ControllerState, LaunchRecipes, dbProvider, cancellationToken);
|
this.AgentManager = new AgentManager(ActorSystem, new AgentConnectionKeys(agentCertificateThumbprint), ControllerState, MinecraftInstanceRecipes, dbProvider, cancellationToken);
|
||||||
this.InstanceLogManager = new InstanceLogManager();
|
this.InstanceLogManager = new InstanceLogManager();
|
||||||
|
|
||||||
this.AuditLogManager = new AuditLogManager(dbProvider);
|
this.AuditLogManager = new AuditLogManager(dbProvider);
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user