2using System.Collections.Generic;
8using System.Threading.Tasks;
10using Microsoft.Extensions.Logging;
65 readonly ILogger<EngineManager>
logger;
70 readonly Dictionary<EngineVersion, ReferenceCountingContainer<IEngineInstallation, EngineExecutableLock>>
installedVersions;
88 ArgumentNullException.ThrowIfNull(version);
90 if (!version.
Engine.HasValue)
91 throw new InvalidOperationException(
"version.Engine cannot be null!");
94 throw new InvalidOperationException(
"version.CustomIteration cannot be 0!");
109 this.logger =
logger ??
throw new ArgumentNullException(nameof(
logger));
111 installedVersions =
new Dictionary<EngineVersion, ReferenceCountingContainer<IEngineInstallation, EngineExecutableLock>>();
123 Stream? customVersionStream,
124 bool allowInstallation,
125 CancellationToken cancellationToken)
142 var stringVersion = version.
ToString();
148 ActiveVersion?.ToString(),
156 logger.LogInformation(
"Active version changed to {version}", version);
163 public async ValueTask<IEngineExecutableLock>
UseExecutables(
EngineVersion? requiredVersion,
string? trustDmbFullPath, CancellationToken cancellationToken)
166 "Acquiring lock on BYOND version {version}...",
167 requiredVersion?.ToString() ?? $
"{ActiveVersion} (active)");
173 requiredVersion !=
null,
178 if (trustDmbFullPath !=
null)
185 installLock.Dispose();
193 ArgumentNullException.ThrowIfNull(progressReporter);
197 logger.LogTrace(
"DeleteVersion {version}", version);
200 if (activeVersion !=
null && version.
Equals(activeVersion))
204 logger.LogTrace(
"Waiting to acquire installedVersions lock...");
209 logger.LogTrace(
"Version {version} already deleted.", version);
213 container = containerNullable;
214 logger.LogTrace(
"Installation container acquired for deletion");
217 progressReporter.StageName =
"Waiting for version to not be in use...";
223 Task activeVersionUpdate;
227 logger.LogTrace(
"Waiting for container.OnZeroReferences or switch of active version...");
231 .WaitAsync(cancellationToken);
233 if (containerTask.IsCompleted)
234 logger.LogTrace(
"All locks for version {version} are gone", version);
236 logger.LogTrace(
"activeVersion changed, we may have to wait again. Acquiring semaphore...");
242 if (activeVersion !=
null && version.
Equals(activeVersion))
246 logger.LogTrace(
"Locking installedVersions...");
252 logger.LogWarning(
"Unable to remove engine installation {version} from list! Is there a duplicate job running?", version);
255 if (container != newerContainer)
260 logger.LogDebug(
"Extreme race condition encountered, applying concentrated copium...");
261 container = newerContainer;
267 logger.LogTrace(
"Proceeding with installation deletion...");
275 logger.LogInformation(
"Deleting version {version}...", version);
276 progressReporter.StageName =
"Deleting installation...";
279 var installPath = version.
ToString();
287 if (containerTask.IsCompleted)
289 "Another lock was acquired before we could remove version {version} from the list. We will have to wait again.",
292 logger.LogTrace(
"Not proceeding for some reason or another");
298 public async Task
StartAsync(CancellationToken cancellationToken)
300 async ValueTask<byte[]?> GetActiveVersion()
306 var activeVersionBytesTask = GetActiveVersion();
311 var installedVersionPaths =
new Dictionary<string, EngineVersion>();
313 async ValueTask ReadVersion(
string path)
324 var text = Encoding.UTF8.GetString(bytes);
333 version = versionNullable!;
338 logger.LogDebug(
"Added detected BYOND version {versionKey}...", version);
344 "It seems that there are multiple directories that say they contain BYOND version {version}. We're ignoring and cleaning the duplicate: {duplicatePath}",
351 lock (installedVersionPaths)
357 .Select(ReadVersion));
359 logger.LogTrace(
"Upgrading BYOND installations...");
361 installedVersionPaths
364 var activeVersionBytes = await activeVersionBytesTask;
365 if (activeVersionBytes !=
null)
367 var activeVersionString = Encoding.UTF8.GetString(activeVersionBytes);
370 bool hasRequestedActiveVersion;
375 if (hasRequestedActiveVersion)
379 logger.LogWarning(
"Failed to load saved active version {activeVersion}!", activeVersionString);
386 public Task
StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
401 Stream? customVersionStream,
403 bool allowInstallation,
404 CancellationToken cancellationToken)
406 var ourTcs =
new TaskCompletionSource();
409 bool installedOrInstalling;
412 if (customVersionStream !=
null)
414 var customInstallationNumber = 1;
417 version.CustomIteration = customInstallationNumber++;
422 installedOrInstalling =
installedVersions.TryGetValue(version, out var installationContainerNullable);
424 if (!installedOrInstalling)
426 if (!allowInstallation)
427 throw new InvalidOperationException($
"Engine version {version} not installed!");
435 installationContainer = installationContainerNullable!;
437 installation = installationContainer.
Instance;
441 var deploymentPipelineProcesses = !neededForLock;
444 if (installedOrInstalling)
446 if (progressReporter !=
null)
447 progressReporter.StageName =
"Waiting for existing installation job...";
450 logger.LogWarning(
"The required engine version ({version}) is not readily available! We will have to wait for it to install.", version);
459 if (customVersionStream !=
null)
460 logger.LogInformation(
"Installing custom engine version as {version}...", version);
461 else if (neededForLock)
466 logger.LogWarning(
"The required engine version ({version}) is not readily available! We will have to install it.", version);
469 logger.LogInformation(
"Requested engine version {version} not currently installed. Doing so now...", version);
471 if (progressReporter !=
null)
472 progressReporter.StageName =
"Running event";
474 var versionString = version.
ToString();
477 await
InstallVersionFiles(progressReporter, version, customVersionStream, deploymentPipelineProcesses, cancellationToken);
485 if (ex is not OperationCanceledException)
491 ourTcs.SetException(ex);
516 Stream? customVersionStream,
517 bool deploymentPipelineProcesses,
518 CancellationToken cancellationToken)
521 async ValueTask DirectoryCleanup()
527 var directoryCleanupTask = DirectoryCleanup();
531 if (customVersionStream ==
null)
533 if (progressReporter !=
null)
534 progressReporter.StageName =
"Downloading version";
541#pragma warning disable CA2000
544 customVersionStream);
545#pragma warning restore CA2000
547 await
using (engineInstallationData)
549 if (progressReporter !=
null)
550 progressReporter.StageName =
"Cleaning target directory";
552 await directoryCleanupTask;
554 if (progressReporter !=
null)
555 progressReporter.StageName =
"Extracting data";
557 logger.LogTrace(
"Extracting engine to {extractPath}...", installFullPath);
558 await engineInstallationData.
ExtractToPath(installFullPath, cancellationToken);
561 if (progressReporter !=
null)
562 progressReporter.StageName =
"Running installation actions";
566 if (progressReporter !=
null)
567 progressReporter.StageName =
"Writing version file";
572 Encoding.UTF8.GetBytes(version.
ToString()),
575 catch (HttpRequestException ex)
580 catch (OperationCanceledException)
607 return installationContainer;
Information about an engine installation.
override string ToString()
static bool TryParse(string input, out EngineVersion? engineVersion)
Attempts to parse a stringified EngineVersion.
bool Equals(EngineVersion other)
EngineType? Engine
The EngineType.
int? CustomIteration
The revision of the custom build.
Extension methods for the ValueTask and ValueTask<TResult> classes.
static async ValueTask WhenAll(IEnumerable< ValueTask > tasks)
Fully await a given list of tasks .
async ValueTask InstallVersionFiles(JobProgressReporter? progressReporter, EngineVersion version, Stream? customVersionStream, bool deploymentPipelineProcesses, CancellationToken cancellationToken)
Installs the files for a given BYOND version .
static void CheckVersionParameter(EngineVersion version)
Validates a given version parameter.
readonly Dictionary< EngineVersion, ReferenceCountingContainer< IEngineInstallation, EngineExecutableLock > > installedVersions
Map of byond EngineVersions to Tasks that complete when they are installed.
Task StopAsync(CancellationToken cancellationToken)
async ValueTask< EngineExecutableLock > AssertAndLockVersion(JobProgressReporter? progressReporter, EngineVersion version, Stream? customVersionStream, bool neededForLock, bool allowInstallation, CancellationToken cancellationToken)
Ensures a BYOND version is installed if it isn't already.
const string VersionFileName
The file in which we store the Version for installations.
async Task StartAsync(CancellationToken cancellationToken)
IReadOnlyList< EngineVersion > InstalledVersions
The installed EngineVersions.
volatile TaskCompletionSource activeVersionChanged
TaskCompletionSource that notifes when the ActiveVersion changes.
const string ActiveVersionFileName
The file in which we store the ActiveVersion.
async ValueTask< IEngineExecutableLock > UseExecutables(EngineVersion? requiredVersion, string? trustDmbFullPath, CancellationToken cancellationToken)
Lock the current installation's location and return a IEngineExecutableLock. A ValueTask<TResult> res...
async ValueTask DeleteVersion(JobProgressReporter progressReporter, EngineVersion version, CancellationToken cancellationToken)
Deletes a given version from the disk. A Task representing the running operation.
EngineVersion? ActiveVersion
The currently active EngineVersion.
EngineManager(IIOManager ioManager, IEngineInstaller engineInstaller, IEventConsumer eventConsumer, ILogger< EngineManager > logger)
Initializes a new instance of the EngineManager class.
readonly SemaphoreSlim changeDeleteSemaphore
The SemaphoreSlim for changing or deleting the active BYOND version.
readonly IEventConsumer eventConsumer
The IEventConsumer for the EngineManager.
readonly IIOManager ioManager
The IIOManager for the EngineManager.
readonly IEngineInstaller engineInstaller
The IEngineInstaller for the EngineManager.
readonly ILogger< EngineManager > logger
The ILogger for the EngineManager.
ReferenceCountingContainer< IEngineInstallation, EngineExecutableLock > AddInstallationContainer(EngineVersion version, string installPath, Task installationTask)
Create and add a new IEngineInstallation to installedVersions.
async ValueTask ChangeVersion(JobProgressReporter? progressReporter, EngineVersion version, Stream? customVersionStream, bool allowInstallation, CancellationToken cancellationToken)
Change the active EngineVersion. A ValueTask representing the running operation.
Implementation of IEngineInstallationData for a zip file in a Stream.
IIOManager that resolves paths to Environment.CurrentDirectory.
const string CurrentDirectory
Path to the current working directory for the IIOManager.
Operation exceptions thrown from the context of a Models.Job.
Progress reporter for a Job.
void ReportProgress(double? progress)
Report progress.
Wrapper for managing some TWrapped .
TReference AddReference()
Create a new TReference to the Instance.
TWrapped Instance
The TWrapped .
Task OnZeroReferences
A Task that completes when there are no TReference s active for the Instance.
Async lock context helper.
static async ValueTask< SemaphoreSlimContext > Lock(SemaphoreSlim semaphore, CancellationToken cancellationToken)
Asyncronously locks a semaphore .
Wraps data containing an engine installation.
Task ExtractToPath(string path, CancellationToken cancellationToken)
Extracts the installation to a given path.
Represents a BYOND installation.
Task InstallationTask
The Task that completes when the BYOND version finished installing.
For downloading and installing game engines for a given system.
IEngineInstallation CreateInstallation(EngineVersion version, string path, Task installationTask)
Creates an IEngineInstallation for a given version .
ValueTask UpgradeInstallation(EngineVersion version, string path, CancellationToken cancellationToken)
Does actions necessary to get upgrade a version installed by a previous version of TGS.
ValueTask< IEngineInstallationData > DownloadVersion(EngineVersion version, JobProgressReporter? jobProgressReporter, CancellationToken cancellationToken)
Download a given engine version .
ValueTask Install(EngineVersion version, string path, bool deploymentPipelineProcesses, CancellationToken cancellationToken)
Does actions necessary to get an extracted installation working.
ValueTask TrustDmbPath(EngineVersion version, string fullDmbPath, CancellationToken cancellationToken)
Add a given fullDmbPath to the trusted DMBs list in BYOND's config.
For managing the engine installations.
Consumes EventTypes and takes the appropriate actions.
ValueTask HandleEvent(EventType eventType, IEnumerable< string?> parameters, bool deploymentPipeline, CancellationToken cancellationToken)
Handle a given eventType .
Interface for using filesystems.
string ResolvePath()
Retrieve the full path of the current working directory.
ValueTask< byte[]> ReadAllBytes(string path, CancellationToken cancellationToken)
Returns all the contents of a file at path as a byte array.
string ConcatPath(params string[] paths)
Combines an array of strings into a path.
Task< IReadOnlyList< string > > GetDirectories(string path, CancellationToken cancellationToken)
Returns full directory names in a given path .
Task CreateDirectory(string path, CancellationToken cancellationToken)
Create a directory at path .
Task DeleteFile(string path, CancellationToken cancellationToken)
Deletes a file at path .
ValueTask WriteAllBytes(string path, byte[] contents, CancellationToken cancellationToken)
Writes some contents to a file at path overwriting previous content.
Task DeleteDirectory(string path, CancellationToken cancellationToken)
Recursively delete a directory, removes and does not enter any symlinks encounterd.
Task< bool > FileExists(string path, CancellationToken cancellationToken)
Check that the file at path exists.
ErrorCode
Types of Response.ErrorMessageResponses that the API may return.
EventType
Types of events. Mirror in tgs.dm. Prefer last listed name for script.