From 9251c91186e34ce3eeaa0675655a68ff21ed8fb7 Mon Sep 17 00:00:00 2001 From: Balazs Zsoldos Date: Sun, 19 Sep 2021 22:51:28 +0200 Subject: [PATCH] Add support to stop docker containers during VM shutdown --- .../io/fabric8/maven/docker/StopMojo.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/main/java/io/fabric8/maven/docker/StopMojo.java b/src/main/java/io/fabric8/maven/docker/StopMojo.java index dec5c1559..9cc6deea7 100644 --- a/src/main/java/io/fabric8/maven/docker/StopMojo.java +++ b/src/main/java/io/fabric8/maven/docker/StopMojo.java @@ -11,6 +11,7 @@ import java.util.regex.Matcher; import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; @@ -71,6 +72,41 @@ public class StopMojo extends AbstractDockerMojo { @Parameter(property = "docker.stopNamePattern") private String stopNamePattern; + /** + * If true, the containers are not stopped right away, but when the build is finished (success or failed). + */ + @Parameter(property = "docker.executeStopOnVMShutdown", defaultValue = "false") + private boolean executeStopOnVMShutdown; + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + if (this.executeStopOnVMShutdown) { + this.executeStopOnVMShutdown = false; + if (!invokedTogetherWithDockerStart()) { + throw new MojoExecutionException("docker:stop with executeStopOnVMShutdown is only possible if" + + " the docker containers started within the same maven session."); + } + + try { + // HttpDelete class is not used during start mojo, so we need to load it and initialize it. It is not + // possible to load classes in the shutdown hook as + Class.forName("org.apache.http.client.methods.HttpDelete", true, this.getClass().getClassLoader()); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + try { + super.execute(); + } catch (MojoExecutionException | MojoFailureException e) { + e.printStackTrace(); + } + })); + } else { + super.execute(); + } + } + @Override protected void executeInternal(ServiceHub hub) throws MojoExecutionException, IOException, ExecException { QueryService queryService = hub.getQueryService();