public boolean isInstalled() { return executableExists(executableName); }
/** * Check whether an executable exists, either at a specific path (if a full path is given) or * on the PATH. * * @param executable the name of an executable on the PATH or a complete path to an executable that may/may not exist * @return whether the executable exists and is executable */ public static boolean executableExists(String executable) { // First check if we've been given the full path already File directFile = new File(executable); if (directFile.exists() && directFile.canExecute()) { return true; } for (String pathString : getSystemPath()) { Path path = Paths.get(pathString); if (Files.exists(path.resolve(executable)) && Files.isExecutable(path.resolve(executable))) { return true; } } return false; }
public String getDockerDaemonIpAddress(@NonNull String machineName) { return runShellCommand(executableName, "ip", machineName); }
public boolean isMachineRunning(String machineName) { String status = runShellCommand("docker-machine", "status", machineName); return status.trim().equalsIgnoreCase("running"); }
@Override public void invoke() { if (!CommandLine.executableExists(COMPOSE_EXECUTABLE)) { throw new ContainerLaunchException("Local Docker Compose not found. Is " + COMPOSE_EXECUTABLE + " on the PATH?");
@Override public void test() throws InvalidConfigurationException { try { boolean installed = DockerMachineClient.instance().isInstalled(); checkArgument(installed, "docker-machine executable was not found on PATH (" + Arrays.toString(CommandLine.getSystemPath()) + ")"); Optional<String> machineNameOptional = DockerMachineClient.instance().getDefaultMachine(); checkArgument(machineNameOptional.isPresent(), "docker-machine is installed but no default machine could be found"); String machineName = machineNameOptional.get(); log.info("Found docker-machine, and will use machine named {}", machineName); DockerMachineClient.instance().ensureMachineRunning(machineName); String dockerDaemonIpAddress = DockerMachineClient.instance().getDockerDaemonIpAddress(machineName); log.info("Docker daemon IP address for docker machine {} is {}", machineName, dockerDaemonIpAddress); config = DefaultDockerClientConfig.createDefaultConfigBuilder() .withDockerHost("tcp://" + dockerDaemonIpAddress + ":2376") .withDockerTlsVerify(true) .withDockerCertPath(Paths.get(System.getProperty("user.home") + "/.docker/machine/certs/").toString()) .build(); client = getClientForConfig(config); } catch (Exception e) { throw new InvalidConfigurationException(e.getMessage()); } // If the docker-machine VM has started, the docker daemon may still not be ready. Retry pinging until it works. final int timeout = Integer.parseInt(System.getProperty(PING_TIMEOUT_PROPERTY_NAME, PING_TIMEOUT_DEFAULT)); ping(client, timeout); }
public Optional<String> getDefaultMachine() { String ls = runShellCommand(executableName, "ls", "-q"); List<String> machineNames = asList(ls.split("\n")); String envMachineName = System.getenv("DOCKER_MACHINE_NAME"); if (machineNames.contains(envMachineName)) { LOGGER.debug("Using docker-machine set in DOCKER_MACHINE_NAME: {}", envMachineName); return Optional.of(envMachineName); } else if (machineNames.contains("default")) { LOGGER.debug("DOCKER_MACHINE_NAME is not set; Using 'default' docker-machine", envMachineName); return Optional.of("default"); } else if (machineNames.size() > 0) { LOGGER.debug("DOCKER_MACHINE_NAME is not set and no machine named 'default' found; Using first machine found with `docker-machine ls`: {}", machineNames.get(0)); return Optional.of(machineNames.get(0)); } else { return Optional.empty(); } }
public boolean isInstalled() { return executableExists(executableName); }
/** * Check whether an executable exists, either at a specific path (if a full path is given) or * on the PATH. * * @param executable the name of an executable on the PATH or a complete path to an executable that may/may not exist * @return whether the executable exists and is executable */ public static boolean executableExists(String executable) { // First check if we've been given the full path already File directFile = new File(executable); if (directFile.exists() && directFile.canExecute()) { return true; } for (String pathString : getSystemPath()) { Path path = Paths.get(pathString); if (Files.exists(path.resolve(executable)) && Files.isExecutable(path.resolve(executable))) { return true; } } return false; }
public void ensureMachineRunning(@NonNull String machineName) { if (!isMachineRunning(machineName)) { LOGGER.info("Docker-machine '{}' is not running. Will start it now", machineName); runShellCommand("docker-machine", "start", machineName); } }
@Override public void invoke() { // bail out early if (!CommandLine.executableExists(COMPOSE_EXECUTABLE)) { throw new ContainerLaunchException("Local Docker Compose not found. Is " + COMPOSE_EXECUTABLE + " on the PATH?"); } final Map<String, String> environment = Maps.newHashMap(env); environment.put(ENV_PROJECT_NAME, identifier); final Stream<String> absoluteDockerComposeFilePaths = composeFiles.stream().map(File::getAbsolutePath).map(Objects::toString); final String composeFileEnvVariableValue = absoluteDockerComposeFilePaths.collect(joining(File.pathSeparator + "")); logger().debug("Set env COMPOSE_FILE={}", composeFileEnvVariableValue); final File pwd = composeFiles.get(0).getAbsoluteFile().getParentFile().getAbsoluteFile(); environment.put(ENV_COMPOSE_FILE, composeFileEnvVariableValue); logger().info("Local Docker Compose is running command: {}", cmd); final List<String> command = Splitter.onPattern(" ").omitEmptyStrings().splitToList(COMPOSE_EXECUTABLE + " " + cmd); try { new ProcessExecutor().command(command).redirectOutput(Slf4jStream.of(logger()).asInfo()).redirectError(Slf4jStream.of(logger()).asError()).environment(environment).directory(pwd).exitValueNormal().executeNoTimeout(); logger().info("Docker Compose has finished running"); } catch (InvalidExitValueException e) { throw new ContainerLaunchException("Local Docker Compose exited abnormally with code " + e.getExitValue() + " whilst running command: " + cmd); } catch (Exception e) { throw new ContainerLaunchException("Error running local Docker Compose command: " + cmd, e); } }
@Override public void test() throws InvalidConfigurationException { try { boolean installed = DockerMachineClient.instance().isInstalled(); checkArgument(installed, "docker-machine executable was not found on PATH (" + Arrays.toString(CommandLine.getSystemPath()) + ")"); Optional<String> machineNameOptional = DockerMachineClient.instance().getDefaultMachine(); checkArgument(machineNameOptional.isPresent(), "docker-machine is installed but no default machine could be found"); String machineName = machineNameOptional.get(); log.info("Found docker-machine, and will use machine named {}", machineName); DockerMachineClient.instance().ensureMachineRunning(machineName); String dockerDaemonIpAddress = DockerMachineClient.instance().getDockerDaemonIpAddress(machineName); log.info("Docker daemon IP address for docker machine {} is {}", machineName, dockerDaemonIpAddress); config = DefaultDockerClientConfig.createDefaultConfigBuilder().withDockerHost("tcp://" + dockerDaemonIpAddress + ":2376").withDockerTlsVerify(true).withDockerCertPath(Paths.get(System.getProperty("user.home") + "/.docker/machine/certs/").toString()).build(); client = getClientForConfig(config); } catch (Exception e) { throw new InvalidConfigurationException(e.getMessage()); } // If the docker-machine VM has started, the docker daemon may still not be ready. Retry pinging until it works. final int timeout = Integer.parseInt(System.getProperty(PING_TIMEOUT_PROPERTY_NAME, PING_TIMEOUT_DEFAULT)); ping(client, timeout); }
/** * {@inheritDoc} */ @Override public String getTestHostIpAddress() { if (DockerMachineClient.instance().isInstalled()) { try { Optional<String> defaultMachine = DockerMachineClient.instance().getDefaultMachine(); if (!defaultMachine.isPresent()) { throw new IllegalStateException("Could not find a default docker-machine instance"); } String sshConnectionString = runShellCommand("docker-machine", "ssh", defaultMachine.get(), "echo $SSH_CONNECTION").trim(); if (Strings.isNullOrEmpty(sshConnectionString)) { throw new IllegalStateException("Could not obtain SSH_CONNECTION environment variable for docker machine " + defaultMachine.get()); } String[] sshConnectionParts = sshConnectionString.split("\\s"); if (sshConnectionParts.length != 4) { throw new IllegalStateException("Unexpected pattern for SSH_CONNECTION for docker machine - expected 'IP PORT IP PORT' pattern but found '" + sshConnectionString + "'"); } return sshConnectionParts[0]; } catch (Exception e) { throw new RuntimeException(e); } } else { throw new UnsupportedOperationException("getTestHostIpAddress() is only implemented for docker-machine right now"); } }
public String getDockerDaemonIpAddress(@NonNull String machineName) { if (machineName == null) { throw new java.lang.NullPointerException("machineName is marked @NonNull but is null"); } return runShellCommand(executableName, "ip", machineName); }
public boolean isMachineRunning(String machineName) { String status = runShellCommand("docker-machine", "status", machineName); return status.trim().equalsIgnoreCase("running"); }
public void ensureMachineRunning(@NonNull String machineName) { if (machineName == null) { throw new java.lang.NullPointerException("machineName is marked @NonNull but is null"); } if (!isMachineRunning(machineName)) { LOGGER.info("Docker-machine \'{}\' is not running. Will start it now", machineName); runShellCommand("docker-machine", "start", machineName); } }
public Optional<String> getDefaultMachine() { String ls = runShellCommand(executableName, "ls", "-q"); List<String> machineNames = asList(ls.split("\n")); String envMachineName = System.getenv("DOCKER_MACHINE_NAME"); if (machineNames.contains(envMachineName)) { LOGGER.debug("Using docker-machine set in DOCKER_MACHINE_NAME: {}", envMachineName); return Optional.of(envMachineName); } else if (machineNames.contains("default")) { LOGGER.debug("DOCKER_MACHINE_NAME is not set; Using \'default\' docker-machine", envMachineName); return Optional.of("default"); } else if (machineNames.size() > 0) { LOGGER.debug("DOCKER_MACHINE_NAME is not set and no machine named \'default\' found; Using first machine found with `docker-machine ls`: {}", machineNames.get(0)); return Optional.of(machineNames.get(0)); } else { return Optional.empty(); } }
/** * {@inheritDoc} */ @Override public String getTestHostIpAddress() { if (DockerMachineClient.instance().isInstalled()) { try { Optional<String> defaultMachine = DockerMachineClient.instance().getDefaultMachine(); if (!defaultMachine.isPresent()) { throw new IllegalStateException("Could not find a default docker-machine instance"); } String sshConnectionString = runShellCommand("docker-machine", "ssh", defaultMachine.get(), "echo $SSH_CONNECTION").trim(); if (Strings.isNullOrEmpty(sshConnectionString)) { throw new IllegalStateException("Could not obtain SSH_CONNECTION environment variable for docker machine " + defaultMachine.get()); } String[] sshConnectionParts = sshConnectionString.split("\\s"); if (sshConnectionParts.length != 4) { throw new IllegalStateException("Unexpected pattern for SSH_CONNECTION for docker machine - expected \'IP PORT IP PORT\' pattern but found \'" + sshConnectionString + "\'"); } return sshConnectionParts[0]; } catch (Exception e) { throw new RuntimeException(e); } } else { throw new UnsupportedOperationException("getTestHostIpAddress() is only implemented for docker-machine right now"); } }