Skip to content

Commit

Permalink
#481 : Enhanced logging, adde 'machine' profile for sample to use a m…
Browse files Browse the repository at this point in the history
…achine "maven"
  • Loading branch information
rhuss committed Jun 27, 2016
1 parent 6f1dd97 commit 513f289
Show file tree
Hide file tree
Showing 6 changed files with 124 additions and 74 deletions.
19 changes: 13 additions & 6 deletions doc/manual/global-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,16 @@ be specified by the certPath or machine configuration, or by the
* **skip** (`docker.skip`)
With this parameter the execution of this plugin can be skipped
completely.
* **skip.build** (`docker.skip.build`)
* **skipBuild** (`docker.skip.build`)
If set not images will be build (which implies also *skip.tag*) with `docker:build`
* **skip.push** (`docker.skip.push`)
* **skipPush** (`docker.skip.push`)
If set dont push any images even when `docker:push` is called.
* **skip.run** (`docker.skip.run`)
* **skipRun** (`docker.skip.run`)
If set dont create and start any containers with `docker:start` or `docker:run`
* **skip.tag** (`docker.skip.tag`)
* **skipTag** (`docker.skip.tag`)
If set to `true` this plugin won't add any tags to images that have been built with `docker:build`
* **skipMachine** (`docker.skip.machine`)
Skip using docker machine in any case
* **sourceDirectory** (`docker.source.dir`) specifies the default directory that contains
the assembly descriptor(s) used by the plugin. The default value is `src/main/docker`. This
option is only relevant for the `docker:build` goal.
Expand All @@ -118,19 +120,24 @@ docker-maven-plugin supports also Docker machine (which must be installed locall
A Docker machine configuration can be provided with a top-level `<machine>` configuration section.
This configuration section knows the following options:

* **name** for the Docker machine's name
* **name** for the Docker machine's name. Default is `default`
* **autoCreate** if set to `true` then a Docker machine will automatically created. Default is `false`.
* **createOptions** is a map with options for Docker machine when auto-creating a machine. See the docker machine
documentation for possible options.

When no Docker host is configured or available as environment variable, then the configured Docker machine
is used. If the machine exists but is not running, it is started automatically. If it does not exists but `autoCreate`
is true, then the machine is created and started. Otherwise an error is printed.
is true, then the machine is created and started. Otherwise an error is printed. Please note, that a machine
which has been created because of `autoCreate` gets never deleted by docker-maven-plugin. This needs to be done manually
if required.

In absent of a `<machine>` configuration section the Maven property `docker.machine.name` can be used to provide
the name of a Docker machine. Similarly the property `docker.machine.autoCreate` can be set to true for creating
a Docker machine, too.

You can use the property `docker.skip.machine` if you want to override the internal detection mechanism to always
disable docker machine support.

Example:

````xml
Expand Down
27 changes: 21 additions & 6 deletions samples/data-jolokia-demo/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,6 @@
<artifactId>docker-maven-plugin</artifactId>
<extensions>true</extensions> <!-- enables using 'docker' packaging above -->
<configuration>
<machine>
<createOptions>
<driver>virtualbox</driver>
</createOptions>
</machine>

<watchInterval>500</watchInterval>
<logDate>default</logDate>
<verbose>true</verbose>
Expand Down Expand Up @@ -512,5 +506,26 @@
</plugins>
</build>
</profile>

<profile>
<id>machine</id>
<build>
<plugins>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<configuration>
<machine>
<name>maven</name>
<autoCreate>true</autoCreate>
<createOptions>
<driver>virtualbox</driver>
</createOptions>
</machine>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
16 changes: 12 additions & 4 deletions src/main/java/io/fabric8/maven/docker/AbstractDockerMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,12 @@ public abstract class AbstractDockerMojo extends AbstractMojo implements Context
@Parameter(property = "docker.skip", defaultValue = "false")
private boolean skip;

/**
* Whether the usage of docker machine should be skipped competely
*/
@Parameter(property = "docker.skip.machine", defaultValue = "false")
private boolean skipMachine;

/**
* Whether to restrict operation to a single image. This can be either
* the image or an alias name. It can also be comma separated list.
Expand Down Expand Up @@ -274,10 +280,12 @@ private DockerAccess createDockerAccess(String minimalVersion) throws MojoExecut
private DockerConnectionDetector createDockerConnectionDetector() {
if (machine == null) {
Properties projectProps = project.getProperties();
if (projectProps.containsKey(DockerMachineConfiguration.DOCKER_MACHINE_NAME_PROP)) {
machine = new DockerMachineConfiguration(
projectProps.getProperty(DockerMachineConfiguration.DOCKER_MACHINE_NAME_PROP),
projectProps.getProperty(DockerMachineConfiguration.DOCKER_MACHINE_AUTO_CREATE_PROP));
if (!skipMachine) {
if (projectProps.containsKey(DockerMachineConfiguration.DOCKER_MACHINE_NAME_PROP)) {
machine = new DockerMachineConfiguration(
projectProps.getProperty(DockerMachineConfiguration.DOCKER_MACHINE_NAME_PROP),
projectProps.getProperty(DockerMachineConfiguration.DOCKER_MACHINE_AUTO_CREATE_PROP));
}
}
}
return new DockerConnectionDetector(log, machine);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,4 @@ private String getValueWithFallback(String value, String envVar) throws MojoExec
return null;
}
}


}
124 changes: 73 additions & 51 deletions src/main/java/io/fabric8/maven/docker/access/DockerMachine.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,13 @@
package io.fabric8.maven.docker.access;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;

import io.fabric8.maven.docker.config.DockerMachineConfiguration;
import io.fabric8.maven.docker.util.Logger;
import org.apache.maven.plugin.MojoExecutionException;

import io.fabric8.maven.docker.config.DockerMachineConfiguration;

/**
* launch docker-machine to obtain environment settings
*/
Expand All @@ -36,18 +22,18 @@ public DockerMachine(Logger log, DockerMachineConfiguration machine) throws Mojo

Status status = new StatusCommand().getStatus();
switch (status) {
case DoesNotExist:
if (Boolean.TRUE == machine.getAutoCreate()) {
new CreateCommand().execute();
} else {
throw new MojoExecutionException(machine.getName() + " does not exist and docker.machine.autoCreate is false");
}
break;
case Running:
break;
case Stopped:
new StartCommand().execute();
break;
case DoesNotExist:
if (Boolean.TRUE == machine.getAutoCreate()) {
new CreateCommand().execute();
} else {
throw new MojoExecutionException(machine.getName() + " does not exist and docker.machine.autoCreate is false");
}
break;
case Running:
break;
case Stopped:
new StartCommand().execute();
break;
}
}

Expand All @@ -65,6 +51,7 @@ abstract class DockerCommand {

void execute() throws MojoExecutionException {
final Process process = startDockerMachineProcess();
start();
try {
closeOutputStream(process.getOutputStream());
Future<IOException> stderrFuture = startStreamPump(process.getErrorStream());
Expand All @@ -75,12 +62,20 @@ void execute() throws MojoExecutionException {
} catch (MojoExecutionException e) {
process.destroy();
throw e;
} finally {
end();
}
if (statusCode != 0) {
throw new MojoExecutionException("docker-machine exited with status " + statusCode);
}

}

// Hooks for logging ...
protected void start() {}
protected void end() {}


private void checkProcessExit(Process process) {
try {
executor.shutdown();
Expand Down Expand Up @@ -112,7 +107,7 @@ private Process startDockerMachineProcess(String... args) throws MojoExecutionEx

private void outputStreamPump(final InputStream inputStream) throws MojoExecutionException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));) {
for (;;) {
for (; ; ) {
String line = reader.readLine();
if (line == null) {
break;
Expand All @@ -125,21 +120,21 @@ private void outputStreamPump(final InputStream inputStream) throws MojoExecutio
}

protected void processLine(String line) {
log.info(line);
log.verbose(line);
}

private Future<IOException> startStreamPump(final InputStream errorStream) {
return executor.submit(new Callable<IOException>() {
@Override
public IOException call() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));) {
for (;;) {
for (; ; ) {
String line = reader.readLine();
if (line == null) {
break;
}
synchronized (log) {
log.error(line);
log.warn(line);
}
}
return null;
Expand Down Expand Up @@ -168,20 +163,20 @@ private void stopStreamPump(Future<IOException> future) throws MojoExecutionExce
private static final int SET_PREFIX_LEN = SET_PREFIX.length();

// docker-machine env <name>
class EnvCommand extends DockerCommand {
private class EnvCommand extends DockerCommand {

private final Map<String, String> env = new HashMap<>();

@Override
protected String[] getArgs() {
return new String[] { "docker-machine", "env", machine.getName(), "--shell", "cmd" };
return new String[]{"docker-machine", "env", machine.getName(), "--shell", "cmd"};
}

@Override
protected void processLine(String line) {
if(log.isDebugEnabled()) {
log.verbose("%s", line);
}
if (log.isDebugEnabled()) {
log.verbose("%s", line);
}
if (line.startsWith(SET_PREFIX)) {
setEnvironmentVariable(line.substring(SET_PREFIX_LEN));
}
Expand All @@ -195,7 +190,7 @@ private void setEnvironmentVariable(String line) {
}
String name = line.substring(0, equals);
String value = line.substring(equals + 1);
log.info(name + "=" + value);
log.debug(name + "=" + value);
env.put(name, value);
}

Expand All @@ -206,19 +201,19 @@ public Map<String, String> getEnvironment() throws MojoExecutionException {
}

// docker-machine status <name>
class StatusCommand extends DockerCommand {
private class StatusCommand extends DockerCommand {

private Status status;
private String message;

@Override
protected String[] getArgs() {
return new String[] { "docker-machine", "status", machine.getName() };
return new String[]{"docker-machine", "status", machine.getName()};
}

@Override
protected void processLine(String line) {
log.verbose(line);
log.info("Docker machine \"%s\" is %s",machine.getName(),line.toLowerCase());
if ("Running".equals(line)) {
status = Status.Running;
} else if ("Stopped".equals(line)) {
Expand All @@ -231,12 +226,10 @@ protected void processLine(String line) {
public Status getStatus() throws MojoExecutionException {
try {
execute();
}
catch(MojoExecutionException ex) {
if(statusCode==1) {
} catch (MojoExecutionException ex) {
if (statusCode == 1) {
status = Status.DoesNotExist;
}
else {
} else {
throw ex;
}
}
Expand All @@ -248,7 +241,9 @@ public Status getStatus() throws MojoExecutionException {
}

// docker-machine create --driver virtualbox <name>
class CreateCommand extends DockerCommand {
private class CreateCommand extends DockerCommand {

private long start;

@Override
protected String[] getArgs() {
Expand All @@ -267,14 +262,41 @@ protected String[] getArgs() {
args.add(machine.getName());
return args.toArray(new String[args.size()]);
}

@Override
protected void start() {
log.info("Creating docker machine \"%s\" with args %s",
machine.getName(),
machine.getCreateOptions() != null ? machine.getCreateOptions().toString() : "");
log.info("This might take a while ...");
start = System.currentTimeMillis();
}

@Override
protected void end() {
log.info("Created docker machine \"%s\" in %d seconds",machine.getName(), (System.currentTimeMillis() - start) / 1000);
}
}

// docker-machine start <name>
class StartCommand extends DockerCommand {
private class StartCommand extends DockerCommand {

private long start;

@Override
protected String[] getArgs() {
return new String[] { "docker-machine", "start", machine.getName() };
return new String[]{"docker-machine", "start", machine.getName()};
}

@Override
protected void start() {
log.info("Starting docker machine \"%s\"", machine.getName());
start = System.currentTimeMillis();
}

@Override
protected void end() {
log.info("Started docker machine \"%s\" in %d seconds",machine.getName(), (System.currentTimeMillis() - start) / 1000);
}
}
}
Loading

0 comments on commit 513f289

Please sign in to comment.