public async Task <string> Post(string containerName) { try { DockerClient client = new DockerClientConfiguration(new Uri("unix:///var/run/docker.sock")).CreateClient(); await client.Containers.RestartContainerAsync(containerName, new ContainerRestartParameters() { WaitBeforeKillSeconds = 10 }); IList <ContainerListResponse> containers = await client.Containers.ListContainersAsync( new ContainersListParameters() { Limit = 10, }); var cont = containers.FirstOrDefault(f => f.State == "running" && f.Names.FirstOrDefault() == $"/{containerName}"); return(cont.ID); } catch (Exception ex) { throw; } }
public async void CreateContainerTest() { var mongoDbImageName = "mongo"; var mongoDbImageTag = "4.0"; var mongodDbImage = $"{mongoDbImageName}:{mongoDbImageTag}"; var mongoDbContainerName = "mongo-tests"; var exposedPort = "27017/tcp"; var hostPort = "33381"; DockerClient docker = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine")) .CreateClient(); await docker.CreateImageIfNotExist(mongoDbImageName, mongoDbImageTag); await docker.RemoveContainerIfExist(mongoDbContainerName); // docker run --name mongo-tests -p 33381:27017 -d mongo:4; var containerId = await docker.RunContainer(mongodDbImage, mongoDbContainerName, exposedPort, hostPort); await docker.WaitBeforeContainerInit(containerId); ContainerListResponse container = await docker.GetContainerByName(mongoDbContainerName); Assert.NotNull(container); await docker.RemoveContainerIfExist(mongoDbContainerName); docker.Dispose(); }
public async Task DisposeAsync() { // we need to wait for all the common locks to be released, otherwise an error will be throwed as we try to access a disposed object await Task.Delay((int)LoRaDevAddrCache.LockExpiry.TotalMilliseconds + 3000); if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("SYSTEM_DEFINITIONID"))) { if (!string.IsNullOrEmpty(this.containerId)) { // we are running locally var dockerConnection = System.Environment.OSVersion.Platform.ToString().Contains("Win") ? "npipe://./pipe/docker_engine" : "unix:///var/run/docker.sock"; using (var conf = new DockerClientConfiguration(new Uri(dockerConnection))) // localhost using (var client = conf.CreateClient()) { await client.Containers.RemoveContainerAsync(this.containerId, new ContainerRemoveParameters() { Force = true }); } } } this.redis?.Dispose(); this.redis = null; }
/// <summary> /// Connect to the given docker environment - Windows or Linux. Local or remote. /// </summary> public void ConnectToDocker() { Console.WriteLine("Enter the IP of Linux/ Windows machine with remote docker config enabled"); var machineIp = Console.ReadLine(); Console.WriteLine("Enter the port that Docker listens to"); var machinePort = Console.ReadLine(); try { if (!string.IsNullOrEmpty(machineIp) && !string.IsNullOrEmpty(machinePort)) { var uri = new Uri($"http://{machineIp}:{machinePort}"); var dockerClient = new DockerClientConfiguration(uri).CreateClient(); var containers = GetContainers(dockerClient).Result; Console.WriteLine("Select the docker container to monitor:"); containers.ForEach(x => Console.WriteLine(x.Names.First())); Console.WriteLine(); var containerName = Console.ReadLine(); GetContainerStats(dockerClient, containerName).Wait(); Console.ReadLine(); } } catch (Exception e) { Console.WriteLine(e); throw; } }
public async Task <IReadOnlyList <(ushort PortNumber, string Protocol)> > GetExposedPortsAsync(string image) { var client = new DockerClientConfiguration().CreateClient(); IDictionary <string, EmptyStruct>?exposedPorts = null; try { await client.Images.CreateImageAsync( new ImagesCreateParameters { FromImage = image, }, null, new Progress <JSONMessage>()); var inspectImage = await client.Images.InspectImageAsync(image).ConfigureAwait(false); exposedPorts = inspectImage.Config.ExposedPorts; } catch (DockerApiException) { } catch (HttpRequestException) { } if (exposedPorts == null) { return(Array.Empty <(ushort PortNumber, string Protocol)>()); } return(exposedPorts.Keys .Select(ParsePort) .ToList()); }
public static void BootSqlServerWithDockerClient(TestContext tc) { DockerClient client = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine")).CreateClient(); var response = client.Containers.CreateContainerAsync(new CreateContainerParameters { Image = "microsoft/mssql-server-linux", AttachStderr = true, AttachStdin = true, AttachStdout = true, Env = new[] { "ACCEPT_EULA=Y", $"SA_PASSWORD={s_saPassword}" }, ExposedPorts = new Dictionary <string, EmptyStruct>() { { "1433/tcp", new EmptyStruct() } }, HostConfig = new HostConfig { PortBindings = new Dictionary <string, IList <PortBinding> > { { "1433/tcp", new List <PortBinding> { new PortBinding { HostPort = 1433.ToString() } } } } } }).Result; s_runningSqlServerContainerID = response.ID; client.Containers.StartContainerAsync(s_runningSqlServerContainerID, new ContainerStartParameters { }).Wait(); }
public async Task ExecuteAsync() { var config = new DockerClientConfiguration(new Uri("tcp://yourip:2375")); DockerClient client = config.CreateClient(); var containers = await client.Containers.ListContainersAsync(new ContainersListParameters { Limit = 10 }); var container = await client.Containers.CreateContainerAsync(new CreateContainerParameters(new Config()) { Env = new List <string> { "PESQUISA=ANYTHING" }, Image = "YourImageName", Name = "YourContainerName", Cmd = new List <string> { "--net bridge" } }); await client.Containers.StartContainerAsync(container.ID, new ContainerStartParameters()); }
public LocalStackFixture() { DockerClientConfiguration config; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { config = new DockerClientConfiguration(new Uri("unix://var/run/docker.sock")); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // config = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine")); // LocalStack is linux only, we're skipping all tests if we're running in widows. IsWindows = true; return; } else { throw new NotSupportedException($"Unsupported OS [{RuntimeInformation.OSDescription}]"); } _client = config.CreateClient(); var rnd = new Random(); Port = rnd.Next(9000, 10000); }
/// <summary> /// Create a new <see cref="Deployer"/>. /// </summary> /// <param name="deployerOptions"> /// The deployer options. /// </summary> /// <param name="logger"> /// The deployer logger. /// </summary> public Deployer(IOptions <DeployerOptions> deployerOptions, ILogger <Deployer> logger) { if (deployerOptions == null) { throw new ArgumentNullException(nameof(deployerOptions)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } DeployerOptions options = deployerOptions.Value; Log = logger; LocalStateDirectory = new DirectoryInfo( Path.Combine(Directory.GetCurrentDirectory(), options.LocalStateDirectory) ); logger.LogInformation("Final value for LocalStateDirectory is '{LocalStateDirectory}'.", LocalStateDirectory.FullName ); HostStateDirectory = new DirectoryInfo( Path.Combine(Directory.GetCurrentDirectory(), options.HostStateDirectory) ); logger.LogInformation("Final value for HostStateDirectory is '{HostStateDirectory}'.", HostStateDirectory.FullName ); Client = new DockerClientConfiguration(options.DockerEndPoint) .CreateClient(); }
public async Task ShouldReturnConfigurationThatIsApplicableAndHighestPriority() { // arrange var mockConfig = new DockerClientConfiguration(new Uri("tcp://abcd")); // only 1 provider should return the mock config var provider1 = new MockDockerClientProvider(false, 1000, () => null, ct => Task.FromResult(true)); var provider2 = new MockDockerClientProvider(true, 1000, () => mockConfig, ct => Task.FromResult(true)); var provider3 = new MockDockerClientProvider(true, 100, () => null, ct => Task.FromResult(true)); var provider4 = new MockDockerClientProvider(true, 20000, () => null, ct => Task.FromResult(false)); var factory = new DockerClientFactory(new NullLogger <DockerClientFactory>(), new List <IDockerClientProvider> { provider1, provider2, provider3, provider4 }); // act var result = await factory.Create(); // assert Assert.Equal(mockConfig, result.Configuration); }
public DockerLabelDashboardItemProvider(IConfiguration config) { dockerEndpoint = config.GetValue <string>("DOCKER_SOCKET", "unix:///var/run/docker.sock"); dockerUri = new Uri(dockerEndpoint); cliConfig = new DockerClientConfiguration(dockerUri); client = cliConfig.CreateClient(); }
public static async Task FinalSwitchAsync(GameConfiguration gameConfiguration, string oldID, string newID) { using (DockerClient client = new DockerClientConfiguration( new Uri("unix:///var/run/docker.sock")) .CreateClient()) { try { // stop old container await client.Containers.StopContainerAsync(oldID, new ContainerStopParameters { WaitBeforeKillSeconds = 1 }); // start new contianer await client.Containers.StartContainerAsync(newID, new ContainerStartParameters { }); // delete old container await client.Containers.RemoveContainerAsync(oldID, new ContainerRemoveParameters { Force = true }); } catch (Exception) { // uh-oh, try to restart the old container await client.Containers.StartContainerAsync(oldID, new ContainerStartParameters { }); } } }
public TestFixture() { // Do not wait forever in case it gets stuck cts = new CancellationTokenSource(TimeSpan.FromMinutes(5)); cts.Token.Register(() => throw new TimeoutException("Docker.DotNet test timeout exception")); dockerClientConfiguration = new DockerClientConfiguration(); dockerClient = dockerClientConfiguration.CreateClient(); // Create image dockerClient.Images.CreateImageAsync( new ImagesCreateParameters { FromImage = _imageName, Tag = "latest" }, null, new Progress <JSONMessage>((m) => { Console.WriteLine(JsonConvert.SerializeObject(m)); Debug.WriteLine(JsonConvert.SerializeObject(m)); }), cts.Token).GetAwaiter().GetResult(); // Create local image tag to reuse var existingImagesResponse = dockerClient.Images.ListImagesAsync( new ImagesListParameters { Filters = new Dictionary <string, IDictionary <string, bool> > { ["reference"] = new Dictionary <string, bool> { [_imageName] = true } } }, cts.Token ).GetAwaiter().GetResult(); imageId = existingImagesResponse[0].ID; dockerClient.Images.TagImageAsync( imageId, new ImageTagParameters { RepositoryName = repositoryName, Tag = tag }, cts.Token ).GetAwaiter().GetResult(); // Init swarm if not part of one try { var result = dockerClient.Swarm.InitSwarmAsync(new SwarmInitParameters { AdvertiseAddr = "10.10.10.10", ListenAddr = "127.0.0.1" }, default).GetAwaiter().GetResult(); } catch { Console.WriteLine("Couldn't init a new swarm, node should take part of a existing one"); _wasSwarmInitialized = true; } }
internal async Task <IList <string> > ListProcessesAsync() { using var client = new DockerClientConfiguration().CreateClient(); var containerProcessesResponse = await client.Containers.ListProcessesAsync(_container.Id, new ContainerListProcessesParameters()); // each process is a list of strings, with last string being cmd return(containerProcessesResponse.Processes.Select(list => list[^ 1]).ToList());
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously public virtual async Task Notify(String pathChanged) { using (DockerClient client = new DockerClientConfiguration(new Uri(DockerNotifier.DOCKER_URI)).CreateClient()) { String dockerPath = m_Notifier.GetDockerDirectory(pathChanged); ContainerExecCreateResponse response = await client.Containers.ExecCreateContainerAsync(m_Notifier.m_Container, new ContainerExecCreateParameters { AttachStderr = false, AttachStdin = false, AttachStdout = m_HandleError, Cmd = new String[] { m_Shell, m_ShellOptions, String.Format(m_ShellCommand, dockerPath) }, Detach = false, Tty = false, User = "******", Privileged = true }); using (var stream = await client.Containers.StartAndAttachContainerExecAsync(response.ID, false, default(CancellationToken))) { if (m_HandleError) { await PostProcess(pathChanged, stream); } } m_Notifier.LogMessage($"Notify {pathChanged} mapped tp {dockerPath} has changed into {m_Notifier.m_Container}"); } }
private (string, string) RunWiremockImage(string port, string image, string tag) { var client = new DockerClientConfiguration() .CreateClient(); var isImageCreated = CreateImage(client, image, tag); var containerId = client.Containers.CreateContainerAsync(new CreateContainerParameters { Image = image, ExposedPorts = new Dictionary <string, EmptyStruct> { { "8080", new EmptyStruct() } }, HostConfig = new HostConfig { PortBindings = new Dictionary <string, IList <PortBinding> > { { "8080", new List <PortBinding> { new PortBinding { HostPort = port } } } }, } }).GetAwaiter().GetResult().ID; client.Containers.StartContainerAsync(containerId, new ContainerStartParameters()).GetAwaiter().GetResult(); return(containerId, isImageCreated ? image : null); }
private async Task CreateTestHarnessContainers( string neo4jUser, string neo4jPassword, int neo4jBoltPort, string sqlHost, int sqlPort, string sqlPassword ) { var dockerClient = new DockerClientConfiguration( RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? new Uri("npipe://./pipe/docker_engine") : new Uri("unix:///var/run/docker.sock") ).CreateClient(); // start Neo4j test instance // Bolt: 10087 // HTTP: 10074 await DockerContainer.On(dockerClient, _logger) .UseImage("neo4j") .SetName("neo4j_unittest_1") //.AddTcpPort(7474, 10074) .AddTcpPort(7687, neo4jBoltPort) .AddEnv("NEO4J_AUTH", $"{neo4jUser}/{neo4jPassword}") .Up(rebuildIfExists: true, waitForAllTcpPorts: true); // start Microsoft SQL test instance await DockerContainer.On(dockerClient, _logger) .UseImage("mcr.microsoft.com/mssql/server", "2017-latest") .SetName("mssql_unittest_1") .AddTcpPort(1433, sqlPort) .AddEnv("ACCEPT_EULA", "y") .AddEnv("SA_PASSWORD", sqlPassword) .Up(rebuildIfExists: true, waitForAllTcpPorts: true); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var dockerUrl = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? new Uri("npipe://./pipe/docker_engine") : new Uri("unix:/var/run/docker.sock"); var dockerClient = new DockerClientConfiguration(dockerUrl).CreateClient(); services .Configure <RunnersSettings>(this.Configuration.GetSection("Runners")); services .AddHostedService <DanglingImagesRemover>() .AddSingleton <IDockerClient>(dockerClient) .AddSingleton <ILanguageReader, LanguageReader>() .AddSingleton <IImageCreator, ImageCreator>() .AddSingleton <IImageRemover, ImageRemover>() .AddSingleton <ICodeSaver, CodeSaver>() .AddSingleton <ICodeArchiver, CodeArchiver>(); services .AddCors(); services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Image Service", Version = "v1" }); }); }
static async Task AsyncMain() { // var certificate = new X509Certificate2 ("/Users/jorikvanderwerf/.docker/machine/machines/xxx/cert.pem"); // var credentials = new CertificateCredentials(certificate); Console.WriteLine("==== Starting backup with configuration: ===="); Console.WriteLine($" - docker endpoint: {_appSettings.DockerRemoteApiUri}"); Console.WriteLine($" - AWS access key id: {_appSettings.AWSAccessKeyId.Substring(0, 4)}..."); Console.WriteLine($" - AWS secret access key: {_appSettings.AWSSecretAccessKey.Substring(0, 4)}..."); Console.WriteLine(); var client = new DockerClientConfiguration(new Uri(_appSettings.DockerRemoteApiUri)) .CreateClient(); var containers = await client.Containers.ListContainersAsync(new ContainersListParameters()); var containersRequiringBackups = containers.Where(x => x.Labels.ContainsKey("BACKUP")).ToList(); Console.WriteLine($"Found {containers.Count} countainers of which {containersRequiringBackups.Count} require backups"); foreach (var container in containersRequiringBackups) { await BackupContainerMounts(container, client); } }
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 async Task CanStartAContainerAsync() { var imageName = "nginx:latest"; DockerClient client = new DockerClientConfiguration().CreateClient(); client.Should().NotBeNull(); //var images = (await client.Images.ListImagesAsync(new ImagesListParameters { All = true })) // .Where(i => i.RepoTags.Any(t => t.Contains("alpine"))) // .Select(i => i.RepoTags.First()); //IList<ImagesListResponse> images = await client.Images.ListImagesAsync( // new ImagesListParameters() // { // All = true // }) ; //var image = images.FirstOrDefault(p => p.RepoTags.Any(p => p.Contains(imageName))); //var imageId = image.ID.Substring(image.ID.IndexOf(":") + 1, 12); //Create The Container var result = await client.Containers.CreateContainerAsync(new CreateContainerParameters { Image = imageName, ExposedPorts = new Dictionary <string, EmptyStruct> { { "8000", default } },
public async void CreateContainerAndWaitBeforeItStartedTest() { var mongoDbImageName = "mongo"; var mongoDbImageTag = "4.0"; var mongodDbImage = $"{mongoDbImageName}:{mongoDbImageTag}"; var mongoDbContainerName = "mongo-tests"; var exposedPort = $"27017/tcp"; DockerClient client = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine")) .CreateClient(); await CreateImageIfNotExist(client, mongoDbImageName, mongoDbImageTag); await RemoveContainerIfExist(client, "mongo-tests"); // docker run --name mongo-tests -p 33381:27017 -d mongo:4; var containerId = await RunContainer(client, mongodDbImage, mongoDbContainerName, exposedPort, "33381"); await WaitBeforeContainerInit(client, containerId, "waiting for connections on port 27017"); ContainerListResponse container = await GetContainerByName(client, mongoDbContainerName); Assert.NotNull(container); await RemoveContainerIfExist(client, "mongo-tests"); client.Dispose(); }
public async Task <IActionResult> Index() { Uri dockerUri = new Uri("unix:///var/run/docker.sock"); DockerClient client = new DockerClientConfiguration(dockerUri).CreateClient(); var containersListParameters = new ContainersListParameters() { All = true, }; IList <ContainerListResponse> containers = await client.Containers.ListContainersAsync(containersListParameters); IEnumerable <Either <string, AutodiscoveryConfigModel> > autodiscovery = containers .Where(KeepRunningContainersWithAutodiscoveryData) .Select(GetAutodiscoveryData); List <AutodiscoveryConfigModel> tools = autodiscovery.Where(tool => tool.IsRight()).Select(tool => tool.right).ToList(); List <string> errorMessages = autodiscovery.Where(tool => !tool.IsRight()).Select(tool => tool.left).ToList(); return(View(model: new HomeModel() { Tools = tools, ContainersCount = containers.Count, ErrorMessages = errorMessages })); }
public async Task InitializeAsync() { var version = Environment.GetEnvironmentVariable("QBT_VERSION")?.Replace(':', '-') ?? "4.2.1"; ImageName = "docker.pkg.github.com/fedarovich/qbittorrent-net-client/qbt-net-test:" + version; var sourceDir = Path.Combine(Utils.StartupFolder, "docker", "qbt-" + version); var env = File.ReadAllText(Path.Combine(sourceDir, "env.json")); Console.WriteLine("Test Environment:"); Console.WriteLine(env); Env = JsonConvert.DeserializeObject <Env>(env); var config = new DockerClientConfiguration(new Uri("http://localhost:2375")); Client = config.CreateClient(); await Client.Images.CreateImageAsync( new ImagesCreateParameters { FromImage = ImageName }, new AuthConfig { // Workaround for issue with GitHub repository authorization Username = "******", Password = Environment.GetEnvironmentVariable("GITHUB_PACKAGES_TOKEN") }, new Progress <JSONMessage>()); }
private PostgresAutomation(string connectionString, string containerName, string finalDatabaseName, TimeSpan timeout) { if (string.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentException("message", nameof(connectionString)); } if (string.IsNullOrWhiteSpace(containerName)) { throw new ArgumentException("message", nameof(containerName)); } if (timeout == default) { timeout = TimeSpan.FromMinutes(5); } var cts = new CancellationTokenSource(); cts.CancelAfter(timeout); _token = cts.Token; ConnectionString = new NpgsqlConnectionStringBuilder(connectionString); _containerName = containerName; _databaseName = finalDatabaseName ?? ConnectionString.Database; _originalDatabaseName = ConnectionString.Database; Uri LocalDockerUri() { var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); return(isWindows ? new Uri("npipe://./pipe/docker_engine") : new Uri("unix:/var/run/docker.sock")); } Client = new DockerClientConfiguration(LocalDockerUri()).CreateClient(); }
static async Task Main() { Program p = new Program(); using (DockerClient client = new DockerClientConfiguration(new Uri("http://192.168.1.30:2375")).CreateClient()) await p.QueryPerform(client); }
/// <summary> /// Performs the playback of actions in this module. /// </summary> /// <remarks>You should not call this method directly, instead pass the module /// instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method /// that will in turn invoke this method.</remarks> void ITestModule.Run() { ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true; DockerClient client = null; if (certFile.Length > 0) { var credentials = new CertificateCredentials(new X509Certificate2(certFile)); client = new DockerClientConfiguration(new Uri(dockerURL), credentials).CreateClient(); } else { client = new DockerClientConfiguration(new Uri(dockerURL)).CreateClient(); } var id = TestSuite.CurrentTestContainer.Parameters["containerID"]; var stopParams = new Docker.DotNet.Models.ContainerStopParameters() { WaitBeforeKillSeconds = 10 }; CancellationToken token = new CancellationToken(); var stopTask = client.Containers.StopContainerAsync(id, stopParams, token); stopTask.Wait(); var remParams = new Docker.DotNet.Models.ContainerRemoveParameters(); var deleteTask = client.Containers.RemoveContainerAsync(id, remParams); deleteTask.Wait(new TimeSpan(0, 0, 15)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddCors(); // docker stuff var dockerClient = new DockerClientConfiguration(new Uri("unix:///var/run/docker.sock")).CreateClient(); var dockerManager = new DockerManager(dockerClient); services.AddSingleton <IDockerManager>(dockerManager); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Argo Manager", Version = "v1", Description = "A tool to manage Argo Tunnels", Contact = new Contact { Name = "Daan Boerlage", Url = "https://github.com/runebaas" }, License = new License { Name = "None" } }); }); }
protected override async Task <int> ExecuteAsync(CommandContext context, CancellationToken cancellationToken) { var deviceType = await context.FindDeviceTypeAsync(DeviceType, cancellationToken); if (deviceType == null) { return(1); } var agentVersion = await context.FindAgentVersion(deviceType.Id, Version, cancellationToken); if (agentVersion == null) { return(1); } using (IDockerClient sourceDockerClient = new DockerClientConfiguration(new Uri(Source)).CreateClient()) using (IDockerClient targetDockerClient = new DockerClientConfiguration(new Uri(Target)).CreateClient()) { Console.WriteLine("Saving image to target..."); //Copy the image. using (var sourceImageStream = await sourceDockerClient.Images.SaveImageAsync(agentVersion.ImageId, cancellationToken)) { await targetDockerClient.Images.LoadImageAsync(new ImageLoadParameters(), sourceImageStream, new Progress <JSONMessage>(p => Console.WriteLine(p.Status)), cancellationToken); } Console.WriteLine("Removing target agent container(s)..."); //Ditch the containers that might cause a problem. await targetDockerClient.ObliterateContainerAsync(DockerContainerNames.AgentA, cancellationToken : cancellationToken); await targetDockerClient.ObliterateContainerAsync(DockerContainerNames.AgentB, cancellationToken : cancellationToken); Console.WriteLine("Creating agent container..."); //Create the container factory var containerFactory = new AgentDockerContainerFactory(); //Create the container itself var createContainerResponse = await containerFactory.CreateContainerForDirectAsync(targetDockerClient, agentVersion.ImageId, cancellationToken); Console.WriteLine($"Container '{createContainerResponse.ID}' created. Starting container..."); //Start the container. bool started = await targetDockerClient.Containers.StartContainerAsync(createContainerResponse.ID, new ContainerStartParameters(), cancellationToken); if (started) { Console.WriteLine("Agent container started."); return(0); } Console.Error.WriteLine("Agent container failed to start."); return(1); } }
public static void UseDockerClient(Action <DockerClient> action) { using (DockerClient client = new DockerClientConfiguration(new Uri("unix:///var/run/docker.sock")) .CreateClient()) { action(client); } }