mirror of
https://github.com/chylex/Minecraft-Phantom-Panel.git
synced 2026-04-07 03:46:52 +02:00
Compare commits
8 Commits
wip-recipe
...
wip-backup
| Author | SHA1 | Date | |
|---|---|---|---|
|
86e6ec8154
|
|||
|
ab699de0e2
|
|||
|
84ca2be336
|
|||
|
a1ed4f9d20
|
|||
|
49bdcc3db3
|
|||
|
21bfdf90ee
|
|||
|
298f9adac2
|
|||
|
e1e8963ff4
|
51
Agent/Phantom.Agent.Services/AgentDirectories.cs
Normal file
51
Agent/Phantom.Agent.Services/AgentDirectories.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
using Phantom.Utils.IO;
|
||||
using Phantom.Utils.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Services;
|
||||
|
||||
public sealed class AgentDirectories {
|
||||
private static readonly ILogger Logger = PhantomLogger.Create<AgentDirectories>();
|
||||
|
||||
internal string DataDirectoryPath { get; }
|
||||
internal string InstancesDirectoryPath { get; }
|
||||
internal string BackupsDirectoryPath { get; }
|
||||
|
||||
internal string TemporaryDirectoryPath { get; }
|
||||
internal string ServerExecutableDirectoryPath { get; }
|
||||
|
||||
public string JavaSearchDirectoryPath { get; }
|
||||
|
||||
public AgentDirectories(string dataDirectoryPath, string temporaryDirectoryPath, string javaSearchDirectoryPath) {
|
||||
this.DataDirectoryPath = Path.GetFullPath(dataDirectoryPath);
|
||||
this.InstancesDirectoryPath = Path.Combine(DataDirectoryPath, "instances");
|
||||
this.BackupsDirectoryPath = Path.Combine(DataDirectoryPath, "backups");
|
||||
|
||||
this.TemporaryDirectoryPath = Path.GetFullPath(temporaryDirectoryPath);
|
||||
this.ServerExecutableDirectoryPath = Path.Combine(TemporaryDirectoryPath, "servers");
|
||||
|
||||
this.JavaSearchDirectoryPath = javaSearchDirectoryPath;
|
||||
}
|
||||
|
||||
public bool TryCreate() {
|
||||
return TryCreateDirectory(DataDirectoryPath) &&
|
||||
TryCreateDirectory(InstancesDirectoryPath) &&
|
||||
TryCreateDirectory(BackupsDirectoryPath) &&
|
||||
TryCreateDirectory(TemporaryDirectoryPath) &&
|
||||
TryCreateDirectory(ServerExecutableDirectoryPath);
|
||||
}
|
||||
|
||||
private static bool TryCreateDirectory(string directoryPath) {
|
||||
if (Directory.Exists(directoryPath)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
Directories.Create(directoryPath, Chmod.URWX_GRX);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
Logger.Fatal(e, "Error creating directory: {DirectoryPath}", directoryPath);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
using Phantom.Utils.IO;
|
||||
using Phantom.Utils.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Services;
|
||||
|
||||
public sealed class AgentFolders {
|
||||
private static readonly ILogger Logger = PhantomLogger.Create<AgentFolders>();
|
||||
|
||||
internal string DataFolderPath { get; }
|
||||
internal string InstancesFolderPath { get; }
|
||||
internal string BackupsFolderPath { get; }
|
||||
|
||||
internal string TemporaryFolderPath { get; }
|
||||
internal string ServerExecutableFolderPath { get; }
|
||||
|
||||
public string JavaSearchFolderPath { get; }
|
||||
|
||||
public AgentFolders(string dataFolderPath, string temporaryFolderPath, string javaSearchFolderPath) {
|
||||
this.DataFolderPath = Path.GetFullPath(dataFolderPath);
|
||||
this.InstancesFolderPath = Path.Combine(DataFolderPath, "instances");
|
||||
this.BackupsFolderPath = Path.Combine(DataFolderPath, "backups");
|
||||
|
||||
this.TemporaryFolderPath = Path.GetFullPath(temporaryFolderPath);
|
||||
this.ServerExecutableFolderPath = Path.Combine(TemporaryFolderPath, "servers");
|
||||
|
||||
this.JavaSearchFolderPath = javaSearchFolderPath;
|
||||
}
|
||||
|
||||
public bool TryCreate() {
|
||||
return TryCreateFolder(DataFolderPath) &&
|
||||
TryCreateFolder(InstancesFolderPath) &&
|
||||
TryCreateFolder(BackupsFolderPath) &&
|
||||
TryCreateFolder(TemporaryFolderPath) &&
|
||||
TryCreateFolder(ServerExecutableFolderPath);
|
||||
}
|
||||
|
||||
private static bool TryCreateFolder(string folderPath) {
|
||||
if (Directory.Exists(folderPath)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
Directories.Create(folderPath, Chmod.URWX_GRX);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
Logger.Fatal(e, "Error creating folder: {FolderPath}", folderPath);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,8 +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
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,16 +22,16 @@ public sealed class AgentServices {
|
||||
internal InstanceTicketManager InstanceTicketManager { get; }
|
||||
internal ActorRef<InstanceManagerActor.ICommand> InstanceManager { get; }
|
||||
|
||||
public AgentServices(AgentInfo agentInfo, AgentFolders agentFolders, AgentServiceConfiguration serviceConfiguration, ControllerConnection controllerConnection, JavaRuntimeRepository javaRuntimeRepository) {
|
||||
public AgentServices(AgentInfo agentInfo, AgentDirectories agentDirectories, AgentServiceConfiguration serviceConfiguration, ControllerConnection controllerConnection, JavaRuntimeRepository javaRuntimeRepository) {
|
||||
this.ActorSystem = ActorSystemFactory.Create("Agent");
|
||||
|
||||
this.AgentState = new AgentState();
|
||||
this.BackupManager = new BackupManager(agentFolders, serviceConfiguration.MaxConcurrentCompressionTasks);
|
||||
this.BackupManager = new BackupManager(agentDirectories, serviceConfiguration.MaxConcurrentCompressionTasks);
|
||||
|
||||
this.JavaRuntimeRepository = javaRuntimeRepository;
|
||||
this.InstanceTicketManager = new InstanceTicketManager(agentInfo, controllerConnection);
|
||||
|
||||
var instanceManagerInit = new InstanceManagerActor.Init(controllerConnection, agentFolders, AgentState, JavaRuntimeRepository, InstanceTicketManager, BackupManager);
|
||||
var instanceManagerInit = new InstanceManagerActor.Init(controllerConnection, agentDirectories, AgentState, JavaRuntimeRepository, InstanceTicketManager, BackupManager);
|
||||
this.InstanceManager = ActorSystem.ActorOf(InstanceManagerActor.Factory(instanceManagerInit), "InstanceManager");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Formats.Tar;
|
||||
using System.Security.Cryptography;
|
||||
using Phantom.Agent.Services.Instances;
|
||||
using Phantom.Common.Data.Backups;
|
||||
using Phantom.Utils.IO;
|
||||
@@ -9,30 +10,27 @@ using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Services.Backups;
|
||||
|
||||
sealed class BackupArchiver {
|
||||
private readonly string destinationBasePath;
|
||||
private readonly string temporaryBasePath;
|
||||
private readonly ILogger logger;
|
||||
private readonly InstanceProperties instanceProperties;
|
||||
private readonly CancellationToken cancellationToken;
|
||||
|
||||
public BackupArchiver(string destinationBasePath, string temporaryBasePath, string loggerName, InstanceProperties instanceProperties, CancellationToken cancellationToken) {
|
||||
this.destinationBasePath = destinationBasePath;
|
||||
this.temporaryBasePath = temporaryBasePath;
|
||||
this.logger = PhantomLogger.Create<BackupArchiver>(loggerName);
|
||||
this.instanceProperties = instanceProperties;
|
||||
this.cancellationToken = cancellationToken;
|
||||
static class BackupArchiver {
|
||||
public static async Task<string?> Run(string loggerName, string destinationBasePath, string temporaryBasePath, InstanceProperties instanceProperties, BackupCreationResult.Builder resuiltBuilder, CancellationToken cancellationToken) {
|
||||
string guid = instanceProperties.InstanceGuid.ToString();
|
||||
string currentDateTime = DateTime.Now.ToString("yyyyMMdd-HHmmss");
|
||||
|
||||
string backupDirectoryPath = Path.Combine(destinationBasePath, guid);
|
||||
string backupFilePath = Path.Combine(backupDirectoryPath, currentDateTime + ".tar");
|
||||
string temporaryDirectoryPath = Path.Combine(temporaryBasePath, guid + "_" + currentDateTime);
|
||||
|
||||
return await new Runner(loggerName, backupDirectoryPath, backupFilePath, temporaryDirectoryPath, instanceProperties, resuiltBuilder, cancellationToken).Run();
|
||||
}
|
||||
|
||||
private bool IsFolderSkipped(ImmutableList<string> relativePath) {
|
||||
return relativePath is ["cache" or "crash-reports" or "debug" or "libraries" or "logs" or "mods" or "versions"];
|
||||
private static bool IsDirectorySkipped(RelativePath relativePath) {
|
||||
return relativePath.Components is ["cache" or "crash-reports" or "debug" or "libraries" or "logs" or "mods" or "versions"];
|
||||
}
|
||||
|
||||
[SuppressMessage("ReSharper", "ConvertIfStatementToReturnStatement")]
|
||||
private bool IsFileSkipped(ImmutableList<string> relativePath) {
|
||||
var name = relativePath[^1];
|
||||
private static bool IsFileSkipped(RelativePath relativePath) {
|
||||
var name = relativePath.Components[^1];
|
||||
|
||||
if (relativePath.Count == 2 && name == "session.lock") {
|
||||
if (relativePath.Components.Count == 2 && name == "session.lock") {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -44,137 +42,184 @@ sealed class BackupArchiver {
|
||||
return false;
|
||||
}
|
||||
|
||||
public async Task<string?> ArchiveWorld(BackupCreationResult.Builder resultBuilder) {
|
||||
string guid = instanceProperties.InstanceGuid.ToString();
|
||||
string currentDateTime = DateTime.Now.ToString("yyyyMMdd-HHmmss");
|
||||
string backupFolderPath = Path.Combine(destinationBasePath, guid);
|
||||
string backupFilePath = Path.Combine(backupFolderPath, currentDateTime + ".tar");
|
||||
private sealed class Runner(
|
||||
string loggerName,
|
||||
string backupDirectoryPath,
|
||||
string backupFilePath,
|
||||
string temporaryDirectoryPath,
|
||||
InstanceProperties instanceProperties,
|
||||
BackupCreationResult.Builder resultBuilder,
|
||||
CancellationToken cancellationToken
|
||||
) {
|
||||
private readonly ILogger logger = PhantomLogger.Create(nameof(BackupArchiver), loggerName);
|
||||
private readonly FileHashComparer fileHashComparer = new (cancellationToken);
|
||||
|
||||
if (File.Exists(backupFilePath)) {
|
||||
resultBuilder.Kind = BackupCreationResultKind.BackupFileAlreadyExists;
|
||||
logger.Warning("Skipping backup, file already exists: {File}", backupFilePath);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
Directories.Create(backupFolderPath, Chmod.URWX_GRX);
|
||||
} catch (Exception e) {
|
||||
resultBuilder.Kind = BackupCreationResultKind.CouldNotCreateBackupFolder;
|
||||
logger.Error(e, "Could not create backup folder: {Folder}", backupFolderPath);
|
||||
return null;
|
||||
}
|
||||
|
||||
string temporaryFolderPath = Path.Combine(temporaryBasePath, guid + "_" + currentDateTime);
|
||||
if (!await CopyWorldAndCreateTarArchive(temporaryFolderPath, backupFilePath, resultBuilder)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
logger.Debug("Created world backup: {FilePath}", backupFilePath);
|
||||
return backupFilePath;
|
||||
}
|
||||
|
||||
private async Task<bool> CopyWorldAndCreateTarArchive(string temporaryFolderPath, string backupFilePath, BackupCreationResult.Builder resultBuilder) {
|
||||
try {
|
||||
if (!await CopyWorldToTemporaryFolder(temporaryFolderPath)) {
|
||||
resultBuilder.Kind = BackupCreationResultKind.CouldNotCopyWorldToTemporaryFolder;
|
||||
return false;
|
||||
public async Task<string?> Run() {
|
||||
if (File.Exists(backupFilePath)) {
|
||||
resultBuilder.Kind = BackupCreationResultKind.BackupFileAlreadyExists;
|
||||
logger.Warning("Skipping backup, file already exists: {FilePath}", backupFilePath);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!await CreateTarArchive(temporaryFolderPath, backupFilePath)) {
|
||||
resultBuilder.Kind = BackupCreationResultKind.CouldNotCreateWorldArchive;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} finally {
|
||||
try {
|
||||
Directory.Delete(temporaryFolderPath, recursive: true);
|
||||
Directories.Create(backupDirectoryPath, Chmod.URWX_GRX);
|
||||
} catch (Exception e) {
|
||||
resultBuilder.Warnings |= BackupCreationWarnings.CouldNotDeleteTemporaryFolder;
|
||||
logger.Error(e, "Could not delete temporary world folder: {Folder}", temporaryFolderPath);
|
||||
resultBuilder.Kind = BackupCreationResultKind.CouldNotCreateBackupDirectory;
|
||||
logger.Error(e, "Could not create backup directory: {DirectoryPath}", backupDirectoryPath);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> CopyWorldToTemporaryFolder(string temporaryFolderPath) {
|
||||
try {
|
||||
await CopyDirectory(new DirectoryInfo(instanceProperties.InstanceFolder), temporaryFolderPath, ImmutableList<string>.Empty);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
logger.Error(e, "Could not copy world to temporary folder.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> CreateTarArchive(string sourceFolderPath, string backupFilePath) {
|
||||
try {
|
||||
await TarFile.CreateFromDirectoryAsync(sourceFolderPath, backupFilePath, includeBaseDirectory: false, cancellationToken);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
logger.Error(e, "Could not create archive.");
|
||||
DeleteBrokenArchiveFile(backupFilePath);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void DeleteBrokenArchiveFile(string filePath) {
|
||||
if (File.Exists(filePath)) {
|
||||
|
||||
try {
|
||||
File.Delete(filePath);
|
||||
} catch (Exception e) {
|
||||
logger.Error(e, "Could not delete broken archive: {File}", filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CopyDirectory(DirectoryInfo sourceFolder, string destinationFolderPath, ImmutableList<string> relativePath) {
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
bool needsToCreateFolder = true;
|
||||
|
||||
foreach (FileInfo file in sourceFolder.EnumerateFiles()) {
|
||||
var filePath = relativePath.Add(file.Name);
|
||||
if (IsFileSkipped(filePath)) {
|
||||
logger.Debug("Skipping file: {File}", string.Join(separator: '/', filePath));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (needsToCreateFolder) {
|
||||
needsToCreateFolder = false;
|
||||
Directories.Create(destinationFolderPath, Chmod.URWX);
|
||||
}
|
||||
|
||||
await CopyFileWithRetries(file, destinationFolderPath);
|
||||
}
|
||||
|
||||
foreach (DirectoryInfo directory in sourceFolder.EnumerateDirectories()) {
|
||||
var folderPath = relativePath.Add(directory.Name);
|
||||
if (IsFolderSkipped(folderPath)) {
|
||||
logger.Debug("Skipping folder: {Folder}", string.Join(separator: '/', folderPath));
|
||||
continue;
|
||||
}
|
||||
|
||||
await CopyDirectory(directory, Path.Join(destinationFolderPath, directory.Name), folderPath);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CopyFileWithRetries(FileInfo sourceFile, string destinationFolderPath) {
|
||||
var destinationFilePath = Path.Combine(destinationFolderPath, sourceFile.Name);
|
||||
|
||||
const int TotalAttempts = 10;
|
||||
for (int attempt = 1; attempt <= TotalAttempts; attempt++) {
|
||||
try {
|
||||
sourceFile.CopyTo(destinationFilePath);
|
||||
return;
|
||||
} catch (IOException) {
|
||||
if (attempt == TotalAttempts) {
|
||||
throw;
|
||||
if (!await CopyInstanceDirectoryIntoTemporaryDirectory()) {
|
||||
resultBuilder.Kind = BackupCreationResultKind.CouldNotCopyInstanceIntoTemporaryDirectory;
|
||||
return null;
|
||||
}
|
||||
else {
|
||||
logger.Warning("Failed copying file {File}, retrying...", sourceFile.FullName);
|
||||
await Task.Delay(millisecondsDelay: 200, cancellationToken);
|
||||
|
||||
if (!await CreateBackupArchiveFromTemporaryDirectory()) {
|
||||
resultBuilder.Kind = BackupCreationResultKind.CouldNotCreateBackupArchive;
|
||||
return null;
|
||||
}
|
||||
|
||||
logger.Information("Created backup: {FilePath}", backupFilePath);
|
||||
return backupFilePath;
|
||||
} finally {
|
||||
try {
|
||||
Directory.Delete(temporaryDirectoryPath, recursive: true);
|
||||
} catch (Exception e1) {
|
||||
resultBuilder.Warnings |= BackupCreationWarnings.CouldNotDeleteTemporaryDirectory;
|
||||
logger.Error(e1, "Could not delete temporary directory: {DirectoryPath}", temporaryDirectoryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> CopyInstanceDirectoryIntoTemporaryDirectory() {
|
||||
try {
|
||||
await CopyDirectory(new DirectoryInfo(instanceProperties.InstanceDirectoryPath), RelativePath.Empty, temporaryDirectoryPath);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
logger.Error(e, "Could not copy instance directory into temporary directory: {DirectoryPath}", temporaryDirectoryPath);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CopyDirectory(DirectoryInfo sourceDirectory, RelativePath sourceDirectoryRelativePath, string destinationDirectoryPath) {
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
bool needsToCreateDirectory = true;
|
||||
|
||||
foreach (FileInfo file in sourceDirectory.EnumerateFiles()) {
|
||||
var filePath = sourceDirectoryRelativePath.Child(file.Name);
|
||||
if (IsFileSkipped(filePath)) {
|
||||
logger.Verbose("Skipped file: {FilePath}", filePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (needsToCreateDirectory) {
|
||||
needsToCreateDirectory = false;
|
||||
Directories.Create(destinationDirectoryPath, Chmod.URWX);
|
||||
}
|
||||
|
||||
await CopyFileWithRetries(file, filePath, Path.Combine(destinationDirectoryPath, file.Name));
|
||||
logger.Verbose("Copied file: {FilePath}", filePath);
|
||||
}
|
||||
|
||||
foreach (DirectoryInfo directory in sourceDirectory.EnumerateDirectories()) {
|
||||
var directoryPath = sourceDirectoryRelativePath.Child(directory.Name);
|
||||
if (IsDirectorySkipped(directoryPath)) {
|
||||
logger.Verbose("Skipped directory: {DirectoryPath}", directoryPath);
|
||||
continue;
|
||||
}
|
||||
|
||||
await CopyDirectory(directory, directoryPath, Path.Join(destinationDirectoryPath, directory.Name));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CopyFileWithRetries(FileInfo sourceFile, RelativePath sourceFileRelativePath, string destinationFilePath) {
|
||||
const int TotalAttempts = 10;
|
||||
|
||||
for (int attempt = 1; attempt <= TotalAttempts; attempt++) {
|
||||
try {
|
||||
FileInfo destinationFile = sourceFile.CopyTo(destinationFilePath, overwrite: true);
|
||||
|
||||
if (await fileHashComparer.CheckHashEquals(sourceFile, destinationFile)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (attempt == TotalAttempts) {
|
||||
logger.Warning("File {FilePath} changed while copying, using last attempt", sourceFileRelativePath);
|
||||
resultBuilder.Warnings |= BackupCreationWarnings.SomeFilesChangedDuringBackup;
|
||||
}
|
||||
else {
|
||||
logger.Warning("File {FilePath} changed while copying, retrying...", sourceFileRelativePath);
|
||||
}
|
||||
} catch (IOException) {
|
||||
if (attempt == TotalAttempts) {
|
||||
throw;
|
||||
}
|
||||
else {
|
||||
logger.Warning("Failed copying file {FilePath}, retrying...", sourceFileRelativePath);
|
||||
}
|
||||
}
|
||||
|
||||
await Task.Delay(millisecondsDelay: 200, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> CreateBackupArchiveFromTemporaryDirectory() {
|
||||
try {
|
||||
await TarFile.CreateFromDirectoryAsync(temporaryDirectoryPath, backupFilePath, includeBaseDirectory: false, cancellationToken);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
logger.Error(e, "Could not create archive.");
|
||||
DeleteBrokenArchiveFile(backupFilePath);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void DeleteBrokenArchiveFile(string filePath) {
|
||||
if (File.Exists(filePath)) {
|
||||
try {
|
||||
File.Delete(filePath);
|
||||
} catch (Exception e) {
|
||||
logger.Error(e, "Could not delete broken archive: {FilePath}", filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private readonly record struct RelativePath(ImmutableList<string> Components) {
|
||||
public static RelativePath Empty => new (ImmutableList<string>.Empty);
|
||||
|
||||
public RelativePath Child(string component) {
|
||||
return new RelativePath(Components.Add(component));
|
||||
}
|
||||
|
||||
public override string ToString() {
|
||||
return string.Join(separator: '/', Components);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FileHashComparer(CancellationToken cancellationToken) {
|
||||
private static readonly FileStreamOptions FileStreamOptions = new () {
|
||||
Mode = FileMode.Open,
|
||||
Access = FileAccess.Read,
|
||||
Share = FileShare.ReadWrite,
|
||||
Options = FileOptions.Asynchronous | FileOptions.SequentialScan,
|
||||
BufferSize = 65536,
|
||||
};
|
||||
|
||||
private readonly Memory<byte> hash1 = new byte[SHA1.HashSizeInBytes];
|
||||
private readonly Memory<byte> hash2 = new byte[SHA1.HashSizeInBytes];
|
||||
|
||||
public async Task<bool> CheckHashEquals(FileInfo file1, FileInfo file2) {
|
||||
await ComputeHash(file1, hash1);
|
||||
await ComputeHash(file2, hash2);
|
||||
return hash1.Span.SequenceEqual(hash2.Span);
|
||||
}
|
||||
|
||||
private async Task ComputeHash(FileInfo file, Memory<byte> destination) {
|
||||
await using var fileStream = file.Open(FileStreamOptions);
|
||||
await SHA1.HashDataAsync(fileStream, destination, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,16 +5,10 @@ using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Services.Backups;
|
||||
|
||||
sealed class BackupManager : IDisposable {
|
||||
private readonly string destinationBasePath;
|
||||
private readonly string temporaryBasePath;
|
||||
private readonly SemaphoreSlim compressionSemaphore;
|
||||
|
||||
public BackupManager(AgentFolders agentFolders, int maxConcurrentCompressionTasks) {
|
||||
this.destinationBasePath = agentFolders.BackupsFolderPath;
|
||||
this.temporaryBasePath = Path.Combine(agentFolders.TemporaryFolderPath, "backups");
|
||||
this.compressionSemaphore = new SemaphoreSlim(maxConcurrentCompressionTasks, maxConcurrentCompressionTasks);
|
||||
}
|
||||
sealed class BackupManager(AgentDirectories agentDirectories, int maxConcurrentCompressionTasks) : IDisposable {
|
||||
private readonly string destinationBasePath = agentDirectories.BackupsDirectoryPath;
|
||||
private readonly string temporaryBasePath = Path.Combine(agentDirectories.TemporaryDirectoryPath, "backups");
|
||||
private readonly SemaphoreSlim compressionSemaphore = new (maxConcurrentCompressionTasks, maxConcurrentCompressionTasks);
|
||||
|
||||
public Task<BackupCreationResult> CreateBackup(string loggerName, InstanceProcess process, CancellationToken cancellationToken) {
|
||||
return new BackupCreator(this, loggerName, process, cancellationToken).CreateBackup();
|
||||
@@ -24,33 +18,17 @@ sealed class BackupManager : IDisposable {
|
||||
compressionSemaphore.Dispose();
|
||||
}
|
||||
|
||||
private sealed class BackupCreator {
|
||||
private readonly BackupManager manager;
|
||||
private readonly string loggerName;
|
||||
private readonly ILogger logger;
|
||||
private readonly InstanceProcess process;
|
||||
private readonly CancellationToken cancellationToken;
|
||||
|
||||
public BackupCreator(BackupManager manager, string loggerName, InstanceProcess process, CancellationToken cancellationToken) {
|
||||
this.manager = manager;
|
||||
this.loggerName = loggerName;
|
||||
this.logger = PhantomLogger.Create<BackupManager>(loggerName);
|
||||
this.process = process;
|
||||
this.cancellationToken = cancellationToken;
|
||||
}
|
||||
private sealed class BackupCreator(BackupManager manager, string loggerName, InstanceProcess process, CancellationToken cancellationToken) {
|
||||
private readonly ILogger logger = PhantomLogger.Create<BackupManager>(loggerName);
|
||||
|
||||
public async Task<BackupCreationResult> CreateBackup() {
|
||||
logger.Information("Backup started.");
|
||||
|
||||
var resultBuilder = new BackupCreationResult.Builder();
|
||||
string? backupFilePath;
|
||||
|
||||
using (var dispatcher = new BackupServerCommandDispatcher(logger, process, cancellationToken)) {
|
||||
backupFilePath = await CreateWorldArchive(dispatcher, resultBuilder);
|
||||
}
|
||||
string? backupFilePath = await CreateBackupArchive(resultBuilder);
|
||||
|
||||
if (backupFilePath != null) {
|
||||
await CompressWorldArchive(backupFilePath, resultBuilder);
|
||||
await CompressBackupArchive(backupFilePath, resultBuilder);
|
||||
}
|
||||
|
||||
var result = resultBuilder.Build();
|
||||
@@ -58,11 +36,9 @@ sealed class BackupManager : IDisposable {
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task<string?> CreateWorldArchive(BackupServerCommandDispatcher dispatcher, BackupCreationResult.Builder resultBuilder) {
|
||||
private async Task<string?> CreateBackupArchive(BackupCreationResult.Builder resultBuilder) {
|
||||
try {
|
||||
await dispatcher.DisableAutomaticSaving();
|
||||
await dispatcher.SaveAllChunks();
|
||||
return await new BackupArchiver(manager.destinationBasePath, manager.temporaryBasePath, loggerName, process.InstanceProperties, cancellationToken).ArchiveWorld(resultBuilder);
|
||||
return await BackupArchiver.Run(loggerName, manager.destinationBasePath, manager.temporaryBasePath, process.InstanceProperties, resultBuilder, cancellationToken);
|
||||
} catch (OperationCanceledException) {
|
||||
resultBuilder.Kind = BackupCreationResultKind.BackupCancelled;
|
||||
logger.Warning("Backup creation was cancelled.");
|
||||
@@ -75,22 +51,10 @@ sealed class BackupManager : IDisposable {
|
||||
resultBuilder.Kind = BackupCreationResultKind.UnknownError;
|
||||
logger.Error(e, "Caught exception while creating an instance backup.");
|
||||
return null;
|
||||
} finally {
|
||||
try {
|
||||
await dispatcher.EnableAutomaticSaving();
|
||||
} catch (OperationCanceledException) {
|
||||
// Ignore.
|
||||
} catch (TimeoutException) {
|
||||
resultBuilder.Warnings |= BackupCreationWarnings.CouldNotRestoreAutomaticSaving;
|
||||
logger.Warning("Timed out waiting for automatic saving to be re-enabled.");
|
||||
} catch (Exception e) {
|
||||
resultBuilder.Warnings |= BackupCreationWarnings.CouldNotRestoreAutomaticSaving;
|
||||
logger.Error(e, "Caught exception while enabling automatic saving after creating an instance backup.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CompressWorldArchive(string filePath, BackupCreationResult.Builder resultBuilder) {
|
||||
private async Task CompressBackupArchive(string filePath, BackupCreationResult.Builder resultBuilder) {
|
||||
if (!await manager.compressionSemaphore.WaitAsync(TimeSpan.FromSeconds(1), cancellationToken)) {
|
||||
logger.Information("Too many compression tasks running, waiting for one of them to complete...");
|
||||
await manager.compressionSemaphore.WaitAsync(cancellationToken);
|
||||
@@ -100,7 +64,7 @@ sealed class BackupManager : IDisposable {
|
||||
try {
|
||||
var compressedFilePath = await BackupCompressor.Compress(filePath, cancellationToken);
|
||||
if (compressedFilePath == null) {
|
||||
resultBuilder.Warnings |= BackupCreationWarnings.CouldNotCompressWorldArchive;
|
||||
resultBuilder.Warnings |= BackupCreationWarnings.CouldNotCompressBackupArchive;
|
||||
}
|
||||
} finally {
|
||||
manager.compressionSemaphore.Release();
|
||||
@@ -124,16 +88,16 @@ sealed class BackupManager : IDisposable {
|
||||
|
||||
private static string DescribeResult(BackupCreationResultKind kind) {
|
||||
return kind switch {
|
||||
BackupCreationResultKind.Success => "Backup created successfully.",
|
||||
BackupCreationResultKind.InstanceNotRunning => "Instance is not running.",
|
||||
BackupCreationResultKind.BackupCancelled => "Backup cancelled.",
|
||||
BackupCreationResultKind.BackupTimedOut => "Backup timed out.",
|
||||
BackupCreationResultKind.BackupAlreadyRunning => "A backup is already being created.",
|
||||
BackupCreationResultKind.BackupFileAlreadyExists => "Backup with the same name already exists.",
|
||||
BackupCreationResultKind.CouldNotCreateBackupFolder => "Could not create backup folder.",
|
||||
BackupCreationResultKind.CouldNotCopyWorldToTemporaryFolder => "Could not copy world to temporary folder.",
|
||||
BackupCreationResultKind.CouldNotCreateWorldArchive => "Could not create world archive.",
|
||||
_ => "Unknown error.",
|
||||
BackupCreationResultKind.Success => "Backup created successfully.",
|
||||
BackupCreationResultKind.InstanceNotRunning => "Instance is not running.",
|
||||
BackupCreationResultKind.BackupCancelled => "Backup cancelled.",
|
||||
BackupCreationResultKind.BackupTimedOut => "Backup timed out.",
|
||||
BackupCreationResultKind.BackupAlreadyRunning => "A backup is already being created.",
|
||||
BackupCreationResultKind.BackupFileAlreadyExists => "Backup with the same name already exists.",
|
||||
BackupCreationResultKind.CouldNotCreateBackupDirectory => "Could not create backup directory.",
|
||||
BackupCreationResultKind.CouldNotCopyInstanceIntoTemporaryDirectory => "Could not copy instance into temporary directory.",
|
||||
BackupCreationResultKind.CouldNotCreateBackupArchive => "Could not create backup archive.",
|
||||
_ => "Unknown error.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Text.RegularExpressions;
|
||||
using Phantom.Agent.Services.Games;
|
||||
using Phantom.Agent.Services.Instances.State;
|
||||
using Phantom.Utils.Tasks;
|
||||
using Serilog;
|
||||
|
||||
namespace Phantom.Agent.Services.Backups;
|
||||
|
||||
sealed partial class BackupServerCommandDispatcher : IDisposable {
|
||||
[GeneratedRegex(@"^(?:(?:\[.*?\] \[Server thread/INFO\].*?:)|(?:[\d-]+? [\d:]+? \[INFO\])) (.*?)$", RegexOptions.NonBacktracking)]
|
||||
private static partial Regex ServerThreadInfoRegex();
|
||||
|
||||
private static readonly ImmutableHashSet<string> AutomaticSavingDisabledMessages = ImmutableHashSet.Create(
|
||||
"Automatic saving is now disabled",
|
||||
"Turned off world auto-saving",
|
||||
"CONSOLE: Disabling level saving.."
|
||||
);
|
||||
|
||||
private static readonly ImmutableHashSet<string> SavedTheGameMessages = ImmutableHashSet.Create(
|
||||
"Saved the game",
|
||||
"Saved the world",
|
||||
"CONSOLE: Save complete."
|
||||
);
|
||||
|
||||
private static readonly ImmutableHashSet<string> AutomaticSavingEnabledMessages = ImmutableHashSet.Create(
|
||||
"Automatic saving is now enabled",
|
||||
"Turned on world auto-saving",
|
||||
"CONSOLE: Enabling level saving.."
|
||||
);
|
||||
|
||||
private readonly ILogger logger;
|
||||
private readonly InstanceProcess process;
|
||||
private readonly CancellationToken cancellationToken;
|
||||
|
||||
private readonly TaskCompletionSource automaticSavingDisabled = AsyncTasks.CreateCompletionSource();
|
||||
private readonly TaskCompletionSource savedTheGame = AsyncTasks.CreateCompletionSource();
|
||||
private readonly TaskCompletionSource automaticSavingEnabled = AsyncTasks.CreateCompletionSource();
|
||||
|
||||
public BackupServerCommandDispatcher(ILogger logger, InstanceProcess process, CancellationToken cancellationToken) {
|
||||
this.logger = logger;
|
||||
this.process = process;
|
||||
this.cancellationToken = cancellationToken;
|
||||
|
||||
this.process.AddOutputListener(OnOutput, maxLinesToReadFromHistory: 0);
|
||||
}
|
||||
|
||||
void IDisposable.Dispose() {
|
||||
process.RemoveOutputListener(OnOutput);
|
||||
}
|
||||
|
||||
public async Task DisableAutomaticSaving() {
|
||||
await process.SendCommand(MinecraftCommand.SaveOff, cancellationToken);
|
||||
await automaticSavingDisabled.Task.WaitAsync(TimeSpan.FromSeconds(30), cancellationToken);
|
||||
}
|
||||
|
||||
public async Task SaveAllChunks() {
|
||||
await process.SendCommand(MinecraftCommand.SaveAll(flush: true), cancellationToken);
|
||||
await savedTheGame.Task.WaitAsync(TimeSpan.FromMinutes(1), cancellationToken);
|
||||
}
|
||||
|
||||
public async Task EnableAutomaticSaving() {
|
||||
await process.SendCommand(MinecraftCommand.SaveOn, cancellationToken);
|
||||
await automaticSavingEnabled.Task.WaitAsync(TimeSpan.FromMinutes(1), cancellationToken);
|
||||
}
|
||||
|
||||
private void OnOutput(object? sender, string? line) {
|
||||
if (line == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
var match = ServerThreadInfoRegex().Match(line);
|
||||
if (!match.Success) {
|
||||
return;
|
||||
}
|
||||
|
||||
string info = match.Groups[1].Value;
|
||||
|
||||
if (!automaticSavingDisabled.Task.IsCompleted) {
|
||||
if (AutomaticSavingDisabledMessages.Contains(info)) {
|
||||
logger.Debug("Detected that automatic saving is disabled.");
|
||||
automaticSavingDisabled.SetResult();
|
||||
}
|
||||
}
|
||||
else if (!savedTheGame.Task.IsCompleted) {
|
||||
if (SavedTheGameMessages.Contains(info)) {
|
||||
logger.Debug("Detected that the game is saved.");
|
||||
savedTheGame.SetResult();
|
||||
}
|
||||
}
|
||||
else if (!automaticSavingEnabled.Task.IsCompleted) {
|
||||
if (AutomaticSavingEnabledMessages.Contains(info)) {
|
||||
logger.Debug("Detected that automatic saving is enabled.");
|
||||
automaticSavingEnabled.SetResult();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ sealed class FileDownloadManager {
|
||||
try {
|
||||
Directories.Create(parentPath.FullName, Chmod.URWX_GRX);
|
||||
} catch (Exception e) {
|
||||
Logger.Error(e, "Unable to create folder: {FolderName}", parentPath.FullName);
|
||||
Logger.Error(e, "Unable to create directory: {DirectoryName}", parentPath.FullName);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ 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;
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
namespace Phantom.Agent.Services.Games;
|
||||
|
||||
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";
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,10 @@ 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;
|
||||
using Phantom.Common.Data.Minecraft;
|
||||
using Phantom.Common.Data.Replies;
|
||||
using Phantom.Common.Messages.Agent.ToController;
|
||||
using Phantom.Utils.Actor;
|
||||
@@ -83,9 +84,9 @@ 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(MinecraftStopStrategy StopStrategy) : ICommand;
|
||||
public sealed record StopInstanceCommand(InstanceStopRecipe StopRecipe) : ICommand;
|
||||
|
||||
public sealed record SendCommandToInstanceCommand(string Command) : ICommand, ICanReply<SendCommandToInstanceResult>;
|
||||
|
||||
@@ -93,7 +94,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();
|
||||
@@ -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);
|
||||
}
|
||||
@@ -125,7 +130,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 +172,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(
|
||||
|
||||
@@ -5,9 +5,10 @@ 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;
|
||||
using Phantom.Common.Data.Minecraft;
|
||||
using Phantom.Common.Data.Replies;
|
||||
using Phantom.Utils.Actor;
|
||||
using Phantom.Utils.IO;
|
||||
@@ -19,14 +20,14 @@ namespace Phantom.Agent.Services.Instances;
|
||||
sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand> {
|
||||
private static readonly ILogger Logger = PhantomLogger.Create<InstanceManagerActor>();
|
||||
|
||||
public readonly record struct Init(ControllerConnection ControllerConnection, AgentFolders AgentFolders, AgentState AgentState, JavaRuntimeRepository JavaRuntimeRepository, InstanceTicketManager InstanceTicketManager, BackupManager BackupManager);
|
||||
public readonly record struct Init(ControllerConnection ControllerConnection, AgentDirectories AgentDirectories, AgentState AgentState, JavaRuntimeRepository JavaRuntimeRepository, InstanceTicketManager InstanceTicketManager, BackupManager BackupManager);
|
||||
|
||||
public static Props<ICommand> Factory(Init init) {
|
||||
return Props<ICommand>.Create(() => new InstanceManagerActor(init), new ActorConfiguration { SupervisorStrategy = SupervisorStrategies.Resume });
|
||||
}
|
||||
|
||||
private readonly AgentState agentState;
|
||||
private readonly AgentFolders agentFolders;
|
||||
private readonly AgentDirectories agentDirectories;
|
||||
|
||||
private readonly InstanceServices instanceServices;
|
||||
private readonly InstanceTicketManager instanceTicketManager;
|
||||
@@ -39,7 +40,7 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
|
||||
private InstanceManagerActor(Init init) {
|
||||
this.agentState = init.AgentState;
|
||||
this.agentFolders = init.AgentFolders;
|
||||
this.agentDirectories = init.AgentDirectories;
|
||||
|
||||
this.instanceServices = new InstanceServices(init.ControllerConnection, init.BackupManager, new FileDownloadManager(), init.JavaRuntimeRepository);
|
||||
this.instanceTicketManager = init.InstanceTicketManager;
|
||||
@@ -52,15 +53,22 @@ 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,
|
||||
InstanceBackupConfiguration? BackupConfiguration
|
||||
);
|
||||
|
||||
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, InstanceBackupConfiguration? BackupConfiguration, 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>>;
|
||||
|
||||
@@ -70,11 +78,15 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
var instanceGuid = command.InstanceGuid;
|
||||
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);
|
||||
@@ -85,10 +97,12 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
}
|
||||
else {
|
||||
var instanceLoggerName = PhantomLogger.ShortenGuid(instanceGuid) + "/" + Interlocked.Increment(ref instanceLoggerSequenceId);
|
||||
var instanceFolder = Path.Combine(agentFolders.InstancesFolderPath, instanceGuid.ToString());
|
||||
var instanceProperties = new InstanceProperties(instanceGuid, instanceFolder);
|
||||
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);
|
||||
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);
|
||||
|
||||
@@ -96,10 +110,10 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
}
|
||||
|
||||
try {
|
||||
Directories.Create(instance.Properties.InstanceFolder, Chmod.URWX_GRX);
|
||||
Directories.Create(instance.Properties.InstanceDirectoryPath, Chmod.URWX_GRX);
|
||||
} catch (Exception e) {
|
||||
Logger.Error(e, "Could not create instance folder: {Path}", instance.Properties.InstanceFolder);
|
||||
return ConfigureInstanceResult.CouldNotCreateInstanceFolder;
|
||||
Logger.Error(e, "Could not create instance directory: {Path}", instance.Properties.InstanceDirectoryPath);
|
||||
return ConfigureInstanceResult.CouldNotCreateInstanceDirectory;
|
||||
}
|
||||
|
||||
if (command.LaunchNow) {
|
||||
@@ -134,11 +148,11 @@ sealed class InstanceManagerActor : ReceiveActor<InstanceManagerActor.ICommand>
|
||||
}
|
||||
}
|
||||
|
||||
var pathResolver = new InstancePathResolver(agentFolders, instanceServices.JavaRuntimeRepository, instance.Properties);
|
||||
var pathResolver = new InstancePathResolver(agentDirectories, instanceServices.JavaRuntimeRepository, instance.Properties);
|
||||
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;
|
||||
}
|
||||
@@ -159,7 +173,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;
|
||||
}
|
||||
|
||||
@@ -181,7 +195,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();
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
|
||||
sealed record InstanceProperties(
|
||||
Guid InstanceGuid,
|
||||
string InstanceFolder
|
||||
string InstanceDirectoryPath
|
||||
);
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -18,6 +18,8 @@ sealed class InstanceLauncher(
|
||||
InstanceProperties instanceProperties,
|
||||
InstanceLaunchRecipe launchRecipe
|
||||
) {
|
||||
public IInstanceValueResolver ValueResolver => valueResolver;
|
||||
|
||||
public async Task<InstanceLaunchResult> Launch(ILogger logger, Action<IInstanceStatus?> reportStatus, CancellationToken cancellationToken) {
|
||||
string? executablePath = launchRecipe.Executable.Resolve(pathResolver);
|
||||
if (executablePath == null) {
|
||||
@@ -26,24 +28,13 @@ sealed class InstanceLauncher(
|
||||
}
|
||||
|
||||
var stepExecutor = new StepExecutor(logger, downloadManager, pathResolver, reportStatus, cancellationToken);
|
||||
var steps = launchRecipe.Preparation;
|
||||
|
||||
for (int stepIndex = 0; stepIndex < steps.Length; stepIndex++) {
|
||||
var step = steps[stepIndex];
|
||||
try {
|
||||
if (await step.Run(stepExecutor)) {
|
||||
continue;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.Error(e, "Failed preparation step {StepIndex} out of {StepCount}: {StepName}", stepIndex, steps.Length, step.GetType().Name);
|
||||
}
|
||||
|
||||
if (!await RunPreparationSteps(logger, stepExecutor)) {
|
||||
return new InstanceLaunchResult.CouldNotPrepareServerInstance();
|
||||
}
|
||||
|
||||
var processConfigurator = new ProcessConfigurator {
|
||||
FileName = executablePath,
|
||||
WorkingDirectory = instanceProperties.InstanceFolder,
|
||||
WorkingDirectory = instanceProperties.InstanceDirectoryPath,
|
||||
RedirectInput = true,
|
||||
UseShellExecute = false,
|
||||
};
|
||||
@@ -80,6 +71,27 @@ sealed class InstanceLauncher(
|
||||
return new InstanceLaunchResult.Success(instanceProcess);
|
||||
}
|
||||
|
||||
private async Task<bool> RunPreparationSteps(ILogger logger, StepExecutor stepExecutor) {
|
||||
var steps = launchRecipe.Preparation;
|
||||
|
||||
for (int stepIndex = 0; stepIndex < steps.Length; stepIndex++) {
|
||||
var step = steps[stepIndex];
|
||||
try {
|
||||
if (await step.Run(stepExecutor)) {
|
||||
continue;
|
||||
}
|
||||
} catch (OperationCanceledException) {
|
||||
throw;
|
||||
} catch (Exception e) {
|
||||
logger.Error(e, "Failed preparation step {StepIndex} out of {StepCount}: {StepName}", stepIndex, steps.Length, step.GetType().Name);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private sealed class StepExecutor(ILogger logger, FileDownloadManager downloadManager, IInstancePathResolver pathResolver, Action<IInstanceStatus?> reportStatus, CancellationToken cancellationToken) : IInstanceLaunchStepExecutor<bool> {
|
||||
public async Task<bool> DownloadFile(FileDownloadInfo downloadInfo, IInstancePath path) {
|
||||
string? filePath = path.Resolve(pathResolver);
|
||||
@@ -99,6 +111,8 @@ sealed class InstanceLauncher(
|
||||
}
|
||||
}
|
||||
|
||||
reportStatus(InstanceStatus.Downloading(null));
|
||||
|
||||
if (await downloadManager.DownloadAndGetPath(downloadInfo, filePath, OnDownloadProgress, cancellationToken) == null) {
|
||||
logger.Error("Could not download file: {Url}", downloadInfo.Url);
|
||||
return false;
|
||||
|
||||
@@ -5,13 +5,13 @@ using Phantom.Common.Data.Agent.Instance;
|
||||
|
||||
namespace Phantom.Agent.Services.Instances.Launch;
|
||||
|
||||
sealed class InstancePathResolver(AgentFolders agentFolders, JavaRuntimeRepository javaRuntimeRepository, InstanceProperties instanceProperties) : IInstancePathResolver {
|
||||
sealed class InstancePathResolver(AgentDirectories agentDirectories, JavaRuntimeRepository javaRuntimeRepository, InstanceProperties instanceProperties) : IInstancePathResolver {
|
||||
public string? Global(ImmutableArray<string> segments) {
|
||||
return ValidateAndCombinePath(agentFolders.ServerExecutableFolderPath, segments);
|
||||
return ValidateAndCombinePath(agentDirectories.ServerExecutableDirectoryPath, segments);
|
||||
}
|
||||
|
||||
public string? Local(ImmutableArray<string> segments) {
|
||||
return ValidateAndCombinePath(instanceProperties.InstanceFolder, segments);
|
||||
return ValidateAndCombinePath(instanceProperties.InstanceDirectoryPath, segments);
|
||||
}
|
||||
|
||||
public string? Runtime(Guid guid) {
|
||||
|
||||
@@ -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("Could not check online player count due to protocol 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();
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,15 @@ 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,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;
|
||||
@@ -11,32 +12,38 @@ 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;
|
||||
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() {
|
||||
@@ -74,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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,8 +103,7 @@ sealed class InstanceRunningState : IDisposable {
|
||||
}
|
||||
|
||||
public void OnStopInitiated() {
|
||||
backupScheduler.Stop();
|
||||
playerCountTracker.Stop();
|
||||
backupScheduler?.Stop();
|
||||
}
|
||||
|
||||
private bool TryDispose() {
|
||||
|
||||
@@ -1,37 +1,50 @@
|
||||
using System.Diagnostics;
|
||||
using Phantom.Agent.Services.Games;
|
||||
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);
|
||||
}
|
||||
@@ -39,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) {
|
||||
|
||||
@@ -21,19 +21,19 @@ public sealed class JavaRuntimeDiscovery {
|
||||
return null;
|
||||
}
|
||||
|
||||
public static async Task<JavaRuntimeRepository> Scan(string folderPath, CancellationToken cancellationToken) {
|
||||
var runtimes = await new JavaRuntimeDiscovery().ScanInternal(folderPath, cancellationToken).ToImmutableArrayAsync(cancellationToken);
|
||||
public static async Task<JavaRuntimeRepository> Scan(string directoryPath, CancellationToken cancellationToken) {
|
||||
var runtimes = await new JavaRuntimeDiscovery().ScanInternal(directoryPath, cancellationToken).ToImmutableArrayAsync(cancellationToken);
|
||||
return new JavaRuntimeRepository(runtimes);
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, int> duplicateDisplayNames = new ();
|
||||
|
||||
private async IAsyncEnumerable<JavaRuntimeExecutable> ScanInternal(string folderPath, [EnumeratorCancellation] CancellationToken cancellationToken) {
|
||||
Logger.Information("Starting Java runtime scan in: {FolderPath}", folderPath);
|
||||
private async IAsyncEnumerable<JavaRuntimeExecutable> ScanInternal(string directoryPath, [EnumeratorCancellation] CancellationToken cancellationToken) {
|
||||
Logger.Information("Starting Java runtime scan in: {DirectoryPath}", directoryPath);
|
||||
|
||||
string javaExecutableName = OperatingSystem.IsWindows() ? "java.exe" : "java";
|
||||
|
||||
foreach (var binFolderPath in Directory.EnumerateDirectories(Paths.ExpandTilde(folderPath), "bin", new EnumerationOptions {
|
||||
foreach (var binDirectoryPath in Directory.EnumerateDirectories(Paths.ExpandTilde(directoryPath), "bin", new EnumerationOptions {
|
||||
MatchType = MatchType.Simple,
|
||||
RecurseSubdirectories = true,
|
||||
ReturnSpecialDirectories = false,
|
||||
@@ -42,7 +42,7 @@ public sealed class JavaRuntimeDiscovery {
|
||||
}).Order()) {
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var javaExecutablePath = Paths.NormalizeSlashes(Path.Combine(binFolderPath, javaExecutableName));
|
||||
var javaExecutablePath = Paths.NormalizeSlashes(Path.Combine(binDirectoryPath, javaExecutableName));
|
||||
|
||||
FileAttributes javaExecutableAttributes;
|
||||
try {
|
||||
|
||||
@@ -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.Value, message.LaunchNow, message.StopRecipe, message.BackupConfiguration.Value, 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) {
|
||||
|
||||
@@ -37,13 +37,13 @@ try {
|
||||
return 1;
|
||||
}
|
||||
|
||||
var folders = new AgentFolders("./data", "./temp", javaSearchPath);
|
||||
if (!folders.TryCreate()) {
|
||||
var agentDirectories = new AgentDirectories("./data", "./temp", javaSearchPath);
|
||||
if (!agentDirectories.TryCreate()) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
var agentInfo = new AgentInfo(ProtocolVersion, fullVersion, maxInstances, maxMemory, allowedServerPorts, allowedRconPorts);
|
||||
var javaRuntimeRepository = await JavaRuntimeDiscovery.Scan(folders.JavaSearchFolderPath, shutdownCancellationToken);
|
||||
var javaRuntimeRepository = await JavaRuntimeDiscovery.Scan(agentDirectories.JavaSearchDirectoryPath, shutdownCancellationToken);
|
||||
|
||||
var agentRegistrationHandler = new AgentRegistrationHandler();
|
||||
var controllerHandshake = new ControllerHandshake(new AgentRegistration(agentInfo, javaRuntimeRepository.All), agentRegistrationHandler);
|
||||
@@ -69,7 +69,7 @@ try {
|
||||
try {
|
||||
PhantomLogger.Root.InformationHeading("Launching Phantom Panel agent...");
|
||||
|
||||
var agentServices = new AgentServices(agentInfo, folders, new AgentServiceConfiguration(maxConcurrentBackupCompressionTasks), new ControllerConnection(rpcClient.MessageSender), javaRuntimeRepository);
|
||||
var agentServices = new AgentServices(agentInfo, agentDirectories, new AgentServiceConfiguration(maxConcurrentBackupCompressionTasks), new ControllerConnection(rpcClient.MessageSender), javaRuntimeRepository);
|
||||
|
||||
var rpcMessageHandlerInit = new ControllerMessageHandlerActor.Init(agentServices);
|
||||
var rpcMessageHandlerActor = agentServices.ActorSystem.ActorOf(ControllerMessageHandlerActor.Factory(rpcMessageHandlerInit), "ControllerMessageHandler");
|
||||
|
||||
@@ -36,7 +36,7 @@ sealed record Variables(
|
||||
}
|
||||
|
||||
private static string GetDefaultJavaSearchPath() {
|
||||
return JavaRuntimeDiscovery.GetSystemSearchPath() ?? throw new Exception("Could not automatically determine the path to Java installations on this system. Please set the JAVA_SEARCH_PATH environment variable to the folder containing Java installations.");
|
||||
return JavaRuntimeDiscovery.GetSystemSearchPath() ?? throw new Exception("Could not automatically determine the path to Java installations on this system. Please set the JAVA_SEARCH_PATH environment variable to the directory containing Java installations.");
|
||||
}
|
||||
|
||||
public static Variables LoadOrStop() {
|
||||
|
||||
@@ -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
|
||||
);
|
||||
@@ -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,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,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) {
|
||||
@@ -8,9 +8,9 @@ public enum BackupCreationResultKind : byte {
|
||||
BackupCancelled = 4,
|
||||
BackupAlreadyRunning = 5,
|
||||
BackupFileAlreadyExists = 6,
|
||||
CouldNotCreateBackupFolder = 7,
|
||||
CouldNotCopyWorldToTemporaryFolder = 8,
|
||||
CouldNotCreateWorldArchive = 9,
|
||||
CouldNotCreateBackupDirectory = 7,
|
||||
CouldNotCopyInstanceIntoTemporaryDirectory = 8,
|
||||
CouldNotCreateBackupArchive = 9,
|
||||
}
|
||||
|
||||
public static class BackupCreationResultSummaryExtensions {
|
||||
|
||||
@@ -4,18 +4,20 @@ namespace Phantom.Common.Data.Backups;
|
||||
|
||||
[Flags]
|
||||
public enum BackupCreationWarnings : byte {
|
||||
None = 0,
|
||||
CouldNotDeleteTemporaryFolder = 1 << 0,
|
||||
CouldNotCompressWorldArchive = 1 << 1,
|
||||
CouldNotRestoreAutomaticSaving = 1 << 2,
|
||||
None = 0,
|
||||
CouldNotDeleteTemporaryDirectory = 1 << 0,
|
||||
CouldNotCompressBackupArchive = 1 << 1,
|
||||
SomeFilesChangedDuringBackup = 1 << 2,
|
||||
}
|
||||
|
||||
public static class BackupCreationWarningsExtensions {
|
||||
public static int Count(this BackupCreationWarnings warnings) {
|
||||
return BitOperations.PopCount((byte) warnings);
|
||||
}
|
||||
|
||||
public static IEnumerable<BackupCreationWarnings> ListFlags(this BackupCreationWarnings warnings) {
|
||||
return Enum.GetValues<BackupCreationWarnings>().Where(warning => warning != BackupCreationWarnings.None && warnings.HasFlag(warning));
|
||||
extension(BackupCreationWarnings warnings) {
|
||||
public int Count() {
|
||||
return BitOperations.PopCount((byte) warnings);
|
||||
}
|
||||
|
||||
public IEnumerable<BackupCreationWarnings> ListFlags() {
|
||||
return Enum.GetValues<BackupCreationWarnings>().Where(warning => warning != BackupCreationWarnings.None && warnings.HasFlag(warning));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
using MemoryPack;
|
||||
|
||||
namespace Phantom.Common.Data.Minecraft;
|
||||
|
||||
[MemoryPackable(GenerateType.VersionTolerant)]
|
||||
public sealed partial record MinecraftStopStrategy(
|
||||
[property: MemoryPackOrder(0)] ushort Seconds
|
||||
) {
|
||||
public static MinecraftStopStrategy Instant => new (0);
|
||||
}
|
||||
@@ -1,16 +1,19 @@
|
||||
namespace Phantom.Common.Data.Replies;
|
||||
|
||||
public enum ConfigureInstanceResult : byte {
|
||||
Success = 0,
|
||||
CouldNotCreateInstanceFolder = 1,
|
||||
Success = 0,
|
||||
CouldNotCreateInstanceDirectory = 1,
|
||||
MinecraftVersionNotFound = 2,
|
||||
UnknownError = 255,
|
||||
}
|
||||
|
||||
public static class ConfigureInstanceResultExtensions {
|
||||
public static string ToSentence(this ConfigureInstanceResult reason) {
|
||||
return reason switch {
|
||||
ConfigureInstanceResult.Success => "Success.",
|
||||
ConfigureInstanceResult.CouldNotCreateInstanceFolder => "Could not create instance folder.",
|
||||
_ => "Unknown error.",
|
||||
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,7 +1,9 @@
|
||||
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;
|
||||
using Phantom.Utils.Actor;
|
||||
|
||||
@@ -11,6 +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(3)] bool LaunchNow = false
|
||||
[property: MemoryPackOrder(2)] Optional<InstanceLaunchRecipe> LaunchRecipe,
|
||||
[property: MemoryPackOrder(3)] bool LaunchNow,
|
||||
[property: MemoryPackOrder(4)] InstanceStopRecipe StopRecipe,
|
||||
[property: MemoryPackOrder(5)] Optional<InstanceBackupConfiguration> BackupConfiguration
|
||||
) : 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);
|
||||
@@ -68,12 +64,14 @@ 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()),
|
||||
("rcon.port", configuration.RconPort.ToString()),
|
||||
("enable-rcon", "true"),
|
||||
("sync-chunk-writes", "false"),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,12 @@
|
||||
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.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 +39,7 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
AgentRuntimeInfo AgentRuntimeInfo,
|
||||
AgentConnectionKeys AgentConnectionKeys,
|
||||
ControllerState ControllerState,
|
||||
MinecraftLaunchRecipes LaunchRecipes,
|
||||
MinecraftInstanceRecipes MinecraftInstanceRecipes,
|
||||
IDbContextProvider DbProvider,
|
||||
CancellationToken CancellationToken
|
||||
);
|
||||
@@ -54,7 +52,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;
|
||||
|
||||
@@ -90,12 +88,11 @@ 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;
|
||||
this.controllerState = init.ControllerState;
|
||||
this.launchRecipes = init.LaunchRecipes;
|
||||
this.minecraftInstanceRecipes = init.MinecraftInstanceRecipes;
|
||||
this.dbProvider = init.DbProvider;
|
||||
this.cancellationToken = init.CancellationToken;
|
||||
|
||||
@@ -143,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);
|
||||
}
|
||||
@@ -187,15 +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 launchRecipes.Create(instanceConfiguration, cancellationToken);
|
||||
var configurationMessage = new ConfigureInstanceMessage(instanceGuid, instanceConfiguration.AsInfo, launchRecipe.OrElse(null), launchAutomatically);
|
||||
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;
|
||||
@@ -226,7 +210,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,38 +325,25 @@ sealed class AgentActor : ReceiveActor<AgentActor.ICommand>, IWithTimers {
|
||||
return Task.FromResult<Result<CreateOrUpdateInstanceResult, InstanceActionFailure>>(CreateOrUpdateInstanceResult.InstanceMemoryMustNotBeZero);
|
||||
}
|
||||
|
||||
return launchRecipes.Create(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 configureInstanceCommand = new InstanceActor.ConfigureInstanceCommand(command.LoggedInUserGuid, instanceGuid, instanceConfiguration, launchRecipe.Value, 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";
|
||||
@@ -385,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
|
||||
@@ -403,7 +377,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) {
|
||||
@@ -411,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 {
|
||||
|
||||
@@ -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,19 +1,28 @@
|
||||
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;
|
||||
using Phantom.Common.Data.Minecraft;
|
||||
using Phantom.Common.Data.Replies;
|
||||
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,11 +83,13 @@ 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 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>>;
|
||||
|
||||
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>>;
|
||||
|
||||
@@ -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);
|
||||
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);
|
||||
@@ -127,12 +168,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)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -19,8 +19,8 @@ abstract class AuthTokenFile {
|
||||
this.certificate = certificate;
|
||||
}
|
||||
|
||||
public async Task<ConnectionKey?> CreateOrLoad(string folderPath) {
|
||||
string filePath = Path.Combine(folderPath, fileName);
|
||||
public async Task<ConnectionKey?> CreateOrLoad(string directoryPath) {
|
||||
string filePath = Path.Combine(directoryPath, fileName);
|
||||
|
||||
if (File.Exists(filePath)) {
|
||||
try {
|
||||
|
||||
@@ -11,8 +11,8 @@ sealed class CertificateFile(string name) {
|
||||
|
||||
private readonly string fileName = name + ".pfx";
|
||||
|
||||
public async Task<RpcServerCertificate?> CreateOrLoad(string folderPath) {
|
||||
string filePath = Path.Combine(folderPath, fileName);
|
||||
public async Task<RpcServerCertificate?> CreateOrLoad(string directoryPath) {
|
||||
string filePath = Path.Combine(directoryPath, fileName);
|
||||
|
||||
if (File.Exists(filePath)) {
|
||||
try {
|
||||
|
||||
@@ -22,12 +22,12 @@ PosixSignals.RegisterCancellation(shutdownCancellationTokenSource, static () =>
|
||||
PhantomLogger.Root.InformationHeading("Stopping Phantom Panel controller...");
|
||||
});
|
||||
|
||||
static void CreateFolderOrStop(string path, UnixFileMode chmod) {
|
||||
static void CreateDirectoryOrStop(string path, UnixFileMode chmod) {
|
||||
if (!Directory.Exists(path)) {
|
||||
try {
|
||||
Directories.Create(path, chmod);
|
||||
} catch (Exception e) {
|
||||
PhantomLogger.Root.Fatal(e, "Error creating folder: {FolderName}", path);
|
||||
PhantomLogger.Root.Fatal(e, "Error creating directory: {DirectoryName}", path);
|
||||
throw StopProcedureException.Instance;
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ try {
|
||||
var (agentRpcServerHost, webRpcServerHost, sqlConnectionString) = Variables.LoadOrStop();
|
||||
|
||||
string secretsPath = Path.GetFullPath("./secrets");
|
||||
CreateFolderOrStop(secretsPath, Chmod.URWX_GRX);
|
||||
CreateDirectoryOrStop(secretsPath, Chmod.URWX_GRX);
|
||||
|
||||
var agentCertificate = await new CertificateFile("agent").CreateOrLoad(secretsPath);
|
||||
if (agentCertificate == null) {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
namespace Phantom.Utils.IO;
|
||||
|
||||
public sealed class StreamCopier(int bufferSize = StreamCopier.DefaultBufferSize) : IDisposable {
|
||||
private const int DefaultBufferSize = 81920;
|
||||
private const int DefaultBufferSize = 65536;
|
||||
|
||||
public event EventHandler<BufferEventArgs>? BufferReady;
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -21,12 +21,12 @@ PosixSignals.RegisterCancellation(shutdownCancellationTokenSource, static () =>
|
||||
PhantomLogger.Root.InformationHeading("Stopping Phantom Panel web...");
|
||||
});
|
||||
|
||||
static void CreateFolderOrStop(string path, UnixFileMode chmod) {
|
||||
static void CreateDirectoryOrStop(string path, UnixFileMode chmod) {
|
||||
if (!Directory.Exists(path)) {
|
||||
try {
|
||||
Directories.Create(path, chmod);
|
||||
} catch (Exception e) {
|
||||
PhantomLogger.Root.Fatal(e, "Error creating folder: {FolderName}", path);
|
||||
PhantomLogger.Root.Fatal(e, "Error creating directory: {DirectoryName}", path);
|
||||
throw StopProcedureException.Instance;
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ try {
|
||||
}
|
||||
|
||||
string dataProtectionKeysPath = Path.GetFullPath("./keys");
|
||||
CreateFolderOrStop(dataProtectionKeysPath, Chmod.URWX);
|
||||
CreateDirectoryOrStop(dataProtectionKeysPath, Chmod.URWX);
|
||||
|
||||
var administratorToken = TokenGenerator.Create(60);
|
||||
var applicationProperties = new ApplicationProperties(fullVersion, TokenGenerator.GetBytesOrThrow(administratorToken));
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -8,7 +8,7 @@ using ILogger = Serilog.ILogger;
|
||||
namespace Phantom.Web;
|
||||
|
||||
static class WebLauncher {
|
||||
internal sealed record Configuration(ILogger Logger, string Host, ushort Port, string BasePath, string DataProtectionKeyFolderPath, CancellationToken CancellationToken) {
|
||||
internal sealed record Configuration(ILogger Logger, string Host, ushort Port, string BasePath, string DataProtectionKeyDirectoryPath, CancellationToken CancellationToken) {
|
||||
public string HttpUrl => "http://" + Host + ":" + Port;
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ static class WebLauncher {
|
||||
builder.Services.AddSingleton<IHostLifetime>(new NullLifetime());
|
||||
builder.Services.AddScoped(Navigation.Create(config.BasePath));
|
||||
|
||||
builder.Services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(config.DataProtectionKeyFolderPath));
|
||||
builder.Services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(config.DataProtectionKeyDirectoryPath));
|
||||
|
||||
builder.Services.AddRazorPages(static options => options.RootDirectory = "/Layout");
|
||||
builder.Services.AddServerSideBlazor();
|
||||
|
||||
Reference in New Issue
Block a user