/// <summary> /// Removes a container (by name) using the Force option. /// </summary> /// <param name="dockerClient"></param> /// <param name="name"></param> /// <param name="logger"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static async Task ObliterateContainerAsync(this IDockerClient dockerClient, string name, ILogger logger = null, CancellationToken cancellationToken = new CancellationToken()) { //Get all of the containers var containers = await dockerClient.Containers.ListContainersAsync(new ContainersListParameters() { All = true }, cancellationToken); var container = containers.FindByName(name); if (container != null) { //Create the parameters var parameters = new ContainerRemoveParameters() { Force = true }; logger?.Information("Obliterating container {ContainerId} with image {ImageId}", container.ID, container.ImageID); //Delete it await dockerClient.Containers.RemoveContainerAsync(container.ID, parameters, cancellationToken); } }
/// <inheritdoc/> public async Task RemoveContainerAsync() { var removeOptions = new ContainerRemoveParameters { Force = true, RemoveVolumes = true }; try { await retryPolicy .ExecuteAsync(async() => { await _client.Containers .RemoveContainerAsync(Instance.Id, removeOptions); foreach (string network in _settings.Networks) { await RemoveNetworkIfUnused(network); } }); } catch (Exception ex) { throw new ContainerException( $"Error in RemoveContainer: {_settings.UniqueContainerName}", ex); } }
internal static async Task <bool> RemoveContainerWithName(string containerName) { DockerClient client = new DockerClientConfiguration( new Uri("npipe://./pipe/docker_engine")) .CreateClient(); var containerList = client.Containers.ListContainersAsync(new ContainersListParameters() { }).Result; foreach (var container in containerList) { if (container.Names.Contains("/" + containerName)) { var removeParams = new ContainerRemoveParameters() { Force = true }; await client.Containers.RemoveContainerAsync(container.ID, removeParams); return(true); } } return(false); }
public static async Task <bool> dockerCleanup() { var containers = ListContainersAsync().Result; foreach (var container in containers) { foreach (var containerName in container.Names) { //logger.Info("NAME {0}", containerName); if (containerName.ToUpper().Contains("EOSCDT")) { logger.Info("Remove container {0}", containerName); ContainerRemoveParameters removeSettings = new ContainerRemoveParameters() { Force = true, RemoveLinks = false, RemoveVolumes = false }; await client.Containers.StopContainerAsync(container.ID, new ContainerStopParameters { }); await client.Containers.RemoveContainerAsync(container.ID, removeSettings, default(CancellationToken)); logger.Info("done"); } } } return(true); }
/// <summary> /// Removes a container (by name) using the Force option. /// </summary> /// <param name="dockerClient"></param> /// <param name="names"></param> /// <param name="logger"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static async Task ObliterateContainersAsync(this IDockerClient dockerClient, string[] names, ILogger logger = null, CancellationToken cancellationToken = new CancellationToken()) { //Get all of the containers var containers = await dockerClient.Containers.ListContainersAsync(new ContainersListParameters() { All = true }, cancellationToken); //Find all of the application containers (should should be one) var containersToDelete = containers.FindByNames(names); //Create the parameters var parameters = new ContainerRemoveParameters() { Force = true }; //Delete each one foreach (var container in containersToDelete) { logger?.Information("Removing application container {ContainerId} with image {ImageId}", container.ID, container.ImageID); //Delete it await dockerClient.Containers.RemoveContainerAsync(container.ID, parameters, cancellationToken); } }
public virtual void Dispose() { var removeParameters = new ContainerRemoveParameters(); removeParameters.Force = true; Client.Containers.RemoveContainerAsync(ID, removeParameters).Wait(); Client.Dispose(); }
public async Task RemoveContainerAsync(string name, CancellationToken token = default) { var ids = await FindContainerIdsAsync(name).ConfigureAwait(false); var containerRemoveParameters = new ContainerRemoveParameters { Force = true, RemoveVolumes = true }; var removeTasks = ids.Select(x => client.Containers.RemoveContainerAsync(x, containerRemoveParameters, token)); await Task.WhenAll(removeTasks); }
private static async Task RemoveContainer(ContainerListResponse container) { var removeOptions = new ContainerRemoveParameters { Force = true, RemoveVolumes = true }; await _client.Containers .RemoveContainerAsync(container.ID, removeOptions); }
/// <summary> /// Create a new <see cref="RemoveContainer"/> message. /// </summary> /// <param name="containerId"> /// The name or Id of the container to remove. /// </param> /// <param name="parameters"> /// Optional <see cref="ContainerRemoveParameters"/> to control operation behaviour. /// </param> /// <param name="correlationId"> /// An optional message correlation Id. /// </param> public RemoveContainer(string containerId, string correlationId = null, ContainerRemoveParameters parameters = null) : base(correlationId) { if (String.IsNullOrWhiteSpace(containerId)) { throw new ArgumentException($"Argument cannot be null, empty, or entirely composed of whitespace: {nameof(containerId)}.", nameof(containerId)); } ContainerId = containerId; Parameters = parameters ?? new ContainerRemoveParameters(); }
public async Task ExecuteAsync(CancellationToken token) { var parameters = new ContainerRemoveParameters(); long exitCode = await this.GetModuleExitCode(); if (exitCode != 0) { await this.TailLogsAsync(exitCode); } await this.client.Containers.RemoveContainerAsync(this.module.Name, parameters, token); }
public Task RemoveContainerAsync(string id, ContainerRemoveParameters parameters) { if (string.IsNullOrEmpty(id)) { throw new ArgumentNullException(nameof(id)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } IQueryString queryParameters = new QueryString <ContainerRemoveParameters>(parameters); return(this._client.MakeRequestAsync(new[] { NoSuchContainerHandler }, HttpMethod.Delete, $"containers/{id}", queryParameters)); }
public async Task DeleteContainerIfExistsByName(string name) { var container = await FindContainerByName(name); if (container == null) { return; } using (var client = GetClient()) { var p = new ContainerRemoveParameters(); p.Force = true; await client.Containers.RemoveContainerAsync(container.ID, p); } }
/// <summary> /// Removes container and deletes image /// </summary> /// <param name="client">Docker client</param> /// <param name="name">Container name</param> /// <param name="image">Image name</param> /// <returns>Task</returns> public static async Task CleanupContainerAsync(this IDockerClient client, string name, string image) { var removeParams = new ContainerRemoveParameters { Force = true }; await Safe(() => client.Containers.RemoveContainerAsync(name, removeParams)); var imageParams = new ImageDeleteParameters { Force = true, PruneChildren = true }; await Safe(() => client.Images.DeleteImageAsync(image, imageParams)); }
public async Task CleanupProcess(ILogger logger) { var container = await this.container(); logger.LogInformation($"Stopping container:{this.SafeName}"); await this.stopContainer(container.ID); var rmPara = new ContainerRemoveParameters(); rmPara.Force = true; logger.LogInformation($"Removing container:{this.SafeName}"); await this.client.Containers.RemoveContainerAsync(container.ID, rmPara, this.cancelTokenSource.Token); var delPara = new ImageDeleteParameters(); delPara.Force = true; logger.LogInformation($"Removing image:{container.Image}"); await this.client.Images.DeleteImageAsync(container.Image, delPara, this.cancelTokenSource.Token); }
static async Task RemoveContainer(IDockerClient client, TestConfig testConfig) { // get current list of containers (running or otherwise) where their name // matches what's given in the test settings IList <ContainerListResponse> containersList = await client.Containers.ListContainersAsync( new ContainersListParameters { All = true }); IEnumerable <ContainerListResponse> toBeRemoved = containersList .Where(c => c.Names.Contains($"/{testConfig.Name}")); // blow them away! var removeParams = new ContainerRemoveParameters { Force = true }; await Task.WhenAll(toBeRemoved.Select(c => client.Containers.RemoveContainerAsync(c.ID, removeParams))); }
public async Task <bool> DeleteContainerAsync(string id) { using var connection = await _dockerClient.ConnectAsync(); var containers = connection.Containers; try { var request = new ContainerRemoveParameters { Force = true }; await containers.RemoveContainerAsync(id, request); _logger.LogInformation("Successfully deleted container with id '{Id}'.", id); return(true); } catch (Exception ex) { _logger.LogWarning(ex, "Could not delete container with id '{Id}'.", id); return(false); } }
private async void button11_Click(object sender, EventArgs e) { int selectednum = listBox1.SelectedIndex; if (selectednum == -1) { return; } string id = listBox1.SelectedItem.ToString(); IList <ContainerListResponse> containers = await client.Containers.ListContainersAsync( new ContainersListParameters() { Limit = 10, }); foreach (ContainerListResponse c in containers) { if (c.ID.Substring(0, 12) == id) { id = c.ID; } } if (id.Length == 12) { MessageBox.Show("出现错误", "Error", MessageBoxButtons.OK); return; } ContainerRemoveParameters crp = new ContainerRemoveParameters { Force = true, RemoveVolumes = true }; await client.Containers.RemoveContainerAsync(id, crp); MessageBox.Show("已经发出指令", "Success", MessageBoxButtons.OK); }
/// <summary> /// Run a container. Does NOT pull the container - the assumption is that /// the container already exists.. /// </summary> /// <param name="image"></param> /// <param name="entrypoint"></param> /// <param name="args"></param> /// <param name="volumes"></param> /// <param name="environment"></param> /// <param name="workingDir"></param> /// <param name="cancelToken"></param> /// <returns></returns> public async Task RunContainerAsync(string image, string entrypoint, IEnumerable <string> args, IReadOnlyList <Volume> volumes, Dictionary <string, string> environment, string workingDir, CancellationToken cancelToken) { CreateContainerParameters parameters = new CreateContainerParameters() { Image = image, Entrypoint = entrypoint.ToEnumerable().AppendMany(args).ToList(), Env = environment?.Select((x, y) => $"{x}={y}")?.ToList(), Tty = false, HostConfig = new HostConfig() { Binds = volumes.Select(v => $"{v.SourcePath}:{v.DestinationPath}").ToList() }, WorkingDir = workingDir }; // Create the container. CreateContainerResponse container = await client.Containers.CreateContainerAsync(parameters, cancelToken); try { // Report any warnings from the docker daemon. foreach (string warning in container.Warnings) { warningHandler(warning); } // Start the container, and wait for it to exit. await client.Containers.StartContainerAsync(container.ID, new ContainerStartParameters(), cancelToken); // Watch stdout and/or stderr as necessary. Task stdoutListener = WatchStdoutStreamAsync(container.ID, cancelToken); Task stderrListener = WatchStderrStreamAsync(container.ID, cancelToken); // Wait for the container to exit. ContainerWaitResponse waitResponse = await client.Containers.WaitContainerAsync(container.ID, cancelToken); // Wait for output listeners if cancellation has not been requested. if (!cancelToken.IsCancellationRequested) { await stdoutListener.ConfigureAwait(false); await stderrListener.ConfigureAwait(false); } // If cancellation isn't requested, ensure the container exited gracefully. if (!cancelToken.IsCancellationRequested && waitResponse.StatusCode != 0) { (string stdout, string stderr) = await GetContainerLogsAsync(container.ID, parameters.Tty, cancelToken); StringBuilder output = new StringBuilder(); output.AppendLine(stdout); output.AppendLine(stderr); throw new Exception($"Container exited with non-zero exit code. Container log:\n{output}"); } } finally { ContainerRemoveParameters removeParameters = new ContainerRemoveParameters() { RemoveVolumes = true, Force = true }; ContainerKillParameters killParameters = new ContainerKillParameters() { }; // Only attempt to kill the container if it's still running. if (await IsRunning(container.ID)) { await client.Containers.KillContainerAsync(container.ID, killParameters); } await client.Containers.RemoveContainerAsync(container.ID, removeParameters); } }
public static void RemoveContainer(this IContainerOperations operations, string name, ContainerRemoveParameters parameters) { operations.RemoveContainerAsync(name, parameters).Wait(); }
internal void RemoveContainer(string id) { var parameter = new ContainerRemoveParameters(); _client.Containers.RemoveContainerAsync(id, parameter).Wait(); }