Files
Servers/MoonlightServers.Daemon/ServerSystem/Implementations/Docker/DockerRuntimeEnv.cs

61 lines
1.9 KiB
C#

using Docker.DotNet;
using MoonlightServers.Daemon.ServerSystem.Abstractions;
using MoonlightServers.Daemon.ServerSystem.Implementations.Docker.Events;
namespace MoonlightServers.Daemon.ServerSystem.Implementations.Docker;
public class DockerRuntimeEnv : IRuntimeEnvironment
{
public IRuntimeStatistics Statistics => InnerStatistics;
public IRuntimeConsole Console => InnerConsole;
public string ContainerId { get; }
public event Func<Task>? OnExited;
private readonly DockerClient DockerClient;
private readonly DockerEventService EventService;
private readonly DockerConsole InnerConsole;
private readonly DockerStatistics InnerStatistics;
public DockerRuntimeEnv(string containerId, DockerClient dockerClient, ILogger logger, DockerEventService eventService)
{
ContainerId = containerId;
DockerClient = dockerClient;
EventService = eventService;
InnerStatistics = new DockerStatistics();
InnerConsole = new DockerConsole(containerId, dockerClient, logger);
EventService.OnContainerDied += HandleDieEventAsync;
}
public async Task<bool> IsRunningAsync()
{
var container = await DockerClient.Containers.InspectContainerAsync(ContainerId);
return container.State.Running;
}
public async Task StartAsync()
=> await DockerClient.Containers.StartContainerAsync(ContainerId, new());
public async Task KillAsync()
=> await DockerClient.Containers.KillContainerAsync(ContainerId, new());
private async Task HandleDieEventAsync(ContainerDieEvent dieEvent)
{
if(dieEvent.ContainerId != ContainerId)
return;
if(OnExited != null)
await OnExited.Invoke();
}
public async ValueTask DisposeAsync()
{
EventService.OnContainerDied -= HandleDieEventAsync;
await InnerConsole.DisposeAsync();
}
}