mirror of
https://github.com/chylex/Minecraft-Phantom-Panel.git
synced 2026-03-01 05:07:53 +01:00
Compare commits
3 Commits
c996a9eaf1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
21bfdf90ee
|
|||
|
298f9adac2
|
|||
|
e1e8963ff4
|
@@ -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,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,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.Agent\Phantom.Common.Data.Agent.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 NUnit.Framework;
|
||||
using Phantom.Agent.Minecraft.Java;
|
||||
using Phantom.Agent.Services.Java;
|
||||
using Phantom.Utils.Collections;
|
||||
|
||||
namespace Phantom.Agent.Minecraft.Tests.Java;
|
||||
namespace Phantom.Agent.Services.Tests.Java;
|
||||
|
||||
[TestFixture]
|
||||
public sealed class JavaPropertiesStreamTests {
|
||||
@@ -17,7 +17,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Phantom.Agent.Minecraft\Phantom.Agent.Minecraft.csproj" />
|
||||
<ProjectReference Include="..\Phantom.Agent.Services\Phantom.Agent.Services.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -79,6 +79,7 @@ public sealed class AgentRegistrationHandler {
|
||||
configureInstanceMessage.Info,
|
||||
configureInstanceMessage.LaunchRecipe,
|
||||
configureInstanceMessage.LaunchNow,
|
||||
configureInstanceMessage.StopRecipe,
|
||||
AlwaysReportStatus: true
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using Akka.Actor;
|
||||
using Phantom.Agent.Minecraft.Java;
|
||||
using Phantom.Agent.Services.Backups;
|
||||
using Phantom.Agent.Services.Instances;
|
||||
using Phantom.Agent.Services.Java;
|
||||
using Phantom.Agent.Services.Rpc;
|
||||
using Phantom.Common.Data.Agent;
|
||||
using Phantom.Utils.Actor;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Formats.Tar;
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Agent.Services.Instances;
|
||||
using Phantom.Common.Data.Backups;
|
||||
using Phantom.Utils.IO;
|
||||
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.Utils.Logging;
|
||||
using Serilog;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Text.RegularExpressions;
|
||||
using Phantom.Agent.Minecraft.Command;
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Agent.Services.Games;
|
||||
using Phantom.Agent.Services.Instances.State;
|
||||
using Phantom.Utils.Tasks;
|
||||
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? TotalBytes { get; }
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
namespace Phantom.Agent.Minecraft.Server;
|
||||
namespace Phantom.Agent.Services.Downloads;
|
||||
|
||||
sealed record FileDownloadListener(EventHandler<DownloadProgressEventArgs> DownloadProgressEventHandler, CancellationToken CancellationToken);
|
||||
@@ -3,14 +3,14 @@ using Phantom.Utils.IO;
|
||||
using Phantom.Utils.Logging;
|
||||
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 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);
|
||||
if (fileInfo.Exists) {
|
||||
return filePath;
|
||||
@@ -3,11 +3,10 @@ using Phantom.Common.Data.Agent;
|
||||
using Phantom.Utils.Cryptography;
|
||||
using Phantom.Utils.IO;
|
||||
using Phantom.Utils.Logging;
|
||||
using Phantom.Utils.Net;
|
||||
using Phantom.Utils.Runtime;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Minecraft.Server;
|
||||
namespace Phantom.Agent.Services.Downloads;
|
||||
|
||||
sealed class 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) {
|
||||
string downloadUrl = fileDownloadInfo.DownloadUrl;
|
||||
string downloadUrl = fileDownloadInfo.Url;
|
||||
|
||||
DownloadResult result;
|
||||
try {
|
||||
@@ -111,7 +110,7 @@ sealed class FileDownloader {
|
||||
var response = await httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
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;
|
||||
|
||||
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 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) {
|
||||
using var tcpClient = new TcpClient();
|
||||
await tcpClient.ConnectAsync(IPAddress.Loopback, serverPort, cancellationToken);
|
||||
@@ -1,11 +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.Rpc;
|
||||
using Phantom.Common.Data.Agent.Instance;
|
||||
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||
using Phantom.Common.Data.Backups;
|
||||
using Phantom.Common.Data.Instance;
|
||||
using Phantom.Common.Data.Minecraft;
|
||||
using Phantom.Common.Data.Replies;
|
||||
using Phantom.Common.Messages.Agent.ToController;
|
||||
using Phantom.Utils.Actor;
|
||||
@@ -85,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 StopInstanceCommand(MinecraftStopStrategy StopStrategy) : ICommand;
|
||||
public sealed record StopInstanceCommand(InstanceStopRecipe StopRecipe) : ICommand;
|
||||
|
||||
public sealed record SendCommandToInstanceCommand(string Command) : ICommand, ICanReply<SendCommandToInstanceResult>;
|
||||
|
||||
@@ -93,7 +93,7 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
|
||||
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) {
|
||||
ReportCurrentStatus();
|
||||
@@ -125,7 +125,7 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
IInstanceStatus oldStatus = currentStatus;
|
||||
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);
|
||||
TransitionState(null);
|
||||
}
|
||||
@@ -167,7 +167,7 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
}
|
||||
|
||||
private async Task Shutdown(ShutdownCommand command) {
|
||||
await StopInstance(new StopInstanceCommand(MinecraftStopStrategy.Instant));
|
||||
await StopInstance(new StopInstanceCommand(command.StopRecipe));
|
||||
await actorCancellationTokenSource.CancelAsync();
|
||||
|
||||
await Task.WhenAll(
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Agent.Minecraft.Java;
|
||||
using Phantom.Agent.Minecraft.Launcher;
|
||||
using Phantom.Agent.Minecraft.Server;
|
||||
using Phantom.Agent.Services.Backups;
|
||||
using Phantom.Agent.Services.Backups;
|
||||
using Phantom.Agent.Services.Downloads;
|
||||
using Phantom.Agent.Services.Instances.Launch;
|
||||
using Phantom.Agent.Services.Java;
|
||||
using Phantom.Agent.Services.Rpc;
|
||||
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.Minecraft;
|
||||
using Phantom.Common.Data.Replies;
|
||||
using Phantom.Utils.Actor;
|
||||
using Phantom.Utils.IO;
|
||||
@@ -53,15 +52,15 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
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 sealed record ConfigureInstanceCommand(Guid InstanceGuid, InstanceInfo InstanceInfo, 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 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>>;
|
||||
|
||||
@@ -71,11 +70,13 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
var instanceGuid = command.InstanceGuid;
|
||||
var instanceInfo = command.InstanceInfo;
|
||||
var launchRecipe = command.LaunchRecipe;
|
||||
var stopRecipe = command.StopRecipe;
|
||||
|
||||
if (instances.TryGetValue(instanceGuid, out var instance)) {
|
||||
instances[instanceGuid] = instance with {
|
||||
Info = instanceInfo,
|
||||
LaunchRecipe = launchRecipe,
|
||||
StopRecipe = stopRecipe,
|
||||
};
|
||||
|
||||
Logger.Information("Reconfigured instance \"{Name}\" (GUID {Guid}).", instanceInfo.InstanceName, instanceGuid);
|
||||
@@ -89,7 +90,7 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
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);
|
||||
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);
|
||||
|
||||
@@ -160,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;
|
||||
}
|
||||
|
||||
@@ -182,7 +183,7 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
|
||||
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();
|
||||
|
||||
shutdownCancellationTokenSource.Dispose();
|
||||
|
||||
@@ -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.Minecraft.Server;
|
||||
using Phantom.Agent.Services.Backups;
|
||||
using Phantom.Agent.Services.Backups;
|
||||
using Phantom.Agent.Services.Downloads;
|
||||
using Phantom.Agent.Services.Java;
|
||||
using Phantom.Agent.Services.Rpc;
|
||||
|
||||
namespace Phantom.Agent.Services.Instances;
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Agent.Minecraft.Launcher;
|
||||
using Phantom.Agent.Services.Instances.State;
|
||||
using Phantom.Common.Data;
|
||||
using Phantom.Common.Data.Agent.Instance;
|
||||
using Phantom.Common.Data.Instance;
|
||||
|
||||
namespace Phantom.Agent.Services.Instances.State;
|
||||
namespace Phantom.Agent.Services.Instances.Launch;
|
||||
|
||||
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) {
|
||||
@@ -44,18 +43,18 @@ static class InstanceLaunchProcedure {
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
switch (await launcher.Launch(context.Logger, reportStatus, cancellationToken)) {
|
||||
case LaunchResult.Success launchSuccess:
|
||||
case InstanceLaunchResult.Success launchSuccess:
|
||||
return launchSuccess.Process;
|
||||
|
||||
case LaunchResult.CouldNotPrepareServerInstance:
|
||||
case InstanceLaunchResult.CouldNotPrepareServerInstance:
|
||||
context.Logger.Error("Session failed to launch, could not prepare server instance.");
|
||||
return InstanceLaunchFailReason.CouldNotPrepareServerInstance;
|
||||
|
||||
case LaunchResult.CouldNotFindServerExecutable:
|
||||
case InstanceLaunchResult.CouldNotFindServerExecutable:
|
||||
context.Logger.Error("Session failed to launch, could not find server executable.");
|
||||
return InstanceLaunchFailReason.CouldNotFindServerExecutable;
|
||||
|
||||
case LaunchResult.CouldNotStartServerExecutable:
|
||||
case InstanceLaunchResult.CouldNotStartServerExecutable:
|
||||
context.Logger.Error("Session failed to launch, could not start server executable.");
|
||||
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;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
using System.Collections.Immutable;
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Agent.Minecraft.Java;
|
||||
using Phantom.Agent.Minecraft.Server;
|
||||
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;
|
||||
@@ -9,33 +9,27 @@ using Phantom.Common.Data.Instance;
|
||||
using Phantom.Utils.Processes;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Minecraft.Launcher;
|
||||
namespace Phantom.Agent.Services.Instances.Launch;
|
||||
|
||||
public sealed class InstanceLauncher(
|
||||
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) {
|
||||
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");
|
||||
return new LaunchResult.CouldNotFindServerExecutable();
|
||||
logger.Error("Could not resolve server executable path: {Path}", launchRecipe.Executable);
|
||||
return new InstanceLaunchResult.CouldNotFindServerExecutable();
|
||||
}
|
||||
|
||||
var stepExecutor = 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(stepExecutor);
|
||||
} catch (Exception e) {
|
||||
logger.Error(e, "Failed preparation step {StepIndex} out of {StepCount}: {Step}", stepIndex, steps.Length, step.GetType().Name);
|
||||
return new LaunchResult.CouldNotPrepareServerInstance();
|
||||
}
|
||||
var stepExecutor = new StepExecutor(logger, downloadManager, pathResolver, reportStatus, cancellationToken);
|
||||
if (!await RunPreparationSteps(logger, stepExecutor)) {
|
||||
return new InstanceLaunchResult.CouldNotPrepareServerInstance();
|
||||
}
|
||||
|
||||
var processConfigurator = new ProcessConfigurator {
|
||||
@@ -47,13 +41,13 @@ public sealed class InstanceLauncher(
|
||||
|
||||
var processArguments = processConfigurator.ArgumentList;
|
||||
|
||||
foreach (var value in launchRecipe.Arguments) {
|
||||
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 LaunchResult.CouldNotPrepareServerInstance();
|
||||
return new InstanceLaunchResult.CouldNotPrepareServerInstance();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,18 +65,39 @@ public sealed class InstanceLauncher(
|
||||
logger.Error(killException, "Caught exception trying to kill the server process after a failed launch.");
|
||||
}
|
||||
|
||||
return new LaunchResult.CouldNotStartServerExecutable();
|
||||
return new InstanceLaunchResult.CouldNotStartServerExecutable();
|
||||
}
|
||||
|
||||
return new LaunchResult.Success(instanceProcess);
|
||||
return new InstanceLaunchResult.Success(instanceProcess);
|
||||
}
|
||||
|
||||
private sealed class StepExecutor(FileDownloadManager downloadManager, IInstancePathResolver pathResolver, Action<IInstanceStatus?> reportStatus, CancellationToken cancellationToken) : IInstanceLaunchStepExecutor {
|
||||
public async Task DownloadFile(FileDownloadInfo downloadInfo, IInstancePath path) {
|
||||
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) {
|
||||
// TODO avoid exc
|
||||
throw new FileNotFoundException("Could not resolve path");
|
||||
logger.Error("Could not resolve download file path: {Path}", path);
|
||||
return false;
|
||||
}
|
||||
|
||||
byte? lastDownloadProgress = null;
|
||||
@@ -96,22 +111,35 @@ public sealed class InstanceLauncher(
|
||||
}
|
||||
}
|
||||
|
||||
reportStatus(InstanceStatus.Downloading(null));
|
||||
|
||||
if (await downloadManager.DownloadAndGetPath(downloadInfo, filePath, OnDownloadProgress, cancellationToken) == null) {
|
||||
throw new FileNotFoundException("Could not download file");
|
||||
logger.Error("Could not download file: {Url}", downloadInfo.Url);
|
||||
return false;
|
||||
}
|
||||
|
||||
reportStatus(null);
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task EditPropertiesFile(InstancePath.Local path, string comment, ImmutableDictionary<string, string> newValues) {
|
||||
public async Task<bool> 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");
|
||||
logger.Error("Could not resolve properties file path: {Path}", path);
|
||||
return false;
|
||||
}
|
||||
|
||||
var editor = new JavaPropertiesFileEditor();
|
||||
editor.SetAll(newValues);
|
||||
await editor.EditOrCreate(filePath, comment, cancellationToken);
|
||||
|
||||
try {
|
||||
await editor.EditOrCreate(filePath, comment, cancellationToken);
|
||||
} catch (Exception e) {
|
||||
logger.Error(e, "Could not edit properties file: {Path}", filePath);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
using System.Buffers;
|
||||
using System.Collections.Immutable;
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Agent.Minecraft.Java;
|
||||
using Phantom.Agent.Services.Java;
|
||||
using Phantom.Common.Data.Agent.Instance;
|
||||
|
||||
namespace Phantom.Agent.Services.Instances;
|
||||
namespace Phantom.Agent.Services.Instances.Launch;
|
||||
|
||||
sealed class InstancePathResolver(AgentFolders agentFolders, JavaRuntimeRepository javaRuntimeRepository, InstanceProperties instanceProperties) : IInstancePathResolver {
|
||||
public string? Global(ImmutableArray<string> segments) {
|
||||
@@ -1,6 +1,6 @@
|
||||
using Phantom.Common.Data.Agent.Instance;
|
||||
|
||||
namespace Phantom.Agent.Services.Instances;
|
||||
namespace Phantom.Agent.Services.Instances.Launch;
|
||||
|
||||
sealed class InstanceValueResolver(IInstancePathResolver pathResolver) : IInstanceValueResolver {
|
||||
public string? Path(IInstancePath value) {
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.Net.Sockets;
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Agent.Minecraft.Server;
|
||||
using Phantom.Agent.Services.Games;
|
||||
using Phantom.Agent.Services.Rpc;
|
||||
using Phantom.Common.Data.Instance;
|
||||
using Phantom.Common.Messages.Agent.ToController;
|
||||
@@ -60,8 +59,8 @@ sealed class InstancePlayerCountTracker : CancellableBackgroundTask {
|
||||
|
||||
private async Task<InstancePlayerCounts?> TryGetPlayerCounts() {
|
||||
try {
|
||||
return await ServerStatusProtocol.GetPlayerCounts(serverPort, CancellationToken);
|
||||
} catch (ServerStatusProtocol.ProtocolException e) {
|
||||
return await MinecraftServerStatusProtocol.GetPlayerCounts(serverPort, CancellationToken);
|
||||
} catch (MinecraftServerStatusProtocol.ProtocolException e) {
|
||||
Logger.Error("{Message}", e.Message);
|
||||
return null;
|
||||
} catch (SocketException e) {
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
using Phantom.Utils.Processes;
|
||||
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; }
|
||||
|
||||
private readonly RingBuffer<string> outputBuffer = new (100);
|
||||
@@ -27,6 +27,15 @@ public sealed class InstanceProcess : IDisposable {
|
||||
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) {
|
||||
OutputEvent += listener;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Agent.Minecraft.Launcher;
|
||||
using Phantom.Agent.Services.Backups;
|
||||
using Phantom.Agent.Services.Backups;
|
||||
using Phantom.Agent.Services.Instances.Launch;
|
||||
using Phantom.Common.Data.Agent.Instance;
|
||||
using Phantom.Common.Data.Backups;
|
||||
using Phantom.Common.Data.Instance;
|
||||
@@ -12,6 +11,7 @@ sealed class InstanceRunningState : IDisposable {
|
||||
public InstanceTicketManager.Ticket Ticket { get; }
|
||||
public InstanceProcess Process { get; }
|
||||
|
||||
internal IInstanceValueResolver ValueResolver => launcher.ValueResolver;
|
||||
internal bool IsStopping { get; set; }
|
||||
|
||||
private readonly InstanceContext context;
|
||||
|
||||
@@ -1,38 +1,50 @@
|
||||
using System.Diagnostics;
|
||||
using Phantom.Agent.Minecraft.Command;
|
||||
using Phantom.Agent.Minecraft.Instance;
|
||||
using Phantom.Common.Data.Agent.Instance;
|
||||
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||
using Phantom.Common.Data.Instance;
|
||||
using Phantom.Common.Data.Minecraft;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Services.Instances.State;
|
||||
|
||||
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, MinecraftStopStrategy stopStrategy, InstanceRunningState runningState, Action<IInstanceStatus> reportStatus, CancellationToken cancellationToken) {
|
||||
var process = runningState.Process;
|
||||
public static async Task<bool> Run(InstanceContext context, InstanceStopRecipe stopRecipe, InstanceRunningState runningState, Action<IInstanceStatus> reportStatus, CancellationToken cancellationToken) {
|
||||
var logger = context.Logger;
|
||||
|
||||
var stopCommand = stopRecipe.StopCommand.Resolve(runningState.ValueResolver);
|
||||
if (stopCommand == null) {
|
||||
logger.Error("Could not resolve stop command");
|
||||
return false;
|
||||
}
|
||||
|
||||
runningState.IsStopping = true;
|
||||
|
||||
var seconds = stopStrategy.Seconds;
|
||||
if (seconds > 0) {
|
||||
try {
|
||||
await CountDownWithAnnouncements(context, process, seconds, cancellationToken);
|
||||
} catch (OperationCanceledException) {
|
||||
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;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!continueStopping) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// Too late to cancel the stop procedure now.
|
||||
runningState.OnStopInitiated();
|
||||
|
||||
if (!process.HasEnded) {
|
||||
context.Logger.Information("Session stopping now.");
|
||||
await DoStop(context, process);
|
||||
if (!runningState.Process.HasEnded) {
|
||||
logger.Information("Sending stop command...");
|
||||
await TrySendStopCommand(context, runningState.Process, stopCommand);
|
||||
|
||||
logger.Information("Waiting for session to end...");
|
||||
await WaitForSessionToEnd(context, runningState.Process);
|
||||
}
|
||||
} finally {
|
||||
context.Logger.Information("Session stopped.");
|
||||
logger.Information("Session stopped.");
|
||||
reportStatus(InstanceStatus.NotRunning);
|
||||
context.ReportEvent(InstanceEvent.Stopped);
|
||||
}
|
||||
@@ -40,39 +52,51 @@ static class InstanceStopProcedure {
|
||||
return true;
|
||||
}
|
||||
|
||||
private static async Task CountDownWithAnnouncements(InstanceContext context, InstanceProcess process, ushort seconds, CancellationToken cancellationToken) {
|
||||
context.Logger.Information("Session stopping in {Seconds} seconds.", seconds);
|
||||
private static async Task<bool> RunPreparationSteps(InstanceContext context, InstanceStopRecipe stopRecipe, StepExecutor executor) {
|
||||
var steps = stopRecipe.Preparation;
|
||||
|
||||
foreach (var stop in Stops) {
|
||||
// TODO change to event-based cancellation
|
||||
if (process.HasEnded) {
|
||||
return;
|
||||
for (int stepIndex = 0; stepIndex < steps.Length; stepIndex++) {
|
||||
var step = steps[stepIndex];
|
||||
try {
|
||||
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) {
|
||||
await process.SendCommand(GetCountDownAnnouncementCommand(seconds), cancellationToken);
|
||||
await Task.Delay(TimeSpan.FromSeconds(seconds - stop), cancellationToken);
|
||||
seconds = stop;
|
||||
return false;
|
||||
}
|
||||
|
||||
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) {
|
||||
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) {
|
||||
private static async Task TrySendStopCommand(InstanceContext context, InstanceProcess process, string command) {
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
try {
|
||||
await process.SendCommand(MinecraftCommand.Stop, timeout.Token);
|
||||
await process.SendCommand(command, timeout.Token);
|
||||
} catch (OperationCanceledException) {
|
||||
// Ignore.
|
||||
} 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 {
|
||||
private readonly Dictionary<string, string> overriddenProperties = new ();
|
||||
@@ -4,7 +4,7 @@ using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using Phantom.Utils.Collections;
|
||||
|
||||
namespace Phantom.Agent.Minecraft.Java;
|
||||
namespace Phantom.Agent.Services.Java;
|
||||
|
||||
static class JavaPropertiesStream {
|
||||
internal static readonly Encoding Encoding = Encoding.GetEncoding("ISO-8859-1");
|
||||
@@ -6,7 +6,7 @@ using Phantom.Utils.IO;
|
||||
using Phantom.Utils.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Minecraft.Java;
|
||||
namespace Phantom.Agent.Services.Java;
|
||||
|
||||
public sealed class 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.Utils.Cryptography;
|
||||
|
||||
namespace Phantom.Agent.Minecraft.Java;
|
||||
namespace Phantom.Agent.Services.Java;
|
||||
|
||||
public sealed class JavaRuntimeRepository {
|
||||
private readonly ImmutableDictionary<Guid, JavaRuntimeExecutable> runtimesByGuid;
|
||||
@@ -25,7 +25,7 @@ public sealed class JavaRuntimeRepository {
|
||||
.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);
|
||||
}
|
||||
|
||||
@@ -5,9 +5,12 @@
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Phantom.Agent.Services.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Common\Phantom.Common.Messages.Agent\Phantom.Common.Messages.Agent.csproj" />
|
||||
<ProjectReference Include="..\Phantom.Agent.Minecraft\Phantom.Agent.Minecraft.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -26,7 +26,7 @@ public sealed class ControllerMessageHandlerActor : ReceiveActor<IMessageToAgent
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -34,7 +34,7 @@ public sealed class ControllerMessageHandlerActor : ReceiveActor<IMessageToAgent
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
|
||||
<ItemGroup>
|
||||
<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" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using System.Reflection;
|
||||
using Phantom.Agent;
|
||||
using Phantom.Agent.Minecraft.Java;
|
||||
using Phantom.Agent.Services;
|
||||
using Phantom.Agent.Services.Java;
|
||||
using Phantom.Agent.Services.Rpc;
|
||||
using Phantom.Common.Data.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.Utils.Logging;
|
||||
using Phantom.Utils.Runtime;
|
||||
|
||||
@@ -6,7 +6,7 @@ namespace Phantom.Common.Data.Agent;
|
||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||
public sealed partial class FileDownloadInfo {
|
||||
[MemoryPackOrder(0)]
|
||||
public string DownloadUrl { get; }
|
||||
public string Url { get; }
|
||||
|
||||
[MemoryPackOrder(1)]
|
||||
[MemoryPackInclude]
|
||||
@@ -15,11 +15,11 @@ public sealed partial class FileDownloadInfo {
|
||||
[MemoryPackIgnore]
|
||||
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]
|
||||
private FileDownloadInfo(string downloadUrl, string? hash) {
|
||||
this.DownloadUrl = downloadUrl;
|
||||
private FileDownloadInfo(string url, string? hash) {
|
||||
this.Url = url;
|
||||
this.hash = hash;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ public static partial class InstancePath {
|
||||
}
|
||||
|
||||
public override string ToString() {
|
||||
return string.Join(separator: '/', Segments);
|
||||
return "Global[" + string.Join(separator: '/', Segments) + "]";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ public static partial class InstancePath {
|
||||
}
|
||||
|
||||
public override string ToString() {
|
||||
return string.Join(separator: '/', Segments);
|
||||
return "Local[" + string.Join(separator: '/', Segments) + "]";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,5 +45,9 @@ public static partial class InstancePath {
|
||||
public string? Resolve(IInstancePathResolver resolver) {
|
||||
return resolver.Runtime(Guid);
|
||||
}
|
||||
|
||||
public override string ToString() {
|
||||
return "Runtime[" + Guid + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,10 @@ public static partial class InstanceValues {
|
||||
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
public override string ToString() {
|
||||
return "Concatenation[" + string.Join(",", Values) + "]";
|
||||
}
|
||||
}
|
||||
|
||||
[MemoryPackable]
|
||||
@@ -36,6 +40,10 @@ public static partial class InstanceValues {
|
||||
public string Resolve(IInstanceValueResolver resolver) {
|
||||
return Value;
|
||||
}
|
||||
|
||||
public override string ToString() {
|
||||
return "Text[" + Value + "]";
|
||||
}
|
||||
}
|
||||
|
||||
[MemoryPackable]
|
||||
@@ -43,5 +51,9 @@ public static partial class InstanceValues {
|
||||
public string? Resolve(IInstanceValueResolver resolver) {
|
||||
return resolver.Path(Value);
|
||||
}
|
||||
|
||||
public override string ToString() {
|
||||
return "Path[" + Value + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace Phantom.Common.Data.Agent.Instance.Launch;
|
||||
[MemoryPackUnion(tag: 0, typeof(InstanceLaunchStep.DownloadFile))]
|
||||
[MemoryPackUnion(tag: 1, typeof(InstanceLaunchStep.EditPropertiesFile))]
|
||||
public partial interface IInstanceLaunchStep {
|
||||
Task Run(IInstanceLaunchStepExecutor executor);
|
||||
Task<TResult> Run<TResult>(IInstanceLaunchStepExecutor<TResult> executor);
|
||||
}
|
||||
|
||||
public static partial class InstanceLaunchStep {
|
||||
@@ -16,7 +16,7 @@ public static partial class InstanceLaunchStep {
|
||||
[property: MemoryPackOrder(0)] FileDownloadInfo DownloadInfo,
|
||||
[property: MemoryPackOrder(1)] IInstancePath Path
|
||||
) : IInstanceLaunchStep {
|
||||
public Task Run(IInstanceLaunchStepExecutor executor) {
|
||||
public Task<TResult> Run<TResult>(IInstanceLaunchStepExecutor<TResult> executor) {
|
||||
return executor.DownloadFile(DownloadInfo, Path);
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ public static partial class InstanceLaunchStep {
|
||||
[property: MemoryPackOrder(1)] string Comment,
|
||||
[property: MemoryPackOrder(2)] ImmutableDictionary<string, string> NewValues
|
||||
) : IInstanceLaunchStep {
|
||||
public Task Run(IInstanceLaunchStepExecutor executor) {
|
||||
public Task<TResult> Run<TResult>(IInstanceLaunchStepExecutor<TResult> executor) {
|
||||
return executor.EditPropertiesFile(Path, Comment, NewValues);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
using System.Collections.Immutable;
|
||||
using Phantom.Common.Data.Minecraft;
|
||||
|
||||
namespace Phantom.Common.Data.Agent.Instance.Launch;
|
||||
|
||||
public interface IInstanceLaunchStepExecutor {
|
||||
Task DownloadFile(FileDownloadInfo downloadInfo, IInstancePath path);
|
||||
Task EditPropertiesFile(InstancePath.Local path, string comment, ImmutableDictionary<string, string> newValues);
|
||||
public interface IInstanceLaunchStepExecutor<TResult> {
|
||||
Task<TResult> DownloadFile(FileDownloadInfo downloadInfo, IInstancePath path);
|
||||
Task<TResult> EditPropertiesFile(InstancePath.Local path, string comment, ImmutableDictionary<string, string> newValues);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
);
|
||||
@@ -1,6 +1,6 @@
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace Phantom.Common.Data.Web.Minecraft;
|
||||
namespace Phantom.Common.Data.Web.Java;
|
||||
|
||||
public static class JvmArgumentsHelper {
|
||||
public static ImmutableArray<string> Split(string arguments) {
|
||||
@@ -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);
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
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.Replies;
|
||||
using Phantom.Utils.Actor;
|
||||
|
||||
@@ -12,5 +13,6 @@ public sealed partial record ConfigureInstanceMessage(
|
||||
[property: MemoryPackOrder(0)] Guid InstanceGuid,
|
||||
[property: MemoryPackOrder(1)] InstanceInfo Info,
|
||||
[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>>;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
using MemoryPack;
|
||||
using Phantom.Common.Data;
|
||||
using Phantom.Common.Data.Minecraft;
|
||||
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||
using Phantom.Common.Data.Replies;
|
||||
using Phantom.Utils.Actor;
|
||||
|
||||
@@ -9,5 +9,5 @@ namespace Phantom.Common.Messages.Agent.ToAgent;
|
||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||
public sealed partial record StopInstanceMessage(
|
||||
[property: MemoryPackOrder(0)] Guid InstanceGuid,
|
||||
[property: MemoryPackOrder(1)] MinecraftStopStrategy StopStrategy
|
||||
[property: MemoryPackOrder(1)] InstanceStopRecipe StopRecipe
|
||||
) : IMessageToAgent, ICanReply<Result<StopInstanceResult, InstanceActionFailure>>;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using System.Collections.Immutable;
|
||||
using MemoryPack;
|
||||
using Phantom.Common.Data;
|
||||
using Phantom.Common.Data.Minecraft;
|
||||
using Phantom.Common.Data.Replies;
|
||||
using Phantom.Common.Data.Web.Users;
|
||||
using Phantom.Utils.Actor;
|
||||
@@ -13,5 +12,5 @@ public sealed partial record StopInstanceMessage(
|
||||
[property: MemoryPackOrder(0)] ImmutableArray<byte> AuthToken,
|
||||
[property: MemoryPackOrder(1)] Guid AgentGuid,
|
||||
[property: MemoryPackOrder(2)] Guid InstanceGuid,
|
||||
[property: MemoryPackOrder(3)] MinecraftStopStrategy StopStrategy
|
||||
[property: MemoryPackOrder(3)] ushort AfterSeconds
|
||||
) : IMessageToController, ICanReply<Result<StopInstanceResult, UserInstanceActionFailure>>;
|
||||
|
||||
@@ -87,10 +87,8 @@ sealed partial class AuditLogRepository {
|
||||
});
|
||||
}
|
||||
|
||||
public void InstanceStopped(Guid instanceGuid, int stopInSeconds) {
|
||||
AddItem(AuditLogEventType.InstanceStopped, instanceGuid.ToString(), new Dictionary<string, object?> {
|
||||
{ "stop_in_seconds", stopInSeconds.ToString() },
|
||||
});
|
||||
public void InstanceStopped(Guid instanceGuid) {
|
||||
AddItem(AuditLogEventType.InstanceStopped, instanceGuid.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,12 +10,8 @@ using Phantom.Utils.Collections;
|
||||
|
||||
namespace Phantom.Controller.Minecraft;
|
||||
|
||||
public sealed partial class MinecraftLaunchRecipes(MinecraftVersions minecraftVersions) {
|
||||
private static readonly ImmutableDictionary<string, string> Eula = ImmutableDictionary.From([
|
||||
("eula", "true"),
|
||||
]);
|
||||
|
||||
public async Task<Result<InstanceLaunchRecipe, MinecraftLaunchRecipeCreationFailReason>> Create(InstanceConfiguration configuration, CancellationToken cancellationToken) {
|
||||
public sealed partial class MinecraftInstanceRecipes(MinecraftVersions minecraftVersions) {
|
||||
public async Task<Result<InstanceLaunchRecipe, MinecraftLaunchRecipeCreationFailReason>> Launch(InstanceConfiguration configuration, CancellationToken cancellationToken) {
|
||||
string minecraftVersion = configuration.MinecraftVersion;
|
||||
|
||||
var serverExecutableInfo = await minecraftVersions.GetServerExecutableInfo(minecraftVersion, cancellationToken);
|
||||
@@ -53,8 +49,8 @@ public sealed partial class MinecraftLaunchRecipes(MinecraftVersions minecraftVe
|
||||
return new InstanceLaunchRecipe(steps.ToImmutable(), new InstancePath.Runtime(configuration.JavaRuntimeGuid), [
|
||||
..configuration.JvmArguments.Select(static arg => new InstanceValues.Text(arg)),
|
||||
..additionalJvmArguments,
|
||||
new InstanceValues.Text("-Xms" + initialHeapSizeMegabytes + "M"),
|
||||
new InstanceValues.Text("-Xmx" + maximumHeapSizeMegabvtes + "M"),
|
||||
new InstanceValues.Text($"-Xms{initialHeapSizeMegabytes}M"),
|
||||
new InstanceValues.Text($"-Xmx{maximumHeapSizeMegabvtes}M"),
|
||||
new InstanceValues.Text("-jar"),
|
||||
new InstanceValues.Path(serverExecutableFilePath),
|
||||
new InstanceValues.Text("-nogui"),
|
||||
@@ -68,6 +64,10 @@ public sealed partial class MinecraftLaunchRecipes(MinecraftVersions minecraftVe
|
||||
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) {
|
||||
return ImmutableDictionary.From([
|
||||
("server-port", configuration.ServerPort.ToString()),
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ public sealed class MinecraftVersions : IDisposable {
|
||||
Logger.Information("Refreshed Minecraft {Version} server executable cache, no file found.", version);
|
||||
}
|
||||
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;
|
||||
|
||||
@@ -5,11 +5,10 @@ using Phantom.Common.Data;
|
||||
using Phantom.Common.Data.Agent.Instance.Launch;
|
||||
using Phantom.Common.Data.Instance;
|
||||
using Phantom.Common.Data.Java;
|
||||
using Phantom.Common.Data.Minecraft;
|
||||
using Phantom.Common.Data.Replies;
|
||||
using Phantom.Common.Data.Web.Agent;
|
||||
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.ToAgent;
|
||||
using Phantom.Controller.Database;
|
||||
@@ -41,7 +40,7 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
AgentRuntimeInfo AgentRuntimeInfo,
|
||||
AgentConnectionKeys AgentConnectionKeys,
|
||||
ControllerState ControllerState,
|
||||
MinecraftLaunchRecipes LaunchRecipes,
|
||||
MinecraftInstanceRecipes MinecraftInstanceRecipes,
|
||||
IDbContextProvider DbProvider,
|
||||
CancellationToken CancellationToken
|
||||
);
|
||||
@@ -54,7 +53,7 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
|
||||
private readonly AgentConnectionKeys agentConnectionKeys;
|
||||
private readonly ControllerState controllerState;
|
||||
private readonly MinecraftLaunchRecipes launchRecipes;
|
||||
private readonly MinecraftInstanceRecipes minecraftInstanceRecipes;
|
||||
private readonly IDbContextProvider dbProvider;
|
||||
private readonly CancellationToken cancellationToken;
|
||||
|
||||
@@ -95,7 +94,7 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
private AgentActor(Init init) {
|
||||
this.agentConnectionKeys = init.AgentConnectionKeys;
|
||||
this.controllerState = init.ControllerState;
|
||||
this.launchRecipes = init.LaunchRecipes;
|
||||
this.minecraftInstanceRecipes = init.MinecraftInstanceRecipes;
|
||||
this.dbProvider = init.DbProvider;
|
||||
this.cancellationToken = init.CancellationToken;
|
||||
|
||||
@@ -190,8 +189,9 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
var configurationMessages = ImmutableArray.CreateBuilder<ConfigureInstanceMessage>();
|
||||
|
||||
foreach (var (instanceGuid, instanceConfiguration, _, _, launchAutomatically) in instanceDataByGuid.Values.ToImmutableArray()) {
|
||||
var launchRecipe = await launchRecipes.Create(instanceConfiguration, cancellationToken);
|
||||
var configurationMessage = new ConfigureInstanceMessage(instanceGuid, instanceConfiguration.AsInfo, launchRecipe.OrElse(null), launchAutomatically);
|
||||
var launchRecipe = await minecraftInstanceRecipes.Launch(instanceConfiguration, cancellationToken);
|
||||
var stopRecipe = minecraftInstanceRecipes.Stop(0);
|
||||
var configurationMessage = new ConfigureInstanceMessage(instanceGuid, instanceConfiguration.AsInfo, launchRecipe.OrElse(null), launchAutomatically, stopRecipe);
|
||||
configurationMessages.Add(configurationMessage);
|
||||
}
|
||||
|
||||
@@ -226,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 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>>;
|
||||
|
||||
@@ -341,7 +341,7 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
return Task.FromResult<Result<CreateOrUpdateInstanceResult, InstanceActionFailure>>(CreateOrUpdateInstanceResult.InstanceMemoryMustNotBeZero);
|
||||
}
|
||||
|
||||
return launchRecipes.Create(instanceConfiguration, cancellationToken)
|
||||
return minecraftInstanceRecipes.Launch(instanceConfiguration, cancellationToken)
|
||||
.ContinueOnActor(CreateOrUpdateInstance1, command)
|
||||
.Unwrap();
|
||||
}
|
||||
@@ -362,7 +362,8 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
instanceActorRef = CreateNewInstance(Instance.Offline(instanceGuid, instanceConfiguration));
|
||||
}
|
||||
|
||||
var configureInstanceCommand = new InstanceActor.ConfigureInstanceCommand(command.LoggedInUserGuid, instanceGuid, instanceConfiguration, launchRecipe.Value, 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)
|
||||
.ContinueOnActor(CreateOrUpdateInstance2, configureInstanceCommand);
|
||||
@@ -403,7 +404,8 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
@@ -21,7 +21,7 @@ sealed class AgentManager(
|
||||
IActorRefFactory actorSystem,
|
||||
AgentConnectionKeys agentConnectionKeys,
|
||||
ControllerState controllerState,
|
||||
MinecraftLaunchRecipes launchRecipes,
|
||||
MinecraftInstanceRecipes minecraftInstanceRecipes,
|
||||
IDbContextProvider dbProvider,
|
||||
CancellationToken cancellationToken
|
||||
) {
|
||||
@@ -42,7 +42,7 @@ sealed class AgentManager(
|
||||
}
|
||||
|
||||
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;
|
||||
return agentsByAgentGuid.TryAdd(agentGuid, actorSystem.ActorOf(AgentActor.Factory(init), name));
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ public sealed class ControllerServices : IDisposable {
|
||||
|
||||
private ControllerState ControllerState { get; }
|
||||
private MinecraftVersions MinecraftVersions { get; }
|
||||
private MinecraftLaunchRecipes LaunchRecipes { get; }
|
||||
private MinecraftInstanceRecipes MinecraftInstanceRecipes { get; }
|
||||
|
||||
private AuthenticatedUserCache AuthenticatedUserCache { get; }
|
||||
private UserManager UserManager { get; }
|
||||
@@ -51,7 +51,7 @@ public sealed class ControllerServices : IDisposable {
|
||||
|
||||
this.ControllerState = new ControllerState();
|
||||
this.MinecraftVersions = new MinecraftVersions();
|
||||
this.LaunchRecipes = new MinecraftLaunchRecipes(MinecraftVersions);
|
||||
this.MinecraftInstanceRecipes = new MinecraftInstanceRecipes(MinecraftVersions);
|
||||
|
||||
this.AuthenticatedUserCache = new AuthenticatedUserCache();
|
||||
this.UserManager = new UserManager(AuthenticatedUserCache, ControllerState, dbProvider);
|
||||
@@ -60,7 +60,7 @@ public sealed class ControllerServices : IDisposable {
|
||||
this.UserLoginManager = new UserLoginManager(AuthenticatedUserCache, 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.AuditLogManager = new AuditLogManager(dbProvider);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using Phantom.Common.Data;
|
||||
using Phantom.Common.Data.Agent.Instance.Launch;
|
||||
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||
using Phantom.Common.Data.Instance;
|
||||
using Phantom.Common.Data.Minecraft;
|
||||
using Phantom.Common.Data.Replies;
|
||||
using Phantom.Common.Data.Web.Instance;
|
||||
using Phantom.Common.Messages.Agent;
|
||||
@@ -71,11 +71,11 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
|
||||
public sealed record SetPlayerCountsCommand(InstancePlayerCounts? PlayerCounts) : ICommand;
|
||||
|
||||
public sealed record ConfigureInstanceCommand(Guid AuditLogUserGuid, Guid InstanceGuid, InstanceConfiguration Configuration, InstanceLaunchRecipe LaunchRecipe, bool IsCreatingInstance) : ICommand, ICanReply<Result<ConfigureInstanceResult, InstanceActionFailure>>;
|
||||
public sealed record ConfigureInstanceCommand(Guid AuditLogUserGuid, Guid InstanceGuid, InstanceConfiguration Configuration, InstanceLaunchRecipe LaunchRecipe, InstanceStopRecipe StopRecipe, bool IsCreatingInstance) : ICommand, ICanReply<Result<ConfigureInstanceResult, InstanceActionFailure>>;
|
||||
|
||||
public sealed record LaunchInstanceCommand(Guid AuditLogUserGuid) : ICommand, ICanReply<Result<LaunchInstanceResult, InstanceActionFailure>>;
|
||||
|
||||
public sealed record StopInstanceCommand(Guid AuditLogUserGuid, MinecraftStopStrategy StopStrategy) : ICommand, ICanReply<Result<StopInstanceResult, InstanceActionFailure>>;
|
||||
public sealed record StopInstanceCommand(Guid AuditLogUserGuid, InstanceStopRecipe StopRecipe) : ICommand, ICanReply<Result<StopInstanceResult, InstanceActionFailure>>;
|
||||
|
||||
public sealed record SendCommandToInstanceCommand(Guid AuditLogUserGuid, string Command) : ICommand, ICanReply<Result<SendCommandToInstanceResult, InstanceActionFailure>>;
|
||||
|
||||
@@ -95,7 +95,7 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
}
|
||||
|
||||
private async Task<Result<ConfigureInstanceResult, InstanceActionFailure>> ConfigureInstance(ConfigureInstanceCommand command) {
|
||||
var message = new ConfigureInstanceMessage(command.InstanceGuid, command.Configuration.AsInfo, command.LaunchRecipe);
|
||||
var message = new ConfigureInstanceMessage(command.InstanceGuid, command.Configuration.AsInfo, command.LaunchRecipe, LaunchNow: false, command.StopRecipe);
|
||||
var result = await SendInstanceActionMessage<ConfigureInstanceMessage, ConfigureInstanceResult>(message);
|
||||
|
||||
if (result.Is(ConfigureInstanceResult.Success)) {
|
||||
@@ -127,12 +127,12 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
}
|
||||
|
||||
private async Task<Result<StopInstanceResult, InstanceActionFailure>> StopInstance(StopInstanceCommand command) {
|
||||
var message = new StopInstanceMessage(instanceGuid, command.StopStrategy);
|
||||
var message = new StopInstanceMessage(instanceGuid, command.StopRecipe);
|
||||
var result = await SendInstanceActionMessage<StopInstanceMessage, StopInstanceResult>(message);
|
||||
|
||||
if (result.Is(StopInstanceResult.StopInitiated)) {
|
||||
SetLaunchAutomatically(false);
|
||||
databaseStorageActor.Tell(new InstanceDatabaseStorageActor.StoreInstanceStoppedCommand(command.AuditLogUserGuid, command.StopStrategy));
|
||||
databaseStorageActor.Tell(new InstanceDatabaseStorageActor.StoreInstanceStoppedCommand(command.AuditLogUserGuid));
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using Phantom.Common.Data.Minecraft;
|
||||
using Phantom.Common.Data.Web.Instance;
|
||||
using Phantom.Common.Data.Web.Minecraft;
|
||||
using Phantom.Common.Data.Web.Instance;
|
||||
using Phantom.Common.Data.Web.Java;
|
||||
using Phantom.Controller.Database;
|
||||
using Phantom.Controller.Database.Entities;
|
||||
using Phantom.Controller.Database.Repositories;
|
||||
@@ -44,7 +43,7 @@ sealed class InstanceDatabaseStorageActor : ReceiveActor<InstanceDatabaseStorage
|
||||
|
||||
public sealed record StoreInstanceLaunchedCommand(Guid AuditLogUserGuid) : ICommand;
|
||||
|
||||
public sealed record StoreInstanceStoppedCommand(Guid AuditLogUserGuid, MinecraftStopStrategy StopStrategy) : ICommand;
|
||||
public sealed record StoreInstanceStoppedCommand(Guid AuditLogUserGuid) : ICommand;
|
||||
|
||||
public sealed record StoreInstanceCommandSentCommand(Guid AuditLogUserGuid, string Command) : ICommand;
|
||||
|
||||
@@ -100,7 +99,7 @@ sealed class InstanceDatabaseStorageActor : ReceiveActor<InstanceDatabaseStorage
|
||||
}
|
||||
|
||||
var auditLogWriter = new AuditLogRepository(db).Writer(command.AuditLogUserGuid);
|
||||
auditLogWriter.InstanceStopped(instanceGuid, command.StopStrategy.Seconds);
|
||||
auditLogWriter.InstanceStopped(instanceGuid);
|
||||
|
||||
await db.Ctx.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ sealed class WebMessageHandlerActor : ReceiveActor<IMessageToController> {
|
||||
userLoginManager.GetLoggedInUser(message.AuthToken),
|
||||
Permission.ControlInstances,
|
||||
message.AgentGuid,
|
||||
loggedInUserGuid => new AgentActor.StopInstanceCommand(loggedInUserGuid, message.InstanceGuid, message.StopStrategy)
|
||||
loggedInUserGuid => new AgentActor.StopInstanceCommand(loggedInUserGuid, message.InstanceGuid, message.AfterSeconds)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,9 +18,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Web", "Web", "{92B26F48-235
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Phantom.Agent", "Agent\Phantom.Agent\Phantom.Agent.csproj", "{418BE1BF-9F63-4B46-B4E4-DF64C3B3DDA7}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Phantom.Agent.Minecraft", "Agent\Phantom.Agent.Minecraft\Phantom.Agent.Minecraft.csproj", "{9FE000D0-91AC-4CB4-8956-91CCC0270015}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Phantom.Agent.Minecraft.Tests", "Agent\Phantom.Agent.Minecraft.Tests\Phantom.Agent.Minecraft.Tests.csproj", "{065FFFA0-DFF4-43DB-AB3D-B92EE9848DDB}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Phantom.Agent.Services.Tests", "Agent\Phantom.Agent.Services.Tests\Phantom.Agent.Services.Tests.csproj", "{065FFFA0-DFF4-43DB-AB3D-B92EE9848DDB}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Phantom.Agent.Services", "Agent\Phantom.Agent.Services\Phantom.Agent.Services.csproj", "{AEE8B77E-AB07-423F-9981-8CD829ACB834}"
|
||||
EndProject
|
||||
@@ -76,10 +74,6 @@ Global
|
||||
{418BE1BF-9F63-4B46-B4E4-DF64C3B3DDA7}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{418BE1BF-9F63-4B46-B4E4-DF64C3B3DDA7}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{418BE1BF-9F63-4B46-B4E4-DF64C3B3DDA7}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{9FE000D0-91AC-4CB4-8956-91CCC0270015}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{9FE000D0-91AC-4CB4-8956-91CCC0270015}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9FE000D0-91AC-4CB4-8956-91CCC0270015}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{9FE000D0-91AC-4CB4-8956-91CCC0270015}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{065FFFA0-DFF4-43DB-AB3D-B92EE9848DDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{065FFFA0-DFF4-43DB-AB3D-B92EE9848DDB}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{065FFFA0-DFF4-43DB-AB3D-B92EE9848DDB}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
@@ -171,7 +165,6 @@ Global
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{418BE1BF-9F63-4B46-B4E4-DF64C3B3DDA7} = {F5878792-64C8-4ECF-A075-66341FF97127}
|
||||
{9FE000D0-91AC-4CB4-8956-91CCC0270015} = {F5878792-64C8-4ECF-A075-66341FF97127}
|
||||
{065FFFA0-DFF4-43DB-AB3D-B92EE9848DDB} = {94C1E464-3F91-49EA-99FF-3A3082C54CE8}
|
||||
{AEE8B77E-AB07-423F-9981-8CD829ACB834} = {F5878792-64C8-4ECF-A075-66341FF97127}
|
||||
{6C3DB1E5-F695-4D70-8F3A-78C2957274BE} = {01CB1A81-8950-471C-BFDF-F135FDDB2C18}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
using System.Net.Http.Headers;
|
||||
using Phantom.Utils.IO;
|
||||
|
||||
namespace Phantom.Utils.Net;
|
||||
|
||||
public static class HttpHeadersExtensions {
|
||||
private const string ContentLength = "Content-Length";
|
||||
|
||||
extension(HttpResponseHeaders headers) {
|
||||
public FileSize? ContentLength {
|
||||
get {
|
||||
if (!headers.TryGetValues(ContentLength, out var values)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
string? value = values.FirstOrDefault();
|
||||
return value != null && ulong.TryParse(value, out ulong result) ? new FileSize(result) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.Collections.Immutable;
|
||||
using Phantom.Common.Data;
|
||||
using Phantom.Common.Data.Minecraft;
|
||||
using Phantom.Common.Data.Replies;
|
||||
using Phantom.Common.Data.Web.Instance;
|
||||
using Phantom.Common.Data.Web.Users;
|
||||
@@ -56,9 +55,9 @@ public sealed class InstanceManager(ControllerConnection controllerConnection) {
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result<StopInstanceResult, UserInstanceActionFailure>> StopInstance(AuthenticatedUser? authenticatedUser, Guid agentGuid, Guid instanceGuid, MinecraftStopStrategy stopStrategy, CancellationToken cancellationToken) {
|
||||
public async Task<Result<StopInstanceResult, UserInstanceActionFailure>> StopInstance(AuthenticatedUser? authenticatedUser, Guid agentGuid, Guid instanceGuid, ushort afterSeconds, CancellationToken cancellationToken) {
|
||||
if (authenticatedUser != null && authenticatedUser.Info.CheckPermission(Permission.ControlInstances)) {
|
||||
var message = new StopInstanceMessage(authenticatedUser.Token, agentGuid, instanceGuid, stopStrategy);
|
||||
var message = new StopInstanceMessage(authenticatedUser.Token, agentGuid, instanceGuid, afterSeconds);
|
||||
return await controllerConnection.Send<StopInstanceMessage, Result<StopInstanceResult, UserInstanceActionFailure>>(message, cancellationToken);
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
@using Phantom.Common.Data.Replies
|
||||
@using Phantom.Common.Data.Web.Agent
|
||||
@using Phantom.Common.Data.Web.Instance
|
||||
@using Phantom.Common.Data.Web.Java
|
||||
@using Phantom.Common.Data.Web.Minecraft
|
||||
@using Phantom.Common.Data.Web.Users
|
||||
@using Phantom.Common.Messages.Web.ToController
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
@using System.ComponentModel.DataAnnotations
|
||||
@using Phantom.Common.Data.Minecraft
|
||||
@using Phantom.Common.Data.Replies
|
||||
@using Phantom.Common.Data.Web.Users
|
||||
@using Phantom.Utils.Result
|
||||
@@ -54,7 +53,7 @@
|
||||
private async Task StopInstance(EditContext context) {
|
||||
await form.SubmitModel.StartSubmitting();
|
||||
|
||||
var result = await InstanceManager.StopInstance(await GetAuthenticatedUser(), AgentGuid, InstanceGuid, new MinecraftStopStrategy(form.StopInSeconds), CancellationToken);
|
||||
var result = await InstanceManager.StopInstance(await GetAuthenticatedUser(), AgentGuid, InstanceGuid, form.StopInSeconds, CancellationToken);
|
||||
|
||||
switch (result.Variant()) {
|
||||
case Ok<StopInstanceResult>(StopInstanceResult.StopInitiated):
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
using Phantom.Common.Data.Instance;
|
||||
using Phantom.Common.Data.Replies;
|
||||
using Phantom.Common.Data.Web.Minecraft;
|
||||
using Phantom.Common.Data.Web.Java;
|
||||
using Phantom.Common.Data.Web.Users;
|
||||
|
||||
namespace Phantom.Web.Utils;
|
||||
|
||||
Reference in New Issue
Block a user