public TestContainer(string imageName, string containerName, string tag = "latest", string[] environmentVariables = null, Action <string> logger = null) { _imageName = imageName ?? throw new ArgumentNullException(nameof(imageName)); _tag = tag; _environmentVariables = environmentVariables; Logger = logger; Name = containerName; _docker = _docker ?? new DockerClientConfiguration(new Uri(GetDockerDefaultUrl())).CreateClient() ?? throw new ArgumentNullException(); }
private static DockerClient GetClient() { if (_client == null) { string endpoint = Environment.GetEnvironmentVariable(ENV_ENDPOINT) ?? "npipe://./pipe/docker_engine"; _client = new DockerClientConfiguration(new System.Uri(endpoint)).CreateClient(); } return(_client); }
public static async Task CreateHardLinkInContainerAsync(this DockerClient dockerClient, string containerId, string sourceFile, string link) { var escapedSourceFile = sourceFile.Replace("\"", "\\\""); var escapedlink = link.Replace("\"", "\\\""); var commandToExecute = $"ln \"{escapedSourceFile}\" \"{escapedlink}\""; await ExecuteSHCommandAsync(dockerClient, containerId, commandToExecute).ConfigureAwait(false); }
public DockerService(IOptions <DockerOptions> dockerOptions, IHubContext <DockerHostHub> hubContext) { _dockerOptions = dockerOptions; _hubContext = hubContext; _client = new DockerClientConfiguration( new Uri("tcp://" + _dockerOptions.Value.ConnectionString)) .CreateClient(); }
public async Task connect(String host, int port, String user, String local_path, String remote_path, String password, TLS_MODE tls_mode, bool use_compression, String container) { cancel = new CancellationTokenSource(); SetLocalPath(local_path); compress = use_compression; this.tls_mode = tls_mode; if (String.IsNullOrWhiteSpace(remote_path)) { remote_path = ""; } else if (remote_path.EndsWith("/") == false && remote_path.EndsWith("\\") == false) { remote_path += "/"; } this.remote_path = remote_path; this.container = container; if (host.IndexOf("://") == -1) { host = "tcp://" + host; } host += ":" + port; Credentials creds = new AnonymousCredentials(); var pswd_info = new FileInfo(password); if (pswd_info.Exists) { if (pswd_info.Attributes.HasFlag(FileAttributes.ReparsePoint)) { throw new Exception("Sysmlinks will crash this;0"); } creds = new CertificateCredentials(new X509Certificate2(password, "")); //warning sym links will throw an error here ca_cert_path = user; ((CertificateCredentials)creds).ServerCertificateValidationCallback += ServerCertificateValidationCallback; //not sure why cannot do this for basic auth } else if (!String.IsNullOrWhiteSpace(user) && !String.IsNullOrWhiteSpace(password)) { creds = new BasicAuthCredentials(user, password, tls_mode != TLS_MODE.None); } var config = new DockerClientConfiguration(new Uri(host), creds); client = config.CreateClient(); try { var stats = await client.Containers.InspectContainerAsync(container); if (!stats.State.Running) { MainWindow.ShowMessage("Container is not running", "Unable to connect"); } else { connected = true; } } catch (Exception e) { HandleException(e); } }
public async Task StartAsync() { while (!_shutdown.IsCancellationRequested) { var containers = await DockerClient.ContainerListAsync(); await ProcessContainersAsync(containers); await Task.Delay(5000, _shutdown); } }
public DockerService() { if (client == null) { client = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine")) .CreateClient(); } ProcessStartInfo processStartInfo = new ProcessStartInfo("docker", " run -it -p 8080:8080 -v \"C:/Users/Minh/.local/share/code-server:/home/coder/.local/share/code-server\" -v \"C:/Users/Minh:/home/coder/project\" -e \"PASSWORD=123456\" codercom/code-server:v2"); }
public static async Task <string> ShouldReportRunningContainerNamedAsync(this DockerClient client, string containerName) { var existingContainersWithMatchingName = await ExistingContainersWithMatchingName(client, containerName); existingContainersWithMatchingName.Should().HaveCount(1); var container = existingContainersWithMatchingName.First(); container.Status.Should().StartWith("Up "); return(container.ID); }
public DockerContainerFactory(DockerClient dockerClient, string dockerHost) { if (dockerHost == null) { throw new ArgumentNullException(nameof(dockerHost)); } _dockerClient = dockerClient ?? throw new ArgumentNullException(nameof(dockerClient)); _dockerHost = dockerHost; }
TestCaseProcessManager() { #if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN // if named pipes prove to be unreliable, we can fall back to Uri("tcp://127.0.0.1:2375"); Uri dockerUri = new Uri("npipe://./pipe/docker_engine"); #else Uri dockerUri = new Uri("unix:///var/run/docker.sock"); #endif dockerClient = new Docker.DotNet.DockerClientConfiguration(dockerUri, defaultTimeout: TimeSpan.FromSeconds(1)).CreateClient(); }
public DockerService(IOptions <LabOptions> options) { _options = options ?? throw new ArgumentNullException(nameof(options)); // Only initialize this if container support is enabled if (!string.IsNullOrWhiteSpace(_options.Value.DockerContainerName)) { _dockerClient = new DockerClientConfiguration(new Uri("unix:///docker/docker.sock")).CreateClient(); } }
async static void Test() { DockerClient client = Env.Client; var version = await client.System.GetVersionAsync(); var im = await client.Images.ListImagesAsync(new ImagesListParameters() { All = true }); }
public MonitoringServiceDockerSocket(int removeAfterHours , MetricsDataContext metricsDataContext , ILogger <MonitoringServiceDockerSocket> logger) { _metricsDataContext = metricsDataContext; _logger = logger; _removeAfterHours = removeAfterHours; _dockerClient = new DockerClientConfiguration(new Uri("unix://var/run/docker.sock")).CreateClient(); }
public static async Task <ContainerListResponse> StartMailDev(DockerClient client) { const string ContainerName = "maildev-integration-tests"; const string ImageName = "djfarrelly/maildev"; const string ImageTag = "latest"; await DockerExtentions.EnsureImageExistsAndCleanupAsync(client, ImageName, ImageTag, ContainerName); var config = new Config(); var hostConfig = new HostConfig { PortBindings = new Dictionary <string, IList <PortBinding> > { { "80/tcp", new List <PortBinding> { new PortBinding { HostIP = "", HostPort = "5080" } } }, { "25/tcp", new List <PortBinding> { new PortBinding { HostIP = "", HostPort = "25" } } } } }; var response = await client.Containers.CreateContainerAsync(new CreateContainerParameters(config) { Image = ImageName + ":" + ImageTag, Name = ContainerName, Tty = false, HostConfig = hostConfig }); var container = await DockerExtentions.GetContainerAsync(client, ContainerName); if (container == null) { throw new Exception("No MailDev container."); } if (container.State != "running") { var started = await client.Containers.StartContainerAsync(container.ID, new ContainerStartParameters()); if (!started) { throw new Exception("Cannot start the MailDev docker container."); } Thread.Sleep(100); } return(container); }
public static async Task <ContainerListResponse> GetContainerAsync(DockerClient client, string containerName) { var containers = await client.Containers.ListContainersAsync(new ContainersListParameters() { All = true }); var container = containers.FirstOrDefault(c => c.Names.Contains("/" + containerName)); return(container); }
public DockerSDK(string url) { if (_client == null) { if (string.IsNullOrWhiteSpace(url)) { url = "unix:/var/run/docker.sock"; } _client = new DockerClientConfiguration(new Uri(url)).CreateClient(); } }
private async static Task <IList <ImagesListResponse> > ListImages(DockerClient _client) { IList <ImagesListResponse> myList = await _client.Images.ListImagesAsync( new Docker.DotNet.Models.ImagesListParameters() { All = true } ); return(myList); }
private async Task RemoveContainersFromHost(DockerClient client) { IList <ContainerListResponse> containers = await client.Containers.ListContainersAsync(new ContainersListParameters { All = true }); foreach (var container in containers) { await client.Containers.StopContainerAsync(container.ID, new ContainerStopParameters(), CancellationToken.None); await client.Containers.RemoveContainerAsync(container.ID, new ContainerRemoveParameters(), CancellationToken.None); } }
public CancellationTokenSource StartLogs(DockerClient client, string id, Action <string, string, long> backCall = null) { var cancellationTokenSource = new CancellationTokenSource(); var progress = new Progress <string>(); var queue = new ConcurrentQueue <string>(); var key = RedisKeys.SentryList(SentryEnum.Log, id); // 重置这个redis _redis.KeyDelete(key); progress.ProgressChanged += (obj, message) => { queue.Enqueue(message); }; _ = Task.Run(async() => // 每 5ms 存储一次 { while (true) { if (queue.TryDequeue(out var message)) { var rule = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{9}Z"; var time = Regex.Matches(message, rule)[0].Value; var v = message.Split(new[] { time }, StringSplitOptions.None)[1] .Replace("\u001b[40m\u001b[1m\u001b[33mwarn\u001b[39m\u001b[22m\u001b[49m:", "[warn]") .Replace("\u001B[41m\u001B[30mfail\u001B[39m\u001B[22m\u001B[49m", "[fail]"); var l = _redis.ListRightPush(key, new { time, log = v }); if (backCall != null) { backCall(id, v, l); } } await Task.Delay(5); } }, cancellationTokenSource.Token); _ = client.Containers.GetContainerLogsAsync( id, new ContainerLogsParameters { // as the error said, you have to choose one stream either stdout or stderr. If you don't input any of these option to be true, it would panic. ShowStdout = true, ShowStderr = true, Timestamps = true, Follow = true }, cancellationTokenSource.Token, progress ); return(cancellationTokenSource); }
public async Task DisposeAsync() { if (DockerClient != null) { await DockerClient.Containers.StopContainerAsync(RedisContainer, new ContainerStopParameters { }); await DockerClient.Containers.RemoveContainerAsync(RedisContainer, new ContainerRemoveParameters { Force = true }); DockerClient.Dispose(); } }
public static async Task <MultiplexedStream> AttachContainer(this DockerClient client, string ID) { return(await client.Containers.AttachContainerAsync(ID, false, new ContainerAttachParameters() { Stream = true, Stderr = true, Stdin = false, Stdout = true, })); }
private void CreateClientNoAuthentication(string hostname, int port, out DockerClient client) { if (port == 0) { port = 2376; } Guard.Against.NullOrEmpty(hostname, nameof(hostname)); Guard.Against.OutOfRange(port, nameof(port), 80, 65000); client = new DockerClientConfiguration(new Uri("tcp://" + hostname + ":" + port)).CreateClient(); }
public ISystemOperationsTests(TestFixture testFixture, ITestOutputHelper output) { _cts = CancellationTokenSource.CreateLinkedTokenSource(testFixture.cts.Token); _cts.Token.Register(() => throw new TimeoutException("ISystemOperationsTest timeout")); _cts.CancelAfter(TimeSpan.FromMinutes(5)); _repositoryName = testFixture.repositoryName; _tag = testFixture.tag; _client = testFixture.dockerClient; _output = new TestOutput(output); }
public async Task Waits_for_log_entry() { var client = new DockerClient(); var containerName = "lcldkr-log-test"; client.RunOrReplace("hello-world", containerName); await client.WaitForLogEntryAsync(containerName, "Hello from Docker!", TimeSpan.FromSeconds(30)); client.StopAndRemoveContainer(containerName); }
public MongoDockerFixture() { docker = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine")).CreateClient(); docker.CreateImageIfNotExist(MongoDbImageName, MongoDbImageTag).Wait(); docker.RemoveContainerIfExist(MongoDbContainerName).Wait(); // docker run --name mongo-tests -p 33381:27017 -d mongo:4; var containerId = docker.RunContainer(MongoDbImage, MongoDbContainerName, ExposedPort, HostPort).Result; docker.WaitBeforeContainerInit(containerId).Wait(); }
public async Task ToolbarDeleteAsync() { ListView.SelectedListViewItemCollection list = listDockerImages.SelectedItems; var dockerConfig = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine")); DockerClient client = dockerConfig.CreateClient(); IList <IDictionary <string, string> > result = await client.Images.DeleteImageAsync(list[0].Text, new Docker.DotNet.Models.ImageDeleteParameters() { Force = false }); ReloadImages(); }
public static async Task <ContainerListResponse> StartRedisCommander(DockerClient client) { const string ContainerName = "redis-commander-integration-tests"; const string ImageName = "rediscommander/redis-commander"; const string ImageTag = "latest"; await DockerExtentions.EnsureImageExistsAndCleanupAsync(client, ImageName, ImageTag, ContainerName); var config = new Config(); var hostConfig = new HostConfig { PortBindings = new Dictionary <string, IList <PortBinding> > { { "8081/tcp", new List <PortBinding> { new PortBinding { HostIP = "", HostPort = "5082" } } } } }; var response = await client.Containers.CreateContainerAsync(new CreateContainerParameters(config) { Image = ImageName + ":" + ImageTag, Name = ContainerName, Tty = false, HostConfig = hostConfig, Env = new List <string> { "REDIS_HOSTS=local:localhost:6379" } }); var container = await DockerExtentions.GetContainerAsync(client, ContainerName); if (container == null) { throw new Exception("No Redis Commander container."); } if (container.State != "running") { var started = await client.Containers.StartContainerAsync(container.ID, new ContainerStartParameters()); if (!started) { throw new Exception("Cannot start the Redis Commander docker container."); } } return(container); }
/// <summary> /// Handmade metod to get count of services /// </summary> /// <returns></returns> private async Task <int> GetServicesCount(DockerClient client) { IEnumerable <SwarmService> services = await client.Swarm.ListServicesAsync(); var servicesCount = 0; foreach (var service in services) { servicesCount++; } return(servicesCount); }
private static async Task CreateImage(DockerClient client) { // https://github.com/docker/for-win/issues/611 - timeout exceeded waiting for headers. Set docker network dns to fixed await client.Images.CreateImageAsync( new ImagesCreateParameters { FromImage = ImageName, Tag = ImageTag }, new AuthConfig() { }, new Progress <JSONMessage>()); }
public IContainerOperationsTests(TestFixture testFixture, ITestOutputHelper outputHelper) { // Do not wait forever in case it gets stuck _cts = CancellationTokenSource.CreateLinkedTokenSource(testFixture.cts.Token); _cts.CancelAfter(TimeSpan.FromMinutes(5)); _cts.Token.Register(() => throw new TimeoutException("IContainerOperationsTest timeout")); _dockerClient = testFixture.dockerClient; _dockerClientConfiguration = testFixture.dockerClientConfiguration; _output = new TestOutput(outputHelper); _imageId = testFixture.imageId; }