diff --git a/.gitignore b/.gitignore index 2fc61df1..8f1fdc77 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ *.swp .project .settings +.classpath # Ignore all build/dist directories target @@ -18,3 +19,6 @@ target # Ignore all log files *.log + +#Ignore Test Output +test-output \ No newline at end of file diff --git a/README.md b/README.md index 5033aa47..a51128f7 100644 --- a/README.md +++ b/README.md @@ -1,112 +1,3 @@ -# docker-java +This project has moved to https://github.com/docker-java/docker-java +-------------------------------------------------------------------- -Java API client for [Docker](http://docs.docker.io/ "Docker") - -Supports Docker Client API v1.3, Server version 0.5.0 - -## Build with Maven - -###### Prerequisites: - -* Java 1.6+ -* Maven 3.0.5 -* Docker daemon running - - -By default maven will run tests during build process. Tests are using localhost instance of Docker, make sure that -you have Docker running, or the tests. - -Run docker: - - $ sudo docker -d - -Make sure that docker is up: - - $ docker version - Client version: 0.5.0 - Server version: 0.5.0 - Go version: go1.1 - -Run build with tests: - - $ mvn clean install - -If you don't have Docker running localy, you can skip tests with -DskipTests flag set to true: - - $ mvn clean install -DskipTests=true - -## Docker Java Client usage: - -To use Java Docker client, include dependency into your pom.xml: - - - com.kpelykh - docker-java - 1.0-SNAPSHOT - - -*Currently Docker Java client is not available in Maven Central, so you will need to install it to a local -repository, before you can use it in your projects.* - -## Example code snippets: - - DockerClient dockerClient = new DockerClient("http://localhost:4243"); - - -###### Get Docker info: - - Info info = dockerClient.info(); - System.out.print(info); - -###### Search Docker repository: - - List dockerSearch = dockerClient.search("busybox"); - System.out.println("Search returned" + dockerSearch.toString()); - -###### Create new Docker container, wait for its start and stop it: - - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[] {"touch", "/test"}); - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - - dockerClient.startContainer(container.id); - - dockerClient.waitContainer(container.id); - - dockerClient.stopContainer(container.id); - - -##### Docker Builder: - -To use Docker Builder, as described on page http://docs.docker.io/en/latest/use/builder/, -user dockerClient.build(baseDir), where baseDir is a path to folder containing Dockerfile. - - - File baseDir = new File("~/kpelykh/docker/netcat"); - - ClientResponse response = dockerClient.build(baseDir); - - StringWriter logwriter = new StringWriter(); - - try { - LineIterator itr = IOUtils.lineIterator(response.getEntityInputStream(), "UTF-8"); - while (itr.hasNext()) { - String line = itr.next(); - logwriter.write(line); - LOG.info(line); - } - } finally { - IOUtils.closeQuietly(response.getEntityInputStream()); - } - - - -For additional examples, please look at [DockerClientTest.java](https://github.com/kpelykh/docker-java/blob/master/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java "DockerClientTest.java") - - -## TODO - -Currently the following APIs are missing: - -export, history, login, push, tag diff --git a/pom.xml b/pom.xml index cbcb55f3..3de239d1 100644 --- a/pom.xml +++ b/pom.xml @@ -2,99 +2,151 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + + org.sonatype.oss + oss-parent + 7 + + com.kpelykh docker-java - 0.4.8-SNAPSHOT jar + 0.8.2-SNAPSHOT docker-java - + https://github.com/kpelykh/docker-java Java API Client for Docker + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:git@github.com:kpelykh/docker-java.git + git@github.com:kpelykh/docker-java.git + scm:git:git@github.com:kpelykh/docker-java.git + + + + + kpelykh + Konstantin Pelykh + kpelykh@gmail.com + + + + true + UTF-8 true false 1.6 1.6 - 5.12.1 + 1.6.1 + + 1.18 + 1.9 + + 2.3.3 + + 4.2.5 + 1.5 + 2.3 + 2.6 + 1.7.5 + 1.3.9 + 0.3 + + 1.0.1 - 1.17.1 - + 5.12.1 + 1.3 + 1.6 + 2.3.3 - - - Konstantin Pelykh - kpelykh@gmail.com - - + + 2.2 + 2.3.1 + 2.3.1 + 2.8.1 + 2.5.1 + 1.7 + - com.sun.jersey - jersey-core - ${jersey-version} + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-jaxrs.version} com.sun.jersey - jersey-client - ${jersey-version} + jersey-core + ${jersey.version} com.sun.jersey - jersey-json - ${jersey-version} + jersey-client + ${jersey.version} + com.sun.jersey.contribs jersey-multipart - ${jersey-version} + ${jersey.version} com.sun.jersey.contribs jersey-apache-client4 - 1.9 + ${jersey-apache-client4.version} - org.apache.httpcomponents httpclient - 4.2.5 + ${httpclient.version} org.apache.commons commons-compress - 1.5 + ${commons-compress.version} commons-lang commons-lang - 2.6 + ${commons-lang.version} commons-io commons-io - 2.3 + ${commons-io.version} + + com.github.jnr + jnr-unixsocket + ${jnr.unixsocket.version} + org.slf4j slf4j-api - 1.7.5 + ${slf4j-api.version} - com.google.code.findbugs - jsr305 - true - 1.3.9 + org.slf4j + jul-to-slf4j + ${slf4j-api.version} - ch.qos.logback @@ -120,14 +172,14 @@ org.hamcrest hamcrest-library - 1.3 + ${hamcrest.library.version} test com.googlecode.lambdaj lambdaj - 2.3.3 + ${lambdaj.version} test @@ -140,141 +192,114 @@ org.testinfected.hamcrest-matchers jpa-matchers - 1.6 + ${hamcrest.jpa-matchers} test - + + + + com.github.jnr + jffi + 1.2.7 + + + com.github.jnr + jffi + native + 1.2.7 + + + - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.1 - - ${jdk.source} - ${jdk.target} - utf-8 - ${jdk.debug} - ${jdk.optimize} - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - - test-jar - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.8.1 - - - - - org.codehaus.mojo - cobertura-maven-plugin - 2.5.1 - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.7 - - - validate - - run - - - - ******************************************************************* - ******************************************************************* - [project.name] : ${project.name} - [project.basedir] : ${project.basedir} - [project.version] : ${project.version} - [project.artifactId] ${project.artifactId} - [project.build.directory] ${project.build.directory} - [jdk.source] : ${jdk.source} - [jdk.target] : ${jdk.target} - [jdk.debug] : ${jdk.debug} - [jdk.optimize] : ${jdk.optimize} - [source encoding]: ${project.build.sourceEncoding} - [M2_HOME] : ${env.M2_HOME} - [LocalRepository] : ${settings.localRepository} - ******************************************************************* - ******************************************************************* - - - - - - - - - org.apache.maven.plugins - maven-site-plugin - 3.0 - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8.1 - - private - - - author - a - Author: - - - todo - a - To Do: - - - - - - org.apache.maven.plugins - maven-jxr-plugin - 2.1 + + + + + org.apache.maven.plugins + maven-release-plugin + ${maven-release-plugin.version} + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${jdk.source} + ${jdk.target} + ISO-8859-1 + ${jdk.debug} + ${jdk.optimize} + + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven-jar-plugin.version} + + + + test-jar + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + ${skipTests} + + + + + + org.codehaus.mojo + cobertura-maven-plugin + ${cobertura-maven-plugin.version} + + + + org.apache.maven.plugins + maven-antrun-plugin + ${maven-antrun-plugin.version} + + + validate + + run + - true + + ******************************************************************* + ******************************************************************* + [project.name] : ${project.name} + [project.basedir] : ${project.basedir} + [project.version] : ${project.version} + [project.artifactId] ${project.artifactId} + [project.build.directory] ${project.build.directory} + [jdk.source] : ${jdk.source} + [jdk.target] : ${jdk.target} + [jdk.debug] : ${jdk.debug} + [jdk.optimize] : ${jdk.optimize} + [source encoding]: ${project.build.sourceEncoding} + [LocalRepository] : ${settings.localRepository} + ******************************************************************* + ******************************************************************* + - - - org.apache.maven.plugins - maven-surefire-report-plugin - 2.10 - - - org.codehaus.mojo - taglist-maven-plugin - 2.4 - - - - - - + + + + + + diff --git a/src/main/java/com/google/common/base/Preconditions.java b/src/main/java/com/google/common/base/Preconditions.java index 05a514bb..6a15fb4d 100644 --- a/src/main/java/com/google/common/base/Preconditions.java +++ b/src/main/java/com/google/common/base/Preconditions.java @@ -17,8 +17,6 @@ package com.google.common.base; -import javax.annotation.Nullable; - import java.util.NoSuchElementException; /** @@ -84,7 +82,7 @@ public static void checkArgument(boolean expression) { * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument( - boolean expression, @Nullable Object errorMessage) { + boolean expression, Object errorMessage) { if (!expression) { throw new IllegalArgumentException(String.valueOf(errorMessage)); } @@ -110,8 +108,8 @@ public static void checkArgument( * this happen) */ public static void checkArgument(boolean expression, - @Nullable String errorMessageTemplate, - @Nullable Object... errorMessageArgs) { + String errorMessageTemplate, + Object... errorMessageArgs) { if (!expression) { throw new IllegalArgumentException( format(errorMessageTemplate, errorMessageArgs)); @@ -141,7 +139,7 @@ public static void checkState(boolean expression) { * @throws IllegalStateException if {@code expression} is false */ public static void checkState( - boolean expression, @Nullable Object errorMessage) { + boolean expression, Object errorMessage) { if (!expression) { throw new IllegalStateException(String.valueOf(errorMessage)); } @@ -167,8 +165,8 @@ public static void checkState( * this happen) */ public static void checkState(boolean expression, - @Nullable String errorMessageTemplate, - @Nullable Object... errorMessageArgs) { + String errorMessageTemplate, + Object... errorMessageArgs) { if (!expression) { throw new IllegalStateException( format(errorMessageTemplate, errorMessageArgs)); @@ -200,7 +198,7 @@ public static T checkNotNull(T reference) { * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ - public static T checkNotNull(T reference, @Nullable Object errorMessage) { + public static T checkNotNull(T reference, Object errorMessage) { if (reference == null) { throw new NullPointerException(String.valueOf(errorMessage)); } @@ -225,8 +223,8 @@ public static T checkNotNull(T reference, @Nullable Object errorMessage) { * @throws NullPointerException if {@code reference} is null */ public static T checkNotNull(T reference, - @Nullable String errorMessageTemplate, - @Nullable Object... errorMessageArgs) { + String errorMessageTemplate, + Object... errorMessageArgs) { if (reference == null) { // If either of these parameters is null, the right thing happens anyway throw new NullPointerException( @@ -296,7 +294,7 @@ public static int checkElementIndex(int index, int size) { * @throws IllegalArgumentException if {@code size} is negative */ public static int checkElementIndex( - int index, int size, @Nullable String desc) { + int index, int size, String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(badElementIndex(index, size, desc)); @@ -346,7 +344,7 @@ public static int checkPositionIndex(int index, int size) { * @throws IllegalArgumentException if {@code size} is negative */ public static int checkPositionIndex( - int index, int size, @Nullable String desc) { + int index, int size, String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index > size) { throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc)); @@ -410,7 +408,7 @@ private static String badPositionIndexes(int start, int end, int size) { * template. Arguments are converted to strings using * {@link String#valueOf(Object)}. Arguments can be null. */ - static String format(String template, @Nullable Object... args) { + static String format(String template, Object... args) { template = String.valueOf(template); // null -> "null" // start substituting the arguments into the '%s' placeholders diff --git a/src/main/java/com/kpelykh/docker/client/Config.java b/src/main/java/com/kpelykh/docker/client/Config.java new file mode 100644 index 00000000..f6e59d76 --- /dev/null +++ b/src/main/java/com/kpelykh/docker/client/Config.java @@ -0,0 +1,57 @@ +package com.kpelykh.docker.client; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URI; +import java.util.Properties; + +class Config { + URI url; + String version, username, password, email; + + private Config() { + } + + static Config createConfig() throws DockerException { + final Properties p = new Properties(); + + try { + p.load(Config.class.getResourceAsStream("/docker.io.properties")); + } catch (IOException e) { + throw new DockerException(e); + } + + final File file = new File(System.getProperty("user.home"), ".docker.io.properties"); + + if (file.isFile()) { + try { + final FileInputStream in = new FileInputStream(file); + try { + p.load(in); + } finally { + in.close(); + } + } catch (IOException e) { + throw new DockerException(e); + } + } + + for (String s : new String[]{"url", "version", "username", "password", "email"}) { + final String key = "docker.io." + s; + if (System.getProperties().keySet().contains(key)) { + p.setProperty(key, System.getProperty(key)); + } + } + + final Config c = new Config(); + + c.url = URI.create(p.getProperty("docker.io.url")); + c.version = p.getProperty("docker.io.version"); + c.username = p.getProperty("docker.io.username"); + c.password = p.getProperty("docker.io.password"); + c.email = p.getProperty("docker.io.email"); + + return c; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/DockerClient.java b/src/main/java/com/kpelykh/docker/client/DockerClient.java index deae28b1..101d7209 100644 --- a/src/main/java/com/kpelykh/docker/client/DockerClient.java +++ b/src/main/java/com/kpelykh/docker/client/DockerClient.java @@ -1,673 +1,954 @@ package com.kpelykh.docker.client; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Preconditions; import com.kpelykh.docker.client.model.*; import com.kpelykh.docker.client.utils.CompressArchiveUtil; import com.kpelykh.docker.client.utils.JsonClientFilter; import com.sun.jersey.api.client.*; +import com.sun.jersey.api.client.WebResource.Builder; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.json.JSONConfiguration; +import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.client.apache4.ApacheHttpClient4; import com.sun.jersey.client.apache4.ApacheHttpClient4Handler; import com.sun.jersey.core.util.MultivaluedMapImpl; + +import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.io.LineIterator; import org.apache.commons.lang.StringUtils; import org.apache.http.client.HttpClient; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; -import org.codehaus.jettison.json.JSONException; -import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; + import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.StringWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; import java.util.List; import java.util.UUID; +import static org.apache.commons.io.IOUtils.closeQuietly; + /** - * * @author Konstantin Pelykh (kpelykh@gmail.com) - * */ -public class DockerClient -{ +public class DockerClient { - private static final Logger LOGGER = LoggerFactory.getLogger(DockerClient.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DockerClient.class); - private static DockerClient instance; private Client client; - private String restEndpointUrl; - - public DockerClient(String serverUrl) { - restEndpointUrl = serverUrl + "/v1.3"; - ClientConfig clientConfig = new DefaultClientConfig(); - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - SchemeRegistry schemeRegistry = new SchemeRegistry(); - schemeRegistry.register(new Scheme("http", 4243, PlainSocketFactory.getSocketFactory())); - - PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); - // Increase max total connection - cm.setMaxTotal(1000); - // Increase default max connection per route - cm.setDefaultMaxPerRoute(1000); - - HttpClient httpClient = new DefaultHttpClient(cm); - client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, null, false), clientConfig); - - client.addFilter(new JsonClientFilter()); - //client.addFilter(new LoggingFilter()); - } - - /** - ** MISC API - ** - **/ - - public Info info() throws DockerException { - WebResource webResource = client.resource(restEndpointUrl + "/info"); - - try { - LOGGER.trace("GET: " + webResource.toString()); - return webResource.accept(MediaType.APPLICATION_JSON).get(Info.class); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error.", exception); - } else { - throw new DockerException(exception); - } - } - } - - - public Version version() throws DockerException { - WebResource webResource = client.resource(restEndpointUrl + "/version"); - - try { - LOGGER.trace("GET: " + webResource.toString()); - return webResource.accept(MediaType.APPLICATION_JSON).get(Version.class); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error.", exception); - } else { - throw new DockerException(exception); - } - } + private String restEndpointUrl; + private AuthConfig authConfig; + + public DockerClient() throws DockerException { + this(Config.createConfig()); + } + + public DockerClient(String serverUrl) throws DockerException { + this(configWithServerUrl(serverUrl)); + } + + private static Config configWithServerUrl(String serverUrl) throws DockerException { + final Config c = Config.createConfig(); + c.url = URI.create(serverUrl); + return c; + } + + private DockerClient(Config config) { + restEndpointUrl = config.url + "/v" + config.version; + ClientConfig clientConfig = new DefaultClientConfig(); + //clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + SchemeRegistry schemeRegistry = new SchemeRegistry(); + schemeRegistry.register(new Scheme("http", config.url.getPort(), PlainSocketFactory.getSocketFactory())); + schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); + + PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); + // Increase max total connection + cm.setMaxTotal(1000); + // Increase default max connection per route + cm.setDefaultMaxPerRoute(1000); + + HttpClient httpClient = new DefaultHttpClient(cm); + client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, null, false), clientConfig); + + client.setReadTimeout(10000); + //Experimental support for unix sockets: + //client = new UnixSocketClient(clientConfig); + + client.addFilter(new JsonClientFilter()); + client.addFilter(new LoggingFilter()); + } + + public void setCredentials(String username, String password, String email) { + if (username == null) { + throw new IllegalArgumentException("username is null"); + } + if (password == null) { + throw new IllegalArgumentException("password is null"); + } + if (email == null) { + throw new IllegalArgumentException("email is null"); + } + authConfig = new AuthConfig(); + authConfig.setUsername(username); + authConfig.setPassword(password); + authConfig.setEmail(email); + } + + /** + * Authenticate with the server, useful for checking authentication. + */ + public void auth() throws DockerException { + try { + client.resource(restEndpointUrl + "/auth") + .header("Content-Type", MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .post(authConfig()); + } catch (UniformInterfaceException e) { + throw new DockerException(e); + } + } + + private String registryAuth() throws DockerException { + try { + return Base64.encodeBase64String(new ObjectMapper().writeValueAsString(authConfig()).getBytes()); + } catch (IOException e) { + throw new DockerException(e); + } + } + + public AuthConfig authConfig() throws DockerException { + return authConfig != null + ? authConfig + : authConfigFromProperties(); + } + + private static AuthConfig authConfigFromProperties() throws DockerException { + final AuthConfig a = new AuthConfig(); + + a.setUsername(Config.createConfig().username); + a.setPassword(Config.createConfig().password); + a.setEmail(Config.createConfig().email); + + if (a.getUsername() == null) {throw new IllegalStateException("username is null");} + if (a.getPassword() == null) {throw new IllegalStateException("password is null");} + if (a.getEmail() == null) {throw new IllegalStateException("email is null");} + + return a; } /** - ** IMAGE API - ** - **/ - - public ClientResponse pull(String repository) throws DockerException { - return this.pull(repository, null, null); - } - - public ClientResponse pull(String repository, String tag) throws DockerException { - return this.pull(repository, tag, null); - } - - public ClientResponse pull(String repository, String tag, String registry) throws DockerException { - Preconditions.checkNotNull(repository, "Repository was not specified"); - - if (StringUtils.countMatches(repository, ":") == 1) { - String repositoryTag[] = StringUtils.split(repository); - repository = repositoryTag[0]; - tag = repositoryTag[1]; - - } - - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("tag", tag); - params.add("fromImage", repository); - params.add("registry", registry); - - WebResource webResource = client.resource(restEndpointUrl + "/images/create").queryParams(params); - - try { - LOGGER.trace("POST: " + webResource.toString()); - return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ClientResponse.class); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error.", exception); - } else { - throw new DockerException(exception); - } - } - } - - public List search(String search) throws DockerException { - WebResource webResource = client.resource(restEndpointUrl + "/images/search").queryParam("term", search); - try { - return webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() {}); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error.", exception); - } else { - throw new DockerException(exception); - } - } - - } - - public void removeImage(String imageId) throws DockerException { - Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty"); - - try { - WebResource webResource = client.resource(restEndpointUrl + "/images/" + imageId); - LOGGER.trace("DELETE: " + webResource.toString()); - webResource.delete(); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 204) { - //no error - LOGGER.trace("Successfully removed image " + imageId); - } else if (exception.getResponse().getStatus() == 404) { - LOGGER.warn(String.format("%s no such image", imageId)); - } else if (exception.getResponse().getStatus() == 409) { - throw new DockerException("Conflict"); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error.", exception); - } else { - throw new DockerException(exception); - } - } - - } - - public void removeImages(List images) throws DockerException { - Preconditions.checkNotNull(images, "List of images can't be null"); - - for (String imageId : images) { - removeImage(imageId); - } - } - - public String getVizImages() throws DockerException { - WebResource webResource = client.resource(restEndpointUrl + "/images/viz"); - - try { - LOGGER.trace("GET: " + webResource.toString()); - String response = webResource.get(String.class); - LOGGER.trace("Response:" + response.toString()); - - return response; - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 400) { - throw new DockerException("bad parameter"); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } - } - - - public List getImages() throws DockerException { - return this.getImages(null, false); - } - - public List getImages(boolean allContainers) throws DockerException { - return this.getImages(null, allContainers); - } - - public List getImages(String name) throws DockerException { - return this.getImages(name, false); - } - - public List getImages(String name, boolean allImages) throws DockerException { - - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("filter", name); - params.add("all", allImages ? "1" : "0"); - - WebResource webResource = client.resource(restEndpointUrl + "/images/json").queryParams(params); - - try { - LOGGER.trace("GET: " + webResource.toString()); - List images = webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() {}); - LOGGER.trace("Response:" + images.toString()); - return images; - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 400) { - throw new DockerException("bad parameter"); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(); - } - } - - } - - public ImageInspectResponse inspectImage(String imageId) throws DockerException { - - WebResource webResource = client.resource(restEndpointUrl + String.format("/images/%s/json", imageId)); - - try { - LOGGER.trace("GET: " + webResource.toString()); - return webResource.accept(MediaType.APPLICATION_JSON).get(ImageInspectResponse.class); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 404) { - throw new DockerException(String.format("No such image %s", imageId)); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } - } - - /** - ** CONTAINER API - ** - **/ - - public List listContainers(boolean allContainers) { - return this.listContainers(allContainers, false, -1, false, null, null); - } - - public List listContainers(boolean allContainers, boolean latest) { - return this.listContainers(allContainers, latest, -1, false, null, null); - } - - public List listContainers(boolean allContainers, boolean latest, int limit) { - return this.listContainers(allContainers, latest, limit, false, null, null); - } - - public List listContainers(boolean allContainers, boolean latest, int limit, boolean showSize) { - return this.listContainers(allContainers, latest, limit, showSize, null, null); - } - - public List listContainers(boolean allContainers, boolean latest, int limit, boolean showSize, String since) { - return this.listContainers(allContainers, latest, limit, false, since, null); - } - - public List listContainers(boolean allContainers, boolean latest, int limit, boolean showSize, String since, String before) { - - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("limit", latest ? "1" : String.valueOf(limit)); - params.add("all", allContainers ? "1" : "0"); - params.add("since", since); - params.add("before", before); - params.add("size", showSize ? "1" : "0"); - - WebResource webResource = client.resource(restEndpointUrl + "/containers/json").queryParams(params); - LOGGER.trace("GET: " + webResource.toString()); - List containers = webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() {}); - LOGGER.trace("Response:" + containers.toString()); - - return containers; - } - - - public ContainerCreateResponse createContainer(ContainerConfig config) throws DockerException { - - WebResource webResource = client.resource(restEndpointUrl + "/containers/create"); - - try { - LOGGER.trace("POST: " + webResource.toString()); - return webResource.accept(MediaType.APPLICATION_JSON) - .type(MediaType.APPLICATION_JSON) - .post(ContainerCreateResponse.class, config); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 404) { - throw new DockerException(String.format("%s is an unrecognized image. Please pull the image first.", config.getImage())); - } else if (exception.getResponse().getStatus() == 406) { - throw new DockerException("impossible to attach (container not running)"); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } - - } - - public void startContainer(String containerId) throws DockerException { - this.startContainer(containerId, null); - } - - public void startContainer(String containerId, HostConfig hostConfig) throws DockerException { - - WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/start", containerId)); - - try { - LOGGER.trace("POST: " + webResource.toString()); - webResource.accept(MediaType.TEXT_PLAIN).type(MediaType.APPLICATION_JSON).post(hostConfig); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 404) { - throw new DockerException(String.format("No such container %s", containerId)); - } else if (exception.getResponse().getStatus() == 204) { - //no error - LOGGER.trace("Successfully started container " + containerId); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } - } - - public ContainerInspectResponse inspectContainer(String containerId) throws DockerException { - - WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/json", containerId)); - - try { - LOGGER.trace("GET: " + webResource.toString()); - return webResource.accept(MediaType.APPLICATION_JSON).get(ContainerInspectResponse.class); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 404) { - throw new DockerException(String.format("No such container %s", containerId)); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } - } - - - public void removeContainer(String container) throws DockerException { - this.removeContainer(container, false); - } - - public void removeContainer(String containerId, boolean removeVolumes) throws DockerException { - Preconditions.checkState(!StringUtils.isEmpty(containerId), "Container ID can't be empty"); - - WebResource webResource = client.resource(restEndpointUrl + "/containers/" + containerId).queryParam("v", removeVolumes ? "1" : "0"); - - try { - LOGGER.trace("DELETE: " + webResource.toString()); - String response = webResource.accept(MediaType.APPLICATION_JSON).delete(String.class); - LOGGER.trace("Response:" + response); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 204) { - //no error - LOGGER.trace("Successfully removed container " + containerId); - } else if (exception.getResponse().getStatus() == 400) { - throw new DockerException("bad parameter"); - } else if (exception.getResponse().getStatus() == 404) { - LOGGER.warn(String.format("%s is an unrecognized container.", containerId)); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } - } - - - public void removeContainers(List containers, boolean removeVolumes) throws DockerException { - Preconditions.checkNotNull(containers, "List of containers can't be null"); - - for (String containerId : containers) { - removeContainer(containerId, removeVolumes); - } - } - - public int waitContainer(String containerId) throws DockerException { - WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/wait", containerId)); - - try { - LOGGER.trace("POST: " + webResource.toString()); - JSONObject jsonObject = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(JSONObject.class); - return jsonObject.getInt("StatusCode"); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 404) { - throw new DockerException(String.format("No such container %s", containerId)); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } catch (JSONException e) { - throw new DockerException(e); - } - } - - - public ClientResponse logContainer(String containerId) throws DockerException { - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("logs", "1"); - params.add("stdout", "1"); - params.add("stderr", "1"); - //params.add("stream", "1"); this parameter keeps stream open indindefinitely - - WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/attach", containerId)) - .queryParams(params); - - try { - LOGGER.trace("POST: " + webResource.toString()); - return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ClientResponse.class, params); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 400) { - throw new DockerException("bad parameter"); - } else if (exception.getResponse().getStatus() == 404) { - throw new DockerException(String.format("No such container %s", containerId)); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } - } - - public List containterDiff(String containerId) throws DockerException { - - WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/changes", containerId)); - - try { - LOGGER.trace("GET: " + webResource.toString()); - return webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() {}); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 404) { - throw new DockerException(String.format("No such container %s", containerId)); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } - } - - - - - public void stopContainer(String containerId) throws DockerException { - this.stopContainer(containerId, 10); - } - - public void stopContainer(String containerId, int timeout) throws DockerException { - - WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/stop", containerId)) - .queryParam("t", String.valueOf(timeout)); - - - try { - LOGGER.trace("POST: " + webResource.toString()); - webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 404) { - LOGGER.warn(String.format("No such container %s", containerId)); - } else if (exception.getResponse().getStatus() == 204) { - //no error - LOGGER.trace("Successfully stopped container " + containerId); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } - } - - public void kill(String containerId) throws DockerException { - WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/kill", containerId)); - - try { - LOGGER.trace("POST: " + webResource.toString()); - webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 404) { - LOGGER.warn(String.format("No such container %s", containerId)); - } else if (exception.getResponse().getStatus() == 204) { - //no error - LOGGER.trace("Successfully killed container " + containerId); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } - } - - public void restart(String containerId, int timeout) throws DockerException { - WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/restart", containerId)); - - try { - LOGGER.trace("POST: " + webResource.toString()); - webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 404) { - throw new DockerException(String.format("No such container %s", containerId)); - } else if (exception.getResponse().getStatus() == 204) { - //no error - LOGGER.trace("Successfully restarted container " + containerId); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } - } - - public String commit(CommitConfig commitConfig) throws DockerException { - Preconditions.checkNotNull(commitConfig.container, "Container ID was not specified"); - - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("container", commitConfig.container); - params.add("repo", commitConfig.repo); - params.add("tag", commitConfig.tag); - params.add("m", commitConfig.message); - params.add("author", commitConfig.author); - params.add("run", commitConfig.run); - - WebResource webResource = client.resource(restEndpointUrl + "/commit").queryParams(params); - - try { - LOGGER.trace("POST: " + webResource.toString()); - JSONObject jsonObject = webResource.accept("application/vnd.docker.raw-stream").post(JSONObject.class, params); - return jsonObject.getString("Id"); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 404) { - throw new DockerException(String.format("No such container %s", commitConfig.container)); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } catch (JSONException e) { - throw new DockerException(e); - } - } - - - public ClientResponse build(File dockerFolder) throws DockerException { - return this.build(dockerFolder, null); - } - - public ClientResponse build(File dockerFolder, String tag) throws DockerException { - Preconditions.checkNotNull(dockerFolder, "Folder is null"); - Preconditions.checkArgument(dockerFolder.exists(), "Folder %s doesn't exist", dockerFolder); - Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(), "Dockerfile doesn't exist in " + dockerFolder); - - //We need to use Jersey HttpClient here, since ApacheHttpClient4 will not add boundary filed to - //Content-Type: multipart/form-data; boundary=Boundary_1_372491238_1372806136625 - - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("t", tag); - - // ARCHIVE TAR - String archiveNameWithOutExtension = UUID.randomUUID().toString(); - - File dockerFolderTar = null; - File tmpDockerContextFolder = null; - - try { - File dockerFile = new File(dockerFolder, "Dockerfile"); - List dockerFileContent = FileUtils.readLines(dockerFile); - - if (dockerFileContent.size() <= 0) { - throw new DockerException(String.format("Dockerfile %s is empty", dockerFile)); - } - - //Create tmp docker context folder - tmpDockerContextFolder = new File(FileUtils.getTempDirectoryPath(), "docker-java-build" + archiveNameWithOutExtension); - - FileUtils.copyFileToDirectory(dockerFile, tmpDockerContextFolder); - - for (String cmd : dockerFileContent) { - if (StringUtils.startsWithIgnoreCase(cmd.trim(), "ADD")) { - String addArgs[] = StringUtils.split(cmd, " \t"); - if (addArgs.length != 3) { - throw new DockerException(String.format("Wrong format on line [%s]", cmd)); - } - - File src = new File(addArgs[1]); - if (!src.isAbsolute()) { - src = new File(dockerFolder, addArgs[1]).getCanonicalFile(); - } - - if (!src.exists()) { - throw new DockerException(String.format("Sorce file %s doesnt' exist", src)); - } - if (src.isDirectory()) { - FileUtils.copyDirectory(src, tmpDockerContextFolder); - } else { - FileUtils.copyFileToDirectory(src, tmpDockerContextFolder); - } - } - } - - dockerFolderTar = CompressArchiveUtil.archiveTARFiles(tmpDockerContextFolder, archiveNameWithOutExtension); - - } catch (IOException ex) { - FileUtils.deleteQuietly(dockerFolderTar); - FileUtils.deleteQuietly(tmpDockerContextFolder); - throw new DockerException("Error occurred while preparing Docker context folder.", ex); - } - - WebResource webResource = client.resource(restEndpointUrl + "/build").queryParams(params); - - try { - LOGGER.trace("POST: " + webResource.toString()); - return webResource - .type("application/tar") - .accept(MediaType.TEXT_PLAIN) - .post(ClientResponse.class, FileUtils.openInputStream(dockerFolderTar)); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } catch (IOException e) { - throw new DockerException(e); - } finally { - FileUtils.deleteQuietly(dockerFolderTar); - FileUtils.deleteQuietly(tmpDockerContextFolder); - } - - } - + * * MISC API + * * + */ + + public Info info() throws DockerException { + WebResource webResource = client.resource(restEndpointUrl + "/info"); + + try { + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(Info.class); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error.", exception); + } else { + throw new DockerException(exception); + } + } + } + + + public Version version() throws DockerException { + WebResource webResource = client.resource(restEndpointUrl + "/version"); + + try { + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(Version.class); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error.", exception); + } else { + throw new DockerException(exception); + } + } + } + + + public int ping() throws DockerException { + WebResource webResource = client.resource(restEndpointUrl + "/_ping"); + + try { + LOGGER.trace("GET: {}", webResource); + ClientResponse resp = webResource.get(ClientResponse.class); + return resp.getStatus(); + } catch (UniformInterfaceException exception) { + throw new DockerException(exception); + } + } + + + /** + * * IMAGE API + * * + */ + + public ClientResponse pull(String repository) throws DockerException { + return this.pull(repository, null, null); + } + + public ClientResponse pull(String repository, String tag) throws DockerException { + return this.pull(repository, tag, null); + } + + public ClientResponse pull(String repository, String tag, String registry) throws DockerException { + Preconditions.checkNotNull(repository, "Repository was not specified"); + + if (StringUtils.countMatches(repository, ":") == 1) { + String repositoryTag[] = StringUtils.split(repository, ':'); + repository = repositoryTag[0]; + tag = repositoryTag[1]; + + } + + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("tag", tag); + params.add("fromImage", repository); + params.add("registry", registry); + + WebResource webResource = client.resource(restEndpointUrl + "/images/create").queryParams(params); + + try { + LOGGER.trace("POST: {}", webResource); + return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ClientResponse.class); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error.", exception); + } else { + throw new DockerException(exception); + } + } + } + + + + + /** + * @return The output slurped into a string. + */ + public static String asString(ClientResponse response) throws IOException { + + StringWriter out = new StringWriter(); + try { + LineIterator itr = IOUtils.lineIterator( + response.getEntityInputStream(), "UTF-8"); + while (itr.hasNext()) { + String line = itr.next(); + out.write(line + (itr.hasNext() ? "\n" : "")); + } + } finally { + closeQuietly(response.getEntityInputStream()); + } + return out.toString(); + } + + /** + * Push the latest image to the repository. + * + * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. + */ + public ClientResponse push(final String name) throws DockerException { + if (name == null) { + throw new IllegalArgumentException("name is null"); + } + try { + final String registryAuth = registryAuth(); + return client.resource(restEndpointUrl + "/images/" + name(name) + "/push") + .header("X-Registry-Auth", registryAuth) + .accept(MediaType.APPLICATION_JSON) + .post(ClientResponse.class); + } catch (UniformInterfaceException e) { + throw new DockerException(e); + } + } + + private String name(String name) { + return name.contains("/") ? name : authConfig.getUsername(); + } + + /** + * Tag an image into a repository + * + * @param image the local image to tag (either a name or an id) + * @param repository the repository to tag in + * @param tag any tag for this image + * @param force (not documented) + * @return the HTTP status code (201 for success) + */ + public int tag(String image, String repository, String tag, boolean force) throws DockerException { + Preconditions.checkNotNull(image, "image was not specified"); + Preconditions.checkNotNull(repository, "repository was not specified"); + Preconditions.checkNotNull(tag, " tag was not provided"); + + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("repo", repository); + params.add("tag", tag); + params.add("force", String.valueOf(force)); + + WebResource webResource = client.resource(restEndpointUrl + "/images/" + image + "/tag").queryParams(params); + + try { + LOGGER.trace("POST: {}", webResource); + ClientResponse resp = webResource.post(ClientResponse.class); + return resp.getStatus(); + } catch (UniformInterfaceException exception) { + throw new DockerException(exception); + } + } + + /** + * Create an image by importing the given stream of a tar file. + * + * @param repository the repository to import to + * @param tag any tag for this image + * @param imageStream the InputStream of the tar file + * @return an {@link ImageCreateResponse} containing the id of the imported image + * @throws DockerException if the import fails for some reason. + */ + public ImageCreateResponse importImage(String repository, String tag, InputStream imageStream) throws DockerException { + Preconditions.checkNotNull(repository, "Repository was not specified"); + Preconditions.checkNotNull(imageStream, "imageStream was not provided"); + + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("repo", repository); + params.add("tag", tag); + params.add("fromSrc", "-"); + + WebResource webResource = client.resource(restEndpointUrl + "/images/create").queryParams(params); + + try { + LOGGER.trace("POST: {}", webResource); + return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ImageCreateResponse.class, imageStream); + + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error.", exception); + } else { + throw new DockerException(exception); + } + } + } + + public List search(String search) throws DockerException { + WebResource webResource = client.resource(restEndpointUrl + "/images/search").queryParam("term", search); + try { + return webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error.", exception); + } else { + throw new DockerException(exception); + } + } + + } + + /** + * Remove an image, deleting any tags it might have. + */ + public void removeImage(String imageId) throws DockerException { + Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty"); + + try { + WebResource webResource = client.resource(restEndpointUrl + "/images/" + imageId) + .queryParam("force", "true"); + LOGGER.trace("DELETE: {}", webResource); + webResource.delete(); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 204) { + //no error + LOGGER.trace("Successfully removed image " + imageId); + } else if (exception.getResponse().getStatus() == 404) { + LOGGER.warn("{} no such image", imageId); + } else if (exception.getResponse().getStatus() == 409) { + throw new DockerException("Conflict"); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error.", exception); + } else { + throw new DockerException(exception); + } + } + + } + + public void removeImages(List images) throws DockerException { + Preconditions.checkNotNull(images, "List of images can't be null"); + + for (String imageId : images) { + removeImage(imageId); + } + } + + public String getVizImages() throws DockerException { + WebResource webResource = client.resource(restEndpointUrl + "/images/viz"); + + try { + LOGGER.trace("GET: {}", webResource); + String response = webResource.get(String.class); + LOGGER.trace("Response: {}", response); + + return response; + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 400) { + throw new DockerException("bad parameter"); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + } + + + public List getImages() throws DockerException { + return this.getImages(null, false); + } + + public List getImages(boolean allContainers) throws DockerException { + return this.getImages(null, allContainers); + } + + public List getImages(String name) throws DockerException { + return this.getImages(name, false); + } + + public List getImages(String name, boolean allImages) throws DockerException { + + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("filter", name); + params.add("all", allImages ? "1" : "0"); + + WebResource webResource = client.resource(restEndpointUrl + "/images/json").queryParams(params); + + try { + LOGGER.trace("GET: {}", webResource); + List images = webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); + LOGGER.trace("Response: {}", images); + return images; + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 400) { + throw new DockerException("bad parameter"); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(); + } + } + + } + + public ImageInspectResponse inspectImage(String imageId) throws DockerException, NotFoundException { + + WebResource webResource = client.resource(restEndpointUrl + String.format("/images/%s/json", imageId)); + + try { + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(ImageInspectResponse.class); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 404) { + throw new NotFoundException(String.format("No such image %s", imageId)); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + } + + /** + * * CONTAINER API + * * + */ + + public List listContainers(boolean allContainers) { + return this.listContainers(allContainers, false, -1, false, null, null); + } + + public List listContainers(boolean allContainers, boolean latest) { + return this.listContainers(allContainers, latest, -1, false, null, null); + } + + public List listContainers(boolean allContainers, boolean latest, int limit) { + return this.listContainers(allContainers, latest, limit, false, null, null); + } + + public List listContainers(boolean allContainers, boolean latest, int limit, boolean showSize) { + return this.listContainers(allContainers, latest, limit, showSize, null, null); + } + + public List listContainers(boolean allContainers, boolean latest, int limit, boolean showSize, String since) { + return this.listContainers(allContainers, latest, limit, false, since, null); + } + + public List listContainers(boolean allContainers, boolean latest, int limit, boolean showSize, String since, String before) { + + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("limit", latest ? "1" : String.valueOf(limit)); + params.add("all", allContainers ? "1" : "0"); + params.add("since", since); + params.add("before", before); + params.add("size", showSize ? "1" : "0"); + + WebResource webResource = client.resource(restEndpointUrl + "/containers/json").queryParams(params); + LOGGER.trace("GET: {}", webResource); + List containers = webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); + LOGGER.trace("Response: {}", containers); + + return containers; + } + + public ContainerCreateResponse createContainer(ContainerConfig config) throws DockerException { + return createContainer(config, null); + } + + public ContainerCreateResponse createContainer(ContainerConfig config, String name) throws DockerException, NotFoundException { + + MultivaluedMap params = new MultivaluedMapImpl(); + if (name != null) { + params.add("name", name); + } + WebResource webResource = client.resource(restEndpointUrl + "/containers/create").queryParams(params); + + try { + LOGGER.trace("POST: {} ", webResource); + return webResource.accept(MediaType.APPLICATION_JSON) + .type(MediaType.APPLICATION_JSON) + .post(ContainerCreateResponse.class, config); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 404) { + throw new NotFoundException(String.format("%s is an unrecognized image. Please pull the image first.", config.getImage())); + } else if (exception.getResponse().getStatus() == 406) { + throw new DockerException("impossible to attach (container not running)"); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + + } + + public void startContainer(String containerId) throws DockerException { + this.startContainer(containerId, null); + } + + public void startContainer(String containerId, HostConfig hostConfig) throws DockerException, NotFoundException { + + WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/start", containerId)); + + try { + LOGGER.trace("POST: {}", webResource); + Builder builder = webResource.accept(MediaType.TEXT_PLAIN); + if (hostConfig != null) { + builder.type(MediaType.APPLICATION_JSON).post(hostConfig); + } else { + builder.post((HostConfig) null); + } + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 404) { + throw new NotFoundException(String.format("No such container %s", containerId)); + } else if (exception.getResponse().getStatus() == 204) { + //no error + LOGGER.trace("Successfully started container {}", containerId); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + } + + public ContainerInspectResponse inspectContainer(String containerId) throws DockerException, NotFoundException { + + WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/json", containerId)); + + try { + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(ContainerInspectResponse.class); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 404) { + throw new NotFoundException(String.format("No such container %s", containerId)); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + } + + + public void removeContainer(String container) throws DockerException { + this.removeContainer(container, false); + } + + public void removeContainer(String containerId, boolean removeVolumes) throws DockerException { + Preconditions.checkState(!StringUtils.isEmpty(containerId), "Container ID can't be empty"); + + WebResource webResource = client.resource(restEndpointUrl + "/containers/" + containerId).queryParam("v", removeVolumes ? "1" : "0"); + + try { + LOGGER.trace("DELETE: {}", webResource); + String response = webResource.accept(MediaType.APPLICATION_JSON).delete(String.class); + LOGGER.trace("Response: {}", response); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 204) { + //no error + LOGGER.trace("Successfully removed container " + containerId); + } else if (exception.getResponse().getStatus() == 400) { + throw new DockerException("bad parameter"); + } else if (exception.getResponse().getStatus() == 404) { + // should really throw a NotFoundException instead of silently ignoring the problem + LOGGER.warn(String.format("%s is an unrecognized container.", containerId)); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + } + + + public void removeContainers(List containers, boolean removeVolumes) throws DockerException { + Preconditions.checkNotNull(containers, "List of containers can't be null"); + + for (String containerId : containers) { + removeContainer(containerId, removeVolumes); + } + } + + public int waitContainer(String containerId) throws DockerException, NotFoundException { + WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/wait", containerId)); + + try { + LOGGER.trace("POST: {}", webResource); + ObjectNode ObjectNode = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ObjectNode.class); + return ObjectNode.get("StatusCode").asInt(); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 404) { + throw new NotFoundException(String.format("No such container %s", containerId)); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } catch (Exception e) { + throw new DockerException(e); + } + } + + + public ClientResponse logContainer(String containerId) throws DockerException { + return logContainer(containerId, false); + } + + public ClientResponse logContainerStream(String containerId) throws DockerException { + return logContainer(containerId, true); + } + + private ClientResponse logContainer(String containerId, boolean stream) throws DockerException, NotFoundException { + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("logs", "1"); + params.add("stdout", "1"); + params.add("stderr", "1"); + if (stream) { + params.add("stream", "1"); // this parameter keeps stream open indefinitely + } + + WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/attach", containerId)) + .queryParams(params); + + try { + LOGGER.trace("POST: {}", webResource); + return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ClientResponse.class, params); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 400) { + throw new DockerException("bad parameter"); + } else if (exception.getResponse().getStatus() == 404) { + throw new NotFoundException(String.format("No such container %s", containerId)); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + } + + public ClientResponse copyFile(String containerId, String resource) throws DockerException { + CopyConfig copyConfig = new CopyConfig(); + copyConfig.setResource(resource); + + WebResource webResource = + client.resource(restEndpointUrl + String.format("/containers/%s/copy", containerId)); + + try { + LOGGER.trace("POST: " + webResource.toString()); + WebResource.Builder builder = + webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).type("application/json"); + + return builder.post(ClientResponse.class, copyConfig.toString()); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 400) { + throw new DockerException("bad parameter"); + } else if (exception.getResponse().getStatus() == 404) { + throw new DockerException(String.format("No such container %s", containerId)); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + } + + public List containerDiff(String containerId) throws DockerException, NotFoundException { + + WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/changes", containerId)); + + try { + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 404) { + throw new NotFoundException(String.format("No such container %s", containerId)); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + } + + + public void stopContainer(String containerId) throws DockerException { + this.stopContainer(containerId, 10); + } + + public void stopContainer(String containerId, int timeout) throws DockerException { + + WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/stop", containerId)) + .queryParam("t", String.valueOf(timeout)); + + + try { + LOGGER.trace("POST: {}", webResource); + webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 404) { + LOGGER.warn("No such container {}", containerId); + } else if (exception.getResponse().getStatus() == 204) { + //no error + LOGGER.trace("Successfully stopped container {}", containerId); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + } + + public void kill(String containerId) throws DockerException { + WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/kill", containerId)); + + try { + LOGGER.trace("POST: {}", webResource); + webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 404) { + LOGGER.warn("No such container {}", containerId); + } else if (exception.getResponse().getStatus() == 204) { + //no error + LOGGER.trace("Successfully killed container {}", containerId); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + } + + public void restart(String containerId, int timeout) throws DockerException, NotFoundException { + WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/restart", containerId)); + + try { + LOGGER.trace("POST: {}", webResource); + webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 404) { + throw new NotFoundException(String.format("No such container %s", containerId)); + } else if (exception.getResponse().getStatus() == 204) { + //no error + LOGGER.trace("Successfully restarted container {}", containerId); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + } + + public String commit(CommitConfig commitConfig) throws DockerException, NotFoundException { + Preconditions.checkNotNull(commitConfig.getContainer(), "Container ID was not specified"); + + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("container", commitConfig.getContainer()); + params.add("repo", commitConfig.getRepo()); + params.add("tag", commitConfig.getTag()); + params.add("m", commitConfig.getMessage()); + params.add("author", commitConfig.getAuthor()); + params.add("run", commitConfig.getRun()); + + WebResource webResource = client.resource(restEndpointUrl + "/commit").queryParams(params); + + try { + LOGGER.trace("POST: {}", webResource); + ObjectNode ObjectNode = webResource.accept("application/vnd.docker.raw-stream").post(ObjectNode.class, params); + return ObjectNode.get("Id").asText(); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 404) { + throw new NotFoundException(String.format("No such container %s", commitConfig.getContainer())); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } catch (Exception e) { + throw new DockerException(e); + } + } + + + public ClientResponse build(File dockerFolder) throws DockerException { + return this.build(dockerFolder, null); + } + + public ClientResponse build(File dockerFolder, String tag) throws DockerException { + return this.build(dockerFolder, tag, false); + } + + private static boolean isFileResource(String resource) { + URI uri; + try { + uri = new URI(resource); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + return uri.getScheme() == null || "file".equals(uri.getScheme()); + } + + public ClientResponse build(File dockerFolder, String tag, boolean noCache) throws DockerException { + Preconditions.checkNotNull(dockerFolder, "Folder is null"); + Preconditions.checkArgument(dockerFolder.exists(), "Folder %s doesn't exist", dockerFolder); + Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(), "Dockerfile doesn't exist in " + dockerFolder); + + //We need to use Jersey HttpClient here, since ApacheHttpClient4 will not add boundary filed to + //Content-Type: multipart/form-data; boundary=Boundary_1_372491238_1372806136625 + + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("t", tag); + if (noCache) { + params.add("nocache", "true"); + } + + // ARCHIVE TAR + String archiveNameWithOutExtension = UUID.randomUUID().toString(); + + File dockerFolderTar = null; + + try { + File dockerFile = new File(dockerFolder, "Dockerfile"); + List dockerFileContent = FileUtils.readLines(dockerFile); + + if (dockerFileContent.size() <= 0) { + throw new DockerException(String.format("Dockerfile %s is empty", dockerFile)); + } + + List filesToAdd = new ArrayList(); + filesToAdd.add(dockerFile); + + for (String cmd : dockerFileContent) { + if (StringUtils.startsWithIgnoreCase(cmd.trim(), "ADD")) { + String addArgs[] = StringUtils.split(cmd, " \t"); + if (addArgs.length != 3) { + throw new DockerException(String.format("Wrong format on line [%s]", cmd)); + } + + String resource = addArgs[1]; + + if(isFileResource(resource)) { + File src = new File(resource); + if (!src.isAbsolute()) { + src = new File(dockerFolder, resource).getCanonicalFile(); + } else { + throw new DockerException(String.format("Source file %s must be relative to %s", src, dockerFolder)); + } + + if (!src.exists()) { + throw new DockerException(String.format("Source file %s doesn't exist", src)); + } + if (src.isDirectory()) { + filesToAdd.addAll(FileUtils.listFiles(src, null, true)); + } else { + filesToAdd.add(src); + } + } + } + } + + dockerFolderTar = CompressArchiveUtil.archiveTARFiles(dockerFolder, filesToAdd, archiveNameWithOutExtension); + + } catch (IOException ex) { + FileUtils.deleteQuietly(dockerFolderTar); + throw new DockerException("Error occurred while preparing Docker context folder.", ex); + } + + WebResource webResource = client.resource(restEndpointUrl + "/build").queryParams(params); + + try { + LOGGER.trace("POST: {}", webResource); + return webResource + .type("application/tar") + .accept(MediaType.TEXT_PLAIN) + .post(ClientResponse.class, FileUtils.openInputStream(dockerFolderTar)); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } catch (IOException e) { + throw new DockerException(e); + } finally { + FileUtils.deleteQuietly(dockerFolderTar); + } + } } diff --git a/src/main/java/com/kpelykh/docker/client/NotFoundException.java b/src/main/java/com/kpelykh/docker/client/NotFoundException.java new file mode 100644 index 00000000..76569f7b --- /dev/null +++ b/src/main/java/com/kpelykh/docker/client/NotFoundException.java @@ -0,0 +1,14 @@ +package com.kpelykh.docker.client; + +/** + * Indicates that the given entity does not exist. + * + * @author Ryan Campbell ryan.campbell@gmail.com + */ +public class NotFoundException extends DockerException { + + public NotFoundException(String message) { + super(message); + } + +} diff --git a/src/main/java/com/kpelykh/docker/client/model/AuthConfig.java b/src/main/java/com/kpelykh/docker/client/model/AuthConfig.java new file mode 100644 index 00000000..514e79be --- /dev/null +++ b/src/main/java/com/kpelykh/docker/client/model/AuthConfig.java @@ -0,0 +1,58 @@ +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class AuthConfig { + @JsonProperty + private String username; + @JsonProperty + private String password; + @JsonProperty + private String email; + @JsonProperty("serveraddress") + private String serverAddress = "https://index.docker.io/v1/"; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getServerAddress() { + return serverAddress; + } + + public void setServerAddress(String serverAddress) { + this.serverAddress = serverAddress; + } + + @Override + public String toString() { + return "AuthConfig{" + + "username='" + username + '\'' + + ", password='" + password + '\'' + + ", email='" + email + '\'' + + ", serverAddress='" + serverAddress + '\'' + + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/BoundHostVolumes.java b/src/main/java/com/kpelykh/docker/client/model/BoundHostVolumes.java new file mode 100644 index 00000000..9a912439 --- /dev/null +++ b/src/main/java/com/kpelykh/docker/client/model/BoundHostVolumes.java @@ -0,0 +1,92 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Kevin A. Archie + * + */ +@JsonSerialize(using=BoundHostVolumes.Serializer.class) +public class BoundHostVolumes { + private static final String[] STRING_ARRAY = new String[0]; + private final String[] dests, binds; + + /** + * + * @param specs Iterable of String binding specs, each of form "{host-path}:{container-patch}:[rw|ro]" + * @throws MalformedVolumeSpecException if any specs are null or empty + */ + public BoundHostVolumes(final Iterable specs) { + final List dests = new ArrayList(), binds = new ArrayList(); + for (final String spec : specs) { + if (null == spec || "".equals(spec)) { + // skip empty spec lines + } else { + final String[] sspec = spec.split(":"); + dests.add(sspec.length > 1 ? sspec[1] : sspec[0]); + binds.add(spec); + } + } + this.dests = dests.toArray(STRING_ARRAY); + this.binds = binds.toArray(STRING_ARRAY); + } + + public String[] asBinds() { + return binds; + } + + private BoundHostVolumes writeVolumes(final JsonGenerator jg) throws IOException { + jg.writeStartObject(); + for (final String dest : dests) { + jg.writeObjectFieldStart(dest); + jg.writeEndObject(); + } + jg.writeEndObject(); + return this; + } + + /** + * This is an ugly hack. We assume that the serializer only gets called when + * a containing ContainerConfig gets serialized, when POSTing to + * /containers/create . In that context, we pass only the container-path + * part (the key in the volumes map). + * + * @author Kevin A. Archie + * + */ + public static class Serializer extends JsonSerializer { + /* (non-Javadoc) + * @see org.codehaus.jackson.map.JsonSerializer#serialize(java.lang.Object, org.codehaus.jackson.JsonGenerator, org.codehaus.jackson.map.SerializerProvider) + */ + @Override + public void serialize(final BoundHostVolumes volumes, final JsonGenerator jg, final SerializerProvider sp) + throws IOException { + volumes.writeVolumes(jg); + } + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/ChangeLog.java b/src/main/java/com/kpelykh/docker/client/model/ChangeLog.java index 1d24f8cf..50fdab4a 100644 --- a/src/main/java/com/kpelykh/docker/client/model/ChangeLog.java +++ b/src/main/java/com/kpelykh/docker/client/model/ChangeLog.java @@ -1,25 +1,35 @@ -package com.kpelykh.docker.client.model; - -import org.codehaus.jackson.annotate.JsonProperty; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class ChangeLog { - - @JsonProperty("Path") - public String path; - - @JsonProperty("Kind") - public int kind; - - @Override - public String toString() { - return "ChangeLog{" + - "path='" + path + '\'' + - ", kind=" + kind + - '}'; - } -} +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ChangeLog { + + @JsonProperty("Path") + private String path; + + @JsonProperty("Kind") + private int kind; + + public String getPath() { + return path; + } + + public int getKind() { + return kind; + } + + @Override + public String toString() { + return "ChangeLog{" + + "path='" + path + '\'' + + ", kind=" + kind + + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/CommitConfig.java b/src/main/java/com/kpelykh/docker/client/model/CommitConfig.java index bbe53d79..4023deb7 100644 --- a/src/main/java/com/kpelykh/docker/client/model/CommitConfig.java +++ b/src/main/java/com/kpelykh/docker/client/model/CommitConfig.java @@ -1,77 +1,87 @@ -package com.kpelykh.docker.client.model; - -import org.codehaus.jackson.annotate.JsonProperty; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class CommitConfig { - - @JsonProperty("container") public String container; - @JsonProperty("repo") public String repo; - @JsonProperty("tag") public String tag; - @JsonProperty("m") public String message; - - //author (eg. “John Hannibal Smith ”) - @JsonProperty("author") public String author; - - //config automatically applied when the image is run. (ex: {“Cmd”: [“cat”, “/world”], “PortSpecs”:[“22”]}) - @JsonProperty("run") public String run; - - - public CommitConfig() {} - - public CommitConfig(Builder builder) { - this.container = builder.container; - this.repo = builder.repo; - this.tag = builder.tag; - this.message = builder.message; - this.author = builder.author; - this.run = builder.run; - } - - public static class Builder { - private String container; - private String repo; - private String tag; - private String message; - private String author; - private String run; - - public Builder(String containerId) { - this.container = containerId; - } - - public Builder repo(String repo) { - this.repo = repo; - return this; - } - - public Builder tag(String tag) { - this.tag = tag; - return this; - } - - public Builder message(String message) { - this.message = message; - return this; - } - - public Builder author(String author) { - this.author = author; - return this; - } - - public Builder run(String run) { - this.run = run; - return this; - } - - public CommitConfig build() { - return new CommitConfig(this); - } - } - -} +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class CommitConfig { + + @JsonProperty("container") + private String container; + + @JsonProperty("repo") + private String repo; + + @JsonProperty("tag") + private String tag; + + @JsonProperty("m") + private String message; + + //author (eg. “John Hannibal Smith ”) + @JsonProperty("author") + private String author; + + //config automatically applied when the image is run. (ex: {“Cmd”: [“cat”, “/world”], “PortSpecs”:[“22”]}) + @JsonProperty("run") + private String run; + + public String getContainer() { + return container; + } + + public String getRepo() { + return repo; + } + + public String getTag() { + return tag; + } + + public String getMessage() { + return message; + } + + public String getAuthor() { + return author; + } + + public String getRun() { + return run; + } + + public CommitConfig setRepo(String repo) { + this.repo = repo; + return this; + } + + public CommitConfig setTag(String tag) { + this.tag = tag; + return this; + } + + public CommitConfig setMessage(String message) { + this.message = message; + return this; + } + + public CommitConfig setAuthor(String author) { + this.author = author; + return this; + } + + public CommitConfig setRun(String run) { + this.run = run; + return this; + } + + public CommitConfig(String container) { + this.container = container; + } + +} diff --git a/src/main/java/com/kpelykh/docker/client/model/Container.java b/src/main/java/com/kpelykh/docker/client/model/Container.java index 8d02c263..3e6554cb 100644 --- a/src/main/java/com/kpelykh/docker/client/model/Container.java +++ b/src/main/java/com/kpelykh/docker/client/model/Container.java @@ -1,51 +1,140 @@ -package com.kpelykh.docker.client.model; - -import org.codehaus.jackson.annotate.JsonProperty; - -import java.util.Arrays; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class Container { - - @JsonProperty("Id") - public String id; - - @JsonProperty("Command") - public String command; - - @JsonProperty("Image") - public String image; - - @JsonProperty("Created") - public long created; - - @JsonProperty("Status") - public String status; - - @JsonProperty("Ports") - public String ports; //Example value "49164->6900, 49165->7100" - - @JsonProperty("SizeRw") - public int size; - - @JsonProperty("SizeRootFs") - public int sizeRootFs; - - @Override - public String toString() { - return "Container{" + - "id='" + id + '\'' + - ", command='" + command + '\'' + - ", image='" + image + '\'' + - ", created=" + created + - ", status='" + status + '\'' + - ", ports=" + ports + - ", size=" + size + - ", sizeRootFs=" + sizeRootFs + - '}'; - } -} +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Arrays; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class Container { + + @JsonProperty("Id") + private String id; + + @JsonProperty("Command") + private String command; + + @JsonProperty("Image") + private String image; + + @JsonProperty("Created") + private long created; + + @JsonProperty("Status") + private String status; + + /* Example: + "Ports": { + "22/tcp": [ + { + "HostIp": "0.0.0.0", + "HostPort": "8022" + } + ] + } + */ + + @JsonProperty("Ports") + public Ports ports; + + @JsonProperty("SizeRw") + private int size; + + @JsonProperty("SizeRootFs") + private int sizeRootFs; + + @JsonProperty("Names") + private String[] names; + + public String getId() { + return id; + } + + public String getCommand() { + return command; + } + + public String getImage() { + return image; + } + + public long getCreated() { + return created; + } + + public String getStatus() { + return status; + } + + public Ports getPorts() { + return ports; + } + + public void setPorts(Ports ports) { + this.ports = ports; + } + + public int getSize() { + return size; + } + + public int getSizeRootFs() { + return sizeRootFs; + } + + public String[] getNames() { + return names; + } + + public void setId(String id) { + this.id = id; + } + + public void setCommand(String command) { + this.command = command; + } + + public void setImage(String image) { + this.image = image; + } + + public void setCreated(long created) { + this.created = created; + } + + public void setStatus(String status) { + this.status = status; + } + + public void setSize(int size) { + this.size = size; + } + + public void setSizeRootFs(int sizeRootFs) { + this.sizeRootFs = sizeRootFs; + } + + public void setNames(String[] names) { + this.names = names; + } + + @Override + public String toString() { + return "Container{" + + "id='" + id + '\'' + + ", command='" + command + '\'' + + ", image='" + image + '\'' + + ", created=" + created + + ", status='" + status + '\'' + + ", ports=" + ports + + ", size=" + size + + ", sizeRootFs=" + sizeRootFs + + ", names=" + Arrays.toString(names) + + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/ContainerConfig.java b/src/main/java/com/kpelykh/docker/client/model/ContainerConfig.java index d56d8bbb..27a1d7e3 100644 --- a/src/main/java/com/kpelykh/docker/client/model/ContainerConfig.java +++ b/src/main/java/com/kpelykh/docker/client/model/ContainerConfig.java @@ -1,213 +1,291 @@ -package com.kpelykh.docker.client.model; - -import org.apache.commons.lang.StringUtils; -import org.codehaus.jackson.annotate.JsonProperty; - -import java.util.Arrays; -import java.util.Map; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class ContainerConfig { - - @JsonProperty("Hostname") private String hostName; - @JsonProperty("PortSpecs") private String[] portSpecs; - @JsonProperty("User") private String user; - @JsonProperty("Tty") private boolean tty; - @JsonProperty("OpenStdin") private boolean stdinOpen; - @JsonProperty("StdinOnce") private boolean stdInOnce; - @JsonProperty("Memory") private long memoryLimit; - @JsonProperty("MemorySwap") private long memorySwap; - @JsonProperty("CpuShares") private int cpuShares; - @JsonProperty("AttachStdin") private boolean attachStdin; - @JsonProperty("AttachStdout") private boolean attachStdout; - @JsonProperty("AttachStderr") private boolean attachStderr; - @JsonProperty("Env") private String[] env; - @JsonProperty("Cmd") private String[] cmd; - @JsonProperty("Dns") private String[] dns; - @JsonProperty("Image") private String image; - @JsonProperty("Volumes") private Object volumes; - @JsonProperty("VolumesFrom") private String volumesFrom; - @JsonProperty("Entrypoint") private String[] entrypoint; - - - public String getHostName() { - return hostName; - } - - public void setHostName(String hostName) { - this.hostName = hostName; - } - - public String[] getPortSpecs() { - return portSpecs; - } - - public void setPortSpecs(String[] portSpecs) { - this.portSpecs = portSpecs; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public boolean isTty() { - return tty; - } - - public void setTty(boolean tty) { - this.tty = tty; - } - - public boolean isStdinOpen() { - return stdinOpen; - } - - public void setStdinOpen(boolean stdinOpen) { - this.stdinOpen = stdinOpen; - } - - public boolean isStdInOnce() { - return stdInOnce; - } - - public void setStdInOnce(boolean stdInOnce) { - this.stdInOnce = stdInOnce; - } - - public long getMemoryLimit() { - return memoryLimit; - } - - public void setMemoryLimit(long memoryLimit) { - this.memoryLimit = memoryLimit; - } - - public long getMemorySwap() { - return memorySwap; - } - - public void setMemorySwap(long memorySwap) { - this.memorySwap = memorySwap; - } - - public int getCpuShares() { - return cpuShares; - } - - public void setCpuShares(int cpuShares) { - this.cpuShares = cpuShares; - } - - public boolean isAttachStdin() { - return attachStdin; - } - - public void setAttachStdin(boolean attachStdin) { - this.attachStdin = attachStdin; - } - - public boolean isAttachStdout() { - return attachStdout; - } - - public void setAttachStdout(boolean attachStdout) { - this.attachStdout = attachStdout; - } - - public boolean isAttachStderr() { - return attachStderr; - } - - public void setAttachStderr(boolean attachStderr) { - this.attachStderr = attachStderr; - } - - public String[] getEnv() { - return env; - } - - public void setEnv(String[] env) { - this.env = env; - } - - public String[] getCmd() { - return cmd; - } - - public void setCmd(String[] cmd) { - this.cmd = cmd; - } - - public String[] getDns() { - return dns; - } - - public void setDns(String[] dns) { - this.dns = dns; - } - - public String getImage() { - return image; - } - - public void setImage(String image) { - this.image = image; - } - - public Object getVolumes() { - return volumes; - } - - public void setVolumes(Object volumes) { - this.volumes = volumes; - } - - public String getVolumesFrom() { - return volumesFrom; - } - - public void setVolumesFrom(String volumesFrom) { - this.volumesFrom = volumesFrom; - } - - public String[] getEntrypoint() { - return entrypoint; - } - - public void setEntrypoint(String[] entrypoint) { - this.entrypoint = entrypoint; - } - - @Override - public String toString() { - return "ContainerConfig{" + - "hostName='" + hostName + '\'' + - ", portSpecs=" + Arrays.toString(portSpecs) + - ", user='" + user + '\'' + - ", tty=" + tty + - ", stdinOpen=" + stdinOpen + - ", stdInOnce=" + stdInOnce + - ", memoryLimit=" + memoryLimit + - ", memorySwap=" + memorySwap + - ", cpuShares=" + cpuShares + - ", attachStdin=" + attachStdin + - ", attachStdout=" + attachStdout + - ", attachStderr=" + attachStderr + - ", env=" + env + - ", cmd=" + Arrays.toString(cmd) + - ", dns=" + Arrays.toString(dns) + - ", image='" + image + '\'' + - ", volumes=" + volumes + - ", volumesFrom='" + volumesFrom + '\'' + - ", entrypoint='" + Arrays.toString(portSpecs) + - '}'; - } -} +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Arrays; +import java.util.Map; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ContainerConfig { + + @JsonProperty("Hostname") private String hostName = ""; + @JsonProperty("PortSpecs") private String[] portSpecs; + @JsonProperty("User") private String user = ""; + @JsonProperty("Tty") private boolean tty = false; + @JsonProperty("OpenStdin") private boolean stdinOpen = false; + @JsonProperty("StdinOnce") private boolean stdInOnce = false; + @JsonProperty("Memory") private long memoryLimit = 0; + @JsonProperty("MemorySwap") private long memorySwap = 0; + @JsonProperty("CpuShares") private int cpuShares = 0; + @JsonProperty("AttachStdin") private boolean attachStdin = false; + @JsonProperty("AttachStdout") private boolean attachStdout = false; + @JsonProperty("AttachStderr") private boolean attachStderr = false; + @JsonProperty("Env") private String[] env; + @JsonProperty("Cmd") private String[] cmd; + @JsonProperty("Dns") private String[] dns; + @JsonProperty("Image") private String image; + @JsonProperty("Volumes") private BoundHostVolumes volumes; + @JsonProperty("VolumesFrom") private String volumesFrom = ""; + @JsonProperty("Entrypoint") private String[] entrypoint = new String[]{}; + @JsonProperty("NetworkDisabled") private boolean networkDisabled = false; + @JsonProperty("Privileged") private boolean privileged = false; + @JsonProperty("WorkingDir") private String workingDir = ""; + @JsonProperty("Domainname") private String domainName = ""; + // FIXME Is this the right type? -BJE + @JsonProperty("ExposedPorts") private Map exposedPorts; + + @JsonProperty("OnBuild") private int[] onBuild; + + public Map getExposedPorts() { + return exposedPorts; + } + + public boolean isNetworkDisabled() { + return networkDisabled; + } + + public String getDomainName() { + return domainName; + } + + public String getWorkingDir() { return workingDir; } + + public ContainerConfig setWorkingDir(String workingDir) { + this.workingDir = workingDir; + return this; + } + + public boolean isPrivileged() { + return privileged; + } + + public ContainerConfig setPrivileged(boolean privileged) { + this.privileged = privileged; + return this; + } + + public String getHostName() { + return hostName; + } + + public ContainerConfig setNetworkDisabled(boolean networkDisabled) { + this.networkDisabled = networkDisabled; + return this; + } + + public ContainerConfig setHostName(String hostName) { + this.hostName = hostName; + return this; + } + + public String[] getPortSpecs() { + return portSpecs; + } + + public ContainerConfig setPortSpecs(String[] portSpecs) { + this.portSpecs = portSpecs; + return this; + } + + public String getUser() { + return user; + } + + public ContainerConfig setUser(String user) { + this.user = user; + return this; + } + + public boolean isTty() { + return tty; + } + + public ContainerConfig setTty(boolean tty) { + this.tty = tty; + return this; + } + + public boolean isStdinOpen() { + return stdinOpen; + } + + public ContainerConfig setStdinOpen(boolean stdinOpen) { + this.stdinOpen = stdinOpen; + return this; + } + + public boolean isStdInOnce() { + return stdInOnce; + } + + public ContainerConfig setStdInOnce(boolean stdInOnce) { + this.stdInOnce = stdInOnce; + return this; + } + + public long getMemoryLimit() { + return memoryLimit; + } + + public ContainerConfig setMemoryLimit(long memoryLimit) { + this.memoryLimit = memoryLimit; + return this; + } + + public long getMemorySwap() { + return memorySwap; + } + + public ContainerConfig setMemorySwap(long memorySwap) { + this.memorySwap = memorySwap; + return this; + } + + public int getCpuShares() { + return cpuShares; + } + + public ContainerConfig setCpuShares(int cpuShares) { + this.cpuShares = cpuShares; + return this; + } + + public boolean isAttachStdin() { + return attachStdin; + } + + public ContainerConfig setAttachStdin(boolean attachStdin) { + this.attachStdin = attachStdin; + return this; + } + + public boolean isAttachStdout() { + return attachStdout; + } + + public ContainerConfig setAttachStdout(boolean attachStdout) { + this.attachStdout = attachStdout; + return this; + } + + public boolean isAttachStderr() { + return attachStderr; + } + + public ContainerConfig setAttachStderr(boolean attachStderr) { + this.attachStderr = attachStderr; + return this; + } + + public String[] getEnv() { + return env; + } + + public ContainerConfig setEnv(String[] env) { + this.env = env; + return this; + } + + public String[] getCmd() { + return cmd; + } + + public ContainerConfig setCmd(String[] cmd) { + this.cmd = cmd; + return this; + } + + public String[] getDns() { + return dns; + } + + public ContainerConfig setDns(String[] dns) { + this.dns = dns; + return this; + } + + public String getImage() { + return image; + } + + public ContainerConfig setImage(String image) { + this.image = image; + return this; + } + + public BoundHostVolumes getVolumes() { + return volumes; + } + + public ContainerConfig setVolumes(BoundHostVolumes volumes) { + this.volumes = volumes; + return this; + } + + public String getVolumesFrom() { + return volumesFrom; + } + + public ContainerConfig setVolumesFrom(String volumesFrom) { + this.volumesFrom = volumesFrom; + return this; + } + + public String[] getEntrypoint() { + return entrypoint; + } + + public ContainerConfig setEntrypoint(String[] entrypoint) { + this.entrypoint = entrypoint; + return this; + } + + public void setOnBuild(int[] onBuild) { + this.onBuild = onBuild; + } + + public int[] getOnBuild() { + return onBuild; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + @Override + public String toString() { + return "ContainerConfig{" + + "hostName='" + hostName + '\'' + + ", portSpecs=" + Arrays.toString(portSpecs) + + ", user='" + user + '\'' + + ", tty=" + tty + + ", stdinOpen=" + stdinOpen + + ", stdInOnce=" + stdInOnce + + ", memoryLimit=" + memoryLimit + + ", memorySwap=" + memorySwap + + ", cpuShares=" + cpuShares + + ", attachStdin=" + attachStdin + + ", attachStdout=" + attachStdout + + ", attachStderr=" + attachStderr + + ", env=" + Arrays.toString(env) + + ", cmd=" + Arrays.toString(cmd) + + ", dns=" + Arrays.toString(dns) + + ", image='" + image + '\'' + + ", volumes=" + volumes + + ", volumesFrom='" + volumesFrom + '\'' + + ", entrypoint=" + Arrays.toString(entrypoint) + + ", networkDisabled=" + networkDisabled + + ", privileged=" + privileged + + ", workingDir='" + workingDir + '\'' + + ", domainName='" + domainName + '\'' + + ", onBuild='" + Arrays.toString(onBuild) + '\'' + + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/ContainerCreateResponse.java b/src/main/java/com/kpelykh/docker/client/model/ContainerCreateResponse.java index a962bbe3..8f60ce15 100644 --- a/src/main/java/com/kpelykh/docker/client/model/ContainerCreateResponse.java +++ b/src/main/java/com/kpelykh/docker/client/model/ContainerCreateResponse.java @@ -1,26 +1,45 @@ -package com.kpelykh.docker.client.model; - -import org.codehaus.jackson.annotate.JsonProperty; -import java.util.Arrays; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class ContainerCreateResponse { - - @JsonProperty("Id") - public String id; - - @JsonProperty("Warnings") - public String[] warnings; - - @Override - public String toString() { - return "ContainerCreateResponse{" + - "id='" + id + '\'' + - ", warnings=" + Arrays.toString(warnings) + - '}'; - } -} +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Arrays; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ContainerCreateResponse { + + @JsonProperty("Id") + private String id; + + @JsonProperty("Warnings") + private String[] warnings; + + public String getId() { + return id; + } + + public String[] getWarnings() { + return warnings; + } + + public void setId(String id) { + this.id = id; + } + + public void setWarnings(String[] warnings) { + this.warnings = warnings; + } + + @Override + public String toString() { + return "ContainerCreateResponse{" + + "id='" + id + '\'' + + ", warnings=" + Arrays.toString(warnings) + + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/ContainerInspectResponse.java b/src/main/java/com/kpelykh/docker/client/model/ContainerInspectResponse.java index fb392a0b..d686f9eb 100644 --- a/src/main/java/com/kpelykh/docker/client/model/ContainerInspectResponse.java +++ b/src/main/java/com/kpelykh/docker/client/model/ContainerInspectResponse.java @@ -1,79 +1,270 @@ -package com.kpelykh.docker.client.model; - - -import org.codehaus.jackson.annotate.JsonProperty; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class ContainerInspectResponse { - - @JsonProperty("ID") public String id; - @JsonProperty("Created") public String created; - @JsonProperty("Path") public String path; - @JsonProperty("Args") public String[] args; - @JsonProperty("Config") public ContainerConfig config; - @JsonProperty("State") public ContainerState state; - @JsonProperty("Image") public String image; - @JsonProperty("NetworkSettings") public NetworkSettings networkSettings; - @JsonProperty("SysInitPath") public String sysInitPath; - @JsonProperty("ResolvConfPath") public String resolvConfPath; - @JsonProperty("Volumes") public Map volumes; - @JsonProperty("VolumesRW") public Map volumesRW; - - @Override - public String toString() { - return "ContainerInspectResponse{" + - "volumes=" + volumes + - ", volumesRW=" + volumesRW + '\'' + - ", resolvConfPath='" + resolvConfPath + '\'' + - ", sysInitPath='" + sysInitPath + '\'' + - ", id='" + id + '\'' + - ", created='" + created + '\'' + - ", path='" + path + '\'' + - ", args=" + Arrays.toString(args) + - ", config=" + config + - ", state=" + state + - ", image='" + image + '\'' + - ", networkSettings=" + networkSettings + - '}'; - } - - public class NetworkSettings { - - @JsonProperty("IPAddress") public String ipAddress; - @JsonProperty("IPPrefixLen") public int ipPrefixLen; - @JsonProperty("Gateway") public String gateway; - @JsonProperty("Bridge") public String bridge; - @JsonProperty("PortMapping") public Map> portMapping; - } - - public class ContainerState { - - @JsonProperty("Running") public boolean running; - @JsonProperty("Pid") public int pid; - @JsonProperty("ExitCode") public int exitCode; - @JsonProperty("StartedAt") public String startedAt; - @JsonProperty("Ghost") public boolean ghost; - - @Override - public String toString() { - return "ContainerState{" + - "running=" + running + - ", pid=" + pid + - ", exitCode=" + exitCode + - ", startedAt='" + startedAt + '\'' + - ", ghost=" + ghost + - '}'; - } - - - } - -} +package com.kpelykh.docker.client.model; + + +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ContainerInspectResponse { + + @JsonProperty("ID") + private String id; + + @JsonProperty("Created") + private String created; + + @JsonProperty("Path") + private String path; + + @JsonProperty("Args") + private String[] args; + + @JsonProperty("Config") + public ContainerConfig config; + + @JsonProperty("State") + private ContainerState state; + + @JsonProperty("Image") + private String imageId; + + @JsonProperty("NetworkSettings") + private NetworkSettings networkSettings; + + @JsonProperty("SysInitPath") + private String sysInitPath; + + @JsonProperty("ResolvConfPath") + private String resolvConfPath; + + @JsonProperty("Volumes") + private Map volumes; + + @JsonProperty("VolumesRW") + private Map volumesRW; + + @JsonProperty("HostnamePath") + private String hostnamePath; + + @JsonProperty("HostsPath") + private String hostsPath; + + @JsonProperty("Name") + private String name; + + @JsonProperty("Driver") + private String driver; + + @JsonProperty("HostConfig") + private HostConfig hostConfig; + + @JsonProperty("ExecDriver") + private String execDriver; + + @JsonProperty("MountLabel") + private String mountLabel; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getCreated() { + return created; + } + + public void setCreated(String created) { + this.created = created; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String[] getArgs() { + return args; + } + + public void setArgs(String[] args) { + this.args = args; + } + + public ContainerConfig getConfig() { + return config; + } + + public void setConfig(ContainerConfig config) { + this.config = config; + } + + public ContainerState getState() { + return state; + } + + public void setState(ContainerState state) { + this.state = state; + } + + public String getImageId() { + return imageId; + } + + public void setImageId(String image) { + this.imageId = image; + } + + public NetworkSettings getNetworkSettings() { + return networkSettings; + } + + public void setNetworkSettings(NetworkSettings networkSettings) { + this.networkSettings = networkSettings; + } + + public String getSysInitPath() { + return sysInitPath; + } + + public void setSysInitPath(String sysInitPath) { + this.sysInitPath = sysInitPath; + } + + public String getResolvConfPath() { + return resolvConfPath; + } + + public void setResolvConfPath(String resolvConfPath) { + this.resolvConfPath = resolvConfPath; + } + + public Map getVolumes() { + return volumes; + } + + public void setVolumes(Map volumes) { + this.volumes = volumes; + } + + public Map getVolumesRW() { + return volumesRW; + } + + public void setVolumesRW(Map volumesRW) { + this.volumesRW = volumesRW; + } + + public String getHostnamePath() { + return hostnamePath; + } + + public void setHostnamePath(String hostnamePath) { + this.hostnamePath = hostnamePath; + } + + public String getHostsPath() { + return hostsPath; + } + + public void setHostsPath(String hostsPath) { + this.hostsPath = hostsPath; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDriver() { + return driver; + } + + public void setDriver(String driver) { + this.driver = driver; + } + + public HostConfig getHostConfig() { + return hostConfig; + } + + public void setHostConfig(HostConfig hostConfig) { + this.hostConfig = hostConfig; + } + + public void setExecDriver(String execDriver) { + this.execDriver = execDriver; + } + + public String getExecDriver() { + return execDriver; + } + + public String getMountLabel() { + return mountLabel; + } + + public void setMountLabel(String mountLabel) { + this.mountLabel = mountLabel; + } + + public class NetworkSettings { + + @JsonProperty("IPAddress") public String ipAddress; + @JsonProperty("IPPrefixLen") public int ipPrefixLen; + @JsonProperty("Gateway") public String gateway; + @JsonProperty("Bridge") public String bridge; + @JsonProperty("PortMapping") public Map> portMapping; + @JsonProperty("Ports") public Ports ports; + + @Override + public String toString() { + return "NetworkSettings{" + + "ports=" + ports + + ", portMapping=" + portMapping + + ", bridge='" + bridge + '\'' + + ", gateway='" + gateway + '\'' + + ", ipPrefixLen=" + ipPrefixLen + + ", ipAddress='" + ipAddress + '\'' + + '}'; + } + } + + public class ContainerState { + + @JsonProperty("Running") public boolean running; + @JsonProperty("Pid") public int pid; + @JsonProperty("ExitCode") public int exitCode; + @JsonProperty("StartedAt") public String startedAt; + @JsonProperty("Ghost") public boolean ghost; + @JsonProperty("FinishedAt") private String finishedAt; + + @Override + public String toString() { + return "ContainerState{" + + "running=" + running + + ", pid=" + pid + + ", exitCode=" + exitCode + + ", startedAt='" + startedAt + '\'' + + ", ghost=" + ghost + + ", finishedAt='" + finishedAt + '\'' + + '}'; + } + } + +} diff --git a/src/main/java/com/kpelykh/docker/client/model/CopyConfig.java b/src/main/java/com/kpelykh/docker/client/model/CopyConfig.java new file mode 100755 index 00000000..696778a2 --- /dev/null +++ b/src/main/java/com/kpelykh/docker/client/model/CopyConfig.java @@ -0,0 +1,63 @@ +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Configuration object for copy command. + * @author Victor Lyuboslavsky + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class CopyConfig { + + @JsonProperty("HostPath") + private String hostPath; + + @JsonProperty("Resource") + private String resource; + + /** + * Constructor. + */ + public CopyConfig() { + hostPath = "."; + } + + /** + * Retrieves the 'resource' variable. + * @return the 'resource' variable value + */ + public String getResource() { + return resource; + } + + /** + * Sets the 'resource' variable. + * @param resource the new 'resource' variable value to set + */ + public void setResource(String resource) { + this.resource = resource; + } + + /** + * Retrieves the 'hostPath' variable. + * @return the 'hostPath' variable value + */ + public String getHostPath() { + return hostPath; + } + + /** + * Sets the 'hostPath' variable. + * @param hostPath the new 'hostPath' variable value to set + */ + public void setHostPath(String hostPath) { + this.hostPath = hostPath; + } + + @Override + public String toString() { + return "{\"HostPath\":\"" + hostPath + "\", \"Resource\":\"" + resource + "\"}"; + } + +} diff --git a/src/main/java/com/kpelykh/docker/client/model/DriverStatus.java b/src/main/java/com/kpelykh/docker/client/model/DriverStatus.java new file mode 100644 index 00000000..5421bc44 --- /dev/null +++ b/src/main/java/com/kpelykh/docker/client/model/DriverStatus.java @@ -0,0 +1,33 @@ +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Created by ben on 12/12/13. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class DriverStatus { + + @JsonProperty("Root Dir") + private String rootDir; + + @JsonProperty("Dirs") + private int dirs; + + public String getRootDir() { + return rootDir; + } + + public int getDirs() { + return dirs; + } + + @Override + public String toString() { + return "DriverStatus{" + + "rootDir='" + rootDir + '\'' + + ", dirs=" + dirs + + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/HostConfig.java b/src/main/java/com/kpelykh/docker/client/model/HostConfig.java index 0ee09592..dc7d4258 100644 --- a/src/main/java/com/kpelykh/docker/client/model/HostConfig.java +++ b/src/main/java/com/kpelykh/docker/client/model/HostConfig.java @@ -1,18 +1,180 @@ -package com.kpelykh.docker.client.model; - -import org.codehaus.jackson.annotate.JsonProperty; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class HostConfig { - - @JsonProperty("Binds") - public String[] binds; - - public HostConfig(String[] binds) { - this.binds = binds; - } -} +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Arrays; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class HostConfig { + + @JsonProperty("Binds") + private String[] binds; + + @JsonProperty("ContainerIDFile") + private String containerIDFile; + + @JsonProperty("LxcConf") + private LxcConf[] lxcConf; + + + @JsonProperty("Links") + private String[] links; + + @JsonProperty("PortBindings") + private Ports portBindings; + + @JsonProperty("Privileged") + private boolean privileged; + + @JsonProperty("PublishAllPorts") + private boolean publishAllPorts; + + @JsonProperty("Dns") + private String dns; + + @JsonProperty("DnsSearch") + private String dnsSearch; + + @JsonProperty("VolumesFrom") + private String volumesFrom; + + public HostConfig() { + this.binds = null; + } + + + public String[] getBinds() { + return binds; + } + + public void setBinds(String[] binds) { + this.binds = binds; + } + + public String getContainerIDFile() { + return containerIDFile; + } + + public void setContainerIDFile(String containerIDFile) { + this.containerIDFile = containerIDFile; + } + + public LxcConf[] getLxcConf() { + return lxcConf; + } + + public void setLxcConf(LxcConf[] lxcConf) { + this.lxcConf = lxcConf; + } + + public String[] getLinks() { + return links; + } + + public void setLinks(String[] links) { + this.links = links; + } + + public Ports getPortBindings() { + return portBindings; + } + + public void setPortBindings(Ports portBindings) { + this.portBindings = portBindings; + } + + public boolean isPrivileged() { + return privileged; + } + + public void setPrivileged(boolean privileged) { + this.privileged = privileged; + } + + public boolean isPublishAllPorts() { + return publishAllPorts; + } + + public void setPublishAllPorts(boolean publishAllPorts) { + this.publishAllPorts = publishAllPorts; + } + + public String getDns() { + return dns; + } + + public void setDns(String dns) { + this.dns = dns; + } + + public void setDnsSearch(String dnsSearch) { + this.dnsSearch = dnsSearch; + } + + public String getDnsSearch() { + return dnsSearch; + } + + public void setVolumesFrom(String volumesFrom) { + this.volumesFrom = volumesFrom; + } + + public String getVolumesFrom() { + return volumesFrom; + } + + @Override + public String toString() { + return "HostConfig{" + + "binds=" + Arrays.toString(binds) + + ", containerIDFile='" + containerIDFile + '\'' + + ", lxcConf=" + Arrays.toString(lxcConf) + + ", links=" + Arrays.toString(links) + + ", portBindings=" + portBindings + + ", privileged=" + privileged + + ", publishAllPorts=" + publishAllPorts + + ", dns='" + dns + '\'' + + '}'; + } + + public class LxcConf { + @JsonProperty("Key") + public String key; + + @JsonProperty("Value") + public String value; + + public LxcConf(String key, String value) { + this.key = key; + this.value = value; + } + + public LxcConf() { + } + + public String getKey() { + return key; + } + + public LxcConf setKey(String key) { + this.key = key; + return this; + } + + public String getValue() { + return value; + } + + public LxcConf setValue(String value) { + this.value = value; + return this; + } + + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/IBuilder.java b/src/main/java/com/kpelykh/docker/client/model/IBuilder.java new file mode 100644 index 00000000..7f5f1606 --- /dev/null +++ b/src/main/java/com/kpelykh/docker/client/model/IBuilder.java @@ -0,0 +1,9 @@ +package com.kpelykh.docker.client.model; + +/** + * Created by ben on 12/12/13. + */ +public interface IBuilder { + + T build(); +} diff --git a/src/main/java/com/kpelykh/docker/client/model/Image.java b/src/main/java/com/kpelykh/docker/client/model/Image.java index 3dbebd4f..cfc578ce 100644 --- a/src/main/java/com/kpelykh/docker/client/model/Image.java +++ b/src/main/java/com/kpelykh/docker/client/model/Image.java @@ -1,42 +1,118 @@ -package com.kpelykh.docker.client.model; - -import org.codehaus.jackson.annotate.JsonProperty; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class Image { - - @JsonProperty("Repository") - public String repository; - - @JsonProperty("Tag") - public String tag; - - @JsonProperty("Id") - public String id; - - @JsonProperty("Created") - public long created; - - @JsonProperty("Size") - public int size; - - @JsonProperty("VirtualSize") - public int virtualSize; - - @Override - public String toString() { - return "Image{" + - "repository='" + repository + '\'' + - ", tag='" + tag + '\'' + - ", id='" + id + '\'' + - ", created=" + created + - ", size=" + size + - ", virtualSize=" + virtualSize + - '}'; - } - -} +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Arrays; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Image { + + @JsonProperty("Id") + private String id; + + @JsonProperty("RepoTags") + private String[] repoTags; + + @JsonProperty("Repository") + private String repository; + + @JsonProperty("Tag") + private String tag; + + + @JsonProperty("ParentId") + private String parentId; + + @JsonProperty("Created") + private long created; + + @JsonProperty("Size") + private long size; + + @JsonProperty("VirtualSize") + private long virtualSize; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String[] getRepoTags() { + return repoTags; + } + + public void setRepoTags(String[] repoTags) { + this.repoTags = repoTags; + } + + public String getRepository() { + return repository; + } + + public void setRepository(String repository) { + this.repository = repository; + } + + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } + + public String getParentId() { + return parentId; + } + + public void setParentId(String parentId) { + this.parentId = parentId; + } + + public long getCreated() { + return created; + } + + public void setCreated(long created) { + this.created = created; + } + + public long getSize() { + return size; + } + + public void setSize(long size) { + this.size = size; + } + + public long getVirtualSize() { + return virtualSize; + } + + public void setVirtualSize(long virtualSize) { + this.virtualSize = virtualSize; + } + + @Override + public String toString() { + return "Image{" + + "virtualSize=" + virtualSize + + ", id='" + id + '\'' + + ", repoTags=" + Arrays.toString(repoTags) + + ", repository='" + repository + '\'' + + ", tag='" + tag + '\'' + + ", parentId='" + parentId + '\'' + + ", created=" + created + + ", size=" + size + + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/ImageCreateResponse.java b/src/main/java/com/kpelykh/docker/client/model/ImageCreateResponse.java new file mode 100644 index 00000000..21545a2d --- /dev/null +++ b/src/main/java/com/kpelykh/docker/client/model/ImageCreateResponse.java @@ -0,0 +1,30 @@ +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Parse reponses from /images/create + * + * @author Ryan Campbell (ryan.campbell@gmail.com) + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ImageCreateResponse { + + @JsonProperty("status") + private String id; + + + public String getId() { + return id; + } + + + @Override + public String toString() { + return "ContainerCreateResponse{" + + "id='" + id + '\'' + + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/ImageInspectResponse.java b/src/main/java/com/kpelykh/docker/client/model/ImageInspectResponse.java index 176533be..3514670c 100644 --- a/src/main/java/com/kpelykh/docker/client/model/ImageInspectResponse.java +++ b/src/main/java/com/kpelykh/docker/client/model/ImageInspectResponse.java @@ -1,41 +1,152 @@ -package com.kpelykh.docker.client.model; - -import org.codehaus.jackson.annotate.JsonProperty; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class ImageInspectResponse { - - @JsonProperty("id") public String id; - @JsonProperty("parent") public String parent; - @JsonProperty("created") public String created; - @JsonProperty("container") public String container; - @JsonProperty("container_config") public ContainerConfig containerConfig; - @JsonProperty("Size") public int size; - @JsonProperty("docker_version") public String dockerVersion; - @JsonProperty("config") public ContainerConfig config; - @JsonProperty("architecture") public String arch; - @JsonProperty("comment") public String comment; - @JsonProperty("author") public String author; - - - @Override - public String toString() { - return "ImageInspectResponse{" + - "id='" + id + '\'' + - ", parent='" + parent + '\'' + - ", created='" + created + '\'' + - ", container='" + container + '\'' + - ", containerConfig=" + containerConfig + - ", size=" + size + - ", dockerVersion='" + dockerVersion + '\'' + - ", config=" + config + - ", arch='" + arch + '\'' + - ", comment='" + comment + '\'' + - ", author='" + author + '\'' + - '}'; - } -} +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ImageInspectResponse { + + @JsonProperty("id") + private String id; + + @JsonProperty("parent") private String parent; + + @JsonProperty("created") private String created; + + @JsonProperty("container") private String container; + + @JsonProperty("container_config") private ContainerConfig containerConfig; + + @JsonProperty("Size") private long size; + + @JsonProperty("docker_version") private String dockerVersion; + + @JsonProperty("config") private ContainerConfig config; + + @JsonProperty("architecture") private String arch; + + @JsonProperty("comment") private String comment; + + @JsonProperty("author") private String author; + + @JsonProperty("os") private String os; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getParent() { + return parent; + } + + public void setParent(String parent) { + this.parent = parent; + } + + public String getCreated() { + return created; + } + + public void setCreated(String created) { + this.created = created; + } + + public String getContainer() { + return container; + } + + public void setContainer(String container) { + this.container = container; + } + + public ContainerConfig getContainerConfig() { + return containerConfig; + } + + public void setContainerConfig(ContainerConfig containerConfig) { + this.containerConfig = containerConfig; + } + + public long getSize() { + return size; + } + + public void setSize(long size) { + this.size = size; + } + + public String getDockerVersion() { + return dockerVersion; + } + + public void setDockerVersion(String dockerVersion) { + this.dockerVersion = dockerVersion; + } + + public ContainerConfig getConfig() { + return config; + } + + public void setConfig(ContainerConfig config) { + this.config = config; + } + + public String getArch() { + return arch; + } + + public void setArch(String arch) { + this.arch = arch; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getOs() { + return os; + } + + public void setOs(String os) { + this.os = os; + } + + @Override + public String toString() { + return "ImageInspectResponse{" + + "id='" + id + '\'' + + ", parent='" + parent + '\'' + + ", created='" + created + '\'' + + ", container='" + container + '\'' + + ", containerConfig=" + containerConfig + + ", size=" + size + + ", dockerVersion='" + dockerVersion + '\'' + + ", config=" + config + + ", arch='" + arch + '\'' + + ", comment='" + comment + '\'' + + ", author='" + author + '\'' + + ", os='" + os + '\'' + + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/Info.java b/src/main/java/com/kpelykh/docker/client/model/Info.java index 9fcef2d6..72f2f360 100644 --- a/src/main/java/com/kpelykh/docker/client/model/Info.java +++ b/src/main/java/com/kpelykh/docker/client/model/Info.java @@ -1,41 +1,227 @@ -package com.kpelykh.docker.client.model; - -import org.codehaus.jackson.annotate.JsonProperty; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class Info { - - @JsonProperty("Debug") - public boolean debug; - - @JsonProperty("Containers") - public int containers; - - @JsonProperty("Images") - public int images; - - public int NFd; - - public int NGoroutines; - - @JsonProperty("MemoryLimit") - public boolean memoryLimit; - - - @Override - public String toString() { - return "Info{" + - "debug=" + debug + - ", containers=" + containers + - ", images=" + images + - ", NFd=" + NFd + - ", NGoroutines=" + NGoroutines + - ", memoryLimit=" + memoryLimit + - '}'; - } - -} +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import java.util.List; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class Info { + + @JsonProperty("Debug") + private boolean debug; + + @JsonProperty("Containers") + private int containers; + + @JsonProperty("Driver") + private String driver; + + @JsonProperty("DriverStatus") + private List driverStatuses; + + + @JsonProperty("Images") + private int images; + + @JsonProperty("IPv4Forwarding") + private String IPv4Forwarding; + + @JsonProperty("IndexServerAddress") + private String IndexServerAddress; + + + @JsonProperty("InitPath") + private String initPath; + + @JsonProperty("InitSha1") + private String initSha1; + + @JsonProperty("KernelVersion") + private String kernelVersion; + + @JsonProperty("LXCVersion") + private String lxcVersion; + + @JsonProperty("MemoryLimit") + private boolean memoryLimit; + + @JsonProperty("NEventsListener") + private long nEventListener; + + @JsonProperty("NFd") + private int NFd; + + @JsonProperty("NGoroutines") + private int NGoroutines; + + @JsonProperty("SwapLimit") + private int swapLimit; + + @JsonProperty("ExecutionDriver") + private String executionDriver; + + public boolean isDebug() { + return debug; + } + + public void setDebug(boolean debug) { + this.debug = debug; + } + + public int getContainers() { + return containers; + } + + public void setContainers(int containers) { + this.containers = containers; + } + + public String getDriver() { + return driver; + } + + public void setDriver(String driver) { + this.driver = driver; + } + + public List getDriverStatuses() { + return driverStatuses; + } + + public void setDriverStatuses(List driverStatuses) { + this.driverStatuses = driverStatuses; + } + + public int getImages() { + return images; + } + + public void setImages(int images) { + this.images = images; + } + + public String getIPv4Forwarding() { + return IPv4Forwarding; + } + + public void setIPv4Forwarding(String IPv4Forwarding) { + this.IPv4Forwarding = IPv4Forwarding; + } + + public String getIndexServerAddress() { + return IndexServerAddress; + } + + public void setIndexServerAddress(String indexServerAddress) { + IndexServerAddress = indexServerAddress; + } + + public String getInitPath() { + return initPath; + } + + public void setInitPath(String initPath) { + this.initPath = initPath; + } + + public String getInitSha1() { + return initSha1; + } + + public void setInitSha1(String initSha1) { + this.initSha1 = initSha1; + } + + public String getKernelVersion() { + return kernelVersion; + } + + public void setKernelVersion(String kernelVersion) { + this.kernelVersion = kernelVersion; + } + + public String getLxcVersion() { + return lxcVersion; + } + + public void setLxcVersion(String lxcVersion) { + this.lxcVersion = lxcVersion; + } + + public boolean isMemoryLimit() { + return memoryLimit; + } + + public void setMemoryLimit(boolean memoryLimit) { + this.memoryLimit = memoryLimit; + } + + public long getnEventListener() { + return nEventListener; + } + + public void setnEventListener(long nEventListener) { + this.nEventListener = nEventListener; + } + + public int getNFd() { + return NFd; + } + + public void setNFd(int NFd) { + this.NFd = NFd; + } + + public int getNGoroutines() { + return NGoroutines; + } + + public void setNGoroutines(int NGoroutines) { + this.NGoroutines = NGoroutines; + } + + public int getSwapLimit() { + return swapLimit; + } + + public void setSwapLimit(int swapLimit) { + this.swapLimit = swapLimit; + } + public String getExecutionDriver() { + return executionDriver; + } + + public void setExecutionDriver(String executionDriver) { + this.executionDriver=executionDriver; + } + + @Override + public String toString() { + return "Info{" + + "debug=" + debug + + ", containers=" + containers + + ", driver='" + driver + '\'' + + ", driverStatuses=" + driverStatuses + + ", images=" + images + + ", IPv4Forwarding='" + IPv4Forwarding + '\'' + + ", IndexServerAddress='" + IndexServerAddress + '\'' + + ", initPath='" + initPath + '\'' + + ", initSha1='" + initSha1 + '\'' + + ", kernelVersion='" + kernelVersion + '\'' + + ", lxcVersion='" + lxcVersion + '\'' + + ", memoryLimit=" + memoryLimit + + ", nEventListener=" + nEventListener + + ", NFd=" + NFd + + ", NGoroutines=" + NGoroutines + + ", swapLimit=" + swapLimit + + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/Port.java b/src/main/java/com/kpelykh/docker/client/model/Port.java new file mode 100644 index 00000000..538213ec --- /dev/null +++ b/src/main/java/com/kpelykh/docker/client/model/Port.java @@ -0,0 +1,53 @@ +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Nicolas De Loof + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Port { + + @JsonProperty("PrivatePort") + private long privatePort; + + @JsonProperty("PublicPort") + private long publicPort; + + @JsonProperty("Type") + private String type; + + public long getPrivatePort() { + return privatePort; + } + + public void setPrivatePort(long privatePort) { + this.privatePort = privatePort; + } + + public long getPublicPort() { + return publicPort; + } + + public void setPublicPort(long publicPort) { + this.publicPort = publicPort; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + @Override + public String toString() { + return "Port{" + + "privatePort=" + privatePort + + ", publicPort=" + publicPort + + ", type='" + type + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/kpelykh/docker/client/model/Ports.java b/src/main/java/com/kpelykh/docker/client/model/Ports.java new file mode 100644 index 00000000..fc590289 --- /dev/null +++ b/src/main/java/com/kpelykh/docker/client/model/Ports.java @@ -0,0 +1,132 @@ +package com.kpelykh.docker.client.model; + + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.node.NullNode; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +/** + * Created by ben on 16/12/13. + */ +@JsonDeserialize(using=Ports.Deserializer.class) +@JsonSerialize(using=Ports.Serializer.class) +public class Ports { + + + private final Map ports = new HashMap(); + + public Ports() { } + + public void addPort(Port port) { + ports.put(port.getPort(), port); + } + + @Override + public String toString(){ + return ports.toString(); + } + + public Map getAllPorts(){ + return ports; + } + + public static class Port{ + + private final String scheme; + private final String port; + private final String hostIp; + private final String hostPort; + + public Port(String scheme_, String port_, String hostIp_, String hostPort_) { + scheme = scheme_; + port = port_; + hostIp = hostIp_; + hostPort = hostPort_; + } + + public String getScheme() { + return scheme; + } + + public String getPort() { + return port; + } + + public String getHostIp() { + return hostIp; + } + + public String getHostPort() { + return hostPort; + } + + public static Port makePort(String full, String hostIp, String hostPort) { + if (full == null) return null; + String[] pieces = full.split("/"); + return new Port(pieces[1], pieces[0], hostIp, hostPort); + } + + @Override + public String toString() { + return "Port{" + + "scheme='" + scheme + '\'' + + ", port='" + port + '\'' + + ", hostIp='" + hostIp + '\'' + + ", hostPort='" + hostPort + '\'' + + '}'; + } + } + + public static class Deserializer extends JsonDeserializer { + @Override + public Ports deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { + + Ports out = new Ports(); + ObjectCodec oc = jsonParser.getCodec(); + JsonNode node = oc.readTree(jsonParser); + for (Iterator> it = node.fields(); it.hasNext();) { + + Map.Entry field = it.next(); + if (!field.getValue().equals(NullNode.getInstance())) { + String hostIp = field.getValue().get(0).get("HostIp").textValue(); + String hostPort = field.getValue().get(0).get("HostPort").textValue(); + out.addPort(Port.makePort(field.getKey(), hostIp, hostPort)); + } + } + return out; + } + } + + public static class Serializer extends JsonSerializer { + + @Override + public void serialize(Ports ports, JsonGenerator jsonGen, + SerializerProvider serProvider) throws IOException, JsonProcessingException { + + jsonGen.writeStartObject();//{ + for(String portKey : ports.getAllPorts().keySet()){ + Port p = ports.getAllPorts().get(portKey); + jsonGen.writeFieldName(p.getPort() + "/" + p.getScheme()); + jsonGen.writeStartArray(); + jsonGen.writeStartObject(); + jsonGen.writeStringField("HostIp", p.hostIp); + jsonGen.writeStringField("HostPort", p.hostPort); + jsonGen.writeEndObject(); + jsonGen.writeEndArray(); + } + jsonGen.writeEndObject();//} + } + + } + +} \ No newline at end of file diff --git a/src/main/java/com/kpelykh/docker/client/model/SearchItem.java b/src/main/java/com/kpelykh/docker/client/model/SearchItem.java index fc87d769..d7f6eb4f 100644 --- a/src/main/java/com/kpelykh/docker/client/model/SearchItem.java +++ b/src/main/java/com/kpelykh/docker/client/model/SearchItem.java @@ -1,25 +1,54 @@ -package com.kpelykh.docker.client.model; - -import org.codehaus.jackson.annotate.JsonProperty; - -import java.util.List; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class SearchItem { - - @JsonProperty("Name") - public String name; - - @JsonProperty("Description") - public String description; - - @Override - public String toString() { - return "name='" + name + '\'' + - ", description='" + description + '\'' + '}'; - } -} +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class SearchItem { + + @JsonProperty("star_count") + private int starCount; + + @JsonProperty("is_official") + private boolean isOfficial; + + @JsonProperty("is_trusted") + private boolean isTrusted; + + @JsonProperty("name") + private String name; + + @JsonProperty("description") + private String description; + + public int getStarCount() { + return starCount; + } + + public boolean isOfficial() { + return isOfficial; + } + + public boolean isTrusted() { + return isTrusted; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + @Override + public String toString() { + return "name='" + name + '\'' + + ", description='" + description + '\'' + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/Version.java b/src/main/java/com/kpelykh/docker/client/model/Version.java index 3fcaaac1..a427aafb 100644 --- a/src/main/java/com/kpelykh/docker/client/model/Version.java +++ b/src/main/java/com/kpelykh/docker/client/model/Version.java @@ -1,32 +1,103 @@ -package com.kpelykh.docker.client.model; - -import org.codehaus.jackson.annotate.JsonProperty; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class Version { - - - @JsonProperty("Version") - public String version; - - @JsonProperty("GitCommit") - public String gitCommit; - - @JsonProperty("GoVersion") - public String goVersion; - - - @Override - public String toString() { - return "Version{" + - "version='" + version + '\'' + - ", gitCommit='" + gitCommit + '\'' + - ", goVersion='" + goVersion + '\'' + - '}'; - } - -} +package com.kpelykh.docker.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Version { + + @JsonProperty("Version") + private String version; + + @JsonProperty("GitCommit") + private String gitCommit; + + @JsonProperty("GoVersion") + private String goVersion; + + @JsonProperty("KernelVersion") + private String kernelVersion; + + @JsonProperty("Arch") + private String arch; + + @JsonProperty("Os") + private String operatingSystem; + + @JsonProperty("ApiVersion") + private String apiVersion; + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getGitCommit() { + return gitCommit; + } + + public void setGitCommit(String gitCommit) { + this.gitCommit = gitCommit; + } + + public String getGoVersion() { + return goVersion; + } + + public void setGoVersion(String goVersion) { + this.goVersion = goVersion; + } + + public String getKernelVersion() { + return kernelVersion; + } + + public void setKernelVersion(String kernelVersion) { + this.kernelVersion = kernelVersion; + } + + public String getArch() { + return arch; + } + + public void setArch(String arch) { + this.arch = arch; + } + + public String getOperatingSystem() { + return operatingSystem; + } + + public void setOperatingSystem(String operatingSystem) { + this.operatingSystem = operatingSystem; + } + + public void setApiVersion(String apiVersion) { + this.apiVersion = apiVersion; + } + + public String getApiVersion() { + return apiVersion; + } + + @Override + public String toString() { + return "Version{" + + "version='" + version + '\'' + + ", gitCommit='" + gitCommit + '\'' + + ", goVersion='" + goVersion + '\'' + + ", kernelVersion='" + kernelVersion + '\'' + + ", arch='" + arch + '\'' + + ", operatingSystem='" + operatingSystem + '\'' + + ", apiVersion='" + apiVersion + '\'' + + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/utils/CompressArchiveUtil.java b/src/main/java/com/kpelykh/docker/client/utils/CompressArchiveUtil.java index 8fdbfd3e..aabf4cbb 100644 --- a/src/main/java/com/kpelykh/docker/client/utils/CompressArchiveUtil.java +++ b/src/main/java/com/kpelykh/docker/client/utils/CompressArchiveUtil.java @@ -1,63 +1,38 @@ package com.kpelykh.docker.client.utils; -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Collection; - import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.filefilter.RegexFileFilter; -import org.apache.commons.lang.StringUtils; -import static org.apache.commons.io.filefilter.FileFilterUtils.*; +import java.io.*; public class CompressArchiveUtil { - public static File archiveTARFiles(File baseDir, String archiveNameWithOutExtension) throws IOException { - - File tarFile = null; - - tarFile = new File(FileUtils.getTempDirectoryPath(), archiveNameWithOutExtension + ".tar"); - - Collection files = - FileUtils.listFiles( - baseDir, - new RegexFileFilter("^(.*?)"), - and(directoryFileFilter(), notFileFilter(nameFileFilter(baseDir.getName())))); - - byte[] buf = new byte[1024]; - int len; - - { - TarArchiveOutputStream tos = new TarArchiveOutputStream(new FileOutputStream(tarFile)); + public static File archiveTARFiles(File base, Iterable files, String archiveNameWithOutExtension) throws IOException { + File tarFile = new File(FileUtils.getTempDirectoryPath(), archiveNameWithOutExtension + ".tar"); + TarArchiveOutputStream tos = new TarArchiveOutputStream(new FileOutputStream(tarFile)); + try { tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); for (File file : files) { TarArchiveEntry tarEntry = new TarArchiveEntry(file); - tarEntry.setName(StringUtils.substringAfter(file.toString(), baseDir.getPath())); + tarEntry.setName(relativize(base, file)); tos.putArchiveEntry(tarEntry); if (!file.isDirectory()) { - FileInputStream fin = new FileInputStream(file); - BufferedInputStream in = new BufferedInputStream(fin); - - while ((len = in.read(buf)) != -1) { - tos.write(buf, 0, len); - } - - in.close(); + FileUtils.copyFile(file, tos); } tos.closeArchiveEntry(); - } + } finally { tos.close(); } - - return tarFile; - } + return tarFile; + } + + private static String relativize(File base, File absolute) { + String relative = base.toURI().relativize(absolute.toURI()).getPath(); + return relative; + } } diff --git a/src/main/java/com/kpelykh/docker/client/utils/JsonClientFilter.java b/src/main/java/com/kpelykh/docker/client/utils/JsonClientFilter.java index eae8d089..55b8b287 100644 --- a/src/main/java/com/kpelykh/docker/client/utils/JsonClientFilter.java +++ b/src/main/java/com/kpelykh/docker/client/utils/JsonClientFilter.java @@ -5,10 +5,6 @@ import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.filter.ClientFilter; -import javax.ws.rs.core.MediaType; -import java.util.HashMap; -import java.util.Map; - /** * * @author Konstantin Pelykh (kpelykh@gmail.com) @@ -17,12 +13,6 @@ public class JsonClientFilter extends ClientFilter { public ClientResponse handle(ClientRequest cr) { - MediaType contentType = (MediaType) cr.getHeaders().getFirst("Content-Type"); - if (contentType != null && !contentType.getParameters().containsKey("charset")) { - Map contentParams = new HashMap(); - contentParams.put("charset", "UTF-8"); - cr.getHeaders().putSingle("Content-Type", new MediaType(contentType.getType(), contentType.getSubtype(), contentParams)); - } // Call the next filter ClientResponse resp = getNext().handle(cr); String respContentType = resp.getHeaders().getFirst("Content-Type"); @@ -33,4 +23,4 @@ public ClientResponse handle(ClientRequest cr) { return resp; } -} \ No newline at end of file +} diff --git a/src/main/resources/docker.io.properties b/src/main/resources/docker.io.properties new file mode 100644 index 00000000..0ce162bd --- /dev/null +++ b/src/main/resources/docker.io.properties @@ -0,0 +1,2 @@ +docker.io.url=http://localhost:4243 +docker.io.version=1.11 \ No newline at end of file diff --git a/src/test/java/com/kpelykh/docker/client/test/AbstractDockerClientTest.java b/src/test/java/com/kpelykh/docker/client/test/AbstractDockerClientTest.java new file mode 100644 index 00000000..d8313ca4 --- /dev/null +++ b/src/test/java/com/kpelykh/docker/client/test/AbstractDockerClientTest.java @@ -0,0 +1,92 @@ +package com.kpelykh.docker.client.test; + +import com.kpelykh.docker.client.DockerClient; +import com.kpelykh.docker.client.DockerException; +import com.sun.jersey.api.client.ClientResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.ITestResult; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +public abstract class AbstractDockerClientTest extends Assert { + + public static final Logger LOG = LoggerFactory + .getLogger(AbstractDockerClientTest.class); + + protected DockerClient dockerClient; + + protected List tmpImgs; + protected List tmpContainers; + + + public void beforeTest() throws DockerException { + LOG.info("======================= BEFORETEST ======================="); + String url = System.getProperty("docker.url", "http://localhost:4243"); + LOG.info("Connecting to Docker server at " + url); + dockerClient = new DockerClient(url); + + LOG.info("Pulling image 'busybox'"); + // need to block until image is pulled completely + logResponseStream(dockerClient.pull("busybox")); + + + + assertNotNull(dockerClient); + LOG.info("======================= END OF BEFORETEST =======================\n\n"); + } + + public void afterTest() { + LOG.info("======================= END OF AFTERTEST ======================="); + } + + + public void beforeMethod(Method method) { + tmpContainers = new ArrayList(); + tmpImgs = new ArrayList(); + LOG.info(String + .format("################################## STARTING %s ##################################", + method.getName())); + } + + public void afterMethod(ITestResult result) { + + for (String container : tmpContainers) { + LOG.info("Cleaning up temporary container {}", container); + try { + dockerClient.stopContainer(container); + dockerClient.kill(container); + dockerClient.removeContainer(container); + } catch (DockerException ignore) { + } + } + + for (String image : tmpImgs) { + LOG.info("Cleaning up temporary image {}", image); + try { + dockerClient.removeImage(image); + } catch (DockerException ignore) { + } + } + + LOG.info( + "################################## END OF {} ##################################\n", + result.getName()); + } + + protected String logResponseStream(ClientResponse response) { + String responseString; + try { + responseString = DockerClient.asString(response); + } catch (IOException e) { + throw new RuntimeException(e); + } + LOG.info("Container log: {}", responseString); + return responseString; + } + +} diff --git a/src/test/java/com/kpelykh/docker/client/test/DockerClientAuthTest.java b/src/test/java/com/kpelykh/docker/client/test/DockerClientAuthTest.java new file mode 100644 index 00000000..8c7fc4fa --- /dev/null +++ b/src/test/java/com/kpelykh/docker/client/test/DockerClientAuthTest.java @@ -0,0 +1,51 @@ +package com.kpelykh.docker.client.test; + +import com.kpelykh.docker.client.DockerException; +import com.sun.jersey.api.client.UniformInterfaceException; + +import org.hamcrest.Matchers; +import org.testng.ITestResult; +import org.testng.annotations.*; + +import java.lang.reflect.Method; + +import static org.hamcrest.MatcherAssert.assertThat; + +public class DockerClientAuthTest extends AbstractDockerClientTest { + + @BeforeTest + public void beforeTest() throws DockerException { + super.beforeTest(); + } + @AfterTest + public void afterTest() { + super.afterTest(); + } + + @BeforeMethod + public void beforeMethod(Method method) { + super.beforeMethod(method); + } + + @AfterMethod + public void afterMethod(ITestResult result) { + super.afterMethod(result); + } + + @Test + public void testAuth() throws Exception { + dockerClient.auth(); + } + + @Test + public void testAuthInvalid() throws Exception { + System.setProperty("docker.io.password", "garbage"); + try { + dockerClient.auth(); + fail(); + } catch (DockerException e) { + assertThat(e.getCause(), Matchers.instanceOf(UniformInterfaceException.class)); + assertEquals(((UniformInterfaceException) e.getCause()).getResponse().getStatus(), 401); + } + } +} diff --git a/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java b/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java index d4d93095..f6af3823 100644 --- a/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java +++ b/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java @@ -1,769 +1,824 @@ package com.kpelykh.docker.client.test; -import com.kpelykh.docker.client.DockerClient; -import com.kpelykh.docker.client.DockerException; -import com.kpelykh.docker.client.model.*; +import static ch.lambdaj.Lambda.filter; +import static ch.lambdaj.Lambda.selectUnique; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.testinfected.hamcrest.jpa.HasFieldWithValue.hasField; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.net.DatagramSocket; +import java.net.ServerSocket; +import java.util.List; +import java.util.Random; -import com.sun.jersey.api.client.ClientResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.math.RandomUtils; import org.hamcrest.Matcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.Assert; import org.testng.ITestResult; -import org.testng.annotations.*; - -import java.io.*; -import java.lang.reflect.Method; -import java.net.DatagramSocket; -import java.net.ServerSocket; -import java.util.ArrayList; -import java.util.List; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; -import static ch.lambdaj.Lambda.filter; -import static ch.lambdaj.Lambda.selectUnique; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.hamcrest.Matchers.hasItem; -import static org.testinfected.hamcrest.jpa.HasFieldWithValue.hasField; +import com.kpelykh.docker.client.DockerException; +import com.kpelykh.docker.client.model.ChangeLog; +import com.kpelykh.docker.client.model.CommitConfig; +import com.kpelykh.docker.client.model.Container; +import com.kpelykh.docker.client.model.ContainerConfig; +import com.kpelykh.docker.client.model.ContainerCreateResponse; +import com.kpelykh.docker.client.model.ContainerInspectResponse; +import com.kpelykh.docker.client.model.Image; +import com.kpelykh.docker.client.model.ImageInspectResponse; +import com.kpelykh.docker.client.model.Info; +import com.kpelykh.docker.client.model.Ports; +import com.kpelykh.docker.client.model.SearchItem; +import com.kpelykh.docker.client.model.Version; +import com.sun.jersey.api.client.ClientResponse; /** * Unit test for DockerClient. + * * @author Konstantin Pelykh (kpelykh@gmail.com) */ -public class DockerClientTest extends Assert -{ - public static final Logger LOG = LoggerFactory.getLogger(DockerClientTest.class); - - private DockerClient dockerClient; - - private List tmpImgs = new ArrayList(); - private List tmpContainers = new ArrayList(); - - @BeforeTest - public void beforeTest() throws DockerException { - LOG.info("======================= BEFORETEST ======================="); - LOG.info("Connecting to Docker server at http://localhost:4243"); - dockerClient = new DockerClient("http://localhost:4243"); - LOG.info("Creating image 'busybox'"); - - dockerClient.pull("busybox"); - - assertNotNull(dockerClient); - LOG.info("======================= END OF BEFORETEST =======================\n\n"); - } - - @AfterTest - public void afterTest() { - LOG.info("======================= END OF AFTERTEST ======================="); - } - - @BeforeMethod - public void beforeMethod(Method method) { - LOG.info(String.format("################################## STARTING %s ##################################", method.getName())); - } - - @AfterMethod - public void afterMethod(ITestResult result) { - for (String image : tmpImgs) { - LOG.info("Cleaning up temporary image " + image); - try { - dockerClient.removeImage(image); - } catch (DockerException ignore) {} - } - - for (String container : tmpContainers) { - LOG.info("Cleaning up temporary container " + container); - try { - dockerClient.removeContainer(container); - } catch (DockerException ignore) {} - } - LOG.info(String.format("################################## END OF %s ##################################\n", result.getName())); - } - - /* - * ######################### - * ## INFORMATION TESTS ## - * ######################### - */ - - @Test - public void testDockerVersion() throws DockerException { - Version version = dockerClient.version(); - LOG.info(version.toString()); - - assertTrue(version.goVersion.length() > 0); - assertTrue(version.version.length() > 0); - - assertEquals(StringUtils.split(version.version, ".").length, 3); - - } - - @Test - public void testDockerInfo() throws DockerException { - Info dockerInfo = dockerClient.info(); - LOG.info(dockerInfo.toString()); - - assertTrue(dockerInfo.toString().contains("containers")); - assertTrue(dockerInfo.toString().contains("images")); - assertTrue(dockerInfo.toString().contains("debug")); - - assertTrue(dockerInfo.containers > 0); - assertTrue(dockerInfo.images > 0); - assertTrue(dockerInfo.NFd > 0); - assertTrue(dockerInfo.NGoroutines > 0); - assertTrue(dockerInfo.memoryLimit); - } - - @Test - public void testDockerSearch() throws DockerException { - List dockerSearch = dockerClient.search("busybox"); - LOG.info("Search returned" + dockerSearch.toString()); - - Matcher matcher = hasItem(hasField("name", equalTo("busybox"))); - assertThat(dockerSearch, matcher); - - assertThat(filter(hasField("name", is("busybox")), dockerSearch).size(), equalTo(1)); - } - - /* - * ################### - * ## LISTING TESTS ## - * ################### - */ - - - @Test - public void testImages() throws DockerException { - List images = dockerClient.getImages(false); - assertThat(images, notNullValue()); - LOG.info("Images List: " + images); - Info info = dockerClient.info(); - - //assertThat(images.size(), equalTo(info.images)); - - Image img = images.get(0); - assertThat(img.created, is(greaterThan(0L)) ); - assertThat(img.size, is(greaterThan(0)) ); - assertThat(img.virtualSize, is(greaterThan(0)) ); - assertThat(img.id, not(isEmptyString())); - assertThat(img.tag, not(isEmptyString())); - assertThat(img.repository, not(isEmptyString())); - } - - - @Test - public void testListContainers() throws DockerException { - List containers = dockerClient.listContainers(true); - assertThat(containers, notNullValue()); - LOG.info("Container List: " + containers); - - int size = containers.size(); - - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[]{"echo"}); - - ContainerCreateResponse container1 = dockerClient.createContainer(containerConfig); - assertThat(container1.id, not(isEmptyString())); - dockerClient.startContainer(container1.id); - tmpContainers.add(container1.id); - - List containers2 = dockerClient.listContainers(true); - assertThat(size + 1, is(equalTo(containers2.size()))); - Matcher matcher = hasItem(hasField("id", startsWith(container1.id))); - assertThat(containers2, matcher); - - List filteredContainers = filter(hasField("id", startsWith(container1.id)), containers2); - assertThat(filteredContainers.size(), is(equalTo(1))); - - Container container2 = filteredContainers.get(0); - assertThat(container2.command, not(isEmptyString())); - assertThat(container2.image, equalTo("busybox:latest")); - } - - - /* - * ##################### - * ## CONTAINER TESTS ## - * ##################### - */ - - @Test - public void testCreateContainer() throws DockerException { - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[]{"true"}); - - - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - - LOG.info("Created container " + container.toString()); - - assertThat(container.id, not(isEmptyString())); - - tmpContainers.add(container.id); - } - - @Test - public void testStartContainer() throws DockerException { - - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[]{"true"}); - - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - LOG.info("Created container " + container.toString()); - assertThat(container.id, not(isEmptyString())); - tmpContainers.add(container.id); - - dockerClient.startContainer(container.id); - - ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container.id); - LOG.info("Container Inspect: " + containerInspectResponse.toString()); - - assertThat(containerInspectResponse.config, is(notNullValue())); - assertThat(containerInspectResponse.id, not(isEmptyString())); - - assertThat(containerInspectResponse.id, startsWith(container.id)); - - assertThat(containerInspectResponse.image, not(isEmptyString())); - assertThat(containerInspectResponse.state, is(notNullValue())); - - assertThat(containerInspectResponse.state.running, is(true)); +public class DockerClientTest extends AbstractDockerClientTest { + public static final Logger LOG = LoggerFactory + .getLogger(DockerClientTest.class); + + @BeforeTest + public void beforeTest() throws DockerException { + super.beforeTest(); + } + @AfterTest + public void afterTest() { + super.afterTest(); + } + + @BeforeMethod + public void beforeMethod(Method method) { + super.beforeMethod(method); + } + + @AfterMethod + public void afterMethod(ITestResult result) { + super.afterMethod(result); + } + + /* + * ######################### ## INFORMATION TESTS ## + * ######################### + */ + + @Test + public void testDockerVersion() throws DockerException { + Version version = dockerClient.version(); + LOG.info(version.toString()); + + assertTrue(version.getGoVersion().length() > 0); + assertTrue(version.getVersion().length() > 0); + + assertEquals(StringUtils.split(version.getVersion(), ".").length, 3); + + } + + @Test + public void testDockerInfo() throws DockerException { + Info dockerInfo = dockerClient.info(); + LOG.info(dockerInfo.toString()); + + assertTrue(dockerInfo.toString().contains("containers")); + assertTrue(dockerInfo.toString().contains("images")); + assertTrue(dockerInfo.toString().contains("debug")); + + assertTrue(dockerInfo.getContainers() > 0); + assertTrue(dockerInfo.getImages() > 0); + assertTrue(dockerInfo.getNFd() > 0); + assertTrue(dockerInfo.getNGoroutines() > 0); + assertTrue(dockerInfo.isMemoryLimit()); + } + + @Test + public void testDockerSearch() throws DockerException { + List dockerSearch = dockerClient.search("busybox"); + LOG.info("Search returned {}", dockerSearch.toString()); + + Matcher matcher = hasItem(hasField("name", equalTo("busybox"))); + assertThat(dockerSearch, matcher); + + assertThat( + filter(hasField("name", is("busybox")), dockerSearch).size(), + equalTo(1)); + } + + /* + * ################### ## LISTING TESTS ## ################### + */ + + @Test + public void testImages() throws DockerException { + List images = dockerClient.getImages(true); + assertThat(images, notNullValue()); + LOG.info("Images List: {}", images); + Info info = dockerClient.info(); + + assertThat(images.size(), equalTo(info.getImages())); + + Image img = images.get(0); + assertThat(img.getCreated(), is(greaterThan(0L))); + assertThat(img.getVirtualSize(), is(greaterThan(0L))); + assertThat(img.getId(), not(isEmptyString())); + assertThat(img.getTag(), not(isEmptyString())); + assertThat(img.getRepository(), not(isEmptyString())); + } + + @Test + public void testListContainers() throws DockerException { + + String testImage = "hackmann/empty"; + + LOG.info("Pulling image 'hackmann/empty'"); + // need to block until image is pulled completely + logResponseStream(dockerClient.pull(testImage)); + tmpImgs.add(testImage); + + List containers = dockerClient.listContainers(true); + assertThat(containers, notNullValue()); + LOG.info("Container List: {}", containers); + + int size = containers.size(); + + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage(testImage); + containerConfig.setCmd(new String[] { "echo" }); + + ContainerCreateResponse container1 = dockerClient + .createContainer(containerConfig); + + assertThat(container1.getId(), not(isEmptyString())); + + ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container1.getId()); + + assertThat(containerInspectResponse.getConfig().getImage(), is(equalTo(testImage))); + + + dockerClient.startContainer(container1.getId()); + tmpContainers.add(container1.getId()); + + LOG.info("container id: " + container1.getId()); + + List containers2 = dockerClient.listContainers(true); + + for(Container container: containers2) { + LOG.info("listContainer: id=" + container.getId() +" image=" + container.getImage()); + } + + assertThat(size + 1, is(equalTo(containers2.size()))); + Matcher matcher = hasItem(hasField("id", startsWith(container1.getId()))); + assertThat(containers2, matcher); + + List filteredContainers = filter( + hasField("id", startsWith(container1.getId())), containers2); + assertThat(filteredContainers.size(), is(equalTo(1))); + + for(Container container: filteredContainers) { + LOG.info("filteredContainer: " + container.getImage()); + } + + Container container2 = filteredContainers.get(0); + assertThat(container2.getCommand(), not(isEmptyString())); + assertThat(container2.getImage(), equalTo(testImage + ":latest")); + } + + /* + * ##################### ## CONTAINER TESTS ## ##################### + */ + + @Test + public void testCreateContainer() throws DockerException { + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(new String[] { "true" }); + + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + tmpContainers.add(container.getId()); + } + + @Test + public void testStartContainer() throws DockerException { + + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(new String[] { "true" }); + + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + LOG.info("Created container {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + boolean add = tmpContainers.add(container.getId()); + + dockerClient.startContainer(container.getId()); + + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainer(container.getId()); + LOG.info("Container Inspect: {}", containerInspectResponse.toString()); + + assertThat(containerInspectResponse.config, is(notNullValue())); + assertThat(containerInspectResponse.getId(), not(isEmptyString())); + + assertThat(containerInspectResponse.getId(), + startsWith(container.getId())); + + assertThat(containerInspectResponse.getImageId(), not(isEmptyString())); + assertThat(containerInspectResponse.getState(), is(notNullValue())); - if (!containerInspectResponse.state.running) { - assertThat(containerInspectResponse.state.exitCode, is(equalTo(0))); - } + assertThat(containerInspectResponse.getState().running, is(true)); - } - - @Test - public void testWaitContainer() throws DockerException { - - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[]{"true"}); - - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - LOG.info("Created container " + container.toString()); - assertThat(container.id, not(isEmptyString())); - tmpContainers.add(container.id); - - dockerClient.startContainer(container.id); - - int exitCode = dockerClient.waitContainer(container.id); - LOG.info("Container exit code: " + exitCode); - - assertThat(exitCode, equalTo(0)); - - ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container.id); - LOG.info("Container Inspect: " + containerInspectResponse.toString()); - - assertThat(containerInspectResponse.state.running, is(equalTo(false))); - assertThat(containerInspectResponse.state.exitCode, is(equalTo(exitCode))); - - } + if (!containerInspectResponse.getState().running) { + assertThat(containerInspectResponse.getState().exitCode, + is(equalTo(0))); + } - @Test - public void testLogs() throws DockerException, IOException { + } - String snippet = "'Flowering Nights (Sakuya Iyazoi)"; + @Test + public void testWaitContainer() throws DockerException { - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[] {"echo", "-n", snippet}); + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(new String[] { "true" }); - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - LOG.info("Created container " + container.toString()); - assertThat(container.id, not(isEmptyString())); + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + tmpContainers.add(container.getId()); - dockerClient.startContainer(container.id); - tmpContainers.add(container.id); + dockerClient.startContainer(container.getId()); - int exitCode = dockerClient.waitContainer(container.id); + int exitCode = dockerClient.waitContainer(container.getId()); + LOG.info("Container exit code: {}", exitCode); - assertThat(exitCode, equalTo(0)); + assertThat(exitCode, equalTo(0)); - ClientResponse response = dockerClient.logContainer(container.id); + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainer(container.getId()); + LOG.info("Container Inspect: {}", containerInspectResponse.toString()); - StringWriter logwriter = new StringWriter(); + assertThat(containerInspectResponse.getState().running, + is(equalTo(false))); + assertThat(containerInspectResponse.getState().exitCode, + is(equalTo(exitCode))); - try { - LineIterator itr = IOUtils.lineIterator(response.getEntityInputStream(), "UTF-8"); - while (itr.hasNext()) { - String line = itr.next(); - logwriter.write(line + (itr.hasNext() ? "\n" : "")); - LOG.info(line); - } - } finally { - IOUtils.closeQuietly(response.getEntityInputStream()); - } + } - String fullLog = logwriter.toString(); + @Test + public void testLogs() throws DockerException, IOException { - LOG.info("Container log: " + fullLog); - assertThat(fullLog, equalTo(snippet)); - } + String snippet = "hello world"; - @Test - public void testDiff() throws DockerException { - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[] {"touch", "/test"}); - - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - LOG.info("Created container " + container.toString()); - assertThat(container.id, not(isEmptyString())); - dockerClient.startContainer(container.id); - tmpContainers.add(container.id); - int exitCode = dockerClient.waitContainer(container.id); - assertThat(exitCode, equalTo(0)); - - List filesystemDiff = dockerClient.containterDiff(container.id); - LOG.info("Container DIFF: " + filesystemDiff.toString()); - - assertThat(filesystemDiff.size(), equalTo(4)); - ChangeLog testChangeLog = selectUnique(filesystemDiff, hasField("path", equalTo("/test"))); - - assertThat(testChangeLog, hasField("path", equalTo("/test"))); - assertThat(testChangeLog, hasField("kind", equalTo(1))); - } + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(new String[] { "/bin/echo", snippet }); - @Test - public void testStopContainer() throws DockerException { + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[] {"sleep", "9999"}); + dockerClient.startContainer(container.getId()); + tmpContainers.add(container.getId()); - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - LOG.info("Created container " + container.toString()); - assertThat(container.id, not(isEmptyString())); - dockerClient.startContainer(container.id); - tmpContainers.add(container.id); + int exitCode = dockerClient.waitContainer(container.getId()); - LOG.info("Stopping container " + container.id); - dockerClient.stopContainer(container.id, 2); + assertThat(exitCode, equalTo(0)); - ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container.id); - LOG.info("Container Inspect:" + containerInspectResponse.toString()); + ClientResponse response = dockerClient.logContainer(container.getId()); - assertThat(containerInspectResponse.state.running, is(equalTo(false))); - assertThat(containerInspectResponse.state.exitCode, not(equalTo(0))); - } + assertThat(logResponseStream(response), endsWith(snippet)); + } - @Test - public void testKillContainer() throws DockerException { + @Test + public void testDiff() throws DockerException { + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(new String[] { "touch", "/test" }); - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[] {"sleep", "9999"}); + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainer(container.getId()); + boolean add = tmpContainers.add(container.getId()); + int exitCode = dockerClient.waitContainer(container.getId()); + assertThat(exitCode, equalTo(0)); - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - LOG.info("Created container " + container.toString()); - assertThat(container.id, not(isEmptyString())); - dockerClient.startContainer(container.id); - tmpContainers.add(container.id); + List filesystemDiff = dockerClient.containerDiff(container.getId()); + LOG.info("Container DIFF: {}", filesystemDiff.toString()); - LOG.info("Killing container " + container.id); - dockerClient.kill(container.id); + assertThat(filesystemDiff.size(), equalTo(1)); + ChangeLog testChangeLog = selectUnique(filesystemDiff, + hasField("path", equalTo("/test"))); - ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container.id); - LOG.info("Container Inspect:" + containerInspectResponse.toString()); + assertThat(testChangeLog, hasField("path", equalTo("/test"))); + assertThat(testChangeLog, hasField("kind", equalTo(1))); + } - assertThat(containerInspectResponse.state.running, is(equalTo(false))); - assertThat(containerInspectResponse.state.exitCode, not(equalTo(0))); + @Test + public void testStopContainer() throws DockerException { - } - - @Test - public void restartContainer() throws DockerException { + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(new String[] { "sleep", "9999" }); - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[] {"sleep", "9999"}); + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainer(container.getId()); + tmpContainers.add(container.getId()); - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - LOG.info("Created container " + container.toString()); - assertThat(container.id, not(isEmptyString())); - dockerClient.startContainer(container.id); - tmpContainers.add(container.id); - - ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container.id); - LOG.info("Container Inspect:" + containerInspectResponse.toString()); - - String startTime = containerInspectResponse.state.startedAt; - - dockerClient.restart(container.id, 2); - - ContainerInspectResponse containerInspectResponse2 = dockerClient.inspectContainer(container.id); - LOG.info("Container Inspect After Restart:" + containerInspectResponse2.toString()); - - String startTime2 = containerInspectResponse2.state.startedAt; - - assertThat(startTime, not(equalTo(startTime2))); - - assertThat(containerInspectResponse.state.running, is(equalTo(true))); - - dockerClient.kill(container.id); - } - - @Test - public void removeContainer() throws DockerException { - - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[] {"true"}); - - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - - dockerClient.startContainer(container.id); - dockerClient.waitContainer(container.id); - tmpContainers.add(container.id); - - LOG.info("Removing container " + container.id); - dockerClient.removeContainer(container.id); - - List containers2 = dockerClient.listContainers(true); - Matcher matcher = not(hasItem(hasField("id", startsWith(container.id)))); - assertThat(containers2, matcher); - - } - - /* - * ################## - * ## IMAGES TESTS ## - * ################## - * */ - - @Test - public void testPullImage() throws DockerException, IOException { + LOG.info("Stopping container: {}", container.getId()); + dockerClient.stopContainer(container.getId(), 2); - String testImage = "joffrey/test001"; + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainer(container.getId()); + LOG.info("Container Inspect: {}", containerInspectResponse.toString()); - LOG.info("Removing image " + testImage); - dockerClient.removeImage(testImage); + assertThat(containerInspectResponse.getState().running, + is(equalTo(false))); + assertThat(containerInspectResponse.getState().exitCode, + not(equalTo(0))); + } - Info info = dockerClient.info(); - LOG.info("Client info " + info.toString()); + @Test + public void testKillContainer() throws DockerException { - int imgCount= info.images; + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(new String[] { "sleep", "9999" }); - LOG.info("Pulling image " + testImage); + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainer(container.getId()); + tmpContainers.add(container.getId()); - ClientResponse response = dockerClient.pull(testImage); + LOG.info("Killing container: {}", container.getId()); + dockerClient.kill(container.getId()); - StringWriter logwriter = new StringWriter(); + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainer(container.getId()); + LOG.info("Container Inspect: {}", containerInspectResponse.toString()); - try { - LineIterator itr = IOUtils.lineIterator(response.getEntityInputStream(), "UTF-8"); - while (itr.hasNext()) { - String line = itr.next(); - logwriter.write(line + "\n"); - LOG.info(line); - } - } finally { - IOUtils.closeQuietly(response.getEntityInputStream()); - } + assertThat(containerInspectResponse.getState().running, + is(equalTo(false))); + assertThat(containerInspectResponse.getState().exitCode, + not(equalTo(0))); - String fullLog = logwriter.toString(); - assertThat(fullLog, containsString("Pulling repository joffrey/test001")); + } - tmpImgs.add(testImage); + @Test + public void restartContainer() throws DockerException { - info = dockerClient.info(); - LOG.info("Client info after pull " + info.toString()); + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(new String[] { "sleep", "9999" }); - assertThat(imgCount + 2, equalTo(info.images)); + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainer(container.getId()); + tmpContainers.add(container.getId()); - ImageInspectResponse imageInspectResponse = dockerClient.inspectImage(testImage); - LOG.info("Image Inspect: " + imageInspectResponse.toString()); - assertThat(imageInspectResponse, notNullValue()); - } + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainer(container.getId()); + LOG.info("Container Inspect: {}", containerInspectResponse.toString()); + String startTime = containerInspectResponse.getState().startedAt; - @Test - public void commitImage() throws DockerException { + dockerClient.restart(container.getId(), 2); - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[] {"touch", "/test"}); + ContainerInspectResponse containerInspectResponse2 = dockerClient + .inspectContainer(container.getId()); + LOG.info("Container Inspect After Restart: {}", + containerInspectResponse2.toString()); - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - LOG.info("Created container " + container.toString()); - assertThat(container.id, not(isEmptyString())); - dockerClient.startContainer(container.id); - tmpContainers.add(container.id); + String startTime2 = containerInspectResponse2.getState().startedAt; - LOG.info("Commiting container " + container.toString()); - String imageId = dockerClient.commit(new CommitConfig.Builder(container.id).build()); - tmpImgs.add(imageId); + assertThat(startTime, not(equalTo(startTime2))); - ImageInspectResponse imageInspectResponse = dockerClient.inspectImage(imageId); - LOG.info("Image Inspect: " + imageInspectResponse.toString()); + assertThat(containerInspectResponse.getState().running, + is(equalTo(true))); - assertThat(imageInspectResponse, hasField("container", startsWith(container.id))); - assertThat(imageInspectResponse.containerConfig.getImage(), equalTo("busybox")); + dockerClient.kill(container.getId()); + } - ImageInspectResponse busyboxImg = dockerClient.inspectImage("busybox"); + @Test + public void removeContainer() throws DockerException { - assertThat(imageInspectResponse.parent, equalTo(busyboxImg.id)); - } + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(new String[] { "true" }); - @Test - public void testRemoveImage() throws DockerException { + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + dockerClient.startContainer(container.getId()); + dockerClient.waitContainer(container.getId()); + tmpContainers.add(container.getId()); - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[] {"touch", "/test"}); + LOG.info("Removing container: {}", container.getId()); + dockerClient.removeContainer(container.getId()); - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - LOG.info("Created container " + container.toString()); - assertThat(container.id, not(isEmptyString())); - dockerClient.startContainer(container.id); - tmpContainers.add(container.id); + List containers2 = dockerClient.listContainers(true); + Matcher matcher = not(hasItem(hasField("id", + startsWith(container.getId())))); + assertThat(containers2, matcher); + } - LOG.info("Commiting container " + container.toString()); - String imageId = dockerClient.commit(new CommitConfig.Builder(container.id).build()); - tmpImgs.add(imageId); + /* + * ################## ## IMAGES TESTS ## ################## + */ - LOG.info("Removing image" + imageId); - dockerClient.removeImage(imageId); + @Test + public void testPullImage() throws DockerException, IOException { - List containers = dockerClient.listContainers(true); - Matcher matcher = not(hasItem(hasField("id", startsWith(imageId)))); - assertThat(containers, matcher); - } + // This should be an image that is not used by other repositories already + // pulled down, preferably small in size. If tag is not used pull will + // download all images in that repository but tmpImgs will only + // deleted 'latest' image but not images with other tags + String testImage = "hackmann/empty"; + LOG.info("Removing image: {}", testImage); + dockerClient.removeImage(testImage); - /* - * - * ################ - * ## MISC TESTS ## - * ################ - */ + Info info = dockerClient.info(); + LOG.info("Client info: {}", info.toString()); - @Test - public void testRunShlex() throws DockerException { - - String[] commands = new String[] { - "true", - "echo \"The Young Descendant of Tepes & Septette for the Dead Princess\"", - "echo -n 'The Young Descendant of Tepes & Septette for the Dead Princess'", - "/bin/sh -c echo Hello World", - "/bin/sh -c echo 'Hello World'", - "echo 'Night of Nights'", - "true && echo 'Night of Nights'" - }; - - for (String command : commands) { - LOG.info("Running command [" + command + "]"); - - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd( commands ); - - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - dockerClient.startContainer(container.id); - tmpContainers.add(container.id); - int exitcode = dockerClient.waitContainer(container.id); - assertThat(exitcode, equalTo(0)); - } - } + int imgCount = info.getImages(); + LOG.info("Pulling image: {}", testImage); - @Test - public void testNgixDockerfileBuilder() throws DockerException, IOException { - File baseDir = new File(Thread.currentThread().getContextClassLoader().getResource("nginx").getFile()); + tmpImgs.add(testImage); + ClientResponse response = dockerClient.pull(testImage); - ClientResponse response = dockerClient.build(baseDir); + assertThat(logResponseStream(response), containsString("Download complete")); - StringWriter logwriter = new StringWriter(); + info = dockerClient.info(); + LOG.info("Client info after pull, {}", info.toString()); - try { - LineIterator itr = IOUtils.lineIterator(response.getEntityInputStream(), "UTF-8"); - while (itr.hasNext()) { - String line = itr.next(); - logwriter.write(line + "\n"); - LOG.info(line); - } - } finally { - IOUtils.closeQuietly(response.getEntityInputStream()); - } + // TODO: imgCount should differ (maybe a docker bug?) + assertThat(imgCount, lessThanOrEqualTo(info.getImages())); - String fullLog = logwriter.toString(); - assertThat(fullLog, containsString("Successfully built")); + ImageInspectResponse imageInspectResponse = dockerClient + .inspectImage(testImage); + LOG.info("Image Inspect: {}", imageInspectResponse.toString()); + assertThat(imageInspectResponse, notNullValue()); + } - String imageId = StringUtils.substringAfterLast(fullLog, "Successfully built ").trim(); + @Test + public void commitImage() throws DockerException { - ImageInspectResponse imageInspectResponse = dockerClient.inspectImage(imageId); - assertThat(imageInspectResponse, not(nullValue())); - LOG.info("Image Inspect:" + imageInspectResponse.toString()); - tmpImgs.add(imageInspectResponse.id); + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(new String[] { "touch", "/test" }); - assertThat(imageInspectResponse.author, equalTo("Guillaume J. Charmes \"guillaume@dotcloud.com\"")); - } + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainer(container.getId()); + tmpContainers.add(container.getId()); - @Test - public void testDockerBuilderAddFile() throws DockerException, IOException { - File baseDir = new File(Thread.currentThread().getContextClassLoader().getResource("testAddFile").getFile()); - dockerfileBuild(baseDir, "Successfully executed testrun.sh"); - } + LOG.info("Commiting container: {}", container.toString()); + String imageId = dockerClient + .commit(new CommitConfig(container.getId())); + tmpImgs.add(imageId); - @Test - public void testDockerBuilderAddFolder() throws DockerException, IOException { - File baseDir = new File(Thread.currentThread().getContextClassLoader().getResource("testAddFolder").getFile()); - dockerfileBuild(baseDir, "Successfully executed testAddFolder.sh"); - } + ImageInspectResponse imageInspectResponse = dockerClient + .inspectImage(imageId); + LOG.info("Image Inspect: {}", imageInspectResponse.toString()); + + assertThat(imageInspectResponse, + hasField("container", startsWith(container.getId()))); + assertThat(imageInspectResponse.getContainerConfig().getImage(), + equalTo("busybox")); + + ImageInspectResponse busyboxImg = dockerClient.inspectImage("busybox"); + + assertThat(imageInspectResponse.getParent(), + equalTo(busyboxImg.getId())); + } + + @Test + public void testRemoveImage() throws DockerException, InterruptedException { + + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(new String[] { "touch", "/test" }); + + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainer(container.getId()); + tmpContainers.add(container.getId()); + + LOG.info("Commiting container {}", container.toString()); + String imageId = dockerClient + .commit(new CommitConfig(container.getId())); + tmpImgs.add(imageId); + + dockerClient.stopContainer(container.getId()); + dockerClient.kill(container.getId()); + dockerClient.removeContainer(container.getId()); + + tmpContainers.remove(container.getId()); + LOG.info("Removing image: {}", imageId); + dockerClient.removeImage(imageId); + + List containers = dockerClient.listContainers(true); + Matcher matcher = not(hasItem(hasField("id", startsWith(imageId)))); + assertThat(containers, matcher); + } + + @Test + public void testTagImage() throws DockerException, InterruptedException { + String tag = String.valueOf(RandomUtils.nextInt(Integer.MAX_VALUE)); + + Integer result = dockerClient.tag("busybox:latest", "docker-java/busybox", tag, false); + assertThat(result, equalTo(Integer.valueOf(201))); + + dockerClient.removeImage("docker-java/busybox:" + tag); + } + + /* + * + * ################ ## MISC TESTS ## ################ + */ + + @Test + public void testRunShlex() throws DockerException { + + String[] commands = new String[] { + "true", + "echo \"The Young Descendant of Tepes & Septette for the Dead Princess\"", + "echo -n 'The Young Descendant of Tepes & Septette for the Dead Princess'", + "/bin/sh -c echo Hello World", "/bin/sh -c echo 'Hello World'", + "echo 'Night of Nights'", "true && echo 'Night of Nights'" }; + + for (String command : commands) { + LOG.info("Running command: [{}]", command); + + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(commands); + + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + dockerClient.startContainer(container.getId()); + tmpContainers.add(container.getId()); + int exitcode = dockerClient.waitContainer(container.getId()); + assertThat(exitcode, equalTo(0)); + } + } + + @Test + public void testNginxDockerfileBuilder() throws DockerException, + IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("nginx").getFile()); + + ClientResponse response = dockerClient.build(baseDir); + + StringWriter logwriter = new StringWriter(); + + try { + LineIterator itr = IOUtils.lineIterator( + response.getEntityInputStream(), "UTF-8"); + while (itr.hasNext()) { + String line = itr.next(); + logwriter.write(line + "\n"); + LOG.info(line); + } + } finally { + IOUtils.closeQuietly(response.getEntityInputStream()); + } + + String fullLog = logwriter.toString(); + assertThat(fullLog, containsString("Successfully built")); + + String imageId = StringUtils.substringBetween(fullLog, + "Successfully built ", "\\n\"}").trim(); + + ImageInspectResponse imageInspectResponse = dockerClient + .inspectImage(imageId); + assertThat(imageInspectResponse, not(nullValue())); + LOG.info("Image Inspect: {}", imageInspectResponse.toString()); + tmpImgs.add(imageInspectResponse.getId()); + + assertThat(imageInspectResponse.getAuthor(), + equalTo("Guillaume J. Charmes \"guillaume@dotcloud.com\"")); + } + + @Test + public void testDockerBuilderAddUrl() throws DockerException, IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("testAddUrl").getFile()); + dockerfileBuild(baseDir, "docker.io"); + } @Test - public void testNetCatDockerfileBuilder() throws DockerException, IOException, InterruptedException { - File baseDir = new File(Thread.currentThread().getContextClassLoader().getResource("netcat").getFile()); - - ClientResponse response = dockerClient.build(baseDir); - - StringWriter logwriter = new StringWriter(); - - try { - LineIterator itr = IOUtils.lineIterator(response.getEntityInputStream(), "UTF-8"); - while (itr.hasNext()) { - String line = itr.next(); - logwriter.write(line + "\n"); - LOG.info(line); - } - } finally { - IOUtils.closeQuietly(response.getEntityInputStream()); - } - - String fullLog = logwriter.toString(); - assertThat(fullLog, containsString("Successfully built")); - - String imageId = StringUtils.substringAfterLast(fullLog, "Successfully built ").trim(); - - ImageInspectResponse imageInspectResponse = dockerClient.inspectImage(imageId); - assertThat(imageInspectResponse, not(nullValue())); - LOG.info("Image Inspect:" + imageInspectResponse.toString()); - tmpImgs.add(imageInspectResponse.id); - - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage(imageInspectResponse.id); - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - assertThat(container.id, not(isEmptyString())); - dockerClient.startContainer(container.id); - tmpContainers.add(container.id); - - ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container.id); - - assertThat(containerInspectResponse.id, notNullValue()); - assertThat(containerInspectResponse.networkSettings.portMapping, notNullValue()); - int port = Integer.valueOf(containerInspectResponse.networkSettings.portMapping.get("Tcp").get("6900")); - - - LOG.info("Checking port {} is open", port); - assertThat(available(port), is(false)); - - dockerClient.stopContainer(container.id, 0); - - LOG.info("Checking port {} is closed", port); - assertThat(available(port), is(true)); - + public void testDockerBuilderAddFileInSubfolder() throws DockerException, IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("testAddFileInSubfolder").getFile()); + dockerfileBuild(baseDir, "Successfully executed testrun.sh"); } - - // UTIL - - /** - * Checks to see if a specific port is available. - * - * @param port the port to check for availability - */ - public static boolean available(int port) { - if (port < 1100 || port > 60000) { - throw new IllegalArgumentException("Invalid start port: " + port); - } - - ServerSocket ss = null; - DatagramSocket ds = null; - try { - ss = new ServerSocket(port); - ss.setReuseAddress(true); - ds = new DatagramSocket(port); - ds.setReuseAddress(true); - return true; - } catch (IOException e) { - } finally { - if (ds != null) { - ds.close(); - } - - if (ss != null) { - try { - ss.close(); - } catch (IOException e) { - /* should not be thrown */ - } - } - } - - return false; - } - - private void dockerfileBuild(File baseDir, String expectedText) throws DockerException, IOException { - - //Build image - ClientResponse response = dockerClient.build(baseDir); - - StringWriter logwriter = new StringWriter(); - - try { - LineIterator itr = IOUtils.lineIterator(response.getEntityInputStream(), "UTF-8"); - while (itr.hasNext()) { - String line = itr.next(); - logwriter.write(line + "\n"); - LOG.info(line); - } - } finally { - IOUtils.closeQuietly(response.getEntityInputStream()); - } - - String fullLog = logwriter.toString(); - assertThat(fullLog, containsString("Successfully built")); - - String imageId = StringUtils.substringAfterLast(fullLog, "Successfully built ").trim(); - - //Create container based on image - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage(imageId); - ContainerCreateResponse container = dockerClient.createContainer(containerConfig); - LOG.info("Created container " + container.toString()); - assertThat(container.id, not(isEmptyString())); - - dockerClient.startContainer(container.id); - dockerClient.waitContainer(container.id); - - tmpContainers.add(container.id); - - //Log container - ClientResponse logResponse = dockerClient.logContainer(container.id); - - StringWriter logwriter2 = new StringWriter(); - - try { - LineIterator itr = IOUtils.lineIterator(logResponse.getEntityInputStream(), "UTF-8"); - while (itr.hasNext()) { - String line = itr.next(); - logwriter2.write(line + (itr.hasNext() ? "\n" : "")); - LOG.info(line); - } - } finally { - IOUtils.closeQuietly(logResponse.getEntityInputStream()); - } - - assertThat(logwriter2.toString(), equalTo(expectedText)); - } + @Test + public void testDockerBuilderAddFolder() throws DockerException, + IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("testAddFolder").getFile()); + dockerfileBuild(baseDir, "Successfully executed testAddFolder.sh"); + } + + @Test + public void testNetCatDockerfileBuilder() throws DockerException, + IOException, InterruptedException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("netcat").getFile()); + + ClientResponse response = dockerClient.build(baseDir); + + StringWriter logwriter = new StringWriter(); + + try { + LineIterator itr = IOUtils.lineIterator( + response.getEntityInputStream(), "UTF-8"); + while (itr.hasNext()) { + String line = itr.next(); + logwriter.write(line + "\n"); + LOG.info(line); + } + } finally { + IOUtils.closeQuietly(response.getEntityInputStream()); + } + + String fullLog = logwriter.toString(); + assertThat(fullLog, containsString("Successfully built")); + + String imageId = StringUtils.substringBetween(fullLog, + "Successfully built ", "\\n\"}").trim(); + + ImageInspectResponse imageInspectResponse = dockerClient + .inspectImage(imageId); + assertThat(imageInspectResponse, not(nullValue())); + LOG.info("Image Inspect: {}", imageInspectResponse.toString()); + tmpImgs.add(imageInspectResponse.getId()); + + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage(imageInspectResponse.getId()); + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainer(container.getId()); + tmpContainers.add(container.getId()); + + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainer(container.getId()); + + assertThat(containerInspectResponse.getId(), notNullValue()); + assertThat(containerInspectResponse.getNetworkSettings().ports, + notNullValue()); + + // No use as such if not running on the server + for (String portstr : containerInspectResponse.getNetworkSettings().ports + .getAllPorts().keySet()) { + + Ports.Port p = containerInspectResponse.getNetworkSettings().ports + .getAllPorts().get(portstr); + int port = Integer.valueOf(p.getHostPort()); + LOG.info("Checking port {} is open", port); + assertThat(available(port), is(false)); + } + dockerClient.stopContainer(container.getId(), 0); + + } + + // UTIL + + /** + * Checks to see if a specific port is available. + * + * @param port + * the port to check for availability + */ + public static boolean available(int port) { + if (port < 1100 || port > 60000) { + throw new IllegalArgumentException("Invalid start port: " + port); + } + + ServerSocket ss = null; + DatagramSocket ds = null; + try { + ss = new ServerSocket(port); + ss.setReuseAddress(true); + ds = new DatagramSocket(port); + ds.setReuseAddress(true); + return true; + } catch (IOException e) { + } finally { + if (ds != null) { + ds.close(); + } + + if (ss != null) { + try { + ss.close(); + } catch (IOException e) { + /* should not be thrown */ + } + } + } + + return false; + } + + private String dockerfileBuild(File baseDir, String expectedText) + throws DockerException, IOException { + + // Build image + ClientResponse response = dockerClient.build(baseDir); + + StringWriter logwriter = new StringWriter(); + + try { + LineIterator itr = IOUtils.lineIterator( + response.getEntityInputStream(), "UTF-8"); + while (itr.hasNext()) { + String line = itr.next(); + logwriter.write(line + "\n"); + LOG.info(line); + } + } finally { + IOUtils.closeQuietly(response.getEntityInputStream()); + } + + String fullLog = logwriter.toString(); + assertThat(fullLog, containsString("Successfully built")); + + String imageId = StringUtils.substringBetween(fullLog, + "Successfully built ", "\\n\"}").trim(); + + // Create container based on image + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage(imageId); + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + + dockerClient.startContainer(container.getId()); + dockerClient.waitContainer(container.getId()); + + tmpContainers.add(container.getId()); + + // Log container + ClientResponse logResponse = dockerClient.logContainer(container + .getId()); + + assertThat(logResponseStream(logResponse), containsString(expectedText)); + + return container.getId(); + } } \ No newline at end of file diff --git a/src/test/java/com/kpelykh/docker/client/test/DockerPushTest.java b/src/test/java/com/kpelykh/docker/client/test/DockerPushTest.java new file mode 100644 index 00000000..7e6d88a9 --- /dev/null +++ b/src/test/java/com/kpelykh/docker/client/test/DockerPushTest.java @@ -0,0 +1,86 @@ +package com.kpelykh.docker.client.test; + + +import com.kpelykh.docker.client.DockerException; +import com.kpelykh.docker.client.model.CommitConfig; +import com.kpelykh.docker.client.model.ContainerConfig; +import com.kpelykh.docker.client.model.ContainerCreateResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.ITestResult; +import org.testng.annotations.*; + +import java.lang.reflect.Method; + +import static com.kpelykh.docker.client.DockerClient.asString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +// delete here : https://index.docker.io/u/alexec/busybox/delete/ +public class DockerPushTest extends AbstractDockerClientTest { + + public static final Logger LOG = LoggerFactory + .getLogger(DockerPushTest.class); + + String username; + + @BeforeTest + public void beforeTest() throws DockerException { + super.beforeTest(); + username = dockerClient.authConfig().getUsername(); + } + @AfterTest + public void afterTest() { + super.afterTest(); + } + + @BeforeMethod + public void beforeMethod(Method method) { + super.beforeMethod(method); + } + + @AfterMethod + public void afterMethod(ITestResult result) { + super.afterMethod(result); + } + + @Test + public void testPushLatest() throws Exception { + + + ContainerConfig containerConfig = new ContainerConfig(); + containerConfig.setImage("busybox"); + containerConfig.setCmd(new String[] { "true" }); + + ContainerCreateResponse container = dockerClient + .createContainer(containerConfig); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + tmpContainers.add(container.getId()); + + LOG.info("Commiting container: {}", container.toString()); + CommitConfig commitConfig = new CommitConfig(container.getId()); + + commitConfig.setRepo(username + "/busybox"); + + String imageId = dockerClient.commit(commitConfig); + + logResponseStream(dockerClient.push(username + "/busybox")); + + dockerClient.removeImage(imageId); + + assertThat(asString(dockerClient.pull(username + "/busybox")), not(containsString("404"))); + } + + @Test + public void testNotExistentImage() throws Exception { + + assertThat(logResponseStream(dockerClient.push(username + "/xxx")), containsString("error")); + } + + +} + diff --git a/src/test/resources/testAddFile/Dockerfile b/src/test/resources/testAddFile/Dockerfile index 6efbf091..2900a5e7 100644 --- a/src/test/resources/testAddFile/Dockerfile +++ b/src/test/resources/testAddFile/Dockerfile @@ -2,8 +2,8 @@ FROM ubuntu # Copy testrun.sh files into the container -add ./testrun.sh /tmp/ +ADD ./testrun.sh /tmp/ -run cp /tmp/testrun.sh /usr/local/bin/ && chmod +x /usr/local/bin/testrun.sh +RUN cp /tmp/testrun.sh /usr/local/bin/ && chmod +x /usr/local/bin/testrun.sh CMD ["testrun.sh"] diff --git a/src/test/resources/testAddFileInSubfolder/Dockerfile b/src/test/resources/testAddFileInSubfolder/Dockerfile new file mode 100644 index 00000000..41d8f437 --- /dev/null +++ b/src/test/resources/testAddFileInSubfolder/Dockerfile @@ -0,0 +1,9 @@ +FROM ubuntu + +# Copy testrun.sh files into the container + +ADD ./files/testrun.sh /tmp/ + +RUN cp /tmp/testrun.sh /usr/local/bin/ && chmod +x /usr/local/bin/testrun.sh + +CMD ["testrun.sh"] diff --git a/src/test/resources/testAddFileInSubfolder/files/testrun.sh b/src/test/resources/testAddFileInSubfolder/files/testrun.sh new file mode 100755 index 00000000..80b468e7 --- /dev/null +++ b/src/test/resources/testAddFileInSubfolder/files/testrun.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Successfully executed testrun.sh" diff --git a/src/test/resources/testAddFolder/Dockerfile b/src/test/resources/testAddFolder/Dockerfile index 73173ad4..b2a8e2a1 100644 --- a/src/test/resources/testAddFolder/Dockerfile +++ b/src/test/resources/testAddFolder/Dockerfile @@ -2,7 +2,7 @@ FROM ubuntu # Copy testrun.sh files into the container -add . /src/ +ADD . /src/ run ls -la /src diff --git a/src/test/resources/testAddUrl/Dockerfile b/src/test/resources/testAddUrl/Dockerfile new file mode 100644 index 00000000..1d76926c --- /dev/null +++ b/src/test/resources/testAddUrl/Dockerfile @@ -0,0 +1,10 @@ +FROM ubuntu + +# Copy testrun.sh files into the container + +ADD http://www.docker.io /tmp/docker_home.html +ADD ./testrun.sh /tmp/ + +RUN cp /tmp/testrun.sh /usr/local/bin/ && chmod +x /usr/local/bin/testrun.sh + +CMD ["testrun.sh"] \ No newline at end of file diff --git a/src/test/resources/testAddUrl/testrun.sh b/src/test/resources/testAddUrl/testrun.sh new file mode 100755 index 00000000..8eb4630b --- /dev/null +++ b/src/test/resources/testAddUrl/testrun.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +cat /tmp/docker_home.html + diff --git a/src/test/resources/testImportImageFromTar/empty.tar b/src/test/resources/testImportImageFromTar/empty.tar new file mode 100644 index 00000000..b055b9c2 Binary files /dev/null and b/src/test/resources/testImportImageFromTar/empty.tar differ diff --git a/src/test/resources/testReadFile/Dockerfile b/src/test/resources/testReadFile/Dockerfile new file mode 100644 index 00000000..3dfe89f9 --- /dev/null +++ b/src/test/resources/testReadFile/Dockerfile @@ -0,0 +1,9 @@ +FROM ubuntu + +# Copy testrun.sh files into the container + +ADD ./testrun.sh /tmp/ +ADD ./oldFile.txt / +RUN cp /tmp/testrun.sh /usr/local/bin/ && chmod +x /usr/local/bin/testrun.sh + +CMD ["testrun.sh"] diff --git a/src/test/resources/testReadFile/oldFile.txt b/src/test/resources/testReadFile/oldFile.txt new file mode 100644 index 00000000..ac1acee1 --- /dev/null +++ b/src/test/resources/testReadFile/oldFile.txt @@ -0,0 +1 @@ +Old File \ No newline at end of file diff --git a/src/test/resources/testReadFile/testrun.sh b/src/test/resources/testReadFile/testrun.sh new file mode 100755 index 00000000..d8b9508d --- /dev/null +++ b/src/test/resources/testReadFile/testrun.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +echo "Hello Word" > hello.txt +echo "hello.txt Created"