Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial implementation of containerNamePattern #1004

Merged
merged 8 commits into from Sep 24, 2018
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/main/java/io/fabric8/maven/docker/LogsMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ protected void executeInternal(ServiceHub hub) throws MojoExecutionException, Do
for (ImageConfiguration image : getResolvedImages()) {
String imageName = image.getName();
if (logAll) {
for (Container container : queryService.getContainersForImage(imageName)) {
for (Container container : queryService.getContainersForImage(imageName, false)) {
doLogging(logDispatcher, image, container.getId());
}
} else {
Expand Down
51 changes: 42 additions & 9 deletions src/main/java/io/fabric8/maven/docker/StartMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,45 @@
*/

import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import io.fabric8.maven.docker.access.*;
import io.fabric8.maven.docker.config.*;
import com.google.common.util.concurrent.MoreExecutors;
import io.fabric8.maven.docker.access.DockerAccessException;
import io.fabric8.maven.docker.access.ExecException;
import io.fabric8.maven.docker.access.PortMapping;
import io.fabric8.maven.docker.config.ConfigHelper;
import io.fabric8.maven.docker.config.ImageConfiguration;
import io.fabric8.maven.docker.config.LogConfiguration;
import io.fabric8.maven.docker.config.NetworkConfig;
import io.fabric8.maven.docker.config.RunImageConfiguration;
import io.fabric8.maven.docker.config.WaitConfiguration;
import io.fabric8.maven.docker.log.LogDispatcher;
import io.fabric8.maven.docker.model.Container;
import io.fabric8.maven.docker.service.*;
import io.fabric8.maven.docker.service.ImagePullManager;
import io.fabric8.maven.docker.service.QueryService;
import io.fabric8.maven.docker.service.RegistryService;
import io.fabric8.maven.docker.service.RunService;
import io.fabric8.maven.docker.service.ServiceHub;
import io.fabric8.maven.docker.util.ContainerNamingUtil;
import io.fabric8.maven.docker.util.StartOrderResolver;
import com.google.common.util.concurrent.MoreExecutors;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.*;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.util.StringUtils;


Expand Down Expand Up @@ -63,6 +90,12 @@ public class StartMojo extends AbstractDockerMojo {
@Parameter(property = "docker.exposeContainerInfo")
private String exposeContainerProps = "docker.container";

/**
* Naming pattern for how to name containers when started
*/
@Parameter(property = "docker.containerNamePattern")
private String containerNamePattern = ContainerNamingUtil.DEFAULT_CONTAINER_NAME_PATTERN;;

/**
* Whether to create the customs networks (user-defined bridge networks) before starting automatically
*/
Expand Down Expand Up @@ -138,7 +171,7 @@ public synchronized void executeInternal(final ServiceHub hub) throws DockerAcce
// Move from waiting to starting status
imagesStarting.add(image);
imagesWaitingToStart.remove(image);

if (!startParallel) {
waitForStartedContainer(hub, containerStartupService, startedContainerAliases, imagesStarting);
}
Expand Down Expand Up @@ -252,7 +285,7 @@ private void startImage(final ImageConfiguration image,
startingContainers.submit(new Callable<StartedContainer>() {
@Override
public StartedContainer call() throws Exception {
final String containerId = runService.createAndStartContainer(image, portMapping, getPomLabel(), projProperties, project.getBasedir());
final String containerId = runService.createAndStartContainer(image, portMapping, getPomLabel(), projProperties, project.getBasedir(), containerNamePattern, getBuildTimestamp());

// Update port-mapping writer
portMappingPropertyWriteHelper.add(portMapping, runConfig.getPortPropertyFile());
Expand Down
69 changes: 34 additions & 35 deletions src/main/java/io/fabric8/maven/docker/StopMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,21 @@
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.fabric8.maven.docker.access.DockerAccessException;
import io.fabric8.maven.docker.access.ExecException;
import io.fabric8.maven.docker.config.ImageConfiguration;
import io.fabric8.maven.docker.config.NetworkConfig;
import io.fabric8.maven.docker.config.RunImageConfiguration;
import io.fabric8.maven.docker.log.LogDispatcher;
import io.fabric8.maven.docker.model.Container;
import io.fabric8.maven.docker.model.Network;
import io.fabric8.maven.docker.service.QueryService;
import io.fabric8.maven.docker.service.RunService;
import io.fabric8.maven.docker.service.ServiceHub;
import io.fabric8.maven.docker.util.ContainerNamingUtil;
import io.fabric8.maven.docker.util.PomLabel;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
Expand Down Expand Up @@ -56,6 +54,12 @@ public class StopMojo extends AbstractDockerMojo {
@Parameter( property = "docker.sledgeHammer", defaultValue = "false" )
private boolean sledgeHammer;

/**
* Naming pattern for how to name containers when started
*/
@Parameter(property = "docker.containerNamePattern")
private String containerNamePattern = ContainerNamingUtil.DEFAULT_CONTAINER_NAME_PATTERN;

@Override
protected void executeInternal(ServiceHub hub) throws MojoExecutionException, DockerAccessException, ExecException {
QueryService queryService = hub.getQueryService();
Expand All @@ -76,40 +80,28 @@ protected void executeInternal(ServiceHub hub) throws MojoExecutionException, Do
dispatcher.untrackAllContainerLogs();
}

private void stopContainers(QueryService queryService, RunService runService, PomLabel pomLabel) throws DockerAccessException, ExecException {
private void stopContainers(QueryService queryService, RunService runService, PomLabel pomLabel) throws DockerAccessException, ExecException, MojoExecutionException {
Collection<Network> networksToRemove = getNetworksToRemove(queryService, pomLabel);
for (ImageConfiguration image : getResolvedImages()) {
for (Container container : getContainersToStop(queryService, image)) {
if (shouldStopContainer(container, pomLabel, image)) {

Collection<Container> existingContainers =
ContainerNamingUtil.getContainersToStop(image,
containerNamePattern,
getBuildTimestamp(),
queryService.getContainersForImage(image.getName(), false));
for (Container container : existingContainers) {
if (shouldStopContainer(container, pomLabel)) {
runService.stopContainer(container.getId(), image, keepContainer, removeVolumes);
}
}
}
runService.removeCustomNetworks(networksToRemove);
}

// If naming strategy is alias stop a container with this name, otherwise get all containers with this image's name
private List<Container> getContainersToStop(QueryService queryService, ImageConfiguration image) throws DockerAccessException {
RunImageConfiguration.NamingStrategy strategy = image.getRunConfiguration().getNamingStrategy();

if (strategy == RunImageConfiguration.NamingStrategy.alias) {
Container container = queryService.getContainer(image.getAlias());
return container != null ? Collections.singletonList(container) : Collections.<Container>emptyList();
} else {
return queryService.getContainersForImage(image.getName());
}
}

private boolean shouldStopContainer(Container container, PomLabel pomLabel, ImageConfiguration image) {
private boolean shouldStopContainer(Container container, PomLabel pomLabel) {
if (isStopAllContainers()) {
return true;
}

RunImageConfiguration.NamingStrategy strategy = image.getRunConfiguration().getNamingStrategy();
if (RunImageConfiguration.NamingStrategy.alias.equals(strategy)) {
return container.getName().equals(image.getAlias());
}

String key = pomLabel.getKey();
Map<String, String> labels = container.getLabels();
return labels.containsKey(key) && pomLabel.equals(new PomLabel(labels.get(key)));
Expand All @@ -124,30 +116,37 @@ private boolean invokedTogetherWithDockerStart() {
return startCalled != null && startCalled;
}

private Set<Network> getNetworksToRemove(QueryService queryService, PomLabel pomLabel) throws DockerAccessException {
private Set<Network> getNetworksToRemove(QueryService queryService, PomLabel pomLabel) throws DockerAccessException, MojoExecutionException {
if (!autoCreateCustomNetworks) {
return Collections.emptySet();
}
Set<Network> customNetworks = new HashSet<>();
Set<Network> networks = queryService.getNetworks();

for (ImageConfiguration image : getResolvedImages()) {

final NetworkConfig config = image.getRunConfiguration().getNetworkingConfig();
if (config.isCustomNetwork()) {
Network network = getNetworkByName(networks, config.getCustomNetwork());
if (network != null) {
customNetworks.add(network);
for (Container container : getContainersToStop(queryService, image)) {
if (!shouldStopContainer(container, pomLabel, image)) {
// it's sill in use don't collect it
customNetworks.remove(network);
}
final Network network = getNetworkByName(networks, config.getCustomNetwork());

if (config.isCustomNetwork() && network != null) {
customNetworks.add(network);
Collection<Container> existingContainers =
ContainerNamingUtil.getContainersToStop(image,
containerNamePattern,
getBuildTimestamp(),
queryService.getContainersForImage(image.getName(), false));

for (Container container : existingContainers) {
if (!shouldStopContainer(container, pomLabel)) {
// it's sill in use don't collect it
customNetworks.remove(network);
}
}
}
}
return customNetworks;
}

private Network getNetworkByName(Set<Network> networks, String networkName) {
for (Network network : networks) {
if (networkName.equals(network.getName())) {
Expand Down
9 changes: 9 additions & 0 deletions src/main/java/io/fabric8/maven/docker/WatchMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import io.fabric8.maven.docker.service.ServiceHub;
import io.fabric8.maven.docker.service.WatchService;

import io.fabric8.maven.docker.util.ContainerNamingUtil;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
Expand Down Expand Up @@ -60,6 +61,12 @@ public class WatchMojo extends AbstractBuildSupportMojo {
@Parameter(property = "docker.watchPostExec")
private String watchPostExec;

/**
* Naming pattern for how to name containers when started
*/
@Parameter(property = "docker.containerNamePattern")
private String containerNamePattern = ContainerNamingUtil.DEFAULT_CONTAINER_NAME_PATTERN;

/**
* Whether to create the customs networks (user-defined bridge networks) before starting automatically
*/
Expand All @@ -86,6 +93,8 @@ protected WatchService.WatchContext getWatchContext() throws MojoExecutionExcept
.keepContainer(keepContainer)
.keepRunning(keepRunning)
.removeVolumes(removeVolumes)
.containerNamePattern(containerNamePattern)
.buildTimestamp(getBuildTimestamp())
.pomLabel(getPomLabel())
.mojoParameters(createMojoParameters())
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,11 @@ public interface DockerAccess {
* can be tuned with a global parameters.
*
* @param image for which its container are looked up
* @param all whether to fetch also stopped containers. If false only running containers are returned
* @return list of <code>Container</code> objects or an empty list if none is found
* @throws DockerAccessException if the request fails
*/
List<Container> getContainersForImage(String image) throws DockerAccessException;
List<Container> getContainersForImage(String image, boolean all) throws DockerAccessException;

/**
* Starts a previously set up exec instance (via {@link #createExecContainer(String, Arguments)} container
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/io/fabric8/maven/docker/access/UrlBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ public String inspectExecContainer(String containerId) {
.build();
}

public String listContainers(String ... filter) {
Builder builder = u("containers/json");
public String listContainers(boolean all, String ... filter) {
Builder builder = u("containers/json").p("all", all);
addFilters(builder, filter);
return builder.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,15 +247,15 @@ public LogGetHandle getLogAsync(String containerId, LogCallback callback) {
}

@Override
public List<Container> getContainersForImage(String image) throws DockerAccessException {
public List<Container> getContainersForImage(String image, boolean all) throws DockerAccessException {
String url;
String serverApiVersion = getServerApiVersion();
if (EnvUtil.greaterOrEqualsVersion(serverApiVersion, "1.23")) {
// For Docker >= 1.11 we can use a new filter when listing containers
url = urlBuilder.listContainers("ancestor",image);
url = urlBuilder.listContainers(all, "ancestor",image);
} else {
// For older versions (< Docker 1.11) we need to iterate over the containers.
url = urlBuilder.listContainers();
url = urlBuilder.listContainers(all);
}

try {
Expand Down
Loading