mirror of
https://github.com/chylex/Minecraft-Phantom-Panel.git
synced 2026-04-07 03:46:52 +02:00
Compare commits
3 Commits
main
...
wip-backup
| Author | SHA1 | Date | |
|---|---|---|---|
|
86e6ec8154
|
|||
|
ab699de0e2
|
|||
|
84ca2be336
|
@@ -77,9 +77,10 @@ public sealed class AgentRegistrationHandler {
|
||||
return new InstanceManagerActor.ConfigureInstanceCommand(
|
||||
configureInstanceMessage.InstanceGuid,
|
||||
configureInstanceMessage.Info,
|
||||
configureInstanceMessage.LaunchRecipe,
|
||||
configureInstanceMessage.LaunchRecipe.Value,
|
||||
configureInstanceMessage.LaunchNow,
|
||||
configureInstanceMessage.StopRecipe,
|
||||
configureInstanceMessage.BackupConfiguration.Value,
|
||||
AlwaysReportStatus: true
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using Phantom.Agent.Services.Instances;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Phantom.Agent.Services.Instances;
|
||||
using Phantom.Agent.Services.Instances.State;
|
||||
using Phantom.Common.Data.Agent.Instance.Backups;
|
||||
using Phantom.Common.Data.Backups;
|
||||
using Phantom.Utils.Logging;
|
||||
using Phantom.Utils.Tasks;
|
||||
@@ -7,28 +9,39 @@ using Phantom.Utils.Tasks;
|
||||
namespace Phantom.Agent.Services.Backups;
|
||||
|
||||
sealed class BackupScheduler : CancellableBackgroundTask {
|
||||
// TODO make configurable
|
||||
private static readonly TimeSpan InitialDelay = TimeSpan.FromMinutes(2);
|
||||
private static readonly TimeSpan BackupInterval = TimeSpan.FromMinutes(30);
|
||||
private static readonly TimeSpan BackupFailureRetryDelay = TimeSpan.FromMinutes(5);
|
||||
|
||||
private readonly BackupManager backupManager;
|
||||
private readonly InstanceContext context;
|
||||
private readonly SemaphoreSlim backupSemaphore = new (initialCount: 1, maxCount: 1);
|
||||
|
||||
private readonly TimeSpan initialDelay;
|
||||
private readonly TimeSpan backupInterval;
|
||||
private readonly TimeSpan failureRetryDelay;
|
||||
|
||||
private readonly ManualResetEventSlim serverOutputWhileWaitingForOnlinePlayers = new ();
|
||||
private readonly InstancePlayerCountTracker playerCountTracker;
|
||||
private readonly InstancePlayerCountTracker? playerCountTracker;
|
||||
|
||||
public event EventHandler<BackupCreationResult>? BackupCompleted;
|
||||
|
||||
public BackupScheduler(InstanceContext context, InstancePlayerCountTracker playerCountTracker) : base(PhantomLogger.Create<BackupScheduler>(context.ShortName)) {
|
||||
this.backupManager = context.Services.BackupManager;
|
||||
[SuppressMessage("ReSharper", "ConvertIfStatementToConditionalTernaryExpression")]
|
||||
public BackupScheduler(InstanceContext context, InstanceProcess process, InstanceBackupSchedule schedule) : base(PhantomLogger.Create<BackupScheduler>(context.ShortName)) {
|
||||
this.context = context;
|
||||
this.playerCountTracker = playerCountTracker;
|
||||
|
||||
this.initialDelay = schedule.InitialDelay;
|
||||
this.backupInterval = schedule.BackupInterval;
|
||||
this.failureRetryDelay = schedule.BackupFailureRetryDelay;
|
||||
|
||||
var playerCountDetectionStrategy = schedule.PlayerCountDetectionStrategy.Value;
|
||||
if (playerCountDetectionStrategy == null) {
|
||||
this.playerCountTracker = null;
|
||||
}
|
||||
else {
|
||||
this.playerCountTracker = new InstancePlayerCountTracker(context, process, playerCountDetectionStrategy.CreateDetector(new InstancePlayerCountDetectorFactory(context)));
|
||||
}
|
||||
|
||||
Start();
|
||||
}
|
||||
|
||||
protected override async Task RunTask() {
|
||||
await Task.Delay(InitialDelay, CancellationToken);
|
||||
await Task.Delay(initialDelay, CancellationToken);
|
||||
Logger.Information("Starting a new backup after server launched.");
|
||||
|
||||
while (!CancellationToken.IsCancellationRequested) {
|
||||
@@ -36,13 +49,16 @@ sealed class BackupScheduler : CancellableBackgroundTask {
|
||||
BackupCompleted?.Invoke(this, result);
|
||||
|
||||
if (result.Kind.ShouldRetry()) {
|
||||
Logger.Warning("Scheduled backup failed, retrying in {Minutes} minutes.", BackupFailureRetryDelay.TotalMinutes);
|
||||
await Task.Delay(BackupFailureRetryDelay, CancellationToken);
|
||||
Logger.Warning("Scheduled backup failed, retrying in {Minutes} minutes.", failureRetryDelay.TotalMinutes);
|
||||
await Task.Delay(failureRetryDelay, CancellationToken);
|
||||
}
|
||||
else {
|
||||
Logger.Information("Scheduling next backup in {Minutes} minutes.", BackupInterval.TotalMinutes);
|
||||
await Task.Delay(BackupInterval, CancellationToken);
|
||||
await WaitForOnlinePlayers();
|
||||
Logger.Information("Scheduling next backup in {Minutes} minutes.", backupInterval.TotalMinutes);
|
||||
await Task.Delay(backupInterval, CancellationToken);
|
||||
|
||||
if (playerCountTracker != null) {
|
||||
await WaitForOnlinePlayers(playerCountTracker);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,7 +70,7 @@ sealed class BackupScheduler : CancellableBackgroundTask {
|
||||
|
||||
try {
|
||||
context.ActorCancellationToken.ThrowIfCancellationRequested();
|
||||
return await context.Actor.Request(new InstanceActor.BackupInstanceCommand(backupManager), context.ActorCancellationToken);
|
||||
return await context.Actor.Request(new InstanceActor.BackupInstanceCommand(context.Services.BackupManager), context.ActorCancellationToken);
|
||||
} catch (OperationCanceledException) {
|
||||
return new BackupCreationResult(BackupCreationResultKind.InstanceNotRunning);
|
||||
} finally {
|
||||
@@ -62,7 +78,7 @@ sealed class BackupScheduler : CancellableBackgroundTask {
|
||||
}
|
||||
}
|
||||
|
||||
private async Task WaitForOnlinePlayers() {
|
||||
private async Task WaitForOnlinePlayers(InstancePlayerCountTracker playerCountTracker) {
|
||||
var task = playerCountTracker.WaitForOnlinePlayers(CancellationToken);
|
||||
if (!task.IsCompleted) {
|
||||
Logger.Information("Waiting for someone to join before starting a new backup.");
|
||||
@@ -79,6 +95,7 @@ sealed class BackupScheduler : CancellableBackgroundTask {
|
||||
}
|
||||
|
||||
protected override void Dispose() {
|
||||
playerCountTracker?.Stop();
|
||||
backupSemaphore.Dispose();
|
||||
serverOutputWhileWaitingForOnlinePlayers.Dispose();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
using System.Net.Sockets;
|
||||
using Phantom.Agent.Services.Instances;
|
||||
using Phantom.Common.Data.Agent.Instance.Backups;
|
||||
using Phantom.Common.Data.Instance;
|
||||
using Phantom.Utils.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Services.Games;
|
||||
|
||||
sealed class MinecraftServerPlayerCountDetector(InstanceContext instanceContext, ushort serverPort) : IInstancePlayerCountDetector {
|
||||
private readonly ILogger logger = PhantomLogger.Create<MinecraftServerPlayerCountDetector>(instanceContext.ShortName);
|
||||
|
||||
private bool waitingForFirstDetection = true;
|
||||
|
||||
public async Task<InstancePlayerCounts?> TryGetPlayerCounts(CancellationToken cancellationToken) {
|
||||
try {
|
||||
var playerCounts = await MinecraftServerStatusProtocol.GetPlayerCounts(serverPort, cancellationToken);
|
||||
waitingForFirstDetection = false;
|
||||
return playerCounts;
|
||||
} catch (MinecraftServerStatusProtocol.ProtocolException e) {
|
||||
logger.Error("{Message}", e.Message);
|
||||
return null;
|
||||
} catch (SocketException e) {
|
||||
bool waitingForServerStart = e.SocketErrorCode == SocketError.ConnectionRefused && waitingForFirstDetection;
|
||||
if (!waitingForServerStart) {
|
||||
logger.Warning("Could not check online player count. Socket error {ErrorCode} ({ErrorCodeName}), reason: {ErrorMessage}", e.ErrorCode, e.SocketErrorCode, e.Message);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ static class MinecraftServerStatusProtocol {
|
||||
await tcpClient.ConnectAsync(IPAddress.Loopback, serverPort, cancellationToken);
|
||||
var tcpStream = tcpClient.GetStream();
|
||||
|
||||
// https://wiki.vg/Server_List_Ping
|
||||
// https://minecraft.wiki/w/Java_Edition_protocol/Server_List_Ping
|
||||
tcpStream.WriteByte(0xFE);
|
||||
await tcpStream.FlushAsync(cancellationToken);
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ 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.Backups;
|
||||
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||
using Phantom.Common.Data.Backups;
|
||||
using Phantom.Common.Data.Instance;
|
||||
@@ -83,7 +84,7 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
|
||||
public sealed record ReportInstanceStatusCommand : ICommand;
|
||||
|
||||
public sealed record LaunchInstanceCommand(InstanceInfo Info, InstanceLauncher Launcher, InstanceTicketManager.Ticket Ticket, bool IsRestarting) : ICommand;
|
||||
public sealed record LaunchInstanceCommand(InstanceInfo Info, InstanceLauncher Launcher, InstanceBackupConfiguration? BackupConfiguration, InstanceTicketManager.Ticket Ticket, bool IsRestarting) : ICommand;
|
||||
|
||||
public sealed record StopInstanceCommand(InstanceStopRecipe StopRecipe) : ICommand;
|
||||
|
||||
@@ -108,7 +109,11 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
SetAndReportStatus(newStatus ?? defaultLaunchStatus);
|
||||
}
|
||||
|
||||
var newState = await InstanceLaunchProcedure.Run(context, command.Info, command.Launcher, instanceTicketManager, command.Ticket, UpdateStatus, shutdownCancellationToken);
|
||||
if (command.IsRestarting) {
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), shutdownCancellationToken);
|
||||
}
|
||||
|
||||
var newState = await InstanceLaunchProcedure.Run(context, command.Info, command.Launcher, command.BackupConfiguration, instanceTicketManager, command.Ticket, UpdateStatus, shutdownCancellationToken);
|
||||
if (newState is null) {
|
||||
instanceTicketManager.Release(command.Ticket);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ 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.Backups;
|
||||
using Phantom.Common.Data.Agent.Instance.Launch;
|
||||
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||
using Phantom.Common.Data.Instance;
|
||||
@@ -52,11 +53,18 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
ReceiveAsync<ShutdownCommand>(Shutdown);
|
||||
}
|
||||
|
||||
private sealed record Instance(ActorRef<InstanceActor.ICommand> Actor, InstanceInfo Info, InstanceProperties Properties, InstanceLaunchRecipe? LaunchRecipe, InstanceStopRecipe StopRecipe);
|
||||
private sealed record Instance(
|
||||
ActorRef<InstanceActor.ICommand> Actor,
|
||||
InstanceInfo Info,
|
||||
InstanceProperties Properties,
|
||||
InstanceLaunchRecipe? LaunchRecipe,
|
||||
InstanceStopRecipe StopRecipe,
|
||||
InstanceBackupConfiguration? BackupConfiguration
|
||||
);
|
||||
|
||||
public interface ICommand;
|
||||
|
||||
public sealed record ConfigureInstanceCommand(Guid InstanceGuid, InstanceInfo InstanceInfo, InstanceLaunchRecipe? LaunchRecipe, bool LaunchNow, InstanceStopRecipe StopRecipe, bool AlwaysReportStatus) : ICommand, ICanReply<Result<ConfigureInstanceResult, InstanceActionFailure>>;
|
||||
public sealed record ConfigureInstanceCommand(Guid InstanceGuid, InstanceInfo InstanceInfo, InstanceLaunchRecipe? LaunchRecipe, bool LaunchNow, InstanceStopRecipe StopRecipe, InstanceBackupConfiguration? BackupConfiguration, bool AlwaysReportStatus) : ICommand, ICanReply<Result<ConfigureInstanceResult, InstanceActionFailure>>;
|
||||
|
||||
public sealed record LaunchInstanceCommand(Guid InstanceGuid) : ICommand, ICanReply<Result<LaunchInstanceResult, InstanceActionFailure>>;
|
||||
|
||||
@@ -71,12 +79,14 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
var instanceInfo = command.InstanceInfo;
|
||||
var launchRecipe = command.LaunchRecipe;
|
||||
var stopRecipe = command.StopRecipe;
|
||||
var backupConfiguration = command.BackupConfiguration;
|
||||
|
||||
if (instances.TryGetValue(instanceGuid, out var instance)) {
|
||||
instances[instanceGuid] = instance with {
|
||||
Info = instanceInfo,
|
||||
LaunchRecipe = launchRecipe,
|
||||
StopRecipe = stopRecipe,
|
||||
BackupConfiguration = backupConfiguration,
|
||||
};
|
||||
|
||||
Logger.Information("Reconfigured instance \"{Name}\" (GUID {Guid}).", instanceInfo.InstanceName, instanceGuid);
|
||||
@@ -90,7 +100,9 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
var instanceDirectoryPath = Path.Combine(agentDirectories.InstancesDirectoryPath, instanceGuid.ToString());
|
||||
var instanceProperties = new InstanceProperties(instanceGuid, instanceDirectoryPath);
|
||||
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, stopRecipe);
|
||||
var instanceActor = Context.ActorOf(InstanceActor.Factory(instanceInit), "Instance-" + instanceGuid);
|
||||
|
||||
instances[instanceGuid] = instance = new Instance(instanceActor, instanceInfo, instanceProperties, launchRecipe, stopRecipe, backupConfiguration);
|
||||
|
||||
Logger.Information("Created instance \"{Name}\" (GUID {Guid}).", instanceInfo.InstanceName, instanceGuid);
|
||||
|
||||
@@ -140,7 +152,7 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
var valueResolver = new InstanceValueResolver(pathResolver);
|
||||
var launcher = new InstanceLauncher(instanceServices.DownloadManager, pathResolver, valueResolver, instance.Properties, launchRecipe);
|
||||
|
||||
instance.Actor.Tell(new InstanceActor.LaunchInstanceCommand(instance.Info, launcher, ticket.Value, IsRestarting: false));
|
||||
instance.Actor.Tell(new InstanceActor.LaunchInstanceCommand(instance.Info, launcher, instance.BackupConfiguration, ticket.Value, IsRestarting: false));
|
||||
|
||||
return LaunchInstanceResult.LaunchInitiated;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
using Phantom.Agent.Services.Instances.State;
|
||||
using Phantom.Common.Data;
|
||||
using Phantom.Common.Data.Agent.Instance;
|
||||
using Phantom.Common.Data.Agent.Instance.Backups;
|
||||
using Phantom.Common.Data.Instance;
|
||||
|
||||
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) {
|
||||
public static async Task<InstanceRunningState?> Run(
|
||||
InstanceContext context,
|
||||
InstanceInfo info,
|
||||
InstanceLauncher launcher,
|
||||
InstanceBackupConfiguration? backupConfiguration,
|
||||
InstanceTicketManager ticketManager,
|
||||
InstanceTicketManager.Ticket ticket,
|
||||
Action<IInstanceStatus?> reportStatus,
|
||||
CancellationToken cancellationToken
|
||||
) {
|
||||
context.Logger.Information("Session starting...");
|
||||
|
||||
Result<InstanceProcess, InstanceLaunchFailReason> result;
|
||||
@@ -30,7 +40,7 @@ static class InstanceLaunchProcedure {
|
||||
if (result) {
|
||||
reportStatus(InstanceStatus.Running);
|
||||
context.ReportEvent(InstanceEvent.LaunchSucceeded);
|
||||
return new InstanceRunningState(context, info, launcher, ticket, result.Value, cancellationToken);
|
||||
return new InstanceRunningState(context, info, launcher, backupConfiguration, ticket, result.Value, cancellationToken);
|
||||
}
|
||||
else {
|
||||
reportStatus(InstanceStatus.Failed(result.Error));
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
using Phantom.Agent.Services.Games;
|
||||
using Phantom.Common.Data.Agent.Instance.Backups;
|
||||
|
||||
namespace Phantom.Agent.Services.Instances.State;
|
||||
|
||||
sealed class InstancePlayerCountDetectorFactory(InstanceContext instanceContext) : IInstancePlayerCountDetectorFactory {
|
||||
public IInstancePlayerCountDetector MinecraftStatusProtocol(ushort port) {
|
||||
return new MinecraftServerPlayerCountDetector(instanceContext, port);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.Net.Sockets;
|
||||
using Phantom.Agent.Services.Games;
|
||||
using Phantom.Agent.Services.Rpc;
|
||||
using Phantom.Agent.Services.Rpc;
|
||||
using Phantom.Common.Data.Agent.Instance.Backups;
|
||||
using Phantom.Common.Data.Instance;
|
||||
using Phantom.Common.Messages.Agent.ToController;
|
||||
using Phantom.Utils.Logging;
|
||||
@@ -12,8 +11,8 @@ namespace Phantom.Agent.Services.Instances.State;
|
||||
sealed class InstancePlayerCountTracker : CancellableBackgroundTask {
|
||||
private readonly ControllerConnection controllerConnection;
|
||||
private readonly Guid instanceGuid;
|
||||
private readonly ushort serverPort;
|
||||
private readonly InstanceProcess process;
|
||||
private readonly IInstancePlayerCountDetector playerCountDetector;
|
||||
|
||||
private readonly TaskCompletionSource firstDetection = AsyncTasks.CreateCompletionSource();
|
||||
private readonly ManualResetEventSlim serverOutputEvent = new ();
|
||||
@@ -25,11 +24,11 @@ sealed class InstancePlayerCountTracker : CancellableBackgroundTask {
|
||||
|
||||
private bool isDisposed = false;
|
||||
|
||||
public InstancePlayerCountTracker(InstanceContext context, InstanceProcess process, ushort serverPort) : base(PhantomLogger.Create<InstancePlayerCountTracker>(context.ShortName)) {
|
||||
public InstancePlayerCountTracker(InstanceContext context, InstanceProcess process, IInstancePlayerCountDetector playerCountDetector) : base(PhantomLogger.Create<InstancePlayerCountTracker>(context.ShortName)) {
|
||||
this.controllerConnection = context.Services.ControllerConnection;
|
||||
this.instanceGuid = context.InstanceGuid;
|
||||
this.process = process;
|
||||
this.serverPort = serverPort;
|
||||
this.playerCountDetector = playerCountDetector;
|
||||
Start();
|
||||
}
|
||||
|
||||
@@ -59,17 +58,7 @@ sealed class InstancePlayerCountTracker : CancellableBackgroundTask {
|
||||
|
||||
private async Task<InstancePlayerCounts?> TryGetPlayerCounts() {
|
||||
try {
|
||||
return await MinecraftServerStatusProtocol.GetPlayerCounts(serverPort, CancellationToken);
|
||||
} catch (MinecraftServerStatusProtocol.ProtocolException e) {
|
||||
Logger.Error("{Message}", e.Message);
|
||||
return null;
|
||||
} catch (SocketException e) {
|
||||
bool waitingForServerStart = e.SocketErrorCode == SocketError.ConnectionRefused && WaitingForFirstDetection;
|
||||
if (!waitingForServerStart) {
|
||||
Logger.Warning("Could not check online player count. Socket error {ErrorCode} ({ErrorCodeName}), reason: {ErrorMessage}", e.ErrorCode, e.SocketErrorCode, e.Message);
|
||||
}
|
||||
|
||||
return null;
|
||||
return await playerCountDetector.TryGetPlayerCounts(CancellationToken);
|
||||
} catch (Exception e) {
|
||||
Logger.Error(e, "Caught exception while checking online player count.");
|
||||
return null;
|
||||
@@ -77,8 +66,8 @@ sealed class InstancePlayerCountTracker : CancellableBackgroundTask {
|
||||
}
|
||||
|
||||
private void UpdatePlayerCounts(InstancePlayerCounts? newPlayerCounts) {
|
||||
if (newPlayerCounts is {} value) {
|
||||
Logger.Debug("Detected {OnlinePlayerCount} / {MaximumPlayerCount} online player(s).", value.Online, value.Maximum);
|
||||
if (newPlayerCounts != null) {
|
||||
Logger.Debug("Detected {OnlinePlayerCount} / {MaximumPlayerCount} online player(s).", newPlayerCounts.Online, newPlayerCounts.Maximum);
|
||||
firstDetection.TrySetResult();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Phantom.Agent.Services.Backups;
|
||||
using Phantom.Agent.Services.Instances.Launch;
|
||||
using Phantom.Common.Data.Agent.Instance;
|
||||
using Phantom.Common.Data.Agent.Instance.Backups;
|
||||
using Phantom.Common.Data.Backups;
|
||||
using Phantom.Common.Data.Instance;
|
||||
using Phantom.Common.Data.Replies;
|
||||
@@ -17,27 +18,32 @@ sealed class InstanceRunningState : IDisposable {
|
||||
private readonly InstanceContext context;
|
||||
private readonly InstanceInfo info;
|
||||
private readonly InstanceLauncher launcher;
|
||||
private readonly InstanceBackupConfiguration? backupConfiguration;
|
||||
private readonly CancellationToken cancellationToken;
|
||||
|
||||
private readonly InstanceLogSender logSender;
|
||||
private readonly InstancePlayerCountTracker playerCountTracker;
|
||||
private readonly BackupScheduler backupScheduler;
|
||||
private readonly BackupScheduler? backupScheduler;
|
||||
|
||||
private bool isDisposed;
|
||||
|
||||
public InstanceRunningState(InstanceContext context, InstanceInfo info, InstanceLauncher launcher, InstanceTicketManager.Ticket ticket, InstanceProcess process, CancellationToken cancellationToken) {
|
||||
public InstanceRunningState(InstanceContext context, InstanceInfo info, InstanceLauncher launcher, InstanceBackupConfiguration? backupConfiguration, InstanceTicketManager.Ticket ticket, InstanceProcess process, CancellationToken cancellationToken) {
|
||||
this.context = context;
|
||||
this.info = info;
|
||||
this.launcher = launcher;
|
||||
this.backupConfiguration = backupConfiguration;
|
||||
this.Ticket = ticket;
|
||||
this.Process = process;
|
||||
this.cancellationToken = cancellationToken;
|
||||
|
||||
this.logSender = new InstanceLogSender(context.Services.ControllerConnection, context.InstanceGuid, context.ShortName);
|
||||
this.playerCountTracker = new InstancePlayerCountTracker(context, process, info.ServerPort);
|
||||
|
||||
this.backupScheduler = new BackupScheduler(context, playerCountTracker);
|
||||
this.backupScheduler.BackupCompleted += OnScheduledBackupCompleted;
|
||||
if (backupConfiguration == null) {
|
||||
this.backupScheduler = null;
|
||||
}
|
||||
else {
|
||||
this.backupScheduler = new BackupScheduler(context, process, backupConfiguration.Schedule);
|
||||
this.backupScheduler.BackupCompleted += OnScheduledBackupCompleted;
|
||||
}
|
||||
}
|
||||
|
||||
public void Initialize() {
|
||||
@@ -75,7 +81,7 @@ sealed class InstanceRunningState : IDisposable {
|
||||
else {
|
||||
context.Logger.Information("Session ended unexpectedly, restarting...");
|
||||
context.ReportEvent(InstanceEvent.Crashed);
|
||||
context.Actor.Tell(new InstanceActor.LaunchInstanceCommand(info, launcher, Ticket, IsRestarting: true));
|
||||
context.Actor.Tell(new InstanceActor.LaunchInstanceCommand(info, launcher, backupConfiguration, Ticket, IsRestarting: true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,8 +103,7 @@ sealed class InstanceRunningState : IDisposable {
|
||||
}
|
||||
|
||||
public void OnStopInitiated() {
|
||||
backupScheduler.Stop();
|
||||
playerCountTracker.Stop();
|
||||
backupScheduler?.Stop();
|
||||
}
|
||||
|
||||
private bool TryDispose() {
|
||||
|
||||
@@ -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, message.StopRecipe, AlwaysReportStatus: false));
|
||||
return await agent.InstanceManager.Request(new InstanceManagerActor.ConfigureInstanceCommand(message.InstanceGuid, message.Info, message.LaunchRecipe.Value, message.LaunchNow, message.StopRecipe, message.BackupConfiguration.Value, AlwaysReportStatus: false));
|
||||
}
|
||||
|
||||
private async Task<Result<LaunchInstanceResult, InstanceActionFailure>> HandleLaunchInstance(LaunchInstanceMessage message) {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using MemoryPack;
|
||||
|
||||
namespace Phantom.Common.Data.Agent.Instance.Backups;
|
||||
|
||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||
public sealed partial record InstanceBackupSchedule(
|
||||
[property: MemoryPackOrder(0)] ushort InitialDelayInMinutes,
|
||||
[property: MemoryPackOrder(1)] ushort BackupIntervalInMinutes,
|
||||
[property: MemoryPackOrder(2)] ushort BackupFailureRetryDelayInMinutes,
|
||||
[property: MemoryPackOrder(3)] Optional<IInstancePlayerCountDetectionStrategy> PlayerCountDetectionStrategy
|
||||
) {
|
||||
[MemoryPackIgnore]
|
||||
public TimeSpan InitialDelay => TimeSpan.FromMinutes(InitialDelayInMinutes);
|
||||
|
||||
[MemoryPackIgnore]
|
||||
public TimeSpan BackupInterval => TimeSpan.FromMinutes(AtLeastOne(BackupIntervalInMinutes));
|
||||
|
||||
[MemoryPackIgnore]
|
||||
public TimeSpan BackupFailureRetryDelay => TimeSpan.FromMinutes(AtLeastOne(BackupFailureRetryDelayInMinutes));
|
||||
|
||||
private static ushort AtLeastOne(ushort value) {
|
||||
return Math.Max(value, (ushort) 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using MemoryPack;
|
||||
|
||||
namespace Phantom.Common.Data.Agent.Instance.Backups;
|
||||
|
||||
[MemoryPackable]
|
||||
[MemoryPackUnion(tag: 0, type: typeof(InstancePlayerCountDetectionStrategy.MinecraftStatusProtocol))]
|
||||
public partial interface IInstancePlayerCountDetectionStrategy {
|
||||
IInstancePlayerCountDetector CreateDetector(IInstancePlayerCountDetectorFactory factory);
|
||||
}
|
||||
|
||||
public static partial class InstancePlayerCountDetectionStrategy {
|
||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||
public sealed partial record MinecraftStatusProtocol(
|
||||
[property: MemoryPackOrder(0)] ushort Port
|
||||
) : IInstancePlayerCountDetectionStrategy {
|
||||
public IInstancePlayerCountDetector CreateDetector(IInstancePlayerCountDetectorFactory factory) {
|
||||
return factory.MinecraftStatusProtocol(Port);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Phantom.Common.Data.Instance;
|
||||
|
||||
namespace Phantom.Common.Data.Agent.Instance.Backups;
|
||||
|
||||
public interface IInstancePlayerCountDetector {
|
||||
Task<InstancePlayerCounts?> TryGetPlayerCounts(CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace Phantom.Common.Data.Agent.Instance.Backups;
|
||||
|
||||
public interface IInstancePlayerCountDetectorFactory {
|
||||
IInstancePlayerCountDetector MinecraftStatusProtocol(ushort port);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using MemoryPack;
|
||||
|
||||
namespace Phantom.Common.Data.Agent.Instance.Backups;
|
||||
|
||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||
public sealed partial record InstanceBackupConfiguration(
|
||||
[property: MemoryPackOrder(0)] InstanceBackupSchedule Schedule
|
||||
);
|
||||
@@ -3,6 +3,8 @@
|
||||
public enum ConfigureInstanceResult : byte {
|
||||
Success = 0,
|
||||
CouldNotCreateInstanceDirectory = 1,
|
||||
MinecraftVersionNotFound = 2,
|
||||
UnknownError = 255,
|
||||
}
|
||||
|
||||
public static class ConfigureInstanceResultExtensions {
|
||||
@@ -10,6 +12,7 @@ public static class ConfigureInstanceResultExtensions {
|
||||
return reason switch {
|
||||
ConfigureInstanceResult.Success => "Success.",
|
||||
ConfigureInstanceResult.CouldNotCreateInstanceDirectory => "Could not create instance directory.",
|
||||
ConfigureInstanceResult.MinecraftVersionNotFound => "Minecraft version not found.",
|
||||
_ => "Unknown error.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -43,6 +43,10 @@ public sealed partial class Result<TValue, TError> {
|
||||
return hasValue ? valueConverter(value!) : errorConverter(error!);
|
||||
}
|
||||
|
||||
public Result<TNewValue, TError> MapValue<TNewValue>(Func<TValue, TNewValue> valueConverter) {
|
||||
return hasValue ? valueConverter(value!) : error!;
|
||||
}
|
||||
|
||||
public Result<TValue, TNewError> MapError<TNewError>(Func<TError, TNewError> errorConverter) {
|
||||
return hasValue ? value! : errorConverter(error!);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using MemoryPack;
|
||||
using Phantom.Common.Data;
|
||||
using Phantom.Common.Data.Agent.Instance;
|
||||
using Phantom.Common.Data.Agent.Instance.Backups;
|
||||
using Phantom.Common.Data.Agent.Instance.Launch;
|
||||
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||
using Phantom.Common.Data.Replies;
|
||||
@@ -12,7 +13,8 @@ namespace Phantom.Common.Messages.Agent.ToAgent;
|
||||
public sealed partial record ConfigureInstanceMessage(
|
||||
[property: MemoryPackOrder(0)] Guid InstanceGuid,
|
||||
[property: MemoryPackOrder(1)] InstanceInfo Info,
|
||||
[property: MemoryPackOrder(2)] InstanceLaunchRecipe? LaunchRecipe,
|
||||
[property: MemoryPackOrder(2)] Optional<InstanceLaunchRecipe> LaunchRecipe,
|
||||
[property: MemoryPackOrder(3)] bool LaunchNow,
|
||||
[property: MemoryPackOrder(4)] InstanceStopRecipe StopRecipe
|
||||
[property: MemoryPackOrder(4)] InstanceStopRecipe StopRecipe,
|
||||
[property: MemoryPackOrder(5)] Optional<InstanceBackupConfiguration> BackupConfiguration
|
||||
) : IMessageToAgent, ICanReply<Result<ConfigureInstanceResult, InstanceActionFailure>>;
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
using Akka.Actor;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
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.Replies;
|
||||
@@ -89,7 +88,6 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
private readonly ActorRef<AgentDatabaseStorageActor.ICommand> databaseStorageActor;
|
||||
|
||||
private readonly Dictionary<Guid, ActorRef<InstanceActor.ICommand>> instanceActorByGuid = new ();
|
||||
private readonly Dictionary<Guid, Instance> instanceDataByGuid = new ();
|
||||
|
||||
private AgentActor(Init init) {
|
||||
this.agentConnectionKeys = init.AgentConnectionKeys;
|
||||
@@ -142,20 +140,15 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
}
|
||||
|
||||
private ActorRef<InstanceActor.ICommand> CreateNewInstance(Instance instance) {
|
||||
UpdateInstanceData(instance);
|
||||
controllerState.UpdateInstance(instance);
|
||||
|
||||
var instanceActor = CreateInstanceActor(instance);
|
||||
instanceActorByGuid.Add(instance.InstanceGuid, instanceActor);
|
||||
return instanceActor;
|
||||
}
|
||||
|
||||
private void UpdateInstanceData(Instance instance) {
|
||||
instanceDataByGuid[instance.InstanceGuid] = instance;
|
||||
controllerState.UpdateInstance(instance);
|
||||
}
|
||||
|
||||
private ActorRef<InstanceActor.ICommand> CreateInstanceActor(Instance instance) {
|
||||
var init = new InstanceActor.Init(instance, SelfTyped, connection, dbProvider, cancellationToken);
|
||||
var init = new InstanceActor.Init(instance, SelfTyped, connection, minecraftInstanceRecipes, dbProvider, cancellationToken);
|
||||
var name = "Instance:" + instance.InstanceGuid;
|
||||
return Context.ActorOf(InstanceActor.Factory(init), name);
|
||||
}
|
||||
@@ -186,16 +179,7 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
}
|
||||
|
||||
private async Task<ImmutableArray<ConfigureInstanceMessage>> PrepareInitialConfigurationMessages() {
|
||||
var configurationMessages = ImmutableArray.CreateBuilder<ConfigureInstanceMessage>();
|
||||
|
||||
foreach (var (instanceGuid, instanceConfiguration, _, _, launchAutomatically) in instanceDataByGuid.Values.ToImmutableArray()) {
|
||||
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);
|
||||
}
|
||||
|
||||
return configurationMessages.ToImmutable();
|
||||
return [..await Task.WhenAll(instanceActorByGuid.Values.Select(async instance => await instance.Request(new InstanceActor.GetInitialInstanceConfigurationCommand(), cancellationToken)))];
|
||||
}
|
||||
|
||||
public interface ICommand;
|
||||
@@ -341,39 +325,25 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
return Task.FromResult<Result<CreateOrUpdateInstanceResult, InstanceActionFailure>>(CreateOrUpdateInstanceResult.InstanceMemoryMustNotBeZero);
|
||||
}
|
||||
|
||||
return minecraftInstanceRecipes.Launch(instanceConfiguration, cancellationToken)
|
||||
.ContinueOnActor(CreateOrUpdateInstance1, command)
|
||||
.Unwrap();
|
||||
}
|
||||
|
||||
private Task<Result<CreateOrUpdateInstanceResult, InstanceActionFailure>> CreateOrUpdateInstance1(Result<InstanceLaunchRecipe, MinecraftLaunchRecipeCreationFailReason> launchRecipe, CreateOrUpdateInstanceCommand command) {
|
||||
if (!launchRecipe) {
|
||||
return Task.FromResult<Result<CreateOrUpdateInstanceResult, InstanceActionFailure>>(launchRecipe.Error switch {
|
||||
MinecraftLaunchRecipeCreationFailReason.MinecraftVersionNotFound => CreateOrUpdateInstanceResult.MinecraftVersionNotFound,
|
||||
_ => CreateOrUpdateInstanceResult.UnknownError,
|
||||
});
|
||||
}
|
||||
|
||||
var instanceGuid = command.InstanceGuid;
|
||||
var instanceConfiguration = command.Configuration;
|
||||
|
||||
bool isCreatingInstance = !instanceActorByGuid.TryGetValue(instanceGuid, out var instanceActorRef);
|
||||
if (isCreatingInstance) {
|
||||
instanceActorRef = CreateNewInstance(Instance.Offline(instanceGuid, instanceConfiguration));
|
||||
}
|
||||
|
||||
var stopRecipe = minecraftInstanceRecipes.Stop(afterSeconds: 0);
|
||||
var configureInstanceCommand = new InstanceActor.ConfigureInstanceCommand(command.LoggedInUserGuid, instanceGuid, instanceConfiguration, launchRecipe.Value, stopRecipe, isCreatingInstance);
|
||||
var configureInstanceCommand = new InstanceActor.ConfigureInstanceCommand(command.LoggedInUserGuid, instanceConfiguration, isCreatingInstance);
|
||||
var configuredInstanceInfo = new ConfiguredInstanceInfo(instanceGuid, instanceConfiguration.InstanceName, isCreatingInstance);
|
||||
|
||||
return instanceActorRef.Request(configureInstanceCommand, cancellationToken)
|
||||
.ContinueOnActor(CreateOrUpdateInstance2, configureInstanceCommand);
|
||||
.ContinueOnActor(CreateOrUpdateInstance2, configuredInstanceInfo);
|
||||
}
|
||||
|
||||
private sealed record ConfiguredInstanceInfo(Guid InstanceGuid, string InstanceName, bool IsCreating);
|
||||
|
||||
#pragma warning disable CA2254
|
||||
private Result<CreateOrUpdateInstanceResult, InstanceActionFailure> CreateOrUpdateInstance2(Result<ConfigureInstanceResult, InstanceActionFailure> result, InstanceActor.ConfigureInstanceCommand command) {
|
||||
var instanceGuid = command.InstanceGuid;
|
||||
var instanceName = command.Configuration.InstanceName;
|
||||
var isCreating = command.IsCreatingInstance;
|
||||
private Result<CreateOrUpdateInstanceResult, InstanceActionFailure> CreateOrUpdateInstance2(Result<ConfigureInstanceResult, InstanceActionFailure> result, ConfiguredInstanceInfo info) {
|
||||
(Guid instanceGuid, string instanceName, bool isCreating) = info;
|
||||
|
||||
if (result.Is(ConfigureInstanceResult.Success)) {
|
||||
string action = isCreating ? "Created" : "Edited";
|
||||
@@ -386,7 +356,10 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
string reason = result.Into(ConfigureInstanceResultExtensions.ToSentence, InstanceActionFailureExtensions.ToSentence);
|
||||
Logger.Information("Failed " + action + " instance \"{InstanceName}\" (GUID {InstanceGuid}) in agent \"{AgentName}\". {ErrorMessage}", instanceName, instanceGuid, AgentName, reason);
|
||||
|
||||
return CreateOrUpdateInstanceResult.UnknownError;
|
||||
return result.MapValue(static value => value switch {
|
||||
ConfigureInstanceResult.MinecraftVersionNotFound => CreateOrUpdateInstanceResult.MinecraftVersionNotFound,
|
||||
_ => CreateOrUpdateInstanceResult.UnknownError,
|
||||
});
|
||||
}
|
||||
}
|
||||
#pragma warning restore CA2254
|
||||
@@ -413,7 +386,7 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
}
|
||||
|
||||
private void ReceiveInstanceData(ReceiveInstanceDataCommand command) {
|
||||
UpdateInstanceData(command.Instance);
|
||||
controllerState.UpdateInstance(command.Instance);
|
||||
}
|
||||
|
||||
private sealed class AuthInfo {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Phantom.Common.Data;
|
||||
using Phantom.Common.Data.Agent.Instance.Backups;
|
||||
using Phantom.Common.Data.Agent.Instance.Launch;
|
||||
using Phantom.Common.Data.Agent.Instance.Stop;
|
||||
using Phantom.Common.Data.Instance;
|
||||
@@ -7,13 +8,21 @@ using Phantom.Common.Data.Web.Instance;
|
||||
using Phantom.Common.Messages.Agent;
|
||||
using Phantom.Common.Messages.Agent.ToAgent;
|
||||
using Phantom.Controller.Database;
|
||||
using Phantom.Controller.Minecraft;
|
||||
using Phantom.Controller.Services.Agents;
|
||||
using Phantom.Utils.Actor;
|
||||
|
||||
namespace Phantom.Controller.Services.Instances;
|
||||
|
||||
sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
public readonly record struct Init(Instance Instance, ActorRef<AgentActor.ICommand> AgentActor, AgentConnection AgentConnection, IDbContextProvider DbProvider, CancellationToken CancellationToken);
|
||||
public readonly record struct Init(
|
||||
Instance Instance,
|
||||
ActorRef<AgentActor.ICommand> AgentActor,
|
||||
AgentConnection AgentConnection,
|
||||
MinecraftInstanceRecipes MinecraftInstanceRecipes,
|
||||
IDbContextProvider DbProvider,
|
||||
CancellationToken CancellationToken
|
||||
);
|
||||
|
||||
public static Props<ICommand> Factory(Init init) {
|
||||
return Props<ICommand>.Create(() => new InstanceActor(init), new ActorConfiguration { SupervisorStrategy = SupervisorStrategies.Resume });
|
||||
@@ -21,6 +30,7 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
|
||||
private readonly ActorRef<AgentActor.ICommand> agentActor;
|
||||
private readonly AgentConnection agentConnection;
|
||||
private readonly MinecraftInstanceRecipes minecraftInstanceRecipes;
|
||||
private readonly CancellationToken cancellationToken;
|
||||
|
||||
private readonly Guid instanceGuid;
|
||||
@@ -35,6 +45,7 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
private InstanceActor(Init init) {
|
||||
this.agentActor = init.AgentActor;
|
||||
this.agentConnection = init.AgentConnection;
|
||||
this.minecraftInstanceRecipes = init.MinecraftInstanceRecipes;
|
||||
this.cancellationToken = init.CancellationToken;
|
||||
|
||||
(this.instanceGuid, this.configuration, this.status, this.playerCounts, this.launchAutomatically) = init.Instance;
|
||||
@@ -43,6 +54,7 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
|
||||
Receive<SetStatusCommand>(SetStatus);
|
||||
Receive<SetPlayerCountsCommand>(SetPlayerCounts);
|
||||
ReceiveAsyncAndReply<GetInitialInstanceConfigurationCommand, ConfigureInstanceMessage>(GetInitialInstanceConfiguration);
|
||||
ReceiveAsyncAndReply<ConfigureInstanceCommand, Result<ConfigureInstanceResult, InstanceActionFailure>>(ConfigureInstance);
|
||||
ReceiveAsyncAndReply<LaunchInstanceCommand, Result<LaunchInstanceResult, InstanceActionFailure>>(LaunchInstance);
|
||||
ReceiveAsyncAndReply<StopInstanceCommand, Result<StopInstanceResult, InstanceActionFailure>>(StopInstance);
|
||||
@@ -71,7 +83,9 @@ 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, InstanceStopRecipe StopRecipe, bool IsCreatingInstance) : ICommand, ICanReply<Result<ConfigureInstanceResult, InstanceActionFailure>>;
|
||||
public sealed record GetInitialInstanceConfigurationCommand : ICommand, ICanReply<ConfigureInstanceMessage>;
|
||||
|
||||
public sealed record ConfigureInstanceCommand(Guid AuditLogUserGuid, InstanceConfiguration Configuration, bool IsCreatingInstance) : ICommand, ICanReply<Result<ConfigureInstanceResult, InstanceActionFailure>>;
|
||||
|
||||
public sealed record LaunchInstanceCommand(Guid AuditLogUserGuid) : ICommand, ICanReply<Result<LaunchInstanceResult, InstanceActionFailure>>;
|
||||
|
||||
@@ -94,8 +108,21 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
NotifyInstanceUpdated();
|
||||
}
|
||||
|
||||
private async Task<ConfigureInstanceMessage> GetInitialInstanceConfiguration(GetInitialInstanceConfigurationCommand command) {
|
||||
var launchRecipe = await minecraftInstanceRecipes.Launch(configuration, cancellationToken);
|
||||
return CreateConfigureInstanceMessage(configuration, launchRecipe.OrElse(null), launchAutomatically);
|
||||
}
|
||||
|
||||
private async Task<Result<ConfigureInstanceResult, InstanceActionFailure>> ConfigureInstance(ConfigureInstanceCommand command) {
|
||||
var message = new ConfigureInstanceMessage(command.InstanceGuid, command.Configuration.AsInfo, command.LaunchRecipe, LaunchNow: false, command.StopRecipe);
|
||||
var launchRecipe = await minecraftInstanceRecipes.Launch(command.Configuration, cancellationToken);
|
||||
if (!launchRecipe) {
|
||||
return launchRecipe.Error switch {
|
||||
MinecraftLaunchRecipeCreationFailReason.MinecraftVersionNotFound => ConfigureInstanceResult.MinecraftVersionNotFound,
|
||||
_ => ConfigureInstanceResult.UnknownError,
|
||||
};
|
||||
}
|
||||
|
||||
var message = CreateConfigureInstanceMessage(command.Configuration, launchRecipe.Value, launchNow: false);
|
||||
var result = await SendInstanceActionMessage<ConfigureInstanceMessage, ConfigureInstanceResult>(message);
|
||||
|
||||
if (result.Is(ConfigureInstanceResult.Success)) {
|
||||
@@ -114,6 +141,20 @@ sealed class InstanceActor : ReceiveActor<InstanceActor.ICommand> {
|
||||
return result;
|
||||
}
|
||||
|
||||
private ConfigureInstanceMessage CreateConfigureInstanceMessage(InstanceConfiguration configuration, InstanceLaunchRecipe? launchRecipe, bool launchNow) {
|
||||
var stopRecipe = minecraftInstanceRecipes.Stop(afterSeconds: 0);
|
||||
|
||||
var backupSchedule = new InstanceBackupSchedule(
|
||||
InitialDelayInMinutes: 2,
|
||||
BackupIntervalInMinutes: 30,
|
||||
BackupFailureRetryDelayInMinutes: 5,
|
||||
PlayerCountDetectionStrategy: new InstancePlayerCountDetectionStrategy.MinecraftStatusProtocol(configuration.ServerPort)
|
||||
);
|
||||
|
||||
var backupConfiguration = new InstanceBackupConfiguration(backupSchedule);
|
||||
return new ConfigureInstanceMessage(instanceGuid, configuration.AsInfo, launchRecipe, launchNow, stopRecipe, backupConfiguration);
|
||||
}
|
||||
|
||||
private async Task<Result<LaunchInstanceResult, InstanceActionFailure>> LaunchInstance(LaunchInstanceCommand command) {
|
||||
var message = new LaunchInstanceMessage(instanceGuid);
|
||||
var result = await SendInstanceActionMessage<LaunchInstanceMessage, LaunchInstanceResult>(message);
|
||||
|
||||
Reference in New Issue
Block a user