private static IImage CreateDefaultImage(IDockerClient dockerClient, ILoggerFactory loggerFactory) { return(new GenericImage(dockerClient, loggerFactory) { ImageName = $"{DefaultImage}:{DefaultTag}" }); }
RuntimeInfoProvider(IDockerClient client, string operatingSystemType, string architecture, string version) { this.client = Preconditions.CheckNotNull(client, nameof(client)); this.operatingSystemType = string.IsNullOrWhiteSpace(operatingSystemType) ? CoreConstants.Unknown : operatingSystemType; this.architecture = string.IsNullOrWhiteSpace(architecture) ? CoreConstants.Unknown : architecture; this.version = string.IsNullOrWhiteSpace(version) ? CoreConstants.Unknown : version; }
/// <summary> /// Registers an image name to be cleaned up when this process exits /// </summary> /// <param name="imageName">image name to be deleted</param> /// <param name="dockerClient">docker client to be used for running the commands in the shutdown hook</param> public static void RegisterImageForCleanup(string imageName, IDockerClient dockerClient) { SetupShutdownHook(dockerClient); // todo: update ryuk to support image clean up // issue: https://github.com/testcontainers/moby-ryuk/issues/6 ImagesToDelete.Add(imageName); }
public ImageCreator(IDockerClient dockerClient, ICodeArchiver codeArchiver, ICodeSaver codeSaver) { this.dockerClient = dockerClient; this.codeArchiver = codeArchiver; this.codeSaver = codeSaver; }
internal DockerImage(IDockerClient client, IRunCommands commandFactory, DockerImageResult imageResult) { _client = client; _commandFactory = commandFactory; Id = imageResult.Id; Repository = imageResult.Repository; Tag = imageResult.Tag; }
/// <inheritdoc /> public UserDefinedNetwork(IDockerClient dockerClient, ILoggerFactory loggerFactory) { DockerClient = dockerClient; _logger = loggerFactory.CreateLogger <UserDefinedNetwork>(); _loggerFactory = loggerFactory; NetworkName = "testcontainers/" + Random.NextAlphaNumeric(16).ToLower(); }
internal DockerContainer(IDockerClient client, IRunCommands commandFactory, string containerId, IEnumerable <DockerPortMapping> portMappings) { _client = client; _commandFactory = commandFactory; Id = containerId; PortMappings = portMappings ?? new DockerPortMapping[0]; }
private static async Task <int> RunDocker(IDockerClient client, RunDockerCommand command, string callingContainerId, IOutputObserver outputObserver, CancellationToken cancellationToken) { var allowedMounts = await GetMounts(client, callingContainerId, cancellationToken); if (!(ValidateDockerCommand(command) && ValidateMounts(command.BindMounts, allowedMounts) is {} mounts)) { await Console.Error.WriteLineAsync("Could not validate docker command."); return(1); } var response = await client.Containers.CreateContainerAsync( new Docker.DotNet.Models.CreateContainerParameters { Image = command.ImageName, Env = command.Environment.Select(env => $"{env.Key}={env.Value}").ToList(), AttachStderr = true, AttachStdout = true, ArgsEscaped = false, Cmd = command.Command.ToList(), WorkingDir = command.CurrentDirectory, HostConfig = new Docker.DotNet.Models.HostConfig { AutoRemove = true, NetworkMode = "none", Isolation = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "process" : null, Mounts = mounts, }, }, cancellationToken ); using var stream = await client.Containers.AttachContainerAsync( response.ID, tty : false, new Docker.DotNet.Models.ContainerAttachParameters { Stream = true, Stderr = true, Stdout = true, }, cancellationToken ); await client.Containers.StartContainerAsync( response.ID, new Docker.DotNet.Models.ContainerStartParameters { }, cancellationToken ); await DockerHelpers.PipeContainerOutput(outputObserver, stream, cancellationToken); var waitResponse = await client.Containers.WaitContainerAsync(response.ID, cancellationToken); return((int)waitResponse.StatusCode); }
public async static Task <RuntimeInfoProvider> CreateAsync(IDockerClient client) { Preconditions.CheckNotNull(client, nameof(client)); // get system information from docker SystemInfoResponse info = await client.System.GetSystemInfoAsync(); return(new RuntimeInfoProvider(client, info.OSType, info.Architecture)); }
public SessionHostContainerConfiguration( VmConfiguration vmConfiguration, MultiLogger logger, Interfaces.ISystemOperations systemOperations, IDockerClient dockerClient, SessionHostsStartInfo sessionHostsStartInfo) : base(vmConfiguration, logger, systemOperations, sessionHostsStartInfo) { _dockerClient = dockerClient; }
public NetworkTest(NetworkCompositionResource resource) { _resource = resource; _dockerClient = new DockerClientConfiguration( LocalDockerUri(), null, TimeSpan.FromMinutes(5)) .CreateClient(); }
public Task <string> GetImage(IDockerClient dockerClient) { if (this.tag == null) { this.tag = this.buildDockerProject(this.projectFile); } return(Task.FromResult(this.tag)); }
public DockerImagesDownloader( IDockerClient dockerClient, IOptions <StartSettings> options, ILogger <DockerImagesDownloader> logger) { this.dockerClient = dockerClient; this.options = options; this.logger = logger; }
/// <summary> /// This is intended for use in a development scenario. This is so the command line can create a /// </summary> /// <param name="dockerClient"></param> /// <param name="imageId"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <CreateContainerResponse> CreateContainerForDirectAsync(IDockerClient dockerClient, string imageId, CancellationToken cancellationToken) { var createContainerParameters = new CreateContainerParameters { Image = imageId, HostConfig = new HostConfig() { Mounts = new List <Mount>() { new Mount() { Type = "bind", Source = "/mnt/boot/", Target = "/mnt/boot/", }, new Mount() { Type = "bind", Source = "/mnt/data/resin-data/resin-supervisor", Target = "/data" }, new Mount() { Type = "bind", Source = "/mnt/boot/config.json", Target = "/boot/config.json", }, new Mount() { Type = "bind", Source = "/", Target = "/mnt/root" } }, Binds = new List <string>() { "/var/run/balena.sock:/var/run/balena.sock", }, RestartPolicy = new RestartPolicy { Name = RestartPolicyKind.Always }, }, Name = DockerContainerNames.AgentA, Env = new List <string>() { "DOCKER_SOCKET=/var/run/balena.sock", "DOCKER_ROOT=/mnt/root/var/lib/docker", "BOOT_MOUNTPOINT=/mnt/boot", "container=docker" }, }; //Create the container return(await dockerClient.Containers.CreateContainerAsync(createContainerParameters, cancellationToken)); }
/// <summary> /// Gets the first container with the given image id. /// </summary> /// <param name="client"></param> /// <param name="imageId"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static async Task <ContainerListResponse> GetContainerByImageId(this IDockerClient client, string imageId, CancellationToken cancellationToken) { var allContainers = await client.Containers.ListContainersAsync(new ContainersListParameters { All = true }, cancellationToken); return(allContainers.FirstOrDefault(c => c.ImageID == imageId)); }
public DockerEvents(IDockerClient docker) { _observers = new ObservableHelper <DockerEvent>(); _cancelSource = new CancellationTokenSource(); Task.Run(() => docker.System.MonitorEventsAsync( new ContainerEventsParameters(), this, _cancelSource.Token )); }
/// <summary> /// Attemmpts to get a container by its name. /// </summary> /// <param name="client"></param> /// <param name="name"></param> /// <param name="cancellationToken"></param> /// <returns>The container if it is found, null otherwise.</returns> public static async Task <ContainerListResponse> GetContainerByName(this IDockerClient client, string name, CancellationToken cancellationToken) { var allContainers = await client.Containers.ListContainersAsync(new ContainersListParameters { All = true }, cancellationToken); return(allContainers.FindByName(name)); }
public ResourceReaperTests() { _container = new ContainerBuilder <GenericContainer>() .ConfigureHostConfiguration(builder => builder.AddInMemoryCollection()) .ConfigureAppConfiguration((context, builder) => builder.AddInMemoryCollection()) .ConfigureDockerImageName(PlatformHelper.GetPlatform().TinyDockerImage) .Build(); _dockerClient = new DockerClientFactory().Create(); }
static async Task <IReadOnlyList <AllowedMount> > GetMounts(IDockerClient client, string containerId, CancellationToken cancellationToken) { var info = await client.Containers.InspectContainerAsync(containerId, cancellationToken); return(info.Mounts.Select(mount => new AllowedMount { BasePath = mount.Destination, RealPath = mount.Source, ReadWrite = mount.RW, }).ToList()); }
/// <summary> /// Called when the actor is stopping. /// </summary> protected override void PostStop() { if (_client != null) { _client.Dispose(); _client = null; } base.PostStop(); }
public ApplicationUpdateService( IDockerClient dockerClient, ApplicationDockerContainerFactory dockerContainerFactory, DeviceApiClient deviceApiClient, ILogger logger) : base(logger, dockerClient) { _dockerClient = dockerClient ?? throw new ArgumentNullException(nameof(dockerClient)); _dockerContainerFactory = dockerContainerFactory ?? throw new ArgumentNullException(nameof(dockerContainerFactory)); _deviceApiClient = deviceApiClient ?? throw new ArgumentNullException(nameof(deviceApiClient)); }
public ResourceReaperTests() { _container = new ContainerBuilder <GenericContainer>() .ConfigureHostConfiguration(builder => builder.AddInMemoryCollection()) .ConfigureAppConfiguration((context, builder) => builder.AddInMemoryCollection()) .ConfigureDockerImageName($"{GenericContainer.DefaultImage}:{GenericContainer.DefaultTag}") .Build(); _dockerClient = ((GenericContainer)_container).DockerClient; }
public DockerContainerEngine( VmConfiguration vmConfiguration, MultiLogger logger, Core.Interfaces.ISystemOperations systemOperations, IDockerClient dockerClient = null, bool shouldPublicPortMatchGamePort = false) : base(vmConfiguration, logger, systemOperations) { _dockerClient = dockerClient ?? CreateDockerClient(); _shouldPublicPortMatchGamePort = shouldPublicPortMatchGamePort; }
private static IImage CreateDefaultImage(IDockerClient dockerClient, ILoggerFactory loggerFactory) { return(new ImageBuilder <DockerfileImage>() .ConfigureImage((context, image) => { image.DockerfilePath = "Dockerfile"; image.DeleteOnExit = true; image.BasePath = "../../../../../db"; }) .Build()); }
private async Task PullDockerImages(IDockerClient client) { await client.Images .CreateImageAsync(new Docker.DotNet.Models.ImagesCreateParameters { FromImage = "mcr.microsoft.com/dotnet/aspnet", Tag = "5.0" }, new AuthConfig(), new Progress <JSONMessage>()); }
public ProgramRunner( ISolutionsBase solutionsBase, IDockerClient dockerClient, RunningSettings runningSettings, ILogger <ProgramRunner> logger) { this.solutionsBase = solutionsBase; this.dockerClient = dockerClient; this.runningSettings = runningSettings; this.logger = logger; }
/// <summary> /// Create a new Docker API <see cref="Client"/> actor for the specified <see cref="Connect"/> request. /// </summary> /// <param name="connectRequest"> /// The <see cref="Connect"/> request message. /// </param> /// <returns> /// A reference to the <see cref="Client"/> actor, and the API version. /// </returns> async Task <(IActorRef, Version)> CreateClientAsync(Connect connectRequest) { if (connectRequest == null) { throw new ArgumentNullException(nameof(connectRequest)); } DockerClientConfiguration clientConfiguration = new DockerClientConfiguration( endpoint: connectRequest.EndpointUri, credentials: connectRequest.Credentials ); IDockerClient dockerClient = clientConfiguration.CreateClient(); VersionResponse versionInfo; try { versionInfo = await dockerClient.Miscellaneous.GetVersionAsync(); } catch (TimeoutException connectionTimedOut) { // TODO: More specific exception type. throw new Exception($"Failed to connect to the Docker API at '{connectRequest.EndpointUri}' (connection timed out).", innerException: connectionTimedOut ); } Version apiVersion = new Version(versionInfo.APIVersion); if (apiVersion < MinimumDockerApiVersion) { throw new NotSupportedException($"The Docker API at '{connectRequest.EndpointUri}' is v{apiVersion}, but AK/DK only supports v{MinimumDockerApiVersion} or newer."); } Log.Debug("Successfully connected to Docker API (v{0}) at '{1}'.", apiVersion, connectRequest.EndpointUri); IActorRef clientActor = Context.ActorOf( Props.Create <Client>( Connection.Create(dockerClient) // TODO: Add constructor overload to inject configuration instead of client; let Client create the DockerClient (except in tests). ), name: $"client-{_nextClientId++}" ); Log.Debug("Created client '{0}' for connection request for '{1}' from '{2}' (CorrelationId = '{3}').", clientActor.Path, Sender.Path, connectRequest.EndpointUri, connectRequest.CorrelationId ); return(clientActor, apiVersion); }
/// <summary> /// Create a new <see cref="Connection"/> actor. /// </summary> /// <param name="client"> /// The underlying docker API client. /// </param> public Connection(IDockerClient client) { if (client == null) { throw new ArgumentNullException(nameof(client)); } _client = client; Become(Ready); }
public DockerContainer( string image, string tag, Func <CancellationToken, Task <bool> > healthCheck, params int[] ports) { _dockerClient = s_dockerClientConfiguration.CreateClient(); _ports = ports; _image = image; _tag = tag; _healthCheck = healthCheck; }
private async Task CreateContainerAsync(IDockerClient client) { var hostConfig = ToHostConfig(); var config = ToConfig(); await client.Containers.CreateContainerAsync(new CreateContainerParameters(config) { Image = ImageName, Name = ContainerName, Tty = true, HostConfig = hostConfig }); }
public ContainerFactory(IDockerClient client) { this.client = client; }
public MongoDbContainer(IDockerClient client, string name) : base(client, DockerImage) { _name = name; }
public MongoDbContainer(IDockerClient client, string name, string id) : this(client, name) { Id = id; }