Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Docker Plug-in] Don't pull image if already exists unless forced #895

Merged
merged 2 commits into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions src/TaskManager/Plug-ins/Docker/DockerPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/

using System.Globalization;
using Amazon.Runtime.Internal.Transform;
using Ardalis.GuardClauses;
using Docker.DotNet;
using Docker.DotNet.Models;
Expand Down Expand Up @@ -50,7 +51,7 @@
ValidateEvent();
Initialize();

_hostTemporaryStoragePath = Environment.GetEnvironmentVariable(Strings.HostTemporaryStorageEnvironmentVariableName) ?? throw new ApplicationException($"Environment variable {Strings.HostTemporaryStorageEnvironmentVariableName} is not set.");

Check warning on line 54 in src/TaskManager/Plug-ins/Docker/DockerPlugin.cs

View workflow job for this annotation

GitHub Actions / sonarscanner

'System.ApplicationException' should not be thrown by user code. (https://rules.sonarsource.com/csharp/RSPEC-112)
var dockerClientFactory = _scope.ServiceProvider.GetService<IDockerClientFactory>() ?? throw new ServiceNotFoundException(nameof(IDockerClientFactory));
_dockerClient = dockerClientFactory.CreateClient(new Uri(Event.TaskPluginArguments[Keys.BaseUrl]));
}
Expand Down Expand Up @@ -132,13 +133,17 @@

try
{
var imageCreateParameters = new ImagesCreateParameters()
var alwaysPull = Event.TaskPluginArguments.ContainsKey(Keys.AlwaysPull) && Event.TaskPluginArguments[Keys.AlwaysPull].Equals("true", StringComparison.OrdinalIgnoreCase);
if (alwaysPull || !await ImageExistsAsync(cancellationToken).ConfigureAwait(false))
{
FromImage = Event.TaskPluginArguments[Keys.ContainerImage],
};

// Pull image.
await _dockerClient.Images.CreateImageAsync(imageCreateParameters, new AuthConfig(), new Progress<JSONMessage>(), cancellationToken).ConfigureAwait(false);
// Pull image.
_logger.ImageDoesNotExist(Event.TaskPluginArguments[Keys.ContainerImage]);
var imageCreateParameters = new ImagesCreateParameters()
{
FromImage = Event.TaskPluginArguments[Keys.ContainerImage],
};
await _dockerClient.Images.CreateImageAsync(imageCreateParameters, new AuthConfig(), new Progress<JSONMessage>(), cancellationToken).ConfigureAwait(false);
}
}
catch (Exception exception)
{
Expand Down Expand Up @@ -199,6 +204,20 @@
};
}

private async Task<bool> ImageExistsAsync(CancellationToken cancellationToken)
{
var imageListParameters = new ImagesListParameters
{
Filters = new Dictionary<string, IDictionary<string, bool>>
{
{ "reference", new Dictionary<string, bool> { { Event.TaskPluginArguments[Keys.ContainerImage], true } } }
}
};

var results = await _dockerClient.Images.ListImagesAsync(imageListParameters, cancellationToken);
return results?.Any() ?? false;
}

public override async Task<ExecutionStatus> GetStatus(string identity, TaskCallbackEvent callbackEvent, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(identity, nameof(identity));
Expand Down Expand Up @@ -267,7 +286,7 @@

TimeSpan? duration = null;

if (DateTime.TryParse(response.State.FinishedAt, out var completedTime))

Check warning on line 289 in src/TaskManager/Plug-ins/Docker/DockerPlugin.cs

View workflow job for this annotation

GitHub Actions / sonarscanner

Use a format provider when parsing date and time. (https://rules.sonarsource.com/csharp/RSPEC-6580)
{
duration = completedTime.Subtract(response.Created);
}
Expand Down Expand Up @@ -324,7 +343,7 @@

var envvars = new List<string>();

foreach (var key in Event.TaskPluginArguments.Keys)

Check warning on line 346 in src/TaskManager/Plug-ins/Docker/DockerPlugin.cs

View workflow job for this annotation

GitHub Actions / sonarscanner

Loops should be simplified using the "Where" LINQ method (https://rules.sonarsource.com/csharp/RSPEC-3267)
{
if (key.StartsWith(Keys.EnvironmentVariableKeyPrefix, false, CultureInfo.InvariantCulture))
{
Expand Down
5 changes: 5 additions & 0 deletions src/TaskManager/Plug-ins/Docker/Keys.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ internal static class Keys
/// </summary>
public static readonly string Command = "command";

/// <summary>
/// Key to indicate whether to always pull the image.
/// </summary>
public static readonly string AlwaysPull = "always_pull";

/// <summary>
/// Key for task timeout value.
/// </summary>
Expand Down
3 changes: 3 additions & 0 deletions src/TaskManager/Plug-ins/Docker/Logging/Log.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,5 +100,8 @@ public static partial class Log

[LoggerMessage(EventId = 1026, Level = LogLevel.Error, Message = "Error terminating container '{container}'.")]
public static partial void ErrorTerminatingContainer(this ILogger logger, string container, Exception ex);

[LoggerMessage(EventId = 1027, Level = LogLevel.Information, Message = "Image does not exist '{image}' locally, attempting to pull.")]
public static partial void ImageDoesNotExist(this ILogger logger, string image);
}
}
89 changes: 89 additions & 0 deletions tests/UnitTests/TaskManager.Docker.Tests/DockerPluginTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,95 @@ public async Task ExecuteTask_WhenFailedToMonitorContainer_ExpectTaskToBeAccepte
runner.Dispose();
}

[Fact(DisplayName = "ExecuteTask - do not pull the image when the specified image exists")]
public async Task ExecuteTask_WhenImageExists_ExpectNotToPull()
{
var payloadFiles = new List<VirtualFileInfo>()
{
new VirtualFileInfo( "file.dcm", "path/to/file.dcm", "etag", 1000)
};
var contianerId = Guid.NewGuid().ToString();

_dockerClient.Setup(p => p.Images.CreateImageAsync(
It.IsAny<ImagesCreateParameters>(),
It.IsAny<AuthConfig>(),
It.IsAny<IProgress<JSONMessage>>(),
It.IsAny<CancellationToken>()));
_dockerClient.Setup(p => p.Images.ListImagesAsync(
It.IsAny<ImagesListParameters>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<ImagesListResponse>() { new ImagesListResponse() });
_dockerClient.Setup(p => p.Containers.CreateContainerAsync(
It.IsAny<CreateContainerParameters>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new CreateContainerResponse { ID = contianerId, Warnings = new List<string>() { "warning" } });

_storageService.Setup(p => p.ListObjectsAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(payloadFiles);
_storageService.Setup(p => p.GetObjectAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new MemoryStream(Encoding.UTF8.GetBytes("hello")));

var message = GenerateTaskDispatchEventWithValidArguments();

var runner = new DockerPlugin(_serviceScopeFactory.Object, _logger.Object, message);
var result = await runner.ExecuteTask(CancellationToken.None).ConfigureAwait(false);

_dockerClient.Verify(p => p.Images.CreateImageAsync(
It.IsAny<ImagesCreateParameters>(),
It.IsAny<AuthConfig>(),
It.IsAny<IProgress<JSONMessage>>(),
It.IsAny<CancellationToken>()), Times.Never());
_dockerClient.Verify(p => p.Images.ListImagesAsync(
It.IsAny<ImagesListParameters>(),
It.IsAny<CancellationToken>()), Times.Once());
runner.Dispose();
}

[Fact(DisplayName = "ExecuteTask - pull the image when force by the user even the specified image exists")]
public async Task ExecuteTask_WhenAlwaysPullIsSet_ExpectToPullEvenWhenImageExists()
{
var payloadFiles = new List<VirtualFileInfo>()
{
new VirtualFileInfo( "file.dcm", "path/to/file.dcm", "etag", 1000)
};
var contianerId = Guid.NewGuid().ToString();

_dockerClient.Setup(p => p.Images.CreateImageAsync(
It.IsAny<ImagesCreateParameters>(),
It.IsAny<AuthConfig>(),
It.IsAny<IProgress<JSONMessage>>(),
It.IsAny<CancellationToken>()));
_dockerClient.Setup(p => p.Images.ListImagesAsync(
It.IsAny<ImagesListParameters>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<ImagesListResponse>() { new ImagesListResponse() });
_dockerClient.Setup(p => p.Containers.CreateContainerAsync(
It.IsAny<CreateContainerParameters>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new CreateContainerResponse { ID = contianerId, Warnings = new List<string>() { "warning" } });

_storageService.Setup(p => p.ListObjectsAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(payloadFiles);
_storageService.Setup(p => p.GetObjectAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new MemoryStream(Encoding.UTF8.GetBytes("hello")));

var message = GenerateTaskDispatchEventWithValidArguments();
message.TaskPluginArguments.Add(Keys.AlwaysPull, bool.TrueString);

var runner = new DockerPlugin(_serviceScopeFactory.Object, _logger.Object, message);
var result = await runner.ExecuteTask(CancellationToken.None).ConfigureAwait(false);

_dockerClient.Verify(p => p.Images.CreateImageAsync(
It.IsAny<ImagesCreateParameters>(),
It.IsAny<AuthConfig>(),
It.IsAny<IProgress<JSONMessage>>(),
It.IsAny<CancellationToken>()), Times.Once());
_dockerClient.Verify(p => p.Images.ListImagesAsync(
It.IsAny<ImagesListParameters>(),
It.IsAny<CancellationToken>()), Times.Never());
runner.Dispose();
}

[Fact(DisplayName = "ExecuteTask - when called with a valid event expect task to be accepted and monitored in the background")]
public async Task ExecuteTask_WhenCalledWithValidEvent_ExpectTaskToBeAcceptedAndMonitored()
{
Expand Down
Loading