mirror of
https://github.com/chylex/Minecraft-Phantom-Panel.git
synced 2026-06-14 22:16:33 +02:00
Compare commits
2 Commits
21bfdf90ee
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
a1ed4f9d20
|
|||
|
49bdcc3db3
|
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
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");
|
||||
|
||||
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;
|
||||
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,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace Phantom.Agent.Services.Games;
|
||||
|
||||
static class MinecraftCommand {
|
||||
public const string SaveOn = "save-on";
|
||||
public const string SaveOff = "save-off";
|
||||
|
||||
public static string SaveAll(bool flush) {
|
||||
return flush ? "save-all flush" : "save-all";
|
||||
}
|
||||
}
|
||||
@@ -19,14 +19,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 +39,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;
|
||||
@@ -87,8 +87,8 @@ 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, stopRecipe);
|
||||
|
||||
@@ -98,10 +98,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) {
|
||||
@@ -136,7 +136,7 @@ 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);
|
||||
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
|
||||
sealed record InstanceProperties(
|
||||
Guid InstanceGuid,
|
||||
string InstanceFolder
|
||||
string InstanceDirectoryPath
|
||||
);
|
||||
|
||||
@@ -34,7 +34,7 @@ sealed class InstanceLauncher(
|
||||
|
||||
var processConfigurator = new ProcessConfigurator {
|
||||
FileName = executablePath,
|
||||
WorkingDirectory = instanceProperties.InstanceFolder,
|
||||
WorkingDirectory = instanceProperties.InstanceDirectoryPath,
|
||||
RedirectInput = true,
|
||||
UseShellExecute = 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) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
extension(BackupCreationWarnings warnings) {
|
||||
public int Count() {
|
||||
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));
|
||||
public IEnumerable<BackupCreationWarnings> ListFlags() {
|
||||
return Enum.GetValues<BackupCreationWarnings>().Where(warning => warning != BackupCreationWarnings.None && warnings.HasFlag(warning));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
namespace Phantom.Common.Data.Replies;
|
||||
|
||||
public enum ConfigureInstanceResult : byte {
|
||||
Success = 0,
|
||||
CouldNotCreateInstanceFolder = 1,
|
||||
Success = 0,
|
||||
CouldNotCreateInstanceDirectory = 1,
|
||||
}
|
||||
|
||||
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.",
|
||||
_ => "Unknown error.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,8 +72,6 @@ public sealed partial class MinecraftInstanceRecipes(MinecraftVersions minecraft
|
||||
return ImmutableDictionary.From([
|
||||
("server-port", configuration.ServerPort.ToString()),
|
||||
("rcon.port", configuration.RconPort.ToString()),
|
||||
("enable-rcon", "true"),
|
||||
("sync-chunk-writes", "false"),
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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