createCommand.withCmd(commandParts);
createContainerCmd.withName("testcontainers-checks-" + SESSION_ID); createContainerCmd.getHostConfig().withAutoRemove(true); createContainerCmd.withCmd("tail", "-f", "/dev/null"); }, (__, containerId) -> {
@Test public void createContainerCmdHookTest() { // Use random name to avoid the conflicts between the tests String randomName = Base58.randomString(5); try( GenericContainer container = new GenericContainer<>("redis:3.0.2") .withCommand("redis-server", "--help") .withCreateContainerCmdModifier(cmd -> cmd.withName("overrideMe")) // Preserves the order .withCreateContainerCmdModifier(cmd -> cmd.withName(randomName)) // Allows to override pre-configured values by GenericContainer .withCreateContainerCmdModifier(cmd -> cmd.withCmd("redis-server", "--port", "6379")) ) { container.start(); assertEquals("Name is configured", "/" + randomName, container.getContainerInfo().getName()); assertEquals("Command is configured", "[redis-server, --port, 6379]", Arrays.toString(container.getContainerInfo().getConfig().getCmd())); } }
@Test public void runCommandInsideDockerShouldNotFailIfImageDoesNotExistsLocally() { final DockerClientFactory dockFactory = DockerClientFactory.instance(); try { //remove tiny image, so it will be pulled during next command run dockFactory.client() .removeImageCmd(TestcontainersConfiguration.getInstance().getTinyImage()) .withForce(true).exec(); } catch (NotFoundException ignored) { // Do not fail if it's not pulled yet } dockFactory.runInsideDocker( cmd -> cmd.withCmd("sh", "-c", "echo 'SUCCESS'"), (client, id) -> client.logContainerCmd(id) .withStdOut(true) .exec(new LogToStringContainerCallback()) .toString() ); }
new Bind(Paths.get(repoPath.getParent().toString(), REPOSITORY).toString(), mvnVolume)) .withWorkingDir(File.separator + fileName) .withCmd(BASH, "-c", cmd) .withTty(true) .exec();
@Override public CreateContainerCmd build(ServiceDescriptor sd, CreateContainerCmd cmd, Command c) { return cmd.withCmd(c.value()); }
private void checkDiskSpace(DockerClient dockerClient, String id) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { dockerClient.execStartCmd(dockerClient.execCreateCmd(id).withAttachStdout(true).withCmd("df", "-P").exec().getId()).exec(new ExecStartResultCallback(outputStream, null)).awaitCompletion(); } catch (Exception e) { log.debug("Can\'t exec disk checking command", e); } DiskSpaceUsage df = parseAvailableDiskSpace(outputStream.toString()); VisibleAssertions.assertTrue("Docker environment should have more than 2GB free disk space", df.availableMB.map(it -> it >= 2048).orElse(true)); }
public String createContainer(String image, String... command){ CreateContainerResponse container = dockerClient .createContainerCmd(image) .withCmd(command) .exec(); return container.getId(); }
private void startContainer(Map<String, String> env, Map<Integer, Integer> ports, Map<String, String> cmd, Consumer<String> log) { final CreateContainerResponse container = client.createContainerCmd(image) .withCmd(cmd.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(toList())) .withLabels(map(label, "true")) .withEnv(env.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(toList())) .withPortBindings(ports.entrySet().stream().map(e -> new PortBinding(Ports.Binding.bindPort(e.getKey()), ExposedPort.tcp(e.getValue()))).collect(toList())) .exec(); client.startContainerCmd(container.getId()).exec(); client.logContainerCmd(container.getId()).withFollowStream(true).withStdOut(true).withStdErr(true).exec( new LogContainerResultCallback() { public void onNext(Frame frame) { final String msg = new String(frame.getPayload()); log.accept(msg.endsWith("\n") ? msg.substring(0, msg.length() - 1) : msg); } }); } }
/** * Ensure container is already set with a command, or set one to make it wait indefinitely */ protected void ensureWaiting(CreateContainerCmd cmd) { if (cmd.getCmd() == null || cmd.getCmd().length == 0) { // no command has been set, we need one that will just hang. Typically "sh" waiting for stdin cmd.withCmd("/bin/sh") .withTty(true) .withAttachStdin(false); } }
@Override protected CreateContainerCmd dockerCommand() { return dockerClient .createContainerCmd(TEST_CONFIG.getSchedulerImageName()) .withName(TEST_CONFIG.getSchedulerName() + "_" + new SecureRandom().nextInt()) .withEnv("JAVA_OPTS=-Xms128m -Xmx256m") .withCmd( ZookeeperCLIParameter.ZOOKEEPER_MESOS_URL, getZookeeperMesosUrl(), ElasticsearchCLIParameter.ELASTICSEARCH_NODES, Integer.toString(TEST_CONFIG.getElasticsearchNodesCount()), Configuration.ELASTICSEARCH_RAM, Integer.toString(TEST_CONFIG.getElasticsearchMemorySize()), Configuration.ELASTICSEARCH_CPU, "0.1", Configuration.ELASTICSEARCH_DISK, "150", Configuration.USE_IP_ADDRESS, "false", Configuration.WEB_UI_PORT, Integer.toString(TEST_CONFIG.getSchedulerGuiPort()), Configuration.EXECUTOR_NAME, TEST_CONFIG.getElasticsearchJobName(), Configuration.FRAMEWORK_USE_DOCKER, "true", Configuration.DATA_DIR, dataDirectory, Configuration.FRAMEWORK_ROLE, frameworkRole); }
@Override public void beforeContainerCreated(DockerAPI api, String workdir, CreateContainerCmd cmd) throws IOException, InterruptedException { final String effectiveJenkinsUrl = StringUtils.isEmpty(jenkinsUrl) ? Jenkins.getInstance().getRootUrl() : jenkinsUrl; final String nodeName = DockerTemplate.getNodeNameFromContainerConfig(cmd); final String secret = JnlpSlaveAgentProtocol.SLAVE_SECRET.mac(nodeName); final EnvVars knownVariables = calculateVariablesForVariableSubstitution(nodeName, secret, jnlpLauncher.tunnel, effectiveJenkinsUrl); final String configuredArgString = getEntryPointArgumentsString(); final String effectiveConfiguredArgString = StringUtils.isNotBlank(configuredArgString) ? configuredArgString : DEFAULT_ENTRY_POINT_ARGUMENTS; final String resolvedArgString = Util.replaceMacro(effectiveConfiguredArgString, knownVariables); final String[] resolvedArgs = splitAndFilterEmpty(resolvedArgString, "\n"); cmd.withCmd(resolvedArgs); String vmargs = jnlpLauncher.vmargs; if (StringUtils.isNotBlank(vmargs)) { DockerEnvUtils.addEnvToCmd("JAVA_OPT", vmargs.trim(), cmd); } if (StringUtils.isNotBlank(user)) { cmd.withUser(user); } }
public String createContainerWithPorts(String image, int[] ports, String... command){ ExposedPort[] exposedPorts=new ExposedPort[ports.length]; for(int i=0;i < ports.length;i++){ exposedPorts[i]=ExposedPort.tcp(ports[i]); } CreateContainerResponse container = dockerClient.createContainerCmd(image) .withCmd(command) .withExposedPorts(exposedPorts) .exec(); return container.getId(); }
@Override public void beforeContainerCreated(DockerAPI api, String workdir, CreateContainerCmd cmd) throws IOException, InterruptedException { // TODO define a strategy for SSHD process configuration so we support more than openssh's sshd if (cmd.getCmd() == null || cmd.getCmd().length == 0) { if (sshKeyStrategy.getInjectedKey() != null) { cmd.withCmd("/usr/sbin/sshd", "-D", "-p", String.valueOf(port), // override sshd_config to force retrieval of InstanceIdentity public for as authentication "-o", "AuthorizedKeysCommand=/root/authorized_key", "-o", "AuthorizedKeysCommandUser=root" ); } else { cmd.withCmd("/usr/sbin/sshd", "-D", "-p", String.valueOf(port)); } } cmd.withPortSpecs(port+"/tcp"); final PortBinding sshPortBinding = PortBinding.parse(":" + port); final Ports portBindings = cmd.getPortBindings(); if(portBindings != null) { portBindings.add(sshPortBinding); cmd.withPortBindings(portBindings); } else { cmd.withPortBindings(sshPortBinding); } cmd.withExposedPorts(ExposedPort.parse(port+"/tcp")); }
@java.lang.SuppressWarnings("all") public static Optional<String> getDefaultGateway() { java.lang.Object value = DockerClientConfigUtils.defaultGateway.get(); if (value == null) { synchronized (DockerClientConfigUtils.defaultGateway) { value = DockerClientConfigUtils.defaultGateway.get(); if (value == null) { final Optional<String> actualValue = Optional.ofNullable(DockerClientFactory.instance().runInsideDocker(cmd -> cmd.withCmd("sh", "-c", "ip route|awk \'/default/ { print $3 }\'"), (client, id) -> { try { LogToStringContainerCallback loggingCallback = new LogToStringContainerCallback(); client.logContainerCmd(id).withStdOut(true).withFollowStream(true).exec(loggingCallback).awaitStarted(); loggingCallback.awaitCompletion(3, SECONDS); return loggingCallback.toString(); } catch (Exception e) { log.warn("Can\'t parse the default gateway IP", e); return null; } })).map(StringUtils::trimToEmpty).filter(StringUtils::isNotBlank); value = actualValue == null ? DockerClientConfigUtils.defaultGateway : actualValue; DockerClientConfigUtils.defaultGateway.set(value); } } } return (Optional<String>) (value == DockerClientConfigUtils.defaultGateway ? null : value); } }
@Override protected CreateContainerCmd dockerCommand() { return DockerClientFactory.build().createContainerCmd(config.getImageName() + ":" + config.getImageTag()) .withNetworkMode("host") .withBinds(Bind.parse("/var/run/docker.sock:/tmp/docker.sock")) .withCmd("-internal", String.format("consul://%s:%d", consul.getIpAddress(), ConsulConfig.CONSUL_HTTP_PORT)) .withName(getName()); }
@Override protected CreateContainerCmd dockerCommand() { return DockerClientFactory.build() .createContainerCmd(config.getImageName() + ":" + config.getImageTag()) .withEnv(newEnvironment() .withValues(getMesosDNSEnvVars()) .createEnvironment()) .withCmd("-v=2", "-config=/etc/mesos-dns/config.json") .withExposedPorts(new ExposedPort(Integer.valueOf(DNS_PORT), InternetProtocol.UDP), new ExposedPort(Integer.valueOf(DNS_PORT), InternetProtocol.TCP)) .withName(getName()); }
@Override public String createVM( String messagingIp, String messagingUsername, String messagingPassword, String rootInstanceName, String applicationName ) throws IaasException { CreateContainerResponse container = this.docker .createContainerCmd(this.machineImageId) .withCmd("/etc/rc.local", applicationName, rootInstanceName, messagingIp, messagingUsername, messagingPassword) .exec(); this.docker.startContainerCmd(container.getId()).exec(); //this.docker.waitContainerCmd(container.getId()).exec(); return container.getId(); }
@Override protected CreateContainerCmd dockerCommand() { ExposedPort exposedPort = ExposedPort.tcp(MARATHON_PORT); Ports portBindings = new Ports(); if (getCluster().isMapPortsToHost()) { portBindings.bind(exposedPort, Ports.Binding.bindPort(MARATHON_PORT)); } return DockerClientFactory.build().createContainerCmd(config.getImageName() + ":" + config.getImageTag()) .withName(getName()) .withExtraHosts("minimesos-zookeeper:" + this.zooKeeper.getIpAddress()) .withCmd(CollectionsUtils.splitCmd(config.getCmd())) .withExposedPorts(exposedPort) .withPortBindings(portBindings); }
@Override protected CreateContainerCmd dockerCommand() { int port = getServicePort(); ExposedPort exposedPort = ExposedPort.tcp(port); Ports portBindings = new Ports(); if (getCluster().isMapPortsToHost()) { portBindings.bind(exposedPort, Ports.Binding.bindPort(port)); } ExposedPort consulHTTPPort = ExposedPort.tcp(ConsulConfig.CONSUL_HTTP_PORT); ExposedPort consulDNSPort = ExposedPort.udp(ConsulConfig.CONSUL_DNS_PORT); return DockerClientFactory.build().createContainerCmd(config.getImageName() + ":" + config.getImageTag()) .withName(getName()) .withCmd("agent", "-server", "-bootstrap", "-client", "0.0.0.0") .withExposedPorts(consulHTTPPort, consulDNSPort) .withPortBindings(portBindings); }