diff --git a/src/Runner.Common/HostContext.cs b/src/Runner.Common/HostContext.cs index 9205faf5831..d2c7eebd97c 100644 --- a/src/Runner.Common/HostContext.cs +++ b/src/Runner.Common/HostContext.cs @@ -375,6 +375,14 @@ public async Task Delay(TimeSpan delay, CancellationToken cancellationToken) await Task.Delay(delay, cancellationToken); } + /// + /// Register a default dynamic service. + /// + public void RegisterService(Type type, Type target) + { + _serviceTypes.TryAdd(type, target); + } + /// /// Creates a new instance of T. /// diff --git a/src/Runner.Worker/ActionManager.cs b/src/Runner.Worker/ActionManager.cs index 76b087a4b71..e0fea06b0db 100644 --- a/src/Runner.Worker/ActionManager.cs +++ b/src/Runner.Worker/ActionManager.cs @@ -530,12 +530,12 @@ private async Task PullActionContainerAsync(IExecutionContext executionContext, executionContext.Output($"##[group]Pull down action image '{setupInfo.Container.Image}'"); // Pull down docker image with retry up to 3 times - var dockerManager = HostContext.GetService(); + var containerManager = HostContext.GetService(); int retryCount = 0; int pullExitCode = 0; while (retryCount < 3) { - pullExitCode = await dockerManager.DockerPull(executionContext, setupInfo.Container.Image); + pullExitCode = await containerManager.DockerPull(executionContext, setupInfo.Container.Image); if (pullExitCode == 0) { break; @@ -574,13 +574,13 @@ private async Task BuildActionContainerAsync(IExecutionContext executionContext, executionContext.Output($"##[group]Build container for action use: '{setupInfo.Container.Dockerfile}'."); // Build docker image with retry up to 3 times - var dockerManager = HostContext.GetService(); + var containerManager = HostContext.GetService(); int retryCount = 0; int buildExitCode = 0; - var imageName = $"{dockerManager.DockerInstanceLabel}:{Guid.NewGuid().ToString("N")}"; + var imageName = $"{containerManager.DockerInstanceLabel}:{Guid.NewGuid().ToString("N")}"; while (retryCount < 3) { - buildExitCode = await dockerManager.DockerBuild( + buildExitCode = await containerManager.DockerBuild( executionContext, setupInfo.Container.WorkingDirectory, setupInfo.Container.Dockerfile, diff --git a/src/Runner.Worker/Container/DockerCommandManager.cs b/src/Runner.Worker/Container/DockerCommandManager.cs index 86cf0eeedf2..b0740995ff8 100644 --- a/src/Runner.Worker/Container/DockerCommandManager.cs +++ b/src/Runner.Worker/Container/DockerCommandManager.cs @@ -11,33 +11,9 @@ namespace GitHub.Runner.Worker.Container { - [ServiceLocator(Default = typeof(DockerCommandManager))] - public interface IDockerCommandManager : IRunnerService - { - string DockerPath { get; } - string DockerInstanceLabel { get; } - Task DockerVersion(IExecutionContext context); - Task DockerPull(IExecutionContext context, string image); - Task DockerPull(IExecutionContext context, string image, string configFileDirectory); - Task DockerBuild(IExecutionContext context, string workingDirectory, string dockerFile, string dockerContext, string tag); - Task DockerCreate(IExecutionContext context, ContainerInfo container); - Task DockerRun(IExecutionContext context, ContainerInfo container, EventHandler stdoutDataReceived, EventHandler stderrDataReceived); - Task DockerStart(IExecutionContext context, string containerId); - Task DockerLogs(IExecutionContext context, string containerId); - Task> DockerPS(IExecutionContext context, string options); - Task DockerRemove(IExecutionContext context, string containerId); - Task DockerNetworkCreate(IExecutionContext context, string network); - Task DockerNetworkRemove(IExecutionContext context, string network); - Task DockerNetworkPrune(IExecutionContext context); - Task DockerExec(IExecutionContext context, string containerId, string options, string command); - Task DockerExec(IExecutionContext context, string containerId, string options, string command, List outputs); - Task> DockerInspect(IExecutionContext context, string dockerObject, string options); - Task> DockerPort(IExecutionContext context, string containerId); - Task DockerLogin(IExecutionContext context, string configFileDirectory, string registry, string username, string password); - } - - public class DockerCommandManager : RunnerService, IDockerCommandManager + public class DockerCommandManager : RunnerService, IContainerCommandManager { + public string Type { get { return "docker"; } } public string DockerPath { get; private set; } public string DockerInstanceLabel { get; private set; } diff --git a/src/Runner.Worker/Container/IContainerCommandManager.cs b/src/Runner.Worker/Container/IContainerCommandManager.cs new file mode 100644 index 00000000000..564dcdfe4b8 --- /dev/null +++ b/src/Runner.Worker/Container/IContainerCommandManager.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +using GitHub.Runner.Common; +using GitHub.Runner.Sdk; + +namespace GitHub.Runner.Worker.Container +{ + [ServiceLocator(Default = typeof(DockerCommandManager))] + public interface IContainerCommandManager : IRunnerService + { + string Type { get; } + string DockerPath { get; } + string DockerInstanceLabel { get; } + Task DockerVersion(IExecutionContext context); + Task DockerPull(IExecutionContext context, string image); + Task DockerPull(IExecutionContext context, string image, string configFileDirectory); + Task DockerBuild(IExecutionContext context, string workingDirectory, string dockerFile, string dockerContext, string tag); + Task DockerCreate(IExecutionContext context, ContainerInfo container); + Task DockerRun(IExecutionContext context, ContainerInfo container, EventHandler stdoutDataReceived, EventHandler stderrDataReceived); + Task DockerStart(IExecutionContext context, string containerId); + Task DockerLogs(IExecutionContext context, string containerId); + Task> DockerPS(IExecutionContext context, string options); + Task DockerRemove(IExecutionContext context, string containerId); + Task DockerNetworkCreate(IExecutionContext context, string network); + Task DockerNetworkRemove(IExecutionContext context, string network); + Task DockerNetworkPrune(IExecutionContext context); + Task DockerExec(IExecutionContext context, string containerId, string options, string command); + Task DockerExec(IExecutionContext context, string containerId, string options, string command, List outputs); + Task> DockerInspect(IExecutionContext context, string dockerObject, string options); + Task> DockerPort(IExecutionContext context, string containerId); + Task DockerLogin(IExecutionContext context, string configFileDirectory, string registry, string username, string password); + } +} diff --git a/src/Runner.Worker/Container/KubernetesCommandManager.cs b/src/Runner.Worker/Container/KubernetesCommandManager.cs new file mode 100644 index 00000000000..64861379cbc --- /dev/null +++ b/src/Runner.Worker/Container/KubernetesCommandManager.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +using GitHub.Runner.Common; +using GitHub.Runner.Sdk; + +namespace GitHub.Runner.Worker.Container +{ + public class KubernetesCommandManager : RunnerService, IContainerCommandManager + { + public string Type { get { return "kubernetes"; } } + public string DockerPath { get; private set; } + + public string DockerInstanceLabel { get; private set; } + + public Task DockerVersion(IExecutionContext context) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerPull(IExecutionContext context, string image) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerPull(IExecutionContext context, string image, string configFileDirectory) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerBuild(IExecutionContext context, string workingDirectory, string dockerFile, string dockerContext, string tag) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerCreate(IExecutionContext context, ContainerInfo container) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerRun(IExecutionContext context, ContainerInfo container, EventHandler stdoutDataReceived, EventHandler stderrDataReceived) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerStart(IExecutionContext context, string containerId) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerRemove(IExecutionContext context, string containerId) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerLogs(IExecutionContext context, string containerId) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task> DockerPS(IExecutionContext context, string options) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerNetworkCreate(IExecutionContext context, string network) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerNetworkRemove(IExecutionContext context, string network) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerNetworkPrune(IExecutionContext context) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerExec(IExecutionContext context, string containerId, string options, string command) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerExec(IExecutionContext context, string containerId, string options, string command, List output) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task> DockerInspect(IExecutionContext context, string dockerObject, string options) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task> DockerPort(IExecutionContext context, string containerId) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + + public Task DockerLogin(IExecutionContext context, string configFileDirectory, string registry, string username, string password) + { + throw new NotImplementedException("Kubernetes support to be implemented"); + } + } +} diff --git a/src/Runner.Worker/ContainerOperationProvider.cs b/src/Runner.Worker/ContainerOperationProvider.cs index 1a57c393e5e..2b780ba6c04 100644 --- a/src/Runner.Worker/ContainerOperationProvider.cs +++ b/src/Runner.Worker/ContainerOperationProvider.cs @@ -24,12 +24,12 @@ public interface IContainerOperationProvider : IRunnerService public class ContainerOperationProvider : RunnerService, IContainerOperationProvider { - private IDockerCommandManager _dockerManager; + private IContainerCommandManager _containerManager; public override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); - _dockerManager = HostContext.GetService(); + _containerManager = HostContext.GetService(); } public async Task StartContainersAsync(IExecutionContext executionContext, object data) @@ -92,7 +92,7 @@ public async Task StartContainersAsync(IExecutionContext executionContext, objec // Check docker client/server version executionContext.Output("##[group]Checking docker version"); - DockerVersion dockerVersion = await _dockerManager.DockerVersion(executionContext); + DockerVersion dockerVersion = await _containerManager.DockerVersion(executionContext); executionContext.Output("##[endgroup]"); ArgUtil.NotNull(dockerVersion.ServerVersion, nameof(dockerVersion.ServerVersion)); @@ -106,26 +106,26 @@ public async Task StartContainersAsync(IExecutionContext executionContext, objec if (dockerVersion.ServerVersion < requiredDockerEngineAPIVersion) { - throw new NotSupportedException($"Min required docker engine API server version is '{requiredDockerEngineAPIVersion}', your docker ('{_dockerManager.DockerPath}') server version is '{dockerVersion.ServerVersion}'"); + throw new NotSupportedException($"Min required docker engine API server version is '{requiredDockerEngineAPIVersion}', your docker ('{_containerManager.DockerPath}') server version is '{dockerVersion.ServerVersion}'"); } if (dockerVersion.ClientVersion < requiredDockerEngineAPIVersion) { - throw new NotSupportedException($"Min required docker engine API client version is '{requiredDockerEngineAPIVersion}', your docker ('{_dockerManager.DockerPath}') client version is '{dockerVersion.ClientVersion}'"); + throw new NotSupportedException($"Min required docker engine API client version is '{requiredDockerEngineAPIVersion}', your docker ('{_containerManager.DockerPath}') client version is '{dockerVersion.ClientVersion}'"); } // Clean up containers left by previous runs executionContext.Output("##[group]Clean up resources from previous jobs"); - var staleContainers = await _dockerManager.DockerPS(executionContext, $"--all --quiet --no-trunc --filter \"label={_dockerManager.DockerInstanceLabel}\""); + var staleContainers = await _containerManager.DockerPS(executionContext, $"--all --quiet --no-trunc --filter \"label={_containerManager.DockerInstanceLabel}\""); foreach (var staleContainer in staleContainers) { - int containerRemoveExitCode = await _dockerManager.DockerRemove(executionContext, staleContainer); + int containerRemoveExitCode = await _containerManager.DockerRemove(executionContext, staleContainer); if (containerRemoveExitCode != 0) { executionContext.Warning($"Delete stale containers failed, docker rm fail with exit code {containerRemoveExitCode} for container {staleContainer}"); } } - int networkPruneExitCode = await _dockerManager.DockerNetworkPrune(executionContext); + int networkPruneExitCode = await _containerManager.DockerNetworkPrune(executionContext); if (networkPruneExitCode != 0) { executionContext.Warning($"Delete stale container networks failed, docker network prune fail with exit code {networkPruneExitCode}"); @@ -208,7 +208,7 @@ private async Task StartContainerAsync(IExecutionContext executionContext, Conta int pullExitCode = 0; while (retryCount < 3) { - pullExitCode = await _dockerManager.DockerPull(executionContext, container.ContainerImage, configLocation); + pullExitCode = await _containerManager.DockerPull(executionContext, container.ContainerImage, configLocation); if (pullExitCode == 0) { break; @@ -266,11 +266,11 @@ private async Task StartContainerAsync(IExecutionContext executionContext, Conta container.ContainerEntryPointArgs = "\"-f\" \"/dev/null\""; } - container.ContainerId = await _dockerManager.DockerCreate(executionContext, container); + container.ContainerId = await _containerManager.DockerCreate(executionContext, container); ArgUtil.NotNullOrEmpty(container.ContainerId, nameof(container.ContainerId)); // Start container - int startExitCode = await _dockerManager.DockerStart(executionContext, container.ContainerId); + int startExitCode = await _containerManager.DockerStart(executionContext, container.ContainerId); if (startExitCode != 0) { throw new InvalidOperationException($"Docker start fail with exit code {startExitCode}"); @@ -279,12 +279,12 @@ private async Task StartContainerAsync(IExecutionContext executionContext, Conta try { // Make sure container is up and running - var psOutputs = await _dockerManager.DockerPS(executionContext, $"--all --filter id={container.ContainerId} --filter status=running --no-trunc --format \"{{{{.ID}}}} {{{{.Status}}}}\""); + var psOutputs = await _containerManager.DockerPS(executionContext, $"--all --filter id={container.ContainerId} --filter status=running --no-trunc --format \"{{{{.ID}}}} {{{{.Status}}}}\""); if (psOutputs.FirstOrDefault(x => !string.IsNullOrEmpty(x))?.StartsWith(container.ContainerId) != true) { // container is not up and running, pull docker log for this container. - await _dockerManager.DockerPS(executionContext, $"--all --filter id={container.ContainerId} --no-trunc --format \"{{{{.ID}}}} {{{{.Status}}}}\""); - int logsExitCode = await _dockerManager.DockerLogs(executionContext, container.ContainerId); + await _containerManager.DockerPS(executionContext, $"--all --filter id={container.ContainerId} --no-trunc --format \"{{{{.ID}}}} {{{{.Status}}}}\""); + int logsExitCode = await _containerManager.DockerLogs(executionContext, container.ContainerId); if (logsExitCode != 0) { executionContext.Warning($"Docker logs fail with exit code {logsExitCode}"); @@ -309,7 +309,7 @@ private async Task StartContainerAsync(IExecutionContext executionContext, Conta ["ports"] = new DictionaryContextData(), ["network"] = new StringContextData(container.ContainerNetwork) }; - container.AddPortMappings(await _dockerManager.DockerPort(executionContext, container.ContainerId)); + container.AddPortMappings(await _containerManager.DockerPort(executionContext, container.ContainerId)); foreach (var port in container.PortMappings) { (service["ports"] as DictionaryContextData)[port.ContainerPort] = new StringContextData(port.HostPort); @@ -319,7 +319,7 @@ private async Task StartContainerAsync(IExecutionContext executionContext, Conta else { var configEnvFormat = "--format \"{{range .Config.Env}}{{println .}}{{end}}\""; - var containerEnv = await _dockerManager.DockerInspect(executionContext, container.ContainerId, configEnvFormat); + var containerEnv = await _containerManager.DockerInspect(executionContext, container.ContainerId, configEnvFormat); container.ContainerRuntimePath = DockerUtil.ParsePathFromConfigEnv(containerEnv); executionContext.JobContext.Container["id"] = new StringContextData(container.ContainerId); } @@ -336,7 +336,7 @@ private async Task StopContainerAsync(IExecutionContext executionContext, Contai { executionContext.Output($"Stop and remove container: {container.ContainerDisplayName}"); - int rmExitCode = await _dockerManager.DockerRemove(executionContext, container.ContainerId); + int rmExitCode = await _containerManager.DockerRemove(executionContext, container.ContainerId); if (rmExitCode != 0) { executionContext.Warning($"Docker rm fail with exit code {rmExitCode}"); @@ -396,7 +396,7 @@ private async Task CreateContainerNetworkAsync(IExecutionContext executionContex { Trace.Entering(); ArgUtil.NotNull(executionContext, nameof(executionContext)); - int networkExitCode = await _dockerManager.DockerNetworkCreate(executionContext, network); + int networkExitCode = await _containerManager.DockerNetworkCreate(executionContext, network); if (networkExitCode != 0) { throw new InvalidOperationException($"Docker network create failed with exit code {networkExitCode}"); @@ -411,7 +411,7 @@ private async Task RemoveContainerNetworkAsync(IExecutionContext executionContex executionContext.Output($"Remove container network: {network}"); - int removeExitCode = await _dockerManager.DockerNetworkRemove(executionContext, network); + int removeExitCode = await _containerManager.DockerNetworkRemove(executionContext, network); if (removeExitCode != 0) { executionContext.Warning($"Docker network rm failed with exit code {removeExitCode}"); @@ -421,7 +421,7 @@ private async Task RemoveContainerNetworkAsync(IExecutionContext executionContex private async Task ContainerHealthcheck(IExecutionContext executionContext, ContainerInfo container) { string healthCheck = "--format=\"{{if .Config.Healthcheck}}{{print .State.Health.Status}}{{end}}\""; - string serviceHealth = (await _dockerManager.DockerInspect(context: executionContext, dockerObject: container.ContainerId, options: healthCheck)).FirstOrDefault(); + string serviceHealth = (await _containerManager.DockerInspect(context: executionContext, dockerObject: container.ContainerId, options: healthCheck)).FirstOrDefault(); if (string.IsNullOrEmpty(serviceHealth)) { // Container has no HEALTHCHECK @@ -433,7 +433,7 @@ private async Task ContainerHealthcheck(IExecutionContext executionContext, Cont TimeSpan backoff = BackoffTimerHelper.GetExponentialBackoff(retryCount, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(32), TimeSpan.FromSeconds(2)); executionContext.Output($"{container.ContainerNetworkAlias} service is starting, waiting {backoff.Seconds} seconds before checking again."); await Task.Delay(backoff, executionContext.CancellationToken); - serviceHealth = (await _dockerManager.DockerInspect(context: executionContext, dockerObject: container.ContainerId, options: healthCheck)).FirstOrDefault(); + serviceHealth = (await _containerManager.DockerInspect(context: executionContext, dockerObject: container.ContainerId, options: healthCheck)).FirstOrDefault(); retryCount++; } if (string.Equals(serviceHealth, "healthy", StringComparison.OrdinalIgnoreCase)) @@ -462,7 +462,7 @@ private async Task ContainerRegistryLogin(IExecutionContext executionCon { throw new InvalidOperationException($"Failed to create directory to store registry client credentials: {e.Message}"); } - var loginExitCode = await _dockerManager.DockerLogin( + var loginExitCode = await _containerManager.DockerLogin( executionContext, configLocation, container.RegistryServer, diff --git a/src/Runner.Worker/Handlers/ContainerActionHandler.cs b/src/Runner.Worker/Handlers/ContainerActionHandler.cs index a74275ba1b3..a60fceeb999 100644 --- a/src/Runner.Worker/Handlers/ContainerActionHandler.cs +++ b/src/Runner.Worker/Handlers/ContainerActionHandler.cs @@ -37,7 +37,7 @@ public async Task RunAsync(ActionRunStage stage) // Update the env dictionary. AddInputsToEnvironment(); - var dockerManager = HostContext.GetService(); + var containerManager = HostContext.GetService(); // container image haven't built/pull if (Data.Image.StartsWith("docker://", StringComparison.OrdinalIgnoreCase)) @@ -52,8 +52,8 @@ public async Task RunAsync(ActionRunStage stage) ExecutionContext.Output($"##[group]Building docker image"); ExecutionContext.Output($"Dockerfile for action: '{dockerFile}'."); - var imageName = $"{dockerManager.DockerInstanceLabel}:{ExecutionContext.Id.ToString("N")}"; - var buildExitCode = await dockerManager.DockerBuild( + var imageName = $"{containerManager.DockerInstanceLabel}:{ExecutionContext.Id.ToString("N")}"; + var buildExitCode = await containerManager.DockerBuild( ExecutionContext, ExecutionContext.GetGitHubContext("workspace"), dockerFile, @@ -228,7 +228,7 @@ public async Task RunAsync(ActionRunStage stage) using (var stdoutManager = new OutputManager(ExecutionContext, ActionCommandManager, container)) using (var stderrManager = new OutputManager(ExecutionContext, ActionCommandManager, container)) { - var runExitCode = await dockerManager.DockerRun(ExecutionContext, container, stdoutManager.OnDataReceived, stderrManager.OnDataReceived); + var runExitCode = await containerManager.DockerRun(ExecutionContext, container, stdoutManager.OnDataReceived, stderrManager.OnDataReceived); ExecutionContext.Debug($"Docker Action run completed with exit code {runExitCode}"); if (runExitCode != 0) { diff --git a/src/Runner.Worker/Handlers/StepHost.cs b/src/Runner.Worker/Handlers/StepHost.cs index 8741c22bbe5..9225b15516f 100644 --- a/src/Runner.Worker/Handlers/StepHost.cs +++ b/src/Runner.Worker/Handlers/StepHost.cs @@ -129,10 +129,10 @@ public async Task DetermineNodeRuntimeVersion(IExecutionContext executio // There may be more variation in which libraries are linked than just musl/glibc, // so determine based on known distribtutions instead var osReleaseIdCmd = "sh -c \"cat /etc/*release | grep ^ID\""; - var dockerManager = HostContext.GetService(); + var containerManager = HostContext.GetService(); var output = new List(); - var execExitCode = await dockerManager.DockerExec(executionContext, Container.ContainerId, string.Empty, osReleaseIdCmd, output); + var execExitCode = await containerManager.DockerExec(executionContext, Container.ContainerId, string.Empty, osReleaseIdCmd, output); string nodeExternal; if (execExitCode == 0) { @@ -174,8 +174,8 @@ public async Task ExecuteAsync(string workingDirectory, ArgUtil.NotNull(Container, nameof(Container)); ArgUtil.NotNullOrEmpty(Container.ContainerId, nameof(Container.ContainerId)); - var dockerManager = HostContext.GetService(); - string dockerClientPath = dockerManager.DockerPath; + var containerManager = HostContext.GetService(); + string dockerClientPath = containerManager.DockerPath; // Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...] IList dockerCommandArgs = new List(); diff --git a/src/Runner.Worker/Program.cs b/src/Runner.Worker/Program.cs index 4f5cf68bd9c..d38799d15f1 100644 --- a/src/Runner.Worker/Program.cs +++ b/src/Runner.Worker/Program.cs @@ -4,6 +4,7 @@ using GitHub.Runner.Common; using GitHub.Runner.Sdk; using System.Diagnostics; +using GitHub.Runner.Worker.Container; namespace GitHub.Runner.Worker { @@ -13,10 +14,30 @@ public static int Main(string[] args) { using (HostContext context = new HostContext("Worker")) { + // Enable until kubernetes support is fully enabled + // configureCommandManager(context); return MainAsync(context, args).GetAwaiter().GetResult(); } } + public static void configureCommandManager(HostContext context) { + Tracing trace = context.GetTrace(nameof(GitHub.Runner.Worker)); + var containerProvider = Environment.GetEnvironmentVariable("RUNNER_CONTAINER_PROVIDER"); + switch (containerProvider) + { + case "docker": + trace.Info($"Registering DockerCommandManager as IDockerCommandManager"); + context.RegisterService(typeof(IContainerCommandManager), typeof(DockerCommandManager)); + break; + case "kubernetes": + trace.Info($"Registering KubernetesCommandManager as IDockerCommandManager"); + context.RegisterService(typeof(IContainerCommandManager), typeof(KubernetesCommandManager)); + break; + } + // If no environment variable is set, it will default to whatever it's defaulted in IContainerCommandManager + // which in this case it defaults to DockerCommandManager + } + public static async Task MainAsync(IHostContext context, string[] args) { Tracing trace = context.GetTrace(nameof(GitHub.Runner.Worker)); diff --git a/src/Test/L0/Worker/ActionManagerL0.cs b/src/Test/L0/Worker/ActionManagerL0.cs index 5334b236f2a..a8a320f12c9 100644 --- a/src/Test/L0/Worker/ActionManagerL0.cs +++ b/src/Test/L0/Worker/ActionManagerL0.cs @@ -26,7 +26,7 @@ public sealed class ActionManagerL0 private const string TestDataFolderName = "TestData"; private CancellationTokenSource _ecTokenSource; private Mock _configurationStore; - private Mock _dockerManager; + private Mock _containerManager; private Mock _ec; private Mock _jobServer; private Mock _pluginManager; @@ -2149,11 +2149,11 @@ private void Setup([CallerMemberName] string name = "", bool enableComposite = t _ec.Setup(x => x.AddIssue(It.IsAny(), It.IsAny())).Callback((Issue issue, string message) => { _hc.GetTrace().Info($"[{issue.Type}]{issue.Message ?? message}"); }); _ec.Setup(x => x.GetGitHubContext("workspace")).Returns(Path.Combine(_workFolder, "actions", "actions")); - _dockerManager = new Mock(); - _dockerManager.Setup(x => x.DockerPull(_ec.Object, "ubuntu:16.04")).Returns(Task.FromResult(0)); - _dockerManager.Setup(x => x.DockerPull(_ec.Object, "ubuntu:100.04")).Returns(Task.FromResult(1)); + _containerManager = new Mock(); + _containerManager.Setup(x => x.DockerPull(_ec.Object, "ubuntu:16.04")).Returns(Task.FromResult(0)); + _containerManager.Setup(x => x.DockerPull(_ec.Object, "ubuntu:100.04")).Returns(Task.FromResult(1)); - _dockerManager.Setup(x => x.DockerBuild(_ec.Object, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(Task.FromResult(0)); + _containerManager.Setup(x => x.DockerBuild(_ec.Object, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(Task.FromResult(0)); _jobServer = new Mock(); _jobServer.Setup(x => x.ResolveActionDownloadInfoAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) @@ -2180,7 +2180,7 @@ private void Setup([CallerMemberName] string name = "", bool enableComposite = t var actionManifest = new ActionManifestManager(); actionManifest.Initialize(_hc); - _hc.SetSingleton(_dockerManager.Object); + _hc.SetSingleton(_containerManager.Object); _hc.SetSingleton(_jobServer.Object); _hc.SetSingleton(_pluginManager.Object); _hc.SetSingleton(actionManifest); diff --git a/src/Test/L0/Worker/StepHostL0.cs b/src/Test/L0/Worker/StepHostL0.cs index 8d0a102efc6..2374461ea9d 100644 --- a/src/Test/L0/Worker/StepHostL0.cs +++ b/src/Test/L0/Worker/StepHostL0.cs @@ -13,7 +13,7 @@ namespace GitHub.Runner.Common.Tests.Worker public sealed class StepHostL0 { private Mock _ec; - private Mock _dc; + private Mock _dc; private TestHostContext CreateTestContext([CallerMemberName] String testName = "") { var hc = new TestHostContext(this, testName); @@ -24,7 +24,7 @@ private TestHostContext CreateTestContext([CallerMemberName] String testName = " var trace = hc.GetTrace(); _ec.Setup(x => x.Write(It.IsAny(), It.IsAny())).Callback((string tag, string message) => { trace.Info($"[{tag}]{message}"); }); - _dc = new Mock(); + _dc = new Mock(); hc.SetSingleton(_dc.Object); return hc; }