/** * {@inheritDoc} */ @Override public String getContainerId() { return this.container.getId(); } }
private List<Container> listChildContainers() { return dockerClient.listContainersCmd() .withShowAll(true) .exec().stream() .filter(container -> Arrays.stream(container.getNames()).anyMatch(name -> name.startsWith("/" + project))) .collect(toList()); }
private String getServiceNameFromContainer(Container container) { final String containerName = container.getLabels().get("com.docker.compose.service"); final String containerNumber = container.getLabels().get("com.docker.compose.container-number"); return String.format("%s_%s", containerName, containerNumber); }
private Set<String> findAllNetworksForLinkedContainers(LinkableContainer linkableContainer) { return dockerClient.listContainersCmd().exec().stream() .filter(container -> container.getNames()[0].endsWith(linkableContainer.getContainerName())) .filter(container -> container.getNetworkSettings() != null && container.getNetworkSettings().getNetworks() != null) .flatMap(container -> container.getNetworkSettings().getNetworks().keySet().stream()) .distinct() .collect(Collectors.toSet()); }
public boolean isServiceReady() { try { List<Container> allContainers = dockerClient.listContainersCmd().withShowAll(true).exec(); for (Container container : allContainers) { if (asList(container.getNames()).contains("/" + otherContainerName) && !container.getStatus().contains("Exited")) { return true; } } } catch (DockerException e) { return false; } return false; } }
private void stop(final Id id) { if (id == null) { throw new IllegalArgumentException("id is null"); } logger.info("Stopping " + id); for (Container container : findRunningContainers(id)) { logger.info("Stopping container " + Arrays.toString(container.getNames())); try { docker.stopContainerCmd(container.getId()).withTimeout(1).exec(); } catch (DockerException e) { throw new OrchestrationException(e); } } for (Plugin plugin : plugins) { plugin.stopped(id, conf(id)); } }
private void terminateContainerGracefully(DockerCloud dc, Container container) throws TerminationException, ContainerIsTaintedException { String containerId = container.getId(); Map<String, String> containerLabels = container.getLabels(); LOGGER.warn("Attempt to terminate container ID {} gracefully, but a node for it suddenly has appeared", container.getId()); throw new ContainerIsTaintedException(String.format("Node for container ID %s has appeared", container.getId())); if (removeVolumesString == null) { throw new ContainerIsTaintedException(String.format("Container ID %s has no '%s' label; skipping.", container.getId(), DockerContainerLabelKeys.REMOVE_VOLUMES)); if (container.getStatus().startsWith("Dead") || container.getStatus().startsWith("Exited") || container.getStatus().startsWith("Created")) { containerRunning = false; Instant start = clock.instant(); boolean success = stopAndRemoveContainer(dockerApi, LOGGER, String.format("(orphaned container found by %s)", DockerContainerWatchdog.class.getSimpleName()), removeVolumes, container.getId(), !containerRunning); Instant stop = clock.instant();
@Override public void execute(Launcher launcher, @SuppressWarnings("rawtypes") AbstractBuild build, ConsoleLogger console) throws DockerException { if (imageId == null || imageId.isEmpty()) { throw new IllegalArgumentException("At least one parameter is required"); } String imageIdRes = Resolver.buildVar(build, imageId); try { Config cfgData = getConfig(build); Descriptor<?> descriptor = Jenkins.getInstance().getDescriptor(DockerBuilder.class); List<Container> containers = launcher.getChannel().call(new ListContainersRemoteCallable(cfgData, descriptor, false)); for (Container container : containers) { if (imageIdRes.equalsIgnoreCase(container.getImage())) { launcher.getChannel().call(new StopContainerRemoteCallable(cfgData, descriptor, container.getId())); console.logInfo("stoped container id " + container.getId()); } } } catch (Exception e) { console.logError("failed to stop containers by imageIdRes " + imageIdRes); e.printStackTrace(); throw new IllegalArgumentException(e); } }
public DockerService(Container container, String host) { this.host = host; containerId = container.getId(); containerNames = Arrays.stream(container.getNames()).collect(Collectors.toList()); if (!containerNames.isEmpty()) { name = containerNames.get(0); } else { name = containerId; } for (ContainerPort port : container.getPorts()) { Record record = createRecord(container, port); if (record != null) { records.add(record); } } }
String nodeName = csm.getNodeName(container.getId()); if (isStillTooYoung(container.getCreated(), snapshotInstant)) { continue; + "is no longer associated (node might be gone already?). " + "The container's last status is {}; it was created on {}", container.getId(), nodeName, container.getStatus(), container.getCreated()); } catch (Exception e) { LOGGER.warn("Graceful termination of Container {} failed; terminating directly via API - this may cause remnants to be left behind", container.getId(), e);
if (container.getLabels().containsKey(TESTCONTAINER_STARTED)) long millis = Long.parseLong(container.getLabels().get(TESTCONTAINER_STARTED)); LocalDateTime started = LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); LocalDateTime staleSince = LocalDateTime.now().minusMinutes(properties.getAfterMinutes()); else if (currentIssuer.equals(container.getLabels().get(TESTCONTAINER_ISSUER))) dockerClient.killContainerCmd(staleContainer.getId()).exec(); log.warn("Stale container removed ({})", staleContainer.labels);
/** * removes a {@link Container} by Microservice uuid */ private void removeContainerByMicroserviceUuid(String microserviceUuid, boolean withCleanUp) { synchronized (deleteLock) { Optional<Container> containerOptional = docker.getContainer(microserviceUuid); if (containerOptional.isPresent()) { Container container = containerOptional.get(); removeContainer(container.getId(), container.getImageId(), withCleanUp); } } }
private List<Container> findContainers(Id id, boolean allContainers) { final List<Container> matchingContainers = new ArrayList<>(); for (Container container : docker.listContainersCmd().withShowAll(allContainers).exec()) { boolean imageNameMatches = container.getImage().equals(repo.imageName(id)); String[] containerNames = container.getNames(); if (containerNames == null) { // Every container should have a name, but this is not the case // on Circle CI. Containers with no name are broken residues of // building the image and therefore will be ignored. continue; } boolean containerNameMatches = asList(containerNames).contains(containerName(id)); if (imageNameMatches || containerNameMatches) { matchingContainers.add(container); } } return matchingContainers; }
public List<Container> getSchedulerContainers() { return getContainers(false).stream().filter(container -> container.getImage().contains("elasticsearch-scheduler")).collect(Collectors.toList()); }
private Set<String> getRecentlyUsedImageIds(List<Image> images, List<Container> containers, Duration minImageAgeToDelete) { final Instant now = clock.instant(); // Add any already downloaded image to the list once images.forEach(image -> lastTimeUsedByImageId.putIfAbsent(image.getId(), now)); // Update last used time for all current containers containers.forEach(container -> lastTimeUsedByImageId.put(container.getImageId(), now)); // Return list of images that have been used within minImageAgeToDelete return lastTimeUsedByImageId.entrySet().stream() .filter(entry -> Duration.between(entry.getValue(), now).minus(minImageAgeToDelete).isNegative()) .map(Map.Entry::getKey) .collect(Collectors.toSet()); }
if (imageIdRes.equalsIgnoreCase(container.getImage())) { String inspectRespSerialized = launcher.getChannel().call(new StartContainerRemoteCallable(cfgData, descriptor, container.getId())); console.logInfo("started container id " + container.getId()); EnvInvisibleAction envAction = new EnvInvisibleAction(inspectResp); build.addAction(envAction);
public boolean isServiceReady() { try { List<Container> allContainers = dockerClient.listContainersCmd().withShowAll(true).exec(); for (Container container : allContainers) { if (asList(container.getNames()).contains("/" + otherContainerName) && !container.getStatus().contains("Exited")) { return true; } } } catch (DockerException e) { return false; } return false; }