From 19e1cce0a826a67511b8da4a256a7adb60e755d1 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 11 Jun 2014 20:24:11 +0200 Subject: [PATCH 001/452] Move to https://github.com/docker-java/docker-java --- pom.xml | 691 +++++++++++++++++++++++++++++++------------------------- 1 file changed, 389 insertions(+), 302 deletions(-) diff --git a/pom.xml b/pom.xml index 3de239d1..11d1e5a4 100644 --- a/pom.xml +++ b/pom.xml @@ -1,305 +1,392 @@ - 4.0.0 - - - org.sonatype.oss - oss-parent - 7 - - - com.kpelykh - docker-java - 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 - - 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 - 5.12.1 - 1.3 - 1.6 - 2.3.3 - - - 2.2 - 2.3.1 - 2.3.1 - 2.8.1 - 2.5.1 - 1.7 - - - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - ${jackson-jaxrs.version} - - - com.sun.jersey - jersey-core - ${jersey.version} - - - com.sun.jersey - jersey-client - ${jersey.version} - - - - com.sun.jersey.contribs - jersey-multipart - ${jersey.version} - - - com.sun.jersey.contribs - jersey-apache-client4 - ${jersey-apache-client4.version} - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - - org.apache.commons - commons-compress - ${commons-compress.version} - - - commons-lang - commons-lang - ${commons-lang.version} - - - commons-io - commons-io - ${commons-io.version} - - - - com.github.jnr - jnr-unixsocket - ${jnr.unixsocket.version} - - - - org.slf4j - slf4j-api - ${slf4j-api.version} - - - - org.slf4j - jul-to-slf4j - ${slf4j-api.version} - - - - - ch.qos.logback - logback-core - ${version.logback} - test - - - - ch.qos.logback - logback-classic - ${version.logback} - test - - - - org.testng - testng - ${version.testng} - test - - - - org.hamcrest - hamcrest-library - ${hamcrest.library.version} - test - - - - com.googlecode.lambdaj - lambdaj - ${lambdaj.version} - test - - - org.hamcrest - hamcrest-all - - - - - - org.testinfected.hamcrest-matchers - jpa-matchers - ${hamcrest.jpa-matchers} - test - - - - - - com.github.jnr - jffi - 1.2.7 - - - com.github.jnr - jffi - native - 1.2.7 - - - - - - - - - - - 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 - - - - ******************************************************************* - ******************************************************************* - [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} - ******************************************************************* - ******************************************************************* - - - - - - - - - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + + + + + + + com.github.docker-java + docker-java + jar + 0.8.2-SNAPSHOT + + docker-java + https://github.com/docker-java/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:docker-java/docker-java.git + git@github.com:docker-java/docker-java.git + scm:git:git@github.com:docker-java/docker-java.git + + + + + kpelykh + Konstantin Pelykh + kpelykh@gmail.com + + + + + true + + UTF-8 + true + false + 1.6 + 1.6 + + 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 + 5.12.1 + 1.3 + 1.6 + 2.3.3 + + + 2.2 + 2.3.1 + 2.3.1 + 2.8.1 + 2.5.1 + 1.7 + + + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-jaxrs.version} + + + com.sun.jersey + jersey-core + ${jersey.version} + + + com.sun.jersey + jersey-client + ${jersey.version} + + + + com.sun.jersey.contribs + jersey-multipart + ${jersey.version} + + + com.sun.jersey.contribs + jersey-apache-client4 + ${jersey-apache-client4.version} + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + + org.apache.commons + commons-compress + ${commons-compress.version} + + + commons-lang + commons-lang + ${commons-lang.version} + + + commons-io + commons-io + ${commons-io.version} + + + + com.github.jnr + jnr-unixsocket + ${jnr.unixsocket.version} + + + + org.slf4j + slf4j-api + ${slf4j-api.version} + + + + org.slf4j + jul-to-slf4j + ${slf4j-api.version} + + + + + ch.qos.logback + logback-core + ${version.logback} + test + + + + ch.qos.logback + logback-classic + ${version.logback} + test + + + + org.testng + testng + ${version.testng} + test + + + + org.hamcrest + hamcrest-library + ${hamcrest.library.version} + test + + + + com.googlecode.lambdaj + lambdaj + ${lambdaj.version} + test + + + org.hamcrest + hamcrest-all + + + + + + org.testinfected.hamcrest-matchers + jpa-matchers + ${hamcrest.jpa-matchers} + test + + + + + + com.github.jnr + jffi + 1.2.7 + + + com.github.jnr + jffi + native + 1.2.7 + + + + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + + + + + 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 + + + + ******************************************************************* + ******************************************************************* + [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.sonatype.plugins + nexus-staging-maven-plugin + 1.6.2 + true + + ossrh + https://oss.sonatype.org/ + true + + + + + org.apache.maven.plugins + maven-release-plugin + 2.5 + + true + false + release + deploy nexus-staging:release + + + + + + + + + + + release + + + + org.apache.maven.plugins + maven-gpg-plugin + + + sign-artifacts + verify + + sign + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + attach-javadocs + + jar + + + + + + + + From f3c9cf50c4e35feef6510650304b61e1d4fc1e5f Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 11 Jun 2014 20:42:38 +0200 Subject: [PATCH 002/452] [maven-release-plugin] prepare release docker-java-0.8.2 --- pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 11d1e5a4..25cb980e 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - + 4.0.0 @@ -11,7 +10,7 @@ com.github.docker-java docker-java jar - 0.8.2-SNAPSHOT + 0.8.2 docker-java https://github.com/docker-java/docker-java @@ -29,7 +28,8 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - + docker-java-0.8.2 + From 3ece2352277cfab1d9e090a6a9cb61bddb34dd26 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 11 Jun 2014 20:42:52 +0200 Subject: [PATCH 003/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 25cb980e..e67c83dd 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.8.2 + 0.8.3-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.8.2 + HEAD From dbe39e6a88de62c7478f5cce98cd46235937e45d Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 12 Jun 2014 20:18:59 +0200 Subject: [PATCH 004/452] POM minor fix --- pom.xml | 70 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/pom.xml b/pom.xml index e67c83dd..ced0c65a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,11 +1,12 @@ - + 4.0.0 - - - - - + + org.sonatype.oss + oss-parent + 9 + com.github.docker-java docker-java @@ -28,8 +29,8 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD - + HEAD + @@ -308,34 +309,33 @@ - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.2 - true - - ossrh - https://oss.sonatype.org/ - true - - - - - org.apache.maven.plugins - maven-release-plugin - 2.5 - - true - false - release - deploy nexus-staging:release - - - - + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.2 + true + + ossrh + https://oss.sonatype.org/ + true + + + + + org.apache.maven.plugins + maven-release-plugin + 2.5 + + true + false + release + deploy nexus-staging:release + + + @@ -370,7 +370,7 @@ - + org.apache.maven.plugins maven-javadoc-plugin From fc00c8b9348302ff0ac8f272c50d15d72bc68329 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 12 Jun 2014 20:23:59 +0200 Subject: [PATCH 005/452] Fix README --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 24cfc9ad..9d6f7ebf 100644 --- a/README.md +++ b/README.md @@ -45,11 +45,12 @@ Run build with tests: ## Docker-Java maven dependency: - com.kpelykh + com.github.docker-java docker-java - 0.8.1 + 0.8.2 +Latest SNAPSHOT is available from maven repo: https://oss.sonatype.org/content/groups/public ## Example code snippets: From e2ffbd6eb29586214a1f2a99e88bee796551a3f4 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 17 Jun 2014 11:26:24 +0200 Subject: [PATCH 006/452] Major refactoring and Docker 1.0 compatibility --- pom.xml | 9 +- .../dockerjava}/client/Config.java | 2 +- .../dockerjava/client/DockerClient.java | 352 +++++++ .../dockerjava}/client/DockerException.java | 4 +- .../dockerjava}/client/NotFoundException.java | 2 +- .../client/command/AbstrAuthCfgDockerCmd.java | 32 + .../client/command/AbstrDockerCmd.java | 23 + .../dockerjava/client/command/AuthCmd.java | 37 + .../client/command/BuildImgCmd.java | 151 +++ .../dockerjava/client/command/CommitCmd.java | 104 ++ .../client/command/ContainerDiffCmd.java | 57 ++ .../command/CopyFileFromContainerCmd.java | 68 ++ .../client/command/CreateContainerCmd.java | 100 ++ .../dockerjava/client/command/DockerCmd.java | 7 + .../client/command/ImportImageCmd.java | 86 ++ .../dockerjava/client/command/InfoCmd.java | 38 + .../client/command/InspectContainerCmd.java | 52 + .../client/command/InspectImageCmd.java | 53 + .../client/command/KillContainerCmd.java | 55 + .../client/command/ListContainersCmd.java | 82 ++ .../client/command/ListImagesCmd.java | 67 ++ .../client/command/LogContainerCmd.java | 102 ++ .../client/command/PullImageCmd.java | 79 ++ .../client/command/PushImageCmd.java | 56 + .../client/command/RemoveContainerCmd.java | 79 ++ .../client/command/RemoveImageCmd.java | 74 ++ .../client/command/RestartContainerCmd.java | 66 ++ .../client/command/SearchImagesCmd.java | 53 + .../client/command/StartContainerCmd.java | 107 ++ .../client/command/StopContainerCmd.java | 66 ++ .../client/command/TagImageCmd.java | 86 ++ .../client/command/TopContainerCmd.java | 65 ++ .../dockerjava/client/command/VersionCmd.java | 38 + .../client/command/WaitContainerCmd.java | 55 + .../dockerjava}/client/model/AuthConfig.java | 2 +- .../dockerjava}/client/model/ChangeLog.java | 2 +- .../client/model/CommitConfig.java | 14 +- .../dockerjava}/client/model/Container.java | 2 +- .../client/model/ContainerConfig.java | 8 +- .../client/model/ContainerCreateResponse.java | 2 +- .../model/ContainerInspectResponse.java | 14 +- .../client/model/ContainerTopResponse.java | 46 + .../dockerjava}/client/model/CopyConfig.java | 2 +- .../client/model/CreateContainerConfig.java | 271 +++++ .../client/model/DriverStatus.java | 2 +- .../dockerjava/client/model/HostConfig.java | 66 ++ .../dockerjava}/client/model/Image.java | 2 +- .../client/model/ImageCreateResponse.java | 2 +- .../client/model/ImageInspectResponse.java | 2 +- .../dockerjava}/client/model/Info.java | 5 +- .../dockerjava/client/model/LxcConf.java | 38 + .../dockerjava}/client/model/Port.java | 2 +- .../dockerjava}/client/model/Ports.java | 50 +- .../dockerjava}/client/model/SearchItem.java | 2 +- .../client/model/StartContainerConfig.java | 50 + .../dockerjava}/client/model/Version.java | 2 +- .../client/utils/CompressArchiveUtil.java | 2 +- .../client/utils/JsonClientFilter.java | 2 +- .../com/google/common/base/Preconditions.java | 443 -------- .../kpelykh/docker/client/DockerClient.java | 954 ------------------ .../docker/client/model/BoundHostVolumes.java | 92 -- .../docker/client/model/HostConfig.java | 180 ---- .../kpelykh/docker/client/model/IBuilder.java | 9 - .../client}/AbstractDockerClientTest.java | 63 +- .../dockerjava/client/DockerClientTest.java | 72 ++ .../client/command/AuthCmdTest.java} | 11 +- .../client/command/BuildImageCmdTest.java | 230 +++++ .../client/command/CommitCmdTest.java | 77 ++ .../client/command/ContainerDiffCmdTest.java | 70 ++ .../command/CreateContainerCmdTest.java | 65 ++ .../client/command/InfoCmdTest.java | 55 + .../client/command/KillContainerCmdTest.java | 77 ++ .../client/command/ListContainersCmdTest.java | 109 ++ .../client/command/ListImagesCmdTest.java | 66 ++ .../client/command/LogContainerCmdTest.java | 75 ++ .../client/command/PullImageCmdTest.java | 90 ++ .../client/command/PushImageCmdTest.java | 84 ++ .../command/RemoveContainerCmdTest.java | 76 ++ .../client/command/RemoveImageCmdTest.java | 85 ++ .../command/RestartContainerCmdTest.java | 79 ++ .../client/command/SearchImagesCmdTest.java | 61 ++ .../client/command/StartContainerCmdTest.java | 118 +++ .../client/command/StopContainerCmdTest.java | 76 ++ .../client/command/TagImageCmdTest.java | 68 ++ .../client/command/VersionCmdTest.java | 52 + .../client/command/WaitContainerCmdTest.java | 75 ++ .../docker/client/test/DockerClientTest.java | 824 --------------- .../docker/client/test/DockerPushTest.java | 86 -- src/test/resources/logback.xml | 4 +- 89 files changed, 4655 insertions(+), 2668 deletions(-) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/Config.java (97%) create mode 100644 src/main/java/com/github/dockerjava/client/DockerClient.java rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/DockerException.java (79%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/NotFoundException.java (86%) create mode 100644 src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/AuthCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/CommitCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/DockerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/InfoCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/PullImageCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/PushImageCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/TagImageCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/VersionCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/AuthConfig.java (96%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/ChangeLog.java (89%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/CommitConfig.java (83%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/Container.java (93%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/ContainerConfig.java (93%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/ContainerCreateResponse.java (90%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/ContainerInspectResponse.java (89%) create mode 100644 src/main/java/com/github/dockerjava/client/model/ContainerTopResponse.java rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/CopyConfig.java (96%) create mode 100644 src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/DriverStatus.java (89%) create mode 100644 src/main/java/com/github/dockerjava/client/model/HostConfig.java rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/Image.java (93%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/ImageCreateResponse.java (88%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/ImageInspectResponse.java (94%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/Info.java (92%) create mode 100644 src/main/java/com/github/dockerjava/client/model/LxcConf.java rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/Port.java (96%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/Ports.java (69%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/SearchItem.java (91%) create mode 100644 src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/model/Version.java (93%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/utils/CompressArchiveUtil.java (96%) rename src/main/java/com/{kpelykh/docker => github/dockerjava}/client/utils/JsonClientFilter.java (94%) delete mode 100644 src/main/java/com/google/common/base/Preconditions.java delete mode 100644 src/main/java/com/kpelykh/docker/client/DockerClient.java delete mode 100644 src/main/java/com/kpelykh/docker/client/model/BoundHostVolumes.java delete mode 100644 src/main/java/com/kpelykh/docker/client/model/HostConfig.java delete mode 100644 src/main/java/com/kpelykh/docker/client/model/IBuilder.java rename src/test/java/com/{kpelykh/docker/client/test => github/dockerjava/client}/AbstractDockerClientTest.java (61%) create mode 100644 src/test/java/com/github/dockerjava/client/DockerClientTest.java rename src/test/java/com/{kpelykh/docker/client/test/DockerClientAuthTest.java => github/dockerjava/client/command/AuthCmdTest.java} (77%) create mode 100644 src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/SearchImagesCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/VersionCmdTest.java create mode 100644 src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java delete mode 100644 src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java delete mode 100644 src/test/java/com/kpelykh/docker/client/test/DockerPushTest.java diff --git a/pom.xml b/pom.xml index ced0c65a..d0f8365e 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ com.github.docker-java docker-java jar - 0.8.3-SNAPSHOT + 0.9.0-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -63,6 +63,7 @@ 1.7.5 1.3.9 0.3 + 11.0.1 1.0.1 @@ -147,6 +148,12 @@ jul-to-slf4j ${slf4j-api.version} + + + com.google.guava + guava + ${guava.version} + diff --git a/src/main/java/com/kpelykh/docker/client/Config.java b/src/main/java/com/github/dockerjava/client/Config.java similarity index 97% rename from src/main/java/com/kpelykh/docker/client/Config.java rename to src/main/java/com/github/dockerjava/client/Config.java index f6e59d76..e007859e 100644 --- a/src/main/java/com/kpelykh/docker/client/Config.java +++ b/src/main/java/com/github/dockerjava/client/Config.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client; +package com.github.dockerjava.client; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java new file mode 100644 index 00000000..b4779866 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -0,0 +1,352 @@ +package com.github.dockerjava.client; + +import static org.apache.commons.io.IOUtils.closeQuietly; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URI; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.io.LineIterator; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.command.AbstrDockerCmd; +import com.github.dockerjava.client.command.AuthCmd; +import com.github.dockerjava.client.command.BuildImgCmd; +import com.github.dockerjava.client.command.CommitCmd; +import com.github.dockerjava.client.command.ContainerDiffCmd; +import com.github.dockerjava.client.command.CopyFileFromContainerCmd; +import com.github.dockerjava.client.command.CreateContainerCmd; +import com.github.dockerjava.client.command.ImportImageCmd; +import com.github.dockerjava.client.command.InfoCmd; +import com.github.dockerjava.client.command.InspectContainerCmd; +import com.github.dockerjava.client.command.InspectImageCmd; +import com.github.dockerjava.client.command.KillContainerCmd; +import com.github.dockerjava.client.command.ListContainersCmd; +import com.github.dockerjava.client.command.ListImagesCmd; +import com.github.dockerjava.client.command.LogContainerCmd; +import com.github.dockerjava.client.command.PullImageCmd; +import com.github.dockerjava.client.command.PushImageCmd; +import com.github.dockerjava.client.command.RemoveContainerCmd; +import com.github.dockerjava.client.command.RemoveImageCmd; +import com.github.dockerjava.client.command.RestartContainerCmd; +import com.github.dockerjava.client.command.SearchImagesCmd; +import com.github.dockerjava.client.command.StartContainerCmd; +import com.github.dockerjava.client.command.StopContainerCmd; +import com.github.dockerjava.client.command.TagImageCmd; +import com.github.dockerjava.client.command.TopContainerCmd; +import com.github.dockerjava.client.command.VersionCmd; +import com.github.dockerjava.client.command.WaitContainerCmd; +import com.github.dockerjava.client.model.AuthConfig; +import com.github.dockerjava.client.model.CreateContainerConfig; +import com.github.dockerjava.client.utils.JsonClientFilter; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.api.client.filter.LoggingFilter; +import com.sun.jersey.client.apache4.ApacheHttpClient4; +import com.sun.jersey.client.apache4.ApacheHttpClient4Handler; + +/** + * @author Konstantin Pelykh (kpelykh@gmail.com) + */ +public class DockerClient { + + private Client client; + private WebResource baseResource; + 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()); + + baseResource = client.resource(config.url + "/v" + config.version); + } + + 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); + } + + public RES_T execute(AbstrDockerCmd command) + throws DockerException { + return command.withBaseResource(baseResource).exec(); + } + + 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; + } + + /** + * * MISC API * + */ + + /** + * Authenticate with the server, useful for checking authentication. + */ + public AuthCmd authCmd() { + return new AuthCmd(authConfig()).withBaseResource(baseResource); + } + + public InfoCmd infoCmd() throws DockerException { + return new InfoCmd().withBaseResource(baseResource); + } + + public VersionCmd versionCmd() throws DockerException { + return new VersionCmd().withBaseResource(baseResource); + } + + /** + * * IMAGE API * + */ + + public PullImageCmd pullImageCmd(String repository) { + return new PullImageCmd(repository).withBaseResource(baseResource); + } + + public PushImageCmd pushImageCmd(String name) { + return new PushImageCmd(name).withAuthConfig(authConfig()) + .withBaseResource(baseResource); + } + +// public ClientResponse pushImage(String name) { +// return execute(pushImageCmd(name)); +// } + + public ImportImageCmd importImageCmd(String repository, + InputStream imageStream) { + return new ImportImageCmd(repository, imageStream) + .withBaseResource(baseResource); + } + +// public ImageCreateResponse importImage(String repository, +// InputStream imageStream) { +// return execute(importImageCmd(repository, imageStream)); +// } + + public SearchImagesCmd searchImagesCmd(String term) { + return new SearchImagesCmd(term).withBaseResource(baseResource); + } + +// public List searchImages(String term) { +// return execute(searchImagesCmd(term)); +// } + + public RemoveImageCmd removeImageCmd(String imageId) { + return new RemoveImageCmd(imageId).withBaseResource(baseResource); + } + +// /** +// * Remove an image, deleting any tags it might have. +// */ +// public void removeImage(String imageId) { +// execute(removeImageCmd(imageId)); +// } +// +// public void removeImages(List images) { +// Preconditions.checkNotNull(images, "List of images can't be null"); +// +// for (String imageId : images) { +// removeImage(imageId); +// } +// } + + public ListImagesCmd listImagesCmd() { + return new ListImagesCmd().withBaseResource(baseResource); + } + +// public List listImages() { +// return execute(listImagesCmd()); +// } + + public InspectImageCmd inspectImageCmd(String imageId) { + return new InspectImageCmd(imageId).withBaseResource(baseResource); + } + +// public ImageInspectResponse inspectImage(String imageId) { +// return execute(inspectImageCmd(imageId)); +// } + + /** + * * CONTAINER API * + */ + + public ListContainersCmd listContainersCmd() { + return new ListContainersCmd().withBaseResource(baseResource); + } + +// public List listContainers() { +// return execute(listContainersCmd()); +// } + + public CreateContainerCmd createContainerCmd(String image) { + return new CreateContainerCmd(new CreateContainerConfig()).withImage( + image).withBaseResource(baseResource); + } + + public StartContainerCmd startContainerCmd(String containerId) { + return new StartContainerCmd(containerId) + .withBaseResource(baseResource); + } + + public InspectContainerCmd inspectContainerCmd(String containerId) { + return new InspectContainerCmd(containerId) + .withBaseResource(baseResource); + } + + public RemoveContainerCmd removeContainerCmd(String containerId) { + return new RemoveContainerCmd(containerId) + .withBaseResource(baseResource); + } + + public WaitContainerCmd waitContainerCmd(String containerId) { + return new WaitContainerCmd(containerId).withBaseResource(baseResource); + } + + public LogContainerCmd logContainerCmd(String containerId) { + return new LogContainerCmd(containerId).withBaseResource(baseResource); + } + + public CopyFileFromContainerCmd copyFileFromContainerCmd( + String containerId, String resource) { + return new CopyFileFromContainerCmd(containerId, resource) + .withBaseResource(baseResource); + } + + public ContainerDiffCmd containerDiffCmd(String containerId) { + return new ContainerDiffCmd(containerId).withBaseResource(baseResource); + } + + public StopContainerCmd stopContainerCmd(String containerId) { + return new StopContainerCmd(containerId).withBaseResource(baseResource); + } + + public KillContainerCmd killContainerCmd(String containerId) { + return new KillContainerCmd(containerId).withBaseResource(baseResource); + } + + public RestartContainerCmd restartContainerCmd(String containerId) { + return new RestartContainerCmd(containerId) + .withBaseResource(baseResource); + } + + public CommitCmd commitCmd(String containerId) { + return new CommitCmd(containerId).withBaseResource(baseResource); + } + + public BuildImgCmd buildImageCmd(File dockerFolder) { + return new BuildImgCmd(dockerFolder).withBaseResource(baseResource); + } + + public TopContainerCmd topContainerCmd(String containerId) { + return new TopContainerCmd(containerId).withBaseResource(baseResource); + } + + public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { + return new TagImageCmd(imageId, repository, tag).withBaseResource(baseResource); + } + + + /** + * @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(); + } +} diff --git a/src/main/java/com/kpelykh/docker/client/DockerException.java b/src/main/java/com/github/dockerjava/client/DockerException.java similarity index 79% rename from src/main/java/com/kpelykh/docker/client/DockerException.java rename to src/main/java/com/github/dockerjava/client/DockerException.java index aa3df660..f0abbe97 100644 --- a/src/main/java/com/kpelykh/docker/client/DockerException.java +++ b/src/main/java/com/github/dockerjava/client/DockerException.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client; +package com.github.dockerjava.client; /** * @@ -6,7 +6,7 @@ * */ -public class DockerException extends Exception { +public class DockerException extends RuntimeException { public DockerException() { } diff --git a/src/main/java/com/kpelykh/docker/client/NotFoundException.java b/src/main/java/com/github/dockerjava/client/NotFoundException.java similarity index 86% rename from src/main/java/com/kpelykh/docker/client/NotFoundException.java rename to src/main/java/com/github/dockerjava/client/NotFoundException.java index 76569f7b..dba76e78 100644 --- a/src/main/java/com/kpelykh/docker/client/NotFoundException.java +++ b/src/main/java/com/github/dockerjava/client/NotFoundException.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client; +package com.github.dockerjava.client; /** * Indicates that the given entity does not exist. diff --git a/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java b/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java new file mode 100644 index 00000000..425df615 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java @@ -0,0 +1,32 @@ +package com.github.dockerjava.client.command; + +import java.io.IOException; + +import org.apache.commons.codec.binary.Base64; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.AuthConfig; +import com.google.common.base.Preconditions; + +public abstract class AbstrAuthCfgDockerCmd, RES_T> extends + AbstrDockerCmd { + + protected AuthConfig authConfig; + + @SuppressWarnings("unchecked") + public T withAuthConfig(AuthConfig authConfig) { + Preconditions.checkNotNull(authConfig, "authConfig was not specified"); + this.authConfig = authConfig; + return (T)this; + } + + protected String registryAuth() throws DockerException { + try { + return Base64.encodeBase64String(new ObjectMapper().writeValueAsString(authConfig).getBytes()); + } catch (IOException e) { + throw new DockerException(e); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java new file mode 100644 index 00000000..a10b2208 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java @@ -0,0 +1,23 @@ +package com.github.dockerjava.client.command; + +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.WebResource; + +public abstract class AbstrDockerCmd, RES_T> implements DockerCmd { + + protected WebResource baseResource; + + @SuppressWarnings("unchecked") + public T withBaseResource(WebResource baseResource) { + this.baseResource = baseResource; + return (T)this; + } + + abstract RES_T impl(); + + @Override + public RES_T exec() { + Preconditions.checkNotNull(baseResource, "baseResource was not specified"); + return impl(); + } +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/client/command/AuthCmd.java b/src/main/java/com/github/dockerjava/client/command/AuthCmd.java new file mode 100644 index 00000000..f5f7b7ed --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/AuthCmd.java @@ -0,0 +1,37 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.AuthConfig; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * + * Authenticate with the server, useful for checking authentication. + * + */ +public class AuthCmd extends AbstrAuthCfgDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(AuthCmd.class); + + public AuthCmd(AuthConfig authConfig) { + withAuthConfig(authConfig); + } + + protected Void impl() throws DockerException { + try { + WebResource webResource = baseResource.path("/auth"); + LOGGER.trace("POST: {}", webResource); + webResource.header("Content-Type", MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON).post(authConfig); + return null; + } catch (UniformInterfaceException e) { + throw new DockerException(e); + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java new file mode 100644 index 00000000..81754d26 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -0,0 +1,151 @@ +package com.github.dockerjava.client.command; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.utils.CompressArchiveUtil; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.core.util.MultivaluedMapImpl; + +/** + * + * Build an image from Dockerfile. + * + */ +public class BuildImgCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(BuildImgCmd.class); + + private File dockerFolder; + private String tag; + private boolean noCache= false; + + + public BuildImgCmd(File dockerFolder) { + Preconditions.checkNotNull(dockerFolder, "dockerFolder is null"); + this.dockerFolder = dockerFolder; + } + + public BuildImgCmd withTag(String tag) { + Preconditions.checkNotNull(tag, "Tag is null"); + this.tag = tag; + return this; + } + + public BuildImgCmd withNoCache(boolean noCache) { + this.noCache = noCache; + return this; + } + + protected ClientResponse impl() { + + Preconditions.checkArgument(dockerFolder.exists(), "Path %s doesn't exist", dockerFolder); + Preconditions.checkArgument(dockerFolder.isDirectory(), "Folder %s doesn't exist", dockerFolder); + Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(), "Dockerfile doesn't exist in " + dockerFolder); + + 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 = baseResource.path("/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); + } + } + + 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()); + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java new file mode 100644 index 00000000..3dc350ea --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java @@ -0,0 +1,104 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MultivaluedMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.client.model.CommitConfig; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.core.util.MultivaluedMapImpl; + + +/** + * + * Create a new image from a container's changes. Returns the new image ID. + * + */ +public class CommitCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(CommitCmd.class); + + private CommitConfig commitConfig; + + public CommitCmd(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.commitConfig = new CommitConfig(containerId); + } + + public CommitCmd withCommitConfig(CommitConfig commitConfig) { + checkCommitConfig(commitConfig); + this.commitConfig = commitConfig; + return this; + } + + public CommitCmd withRepo(String repo) { + Preconditions.checkNotNull(repo, "repo was not specified"); + this.commitConfig.setRepo(repo); + return this; + } + + public CommitCmd withTag(String tag) { + Preconditions.checkNotNull(tag, "tag was not specified"); + this.commitConfig.setTag(tag); + return this; + } + + public CommitCmd withMessage(String message) { + Preconditions.checkNotNull(message, "message was not specified"); + this.commitConfig.setMessage(message); + return this; + } + + public CommitCmd withAuthor(String author) { + Preconditions.checkNotNull(author, "author was not specified"); + this.commitConfig.setAuthor(author); + return this; + } + + public CommitCmd withRun(String run) { + Preconditions.checkNotNull(run, "run was not specified"); + this.commitConfig.setRun(run); + return this; + } + + + private void checkCommitConfig(CommitConfig commitConfig) { + Preconditions.checkNotNull(commitConfig, "CommitConfig was not specified"); + } + + protected String impl() throws DockerException { + checkCommitConfig(commitConfig); + + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("container", commitConfig.getContainerId()); + 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 = baseResource.path("/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.getContainerId())); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } catch (Exception e) { + throw new DockerException(e); + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java b/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java new file mode 100644 index 00000000..a0225bec --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java @@ -0,0 +1,57 @@ +package com.github.dockerjava.client.command; + +import java.util.List; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.client.model.ChangeLog; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.GenericType; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * Inspect changes on a container's filesystem + * + * @param containerId - Id of the container + * + */ +public class ContainerDiffCmd extends AbstrDockerCmd> { + + private static final Logger LOGGER = LoggerFactory.getLogger(ContainerDiffCmd.class); + + private String containerId; + + public ContainerDiffCmd(String containerId) { + withContainerId(containerId); + } + + public ContainerDiffCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + protected List impl() throws DockerException { + WebResource webResource = baseResource.path(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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java new file mode 100644 index 00000000..d9543418 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java @@ -0,0 +1,68 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.CopyConfig; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * + * Copy files or folders from a container. + * + */ +public class CopyFileFromContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(CopyFileFromContainerCmd.class); + + private String containerId, resource; + + public CopyFileFromContainerCmd(String containerId, String resource) { + withContainerId(containerId); + withResource(resource); + } + + public CopyFileFromContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + public CopyFileFromContainerCmd withResource(String resource) { + Preconditions.checkNotNull(resource, "resource was not specified"); + this.resource = resource; + return this; + } + + protected ClientResponse impl() throws DockerException { + CopyConfig copyConfig = new CopyConfig(); + copyConfig.setResource(resource); + + WebResource webResource = + baseResource.path(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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java new file mode 100644 index 00000000..d94ce153 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -0,0 +1,100 @@ +package com.github.dockerjava.client.command; + +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.CreateContainerConfig; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.core.util.MultivaluedMapImpl; + + +/** + * + * Creates a new container. + * + */ +public class CreateContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(CreateContainerCmd.class); + + private CreateContainerConfig containerCreateConfig; + private String name; + + public CreateContainerCmd(String image) { + this(new CreateContainerConfig()); + Preconditions.checkNotNull(image, "image was not specified"); + this.containerCreateConfig.withImage(image); + } + + public CreateContainerCmd(CreateContainerConfig config) { + Preconditions.checkNotNull(config, "config was not specified"); + this.containerCreateConfig = config; + } + + public CreateContainerCmd withImage(String image) { + Preconditions.checkNotNull(image, "image was not specified"); + this.containerCreateConfig.withImage(image); + return this; + } + + public CreateContainerCmd withCmd(String... cmd) { + Preconditions.checkNotNull(cmd, "cmd was not specified"); + this.containerCreateConfig.withCmd(cmd); + return this; + } + + public CreateContainerCmd withVolumes(String... volumes) { + Preconditions.checkNotNull(volumes, "volumes was not specified"); + + Map _volumes = new HashMap(); + for(String volume:volumes) { + _volumes.put(volume, ""); + } + + this.containerCreateConfig.withVolumes(_volumes); + return this; + } + + + public CreateContainerCmd withName(String name) { + Preconditions.checkNotNull(name, "name was not specified"); + this.name = name; + return this; + } + + protected ContainerCreateResponse impl() { + MultivaluedMap params = new MultivaluedMapImpl(); + if (name != null) { + params.add("name", name); + } + WebResource webResource = baseResource.path("/containers/create").queryParams(params); + + try { + LOGGER.trace("POST: {} ", webResource); + return webResource.accept(MediaType.APPLICATION_JSON) + .type(MediaType.APPLICATION_JSON) + .post(ContainerCreateResponse.class, containerCreateConfig); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 404) { + throw new NotFoundException(String.format("%s is an unrecognized image. Please pull the image first.", containerCreateConfig.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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/DockerCmd.java b/src/main/java/com/github/dockerjava/client/command/DockerCmd.java new file mode 100644 index 00000000..dd3d8759 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/DockerCmd.java @@ -0,0 +1,7 @@ +package com.github.dockerjava.client.command; + +public interface DockerCmd { + + public RES_T exec(); + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java b/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java new file mode 100644 index 00000000..4797110d --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java @@ -0,0 +1,86 @@ +package com.github.dockerjava.client.command; + +import java.io.InputStream; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ImageCreateResponse; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.core.util.MultivaluedMapImpl; + +/** + * Create an image by importing the given stream of a tar file. + */ +public class ImportImageCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(ImportImageCmd.class); + + private String repository, tag; + private InputStream imageStream; + + /** + * @param repository the repository to import to + * @param imageStream the InputStream of the tar file + */ + public ImportImageCmd(String repository, InputStream imageStream) { + withRepository(repository); + withImageStream(imageStream); + } + + /** + * @param repository the repository to import to + */ + public ImportImageCmd withRepository(String repository) { + Preconditions.checkNotNull(repository, "repository was not specified"); + this.repository = repository; + return this; + } + + /** + * @param imageStream the InputStream of the tar file + */ + public ImportImageCmd withImageStream(InputStream imageStream) { + Preconditions + .checkNotNull(imageStream, "imageStream was not specified"); + this.imageStream = imageStream; + return this; + } + + /** + * @param tag any tag for this image + */ + public ImportImageCmd withTag(String tag) { + Preconditions.checkNotNull(tag, "tag was not specified"); + this.tag = tag; + return this; + } + + protected ImageCreateResponse impl() { + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("repo", repository); + params.add("tag", tag); + params.add("fromSrc", "-"); + + WebResource webResource = baseResource.path("/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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/InfoCmd.java b/src/main/java/com/github/dockerjava/client/command/InfoCmd.java new file mode 100644 index 00000000..810718f0 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/InfoCmd.java @@ -0,0 +1,38 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.Info; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + + +/** + * + * + * + */ +public class InfoCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(InfoCmd.class); + + + protected Info impl() throws DockerException { + WebResource webResource = baseResource.path("/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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java new file mode 100644 index 00000000..ba6eedd5 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java @@ -0,0 +1,52 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.client.model.ContainerInspectResponse; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * + * + * + */ +public class InspectContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(InspectContainerCmd.class); + + private String containerId; + + public InspectContainerCmd(String containerId) { + withContainerId(containerId); + } + + public InspectContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + protected ContainerInspectResponse impl() throws DockerException { + WebResource webResource = baseResource.path(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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java new file mode 100644 index 00000000..23f6a775 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java @@ -0,0 +1,53 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.client.model.ImageInspectResponse; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + + +/** + * + * + * + */ +public class InspectImageCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(InspectImageCmd.class); + + private String imageId; + + public InspectImageCmd(String imageId) { + withImageId(imageId); + } + + public InspectImageCmd withImageId(String imageId) { + Preconditions.checkNotNull(imageId, "imageId was not specified"); + this.imageId = imageId; + return this; + } + + protected ImageInspectResponse impl() { + WebResource webResource = baseResource.path(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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java new file mode 100644 index 00000000..75874559 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java @@ -0,0 +1,55 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * + * + * + */ +public class KillContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(KillContainerCmd.class); + + private String containerId; + + public KillContainerCmd(String containerId) { + withContainerId(containerId); + } + + public KillContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + protected Void impl() throws DockerException { + WebResource webResource = baseResource.path(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); + } + } + + return null; + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java b/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java new file mode 100644 index 00000000..9724fa15 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java @@ -0,0 +1,82 @@ +package com.github.dockerjava.client.command; + +import java.util.List; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.model.Container; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.GenericType; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.core.util.MultivaluedMapImpl; + + +/** + * List containers + * + * @param showAll - true or false, Show all containers. Only running containers are shown by default. + * @param showSize - true or false, Show the containers sizes. This is false by default. + * @param limit - Show `limit` last created containers, include non-running ones. There is no limit by default. + * @param sinceId - Show only containers created since Id, include non-running ones. + * @param beforeId - Show only containers created before Id, include non-running ones. + * + */ +public class ListContainersCmd extends AbstrDockerCmd> { + + private static final Logger LOGGER = LoggerFactory.getLogger(ListContainersCmd.class); + + private int limit = -1; + private boolean showSize, showAll = false; + String sinceId, beforeId; + + public ListContainersCmd withShowAll(boolean showAll) { + this.showAll = showAll; + return this; + } + + public ListContainersCmd withShowSize(boolean showSize) { + this.showSize = showSize; + return this; + } + + public ListContainersCmd withLimit(int limit) { + Preconditions.checkArgument(limit > 0, "limit must be greater 0"); + this.limit = limit; + return this; + } + + public ListContainersCmd withSince(String since) { + Preconditions.checkNotNull(since, "since was not specified"); + this.sinceId = since; + return this; + } + + public ListContainersCmd withBefore(String before) { + Preconditions.checkNotNull(before, "before was not specified"); + this.beforeId = before; + return this; + } + + protected List impl() { + MultivaluedMap params = new MultivaluedMapImpl(); + if(limit >= 0) { + params.add("limit", String.valueOf(limit)); + } + params.add("all", showAll ? "1" : "0"); + params.add("since", sinceId); + params.add("before", beforeId); + params.add("size", showSize ? "1" : "0"); + + WebResource webResource = baseResource.path("/containers/json").queryParams(params); + LOGGER.trace("GET: {}", webResource); + List containers = webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); + LOGGER.trace("Response: {}", containers); + + return containers; + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java b/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java new file mode 100644 index 00000000..5756b72d --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java @@ -0,0 +1,67 @@ +package com.github.dockerjava.client.command; + +import java.util.List; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.Image; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.GenericType; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.core.util.MultivaluedMapImpl; + + +/** + * List images + * + * @param showAll - Show all images (by default filter out the intermediate images used to build) + * @param filter - TODO: undocumented in docker remote api reference + */ +public class ListImagesCmd extends AbstrDockerCmd> { + + private static final Logger LOGGER = LoggerFactory.getLogger(ListImagesCmd.class); + + private String filter; + private boolean showAll = false; + + public ListImagesCmd withShowAll(boolean showAll) { + this.showAll = showAll; + return this; + } + + public ListImagesCmd withFilter(String filter) { + Preconditions.checkNotNull(filter, "filter was not specified"); + this.filter = filter; + return this; + } + + protected List impl() { + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("filter", filter); + params.add("all", showAll ? "1" : "0"); + + WebResource webResource = baseResource.path("/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(); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java new file mode 100644 index 00000000..2183e734 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java @@ -0,0 +1,102 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.core.util.MultivaluedMapImpl; + +/** + * Get container logs + * + * @param followStream - true or false, return stream. Defaults to false. + * @param stdout - true or false, includes stdout log. Defaults to false. + * @param stderr - true or false, includes stderr log. Defaults to false. + * @param timestamps - true or false, if true, print timestamps for every log line. Defaults to false. + */ +public class LogContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(LogContainerCmd.class); + + private String containerId; + + private boolean followStream, timestamps, stdout, stderr; + + public LogContainerCmd(String containerId) { + withContainerId(containerId); + } + + public LogContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + public LogContainerCmd withFollowStream() { + return withFollowStream(true); + } + + public LogContainerCmd withFollowStream(boolean followStream) { + this.followStream = followStream; + return this; + } + + public LogContainerCmd withTimestamps(boolean timestamps) { + this.timestamps = timestamps; + return this; + } + + public LogContainerCmd withStdOut() { + return withStdOut(true); + } + + public LogContainerCmd withStdOut(boolean stdout) { + this.stdout = stdout; + return this; + } + + public LogContainerCmd withStdErr() { + return withStdErr(true); + } + + public LogContainerCmd withStdErr(boolean stderr) { + this.stderr = stderr; + return this; + } + + protected ClientResponse impl() throws DockerException { + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("logs", "1"); + params.add("timestamps", timestamps ? "1" : "0"); + params.add("stdout", stdout ? "1" : "0"); + params.add("stderr", stderr ? "1" : "0"); + params.add("follow", followStream ? "1" : "0"); // this parameter keeps stream open indefinitely + + WebResource webResource = baseResource.path(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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java b/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java new file mode 100644 index 00000000..0c6ee7a3 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java @@ -0,0 +1,79 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.core.util.MultivaluedMapImpl; + + +/** + * + * Pull image from repository. + * + */ +public class PullImageCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(PullImageCmd.class); + + private String repository, tag, registry; + + public PullImageCmd(String repository) { + withRepository(repository); + } + + public PullImageCmd withRepository(String repository) { + Preconditions.checkNotNull(repository, "repository was not specified"); + this.repository = repository; + return this; + } + + public PullImageCmd withTag(String tag) { + Preconditions.checkNotNull(tag, "tag was not specified"); + this.tag = tag; + return this; + } + + public PullImageCmd withRegistry(String registry) { + Preconditions.checkNotNull(registry, "registry was not specified"); + this.registry = registry; + return this; + } + + protected ClientResponse impl() { + 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 = baseResource.path("/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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java b/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java new file mode 100644 index 00000000..dc0b35b1 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java @@ -0,0 +1,56 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + + +/** + * 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 class PushImageCmd extends AbstrAuthCfgDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(PushImageCmd.class); + + private String name; + + public PushImageCmd(String name) { + withName(name); + } + + /** + * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. + */ + public PushImageCmd withName(String name) { + Preconditions.checkNotNull(name, "name was not specified"); + this.name = name; + return this; + } + + protected ClientResponse impl() { + WebResource webResource = baseResource.path("/images/" + name(name) + "/push"); + try { + final String registryAuth = registryAuth(); + LOGGER.trace("POST: {}", webResource); + return webResource + .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(); + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java new file mode 100644 index 00000000..b8e10765 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java @@ -0,0 +1,79 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * Remove a container. + * + * @param removeVolumes - true or false, Remove the volumes associated to the container. Defaults to false + * @param force - true or false, Removes the container even if it was running. Defaults to false + */ +public class RemoveContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(RemoveContainerCmd.class); + + private String containerId; + + private boolean removeVolumes, force; + + public RemoveContainerCmd(String containerId) { + withContainerId(containerId); + } + + public RemoveContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + public RemoveContainerCmd withRemoveVolumes(boolean removeVolumes) { + this.removeVolumes = removeVolumes; + return this; + } + + public RemoveContainerCmd withForce() { + return withForce(true); + } + + public RemoveContainerCmd withForce(boolean force) { + this.force = force; + return this; + } + + protected Void impl() throws DockerException { + Preconditions.checkState(!StringUtils.isEmpty(containerId), "Container ID can't be empty"); + + WebResource webResource = baseResource.path("/containers/" + containerId).queryParam("v", removeVolumes ? "1" : "0").queryParam("force", force ? "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); + } + } + + return null; + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java b/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java new file mode 100644 index 00000000..cef438fe --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java @@ -0,0 +1,74 @@ +package com.github.dockerjava.client.command; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * + * Remove an image, deleting any tags it might have. + * + */ +public class RemoveImageCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(RemoveImageCmd.class); + + private String imageId; + + private boolean force, noPrune; + + public RemoveImageCmd(String imageId) { + withImageId(imageId); + } + + public RemoveImageCmd withImageId(String imageId) { + Preconditions.checkNotNull(imageId, "imageId was not specified"); + this.imageId = imageId; + return this; + } + + public RemoveImageCmd withForce(boolean force) { + this.force = force; + return this; + } + + public RemoveImageCmd withNoPrune(boolean noPrune) { + this.noPrune = noPrune; + return this; + } + + protected Void impl() throws DockerException { + Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty"); + + try { + WebResource webResource = baseResource.path("/images/" + imageId) + .queryParam("force", force ? "1" : "0").queryParam("noprune", noPrune ? "1" : "0"); + + LOGGER.trace("DELETE: {}", webResource); + webResource.delete(ClientResponse.class); + + + } 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); + } + } + + return null; + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java new file mode 100644 index 00000000..b8da9dbd --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java @@ -0,0 +1,66 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * Restart a running container. + * + * @param timeout - Timeout in seconds before killing the container. Defaults to 10 seconds. + * + */ +public class RestartContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(RestartContainerCmd.class); + + private String containerId; + + private int timeout = 10; + + public RestartContainerCmd(String containerId) { + withContainerId(containerId); + } + + public RestartContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + public RestartContainerCmd withtTimeout(int timeout) { + Preconditions.checkArgument(timeout >= 0, "timeout must be greater or equal 0"); + this.timeout = timeout; + return this; + } + + protected Void impl() throws DockerException { + WebResource webResource = baseResource.path(String.format("/containers/%s/restart", 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) { + 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); + } + } + + return null; + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java b/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java new file mode 100644 index 00000000..784e49de --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java @@ -0,0 +1,53 @@ +package com.github.dockerjava.client.command; + +import java.util.List; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.SearchItem; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.GenericType; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + + +/** + * + * + * + */ +public class SearchImagesCmd extends AbstrDockerCmd> { + + private static final Logger LOGGER = LoggerFactory.getLogger(SearchImagesCmd.class); + + private String term; + + public SearchImagesCmd(String term) { + withTerm(term); + } + + public SearchImagesCmd withTerm(String term) { + Preconditions.checkNotNull(term, "term was not specified"); + this.term = term; + return this; + } + + protected List impl() { + WebResource webResource = baseResource.path("/images/search").queryParam("term", term); + try { + LOGGER.trace("GET: {}", webResource); + 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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java new file mode 100644 index 00000000..0470a59e --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -0,0 +1,107 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.client.model.LxcConf; +import com.github.dockerjava.client.model.StartContainerConfig; +import com.github.dockerjava.client.model.Ports; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.WebResource.Builder; + +/** + * + * + * + */ +public class StartContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(StartContainerCmd.class); + + private String containerId; + + private StartContainerConfig startContainerConfig; + + public StartContainerCmd(String containerId) { + startContainerConfig = new StartContainerConfig(); + withContainerId(containerId); + } + + public StartContainerCmd withBinds(String... binds) { + startContainerConfig.binds = binds; + return this; + } + + public StartContainerCmd withLxcConf(LxcConf[] lxcConf) { + startContainerConfig.lxcConf = lxcConf; + return this; + } + + public StartContainerCmd withPortBindings(Ports portBindings) { + startContainerConfig.portBindings = portBindings; + return this; + } + + public StartContainerCmd withPrivileged(boolean privileged) { + startContainerConfig.privileged = privileged; + return this; + } + + public StartContainerCmd withPublishAllPorts(boolean publishAllPorts) { + startContainerConfig.publishAllPorts = publishAllPorts; + return this; + } + + public StartContainerCmd withDns(String dns) { + startContainerConfig.dns = dns; + return this; + } + + + public StartContainerCmd withVolumesFrom(String volumesFrom) { + startContainerConfig.volumesFrom = volumesFrom; + return this; + } + + public StartContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + protected Void impl() throws DockerException { + WebResource webResource = baseResource.path(String.format("/containers/%s/start", containerId)); + + try { + LOGGER.trace("POST: {}", webResource); + Builder builder = webResource.accept(MediaType.TEXT_PLAIN); + if (startContainerConfig != null) { + builder.type(MediaType.APPLICATION_JSON).post(startContainerConfig); + } else { + builder.post((StartContainerConfig) 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) { + LOGGER.error("", exception); + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + + return null; + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java new file mode 100644 index 00000000..cb2e26f9 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java @@ -0,0 +1,66 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * Stop a running container. + * + * @param containerId - Id of the container + * @param timeout - Timeout in seconds before killing the container. Defaults to 10 seconds. + * + */ +public class StopContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(StopContainerCmd.class); + + private String containerId; + + private int timeout = 10; + + public StopContainerCmd(String containerId) { + withContainerId(containerId); + } + + public StopContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + public StopContainerCmd withTimeout(int timeout) { + Preconditions.checkArgument(timeout >= 0, "timeout must be greater or equal 0"); + this.timeout = timeout; + return this; + } + + protected Void impl() throws DockerException { + WebResource webResource = baseResource.path(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); + } + } + + return null; + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java b/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java new file mode 100644 index 00000000..f06ab376 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java @@ -0,0 +1,86 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MultivaluedMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.core.util.MultivaluedMapImpl; + + +/** + * 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 force + * (not documented) + * @return the HTTP status code (201 for success) + */ +public class TagImageCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(TagImageCmd.class); + + private String imageId, repository, tag; + + private boolean force; + + public TagImageCmd(String imageId, String repository, String tag) { + withImageId(imageId); + withRepository(repository); + withTag(tag); + } + + public TagImageCmd withImageId(String imageId) { + Preconditions.checkNotNull(imageId, "imageId was not specified"); + this.imageId = imageId; + return this; + } + + public TagImageCmd withRepository(String repository) { + Preconditions.checkNotNull(repository, "repository was not specified"); + this.repository = repository; + return this; + } + + public TagImageCmd withTag(String tag) { + Preconditions.checkNotNull(tag, "tag was not specified"); + this.tag = tag; + return this; + } + + public TagImageCmd withForce() { + return withForce(true); + } + + public TagImageCmd withForce(boolean force) { + this.force = force; + return this; + } + + protected Integer impl() { + + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("repo", repository); + params.add("tag", tag); + params.add("force", force ? "1" : "0"); + + WebResource webResource = baseResource.path("/images/" + imageId + "/tag").queryParams( + params); + + try { + LOGGER.trace("POST: {}", webResource); + ClientResponse resp = webResource.post(ClientResponse.class); + return resp.getStatus(); + } catch (UniformInterfaceException exception) { + throw new DockerException(exception); + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java new file mode 100644 index 00000000..34be6e97 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java @@ -0,0 +1,65 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.client.model.ContainerTopResponse; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * + * @author marcus + * + */ +public class TopContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(TopContainerCmd.class); + + private String containerId; + + private String psArgs; + + public TopContainerCmd(String containerId) { + withContainerId(containerId); + } + + public TopContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + + public TopContainerCmd withPsArgs(String psArgs) { + Preconditions.checkNotNull(psArgs, "psArgs was not specified"); + this.psArgs = psArgs; + return this; + } + + protected ContainerTopResponse impl() throws DockerException { + WebResource webResource = baseResource.path(String.format("/containers/%s/top", containerId)); + + if(!StringUtils.isEmpty(psArgs)) + webResource = webResource.queryParam("ps_args", psArgs); + + try { + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(ContainerTopResponse.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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/VersionCmd.java b/src/main/java/com/github/dockerjava/client/command/VersionCmd.java new file mode 100644 index 00000000..15fd00bc --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/VersionCmd.java @@ -0,0 +1,38 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.Version; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + + +/** + * + * + * + */ +public class VersionCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(VersionCmd.class); + + + protected Version impl() throws DockerException { + WebResource webResource = baseResource.path("/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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java new file mode 100644 index 00000000..71134895 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java @@ -0,0 +1,55 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * + * + * + */ +public class WaitContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(WaitContainerCmd.class); + + private String containerId; + + public WaitContainerCmd(String containerId) { + withContainerId(containerId); + } + + public WaitContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + protected Integer impl() throws DockerException { + WebResource webResource = baseResource.path(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); + } + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/AuthConfig.java b/src/main/java/com/github/dockerjava/client/model/AuthConfig.java similarity index 96% rename from src/main/java/com/kpelykh/docker/client/model/AuthConfig.java rename to src/main/java/com/github/dockerjava/client/model/AuthConfig.java index 514e79be..ee292f71 100644 --- a/src/main/java/com/kpelykh/docker/client/model/AuthConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/AuthConfig.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/kpelykh/docker/client/model/ChangeLog.java b/src/main/java/com/github/dockerjava/client/model/ChangeLog.java similarity index 89% rename from src/main/java/com/kpelykh/docker/client/model/ChangeLog.java rename to src/main/java/com/github/dockerjava/client/model/ChangeLog.java index 50fdab4a..7fba4cfe 100644 --- a/src/main/java/com/kpelykh/docker/client/model/ChangeLog.java +++ b/src/main/java/com/github/dockerjava/client/model/ChangeLog.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/kpelykh/docker/client/model/CommitConfig.java b/src/main/java/com/github/dockerjava/client/model/CommitConfig.java similarity index 83% rename from src/main/java/com/kpelykh/docker/client/model/CommitConfig.java rename to src/main/java/com/github/dockerjava/client/model/CommitConfig.java index 4023deb7..a8e6892b 100644 --- a/src/main/java/com/kpelykh/docker/client/model/CommitConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/CommitConfig.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @@ -12,7 +12,7 @@ public class CommitConfig { @JsonProperty("container") - private String container; + private String containerId; @JsonProperty("repo") private String repo; @@ -31,8 +31,8 @@ public class CommitConfig { @JsonProperty("run") private String run; - public String getContainer() { - return container; + public String getContainerId() { + return containerId; } public String getRepo() { @@ -80,8 +80,8 @@ public CommitConfig setRun(String run) { return this; } - public CommitConfig(String container) { - this.container = container; + public CommitConfig(String containerId) { + this.containerId = containerId; } - + } diff --git a/src/main/java/com/kpelykh/docker/client/model/Container.java b/src/main/java/com/github/dockerjava/client/model/Container.java similarity index 93% rename from src/main/java/com/kpelykh/docker/client/model/Container.java rename to src/main/java/com/github/dockerjava/client/model/Container.java index 3e6554cb..acdb95ee 100644 --- a/src/main/java/com/kpelykh/docker/client/model/Container.java +++ b/src/main/java/com/github/dockerjava/client/model/Container.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/kpelykh/docker/client/model/ContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java similarity index 93% rename from src/main/java/com/kpelykh/docker/client/model/ContainerConfig.java rename to src/main/java/com/github/dockerjava/client/model/ContainerConfig.java index 27a1d7e3..dec568e4 100644 --- a/src/main/java/com/kpelykh/docker/client/model/ContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @@ -30,7 +30,7 @@ public class ContainerConfig { @JsonProperty("Cmd") private String[] cmd; @JsonProperty("Dns") private String[] dns; @JsonProperty("Image") private String image; - @JsonProperty("Volumes") private BoundHostVolumes volumes; + @JsonProperty("Volumes") private Map volumes; @JsonProperty("VolumesFrom") private String volumesFrom = ""; @JsonProperty("Entrypoint") private String[] entrypoint = new String[]{}; @JsonProperty("NetworkDisabled") private boolean networkDisabled = false; @@ -219,11 +219,11 @@ public ContainerConfig setImage(String image) { return this; } - public BoundHostVolumes getVolumes() { + public Map getVolumes() { return volumes; } - public ContainerConfig setVolumes(BoundHostVolumes volumes) { + public ContainerConfig setVolumes(Map volumes) { this.volumes = volumes; return this; } diff --git a/src/main/java/com/kpelykh/docker/client/model/ContainerCreateResponse.java b/src/main/java/com/github/dockerjava/client/model/ContainerCreateResponse.java similarity index 90% rename from src/main/java/com/kpelykh/docker/client/model/ContainerCreateResponse.java rename to src/main/java/com/github/dockerjava/client/model/ContainerCreateResponse.java index 8f60ce15..4cd75b58 100644 --- a/src/main/java/com/kpelykh/docker/client/model/ContainerCreateResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerCreateResponse.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/kpelykh/docker/client/model/ContainerInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java similarity index 89% rename from src/main/java/com/kpelykh/docker/client/model/ContainerInspectResponse.java rename to src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java index d686f9eb..a90183b9 100644 --- a/src/main/java/com/kpelykh/docker/client/model/ContainerInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import java.util.Map; @@ -48,7 +48,7 @@ public class ContainerInspectResponse { private Map volumes; @JsonProperty("VolumesRW") - private Map volumesRW; + private Map volumesRW; @JsonProperty("HostnamePath") private String hostnamePath; @@ -159,11 +159,11 @@ public void setVolumes(Map volumes) { this.volumes = volumes; } - public Map getVolumesRW() { + public Map getVolumesRW() { return volumesRW; } - public void setVolumesRW(Map volumesRW) { + public void setVolumesRW(Map volumesRW) { this.volumesRW = volumesRW; } @@ -223,6 +223,7 @@ public void setMountLabel(String mountLabel) { this.mountLabel = mountLabel; } + @JsonIgnoreProperties(ignoreUnknown = true) public class NetworkSettings { @JsonProperty("IPAddress") public String ipAddress; @@ -245,23 +246,24 @@ public String toString() { } } + @JsonIgnoreProperties(ignoreUnknown = true) public class ContainerState { @JsonProperty("Running") public boolean running; + @JsonProperty("Paused") public boolean paused; @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 + + ", paused=" + paused + ", pid=" + pid + ", exitCode=" + exitCode + ", startedAt='" + startedAt + '\'' + - ", ghost=" + ghost + ", finishedAt='" + finishedAt + '\'' + '}'; } diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerTopResponse.java b/src/main/java/com/github/dockerjava/client/model/ContainerTopResponse.java new file mode 100644 index 00000000..6b43690a --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/ContainerTopResponse.java @@ -0,0 +1,46 @@ +package com.github.dockerjava.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.common.base.Joiner; + +/** + * + * @author marcus + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ContainerTopResponse { + + @JsonProperty("Titles") + private String[] titles; + + @JsonProperty("Processes") + private String[][] processes; + + public String[] getTitles() { + return titles; + } + + public String[][] getProcesses() { + return processes; + } + + @Override + public String toString() { + Joiner joiner = Joiner.on("; ").skipNulls(); + + StringBuffer buffer = new StringBuffer(); + buffer.append("["); + for(String[] fields: processes) { + buffer.append("[" + joiner.join(fields) + "]"); + } + buffer.append("]"); + + return "ContainerTopResponse{" + + "titles=" + joiner.join(titles) + + ", processes=" + buffer.toString() + + '}'; + } + +} diff --git a/src/main/java/com/kpelykh/docker/client/model/CopyConfig.java b/src/main/java/com/github/dockerjava/client/model/CopyConfig.java similarity index 96% rename from src/main/java/com/kpelykh/docker/client/model/CopyConfig.java rename to src/main/java/com/github/dockerjava/client/model/CopyConfig.java index 696778a2..423cc336 100755 --- a/src/main/java/com/kpelykh/docker/client/model/CopyConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/CopyConfig.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java new file mode 100644 index 00000000..2b267589 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java @@ -0,0 +1,271 @@ +package com.github.dockerjava.client.model; + + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Arrays; +import java.util.Map; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + * "Hostname":"", + "User":"", + "Memory":0, + "MemorySwap":0, + "AttachStdin":false, + "AttachStdout":true, + "AttachStderr":true, + "PortSpecs":null, + "Tty":false, + "OpenStdin":false, + "StdinOnce":false, + "Env":null, + "Cmd":[ + "date" + ], + "Dns":null, + "Image":"base", + "Volumes":{ + "/tmp": {} + }, + "VolumesFrom":"", + "WorkingDir":"", + "DisableNetwork": false, + "ExposedPorts":{ + "22/tcp": {} + } + * + * + */ +public class CreateContainerConfig { + + @JsonProperty("Hostname") private String hostName = ""; + @JsonProperty("User") private String user = ""; + @JsonProperty("Memory") private long memoryLimit = 0; + @JsonProperty("MemorySwap") private long memorySwap = 0; + @JsonProperty("AttachStdin") private boolean attachStdin = false; + @JsonProperty("AttachStdout") private boolean attachStdout = false; + @JsonProperty("AttachStderr") private boolean attachStderr = false; + @JsonProperty("PortSpecs") private String[] portSpecs; + @JsonProperty("Tty") private boolean tty = false; + @JsonProperty("OpenStdin") private boolean stdinOpen = false; + @JsonProperty("StdinOnce") private boolean stdInOnce = false; + @JsonProperty("Env") private String[] env; + @JsonProperty("Cmd") private String[] cmd; + @JsonProperty("Dns") private String[] dns; + @JsonProperty("Image") private String image; + @JsonProperty("Volumes") private Map volumes; + @JsonProperty("VolumesFrom") private String volumesFrom = ""; + @JsonProperty("WorkingDir") private String workingDir = ""; + @JsonProperty("DisableNetwork") private boolean disableNetwork = false; + @JsonProperty("ExposedPorts") private Map exposedPorts; + + public Map getExposedPorts() { + return exposedPorts; + } + + public boolean isDisableNetwork() { + return disableNetwork; + } + + + + public String getWorkingDir() { return workingDir; } + + public CreateContainerConfig withWorkingDir(String workingDir) { + this.workingDir = workingDir; + return this; + } + + + public String getHostName() { + return hostName; + } + + public CreateContainerConfig withDisableNetwork(boolean disableNetwork) { + this.disableNetwork = disableNetwork; + return this; + } + + public CreateContainerConfig withHostName(String hostName) { + this.hostName = hostName; + return this; + } + + public String[] getPortSpecs() { + return portSpecs; + } + + public CreateContainerConfig withPortSpecs(String[] portSpecs) { + this.portSpecs = portSpecs; + return this; + } + + public String getUser() { + return user; + } + + public CreateContainerConfig withUser(String user) { + this.user = user; + return this; + } + + public boolean isTty() { + return tty; + } + + public CreateContainerConfig withTty(boolean tty) { + this.tty = tty; + return this; + } + + public boolean isStdinOpen() { + return stdinOpen; + } + + public CreateContainerConfig withStdinOpen(boolean stdinOpen) { + this.stdinOpen = stdinOpen; + return this; + } + + public boolean isStdInOnce() { + return stdInOnce; + } + + public CreateContainerConfig withStdInOnce(boolean stdInOnce) { + this.stdInOnce = stdInOnce; + return this; + } + + public long getMemoryLimit() { + return memoryLimit; + } + + public CreateContainerConfig withMemoryLimit(long memoryLimit) { + this.memoryLimit = memoryLimit; + return this; + } + + public long getMemorySwap() { + return memorySwap; + } + + public CreateContainerConfig withMemorySwap(long memorySwap) { + this.memorySwap = memorySwap; + return this; + } + + + public boolean isAttachStdin() { + return attachStdin; + } + + public CreateContainerConfig withAttachStdin(boolean attachStdin) { + this.attachStdin = attachStdin; + return this; + } + + public boolean isAttachStdout() { + return attachStdout; + } + + public CreateContainerConfig withAttachStdout(boolean attachStdout) { + this.attachStdout = attachStdout; + return this; + } + + public boolean isAttachStderr() { + return attachStderr; + } + + public CreateContainerConfig withAttachStderr(boolean attachStderr) { + this.attachStderr = attachStderr; + return this; + } + + public String[] getEnv() { + return env; + } + + public CreateContainerConfig withEnv(String[] env) { + this.env = env; + return this; + } + + public String[] getCmd() { + return cmd; + } + + public CreateContainerConfig withCmd(String[] cmd) { + this.cmd = cmd; + return this; + } + + public String[] getDns() { + return dns; + } + + public CreateContainerConfig withDns(String[] dns) { + this.dns = dns; + return this; + } + + public String getImage() { + return image; + } + + public CreateContainerConfig withImage(String image) { + this.image = image; + return this; + } + + public Map getVolumes() { + return volumes; + } + + public CreateContainerConfig withVolumes(Map volumes) { + this.volumes = volumes; + return this; + } + + public String getVolumesFrom() { + return volumesFrom; + } + + public CreateContainerConfig withVolumesFrom(String volumesFrom) { + this.volumesFrom = volumesFrom; + return this; + } + + + + + + + @Override + public String toString() { + return "CreateContainerConfig{" + + "hostName='" + hostName + '\'' + + ", portSpecs=" + Arrays.toString(portSpecs) + + ", user='" + user + '\'' + + ", tty=" + tty + + ", stdinOpen=" + stdinOpen + + ", stdInOnce=" + stdInOnce + + ", memoryLimit=" + memoryLimit + + ", memorySwap=" + memorySwap + + ", attachStdin=" + attachStdin + + ", attachStdout=" + attachStdout + + ", attachStderr=" + attachStderr + + ", env=" + Arrays.toString(env) + + ", cmd=" + Arrays.toString(cmd) + + ", dns=" + Arrays.toString(dns) + + ", image='" + image + '\'' + + ", volumes=" + volumes + + ", volumesFrom='" + volumesFrom + '\'' + + ", disableNetwork=" + disableNetwork + + ", workingDir='" + workingDir + '\'' + + '}'; + } +} diff --git a/src/main/java/com/kpelykh/docker/client/model/DriverStatus.java b/src/main/java/com/github/dockerjava/client/model/DriverStatus.java similarity index 89% rename from src/main/java/com/kpelykh/docker/client/model/DriverStatus.java rename to src/main/java/com/github/dockerjava/client/model/DriverStatus.java index 5421bc44..c9794f02 100644 --- a/src/main/java/com/kpelykh/docker/client/model/DriverStatus.java +++ b/src/main/java/com/github/dockerjava/client/model/DriverStatus.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/github/dockerjava/client/model/HostConfig.java b/src/main/java/com/github/dockerjava/client/model/HostConfig.java new file mode 100644 index 00000000..7fcaf79c --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/HostConfig.java @@ -0,0 +1,66 @@ +package com.github.dockerjava.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") + public String[] binds; + + @JsonProperty("LxcConf") + public LxcConf[] lxcConf; + + @JsonProperty("PortBindings") + public Ports portBindings; + + @JsonProperty("PublishAllPorts") + public boolean publishAllPorts; + + @JsonProperty("Privileged") + public boolean privileged; + + @JsonProperty("Dns") + public String dns; + + @JsonProperty("VolumesFrom") + public String volumesFrom; + + @JsonProperty("ContainerIDFile") + public String containerIDFile; + + @JsonProperty("DnsSearch") + public String dnsSearch; + + @JsonProperty("Links") + public String[] links; + + @JsonProperty("NetworkMode") + public String networkMode; + + + + @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 + + ", networkMode=" + networkMode + + ", dns='" + dns + '\'' + + '}'; + } + +} diff --git a/src/main/java/com/kpelykh/docker/client/model/Image.java b/src/main/java/com/github/dockerjava/client/model/Image.java similarity index 93% rename from src/main/java/com/kpelykh/docker/client/model/Image.java rename to src/main/java/com/github/dockerjava/client/model/Image.java index cfc578ce..5472c3e2 100644 --- a/src/main/java/com/kpelykh/docker/client/model/Image.java +++ b/src/main/java/com/github/dockerjava/client/model/Image.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/kpelykh/docker/client/model/ImageCreateResponse.java b/src/main/java/com/github/dockerjava/client/model/ImageCreateResponse.java similarity index 88% rename from src/main/java/com/kpelykh/docker/client/model/ImageCreateResponse.java rename to src/main/java/com/github/dockerjava/client/model/ImageCreateResponse.java index 21545a2d..05cc00b9 100644 --- a/src/main/java/com/kpelykh/docker/client/model/ImageCreateResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ImageCreateResponse.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/kpelykh/docker/client/model/ImageInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java similarity index 94% rename from src/main/java/com/kpelykh/docker/client/model/ImageInspectResponse.java rename to src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java index 3514670c..31bd46b1 100644 --- a/src/main/java/com/kpelykh/docker/client/model/ImageInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/kpelykh/docker/client/model/Info.java b/src/main/java/com/github/dockerjava/client/model/Info.java similarity index 92% rename from src/main/java/com/kpelykh/docker/client/model/Info.java rename to src/main/java/com/github/dockerjava/client/model/Info.java index 72f2f360..b26531f1 100644 --- a/src/main/java/com/kpelykh/docker/client/model/Info.java +++ b/src/main/java/com/github/dockerjava/client/model/Info.java @@ -1,6 +1,8 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @@ -12,6 +14,7 @@ * */ @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class Info { diff --git a/src/main/java/com/github/dockerjava/client/model/LxcConf.java b/src/main/java/com/github/dockerjava/client/model/LxcConf.java new file mode 100644 index 00000000..a2f02208 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/LxcConf.java @@ -0,0 +1,38 @@ +package com.github.dockerjava.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +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/Port.java b/src/main/java/com/github/dockerjava/client/model/Port.java similarity index 96% rename from src/main/java/com/kpelykh/docker/client/model/Port.java rename to src/main/java/com/github/dockerjava/client/model/Port.java index 538213ec..41194ce1 100644 --- a/src/main/java/com/kpelykh/docker/client/model/Port.java +++ b/src/main/java/com/github/dockerjava/client/model/Port.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/kpelykh/docker/client/model/Ports.java b/src/main/java/com/github/dockerjava/client/model/Ports.java similarity index 69% rename from src/main/java/com/kpelykh/docker/client/model/Ports.java rename to src/main/java/com/github/dockerjava/client/model/Ports.java index fc590289..32055ed7 100644 --- a/src/main/java/com/kpelykh/docker/client/model/Ports.java +++ b/src/main/java/com/github/dockerjava/client/model/Ports.java @@ -1,23 +1,24 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; 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.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; 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. - */ +* Created by ben on 16/12/13. +*/ @JsonDeserialize(using=Ports.Deserializer.class) @JsonSerialize(using=Ports.Serializer.class) public class Ports { @@ -93,14 +94,14 @@ public Ports deserialize(JsonParser jsonParser, DeserializationContext deseriali 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)); + JsonNode portNodes = oc.readTree(jsonParser); + if (portNodes.isArray()) { + for (JsonNode portNode : portNodes) { + String hostIp = portNode.get("IP").textValue(); + String hostPort = portNode.get("PublicPort").asText(); + String privatePort = portNode.get("PrivatePort").asText(); + String scheme = portNode.get("Type").textValue(); + out.addPort(new Port(scheme, privatePort, hostIp, hostPort)); } } return out; @@ -113,18 +114,17 @@ public static class Serializer extends JsonSerializer { public void serialize(Ports ports, JsonGenerator jsonGen, SerializerProvider serProvider) throws IOException, JsonProcessingException { - jsonGen.writeStartObject();//{ + jsonGen.writeStartArray(); 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.writeStringField("IP", p.hostIp); + jsonGen.writeNumberField("PrivatePort", Integer.parseInt(p.getPort())); + jsonGen.writeNumberField("PublicPort", Integer.parseInt(p.getHostPort())); + jsonGen.writeStringField("Type", p.getScheme()); jsonGen.writeEndObject(); - jsonGen.writeEndArray(); } - jsonGen.writeEndObject();//} + jsonGen.writeEndArray(); } } diff --git a/src/main/java/com/kpelykh/docker/client/model/SearchItem.java b/src/main/java/com/github/dockerjava/client/model/SearchItem.java similarity index 91% rename from src/main/java/com/kpelykh/docker/client/model/SearchItem.java rename to src/main/java/com/github/dockerjava/client/model/SearchItem.java index d7f6eb4f..e98a151b 100644 --- a/src/main/java/com/kpelykh/docker/client/model/SearchItem.java +++ b/src/main/java/com/github/dockerjava/client/model/SearchItem.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java new file mode 100644 index 00000000..1bd941b1 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java @@ -0,0 +1,50 @@ +package com.github.dockerjava.client.model; + +import java.util.Arrays; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +public class StartContainerConfig { + + @JsonProperty("Binds") + public String[] binds; + + @JsonProperty("LxcConf") + public LxcConf[] lxcConf; + + @JsonProperty("PortBindings") + public Ports portBindings; + + @JsonProperty("PublishAllPorts") + public boolean publishAllPorts; + + @JsonProperty("Privileged") + public boolean privileged; + + @JsonProperty("Dns") + public String dns; + + @JsonProperty("VolumesFrom") + public String volumesFrom; + + + + + @Override + public String toString() { + return "StartContainerConfig{" + + "binds=" + Arrays.toString(binds) + + ", lxcConf=" + Arrays.toString(lxcConf) + + ", portBindings=" + portBindings + + ", privileged=" + privileged + + ", publishAllPorts=" + publishAllPorts + + ", dns='" + dns + '\'' + + '}'; + } + +} diff --git a/src/main/java/com/kpelykh/docker/client/model/Version.java b/src/main/java/com/github/dockerjava/client/model/Version.java similarity index 93% rename from src/main/java/com/kpelykh/docker/client/model/Version.java rename to src/main/java/com/github/dockerjava/client/model/Version.java index a427aafb..35843ca4 100644 --- a/src/main/java/com/kpelykh/docker/client/model/Version.java +++ b/src/main/java/com/github/dockerjava/client/model/Version.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.model; +package com.github.dockerjava.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/kpelykh/docker/client/utils/CompressArchiveUtil.java b/src/main/java/com/github/dockerjava/client/utils/CompressArchiveUtil.java similarity index 96% rename from src/main/java/com/kpelykh/docker/client/utils/CompressArchiveUtil.java rename to src/main/java/com/github/dockerjava/client/utils/CompressArchiveUtil.java index aabf4cbb..4da0cdac 100644 --- a/src/main/java/com/kpelykh/docker/client/utils/CompressArchiveUtil.java +++ b/src/main/java/com/github/dockerjava/client/utils/CompressArchiveUtil.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.utils; +package com.github.dockerjava.client.utils; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; diff --git a/src/main/java/com/kpelykh/docker/client/utils/JsonClientFilter.java b/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java similarity index 94% rename from src/main/java/com/kpelykh/docker/client/utils/JsonClientFilter.java rename to src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java index 55b8b287..89633b52 100644 --- a/src/main/java/com/kpelykh/docker/client/utils/JsonClientFilter.java +++ b/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java @@ -1,4 +1,4 @@ -package com.kpelykh.docker.client.utils; +package com.github.dockerjava.client.utils; import com.sun.jersey.api.client.ClientRequest; diff --git a/src/main/java/com/google/common/base/Preconditions.java b/src/main/java/com/google/common/base/Preconditions.java deleted file mode 100644 index 6a15fb4d..00000000 --- a/src/main/java/com/google/common/base/Preconditions.java +++ /dev/null @@ -1,443 +0,0 @@ -/* - * Copyright (C) 2007 The Guava Authors - * - * Licensed 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.google.common.base; - - -import java.util.NoSuchElementException; - -/** - * Simple static methods to be called at the start of your own methods to verify - * correct arguments and state. This allows constructs such as - *
- *     if (count <= 0) {
- *       throw new IllegalArgumentException("must be positive: " + count);
- *     }
- * - * to be replaced with the more compact - *
- *     checkArgument(count > 0, "must be positive: %s", count);
- * - * Note that the sense of the expression is inverted; with {@code Preconditions} - * you declare what you expect to be true, just as you do with an - * - * {@code assert} or a JUnit {@code assertTrue} call. - * - *

Warning: only the {@code "%s"} specifier is recognized as a - * placeholder in these messages, not the full range of {@link - * String#format(String, Object[])} specifiers. - * - *

Take care not to confuse precondition checking with other similar types - * of checks! Precondition exceptions -- including those provided here, but also - * {@link IndexOutOfBoundsException}, {@link NoSuchElementException}, {@link - * UnsupportedOperationException} and others -- are used to signal that the - * calling method has made an error. This tells the caller that it should - * not have invoked the method when it did, with the arguments it did, or - * perhaps ever. Postcondition or other invariant failures should not throw - * these types of exceptions. - * - *

See the Guava User Guide on - * using {@code Preconditions}. - * - * @author Kevin Bourrillion - * @since 2.0 (imported from Google Collections Library) - */ -public final class Preconditions { - private Preconditions() {} - - /** - * Ensures the truth of an expression involving one or more parameters to the - * calling method. - * - * @param expression a boolean expression - * @throws IllegalArgumentException if {@code expression} is false - */ - public static void checkArgument(boolean expression) { - if (!expression) { - throw new IllegalArgumentException(); - } - } - - /** - * Ensures the truth of an expression involving one or more parameters to the - * calling method. - * - * @param expression a boolean expression - * @param errorMessage the exception message to use if the check fails; will - * be converted to a string using {@link String#valueOf(Object)} - * @throws IllegalArgumentException if {@code expression} is false - */ - public static void checkArgument( - boolean expression, Object errorMessage) { - if (!expression) { - throw new IllegalArgumentException(String.valueOf(errorMessage)); - } - } - - /** - * Ensures the truth of an expression involving one or more parameters to the - * calling method. - * - * @param expression a boolean expression - * @param errorMessageTemplate a template for the exception message should the - * check fail. The message is formed by replacing each {@code %s} - * placeholder in the template with an argument. These are matched by - * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc. - * Unmatched arguments will be appended to the formatted message in square - * braces. Unmatched placeholders will be left as-is. - * @param errorMessageArgs the arguments to be substituted into the message - * template. Arguments are converted to strings using - * {@link String#valueOf(Object)}. - * @throws IllegalArgumentException if {@code expression} is false - * @throws NullPointerException if the check fails and either {@code - * errorMessageTemplate} or {@code errorMessageArgs} is null (don't let - * this happen) - */ - public static void checkArgument(boolean expression, - String errorMessageTemplate, - Object... errorMessageArgs) { - if (!expression) { - throw new IllegalArgumentException( - format(errorMessageTemplate, errorMessageArgs)); - } - } - - /** - * Ensures the truth of an expression involving the state of the calling - * instance, but not involving any parameters to the calling method. - * - * @param expression a boolean expression - * @throws IllegalStateException if {@code expression} is false - */ - public static void checkState(boolean expression) { - if (!expression) { - throw new IllegalStateException(); - } - } - - /** - * Ensures the truth of an expression involving the state of the calling - * instance, but not involving any parameters to the calling method. - * - * @param expression a boolean expression - * @param errorMessage the exception message to use if the check fails; will - * be converted to a string using {@link String#valueOf(Object)} - * @throws IllegalStateException if {@code expression} is false - */ - public static void checkState( - boolean expression, Object errorMessage) { - if (!expression) { - throw new IllegalStateException(String.valueOf(errorMessage)); - } - } - - /** - * Ensures the truth of an expression involving the state of the calling - * instance, but not involving any parameters to the calling method. - * - * @param expression a boolean expression - * @param errorMessageTemplate a template for the exception message should the - * check fail. The message is formed by replacing each {@code %s} - * placeholder in the template with an argument. These are matched by - * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc. - * Unmatched arguments will be appended to the formatted message in square - * braces. Unmatched placeholders will be left as-is. - * @param errorMessageArgs the arguments to be substituted into the message - * template. Arguments are converted to strings using - * {@link String#valueOf(Object)}. - * @throws IllegalStateException if {@code expression} is false - * @throws NullPointerException if the check fails and either {@code - * errorMessageTemplate} or {@code errorMessageArgs} is null (don't let - * this happen) - */ - public static void checkState(boolean expression, - String errorMessageTemplate, - Object... errorMessageArgs) { - if (!expression) { - throw new IllegalStateException( - format(errorMessageTemplate, errorMessageArgs)); - } - } - - /** - * Ensures that an object reference passed as a parameter to the calling - * method is not null. - * - * @param reference an object reference - * @return the non-null reference that was validated - * @throws NullPointerException if {@code reference} is null - */ - public static T checkNotNull(T reference) { - if (reference == null) { - throw new NullPointerException(); - } - return reference; - } - - /** - * Ensures that an object reference passed as a parameter to the calling - * method is not null. - * - * @param reference an object reference - * @param errorMessage the exception message to use if the check fails; will - * be converted to a string using {@link String#valueOf(Object)} - * @return the non-null reference that was validated - * @throws NullPointerException if {@code reference} is null - */ - public static T checkNotNull(T reference, Object errorMessage) { - if (reference == null) { - throw new NullPointerException(String.valueOf(errorMessage)); - } - return reference; - } - - /** - * Ensures that an object reference passed as a parameter to the calling - * method is not null. - * - * @param reference an object reference - * @param errorMessageTemplate a template for the exception message should the - * check fail. The message is formed by replacing each {@code %s} - * placeholder in the template with an argument. These are matched by - * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc. - * Unmatched arguments will be appended to the formatted message in square - * braces. Unmatched placeholders will be left as-is. - * @param errorMessageArgs the arguments to be substituted into the message - * template. Arguments are converted to strings using - * {@link String#valueOf(Object)}. - * @return the non-null reference that was validated - * @throws NullPointerException if {@code reference} is null - */ - public static T checkNotNull(T reference, - String errorMessageTemplate, - Object... errorMessageArgs) { - if (reference == null) { - // If either of these parameters is null, the right thing happens anyway - throw new NullPointerException( - format(errorMessageTemplate, errorMessageArgs)); - } - return reference; - } - - /* - * All recent hotspots (as of 2009) *really* like to have the natural code - * - * if (guardExpression) { - * throw new BadException(messageExpression); - * } - * - * refactored so that messageExpression is moved to a separate - * String-returning method. - * - * if (guardExpression) { - * throw new BadException(badMsg(...)); - * } - * - * The alternative natural refactorings into void or Exception-returning - * methods are much slower. This is a big deal - we're talking factors of - * 2-8 in microbenchmarks, not just 10-20%. (This is a hotspot optimizer - * bug, which should be fixed, but that's a separate, big project). - * - * The coding pattern above is heavily used in java.util, e.g. in ArrayList. - * There is a RangeCheckMicroBenchmark in the JDK that was used to test this. - * - * But the methods in this class want to throw different exceptions, - * depending on the args, so it appears that this pattern is not directly - * applicable. But we can use the ridiculous, devious trick of throwing an - * exception in the middle of the construction of another exception. - * Hotspot is fine with that. - */ - - /** - * Ensures that {@code index} specifies a valid element in an array, - * list or string of size {@code size}. An element index may range from zero, - * inclusive, to {@code size}, exclusive. - * - * @param index a user-supplied index identifying an element of an array, list - * or string - * @param size the size of that array, list or string - * @return the value of {@code index} - * @throws IndexOutOfBoundsException if {@code index} is negative or is not - * less than {@code size} - * @throws IllegalArgumentException if {@code size} is negative - */ - public static int checkElementIndex(int index, int size) { - return checkElementIndex(index, size, "index"); - } - - /** - * Ensures that {@code index} specifies a valid element in an array, - * list or string of size {@code size}. An element index may range from zero, - * inclusive, to {@code size}, exclusive. - * - * @param index a user-supplied index identifying an element of an array, list - * or string - * @param size the size of that array, list or string - * @param desc the text to use to describe this index in an error message - * @return the value of {@code index} - * @throws IndexOutOfBoundsException if {@code index} is negative or is not - * less than {@code size} - * @throws IllegalArgumentException if {@code size} is negative - */ - public static int checkElementIndex( - 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)); - } - return index; - } - - private static String badElementIndex(int index, int size, String desc) { - if (index < 0) { - return format("%s (%s) must not be negative", desc, index); - } else if (size < 0) { - throw new IllegalArgumentException("negative size: " + size); - } else { // index >= size - return format("%s (%s) must be less than size (%s)", desc, index, size); - } - } - - /** - * Ensures that {@code index} specifies a valid position in an array, - * list or string of size {@code size}. A position index may range from zero - * to {@code size}, inclusive. - * - * @param index a user-supplied index identifying a position in an array, list - * or string - * @param size the size of that array, list or string - * @return the value of {@code index} - * @throws IndexOutOfBoundsException if {@code index} is negative or is - * greater than {@code size} - * @throws IllegalArgumentException if {@code size} is negative - */ - public static int checkPositionIndex(int index, int size) { - return checkPositionIndex(index, size, "index"); - } - - /** - * Ensures that {@code index} specifies a valid position in an array, - * list or string of size {@code size}. A position index may range from zero - * to {@code size}, inclusive. - * - * @param index a user-supplied index identifying a position in an array, list - * or string - * @param size the size of that array, list or string - * @param desc the text to use to describe this index in an error message - * @return the value of {@code index} - * @throws IndexOutOfBoundsException if {@code index} is negative or is - * greater than {@code size} - * @throws IllegalArgumentException if {@code size} is negative - */ - public static int checkPositionIndex( - 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)); - } - return index; - } - - private static String badPositionIndex(int index, int size, String desc) { - if (index < 0) { - return format("%s (%s) must not be negative", desc, index); - } else if (size < 0) { - throw new IllegalArgumentException("negative size: " + size); - } else { // index > size - return format("%s (%s) must not be greater than size (%s)", - desc, index, size); - } - } - - /** - * Ensures that {@code start} and {@code end} specify a valid positions - * in an array, list or string of size {@code size}, and are in order. A - * position index may range from zero to {@code size}, inclusive. - * - * @param start a user-supplied index identifying a starting position in an - * array, list or string - * @param end a user-supplied index identifying a ending position in an array, - * list or string - * @param size the size of that array, list or string - * @throws IndexOutOfBoundsException if either index is negative or is - * greater than {@code size}, or if {@code end} is less than {@code start} - * @throws IllegalArgumentException if {@code size} is negative - */ - public static void checkPositionIndexes(int start, int end, int size) { - // Carefully optimized for execution by hotspot (explanatory comment above) - if (start < 0 || end < start || end > size) { - throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size)); - } - } - - private static String badPositionIndexes(int start, int end, int size) { - if (start < 0 || start > size) { - return badPositionIndex(start, size, "start index"); - } - if (end < 0 || end > size) { - return badPositionIndex(end, size, "end index"); - } - // end < start - return format("end index (%s) must not be less than start index (%s)", - end, start); - } - - /** - * Substitutes each {@code %s} in {@code template} with an argument. These - * are matched by position - the first {@code %s} gets {@code args[0]}, etc. - * If there are more arguments than placeholders, the unmatched arguments will - * be appended to the end of the formatted message in square braces. - * - * @param template a non-null string containing 0 or more {@code %s} - * placeholders. - * @param args the arguments to be substituted into the message - * template. Arguments are converted to strings using - * {@link String#valueOf(Object)}. Arguments can be null. - */ - static String format(String template, Object... args) { - template = String.valueOf(template); // null -> "null" - - // start substituting the arguments into the '%s' placeholders - StringBuilder builder = new StringBuilder( - template.length() + 16 * args.length); - int templateStart = 0; - int i = 0; - while (i < args.length) { - int placeholderStart = template.indexOf("%s", templateStart); - if (placeholderStart == -1) { - break; - } - builder.append(template.substring(templateStart, placeholderStart)); - builder.append(args[i++]); - templateStart = placeholderStart + 2; - } - builder.append(template.substring(templateStart)); - - // if we run out of placeholders, append the extra args in square braces - if (i < args.length) { - builder.append(" ["); - builder.append(args[i++]); - while (i < args.length) { - builder.append(", "); - builder.append(args[i++]); - } - builder.append(']'); - } - - return builder.toString(); - } -} diff --git a/src/main/java/com/kpelykh/docker/client/DockerClient.java b/src/main/java/com/kpelykh/docker/client/DockerClient.java deleted file mode 100644 index 101d7209..00000000 --- a/src/main/java/com/kpelykh/docker/client/DockerClient.java +++ /dev/null @@ -1,954 +0,0 @@ -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.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.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 { - - private static final Logger LOGGER = LoggerFactory.getLogger(DockerClient.class); - - private Client client; - 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; - } - - - /** - * * 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/model/BoundHostVolumes.java b/src/main/java/com/kpelykh/docker/client/model/BoundHostVolumes.java deleted file mode 100644 index 9a912439..00000000 --- a/src/main/java/com/kpelykh/docker/client/model/BoundHostVolumes.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * 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/HostConfig.java b/src/main/java/com/kpelykh/docker/client/model/HostConfig.java deleted file mode 100644 index dc7d4258..00000000 --- a/src/main/java/com/kpelykh/docker/client/model/HostConfig.java +++ /dev/null @@ -1,180 +0,0 @@ -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 deleted file mode 100644 index 7f5f1606..00000000 --- a/src/main/java/com/kpelykh/docker/client/model/IBuilder.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.kpelykh.docker.client.model; - -/** - * Created by ben on 12/12/13. - */ -public interface IBuilder { - - T build(); -} diff --git a/src/test/java/com/kpelykh/docker/client/test/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java similarity index 61% rename from src/test/java/com/kpelykh/docker/client/test/AbstractDockerClientTest.java rename to src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index d8313ca4..9adecd30 100644 --- a/src/test/java/com/kpelykh/docker/client/test/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -1,8 +1,9 @@ -package com.kpelykh.docker.client.test; +package com.github.dockerjava.client; -import com.kpelykh.docker.client.DockerClient; -import com.kpelykh.docker.client.DockerException; +import com.github.dockerjava.client.DockerClient; +import com.github.dockerjava.client.DockerException; import com.sun.jersey.api.client.ClientResponse; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; @@ -10,6 +11,8 @@ import java.io.IOException; import java.lang.reflect.Method; +import java.net.DatagramSocket; +import java.net.ServerSocket; import java.util.ArrayList; import java.util.List; @@ -26,13 +29,12 @@ public abstract class AbstractDockerClientTest extends Assert { 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("Connecting to Docker server"); + dockerClient = new DockerClient(); LOG.info("Pulling image 'busybox'"); // need to block until image is pulled completely - logResponseStream(dockerClient.pull("busybox")); + logResponseStream(dockerClient.pullImageCmd("busybox").exec()); @@ -58,9 +60,9 @@ 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); + dockerClient.stopContainerCmd(container).exec(); + dockerClient.killContainerCmd(container).exec(); + dockerClient.removeContainerCmd(container).exec(); } catch (DockerException ignore) { } } @@ -68,7 +70,7 @@ public void afterMethod(ITestResult result) { for (String image : tmpImgs) { LOG.info("Cleaning up temporary image {}", image); try { - dockerClient.removeImage(image); + dockerClient.removeImageCmd(image).exec(); } catch (DockerException ignore) { } } @@ -88,5 +90,44 @@ protected String logResponseStream(ClientResponse response) { LOG.info("Container log: {}", responseString); return responseString; } + + // 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; + } } diff --git a/src/test/java/com/github/dockerjava/client/DockerClientTest.java b/src/test/java/com/github/dockerjava/client/DockerClientTest.java new file mode 100644 index 00000000..79f651c3 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/DockerClientTest.java @@ -0,0 +1,72 @@ +package com.github.dockerjava.client; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +import java.lang.reflect.Method; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.ITestResult; +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 com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; + +/** + * Unit test for DockerClient. + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + */ +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); + } + + + @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); + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withCmd(commands).exec(); + dockerClient.startContainerCmd(container.getId()); + tmpContainers.add(container.getId()); + int exitcode = dockerClient.waitContainerCmd(container.getId()).exec(); + assertThat(exitcode, equalTo(0)); + } + } + + +} \ No newline at end of file diff --git a/src/test/java/com/kpelykh/docker/client/test/DockerClientAuthTest.java b/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java similarity index 77% rename from src/test/java/com/kpelykh/docker/client/test/DockerClientAuthTest.java rename to src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java index 8c7fc4fa..4ccac663 100644 --- a/src/test/java/com/kpelykh/docker/client/test/DockerClientAuthTest.java +++ b/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java @@ -1,6 +1,7 @@ -package com.kpelykh.docker.client.test; +package com.github.dockerjava.client.command; -import com.kpelykh.docker.client.DockerException; +import com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; import com.sun.jersey.api.client.UniformInterfaceException; import org.hamcrest.Matchers; @@ -11,7 +12,7 @@ import static org.hamcrest.MatcherAssert.assertThat; -public class DockerClientAuthTest extends AbstractDockerClientTest { +public class AuthCmdTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { @@ -34,14 +35,14 @@ public void afterMethod(ITestResult result) { @Test public void testAuth() throws Exception { - dockerClient.auth(); + dockerClient.authCmd().exec(); } @Test public void testAuthInvalid() throws Exception { System.setProperty("docker.io.password", "garbage"); try { - dockerClient.auth(); + dockerClient.authCmd().exec(); fail(); } catch (DockerException e) { assertThat(e.getCause(), Matchers.instanceOf(UniformInterfaceException.class)); diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java new file mode 100644 index 00000000..11e87aad --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java @@ -0,0 +1,230 @@ +package com.github.dockerjava.client.command; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.lang.reflect.Method; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.io.LineIterator; +import org.apache.commons.lang.StringUtils; +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.ContainerInspectResponse; +import com.github.dockerjava.client.model.ImageInspectResponse; +import com.github.dockerjava.client.model.Ports; +import com.sun.jersey.api.client.ClientResponse; + +public class BuildImageCmdTest 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 testNginxDockerfileBuilder() throws DockerException, + IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("nginx").getFile()); + + ClientResponse response = dockerClient.buildImageCmd(baseDir).exec(); + + 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 + .inspectImageCmd(imageId).exec(); + 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"); + } + + @Test + public void testDockerBuilderAddFileInSubfolder() throws DockerException, + IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("testAddFileInSubfolder").getFile()); + dockerfileBuild(baseDir, "Successfully executed testrun.sh"); + } + + @Test + public void testDockerBuilderAddFolder() throws DockerException, + IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("testAddFolder").getFile()); + dockerfileBuild(baseDir, "Successfully executed testAddFolder.sh"); + } + + private String dockerfileBuild(File baseDir, String expectedText) + throws DockerException, IOException { + + // Build image + ClientResponse response = dockerClient.buildImageCmd(baseDir).exec(); + + 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 + ContainerCreateResponse container = dockerClient.createContainerCmd( + imageId).exec(); + + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + + dockerClient.startContainerCmd(container.getId()).exec(); + dockerClient.waitContainerCmd(container.getId()).exec(); + + tmpContainers.add(container.getId()); + + // Log container + ClientResponse logResponse = logContainer(container + .getId()); + + assertThat(logResponseStream(logResponse), containsString(expectedText)); + + return container.getId(); + } + + + private ClientResponse logContainer(String containerId) { + return dockerClient.logContainerCmd(containerId).withStdErr().withStdOut().exec(); + } + + @Test + public void testNetCatDockerfileBuilder() throws DockerException, + IOException, InterruptedException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("netcat").getFile()); + + ClientResponse response = dockerClient.buildImageCmd(baseDir).exec(); + + 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 + .inspectImageCmd(imageId).exec(); + assertThat(imageInspectResponse, not(nullValue())); + LOG.info("Image Inspect: {}", imageInspectResponse.toString()); + tmpImgs.add(imageInspectResponse.getId()); + + ContainerCreateResponse container = dockerClient.createContainerCmd( + imageInspectResponse.getId()).exec(); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainerCmd(container.getId()).exec(); + tmpContainers.add(container.getId()); + + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + 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.stopContainerCmd(container.getId()).withTimeout(0).exec(); + + } +} \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java new file mode 100644 index 00000000..631b5ddf --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java @@ -0,0 +1,77 @@ +package com.github.dockerjava.client.command; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; +import static org.testinfected.hamcrest.jpa.HasFieldWithValue.hasField; + +import java.lang.reflect.Method; + +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.ImageInspectResponse; + +public class CommitCmdTest 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 commit() throws DockerException { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withCmd(new String[] { "touch", "/test" }).exec(); + + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainerCmd(container.getId()).exec(); + tmpContainers.add(container.getId()); + + LOG.info("Commiting container: {}", container.toString()); + String imageId = dockerClient + .commitCmd(container.getId()).exec(); + tmpImgs.add(imageId); + + ImageInspectResponse imageInspectResponse = dockerClient + .inspectImageCmd(imageId).exec(); + LOG.info("Image Inspect: {}", imageInspectResponse.toString()); + + assertThat(imageInspectResponse, + hasField("container", startsWith(container.getId()))); + assertThat(imageInspectResponse.getContainerConfig().getImage(), + equalTo("busybox")); + + ImageInspectResponse busyboxImg = dockerClient.inspectImageCmd("busybox").exec(); + + assertThat(imageInspectResponse.getParent(), + equalTo(busyboxImg.getId())); + } + +} diff --git a/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java b/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java new file mode 100644 index 00000000..697c08c0 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java @@ -0,0 +1,70 @@ +package com.github.dockerjava.client.command; + +import static ch.lambdaj.Lambda.selectUnique; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; +import static org.testinfected.hamcrest.jpa.HasFieldWithValue.hasField; + +import java.lang.reflect.Method; +import java.util.List; + +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ChangeLog; +import com.github.dockerjava.client.model.ContainerCreateResponse; + +public class ContainerDiffCmdTest 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 testDiff() throws DockerException { + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withCmd("touch", "/test" ).exec(); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainerCmd(container.getId()).exec(); + boolean add = tmpContainers.add(container.getId()); + int exitCode = dockerClient.waitContainerCmd(container.getId()).exec(); + assertThat(exitCode, equalTo(0)); + + List filesystemDiff = dockerClient.containerDiffCmd(container.getId()).exec(); + LOG.info("Container DIFF: {}", filesystemDiff.toString()); + + assertThat(filesystemDiff.size(), equalTo(1)); + ChangeLog testChangeLog = selectUnique(filesystemDiff, + hasField("path", equalTo("/test"))); + + assertThat(testChangeLog, hasField("path", equalTo("/test"))); + assertThat(testChangeLog, hasField("kind", equalTo(1))); + } + + +} diff --git a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java new file mode 100644 index 00000000..020fce7e --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java @@ -0,0 +1,65 @@ +package com.github.dockerjava.client.command; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; + +import java.lang.reflect.Method; + +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.ContainerInspectResponse; + +public class CreateContainerCmdTest 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 createContainer() throws DockerException { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withVolumes("/var/log").withCmd(new String[] { "true" }).exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); + + LOG.info("Inspect container {}", containerInspectResponse.getConfig().getVolumes()); + + assertThat(containerInspectResponse.getConfig().getVolumes().keySet(), contains("/var/log")); + + tmpContainers.add(container.getId()); + } + + + +} diff --git a/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java b/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java new file mode 100644 index 00000000..a44e6872 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java @@ -0,0 +1,55 @@ +package com.github.dockerjava.client.command; + +import java.lang.reflect.Method; + +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.Info; + +public class InfoCmdTest 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 info() throws DockerException { + Info dockerInfo = dockerClient.infoCmd().exec(); + 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()); + } + + +} diff --git a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java new file mode 100644 index 00000000..db0b75e9 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java @@ -0,0 +1,77 @@ +package com.github.dockerjava.client.command; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; + +import java.lang.reflect.Method; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.ContainerInspectResponse; + +public class KillContainerCmdTest extends AbstractDockerClientTest { + + public static final Logger LOG = LoggerFactory + .getLogger(KillContainerCmdTest.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 testKillContainer() throws DockerException { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainerCmd(container.getId()).exec(); + tmpContainers.add(container.getId()); + + LOG.info("Killing container: {}", container.getId()); + dockerClient.killContainerCmd(container.getId()).exec(); + + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + LOG.info("Container Inspect: {}", containerInspectResponse.toString()); + + assertThat(containerInspectResponse.getState().running, + is(equalTo(false))); + assertThat(containerInspectResponse.getState().exitCode, + not(equalTo(0))); + + } + +} diff --git a/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java b/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java new file mode 100644 index 00000000..a5fd5cbf --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java @@ -0,0 +1,109 @@ +package com.github.dockerjava.client.command; + +import static ch.lambdaj.Lambda.filter; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.testinfected.hamcrest.jpa.HasFieldWithValue.hasField; + +import java.lang.reflect.Method; +import java.util.List; + +import org.hamcrest.Matcher; +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.Container; +import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.ContainerInspectResponse; + +public class ListContainersCmdTest 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 testListContainers() throws DockerException { + + String testImage = "hackmann/empty"; + + LOG.info("Pulling image 'hackmann/empty'"); + // need to block until image is pulled completely + logResponseStream(dockerClient.pullImageCmd(testImage).exec()); + tmpImgs.add(testImage); + + List containers = dockerClient.listContainersCmd().withShowAll(true).exec(); + assertThat(containers, notNullValue()); + LOG.info("Container List: {}", containers); + + int size = containers.size(); + + ContainerCreateResponse container1 = dockerClient + .createContainerCmd(testImage).withCmd(new String[] { "echo" }).exec(); + + assertThat(container1.getId(), not(isEmptyString())); + + ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container1.getId()).exec(); + + assertThat(containerInspectResponse.getConfig().getImage(), is(equalTo(testImage))); + + + dockerClient.startContainerCmd(container1.getId()).exec(); + tmpContainers.add(container1.getId()); + + LOG.info("container id: " + container1.getId()); + + List containers2 = dockerClient.listContainersCmd().withShowAll(true).exec(); + + 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")); + } + + + +} diff --git a/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java b/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java new file mode 100644 index 00000000..68c8ed01 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java @@ -0,0 +1,66 @@ +package com.github.dockerjava.client.command; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; + +import java.lang.reflect.Method; +import java.util.List; + +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.Image; +import com.github.dockerjava.client.model.Info; + +public class ListImagesCmdTest 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 listImages() throws DockerException { + List images = dockerClient.listImagesCmd().withShowAll(true).exec(); + assertThat(images, notNullValue()); + LOG.info("Images List: {}", images); + Info info = dockerClient.infoCmd().exec(); + + 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())); + } + + +} diff --git a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java new file mode 100644 index 00000000..d20f738e --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java @@ -0,0 +1,75 @@ +package com.github.dockerjava.client.command; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; + +import java.io.IOException; +import java.lang.reflect.Method; + +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.ContainerInspectResponse; +import com.sun.jersey.api.client.ClientResponse; + +public class LogContainerCmdTest 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 logs() throws DockerException, IOException { + + String snippet = "hello world"; + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withCmd("/bin/echo", snippet).exec(); + + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + + dockerClient.startContainerCmd(container.getId()).exec(); + tmpContainers.add(container.getId()); + + int exitCode = dockerClient.waitContainerCmd(container.getId()).exec(); + + assertThat(exitCode, equalTo(0)); + + ClientResponse response = dockerClient.logContainerCmd(container.getId()).withStdErr().withStdOut().exec(); + + assertThat(logResponseStream(response), endsWith(snippet)); + } + + +} diff --git a/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java new file mode 100644 index 00000000..e4c77178 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java @@ -0,0 +1,90 @@ +package com.github.dockerjava.client.command; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.hamcrest.Matchers.notNullValue; + +import java.io.IOException; +import java.lang.reflect.Method; + +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ImageInspectResponse; +import com.github.dockerjava.client.model.Info; +import com.sun.jersey.api.client.ClientResponse; + +public class PullImageCmdTest 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 testPullImage() throws DockerException, IOException { + Info info = dockerClient.infoCmd().exec(); + LOG.info("Client info: {}", info.toString()); + + int imgCount = info.getImages(); + LOG.info("imgCount1: {}", imgCount); + + // 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.removeImageCmd(testImage).exec(); + + info = dockerClient.infoCmd().exec(); + LOG.info("Client info: {}", info.toString()); + + imgCount = info.getImages(); + LOG.info("imgCount2: {}", imgCount); + + + LOG.info("Pulling image: {}", testImage); + + tmpImgs.add(testImage); + ClientResponse response = dockerClient.pullImageCmd(testImage).exec(); + + assertThat(logResponseStream(response), + containsString("Download complete")); + + info = dockerClient.infoCmd().exec(); + LOG.info("Client info after pull, {}", info.toString()); + + assertThat(imgCount, lessThanOrEqualTo(info.getImages())); + + ImageInspectResponse imageInspectResponse = dockerClient + .inspectImageCmd(testImage).exec(); + LOG.info("Image Inspect: {}", imageInspectResponse.toString()); + assertThat(imageInspectResponse, notNullValue()); + } + +} diff --git a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java new file mode 100644 index 00000000..cc68cd46 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java @@ -0,0 +1,84 @@ +package com.github.dockerjava.client.command; + + +import static com.github.dockerjava.client.DockerClient.asString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; + +import java.lang.reflect.Method; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; + +public class PushImageCmdTest extends AbstractDockerClientTest { + + public static final Logger LOG = LoggerFactory + .getLogger(PushImageCmdTest.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 { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withCmd("true").exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + tmpContainers.add(container.getId()); + + LOG.info("Commiting container: {}", container.toString()); + String imageId = dockerClient.commitCmd(container.getId()).withRepo(username + "/busybox").exec(); + + logResponseStream(dockerClient.pushImageCmd(username + "/busybox").exec()); + + dockerClient.removeImageCmd(imageId).exec(); + + assertThat(asString(dockerClient.pullImageCmd(username + "/busybox").exec()), not(containsString("404"))); + + tmpImgs.add(username + "/busybox"); + } + + @Test + public void testNotExistentImage() throws Exception { + + assertThat(logResponseStream(dockerClient.pushImageCmd(username + "/xxx").exec()), containsString("error")); + } + + +} + diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java new file mode 100644 index 00000000..9a2a5d6d --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java @@ -0,0 +1,76 @@ +package com.github.dockerjava.client.command; + + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; +import static org.testinfected.hamcrest.jpa.HasFieldWithValue.hasField; + +import java.lang.reflect.Method; +import java.util.List; + +import org.hamcrest.Matcher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; + +public class RemoveContainerCmdTest extends AbstractDockerClientTest { + + public static final Logger LOG = LoggerFactory + .getLogger(RemoveContainerCmdTest.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 removeContainer() throws DockerException { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withCmd("true").exec(); + + dockerClient.startContainerCmd(container.getId()).exec(); + dockerClient.waitContainerCmd(container.getId()).exec(); + tmpContainers.add(container.getId()); + + LOG.info("Removing container: {}", container.getId()); + dockerClient.removeContainerCmd(container.getId()).exec(); + + List containers2 = dockerClient.listContainersCmd().withShowAll(true).exec(); + Matcher matcher = not(hasItem(hasField("id", + startsWith(container.getId())))); + assertThat(containers2, matcher); + + } + + +} + diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java new file mode 100644 index 00000000..9b9bdba0 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java @@ -0,0 +1,85 @@ +package com.github.dockerjava.client.command; + + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; +import static org.testinfected.hamcrest.jpa.HasFieldWithValue.hasField; + +import java.lang.reflect.Method; +import java.util.List; + +import org.hamcrest.Matcher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; + +public class RemoveImageCmdTest extends AbstractDockerClientTest { + + public static final Logger LOG = LoggerFactory + .getLogger(RemoveImageCmdTest.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 testRemoveImage() throws DockerException, InterruptedException { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withCmd("touch", "/test").exec(); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainerCmd(container.getId()).exec(); + tmpContainers.add(container.getId()); + + LOG.info("Commiting container {}", container.toString()); + String imageId = dockerClient + .commitCmd(container.getId()).exec(); + tmpImgs.add(imageId); + + dockerClient.stopContainerCmd(container.getId()).exec(); + dockerClient.killContainerCmd(container.getId()).exec(); + dockerClient.removeContainerCmd(container.getId()).exec(); + + tmpContainers.remove(container.getId()); + LOG.info("Removing image: {}", imageId); + dockerClient.removeImageCmd(imageId).exec(); + + List containers = dockerClient.listContainersCmd().withShowAll(true).exec(); + Matcher matcher = not(hasItem(hasField("id", startsWith(imageId)))); + assertThat(containers, matcher); + } + + +} + diff --git a/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java new file mode 100644 index 00000000..826c57b4 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java @@ -0,0 +1,79 @@ +package com.github.dockerjava.client.command; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; + +import java.lang.reflect.Method; + +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.ContainerInspectResponse; + +public class RestartContainerCmdTest 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 restartContainer() throws DockerException { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainerCmd(container.getId()).exec(); + tmpContainers.add(container.getId()); + + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + LOG.info("Container Inspect: {}", containerInspectResponse.toString()); + + String startTime = containerInspectResponse.getState().startedAt; + + dockerClient.restartContainerCmd(container.getId()).withtTimeout(2).exec(); + + ContainerInspectResponse containerInspectResponse2 = dockerClient + .inspectContainerCmd(container.getId()).exec(); + LOG.info("Container Inspect After Restart: {}", + containerInspectResponse2.toString()); + + String startTime2 = containerInspectResponse2.getState().startedAt; + + assertThat(startTime, not(equalTo(startTime2))); + + assertThat(containerInspectResponse.getState().running, + is(equalTo(true))); + + dockerClient.killContainerCmd(container.getId()).exec(); + } + + +} diff --git a/src/test/java/com/github/dockerjava/client/command/SearchImagesCmdTest.java b/src/test/java/com/github/dockerjava/client/command/SearchImagesCmdTest.java new file mode 100644 index 00000000..73ed9e35 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/SearchImagesCmdTest.java @@ -0,0 +1,61 @@ +package com.github.dockerjava.client.command; + +import static ch.lambdaj.Lambda.filter; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.testinfected.hamcrest.jpa.HasFieldWithValue.hasField; + +import java.lang.reflect.Method; +import java.util.List; + +import org.hamcrest.Matcher; +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.SearchItem; + +public class SearchImagesCmdTest 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 searchImages() throws DockerException { + List dockerSearch = dockerClient.searchImagesCmd("busybox").exec(); + 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)); + } + + +} diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java new file mode 100644 index 00000000..5441d9db --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -0,0 +1,118 @@ +package com.github.dockerjava.client.command; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; + +import java.lang.reflect.Method; + +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.ContainerInspectResponse; + +public class StartContainerCmdTest 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 startContainerWithVolumes() throws DockerException { + + // see http://docs.docker.io/use/working_with_volumes/ + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withVolumes("/logs_from_host") + .withCmd(new String[] { "true" }).exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + assertThat(containerInspectResponse.getConfig().getVolumes().keySet(), + contains("/logs_from_host")); + + dockerClient.startContainerCmd(container.getId()).withBinds("/var/log:/logs_from_host:ro").exec(); + + dockerClient.waitContainerCmd(container.getId()).exec(); + + containerInspectResponse = dockerClient.inspectContainerCmd(container + .getId()).exec(); + + assertThat(containerInspectResponse.getVolumes().get("/logs_from_host"), + equalTo("/var/log")); + + assertThat(containerInspectResponse.getVolumesRW().get("/logs_from_host"), + equalTo(false)); + + tmpContainers.add(container.getId()); + } + + @Test + public void startContainer() throws DockerException { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withCmd(new String[] { "true" }).exec(); + + LOG.info("Created container {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + tmpContainers.add(container.getId()); + + dockerClient.startContainerCmd(container.getId()).exec(); + + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + 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())); + + assertThat(containerInspectResponse.getState().running, is(true)); + + if (!containerInspectResponse.getState().running) { + assertThat(containerInspectResponse.getState().exitCode, + is(equalTo(0))); + } + + } + + +} diff --git a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java new file mode 100644 index 00000000..c7cad166 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java @@ -0,0 +1,76 @@ +package com.github.dockerjava.client.command; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; + +import java.lang.reflect.Method; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.ContainerInspectResponse; + +public class StopContainerCmdTest extends AbstractDockerClientTest { + + public static final Logger LOG = LoggerFactory + .getLogger(StopContainerCmdTest.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 testStopContainer() throws DockerException { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainerCmd(container.getId()).exec(); + tmpContainers.add(container.getId()); + + LOG.info("Stopping container: {}", container.getId()); + dockerClient.stopContainerCmd(container.getId()).withTimeout(2).exec(); + + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + LOG.info("Container Inspect: {}", containerInspectResponse.toString()); + + assertThat(containerInspectResponse.getState().running, + is(equalTo(false))); + assertThat(containerInspectResponse.getState().exitCode, + not(equalTo(0))); + } + +} diff --git a/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java new file mode 100644 index 00000000..8df20381 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java @@ -0,0 +1,68 @@ +package com.github.dockerjava.client.command; + + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; +import static org.testinfected.hamcrest.jpa.HasFieldWithValue.hasField; + +import java.lang.reflect.Method; +import java.util.List; + +import org.apache.commons.lang.math.RandomUtils; +import org.hamcrest.Matcher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; + +public class TagImageCmdTest extends AbstractDockerClientTest { + + public static final Logger LOG = LoggerFactory + .getLogger(TagImageCmdTest.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 testTagImage() throws DockerException, InterruptedException { + String tag = String.valueOf(RandomUtils.nextInt(Integer.MAX_VALUE)); + + Integer result = dockerClient.tagImageCmd("busybox:latest", "docker-java/busybox", tag).exec(); + assertThat(result, equalTo(Integer.valueOf(201))); + + dockerClient.removeImageCmd("docker-java/busybox:" + tag).exec(); + } + +} + diff --git a/src/test/java/com/github/dockerjava/client/command/VersionCmdTest.java b/src/test/java/com/github/dockerjava/client/command/VersionCmdTest.java new file mode 100644 index 00000000..75d7c207 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/VersionCmdTest.java @@ -0,0 +1,52 @@ +package com.github.dockerjava.client.command; + +import java.lang.reflect.Method; + +import org.apache.commons.lang.StringUtils; +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.Version; + +public class VersionCmdTest 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 version() throws DockerException { + Version version = dockerClient.versionCmd().exec(); + LOG.info(version.toString()); + + assertTrue(version.getGoVersion().length() > 0); + assertTrue(version.getVersion().length() > 0); + + assertEquals(StringUtils.split(version.getVersion(), ".").length, 3); + + } + + +} diff --git a/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java new file mode 100644 index 00000000..4b443b56 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java @@ -0,0 +1,75 @@ +package com.github.dockerjava.client.command; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; + +import java.lang.reflect.Method; + +import org.testng.ITestResult; +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 com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.ContainerInspectResponse; + +public class WaitContainerCmdTest 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 testWaitContainer() throws DockerException { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withCmd("true").exec(); + + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + tmpContainers.add(container.getId()); + + dockerClient.startContainerCmd(container.getId()).exec(); + + int exitCode = dockerClient.waitContainerCmd(container.getId()).exec(); + LOG.info("Container exit code: {}", exitCode); + + assertThat(exitCode, equalTo(0)); + + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + LOG.info("Container Inspect: {}", containerInspectResponse.toString()); + + assertThat(containerInspectResponse.getState().running, + is(equalTo(false))); + assertThat(containerInspectResponse.getState().exitCode, + is(equalTo(exitCode))); + + } + + + +} diff --git a/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java b/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java deleted file mode 100644 index f6af3823..00000000 --- a/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java +++ /dev/null @@ -1,824 +0,0 @@ -package com.kpelykh.docker.client.test; - -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 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.ITestResult; -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 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 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())); - - assertThat(containerInspectResponse.getState().running, is(true)); - - if (!containerInspectResponse.getState().running) { - assertThat(containerInspectResponse.getState().exitCode, - is(equalTo(0))); - } - - } - - @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.getId(), not(isEmptyString())); - tmpContainers.add(container.getId()); - - dockerClient.startContainer(container.getId()); - - int exitCode = dockerClient.waitContainer(container.getId()); - LOG.info("Container exit code: {}", exitCode); - - assertThat(exitCode, equalTo(0)); - - ContainerInspectResponse containerInspectResponse = dockerClient - .inspectContainer(container.getId()); - LOG.info("Container Inspect: {}", containerInspectResponse.toString()); - - assertThat(containerInspectResponse.getState().running, - is(equalTo(false))); - assertThat(containerInspectResponse.getState().exitCode, - is(equalTo(exitCode))); - - } - - @Test - public void testLogs() throws DockerException, IOException { - - String snippet = "hello world"; - - ContainerConfig containerConfig = new ContainerConfig(); - containerConfig.setImage("busybox"); - containerConfig.setCmd(new String[] { "/bin/echo", snippet }); - - ContainerCreateResponse container = dockerClient - .createContainer(containerConfig); - LOG.info("Created container: {}", container.toString()); - assertThat(container.getId(), not(isEmptyString())); - - dockerClient.startContainer(container.getId()); - tmpContainers.add(container.getId()); - - int exitCode = dockerClient.waitContainer(container.getId()); - - assertThat(exitCode, equalTo(0)); - - ClientResponse response = dockerClient.logContainer(container.getId()); - - assertThat(logResponseStream(response), endsWith(snippet)); - } - - @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.getId(), not(isEmptyString())); - dockerClient.startContainer(container.getId()); - boolean add = tmpContainers.add(container.getId()); - int exitCode = dockerClient.waitContainer(container.getId()); - assertThat(exitCode, equalTo(0)); - - List filesystemDiff = dockerClient.containerDiff(container.getId()); - LOG.info("Container DIFF: {}", filesystemDiff.toString()); - - assertThat(filesystemDiff.size(), equalTo(1)); - ChangeLog testChangeLog = selectUnique(filesystemDiff, - hasField("path", equalTo("/test"))); - - assertThat(testChangeLog, hasField("path", equalTo("/test"))); - assertThat(testChangeLog, hasField("kind", equalTo(1))); - } - - @Test - public void testStopContainer() throws DockerException { - - 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()); - - LOG.info("Stopping container: {}", container.getId()); - dockerClient.stopContainer(container.getId(), 2); - - ContainerInspectResponse containerInspectResponse = dockerClient - .inspectContainer(container.getId()); - LOG.info("Container Inspect: {}", containerInspectResponse.toString()); - - assertThat(containerInspectResponse.getState().running, - is(equalTo(false))); - assertThat(containerInspectResponse.getState().exitCode, - not(equalTo(0))); - } - - @Test - public void testKillContainer() throws DockerException { - - 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()); - - LOG.info("Killing container: {}", container.getId()); - dockerClient.kill(container.getId()); - - ContainerInspectResponse containerInspectResponse = dockerClient - .inspectContainer(container.getId()); - LOG.info("Container Inspect: {}", containerInspectResponse.toString()); - - assertThat(containerInspectResponse.getState().running, - is(equalTo(false))); - assertThat(containerInspectResponse.getState().exitCode, - not(equalTo(0))); - - } - - @Test - public void restartContainer() throws DockerException { - - 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()); - - ContainerInspectResponse containerInspectResponse = dockerClient - .inspectContainer(container.getId()); - LOG.info("Container Inspect: {}", containerInspectResponse.toString()); - - String startTime = containerInspectResponse.getState().startedAt; - - dockerClient.restart(container.getId(), 2); - - ContainerInspectResponse containerInspectResponse2 = dockerClient - .inspectContainer(container.getId()); - LOG.info("Container Inspect After Restart: {}", - containerInspectResponse2.toString()); - - String startTime2 = containerInspectResponse2.getState().startedAt; - - assertThat(startTime, not(equalTo(startTime2))); - - assertThat(containerInspectResponse.getState().running, - is(equalTo(true))); - - dockerClient.kill(container.getId()); - } - - @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.getId()); - dockerClient.waitContainer(container.getId()); - tmpContainers.add(container.getId()); - - LOG.info("Removing container: {}", container.getId()); - dockerClient.removeContainer(container.getId()); - - List containers2 = dockerClient.listContainers(true); - Matcher matcher = not(hasItem(hasField("id", - startsWith(container.getId())))); - assertThat(containers2, matcher); - - } - - /* - * ################## ## IMAGES TESTS ## ################## - */ - - @Test - public void testPullImage() throws DockerException, IOException { - - // 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); - - Info info = dockerClient.info(); - LOG.info("Client info: {}", info.toString()); - - int imgCount = info.getImages(); - - LOG.info("Pulling image: {}", testImage); - - tmpImgs.add(testImage); - ClientResponse response = dockerClient.pull(testImage); - - assertThat(logResponseStream(response), containsString("Download complete")); - - info = dockerClient.info(); - LOG.info("Client info after pull, {}", info.toString()); - - // TODO: imgCount should differ (maybe a docker bug?) - assertThat(imgCount, lessThanOrEqualTo(info.getImages())); - - ImageInspectResponse imageInspectResponse = dockerClient - .inspectImage(testImage); - LOG.info("Image Inspect: {}", imageInspectResponse.toString()); - assertThat(imageInspectResponse, notNullValue()); - } - - @Test - public void commitImage() 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.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); - - 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 testDockerBuilderAddFileInSubfolder() throws DockerException, IOException { - File baseDir = new File(Thread.currentThread().getContextClassLoader() - .getResource("testAddFileInSubfolder").getFile()); - dockerfileBuild(baseDir, "Successfully executed testrun.sh"); - } - - @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 deleted file mode 100644 index 7e6d88a9..00000000 --- a/src/test/java/com/kpelykh/docker/client/test/DockerPushTest.java +++ /dev/null @@ -1,86 +0,0 @@ -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/logback.xml b/src/test/resources/logback.xml index 99f8b3d9..318af286 100644 --- a/src/test/resources/logback.xml +++ b/src/test/resources/logback.xml @@ -6,8 +6,8 @@ - - + + From 605d639ad4dfbcaafbf92c1dee47de31426012b1 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Tue, 17 Jun 2014 11:38:06 +0200 Subject: [PATCH 007/452] Update README to reflect API changes --- README.md | 48 ++++++++++++++++++++++-------------------------- 1 file changed, 22 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 9d6f7ebf..c78d3b6d 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Java API client for [Docker](http://docs.docker.io/ "Docker") -Supports a subset of the Docker Client API v1.11, Docker Server version 0.11 +Supports a subset of the Docker Client API v1.12, Docker Server version 1.0 Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/docker-java-dev "docker-java") @@ -22,62 +22,58 @@ By default Docker server is using UNIX sockets for communication with the Docker client uses TCP/IP to connect to the Docker server, so you will need to make sure that your Docker server is listening on TCP port. To allow Docker server to use TCP add the following line to /etc/default/docker - DOCKER_OPTS="-H tcp://127.0.0.1:4243 -H unix:///var/run/docker.sock" + DOCKER_OPTS="-H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock" More details setting up docket server can be found in official documentation: http://docs.docker.io/en/latest/use/basics/ Now make sure that docker is up: - $ docker -H tcp://127.0.0.1:4243 version + $ docker -H tcp://127.0.0.1:2375 version - Client version: 0.8.1 + Client version: 0.8.0 Go version (client): go1.2 - Git commit (client): a1598d1 - Server version: 0.8.1 - Git commit (server): a1598d1 - Go version (server): go1.2 - Last stable version: 0.8.1 + Git commit (client): cc3a8c8 + Server version: 1.0.0 + Git commit (server): 63fe64c + Go version (server): go1.2.1 Run build with tests: - $ mvn clean install + $ mvn clean install -DskipTests=false ## Docker-Java maven dependency: com.github.docker-java docker-java - 0.8.2 + 0.9.0-SNAPSHOT Latest SNAPSHOT is available from maven repo: https://oss.sonatype.org/content/groups/public ## Example code snippets: - DockerClient dockerClient = new DockerClient("http://localhost:4243"); + DockerClient dockerClient = new DockerClient("http://localhost:2375"); ###### Get Docker info: - Info info = dockerClient.info(); + Info info = dockerClient.infoCmd().exec(); System.out.print(info); ###### Search Docker repository: - List dockerSearch = dockerClient.search("busybox"); + List dockerSearch = dockerClient.searchImagesCmd("busybox").exec(); 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); + ContainerCreateResponse container = dockerClient.createContainerCmd("busybox").withCmd("touch", "/test").exec(); - dockerClient.startContainer(container.id); + dockerClient.startContainerCmd(container.id).exec(); - dockerClient.waitContainer(container.id); + dockerClient.waitContainerCmd(container.id).exec(); - dockerClient.stopContainer(container.id); + dockerClient.stopContainerCmd(container.id).exec(); ##### Support for UNIX sockets: @@ -92,7 +88,7 @@ user dockerClient.build(baseDir), where baseDir is a path to folder containing D File baseDir = new File("~/kpelykh/docker/netcat"); - ClientResponse response = dockerClient.build(baseDir); + ClientResponse response = dockerClient.buildImageCmd(baseDir).exec(); StringWriter logwriter = new StringWriter(); @@ -115,8 +111,8 @@ For additional examples, please look at [DockerClientTest.java](https://github.c There are a couple of configuration items, all of which have sensible defaults: -* `url` The Docker URL, e.g. `http://localhost:4243`. -* `version` The API version, e.g. `1.11`. +* `url` The Docker URL, e.g. `http://localhost:2375`. +* `version` The API version, e.g. `1.12`. * `username` Your repository username (required to push containers). * `password` Your repository password. * `email` Your repository email. @@ -126,7 +122,7 @@ There are three ways to configure, in descending order of precedence: ##### Programatic: In your application, e.g. - DockerClient docker = new DockerClient("http://localhost:4243"); + DockerClient docker = new DockerClient("http://localhost:2375"); docker.setCredentials("dockeruser", "ilovedocker", "dockeruser@github.com");` ##### System Properties: @@ -142,5 +138,5 @@ In `$HOME/.docker.io.properties`, e.g.: ##### Class Path In the class path at `/docker.io.properties`, e.g.: - docker.io.url=http://localhost:4243 + docker.io.url=http://localhost:2375 docker.io.version=1.11 From 0797cbff83b6d3ff294d17793260775ec10e4ddc Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Tue, 17 Jun 2014 11:54:14 +0200 Subject: [PATCH 008/452] Fix link to test cases --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c78d3b6d..843456bb 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,7 @@ user dockerClient.build(baseDir), where baseDir is a path to folder containing D -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") +For additional examples, please look at [Test cases](https://github.com/docker-java/docker-java/tree/master/src/test/java/com/github/dockerjava/client/command "Test cases") ## Configuration From 6b042a93d0f2a0048155a96f6f85f8676fab61a7 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Tue, 17 Jun 2014 12:05:51 +0200 Subject: [PATCH 009/452] Minor fixes --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 843456bb..c843c1b1 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ Latest SNAPSHOT is available from maven repo: https://oss.sonatype.org/content/g ##### 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. +user dockerClient.buildImageCmd(baseDir), where baseDir is a path to folder containing Dockerfile. File baseDir = new File("~/kpelykh/docker/netcat"); @@ -139,4 +139,4 @@ In `$HOME/.docker.io.properties`, e.g.: In the class path at `/docker.io.properties`, e.g.: docker.io.url=http://localhost:2375 - docker.io.version=1.11 + docker.io.version=1.12 From fe105939805209e684053d53b3a1934d151cb86e Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 17 Jun 2014 22:04:41 +0200 Subject: [PATCH 010/452] Fix issue #8 --- .../dockerjava/client/DockerClient.java | 8 +- .../client/command/AttachContainerCmd.java | 117 +++++++ .../client/command/BuildImgCmd.java | 2 +- .../client/command/LogContainerCmd.java | 35 ++- .../client/command/StartContainerCmd.java | 2 +- .../dockerjava/client/model/Container.java | 92 +++--- .../model/ContainerInspectResponse.java | 249 +++++++++------ .../dockerjava/client/model/HostConfig.java | 1 + .../github/dockerjava/client/model/Port.java | 53 ---- .../github/dockerjava/client/model/Ports.java | 286 ++++++++++-------- .../client/model/StartContainerConfig.java | 8 +- .../client/command/BuildImageCmdTest.java | 8 +- .../client/command/KillContainerCmdTest.java | 4 +- .../client/command/LogContainerCmdTest.java | 7 +- .../command/RestartContainerCmdTest.java | 6 +- .../client/command/StartContainerCmdTest.java | 40 ++- .../client/command/StopContainerCmdTest.java | 6 +- .../client/command/WaitContainerCmdTest.java | 6 +- 18 files changed, 559 insertions(+), 371 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java delete mode 100644 src/main/java/com/github/dockerjava/client/model/Port.java diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index b4779866..22e78b7c 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -17,8 +17,6 @@ import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.github.dockerjava.client.command.AbstrDockerCmd; import com.github.dockerjava.client.command.AuthCmd; @@ -34,6 +32,7 @@ import com.github.dockerjava.client.command.KillContainerCmd; import com.github.dockerjava.client.command.ListContainersCmd; import com.github.dockerjava.client.command.ListImagesCmd; +import com.github.dockerjava.client.command.AttachContainerCmd; import com.github.dockerjava.client.command.LogContainerCmd; import com.github.dockerjava.client.command.PullImageCmd; import com.github.dockerjava.client.command.PushImageCmd; @@ -287,6 +286,11 @@ public WaitContainerCmd waitContainerCmd(String containerId) { return new WaitContainerCmd(containerId).withBaseResource(baseResource); } + public AttachContainerCmd attachContainerCmd(String containerId) { + return new AttachContainerCmd(containerId).withBaseResource(baseResource); + } + + public LogContainerCmd logContainerCmd(String containerId) { return new LogContainerCmd(containerId).withBaseResource(baseResource); } diff --git a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java new file mode 100644 index 00000000..63dca1ed --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java @@ -0,0 +1,117 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.core.util.MultivaluedMapImpl; + +/** + * Attach to container + * + * @param logs - true or false, includes logs. Defaults to false. + * + * @param followStream + * - true or false, return stream. Defaults to false. + * @param stdout + * - true or false, includes stdout log. Defaults to false. + * @param stderr + * - true or false, includes stderr log. Defaults to false. + * @param timestamps + * - true or false, if true, print timestamps for every log line. + * Defaults to false. + */ +public class AttachContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory + .getLogger(AttachContainerCmd.class); + + private String containerId; + + private boolean logs, followStream, timestamps, stdout, stderr; + + public AttachContainerCmd(String containerId) { + withContainerId(containerId); + } + + public AttachContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + public AttachContainerCmd withFollowStream() { + return withFollowStream(true); + } + + public AttachContainerCmd withFollowStream(boolean followStream) { + this.followStream = followStream; + return this; + } + + public AttachContainerCmd withTimestamps(boolean timestamps) { + this.timestamps = timestamps; + return this; + } + + public AttachContainerCmd withStdOut() { + return withStdOut(true); + } + + public AttachContainerCmd withStdOut(boolean stdout) { + this.stdout = stdout; + return this; + } + + public AttachContainerCmd withStdErr() { + return withStdErr(true); + } + + public AttachContainerCmd withStdErr(boolean stderr) { + this.stderr = stderr; + return this; + } + + public AttachContainerCmd withLogs(boolean logs) { + this.logs = logs; + return this; + } + + protected ClientResponse impl() throws DockerException { + MultivaluedMap params = new MultivaluedMapImpl(); + params.add("logs", logs ? "1" : "0"); + params.add("timestamps", timestamps ? "1" : "0"); + params.add("stdout", stdout ? "1" : "0"); + params.add("stderr", stderr ? "1" : "0"); + params.add("follow", followStream ? "1" : "0"); + + WebResource webResource = baseResource.path( + 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); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java index 81754d26..b50b9eef 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -35,7 +35,7 @@ public class BuildImgCmd extends AbstrDockerCmd { private File dockerFolder; private String tag; - private boolean noCache= false; + private boolean noCache; public BuildImgCmd(File dockerFolder) { diff --git a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java index 2183e734..c924be29 100644 --- a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java @@ -17,14 +17,20 @@ /** * Get container logs * - * @param followStream - true or false, return stream. Defaults to false. - * @param stdout - true or false, includes stdout log. Defaults to false. - * @param stderr - true or false, includes stderr log. Defaults to false. - * @param timestamps - true or false, if true, print timestamps for every log line. Defaults to false. + * @param followStream + * - true or false, return stream. Defaults to false. + * @param stdout + * - true or false, includes stdout log. Defaults to false. + * @param stderr + * - true or false, includes stderr log. Defaults to false. + * @param timestamps + * - true or false, if true, print timestamps for every log line. + * Defaults to false. */ public class LogContainerCmd extends AbstrDockerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(LogContainerCmd.class); + private static final Logger LOGGER = LoggerFactory + .getLogger(LogContainerCmd.class); private String containerId; @@ -39,7 +45,7 @@ public LogContainerCmd withContainerId(String containerId) { this.containerId = containerId; return this; } - + public LogContainerCmd withFollowStream() { return withFollowStream(true); } @@ -53,7 +59,7 @@ public LogContainerCmd withTimestamps(boolean timestamps) { this.timestamps = timestamps; return this; } - + public LogContainerCmd withStdOut() { return withStdOut(true); } @@ -62,7 +68,7 @@ public LogContainerCmd withStdOut(boolean stdout) { this.stdout = stdout; return this; } - + public LogContainerCmd withStdErr() { return withStdErr(true); } @@ -72,20 +78,23 @@ public LogContainerCmd withStdErr(boolean stderr) { return this; } + + protected ClientResponse impl() throws DockerException { MultivaluedMap params = new MultivaluedMapImpl(); - params.add("logs", "1"); params.add("timestamps", timestamps ? "1" : "0"); params.add("stdout", stdout ? "1" : "0"); params.add("stderr", stderr ? "1" : "0"); - params.add("follow", followStream ? "1" : "0"); // this parameter keeps stream open indefinitely + params.add("follow", followStream ? "1" : "0"); - WebResource webResource = baseResource.path(String.format("/containers/%s/attach", containerId)) + WebResource webResource = baseResource.path( + String.format("/containers/%s/logs", containerId)) .queryParams(params); try { - LOGGER.trace("POST: {}", webResource); - return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ClientResponse.class, params); + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .get(ClientResponse.class); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 400) { throw new DockerException("bad parameter"); diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index 0470a59e..36822ce9 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -8,8 +8,8 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.github.dockerjava.client.model.LxcConf; -import com.github.dockerjava.client.model.StartContainerConfig; import com.github.dockerjava.client.model.Ports; +import com.github.dockerjava.client.model.StartContainerConfig; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; diff --git a/src/main/java/com/github/dockerjava/client/model/Container.java b/src/main/java/com/github/dockerjava/client/model/Container.java index acdb95ee..e368758d 100644 --- a/src/main/java/com/github/dockerjava/client/model/Container.java +++ b/src/main/java/com/github/dockerjava/client/model/Container.java @@ -28,19 +28,8 @@ public class Container { @JsonProperty("Status") private String status; - /* Example: - "Ports": { - "22/tcp": [ - { - "HostIp": "0.0.0.0", - "HostPort": "8022" - } - ] - } - */ - @JsonProperty("Ports") - public Ports ports; + public Port[] ports; @JsonProperty("SizeRw") private int size; @@ -71,11 +60,11 @@ public String getStatus() { return status; } - public Ports getPorts() { + public Port[] getPorts() { return ports; } - public void setPorts(Ports ports) { + public void setPorts(Port[] ports) { this.ports = ports; } @@ -91,37 +80,6 @@ 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() { @@ -131,10 +89,52 @@ public String toString() { ", image='" + image + '\'' + ", created=" + created + ", status='" + status + '\'' + - ", ports=" + ports + + ", ports=" + Arrays.toString(ports) + ", size=" + size + ", sizeRootFs=" + sizeRootFs + ", names=" + Arrays.toString(names) + '}'; } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Port { + + @JsonProperty("IP") + private String ip; + + @JsonProperty("PrivatePort") + private Integer privatePort; + + @JsonProperty("PublicPort") + private Integer publicPort; + + @JsonProperty("Type") + private String type; + + public String getIp() { + return ip; + } + + public Integer getPrivatePort() { + return privatePort; + } + + public Integer getPublicPort() { + return publicPort; + } + + public String getType() { + return type; + } + + @Override + public String toString() { + return "Port{" + + "IP='" + ip + '\'' + + ", privatePort='" + privatePort + '\'' + + ", publicPort='" + publicPort + '\'' + + ", type='" + type + '\'' + + '}'; + } + } } diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java index a90183b9..dd7a6a14 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java @@ -1,6 +1,7 @@ package com.github.dockerjava.client.model; +import java.util.Arrays; import java.util.Map; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -75,141 +76,69 @@ 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; @@ -218,22 +147,43 @@ public String getExecDriver() { public String getMountLabel() { return mountLabel; } - - public void setMountLabel(String mountLabel) { - this.mountLabel = mountLabel; - } @JsonIgnoreProperties(ignoreUnknown = true) 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; + @JsonProperty("IPAddress") private String ipAddress; + @JsonProperty("IPPrefixLen") private int ipPrefixLen; + @JsonProperty("Gateway") private String gateway; + @JsonProperty("Bridge") private String bridge; + @JsonProperty("PortMapping") private Map> portMapping; + @JsonProperty("Ports") private Ports ports; + + public String getIpAddress() { + return ipAddress; + } + + public int getIpPrefixLen() { + return ipPrefixLen; + } + + public String getGateway() { + return gateway; + } + + public String getBridge() { + return bridge; + } + + public Map> getPortMapping() { + return portMapping; + } - @Override + public Ports getPorts() { + return ports; + } + + + @Override public String toString() { return "NetworkSettings{" + "ports=" + ports + @@ -249,14 +199,38 @@ public String toString() { @JsonIgnoreProperties(ignoreUnknown = true) public class ContainerState { - @JsonProperty("Running") public boolean running; - @JsonProperty("Paused") public boolean paused; - @JsonProperty("Pid") public int pid; - @JsonProperty("ExitCode") public int exitCode; - @JsonProperty("StartedAt") public String startedAt; + @JsonProperty("Running") private boolean running; + @JsonProperty("Paused") private boolean paused; + @JsonProperty("Pid") private int pid; + @JsonProperty("ExitCode") private int exitCode; + @JsonProperty("StartedAt") private String startedAt; @JsonProperty("FinishedAt") private String finishedAt; + + public boolean isRunning() { + return running; + } + + public boolean isPaused() { + return paused; + } + + public int getPid() { + return pid; + } + + public int getExitCode() { + return exitCode; + } + + public String getStartedAt() { + return startedAt; + } + + public String getFinishedAt() { + return finishedAt; + } - @Override + @Override public String toString() { return "ContainerState{" + "running=" + running + @@ -268,5 +242,102 @@ public String toString() { '}'; } } + + @JsonIgnoreProperties(ignoreUnknown = true) + public class HostConfig { + + @JsonProperty("Binds") + private String[] binds; + + @JsonProperty("LxcConf") + private LxcConf[] lxcConf; + + @JsonProperty("PortBindings") + private Ports portBindings; + + @JsonProperty("PublishAllPorts") + private boolean publishAllPorts; + + @JsonProperty("Privileged") + private boolean privileged; + + @JsonProperty("Dns") + private String dns; + + @JsonProperty("VolumesFrom") + private String volumesFrom; + + @JsonProperty("ContainerIDFile") + private String containerIDFile; + + @JsonProperty("DnsSearch") + private String dnsSearch; + + @JsonProperty("Links") + private String[] links; + + @JsonProperty("NetworkMode") + private String networkMode; + + public String[] getBinds() { + return binds; + } + + public LxcConf[] getLxcConf() { + return lxcConf; + } + + public Ports getPortBindings() { + return portBindings; + } + + public boolean isPublishAllPorts() { + return publishAllPorts; + } + + public boolean isPrivileged() { + return privileged; + } + + public String getDns() { + return dns; + } + + public String getVolumesFrom() { + return volumesFrom; + } + + public String getContainerIDFile() { + return containerIDFile; + } + + public String getDnsSearch() { + return dnsSearch; + } + + public String[] getLinks() { + return links; + } + + public String getNetworkMode() { + return networkMode; + } + + @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 + + ", networkMode=" + networkMode + + ", dns='" + dns + '\'' + + '}'; + } + + } } diff --git a/src/main/java/com/github/dockerjava/client/model/HostConfig.java b/src/main/java/com/github/dockerjava/client/model/HostConfig.java index 7fcaf79c..d359689d 100644 --- a/src/main/java/com/github/dockerjava/client/model/HostConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/HostConfig.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; + import java.util.Arrays; /** diff --git a/src/main/java/com/github/dockerjava/client/model/Port.java b/src/main/java/com/github/dockerjava/client/model/Port.java deleted file mode 100644 index 41194ce1..00000000 --- a/src/main/java/com/github/dockerjava/client/model/Port.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.github.dockerjava.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/github/dockerjava/client/model/Ports.java b/src/main/java/com/github/dockerjava/client/model/Ports.java index 32055ed7..f3b8e3d9 100644 --- a/src/main/java/com/github/dockerjava/client/model/Ports.java +++ b/src/main/java/com/github/dockerjava/client/model/Ports.java @@ -1,132 +1,154 @@ -package com.github.dockerjava.client.model; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -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.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -/** -* 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 portNodes = oc.readTree(jsonParser); - if (portNodes.isArray()) { - for (JsonNode portNode : portNodes) { - String hostIp = portNode.get("IP").textValue(); - String hostPort = portNode.get("PublicPort").asText(); - String privatePort = portNode.get("PrivatePort").asText(); - String scheme = portNode.get("Type").textValue(); - out.addPort(new Port(scheme, privatePort, hostIp, hostPort)); - } - } - return out; - } - } - - public static class Serializer extends JsonSerializer { - - @Override - public void serialize(Ports ports, JsonGenerator jsonGen, - SerializerProvider serProvider) throws IOException, JsonProcessingException { - - jsonGen.writeStartArray(); - for(String portKey : ports.getAllPorts().keySet()){ - Port p = ports.getAllPorts().get(portKey); - jsonGen.writeStartObject(); - jsonGen.writeStringField("IP", p.hostIp); - jsonGen.writeNumberField("PrivatePort", Integer.parseInt(p.getPort())); - jsonGen.writeNumberField("PublicPort", Integer.parseInt(p.getHostPort())); - jsonGen.writeStringField("Type", p.getScheme()); - jsonGen.writeEndObject(); - } - jsonGen.writeEndArray(); - } - - } - -} \ No newline at end of file +package com.github.dockerjava.client.model; + +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.apache.commons.lang.builder.EqualsBuilder; + +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.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.node.NullNode; + + +@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); + } + + public void addPort(String full, String hostIp, String hostPort) { + addPort(makePort(full, hostIp, hostPort)); + } + + @Override + public String toString(){ + return ports.toString(); + } + + public Collection getAllPorts(){ + return ports.values(); + } + + 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); + } + + + 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; + } + + + @Override + public String toString() { + return "Port{" + + "scheme='" + scheme + '\'' + + ", port='" + port + '\'' + + ", hostIp='" + hostIp + '\'' + + ", hostPort='" + hostPort + '\'' + + '}'; + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Port) { + Port other = (Port) obj; + return new EqualsBuilder().append(scheme, other.getScheme()) + .append(port, other.getPort()) + .append(hostIp, other.getHostIp()) + .append(hostPort, other.getHostPort()).isEquals(); + } else + return super.equals(obj); + } + } + + + 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(makePort(field.getKey(), hostIp, hostPort)); + } + } + return out; + } + } + + public static class Serializer extends JsonSerializer { + + @Override + public void serialize(Ports portBindings, JsonGenerator jsonGen, + SerializerProvider serProvider) throws IOException, JsonProcessingException { + + jsonGen.writeStartObject(); + for(Port p : portBindings.getAllPorts()){ + 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(); + } + + } + +} diff --git a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java index 1bd941b1..b04d1331 100644 --- a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; + /** * * @author Konstantin Pelykh (kpelykh@gmail.com) @@ -31,9 +32,6 @@ public class StartContainerConfig { @JsonProperty("VolumesFrom") public String volumesFrom; - - - @Override public String toString() { @@ -46,5 +44,7 @@ public String toString() { ", dns='" + dns + '\'' + '}'; } - + + + } diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java index 11e87aad..5f55a725 100644 --- a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java @@ -211,15 +211,11 @@ public void testNetCatDockerfileBuilder() throws DockerException, .inspectContainerCmd(container.getId()).exec(); assertThat(containerInspectResponse.getId(), notNullValue()); - assertThat(containerInspectResponse.getNetworkSettings().ports, + assertThat(containerInspectResponse.getNetworkSettings().getPorts(), 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); + for (Ports.Port p : containerInspectResponse.getNetworkSettings().getPorts().getAllPorts()) { int port = Integer.valueOf(p.getHostPort()); LOG.info("Checking port {} is open", port); assertThat(available(port), is(false)); diff --git a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java index db0b75e9..95f246c3 100644 --- a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java @@ -67,9 +67,9 @@ public void testKillContainer() throws DockerException { .inspectContainerCmd(container.getId()).exec(); LOG.info("Container Inspect: {}", containerInspectResponse.toString()); - assertThat(containerInspectResponse.getState().running, + assertThat(containerInspectResponse.getState().isRunning(), is(equalTo(false))); - assertThat(containerInspectResponse.getState().exitCode, + assertThat(containerInspectResponse.getState().getExitCode(), not(equalTo(0))); } diff --git a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java index d20f738e..b9ac5ad7 100644 --- a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java @@ -1,14 +1,10 @@ package com.github.dockerjava.client.command; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.startsWith; import java.io.IOException; import java.lang.reflect.Method; @@ -23,7 +19,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.ContainerCreateResponse; -import com.github.dockerjava.client.model.ContainerInspectResponse; import com.sun.jersey.api.client.ClientResponse; public class LogContainerCmdTest extends AbstractDockerClientTest { @@ -49,7 +44,7 @@ public void afterMethod(ITestResult result) { } @Test - public void logs() throws DockerException, IOException { + public void attach() throws DockerException, IOException { String snippet = "hello world"; diff --git a/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java index 826c57b4..cc65457e 100644 --- a/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java @@ -56,7 +56,7 @@ public void restartContainer() throws DockerException { .inspectContainerCmd(container.getId()).exec(); LOG.info("Container Inspect: {}", containerInspectResponse.toString()); - String startTime = containerInspectResponse.getState().startedAt; + String startTime = containerInspectResponse.getState().getStartedAt(); dockerClient.restartContainerCmd(container.getId()).withtTimeout(2).exec(); @@ -65,11 +65,11 @@ public void restartContainer() throws DockerException { LOG.info("Container Inspect After Restart: {}", containerInspectResponse2.toString()); - String startTime2 = containerInspectResponse2.getState().startedAt; + String startTime2 = containerInspectResponse2.getState().getStartedAt(); assertThat(startTime, not(equalTo(startTime2))); - assertThat(containerInspectResponse.getState().running, + assertThat(containerInspectResponse.getState().isRunning(), is(equalTo(true))); dockerClient.killContainerCmd(container.getId()).exec(); diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java index 5441d9db..bf16317c 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -20,8 +20,9 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; -import com.github.dockerjava.client.model.ContainerInspectResponse; +import com.github.dockerjava.client.model.*; + + public class StartContainerCmdTest extends AbstractDockerClientTest { @@ -80,6 +81,35 @@ public void startContainerWithVolumes() throws DockerException { tmpContainers.add(container.getId()); } + @Test + public void startContainerWithPortBindings() throws DockerException { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox") + .withCmd(new String[] { "true" }).exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + ContainerInspectResponse containerInspectResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + Ports portBindings = new Ports(); + + portBindings.addPort("22/tcp", "", "11022"); + + dockerClient.startContainerCmd(container.getId()).withPortBindings(portBindings).exec(); + + containerInspectResponse = dockerClient.inspectContainerCmd(container + .getId()).exec(); + + assertThat(containerInspectResponse.getHostConfig().getPortBindings().getAllPorts(), + contains(new Ports.Port("tcp", "22", "", "11022"))); + + tmpContainers.add(container.getId()); + } + @Test public void startContainer() throws DockerException { @@ -105,10 +135,10 @@ public void startContainer() throws DockerException { assertThat(containerInspectResponse.getImageId(), not(isEmptyString())); assertThat(containerInspectResponse.getState(), is(notNullValue())); - assertThat(containerInspectResponse.getState().running, is(true)); + assertThat(containerInspectResponse.getState().isRunning(), is(true)); - if (!containerInspectResponse.getState().running) { - assertThat(containerInspectResponse.getState().exitCode, + if (!containerInspectResponse.getState().isRunning()) { + assertThat(containerInspectResponse.getState().getExitCode(), is(equalTo(0))); } diff --git a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java index c7cad166..96059a85 100644 --- a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java @@ -67,10 +67,8 @@ public void testStopContainer() throws DockerException { .inspectContainerCmd(container.getId()).exec(); LOG.info("Container Inspect: {}", containerInspectResponse.toString()); - assertThat(containerInspectResponse.getState().running, - is(equalTo(false))); - assertThat(containerInspectResponse.getState().exitCode, - not(equalTo(0))); + assertThat(containerInspectResponse.getState().isRunning(), is(equalTo(false))); + assertThat(containerInspectResponse.getState().getExitCode(), not(equalTo(0))); } } diff --git a/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java index 4b443b56..0fd5a328 100644 --- a/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java @@ -63,10 +63,8 @@ public void testWaitContainer() throws DockerException { .inspectContainerCmd(container.getId()).exec(); LOG.info("Container Inspect: {}", containerInspectResponse.toString()); - assertThat(containerInspectResponse.getState().running, - is(equalTo(false))); - assertThat(containerInspectResponse.getState().exitCode, - is(equalTo(exitCode))); + assertThat(containerInspectResponse.getState().isRunning(), is(equalTo(false))); + assertThat(containerInspectResponse.getState().getExitCode(), is(equalTo(exitCode))); } From 51075a42af02ee9cf9b15fbf0f31db1783be5e18 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 17 Jun 2014 23:16:44 +0200 Subject: [PATCH 011/452] fix startContainerWithPortBindings test --- .../dockerjava/client/command/CreateContainerCmd.java | 10 ++++++++++ .../dockerjava/client/model/CreateContainerConfig.java | 6 ++++++ .../client/command/StartContainerCmdTest.java | 8 ++++++-- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index d94ce153..e340a59d 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -73,6 +73,16 @@ public CreateContainerCmd withName(String name) { return this; } + public CreateContainerCmd withExposedPorts(String... exposedPorts) { + Preconditions.checkNotNull(exposedPorts, "exposedPorts was not specified"); + HashMap ports = new HashMap(); + for(String exposedPort: exposedPorts) { + ports.put(exposedPort, ""); + } + this.containerCreateConfig.withExposedPorts(ports); + return this; + } + protected ContainerCreateResponse impl() { MultivaluedMap params = new MultivaluedMapImpl(); if (name != null) { diff --git a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java index 2b267589..6994e3ab 100644 --- a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java @@ -65,6 +65,12 @@ public class CreateContainerConfig { public Map getExposedPorts() { return exposedPorts; } + + public CreateContainerConfig withExposedPorts(Map exposedPorts) { + this.exposedPorts = exposedPorts; + return this; + } + public boolean isDisableNetwork() { return disableNetwork; diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java index bf16317c..b8f9d461 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -10,6 +10,7 @@ import static org.hamcrest.Matchers.startsWith; import java.lang.reflect.Method; +import java.util.HashMap; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; @@ -86,7 +87,7 @@ public void startContainerWithPortBindings() throws DockerException { ContainerCreateResponse container = dockerClient .createContainerCmd("busybox") - .withCmd(new String[] { "true" }).exec(); + .withCmd("true").withExposedPorts("22/tcp").exec(); LOG.info("Created container {}", container.toString()); @@ -103,9 +104,12 @@ public void startContainerWithPortBindings() throws DockerException { containerInspectResponse = dockerClient.inspectContainerCmd(container .getId()).exec(); + + assertThat(containerInspectResponse.getConfig().getExposedPorts().keySet(), + contains("22/tcp")); assertThat(containerInspectResponse.getHostConfig().getPortBindings().getAllPorts(), - contains(new Ports.Port("tcp", "22", "", "11022"))); + contains(new Ports.Port("tcp", "22", "0.0.0.0", "11022"))); tmpContainers.add(container.getId()); } From e6f13f85943b258d6db1f2d477e8dc57713040f7 Mon Sep 17 00:00:00 2001 From: Yoann Dubreuil Date: Wed, 18 Jun 2014 11:38:07 +0200 Subject: [PATCH 012/452] Refactor BuildImgCmd command to accept the docker tar folder as a InputStream, so we can build it on the fly without a temporary folder. --- .../dockerjava/client/DockerClient.java | 6 +- .../client/command/BuildImgCmd.java | 73 ++++++++++++------- 2 files changed, 51 insertions(+), 28 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index 22e78b7c..b7d0993e 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -19,6 +19,7 @@ import org.apache.http.impl.conn.PoolingClientConnectionManager; import com.github.dockerjava.client.command.AbstrDockerCmd; +import com.github.dockerjava.client.command.AttachContainerCmd; import com.github.dockerjava.client.command.AuthCmd; import com.github.dockerjava.client.command.BuildImgCmd; import com.github.dockerjava.client.command.CommitCmd; @@ -32,7 +33,6 @@ import com.github.dockerjava.client.command.KillContainerCmd; import com.github.dockerjava.client.command.ListContainersCmd; import com.github.dockerjava.client.command.ListImagesCmd; -import com.github.dockerjava.client.command.AttachContainerCmd; import com.github.dockerjava.client.command.LogContainerCmd; import com.github.dockerjava.client.command.PullImageCmd; import com.github.dockerjava.client.command.PushImageCmd; @@ -326,6 +326,10 @@ public BuildImgCmd buildImageCmd(File dockerFolder) { return new BuildImgCmd(dockerFolder).withBaseResource(baseResource); } + public BuildImgCmd buildImageCmd(InputStream tarInputStream) { + return new BuildImgCmd(tarInputStream).withBaseResource(baseResource); + } + public TopContainerCmd topContainerCmd(String containerId) { return new TopContainerCmd(containerId).withBaseResource(baseResource); } diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java index b50b9eef..edaa3110 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -2,6 +2,7 @@ import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; @@ -33,7 +34,8 @@ public class BuildImgCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(BuildImgCmd.class); - private File dockerFolder; + private File dockerFolder = null; + private InputStream tarInputStream = null; private String tag; private boolean noCache; @@ -43,6 +45,11 @@ public BuildImgCmd(File dockerFolder) { this.dockerFolder = dockerFolder; } + public BuildImgCmd(InputStream tarInputStream) { + Preconditions.checkNotNull(tarInputStream, "tarInputStream is null"); + this.tarInputStream = tarInputStream; + } + public BuildImgCmd withTag(String tag) { Preconditions.checkNotNull(tag, "Tag is null"); this.tag = tag; @@ -55,17 +62,49 @@ public BuildImgCmd withNoCache(boolean noCache) { } protected ClientResponse impl() { - - Preconditions.checkArgument(dockerFolder.exists(), "Path %s doesn't exist", dockerFolder); - Preconditions.checkArgument(dockerFolder.isDirectory(), "Folder %s doesn't exist", dockerFolder); - Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(), "Dockerfile doesn't exist in " + dockerFolder); - + if (tarInputStream == null) { + File dockerFolderTar = buildDockerFolderTar(); + try { + return callDocker(FileUtils.openInputStream(dockerFolderTar)); + } catch (IOException e) { + throw new DockerException(e); + } finally { + FileUtils.deleteQuietly(dockerFolderTar); + } + } else { + return callDocker(tarInputStream); + } + } + + protected ClientResponse callDocker(final InputStream dockerFolderTarInputStream) { MultivaluedMap params = new MultivaluedMapImpl(); params.add("t", tag); if (noCache) { params.add("nocache", "true"); } + WebResource webResource = baseResource.path("/build").queryParams(params); + + try { + LOGGER.trace("POST: {}", webResource); + return webResource + .type("application/tar") + .accept(MediaType.TEXT_PLAIN) + .post(ClientResponse.class, dockerFolderTarInputStream); + } catch (UniformInterfaceException exception) { + if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + } + + protected File buildDockerFolderTar() { + Preconditions.checkArgument(dockerFolder.exists(), "Path %s doesn't exist", dockerFolder); + Preconditions.checkArgument(dockerFolder.isDirectory(), "Folder %s doesn't exist", dockerFolder); + Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(), "Dockerfile doesn't exist in " + dockerFolder); + // ARCHIVE TAR String archiveNameWithOutExtension = UUID.randomUUID().toString(); @@ -112,31 +151,11 @@ protected ClientResponse impl() { } dockerFolderTar = CompressArchiveUtil.archiveTARFiles(dockerFolder, filesToAdd, archiveNameWithOutExtension); - + return dockerFolderTar; } catch (IOException ex) { FileUtils.deleteQuietly(dockerFolderTar); throw new DockerException("Error occurred while preparing Docker context folder.", ex); } - - WebResource webResource = baseResource.path("/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); - } } private static boolean isFileResource(String resource) { From 1f84a6e08a594deeffe9c795961b32f1ac6dfc61 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 20 Jun 2014 00:22:51 +0200 Subject: [PATCH 013/452] Added model classes for exposed ports --- .../client/command/CreateContainerCmd.java | 10 +- .../client/model/ContainerConfig.java | 16 ++- .../client/model/CreateContainerConfig.java | 27 ++-- .../dockerjava/client/model/ExposedPort.java | 136 ++++++++++++++++++ .../dockerjava/client/model/ExposedPorts.java | 75 ++++++++++ .../github/dockerjava/client/model/Ports.java | 89 +++++------- .../client/command/BuildImageCmdTest.java | 10 +- .../client/command/StartContainerCmdTest.java | 29 ++-- 8 files changed, 301 insertions(+), 91 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/client/model/ExposedPort.java create mode 100644 src/main/java/com/github/dockerjava/client/model/ExposedPorts.java diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index e340a59d..b3795089 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -13,6 +13,7 @@ import com.github.dockerjava.client.NotFoundException; import com.github.dockerjava.client.model.ContainerCreateResponse; import com.github.dockerjava.client.model.CreateContainerConfig; +import com.github.dockerjava.client.model.ExposedPort; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -73,13 +74,10 @@ public CreateContainerCmd withName(String name) { return this; } - public CreateContainerCmd withExposedPorts(String... exposedPorts) { + public CreateContainerCmd withExposedPorts(ExposedPort... exposedPorts) { Preconditions.checkNotNull(exposedPorts, "exposedPorts was not specified"); - HashMap ports = new HashMap(); - for(String exposedPort: exposedPorts) { - ports.put(exposedPort, ""); - } - this.containerCreateConfig.withExposedPorts(ports); + + this.containerCreateConfig.withExposedPorts(exposedPorts); return this; } diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java index dec568e4..ebd1006d 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java @@ -1,7 +1,10 @@ package com.github.dockerjava.client.model; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + import java.util.Arrays; import java.util.Map; @@ -37,14 +40,19 @@ public class ContainerConfig { @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("ExposedPorts") private ExposedPorts exposedPorts; @JsonProperty("OnBuild") private int[] onBuild; - public Map getExposedPorts() { - return exposedPorts; + @JsonIgnore + public ExposedPort[] getExposedPorts() { + return exposedPorts.getExposedPorts(); } + + @JsonIgnore + public void setExposedPorts(ExposedPort[] exposedPorts) { + this.exposedPorts = new ExposedPorts(exposedPorts); + } public boolean isNetworkDisabled() { return networkDisabled; diff --git a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java index 6994e3ab..232d2782 100644 --- a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java @@ -1,11 +1,12 @@ package com.github.dockerjava.client.model; -import com.fasterxml.jackson.annotation.JsonProperty; - import java.util.Arrays; import java.util.Map; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + /** * * @author Konstantin Pelykh (kpelykh@gmail.com) @@ -60,15 +61,16 @@ public class CreateContainerConfig { @JsonProperty("VolumesFrom") private String volumesFrom = ""; @JsonProperty("WorkingDir") private String workingDir = ""; @JsonProperty("DisableNetwork") private boolean disableNetwork = false; - @JsonProperty("ExposedPorts") private Map exposedPorts; + @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts; - public Map getExposedPorts() { - return exposedPorts; + public CreateContainerConfig withExposedPorts(ExposedPort[] exposedPorts) { + this.exposedPorts = new ExposedPorts(exposedPorts); + return this; } - public CreateContainerConfig withExposedPorts(Map exposedPorts) { - this.exposedPorts = exposedPorts; - return this; + @JsonIgnore + public ExposedPort[] getExposedPorts() { + return exposedPorts.getExposedPorts(); } @@ -76,8 +78,6 @@ public boolean isDisableNetwork() { return disableNetwork; } - - public String getWorkingDir() { return workingDir; } public CreateContainerConfig withWorkingDir(String workingDir) { @@ -245,11 +245,6 @@ public CreateContainerConfig withVolumesFrom(String volumesFrom) { return this; } - - - - - @Override public String toString() { return "CreateContainerConfig{" + @@ -274,4 +269,6 @@ public String toString() { ", workingDir='" + workingDir + '\'' + '}'; } + + } diff --git a/src/main/java/com/github/dockerjava/client/model/ExposedPort.java b/src/main/java/com/github/dockerjava/client/model/ExposedPort.java new file mode 100644 index 00000000..b8a284c3 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/ExposedPort.java @@ -0,0 +1,136 @@ +package com.github.dockerjava.client.model; + +import java.io.IOException; +import java.util.Map.Entry; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +import com.fasterxml.jackson.annotation.JsonCreator; +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.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.node.NullNode; + +@JsonDeserialize(using = ExposedPort.Deserializer.class) +@JsonSerialize(using = ExposedPort.Serializer.class) +public class ExposedPort { + + private String scheme; + + private int port; + + public ExposedPort(String scheme, int port) { + this.scheme = scheme; + this.port = port; + } + + public String getScheme() { + return scheme; + } + + public int getPort() { + return port; + } + + public static ExposedPort tcp(int port) { + return new ExposedPort("tcp", port); + } + + public static ExposedPort parse(String serialized) { + String[] parts = serialized.split("/"); + ExposedPort out = new ExposedPort(parts[1], Integer.valueOf(parts[0])); + return out; + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof ExposedPort) { + ExposedPort other = (ExposedPort)obj; + return new EqualsBuilder().append(scheme, other.getScheme()).append(port, other.getPort()).isEquals(); + } else + return super.equals(obj); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(scheme).append(port).toHashCode(); + } + + + public static class KeySerializer extends JsonSerializer { + + @Override + public void serialize(ExposedPort exposedPort, JsonGenerator jsonGen, + SerializerProvider serProvider) throws IOException, + JsonProcessingException { + + + + jsonGen.writeFieldName(exposedPort.getPort() + "/" + + exposedPort.getScheme()); + + + } + + } + + + public static class KeyDeserializer extends com.fasterxml.jackson.databind.KeyDeserializer { + + @Override + public Object deserializeKey(String key, DeserializationContext ctxt) + throws IOException, JsonProcessingException { + String[] parts = key.split("/"); + ExposedPort out = new ExposedPort(parts[1], Integer.valueOf(parts[0])); + return out; + } + + } + + + public static class Deserializer extends JsonDeserializer { + @Override + public ExposedPort deserialize(JsonParser jsonParser, + DeserializationContext deserializationContext) + throws IOException, JsonProcessingException { + ObjectCodec oc = jsonParser.getCodec(); + JsonNode node = oc.readTree(jsonParser); + if (!node.equals(NullNode.getInstance())) { + Entry field = node.fields().next(); + String[] parts = field.getKey().split("/"); + ExposedPort out = new ExposedPort(parts[1], + Integer.valueOf(parts[0])); + return out; + } else { + return null; + } + } + } + + public static class Serializer extends JsonSerializer { + + @Override + public void serialize(ExposedPort exposedPort, JsonGenerator jsonGen, + SerializerProvider serProvider) throws IOException, + JsonProcessingException { + + jsonGen.writeStartObject(); + + jsonGen.writeFieldName(exposedPort.getPort() + "/" + + exposedPort.getScheme()); + + jsonGen.writeEndObject(); + } + + } + +} diff --git a/src/main/java/com/github/dockerjava/client/model/ExposedPorts.java b/src/main/java/com/github/dockerjava/client/model/ExposedPorts.java new file mode 100644 index 00000000..b98b0c5e --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/ExposedPorts.java @@ -0,0 +1,75 @@ +package com.github.dockerjava.client.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonIgnore; +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.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.node.NullNode; + + +@JsonSerialize(using = ExposedPorts.Serializer.class) +@JsonDeserialize(using = ExposedPorts.Deserializer.class) +public class ExposedPorts { + + private ExposedPort[] exposedPorts; + + public ExposedPorts(ExposedPort... exposedPorts) { + this.exposedPorts = exposedPorts; + } + + public ExposedPort[] getExposedPorts() { + return exposedPorts; + } + + public static class Serializer extends JsonSerializer { + + @Override + public void serialize(ExposedPorts exposedPorts, JsonGenerator jsonGen, + SerializerProvider serProvider) throws IOException, + JsonProcessingException { + + jsonGen.writeStartObject(); + for (ExposedPort exposedPort : exposedPorts.getExposedPorts()) { + jsonGen.writeFieldName(exposedPort.getPort() + "/" + + exposedPort.getScheme()); + jsonGen.writeStartObject(); + jsonGen.writeEndObject(); + } + jsonGen.writeEndObject(); + } + + } + + public static class Deserializer extends JsonDeserializer { + @Override + public ExposedPorts deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { + + List exposedPorts = new ArrayList(); + 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())) { + exposedPorts.add(ExposedPort.parse(field.getKey())); + } + } + return new ExposedPorts(exposedPorts.toArray(new ExposedPort[0])); + } + } + +} diff --git a/src/main/java/com/github/dockerjava/client/model/Ports.java b/src/main/java/com/github/dockerjava/client/model/Ports.java index f3b8e3d9..f67f01bf 100644 --- a/src/main/java/com/github/dockerjava/client/model/Ports.java +++ b/src/main/java/com/github/dockerjava/client/model/Ports.java @@ -1,13 +1,16 @@ package com.github.dockerjava.client.model; import java.io.IOException; -import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import java.util.Map.Entry; import org.apache.commons.lang.builder.EqualsBuilder; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; @@ -16,27 +19,26 @@ import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.node.NullNode; - -@JsonDeserialize(using=Ports.Deserializer.class) -@JsonSerialize(using=Ports.Serializer.class) +@JsonDeserialize(using = Ports.Deserializer.class) +@JsonSerialize(using = Ports.Serializer.class) public class Ports { - - private final Map ports = new HashMap(); + private final Map ports = new HashMap(); public Ports() { } - - public void addPort(Port port) { - ports.put(port.getPort(), port); - } - public void addPort(String full, String hostIp, String hostPort) { - addPort(makePort(full, hostIp, hostPort)); + public Ports(ExposedPort exposedPort, Host host) { + addMapping(exposedPort, host); + } + + public void addMapping(ExposedPort exposedPort, Host host) { + ports.put(exposedPort, host); } @Override @@ -44,64 +46,45 @@ public String toString(){ return ports.toString(); } - public Collection getAllPorts(){ - return ports.values(); - } - - 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); + public Map getMappings(){ + return ports; } - public static class Port{ + public static class Host { + - 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_; - } + private final int hostPort; - public String getScheme() { - return scheme; + public Host(String hostIp, int hostPort) { + this.hostIp = hostIp; + this.hostPort = hostPort; } - - public String getPort() { - return port; - } - + public String getHostIp() { return hostIp; } - public String getHostPort() { + public int getHostPort() { return hostPort; } @Override public String toString() { - return "Port{" + - "scheme='" + scheme + '\'' + - ", port='" + port + '\'' + - ", hostIp='" + hostIp + '\'' + + return "Host{" + + "hostIp='" + hostIp + '\'' + ", hostPort='" + hostPort + '\'' + '}'; } @Override public boolean equals(Object obj) { - if(obj instanceof Port) { - Port other = (Port) obj; - return new EqualsBuilder().append(scheme, other.getScheme()) - .append(port, other.getPort()) + if(obj instanceof Host) { + Host other = (Host) obj; + return new EqualsBuilder() .append(hostIp, other.getHostIp()) .append(hostPort, other.getHostPort()).isEquals(); } else @@ -120,10 +103,10 @@ public Ports deserialize(JsonParser jsonParser, DeserializationContext deseriali for (Iterator> it = node.fields(); it.hasNext();) { Map.Entry field = it.next(); - if (!field.getValue().equals(NullNode.getInstance())) { + 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(makePort(field.getKey(), hostIp, hostPort)); + int hostPort = field.getValue().get(0).get("HostPort").asInt(); + out.addMapping(ExposedPort.parse(field.getKey()), new Host(hostIp, hostPort)); } } return out; @@ -137,12 +120,12 @@ public void serialize(Ports portBindings, JsonGenerator jsonGen, SerializerProvider serProvider) throws IOException, JsonProcessingException { jsonGen.writeStartObject(); - for(Port p : portBindings.getAllPorts()){ - jsonGen.writeFieldName(p.getPort() + "/" + p.getScheme()); + for(Entry entry : portBindings.getMappings().entrySet()){ + jsonGen.writeFieldName(entry.getKey().getPort() + "/" + entry.getKey().getScheme()); jsonGen.writeStartArray(); jsonGen.writeStartObject(); - jsonGen.writeStringField("HostIp", p.hostIp); - jsonGen.writeStringField("HostPort", p.hostPort); + jsonGen.writeStringField("HostIp", entry.getValue().getHostIp()); + jsonGen.writeStringField("HostPort", "" + entry.getValue().getHostPort()); jsonGen.writeEndObject(); jsonGen.writeEndArray(); } diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java index 5f55a725..e86ab2fd 100644 --- a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java @@ -215,11 +215,11 @@ public void testNetCatDockerfileBuilder() throws DockerException, notNullValue()); // No use as such if not running on the server - for (Ports.Port p : containerInspectResponse.getNetworkSettings().getPorts().getAllPorts()) { - int port = Integer.valueOf(p.getHostPort()); - LOG.info("Checking port {} is open", port); - assertThat(available(port), is(false)); - } +// for (Ports.Port p : containerInspectResponse.getNetworkSettings().getPorts().getAllPorts()) { +// int port = Integer.valueOf(p.getHostPort()); +// LOG.info("Checking port {} is open", port); +// assertThat(available(port), is(false)); +// } dockerClient.stopContainerCmd(container.getId()).withTimeout(0).exec(); } diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java index b8f9d461..b9c70535 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -10,7 +10,7 @@ import static org.hamcrest.Matchers.startsWith; import java.lang.reflect.Method; -import java.util.HashMap; +import java.util.Arrays; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; @@ -21,7 +21,10 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.*; +import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.ContainerInspectResponse; +import com.github.dockerjava.client.model.ExposedPort; +import com.github.dockerjava.client.model.Ports; @@ -85,9 +88,12 @@ public void startContainerWithVolumes() throws DockerException { @Test public void startContainerWithPortBindings() throws DockerException { + ExposedPort tcp22 = ExposedPort.tcp(22); + ExposedPort tcp23 = ExposedPort.tcp(23); + ContainerCreateResponse container = dockerClient .createContainerCmd("busybox") - .withCmd("true").withExposedPorts("22/tcp").exec(); + .withCmd("true").withExposedPorts(tcp22, tcp23).exec(); LOG.info("Created container {}", container.toString()); @@ -98,18 +104,25 @@ public void startContainerWithPortBindings() throws DockerException { Ports portBindings = new Ports(); - portBindings.addPort("22/tcp", "", "11022"); + Ports.Host host11022 = new Ports.Host("", 11022); + Ports.Host host11023 = new Ports.Host("", 11023); + + portBindings.addMapping(tcp22, host11022); + portBindings.addMapping(tcp23, host11023); dockerClient.startContainerCmd(container.getId()).withPortBindings(portBindings).exec(); containerInspectResponse = dockerClient.inspectContainerCmd(container .getId()).exec(); - assertThat(containerInspectResponse.getConfig().getExposedPorts().keySet(), - contains("22/tcp")); + assertThat(Arrays.asList(containerInspectResponse.getConfig().getExposedPorts()), + contains(tcp22, tcp23)); - assertThat(containerInspectResponse.getHostConfig().getPortBindings().getAllPorts(), - contains(new Ports.Port("tcp", "22", "0.0.0.0", "11022"))); + assertThat(containerInspectResponse.getHostConfig().getPortBindings().getMappings().get(tcp22), + is(equalTo(new Ports.Host("0.0.0.0", 11022)))); + + assertThat(containerInspectResponse.getHostConfig().getPortBindings().getMappings().get(tcp23), + is(equalTo(new Ports.Host("0.0.0.0", 11023)))); tmpContainers.add(container.getId()); } From 4cfc7f3a73a8a532240241dc1e22133114488e7c Mon Sep 17 00:00:00 2001 From: Jonathan Pearlin Date: Wed, 2 Jul 2014 12:02:02 -0400 Subject: [PATCH 014/452] Use regular expression to match on ADD command. Dockerfile spec does not specify the whitespace format between the `ADD` command and the parameters. This change uses the whitespace character class to handle any whitespace (space, tab, etc) between the command and the parameters. --- .../dockerjava/client/command/BuildImgCmd.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java index edaa3110..7ce47447 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -8,6 +8,8 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -34,6 +36,8 @@ public class BuildImgCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(BuildImgCmd.class); + private static final Pattern ADD_PATTERN = Pattern.compile("^ADD\\s+(.*)\\s+(.*)$"); + private File dockerFolder = null; private InputStream tarInputStream = null; private String tag; @@ -122,13 +126,13 @@ protected File buildDockerFolderTar() { filesToAdd.add(dockerFile); for (String cmd : dockerFileContent) { - if (StringUtils.startsWithIgnoreCase(cmd.trim(), "ADD")) { - String addArgs[] = StringUtils.split(cmd, " \t"); - if (addArgs.length != 3) { + final Matcher matcher = ADD_PATTERN.matcher(cmd); + if (matcher.find()) { + if (matcher.groupCount() != 2) { throw new DockerException(String.format("Wrong format on line [%s]", cmd)); } - String resource = addArgs[1]; + String resource = matcher.group(1); if(isFileResource(resource)) { File src = new File(resource); From d71d9681c700c1964e5d71d1805c9f68125ae8f3 Mon Sep 17 00:00:00 2001 From: Jonathan Pearlin Date: Wed, 2 Jul 2014 12:07:38 -0400 Subject: [PATCH 015/452] Added .trim() to command string. --- .../java/com/github/dockerjava/client/command/BuildImgCmd.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java index 7ce47447..0b718798 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -126,7 +126,7 @@ protected File buildDockerFolderTar() { filesToAdd.add(dockerFile); for (String cmd : dockerFileContent) { - final Matcher matcher = ADD_PATTERN.matcher(cmd); + final Matcher matcher = ADD_PATTERN.matcher(cmd.trim()); if (matcher.find()) { if (matcher.groupCount() != 2) { throw new DockerException(String.format("Wrong format on line [%s]", cmd)); From 9570465a3d0f1bfd5242f7eb6ba1ea23d6aaa88e Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 3 Jul 2014 21:11:23 +0200 Subject: [PATCH 016/452] Introduced model classes for working with volumes --- .../client/command/CreateContainerCmd.java | 11 +- .../client/command/StartContainerCmd.java | 17 +-- .../github/dockerjava/client/model/Bind.java | 126 ++++++++++++++++++ .../github/dockerjava/client/model/Binds.java | 76 +++++++++++ .../client/model/ContainerConfig.java | 8 +- .../model/ContainerInspectResponse.java | 15 ++- .../client/model/CreateContainerConfig.java | 13 +- .../dockerjava/client/model/ExposedPort.java | 71 +++------- .../dockerjava/client/model/ExposedPorts.java | 1 - .../github/dockerjava/client/model/Ports.java | 39 +++--- .../client/model/StartContainerConfig.java | 77 +++++++++-- .../dockerjava/client/model/Volume.java | 99 ++++++++++++++ .../dockerjava/client/model/Volumes.java | 73 ++++++++++ .../client/command/BuildImageCmdTest.java | 2 - .../command/CreateContainerCmdTest.java | 3 +- .../command/RemoveContainerCmdTest.java | 1 - .../client/command/RemoveImageCmdTest.java | 1 - .../client/command/StartContainerCmdTest.java | 38 +++--- .../client/command/TagImageCmdTest.java | 8 -- 19 files changed, 539 insertions(+), 140 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/client/model/Bind.java create mode 100644 src/main/java/com/github/dockerjava/client/model/Binds.java create mode 100644 src/main/java/com/github/dockerjava/client/model/Volume.java create mode 100644 src/main/java/com/github/dockerjava/client/model/Volumes.java diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index b3795089..04753b52 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -14,6 +14,7 @@ import com.github.dockerjava.client.model.ContainerCreateResponse; import com.github.dockerjava.client.model.CreateContainerConfig; import com.github.dockerjava.client.model.ExposedPort; +import com.github.dockerjava.client.model.Volume; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -55,15 +56,9 @@ public CreateContainerCmd withCmd(String... cmd) { return this; } - public CreateContainerCmd withVolumes(String... volumes) { + public CreateContainerCmd withVolumes(Volume... volumes) { Preconditions.checkNotNull(volumes, "volumes was not specified"); - - Map _volumes = new HashMap(); - for(String volume:volumes) { - _volumes.put(volume, ""); - } - - this.containerCreateConfig.withVolumes(_volumes); + this.containerCreateConfig.withVolumes(volumes); return this; } diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index 36822ce9..bb2d102e 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -7,6 +7,7 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.client.model.Bind; import com.github.dockerjava.client.model.LxcConf; import com.github.dockerjava.client.model.Ports; import com.github.dockerjava.client.model.StartContainerConfig; @@ -33,39 +34,39 @@ public StartContainerCmd(String containerId) { withContainerId(containerId); } - public StartContainerCmd withBinds(String... binds) { - startContainerConfig.binds = binds; + public StartContainerCmd withBinds(Bind... binds) { + startContainerConfig.setBinds(binds); return this; } public StartContainerCmd withLxcConf(LxcConf[] lxcConf) { - startContainerConfig.lxcConf = lxcConf; + startContainerConfig.setLxcConf(lxcConf); return this; } public StartContainerCmd withPortBindings(Ports portBindings) { - startContainerConfig.portBindings = portBindings; + startContainerConfig.setPortBindings(portBindings); return this; } public StartContainerCmd withPrivileged(boolean privileged) { - startContainerConfig.privileged = privileged; + startContainerConfig.setPrivileged(privileged); return this; } public StartContainerCmd withPublishAllPorts(boolean publishAllPorts) { - startContainerConfig.publishAllPorts = publishAllPorts; + startContainerConfig.setPublishAllPorts(publishAllPorts); return this; } public StartContainerCmd withDns(String dns) { - startContainerConfig.dns = dns; + startContainerConfig.setDns(dns); return this; } public StartContainerCmd withVolumesFrom(String volumesFrom) { - startContainerConfig.volumesFrom = volumesFrom; + startContainerConfig.setVolumesFrom(volumesFrom); return this; } diff --git a/src/main/java/com/github/dockerjava/client/model/Bind.java b/src/main/java/com/github/dockerjava/client/model/Bind.java new file mode 100644 index 00000000..09a7c943 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/Bind.java @@ -0,0 +1,126 @@ +package com.github.dockerjava.client.model; + +import java.io.IOException; +import java.util.Map.Entry; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +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.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.node.NullNode; + +//@JsonDeserialize(using = Bind.Deserializer.class) +//@JsonSerialize(using = Bind.Serializer.class) +public class Bind { + + private String path; + + private Volume volume; + + private boolean readOnly = false; + + public Bind(String path, Volume volume) { + this(path, volume, false); + } + + public Bind(String path, Volume volume, boolean readOnly) { + this.path = path; + this.volume = volume; + this.readOnly = readOnly; + } + + public String getPath() { + return path; + } + + public Volume getVolume() { + return volume; + } + + public boolean isReadOnly() { + return readOnly; + } + + public static Bind parse(String serialized) { + try { + String[] parts = serialized.split(":"); + switch(parts.length) { + case 2: { + return new Bind(parts[0], Volume.parse(parts[1])); + } + case 3: { + if("rw".equals(parts[3].toLowerCase())) + return new Bind(parts[0], Volume.parse(parts[1]), true); + else throw new RuntimeException("Error parsing Bind '" + serialized + "'"); + } + default: { + throw new RuntimeException("Error parsing Bind '" + serialized + "'"); + } + } + } catch (Exception e) { + throw new RuntimeException("Error parsing Bind '" + serialized + "'"); + } + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Bind) { + Bind other = (Bind) obj; + return new EqualsBuilder().append(path, other.getPath()).append(volume, other.getVolume()).append(readOnly, other.isReadOnly()) + .isEquals(); + } else + return super.equals(obj); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(path).append(volume).append(readOnly).toHashCode(); + } + + public static class Serializer extends JsonSerializer { + + @Override + public void serialize(Bind bind, JsonGenerator jsonGen, + SerializerProvider serProvider) throws IOException, + JsonProcessingException { + + + + //jsonGen.writeStartObject(); + //jsonGen.writeFieldName(s); +// jsonGen.writeStartObject(); +// jsonGen.writeEndObject(); +// jsonGen.writeEndObject(); + } + + } + + public static class Deserializer extends JsonDeserializer { + @Override + public Bind deserialize(JsonParser jsonParser, + DeserializationContext deserializationContext) + throws IOException, JsonProcessingException { + ObjectCodec oc = jsonParser.getCodec(); + JsonNode node = oc.readTree(jsonParser); + if (!node.equals(NullNode.getInstance())) { + Entry field = node.fields().next(); + return Bind.parse(field.getKey()); + } else { + return null; + } + } + } + + + +} diff --git a/src/main/java/com/github/dockerjava/client/model/Binds.java b/src/main/java/com/github/dockerjava/client/model/Binds.java new file mode 100644 index 00000000..c359ae96 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/Binds.java @@ -0,0 +1,76 @@ +package com.github.dockerjava.client.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +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.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.node.NullNode; + + +@JsonSerialize(using = Binds.Serializer.class) +@JsonDeserialize(using = Binds.Deserializer.class) +public class Binds { + + private Bind[] binds; + + public Binds(Bind... binds) { + this.binds = binds; + } + + public Bind[] getBinds() { + return binds; + } + + public static class Serializer extends JsonSerializer { + + @Override + public void serialize(Binds binds, JsonGenerator jsonGen, + SerializerProvider serProvider) throws IOException, + JsonProcessingException { + + // + jsonGen.writeStartArray(); + for (Bind bind : binds.getBinds()) { + String s = bind.getPath() + ":" + bind.getVolume().toString(); + if(bind.isReadOnly()) s += ":ro"; + jsonGen.writeString(s); + + } + jsonGen.writeEndArray(); + // + } + + } + + public static class Deserializer extends JsonDeserializer { + @Override + public Binds deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { + + List binds = new ArrayList(); + 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())) { + binds.add(Bind.parse(field.getKey())); + } + } + return new Binds(binds.toArray(new Bind[0])); + } + } + +} diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java index ebd1006d..28d6b289 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java @@ -1,13 +1,11 @@ package com.github.dockerjava.client.model; +import java.util.Arrays; +import java.util.Map; + import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - - -import java.util.Arrays; -import java.util.Map; /** * diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java index dd7a6a14..7661ac89 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java @@ -4,6 +4,7 @@ import java.util.Arrays; import java.util.Map; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @@ -46,10 +47,10 @@ public class ContainerInspectResponse { private String resolvConfPath; @JsonProperty("Volumes") - private Map volumes; + private Volumes volumes; @JsonProperty("VolumesRW") - private Map volumesRW; + private Volumes volumesRW; @JsonProperty("HostnamePath") private String hostnamePath; @@ -112,12 +113,14 @@ public String getResolvConfPath() { return resolvConfPath; } - public Map getVolumes() { - return volumes; + @JsonIgnore + public Volume[] getVolumes() { + return volumes.getVolumes(); } - public Map getVolumesRW() { - return volumesRW; + @JsonIgnore + public Volume[] getVolumesRW() { + return volumesRW.getVolumes(); } public String getHostnamePath() { diff --git a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java index 232d2782..6efbb1e2 100644 --- a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java @@ -57,11 +57,11 @@ public class CreateContainerConfig { @JsonProperty("Cmd") private String[] cmd; @JsonProperty("Dns") private String[] dns; @JsonProperty("Image") private String image; - @JsonProperty("Volumes") private Map volumes; + @JsonProperty("Volumes") private Volumes volumes = new Volumes(); @JsonProperty("VolumesFrom") private String volumesFrom = ""; @JsonProperty("WorkingDir") private String workingDir = ""; @JsonProperty("DisableNetwork") private boolean disableNetwork = false; - @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts; + @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts = new ExposedPorts(); public CreateContainerConfig withExposedPorts(ExposedPort[] exposedPorts) { this.exposedPorts = new ExposedPorts(exposedPorts); @@ -227,12 +227,13 @@ public CreateContainerConfig withImage(String image) { return this; } - public Map getVolumes() { - return volumes; + @JsonIgnore + public Volume[] getVolumes() { + return volumes.getVolumes(); } - public CreateContainerConfig withVolumes(Map volumes) { - this.volumes = volumes; + public CreateContainerConfig withVolumes(Volume[] volumes) { + this.volumes = new Volumes(volumes); return this; } diff --git a/src/main/java/com/github/dockerjava/client/model/ExposedPort.java b/src/main/java/com/github/dockerjava/client/model/ExposedPort.java index b8a284c3..fd353d3a 100644 --- a/src/main/java/com/github/dockerjava/client/model/ExposedPort.java +++ b/src/main/java/com/github/dockerjava/client/model/ExposedPort.java @@ -6,7 +6,6 @@ import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; -import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; @@ -40,63 +39,41 @@ public String getScheme() { public int getPort() { return port; } - + public static ExposedPort tcp(int port) { return new ExposedPort("tcp", port); } - + public static ExposedPort parse(String serialized) { - String[] parts = serialized.split("/"); - ExposedPort out = new ExposedPort(parts[1], Integer.valueOf(parts[0])); - return out; + try { + String[] parts = serialized.split("/"); + ExposedPort out = new ExposedPort(parts[1], Integer.valueOf(parts[0])); + return out; + } catch (Exception e) { + throw new RuntimeException("Error parsing ExposedPort '" + serialized + "'"); + } } + @Override + public String toString() { + return getPort() + "/" + getScheme(); + } + @Override public boolean equals(Object obj) { - if(obj instanceof ExposedPort) { - ExposedPort other = (ExposedPort)obj; - return new EqualsBuilder().append(scheme, other.getScheme()).append(port, other.getPort()).isEquals(); + if (obj instanceof ExposedPort) { + ExposedPort other = (ExposedPort) obj; + return new EqualsBuilder().append(scheme, other.getScheme()) + .append(port, other.getPort()).isEquals(); } else return super.equals(obj); } - + @Override public int hashCode() { return new HashCodeBuilder().append(scheme).append(port).toHashCode(); } - - - public static class KeySerializer extends JsonSerializer { - - @Override - public void serialize(ExposedPort exposedPort, JsonGenerator jsonGen, - SerializerProvider serProvider) throws IOException, - JsonProcessingException { - - - jsonGen.writeFieldName(exposedPort.getPort() + "/" - + exposedPort.getScheme()); - - - } - - } - - - public static class KeyDeserializer extends com.fasterxml.jackson.databind.KeyDeserializer { - - @Override - public Object deserializeKey(String key, DeserializationContext ctxt) - throws IOException, JsonProcessingException { - String[] parts = key.split("/"); - ExposedPort out = new ExposedPort(parts[1], Integer.valueOf(parts[0])); - return out; - } - - } - - public static class Deserializer extends JsonDeserializer { @Override public ExposedPort deserialize(JsonParser jsonParser, @@ -106,10 +83,7 @@ public ExposedPort deserialize(JsonParser jsonParser, JsonNode node = oc.readTree(jsonParser); if (!node.equals(NullNode.getInstance())) { Entry field = node.fields().next(); - String[] parts = field.getKey().split("/"); - ExposedPort out = new ExposedPort(parts[1], - Integer.valueOf(parts[0])); - return out; + return ExposedPort.parse(field.getKey()); } else { return null; } @@ -124,10 +98,7 @@ public void serialize(ExposedPort exposedPort, JsonGenerator jsonGen, JsonProcessingException { jsonGen.writeStartObject(); - - jsonGen.writeFieldName(exposedPort.getPort() + "/" - + exposedPort.getScheme()); - + jsonGen.writeFieldName(exposedPort.toString()); jsonGen.writeEndObject(); } diff --git a/src/main/java/com/github/dockerjava/client/model/ExposedPorts.java b/src/main/java/com/github/dockerjava/client/model/ExposedPorts.java index b98b0c5e..e4114b70 100644 --- a/src/main/java/com/github/dockerjava/client/model/ExposedPorts.java +++ b/src/main/java/com/github/dockerjava/client/model/ExposedPorts.java @@ -6,7 +6,6 @@ import java.util.List; import java.util.Map; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; diff --git a/src/main/java/com/github/dockerjava/client/model/Ports.java b/src/main/java/com/github/dockerjava/client/model/Ports.java index f67f01bf..f4519a8d 100644 --- a/src/main/java/com/github/dockerjava/client/model/Ports.java +++ b/src/main/java/com/github/dockerjava/client/model/Ports.java @@ -8,9 +8,6 @@ import org.apache.commons.lang.builder.EqualsBuilder; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; @@ -19,7 +16,6 @@ import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @@ -29,15 +25,15 @@ @JsonSerialize(using = Ports.Serializer.class) public class Ports { - private final Map ports = new HashMap(); + private final Map ports = new HashMap(); public Ports() { } - public Ports(ExposedPort exposedPort, Host host) { - addMapping(exposedPort, host); + public Ports(ExposedPort exposedPort, Binding host) { + bind(exposedPort, host); } - public void addMapping(ExposedPort exposedPort, Host host) { + public void bind(ExposedPort exposedPort, Binding host) { ports.put(exposedPort, host); } @@ -46,23 +42,34 @@ public String toString(){ return ports.toString(); } - public Map getMappings(){ + public Map getBindings(){ return ports; } + + public static Binding Binding(String hostIp, int hostPort) { + return new Binding(hostIp, hostPort); + } + public static Binding Binding(int hostPort) { + return new Binding(hostPort); + } - public static class Host { + public static class Binding { private final String hostIp; private final int hostPort; - public Host(String hostIp, int hostPort) { + public Binding(String hostIp, int hostPort) { this.hostIp = hostIp; this.hostPort = hostPort; } + public Binding(int hostPort) { + this("", hostPort); + } + public String getHostIp() { return hostIp; } @@ -74,7 +81,7 @@ public int getHostPort() { @Override public String toString() { - return "Host{" + + return "PortBinding{" + "hostIp='" + hostIp + '\'' + ", hostPort='" + hostPort + '\'' + '}'; @@ -82,8 +89,8 @@ public String toString() { @Override public boolean equals(Object obj) { - if(obj instanceof Host) { - Host other = (Host) obj; + if(obj instanceof Binding) { + Binding other = (Binding) obj; return new EqualsBuilder() .append(hostIp, other.getHostIp()) .append(hostPort, other.getHostPort()).isEquals(); @@ -106,7 +113,7 @@ public Ports deserialize(JsonParser jsonParser, DeserializationContext deseriali if (!field.getValue().equals(NullNode.getInstance())) { String hostIp = field.getValue().get(0).get("HostIp").textValue(); int hostPort = field.getValue().get(0).get("HostPort").asInt(); - out.addMapping(ExposedPort.parse(field.getKey()), new Host(hostIp, hostPort)); + out.bind(ExposedPort.parse(field.getKey()), new Binding(hostIp, hostPort)); } } return out; @@ -120,7 +127,7 @@ public void serialize(Ports portBindings, JsonGenerator jsonGen, SerializerProvider serProvider) throws IOException, JsonProcessingException { jsonGen.writeStartObject(); - for(Entry entry : portBindings.getMappings().entrySet()){ + for(Entry entry : portBindings.getBindings().entrySet()){ jsonGen.writeFieldName(entry.getKey().getPort() + "/" + entry.getKey().getScheme()); jsonGen.writeStartArray(); jsonGen.writeStartObject(); diff --git a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java index b04d1331..3a27d4f6 100644 --- a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java @@ -2,6 +2,7 @@ import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @@ -13,30 +14,88 @@ public class StartContainerConfig { @JsonProperty("Binds") - public String[] binds; + private Binds binds = new Binds(); @JsonProperty("LxcConf") - public LxcConf[] lxcConf; + private LxcConf[] lxcConf; @JsonProperty("PortBindings") - public Ports portBindings; + private Ports portBindings; @JsonProperty("PublishAllPorts") - public boolean publishAllPorts; + private boolean publishAllPorts; @JsonProperty("Privileged") - public boolean privileged; + private boolean privileged; @JsonProperty("Dns") - public String dns; + private String dns; @JsonProperty("VolumesFrom") - public String volumesFrom; + private String volumesFrom; - @Override + @JsonIgnore + public Bind[] getBinds() { + return binds.getBinds(); + } + + @JsonIgnore + public void setBinds(Bind[] binds) { + this.binds = new Binds(binds); + } + + public LxcConf[] getLxcConf() { + return lxcConf; + } + + public void setLxcConf(LxcConf[] lxcConf) { + this.lxcConf = lxcConf; + } + + public Ports getPortBindings() { + return portBindings; + } + + public void setPortBindings(Ports portBindings) { + this.portBindings = portBindings; + } + + public boolean isPublishAllPorts() { + return publishAllPorts; + } + + public void setPublishAllPorts(boolean publishAllPorts) { + this.publishAllPorts = publishAllPorts; + } + + public boolean isPrivileged() { + return privileged; + } + + public void setPrivileged(boolean privileged) { + this.privileged = privileged; + } + + public String getDns() { + return dns; + } + + public void setDns(String dns) { + this.dns = dns; + } + + public String getVolumesFrom() { + return volumesFrom; + } + + public void setVolumesFrom(String volumesFrom) { + this.volumesFrom = volumesFrom; + } + + @Override public String toString() { return "StartContainerConfig{" + - "binds=" + Arrays.toString(binds) + + "binds=" + binds + ", lxcConf=" + Arrays.toString(lxcConf) + ", portBindings=" + portBindings + ", privileged=" + privileged + diff --git a/src/main/java/com/github/dockerjava/client/model/Volume.java b/src/main/java/com/github/dockerjava/client/model/Volume.java new file mode 100644 index 00000000..48a0dc72 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/Volume.java @@ -0,0 +1,99 @@ +package com.github.dockerjava.client.model; + +import java.io.IOException; +import java.util.Map.Entry; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +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.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.node.NullNode; + +@JsonDeserialize(using = Volume.Deserializer.class) +@JsonSerialize(using = Volume.Serializer.class) +public class Volume { + + private String path; + + private boolean readWrite = true; + + public Volume(String path) { + this.path = path; + } + + public String getPath() { + return path; + } + + public boolean isReadWrite() { + return readWrite; + } + + public static Volume parse(String serialized) { + return new Volume(serialized); + } + + @Override + public String toString() { + return getPath(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Volume) { + Volume other = (Volume) obj; + return new EqualsBuilder().append(path, other.getPath()).append(readWrite, other.isReadWrite()) + .isEquals(); + } else + return super.equals(obj); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(path).append(readWrite).toHashCode(); + } + + public static class Serializer extends JsonSerializer { + + @Override + public void serialize(Volume volume, JsonGenerator jsonGen, + SerializerProvider serProvider) throws IOException, + JsonProcessingException { + + jsonGen.writeStartObject(); + jsonGen.writeFieldName(volume.getPath()); + jsonGen.writeString(Boolean.toString(volume.isReadWrite())); + jsonGen.writeEndObject(); + } + + } + + public static class Deserializer extends JsonDeserializer { + @Override + public Volume deserialize(JsonParser jsonParser, + DeserializationContext deserializationContext) + throws IOException, JsonProcessingException { + ObjectCodec oc = jsonParser.getCodec(); + JsonNode node = oc.readTree(jsonParser); + if (!node.equals(NullNode.getInstance())) { + Entry field = node.fields().next(); + return Volume.parse(field.getKey()); + } else { + return null; + } + } + } + + + +} diff --git a/src/main/java/com/github/dockerjava/client/model/Volumes.java b/src/main/java/com/github/dockerjava/client/model/Volumes.java new file mode 100644 index 00000000..d4557d98 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/Volumes.java @@ -0,0 +1,73 @@ +package com.github.dockerjava.client.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +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.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.node.NullNode; + + +@JsonSerialize(using = Volumes.Serializer.class) +@JsonDeserialize(using = Volumes.Deserializer.class) +public class Volumes { + + private Volume[] volumes; + + public Volumes(Volume... volumes) { + this.volumes = volumes; + } + + public Volume[] getVolumes() { + return volumes; + } + + public static class Serializer extends JsonSerializer { + + @Override + public void serialize(Volumes volumes, JsonGenerator jsonGen, + SerializerProvider serProvider) throws IOException, + JsonProcessingException { + + jsonGen.writeStartObject(); + for (Volume volume : volumes.getVolumes()) { + jsonGen.writeFieldName(volume.getPath()); + jsonGen.writeString(Boolean.toString(volume.isReadWrite())); + } + jsonGen.writeEndObject(); + } + + } + + public static class Deserializer extends JsonDeserializer { + @Override + public Volumes deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { + + List volumes = new ArrayList(); + 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())) { + Volume volume = Volume.parse(field.getKey()); + volumes.add(volume); + } + } + return new Volumes(volumes.toArray(new Volume[0])); + } + } + +} diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java index e86ab2fd..feb925d2 100644 --- a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java @@ -3,7 +3,6 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; @@ -29,7 +28,6 @@ import com.github.dockerjava.client.model.ContainerCreateResponse; import com.github.dockerjava.client.model.ContainerInspectResponse; import com.github.dockerjava.client.model.ImageInspectResponse; -import com.github.dockerjava.client.model.Ports; import com.sun.jersey.api.client.ClientResponse; public class BuildImageCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java index 020fce7e..a6a1a7e1 100644 --- a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java @@ -18,6 +18,7 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.ContainerCreateResponse; import com.github.dockerjava.client.model.ContainerInspectResponse; +import com.github.dockerjava.client.model.Volume; public class CreateContainerCmdTest extends AbstractDockerClientTest { @@ -45,7 +46,7 @@ public void afterMethod(ITestResult result) { public void createContainer() throws DockerException { ContainerCreateResponse container = dockerClient - .createContainerCmd("busybox").withVolumes("/var/log").withCmd(new String[] { "true" }).exec(); + .createContainerCmd("busybox").withVolumes(new Volume("/var/log")).withCmd("true").exec(); LOG.info("Created container {}", container.toString()); diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java index 9a2a5d6d..96ef538d 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java @@ -1,6 +1,5 @@ package com.github.dockerjava.client.command; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java index 9b9bdba0..4f640302 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java @@ -1,6 +1,5 @@ package com.github.dockerjava.client.command; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.isEmptyString; diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java index b9c70535..1a4a535e 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -21,10 +21,12 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.Bind; import com.github.dockerjava.client.model.ContainerCreateResponse; import com.github.dockerjava.client.model.ContainerInspectResponse; import com.github.dockerjava.client.model.ExposedPort; import com.github.dockerjava.client.model.Ports; +import com.github.dockerjava.client.model.Volume; @@ -54,10 +56,13 @@ public void afterMethod(ITestResult result) { public void startContainerWithVolumes() throws DockerException { // see http://docs.docker.io/use/working_with_volumes/ + Volume volume1 = new Volume("/opt/webapp1"); + + Volume volume2 = new Volume("/opt/webapp2"); ContainerCreateResponse container = dockerClient - .createContainerCmd("busybox").withVolumes("/logs_from_host") - .withCmd(new String[] { "true" }).exec(); + .createContainerCmd("busybox").withVolumes(volume1, volume2) + .withCmd("true").exec(); LOG.info("Created container {}", container.toString()); @@ -67,20 +72,21 @@ public void startContainerWithVolumes() throws DockerException { .inspectContainerCmd(container.getId()).exec(); assertThat(containerInspectResponse.getConfig().getVolumes().keySet(), - contains("/logs_from_host")); + contains("/opt/webapp1", "/opt/webapp2")); - dockerClient.startContainerCmd(container.getId()).withBinds("/var/log:/logs_from_host:ro").exec(); + + dockerClient.startContainerCmd(container.getId()).withBinds(new Bind("/src/webapp1", volume1, true), new Bind("/src/webapp2", volume2)).exec(); dockerClient.waitContainerCmd(container.getId()).exec(); containerInspectResponse = dockerClient.inspectContainerCmd(container .getId()).exec(); - assertThat(containerInspectResponse.getVolumes().get("/logs_from_host"), - equalTo("/var/log")); + assertThat(Arrays.asList(containerInspectResponse.getVolumes()), + contains(volume1, volume2)); - assertThat(containerInspectResponse.getVolumesRW().get("/logs_from_host"), - equalTo(false)); + assertThat(Arrays.asList(containerInspectResponse.getVolumesRW()), + contains(volume1, volume2)); tmpContainers.add(container.getId()); } @@ -103,12 +109,8 @@ public void startContainerWithPortBindings() throws DockerException { .inspectContainerCmd(container.getId()).exec(); Ports portBindings = new Ports(); - - Ports.Host host11022 = new Ports.Host("", 11022); - Ports.Host host11023 = new Ports.Host("", 11023); - - portBindings.addMapping(tcp22, host11022); - portBindings.addMapping(tcp23, host11023); + portBindings.bind(tcp22, Ports.Binding(11022)); + portBindings.bind(tcp23, Ports.Binding(11023)); dockerClient.startContainerCmd(container.getId()).withPortBindings(portBindings).exec(); @@ -118,11 +120,11 @@ public void startContainerWithPortBindings() throws DockerException { assertThat(Arrays.asList(containerInspectResponse.getConfig().getExposedPorts()), contains(tcp22, tcp23)); - assertThat(containerInspectResponse.getHostConfig().getPortBindings().getMappings().get(tcp22), - is(equalTo(new Ports.Host("0.0.0.0", 11022)))); + assertThat(containerInspectResponse.getHostConfig().getPortBindings().getBindings().get(tcp22), + is(equalTo(Ports.Binding("0.0.0.0", 11022)))); - assertThat(containerInspectResponse.getHostConfig().getPortBindings().getMappings().get(tcp23), - is(equalTo(new Ports.Host("0.0.0.0", 11023)))); + assertThat(containerInspectResponse.getHostConfig().getPortBindings().getBindings().get(tcp23), + is(equalTo(Ports.Binding("0.0.0.0", 11023)))); tmpContainers.add(container.getId()); } diff --git a/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java index 8df20381..a756b49f 100644 --- a/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java @@ -3,17 +3,10 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.isEmptyString; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.startsWith; -import static org.testinfected.hamcrest.jpa.HasFieldWithValue.hasField; import java.lang.reflect.Method; -import java.util.List; import org.apache.commons.lang.math.RandomUtils; -import org.hamcrest.Matcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; @@ -25,7 +18,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; public class TagImageCmdTest extends AbstractDockerClientTest { From 9ebaac8e707782f3c55a323c00d6695747d74025 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 3 Jul 2014 21:14:54 +0200 Subject: [PATCH 017/452] [maven-release-plugin] prepare release docker-java-0.9.0 --- pom.xml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index d0f8365e..57b57f20 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - + 4.0.0 @@ -11,7 +10,7 @@ com.github.docker-java docker-java jar - 0.9.0-SNAPSHOT + 0.9.0 docker-java https://github.com/docker-java/docker-java @@ -29,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-0.9.0 From 933525f6be620e9cc0d8941f79de69f44de83f98 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 3 Jul 2014 21:14:58 +0200 Subject: [PATCH 018/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 57b57f20..5aee03c6 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.9.0 + 0.9.1-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.9.0 + HEAD From 6ddf0c0cbf54ddfafe6050010e0318b4ca45de84 Mon Sep 17 00:00:00 2001 From: docker-java Date: Thu, 3 Jul 2014 21:49:45 +0200 Subject: [PATCH 019/452] Update README.md --- README.md | 58 +++---------------------------------------------------- 1 file changed, 3 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index c843c1b1..5e521f4a 100644 --- a/README.md +++ b/README.md @@ -46,66 +46,14 @@ Run build with tests: com.github.docker-java docker-java - 0.9.0-SNAPSHOT + 0.9.0 Latest SNAPSHOT is available from maven repo: https://oss.sonatype.org/content/groups/public -## Example code snippets: +## Documentation - DockerClient dockerClient = new DockerClient("http://localhost:2375"); - -###### Get Docker info: - - Info info = dockerClient.infoCmd().exec(); - System.out.print(info); - -###### Search Docker repository: - - List dockerSearch = dockerClient.searchImagesCmd("busybox").exec(); - System.out.println("Search returned" + dockerSearch.toString()); - -###### Create new Docker container, wait for its start and stop it: - - ContainerCreateResponse container = dockerClient.createContainerCmd("busybox").withCmd("touch", "/test").exec(); - - dockerClient.startContainerCmd(container.id).exec(); - - dockerClient.waitContainerCmd(container.id).exec(); - - dockerClient.stopContainerCmd(container.id).exec(); - - -##### Support for UNIX sockets: - - Support for UNIX socket should appear in docker-java pretty soon. I'm working on its integration. - -##### Docker Builder: - -To use Docker Builder, as described on page http://docs.docker.io/en/latest/use/builder/, -user dockerClient.buildImageCmd(baseDir), where baseDir is a path to folder containing Dockerfile. - - - File baseDir = new File("~/kpelykh/docker/netcat"); - - ClientResponse response = dockerClient.buildImageCmd(baseDir).exec(); - - 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 [Test cases](https://github.com/docker-java/docker-java/tree/master/src/test/java/com/github/dockerjava/client/command "Test cases") +For code examples, please look at the [Wiki](https://github.com/docker-java/docker-java/wiki) or [Test cases](https://github.com/docker-java/docker-java/tree/master/src/test/java/com/github/dockerjava/client/command "Test cases") ## Configuration From ffe330141ac4e04d8528dced3ed2b9e4be5164c8 Mon Sep 17 00:00:00 2001 From: Sean Fitts Date: Thu, 3 Jul 2014 16:08:22 -0700 Subject: [PATCH 020/452] Some tweaks for use in gradle-docker. - Change the default Docker port to 2375 to match current Docker version. - Add toString() to all commands which prints out a form similar to the corresponding Docker command line. Useful in tracing. - Create client logging filter variant which allows us to avoid logging requests whose content type is likely to cause issues for both the Windows and OSX consoles. This is an adaptation of a change from a while back (https://github.com/alexec/docker-java/commit/887a1120e5d3c54afa51e84f360ca6740d9916ec) which seems to have be lost in the move. --- .../dockerjava/client/DockerClient.java | 7 ++- .../client/SelectiveLoggingFilter.java | 47 +++++++++++++++++++ .../dockerjava/client/command/AuthCmd.java | 5 ++ .../client/command/BuildImgCmd.java | 9 ++++ .../dockerjava/client/command/CommitCmd.java | 12 ++++- .../client/command/ContainerDiffCmd.java | 9 +++- .../command/CopyFileFromContainerCmd.java | 9 ++++ .../client/command/CreateContainerCmd.java | 8 ++++ .../client/command/ImportImageCmd.java | 8 ++++ .../dockerjava/client/command/InfoCmd.java | 10 ++-- .../client/command/InspectContainerCmd.java | 9 ++-- .../client/command/InspectImageCmd.java | 9 ++-- .../client/command/KillContainerCmd.java | 9 ++-- .../client/command/ListContainersCmd.java | 11 +++++ .../client/command/ListImagesCmd.java | 8 ++++ .../client/command/LogContainerCmd.java | 9 +++- .../client/command/PullImageCmd.java | 8 ++++ .../client/command/PushImageCmd.java | 7 +++ .../client/command/RemoveContainerCmd.java | 9 ++++ .../client/command/RemoveImageCmd.java | 9 ++++ .../client/command/RestartContainerCmd.java | 8 ++++ .../client/command/SearchImagesCmd.java | 7 +++ .../client/command/StartContainerCmd.java | 13 +++-- .../client/command/StopContainerCmd.java | 8 ++++ .../client/command/TagImageCmd.java | 10 ++++ .../client/command/TopContainerCmd.java | 8 ++++ .../dockerjava/client/command/VersionCmd.java | 9 ++-- .../client/command/WaitContainerCmd.java | 9 ++-- src/main/resources/docker.io.properties | 4 +- 29 files changed, 257 insertions(+), 31 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index b7d0993e..0b848b94 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -1,6 +1,6 @@ package com.github.dockerjava.client; -import static org.apache.commons.io.IOUtils.closeQuietly; +import static org.apache.commons.io.IOUtils.*; import java.io.File; import java.io.IOException; @@ -54,7 +54,6 @@ import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.client.apache4.ApacheHttpClient4; import com.sun.jersey.client.apache4.ApacheHttpClient4Handler; @@ -63,7 +62,7 @@ */ public class DockerClient { - private Client client; + private Client client; private WebResource baseResource; private AuthConfig authConfig; @@ -110,7 +109,7 @@ private DockerClient(Config config) { // client = new UnixSocketClient(clientConfig); client.addFilter(new JsonClientFilter()); - client.addFilter(new LoggingFilter()); + client.addFilter(new SelectiveLoggingFilter()); baseResource = client.resource(config.url + "/v" + config.version); } diff --git a/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java b/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java new file mode 100644 index 00000000..bb105753 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java @@ -0,0 +1,47 @@ +package com.github.dockerjava.client; + +import java.util.Set; + +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; + +import com.google.common.collect.ImmutableSet; +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.filter.LoggingFilter; + +/** + * A version of the logging filter that will avoid trying to log entities which can cause + * issues with the console. + * + * @author sfitts + * + */ +public class SelectiveLoggingFilter extends LoggingFilter { + + private static final Set SKIPPED_CONTENT = ImmutableSet.builder() + .add(MediaType.APPLICATION_OCTET_STREAM) + .add("application/tar") + .build(); + + @Override + public ClientResponse handle(ClientRequest request) throws ClientHandlerException { + // Unless the content type is in the list of those we want to ellide, then just have + // our super-class handle things. + MediaType contentType = (MediaType) request.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE); + if (SKIPPED_CONTENT.contains(contentType.toString())) { + // Skip logging this. + // + // N.B. -- I'd actually love to reproduce (or better yet just use) the logging code from + // our super-class. However, everything is private (so we can't use it) and the code + // is under a modified GPL which means we can't pull it into an ASL project. Right now + // I don't have the energy to do a clean implementation. + return getNext().handle(request); + } + + // Do what we normally would + return super.handle(request); + } + +} diff --git a/src/main/java/com/github/dockerjava/client/command/AuthCmd.java b/src/main/java/com/github/dockerjava/client/command/AuthCmd.java index f5f7b7ed..85f68103 100644 --- a/src/main/java/com/github/dockerjava/client/command/AuthCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AuthCmd.java @@ -34,4 +34,9 @@ protected Void impl() throws DockerException { throw new DockerException(e); } } + + @Override + public String toString() { + return "authenticate using " + this.authConfig; + } } diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java index edaa3110..5a92fb56 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -61,6 +61,15 @@ public BuildImgCmd withNoCache(boolean noCache) { return this; } + @Override + public String toString() { + return new StringBuilder("build ") + .append(tag != null ? "-t " + tag + " " : "") + .append(noCache ? "--nocache=true " : "") + .append(dockerFolder != null ? dockerFolder.getPath() : "-") + .toString(); + } + protected ClientResponse impl() { if (tarInputStream == null) { File dockerFolderTar = buildDockerFolderTar(); diff --git a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java index 3dc350ea..16a76985 100644 --- a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java @@ -67,7 +67,17 @@ public CommitCmd withRun(String run) { return this; } - + @Override + public String toString() { + return new StringBuilder("commit ") + .append(commitConfig.getAuthor() != null ? "--author " + commitConfig.getAuthor() + " " : "") + .append(commitConfig.getMessage() != null ? "--message " + commitConfig.getMessage() + " " : "") + .append(commitConfig.getContainerId()) + .append(commitConfig.getRepo() != null ? " " + commitConfig.getRepo() + ":" : " ") + .append(commitConfig.getTag() != null ? commitConfig.getTag() : "") + .toString(); + } + private void checkCommitConfig(CommitConfig commitConfig) { Preconditions.checkNotNull(commitConfig, "CommitConfig was not specified"); } diff --git a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java b/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java index a0225bec..ed684d04 100644 --- a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java @@ -37,7 +37,14 @@ public ContainerDiffCmd withContainerId(String containerId) { return this; } - protected List impl() throws DockerException { + @Override + public String toString() { + return new StringBuilder("diff ") + .append(containerId) + .toString(); + } + + protected List impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/changes", containerId)); try { diff --git a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java index d9543418..3e374aa5 100644 --- a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java @@ -40,6 +40,15 @@ public CopyFileFromContainerCmd withResource(String resource) { return this; } + @Override + public String toString() { + return new StringBuilder("cp ") + .append(containerId) + .append(":") + .append(resource) + .toString(); + } + protected ClientResponse impl() throws DockerException { CopyConfig copyConfig = new CopyConfig(); copyConfig.setResource(resource); diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index b3795089..94b46bb8 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -81,6 +81,14 @@ public CreateContainerCmd withExposedPorts(ExposedPort... exposedPorts) { return this; } + @Override + public String toString() { + return new StringBuilder("create container ") + .append(name != null ? "name=" + name + " " : "") + .append(containerCreateConfig) + .toString(); + } + protected ContainerCreateResponse impl() { MultivaluedMap params = new MultivaluedMapImpl(); if (name != null) { diff --git a/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java b/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java index 4797110d..020d5e75 100644 --- a/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java @@ -62,6 +62,14 @@ public ImportImageCmd withTag(String tag) { return this; } + @Override + public String toString() { + return new StringBuilder("import - ") + .append(repository != null ? repository + ":" : "") + .append(tag != null ? tag : "") + .toString(); + } + protected ImageCreateResponse impl() { MultivaluedMap params = new MultivaluedMapImpl(); params.add("repo", repository); diff --git a/src/main/java/com/github/dockerjava/client/command/InfoCmd.java b/src/main/java/com/github/dockerjava/client/command/InfoCmd.java index 810718f0..42985e63 100644 --- a/src/main/java/com/github/dockerjava/client/command/InfoCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InfoCmd.java @@ -12,15 +12,17 @@ /** - * - * - * + * Return Docker server info */ public class InfoCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(InfoCmd.class); - + @Override + public String toString() { + return "info"; + } + protected Info impl() throws DockerException { WebResource webResource = baseResource.path("/info"); diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java index ba6eedd5..ff031537 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java @@ -13,9 +13,7 @@ import com.sun.jersey.api.client.WebResource; /** - * - * - * + * Inspect the details of a container. */ public class InspectContainerCmd extends AbstrDockerCmd { @@ -33,6 +31,11 @@ public InspectContainerCmd withContainerId(String containerId) { return this; } + @Override + public String toString() { + return "inspect " + containerId; + } + protected ContainerInspectResponse impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/json", containerId)); diff --git a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java index 23f6a775..ab4f3510 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java @@ -14,9 +14,7 @@ /** - * - * - * + * Inspect the details of an image. */ public class InspectImageCmd extends AbstrDockerCmd { @@ -34,6 +32,11 @@ public InspectImageCmd withImageId(String imageId) { return this; } + @Override + public String toString() { + return "inspect " + imageId; + } + protected ImageInspectResponse impl() { WebResource webResource = baseResource.path(String.format("/images/%s/json", imageId)); diff --git a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java index 75874559..58ac5564 100644 --- a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java @@ -11,9 +11,7 @@ import com.sun.jersey.api.client.WebResource; /** - * - * - * + * Kill a running container. */ public class KillContainerCmd extends AbstrDockerCmd { @@ -31,6 +29,11 @@ public KillContainerCmd withContainerId(String containerId) { return this; } + @Override + public String toString() { + return "kill " + containerId; + } + protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/kill", containerId)); diff --git a/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java b/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java index 9724fa15..77406155 100644 --- a/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java @@ -61,6 +61,17 @@ public ListContainersCmd withBefore(String before) { return this; } + @Override + public String toString() { + return new StringBuilder("ps ") + .append(showAll ? "--all=true" : "") + .append(showSize ? "--size=true" : "") + .append(sinceId != null ? "--since " + sinceId : "") + .append(beforeId != null ? "--before " + beforeId : "") + .append(limit != -1 ? "-n " + limit : "") + .toString(); + } + protected List impl() { MultivaluedMap params = new MultivaluedMapImpl(); if(limit >= 0) { diff --git a/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java b/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java index 5756b72d..e4611f51 100644 --- a/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java @@ -41,6 +41,14 @@ public ListImagesCmd withFilter(String filter) { return this; } + @Override + public String toString() { + return new StringBuilder("images ") + .append(showAll ? "--all=true" : "") + .append(filter != null ? "--filter " + filter : "") + .toString(); + } + protected List impl() { MultivaluedMap params = new MultivaluedMapImpl(); params.add("filter", filter); diff --git a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java index c924be29..cda2e090 100644 --- a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java @@ -78,7 +78,14 @@ public LogContainerCmd withStdErr(boolean stderr) { return this; } - + @Override + public String toString() { + return new StringBuilder("logs ") + .append(followStream ? "--follow=true" : "") + .append(timestamps ? "--timestamps=true" : "") + .append(containerId) + .toString(); + } protected ClientResponse impl() throws DockerException { MultivaluedMap params = new MultivaluedMapImpl(); diff --git a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java b/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java index 0c6ee7a3..16e0ee71 100644 --- a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java @@ -48,6 +48,14 @@ public PullImageCmd withRegistry(String registry) { return this; } + @Override + public String toString() { + return new StringBuilder("pull ") + .append(repository) + .append(tag != null ? ":" + tag : "") + .toString(); + } + protected ClientResponse impl() { Preconditions.checkNotNull(repository, "Repository was not specified"); diff --git a/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java b/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java index dc0b35b1..6d54a756 100644 --- a/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java @@ -36,6 +36,13 @@ public PushImageCmd withName(String name) { return this; } + @Override + public String toString() { + return new StringBuilder("push ") + .append(name) + .toString(); + } + protected ClientResponse impl() { WebResource webResource = baseResource.path("/images/" + name(name) + "/push"); try { diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java index b8e10765..e13cd970 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java @@ -49,6 +49,15 @@ public RemoveContainerCmd withForce(boolean force) { return this; } + @Override + public String toString() { + return new StringBuilder("rm ") + .append(removeVolumes ? "--volumes=true" : "") + .append(force ? "--force=true" : "") + .append(containerId) + .toString(); + } + protected Void impl() throws DockerException { Preconditions.checkState(!StringUtils.isEmpty(containerId), "Container ID can't be empty"); diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java b/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java index cef438fe..da6f658c 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java @@ -43,6 +43,15 @@ public RemoveImageCmd withNoPrune(boolean noPrune) { return this; } + @Override + public String toString() { + return new StringBuilder("rmi ") + .append(noPrune ? "--no-prune=true" : "") + .append(force ? "--force=true" : "") + .append(imageId) + .toString(); + } + protected Void impl() throws DockerException { Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty"); diff --git a/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java index b8da9dbd..48a436c9 100644 --- a/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java @@ -41,6 +41,14 @@ public RestartContainerCmd withtTimeout(int timeout) { return this; } + @Override + public String toString() { + return new StringBuilder("restart ") + .append("--time=" + timeout + " ") + .append(containerId) + .toString(); + } + protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/restart", containerId)) .queryParam("t", String.valueOf(timeout));; diff --git a/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java b/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java index 784e49de..90df5b78 100644 --- a/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java @@ -36,6 +36,13 @@ public SearchImagesCmd withTerm(String term) { return this; } + @Override + public String toString() { + return new StringBuilder("search ") + .append(term) + .toString(); + } + protected List impl() { WebResource webResource = baseResource.path("/images/search").queryParam("term", term); try { diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index 36822ce9..305dd866 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -16,9 +16,7 @@ import com.sun.jersey.api.client.WebResource.Builder; /** - * - * - * + * Run a container */ public class StartContainerCmd extends AbstrDockerCmd { @@ -75,6 +73,15 @@ public StartContainerCmd withContainerId(String containerId) { return this; } + @Override + public String toString() { + return new StringBuilder("run ") + .append(containerId) + .append(" using ") + .append(startContainerConfig) + .toString(); + } + protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/start", containerId)); diff --git a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java index cb2e26f9..ed395619 100644 --- a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java @@ -41,6 +41,14 @@ public StopContainerCmd withTimeout(int timeout) { return this; } + @Override + public String toString() { + return new StringBuilder("stop ") + .append("--time=" + timeout + " ") + .append(containerId) + .toString(); + } + protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/stop", containerId)) .queryParam("t", String.valueOf(timeout)); diff --git a/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java b/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java index f06ab376..80289050 100644 --- a/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java @@ -65,6 +65,16 @@ public TagImageCmd withForce(boolean force) { return this; } + @Override + public String toString() { + return new StringBuilder("tag ") + .append(force ? "--force=true " : "") + .append(repository != null ? repository + "/" : "") + .append(imageId) + .append(tag != null ? ":" + tag : "") + .toString(); + } + protected Integer impl() { MultivaluedMap params = new MultivaluedMapImpl(); diff --git a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java index 34be6e97..490f1951 100644 --- a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java @@ -43,6 +43,14 @@ public TopContainerCmd withPsArgs(String psArgs) { return this; } + @Override + public String toString() { + return new StringBuilder("top ") + .append(containerId) + .append(psArgs != null ? " " + psArgs : "") + .toString(); + } + protected ContainerTopResponse impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/top", containerId)); diff --git a/src/main/java/com/github/dockerjava/client/command/VersionCmd.java b/src/main/java/com/github/dockerjava/client/command/VersionCmd.java index 15fd00bc..c1809e4e 100644 --- a/src/main/java/com/github/dockerjava/client/command/VersionCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/VersionCmd.java @@ -12,15 +12,18 @@ /** - * - * - * + * Return the Docker version info. */ public class VersionCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(VersionCmd.class); + @Override + public String toString() { + return "version"; + } + protected Version impl() throws DockerException { WebResource webResource = baseResource.path("/version"); diff --git a/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java index 71134895..41202f14 100644 --- a/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java @@ -13,9 +13,7 @@ import com.sun.jersey.api.client.WebResource; /** - * - * - * + * Wait for a container to exit and print its exit code */ public class WaitContainerCmd extends AbstrDockerCmd { @@ -33,6 +31,11 @@ public WaitContainerCmd withContainerId(String containerId) { return this; } + @Override + public String toString() { + return "wait " + containerId; + } + protected Integer impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/wait", containerId)); diff --git a/src/main/resources/docker.io.properties b/src/main/resources/docker.io.properties index 0ce162bd..249c8fb6 100644 --- a/src/main/resources/docker.io.properties +++ b/src/main/resources/docker.io.properties @@ -1,2 +1,2 @@ -docker.io.url=http://localhost:4243 -docker.io.version=1.11 \ No newline at end of file +docker.io.url=http://localhost:2375 +docker.io.version=1.12 \ No newline at end of file From 6a2110cd41a3615e48ddccaebc2a3575c4241f4e Mon Sep 17 00:00:00 2001 From: Sean Fitts Date: Thu, 3 Jul 2014 17:38:59 -0700 Subject: [PATCH 021/452] A few tweaks Revert API version which was by accident Fix bug in logging filter Add extra check to test to avoid downstream issues --- .../github/dockerjava/client/SelectiveLoggingFilter.java | 4 ++-- .../github/dockerjava/client/command/AbstrDockerCmd.java | 6 ++++++ src/main/resources/docker.io.properties | 2 +- .../github/dockerjava/client/command/BuildImageCmdTest.java | 1 + 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java b/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java index bb105753..fbdbfc7a 100644 --- a/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java +++ b/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java @@ -29,8 +29,8 @@ public class SelectiveLoggingFilter extends LoggingFilter { public ClientResponse handle(ClientRequest request) throws ClientHandlerException { // Unless the content type is in the list of those we want to ellide, then just have // our super-class handle things. - MediaType contentType = (MediaType) request.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE); - if (SKIPPED_CONTENT.contains(contentType.toString())) { + Object contentType = request.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE); + if (contentType != null && SKIPPED_CONTENT.contains(contentType.toString())) { // Skip logging this. // // N.B. -- I'd actually love to reproduce (or better yet just use) the logging code from diff --git a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java index a10b2208..e5e2f2be 100644 --- a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java @@ -1,9 +1,14 @@ package com.github.dockerjava.client.command; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; public abstract class AbstrDockerCmd, RES_T> implements DockerCmd { + + private final static Logger LOGGER = LoggerFactory.getLogger(AbstrDockerCmd.class); protected WebResource baseResource; @@ -18,6 +23,7 @@ public T withBaseResource(WebResource baseResource) { @Override public RES_T exec() { Preconditions.checkNotNull(baseResource, "baseResource was not specified"); + LOGGER.debug("Cmd: {}", this); return impl(); } } \ No newline at end of file diff --git a/src/main/resources/docker.io.properties b/src/main/resources/docker.io.properties index 249c8fb6..b154e876 100644 --- a/src/main/resources/docker.io.properties +++ b/src/main/resources/docker.io.properties @@ -1,2 +1,2 @@ docker.io.url=http://localhost:2375 -docker.io.version=1.12 \ No newline at end of file +docker.io.version=1.11 \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java index e86ab2fd..b5983c91 100644 --- a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java @@ -198,6 +198,7 @@ public void testNetCatDockerfileBuilder() throws DockerException, ImageInspectResponse imageInspectResponse = dockerClient .inspectImageCmd(imageId).exec(); assertThat(imageInspectResponse, not(nullValue())); + assertThat(imageInspectResponse.getId(), not(nullValue())); LOG.info("Image Inspect: {}", imageInspectResponse.toString()); tmpImgs.add(imageInspectResponse.getId()); From 96da4b14bd2b9e09e8d146cc38d004646c138b85 Mon Sep 17 00:00:00 2001 From: Sean Fitts Date: Thu, 3 Jul 2014 17:49:26 -0700 Subject: [PATCH 022/452] Normalize line endings This uses the recommended strategy to normalize line endings for mixed Windows/*nix development. We also make sure that the shell scripts used for testing have Unix line endings on all platforms so they will function properly. --- .gitattributes | 17 + .../dockerjava/client/model/ChangeLog.java | 70 +- .../dockerjava/client/model/CommitConfig.java | 174 ++--- .../dockerjava/client/model/Container.java | 280 +++---- .../client/model/ContainerConfig.java | 598 +++++++-------- .../client/model/ContainerCreateResponse.java | 90 +-- .../model/ContainerInspectResponse.java | 686 +++++++++--------- .../client/model/ContainerTopResponse.java | 92 +-- .../client/model/CreateContainerConfig.java | 548 +++++++------- .../dockerjava/client/model/DriverStatus.java | 66 +- .../dockerjava/client/model/HostConfig.java | 134 ++-- .../github/dockerjava/client/model/Image.java | 236 +++--- .../client/model/ImageCreateResponse.java | 60 +- .../client/model/ImageInspectResponse.java | 304 ++++---- .../github/dockerjava/client/model/Info.java | 460 ++++++------ .../dockerjava/client/model/SearchItem.java | 108 +-- .../client/model/StartContainerConfig.java | 100 +-- .../dockerjava/client/model/Version.java | 206 +++--- 18 files changed, 2123 insertions(+), 2106 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..9a39f917 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,17 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Unix shell files use Unix line endings +*.sh text eol=lf + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain diff --git a/src/main/java/com/github/dockerjava/client/model/ChangeLog.java b/src/main/java/com/github/dockerjava/client/model/ChangeLog.java index 7fba4cfe..cc4c5ece 100644 --- a/src/main/java/com/github/dockerjava/client/model/ChangeLog.java +++ b/src/main/java/com/github/dockerjava/client/model/ChangeLog.java @@ -1,35 +1,35 @@ -package com.github.dockerjava.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 + - '}'; - } -} +package com.github.dockerjava.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/github/dockerjava/client/model/CommitConfig.java b/src/main/java/com/github/dockerjava/client/model/CommitConfig.java index a8e6892b..734119e8 100644 --- a/src/main/java/com/github/dockerjava/client/model/CommitConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/CommitConfig.java @@ -1,87 +1,87 @@ -package com.github.dockerjava.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 containerId; - - @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 getContainerId() { - return containerId; - } - - 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 containerId) { - this.containerId = containerId; - } - -} +package com.github.dockerjava.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 containerId; + + @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 getContainerId() { + return containerId; + } + + 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 containerId) { + this.containerId = containerId; + } + +} diff --git a/src/main/java/com/github/dockerjava/client/model/Container.java b/src/main/java/com/github/dockerjava/client/model/Container.java index e368758d..3f0d642a 100644 --- a/src/main/java/com/github/dockerjava/client/model/Container.java +++ b/src/main/java/com/github/dockerjava/client/model/Container.java @@ -1,140 +1,140 @@ -package com.github.dockerjava.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; - - @JsonProperty("Ports") - public Port[] 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 Port[] getPorts() { - return ports; - } - - public void setPorts(Port[] ports) { - this.ports = ports; - } - - public int getSize() { - return size; - } - - public int getSizeRootFs() { - return sizeRootFs; - } - - public String[] getNames() { - return names; - } - - - @Override - public String toString() { - return "Container{" + - "id='" + id + '\'' + - ", command='" + command + '\'' + - ", image='" + image + '\'' + - ", created=" + created + - ", status='" + status + '\'' + - ", ports=" + Arrays.toString(ports) + - ", size=" + size + - ", sizeRootFs=" + sizeRootFs + - ", names=" + Arrays.toString(names) + - '}'; - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static class Port { - - @JsonProperty("IP") - private String ip; - - @JsonProperty("PrivatePort") - private Integer privatePort; - - @JsonProperty("PublicPort") - private Integer publicPort; - - @JsonProperty("Type") - private String type; - - public String getIp() { - return ip; - } - - public Integer getPrivatePort() { - return privatePort; - } - - public Integer getPublicPort() { - return publicPort; - } - - public String getType() { - return type; - } - - @Override - public String toString() { - return "Port{" + - "IP='" + ip + '\'' + - ", privatePort='" + privatePort + '\'' + - ", publicPort='" + publicPort + '\'' + - ", type='" + type + '\'' + - '}'; - } - } -} +package com.github.dockerjava.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; + + @JsonProperty("Ports") + public Port[] 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 Port[] getPorts() { + return ports; + } + + public void setPorts(Port[] ports) { + this.ports = ports; + } + + public int getSize() { + return size; + } + + public int getSizeRootFs() { + return sizeRootFs; + } + + public String[] getNames() { + return names; + } + + + @Override + public String toString() { + return "Container{" + + "id='" + id + '\'' + + ", command='" + command + '\'' + + ", image='" + image + '\'' + + ", created=" + created + + ", status='" + status + '\'' + + ", ports=" + Arrays.toString(ports) + + ", size=" + size + + ", sizeRootFs=" + sizeRootFs + + ", names=" + Arrays.toString(names) + + '}'; + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Port { + + @JsonProperty("IP") + private String ip; + + @JsonProperty("PrivatePort") + private Integer privatePort; + + @JsonProperty("PublicPort") + private Integer publicPort; + + @JsonProperty("Type") + private String type; + + public String getIp() { + return ip; + } + + public Integer getPrivatePort() { + return privatePort; + } + + public Integer getPublicPort() { + return publicPort; + } + + public String getType() { + return type; + } + + @Override + public String toString() { + return "Port{" + + "IP='" + ip + '\'' + + ", privatePort='" + privatePort + '\'' + + ", publicPort='" + publicPort + '\'' + + ", type='" + type + '\'' + + '}'; + } + } +} diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java index ebd1006d..b623e408 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java @@ -1,299 +1,299 @@ -package com.github.dockerjava.client.model; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - - -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 Map 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 = ""; - @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts; - - @JsonProperty("OnBuild") private int[] onBuild; - - @JsonIgnore - public ExposedPort[] getExposedPorts() { - return exposedPorts.getExposedPorts(); - } - - @JsonIgnore - public void setExposedPorts(ExposedPort[] exposedPorts) { - this.exposedPorts = new ExposedPorts(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 Map getVolumes() { - return volumes; - } - - public ContainerConfig setVolumes(Map 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) + '\'' + - '}'; - } -} +package com.github.dockerjava.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + + +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 Map 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 = ""; + @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts; + + @JsonProperty("OnBuild") private int[] onBuild; + + @JsonIgnore + public ExposedPort[] getExposedPorts() { + return exposedPorts.getExposedPorts(); + } + + @JsonIgnore + public void setExposedPorts(ExposedPort[] exposedPorts) { + this.exposedPorts = new ExposedPorts(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 Map getVolumes() { + return volumes; + } + + public ContainerConfig setVolumes(Map 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/github/dockerjava/client/model/ContainerCreateResponse.java b/src/main/java/com/github/dockerjava/client/model/ContainerCreateResponse.java index 4cd75b58..d912ecc1 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerCreateResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerCreateResponse.java @@ -1,45 +1,45 @@ -package com.github.dockerjava.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) + - '}'; - } -} +package com.github.dockerjava.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/github/dockerjava/client/model/ContainerInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java index dd7a6a14..2db41cdb 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java @@ -1,343 +1,343 @@ -package com.github.dockerjava.client.model; - - -import java.util.Arrays; -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 String getCreated() { - return created; - } - - public String getPath() { - return path; - } - - public String[] getArgs() { - return args; - } - - public ContainerConfig getConfig() { - return config; - } - - public ContainerState getState() { - return state; - } - - public String getImageId() { - return imageId; - } - - public NetworkSettings getNetworkSettings() { - return networkSettings; - } - - public String getSysInitPath() { - return sysInitPath; - } - - public String getResolvConfPath() { - return resolvConfPath; - } - - public Map getVolumes() { - return volumes; - } - - public Map getVolumesRW() { - return volumesRW; - } - - public String getHostnamePath() { - return hostnamePath; - } - - public String getHostsPath() { - return hostsPath; - } - - public String getName() { - return name; - } - - public String getDriver() { - return driver; - } - - public HostConfig getHostConfig() { - return hostConfig; - } - - public String getExecDriver() { - return execDriver; - } - - public String getMountLabel() { - return mountLabel; - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public class NetworkSettings { - - @JsonProperty("IPAddress") private String ipAddress; - @JsonProperty("IPPrefixLen") private int ipPrefixLen; - @JsonProperty("Gateway") private String gateway; - @JsonProperty("Bridge") private String bridge; - @JsonProperty("PortMapping") private Map> portMapping; - @JsonProperty("Ports") private Ports ports; - - public String getIpAddress() { - return ipAddress; - } - - public int getIpPrefixLen() { - return ipPrefixLen; - } - - public String getGateway() { - return gateway; - } - - public String getBridge() { - return bridge; - } - - public Map> getPortMapping() { - return portMapping; - } - - public Ports getPorts() { - return ports; - } - - - @Override - public String toString() { - return "NetworkSettings{" + - "ports=" + ports + - ", portMapping=" + portMapping + - ", bridge='" + bridge + '\'' + - ", gateway='" + gateway + '\'' + - ", ipPrefixLen=" + ipPrefixLen + - ", ipAddress='" + ipAddress + '\'' + - '}'; - } - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public class ContainerState { - - @JsonProperty("Running") private boolean running; - @JsonProperty("Paused") private boolean paused; - @JsonProperty("Pid") private int pid; - @JsonProperty("ExitCode") private int exitCode; - @JsonProperty("StartedAt") private String startedAt; - @JsonProperty("FinishedAt") private String finishedAt; - - public boolean isRunning() { - return running; - } - - public boolean isPaused() { - return paused; - } - - public int getPid() { - return pid; - } - - public int getExitCode() { - return exitCode; - } - - public String getStartedAt() { - return startedAt; - } - - public String getFinishedAt() { - return finishedAt; - } - - @Override - public String toString() { - return "ContainerState{" + - "running=" + running + - ", paused=" + paused + - ", pid=" + pid + - ", exitCode=" + exitCode + - ", startedAt='" + startedAt + '\'' + - ", finishedAt='" + finishedAt + '\'' + - '}'; - } - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public class HostConfig { - - @JsonProperty("Binds") - private String[] binds; - - @JsonProperty("LxcConf") - private LxcConf[] lxcConf; - - @JsonProperty("PortBindings") - private Ports portBindings; - - @JsonProperty("PublishAllPorts") - private boolean publishAllPorts; - - @JsonProperty("Privileged") - private boolean privileged; - - @JsonProperty("Dns") - private String dns; - - @JsonProperty("VolumesFrom") - private String volumesFrom; - - @JsonProperty("ContainerIDFile") - private String containerIDFile; - - @JsonProperty("DnsSearch") - private String dnsSearch; - - @JsonProperty("Links") - private String[] links; - - @JsonProperty("NetworkMode") - private String networkMode; - - public String[] getBinds() { - return binds; - } - - public LxcConf[] getLxcConf() { - return lxcConf; - } - - public Ports getPortBindings() { - return portBindings; - } - - public boolean isPublishAllPorts() { - return publishAllPorts; - } - - public boolean isPrivileged() { - return privileged; - } - - public String getDns() { - return dns; - } - - public String getVolumesFrom() { - return volumesFrom; - } - - public String getContainerIDFile() { - return containerIDFile; - } - - public String getDnsSearch() { - return dnsSearch; - } - - public String[] getLinks() { - return links; - } - - public String getNetworkMode() { - return networkMode; - } - - @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 + - ", networkMode=" + networkMode + - ", dns='" + dns + '\'' + - '}'; - } - - } - -} +package com.github.dockerjava.client.model; + + +import java.util.Arrays; +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 String getCreated() { + return created; + } + + public String getPath() { + return path; + } + + public String[] getArgs() { + return args; + } + + public ContainerConfig getConfig() { + return config; + } + + public ContainerState getState() { + return state; + } + + public String getImageId() { + return imageId; + } + + public NetworkSettings getNetworkSettings() { + return networkSettings; + } + + public String getSysInitPath() { + return sysInitPath; + } + + public String getResolvConfPath() { + return resolvConfPath; + } + + public Map getVolumes() { + return volumes; + } + + public Map getVolumesRW() { + return volumesRW; + } + + public String getHostnamePath() { + return hostnamePath; + } + + public String getHostsPath() { + return hostsPath; + } + + public String getName() { + return name; + } + + public String getDriver() { + return driver; + } + + public HostConfig getHostConfig() { + return hostConfig; + } + + public String getExecDriver() { + return execDriver; + } + + public String getMountLabel() { + return mountLabel; + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public class NetworkSettings { + + @JsonProperty("IPAddress") private String ipAddress; + @JsonProperty("IPPrefixLen") private int ipPrefixLen; + @JsonProperty("Gateway") private String gateway; + @JsonProperty("Bridge") private String bridge; + @JsonProperty("PortMapping") private Map> portMapping; + @JsonProperty("Ports") private Ports ports; + + public String getIpAddress() { + return ipAddress; + } + + public int getIpPrefixLen() { + return ipPrefixLen; + } + + public String getGateway() { + return gateway; + } + + public String getBridge() { + return bridge; + } + + public Map> getPortMapping() { + return portMapping; + } + + public Ports getPorts() { + return ports; + } + + + @Override + public String toString() { + return "NetworkSettings{" + + "ports=" + ports + + ", portMapping=" + portMapping + + ", bridge='" + bridge + '\'' + + ", gateway='" + gateway + '\'' + + ", ipPrefixLen=" + ipPrefixLen + + ", ipAddress='" + ipAddress + '\'' + + '}'; + } + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public class ContainerState { + + @JsonProperty("Running") private boolean running; + @JsonProperty("Paused") private boolean paused; + @JsonProperty("Pid") private int pid; + @JsonProperty("ExitCode") private int exitCode; + @JsonProperty("StartedAt") private String startedAt; + @JsonProperty("FinishedAt") private String finishedAt; + + public boolean isRunning() { + return running; + } + + public boolean isPaused() { + return paused; + } + + public int getPid() { + return pid; + } + + public int getExitCode() { + return exitCode; + } + + public String getStartedAt() { + return startedAt; + } + + public String getFinishedAt() { + return finishedAt; + } + + @Override + public String toString() { + return "ContainerState{" + + "running=" + running + + ", paused=" + paused + + ", pid=" + pid + + ", exitCode=" + exitCode + + ", startedAt='" + startedAt + '\'' + + ", finishedAt='" + finishedAt + '\'' + + '}'; + } + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public class HostConfig { + + @JsonProperty("Binds") + private String[] binds; + + @JsonProperty("LxcConf") + private LxcConf[] lxcConf; + + @JsonProperty("PortBindings") + private Ports portBindings; + + @JsonProperty("PublishAllPorts") + private boolean publishAllPorts; + + @JsonProperty("Privileged") + private boolean privileged; + + @JsonProperty("Dns") + private String dns; + + @JsonProperty("VolumesFrom") + private String volumesFrom; + + @JsonProperty("ContainerIDFile") + private String containerIDFile; + + @JsonProperty("DnsSearch") + private String dnsSearch; + + @JsonProperty("Links") + private String[] links; + + @JsonProperty("NetworkMode") + private String networkMode; + + public String[] getBinds() { + return binds; + } + + public LxcConf[] getLxcConf() { + return lxcConf; + } + + public Ports getPortBindings() { + return portBindings; + } + + public boolean isPublishAllPorts() { + return publishAllPorts; + } + + public boolean isPrivileged() { + return privileged; + } + + public String getDns() { + return dns; + } + + public String getVolumesFrom() { + return volumesFrom; + } + + public String getContainerIDFile() { + return containerIDFile; + } + + public String getDnsSearch() { + return dnsSearch; + } + + public String[] getLinks() { + return links; + } + + public String getNetworkMode() { + return networkMode; + } + + @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 + + ", networkMode=" + networkMode + + ", dns='" + dns + '\'' + + '}'; + } + + } + +} diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerTopResponse.java b/src/main/java/com/github/dockerjava/client/model/ContainerTopResponse.java index 6b43690a..080bccc2 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerTopResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerTopResponse.java @@ -1,46 +1,46 @@ -package com.github.dockerjava.client.model; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.base.Joiner; - -/** - * - * @author marcus - * - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class ContainerTopResponse { - - @JsonProperty("Titles") - private String[] titles; - - @JsonProperty("Processes") - private String[][] processes; - - public String[] getTitles() { - return titles; - } - - public String[][] getProcesses() { - return processes; - } - - @Override - public String toString() { - Joiner joiner = Joiner.on("; ").skipNulls(); - - StringBuffer buffer = new StringBuffer(); - buffer.append("["); - for(String[] fields: processes) { - buffer.append("[" + joiner.join(fields) + "]"); - } - buffer.append("]"); - - return "ContainerTopResponse{" + - "titles=" + joiner.join(titles) + - ", processes=" + buffer.toString() + - '}'; - } - -} +package com.github.dockerjava.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.common.base.Joiner; + +/** + * + * @author marcus + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ContainerTopResponse { + + @JsonProperty("Titles") + private String[] titles; + + @JsonProperty("Processes") + private String[][] processes; + + public String[] getTitles() { + return titles; + } + + public String[][] getProcesses() { + return processes; + } + + @Override + public String toString() { + Joiner joiner = Joiner.on("; ").skipNulls(); + + StringBuffer buffer = new StringBuffer(); + buffer.append("["); + for(String[] fields: processes) { + buffer.append("[" + joiner.join(fields) + "]"); + } + buffer.append("]"); + + return "ContainerTopResponse{" + + "titles=" + joiner.join(titles) + + ", processes=" + buffer.toString() + + '}'; + } + +} diff --git a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java index 232d2782..687161a1 100644 --- a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java @@ -1,274 +1,274 @@ -package com.github.dockerjava.client.model; - - -import java.util.Arrays; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - * "Hostname":"", - "User":"", - "Memory":0, - "MemorySwap":0, - "AttachStdin":false, - "AttachStdout":true, - "AttachStderr":true, - "PortSpecs":null, - "Tty":false, - "OpenStdin":false, - "StdinOnce":false, - "Env":null, - "Cmd":[ - "date" - ], - "Dns":null, - "Image":"base", - "Volumes":{ - "/tmp": {} - }, - "VolumesFrom":"", - "WorkingDir":"", - "DisableNetwork": false, - "ExposedPorts":{ - "22/tcp": {} - } - * - * - */ -public class CreateContainerConfig { - - @JsonProperty("Hostname") private String hostName = ""; - @JsonProperty("User") private String user = ""; - @JsonProperty("Memory") private long memoryLimit = 0; - @JsonProperty("MemorySwap") private long memorySwap = 0; - @JsonProperty("AttachStdin") private boolean attachStdin = false; - @JsonProperty("AttachStdout") private boolean attachStdout = false; - @JsonProperty("AttachStderr") private boolean attachStderr = false; - @JsonProperty("PortSpecs") private String[] portSpecs; - @JsonProperty("Tty") private boolean tty = false; - @JsonProperty("OpenStdin") private boolean stdinOpen = false; - @JsonProperty("StdinOnce") private boolean stdInOnce = false; - @JsonProperty("Env") private String[] env; - @JsonProperty("Cmd") private String[] cmd; - @JsonProperty("Dns") private String[] dns; - @JsonProperty("Image") private String image; - @JsonProperty("Volumes") private Map volumes; - @JsonProperty("VolumesFrom") private String volumesFrom = ""; - @JsonProperty("WorkingDir") private String workingDir = ""; - @JsonProperty("DisableNetwork") private boolean disableNetwork = false; - @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts; - - public CreateContainerConfig withExposedPorts(ExposedPort[] exposedPorts) { - this.exposedPorts = new ExposedPorts(exposedPorts); - return this; - } - - @JsonIgnore - public ExposedPort[] getExposedPorts() { - return exposedPorts.getExposedPorts(); - } - - - public boolean isDisableNetwork() { - return disableNetwork; - } - - public String getWorkingDir() { return workingDir; } - - public CreateContainerConfig withWorkingDir(String workingDir) { - this.workingDir = workingDir; - return this; - } - - - public String getHostName() { - return hostName; - } - - public CreateContainerConfig withDisableNetwork(boolean disableNetwork) { - this.disableNetwork = disableNetwork; - return this; - } - - public CreateContainerConfig withHostName(String hostName) { - this.hostName = hostName; - return this; - } - - public String[] getPortSpecs() { - return portSpecs; - } - - public CreateContainerConfig withPortSpecs(String[] portSpecs) { - this.portSpecs = portSpecs; - return this; - } - - public String getUser() { - return user; - } - - public CreateContainerConfig withUser(String user) { - this.user = user; - return this; - } - - public boolean isTty() { - return tty; - } - - public CreateContainerConfig withTty(boolean tty) { - this.tty = tty; - return this; - } - - public boolean isStdinOpen() { - return stdinOpen; - } - - public CreateContainerConfig withStdinOpen(boolean stdinOpen) { - this.stdinOpen = stdinOpen; - return this; - } - - public boolean isStdInOnce() { - return stdInOnce; - } - - public CreateContainerConfig withStdInOnce(boolean stdInOnce) { - this.stdInOnce = stdInOnce; - return this; - } - - public long getMemoryLimit() { - return memoryLimit; - } - - public CreateContainerConfig withMemoryLimit(long memoryLimit) { - this.memoryLimit = memoryLimit; - return this; - } - - public long getMemorySwap() { - return memorySwap; - } - - public CreateContainerConfig withMemorySwap(long memorySwap) { - this.memorySwap = memorySwap; - return this; - } - - - public boolean isAttachStdin() { - return attachStdin; - } - - public CreateContainerConfig withAttachStdin(boolean attachStdin) { - this.attachStdin = attachStdin; - return this; - } - - public boolean isAttachStdout() { - return attachStdout; - } - - public CreateContainerConfig withAttachStdout(boolean attachStdout) { - this.attachStdout = attachStdout; - return this; - } - - public boolean isAttachStderr() { - return attachStderr; - } - - public CreateContainerConfig withAttachStderr(boolean attachStderr) { - this.attachStderr = attachStderr; - return this; - } - - public String[] getEnv() { - return env; - } - - public CreateContainerConfig withEnv(String[] env) { - this.env = env; - return this; - } - - public String[] getCmd() { - return cmd; - } - - public CreateContainerConfig withCmd(String[] cmd) { - this.cmd = cmd; - return this; - } - - public String[] getDns() { - return dns; - } - - public CreateContainerConfig withDns(String[] dns) { - this.dns = dns; - return this; - } - - public String getImage() { - return image; - } - - public CreateContainerConfig withImage(String image) { - this.image = image; - return this; - } - - public Map getVolumes() { - return volumes; - } - - public CreateContainerConfig withVolumes(Map volumes) { - this.volumes = volumes; - return this; - } - - public String getVolumesFrom() { - return volumesFrom; - } - - public CreateContainerConfig withVolumesFrom(String volumesFrom) { - this.volumesFrom = volumesFrom; - return this; - } - - @Override - public String toString() { - return "CreateContainerConfig{" + - "hostName='" + hostName + '\'' + - ", portSpecs=" + Arrays.toString(portSpecs) + - ", user='" + user + '\'' + - ", tty=" + tty + - ", stdinOpen=" + stdinOpen + - ", stdInOnce=" + stdInOnce + - ", memoryLimit=" + memoryLimit + - ", memorySwap=" + memorySwap + - ", attachStdin=" + attachStdin + - ", attachStdout=" + attachStdout + - ", attachStderr=" + attachStderr + - ", env=" + Arrays.toString(env) + - ", cmd=" + Arrays.toString(cmd) + - ", dns=" + Arrays.toString(dns) + - ", image='" + image + '\'' + - ", volumes=" + volumes + - ", volumesFrom='" + volumesFrom + '\'' + - ", disableNetwork=" + disableNetwork + - ", workingDir='" + workingDir + '\'' + - '}'; - } - - -} +package com.github.dockerjava.client.model; + + +import java.util.Arrays; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + * "Hostname":"", + "User":"", + "Memory":0, + "MemorySwap":0, + "AttachStdin":false, + "AttachStdout":true, + "AttachStderr":true, + "PortSpecs":null, + "Tty":false, + "OpenStdin":false, + "StdinOnce":false, + "Env":null, + "Cmd":[ + "date" + ], + "Dns":null, + "Image":"base", + "Volumes":{ + "/tmp": {} + }, + "VolumesFrom":"", + "WorkingDir":"", + "DisableNetwork": false, + "ExposedPorts":{ + "22/tcp": {} + } + * + * + */ +public class CreateContainerConfig { + + @JsonProperty("Hostname") private String hostName = ""; + @JsonProperty("User") private String user = ""; + @JsonProperty("Memory") private long memoryLimit = 0; + @JsonProperty("MemorySwap") private long memorySwap = 0; + @JsonProperty("AttachStdin") private boolean attachStdin = false; + @JsonProperty("AttachStdout") private boolean attachStdout = false; + @JsonProperty("AttachStderr") private boolean attachStderr = false; + @JsonProperty("PortSpecs") private String[] portSpecs; + @JsonProperty("Tty") private boolean tty = false; + @JsonProperty("OpenStdin") private boolean stdinOpen = false; + @JsonProperty("StdinOnce") private boolean stdInOnce = false; + @JsonProperty("Env") private String[] env; + @JsonProperty("Cmd") private String[] cmd; + @JsonProperty("Dns") private String[] dns; + @JsonProperty("Image") private String image; + @JsonProperty("Volumes") private Map volumes; + @JsonProperty("VolumesFrom") private String volumesFrom = ""; + @JsonProperty("WorkingDir") private String workingDir = ""; + @JsonProperty("DisableNetwork") private boolean disableNetwork = false; + @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts; + + public CreateContainerConfig withExposedPorts(ExposedPort[] exposedPorts) { + this.exposedPorts = new ExposedPorts(exposedPorts); + return this; + } + + @JsonIgnore + public ExposedPort[] getExposedPorts() { + return exposedPorts.getExposedPorts(); + } + + + public boolean isDisableNetwork() { + return disableNetwork; + } + + public String getWorkingDir() { return workingDir; } + + public CreateContainerConfig withWorkingDir(String workingDir) { + this.workingDir = workingDir; + return this; + } + + + public String getHostName() { + return hostName; + } + + public CreateContainerConfig withDisableNetwork(boolean disableNetwork) { + this.disableNetwork = disableNetwork; + return this; + } + + public CreateContainerConfig withHostName(String hostName) { + this.hostName = hostName; + return this; + } + + public String[] getPortSpecs() { + return portSpecs; + } + + public CreateContainerConfig withPortSpecs(String[] portSpecs) { + this.portSpecs = portSpecs; + return this; + } + + public String getUser() { + return user; + } + + public CreateContainerConfig withUser(String user) { + this.user = user; + return this; + } + + public boolean isTty() { + return tty; + } + + public CreateContainerConfig withTty(boolean tty) { + this.tty = tty; + return this; + } + + public boolean isStdinOpen() { + return stdinOpen; + } + + public CreateContainerConfig withStdinOpen(boolean stdinOpen) { + this.stdinOpen = stdinOpen; + return this; + } + + public boolean isStdInOnce() { + return stdInOnce; + } + + public CreateContainerConfig withStdInOnce(boolean stdInOnce) { + this.stdInOnce = stdInOnce; + return this; + } + + public long getMemoryLimit() { + return memoryLimit; + } + + public CreateContainerConfig withMemoryLimit(long memoryLimit) { + this.memoryLimit = memoryLimit; + return this; + } + + public long getMemorySwap() { + return memorySwap; + } + + public CreateContainerConfig withMemorySwap(long memorySwap) { + this.memorySwap = memorySwap; + return this; + } + + + public boolean isAttachStdin() { + return attachStdin; + } + + public CreateContainerConfig withAttachStdin(boolean attachStdin) { + this.attachStdin = attachStdin; + return this; + } + + public boolean isAttachStdout() { + return attachStdout; + } + + public CreateContainerConfig withAttachStdout(boolean attachStdout) { + this.attachStdout = attachStdout; + return this; + } + + public boolean isAttachStderr() { + return attachStderr; + } + + public CreateContainerConfig withAttachStderr(boolean attachStderr) { + this.attachStderr = attachStderr; + return this; + } + + public String[] getEnv() { + return env; + } + + public CreateContainerConfig withEnv(String[] env) { + this.env = env; + return this; + } + + public String[] getCmd() { + return cmd; + } + + public CreateContainerConfig withCmd(String[] cmd) { + this.cmd = cmd; + return this; + } + + public String[] getDns() { + return dns; + } + + public CreateContainerConfig withDns(String[] dns) { + this.dns = dns; + return this; + } + + public String getImage() { + return image; + } + + public CreateContainerConfig withImage(String image) { + this.image = image; + return this; + } + + public Map getVolumes() { + return volumes; + } + + public CreateContainerConfig withVolumes(Map volumes) { + this.volumes = volumes; + return this; + } + + public String getVolumesFrom() { + return volumesFrom; + } + + public CreateContainerConfig withVolumesFrom(String volumesFrom) { + this.volumesFrom = volumesFrom; + return this; + } + + @Override + public String toString() { + return "CreateContainerConfig{" + + "hostName='" + hostName + '\'' + + ", portSpecs=" + Arrays.toString(portSpecs) + + ", user='" + user + '\'' + + ", tty=" + tty + + ", stdinOpen=" + stdinOpen + + ", stdInOnce=" + stdInOnce + + ", memoryLimit=" + memoryLimit + + ", memorySwap=" + memorySwap + + ", attachStdin=" + attachStdin + + ", attachStdout=" + attachStdout + + ", attachStderr=" + attachStderr + + ", env=" + Arrays.toString(env) + + ", cmd=" + Arrays.toString(cmd) + + ", dns=" + Arrays.toString(dns) + + ", image='" + image + '\'' + + ", volumes=" + volumes + + ", volumesFrom='" + volumesFrom + '\'' + + ", disableNetwork=" + disableNetwork + + ", workingDir='" + workingDir + '\'' + + '}'; + } + + +} diff --git a/src/main/java/com/github/dockerjava/client/model/DriverStatus.java b/src/main/java/com/github/dockerjava/client/model/DriverStatus.java index c9794f02..187e35d5 100644 --- a/src/main/java/com/github/dockerjava/client/model/DriverStatus.java +++ b/src/main/java/com/github/dockerjava/client/model/DriverStatus.java @@ -1,33 +1,33 @@ -package com.github.dockerjava.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 + - '}'; - } -} +package com.github.dockerjava.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/github/dockerjava/client/model/HostConfig.java b/src/main/java/com/github/dockerjava/client/model/HostConfig.java index d359689d..be78c1bd 100644 --- a/src/main/java/com/github/dockerjava/client/model/HostConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/HostConfig.java @@ -1,67 +1,67 @@ -package com.github.dockerjava.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") - public String[] binds; - - @JsonProperty("LxcConf") - public LxcConf[] lxcConf; - - @JsonProperty("PortBindings") - public Ports portBindings; - - @JsonProperty("PublishAllPorts") - public boolean publishAllPorts; - - @JsonProperty("Privileged") - public boolean privileged; - - @JsonProperty("Dns") - public String dns; - - @JsonProperty("VolumesFrom") - public String volumesFrom; - - @JsonProperty("ContainerIDFile") - public String containerIDFile; - - @JsonProperty("DnsSearch") - public String dnsSearch; - - @JsonProperty("Links") - public String[] links; - - @JsonProperty("NetworkMode") - public String networkMode; - - - - @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 + - ", networkMode=" + networkMode + - ", dns='" + dns + '\'' + - '}'; - } - -} +package com.github.dockerjava.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") + public String[] binds; + + @JsonProperty("LxcConf") + public LxcConf[] lxcConf; + + @JsonProperty("PortBindings") + public Ports portBindings; + + @JsonProperty("PublishAllPorts") + public boolean publishAllPorts; + + @JsonProperty("Privileged") + public boolean privileged; + + @JsonProperty("Dns") + public String dns; + + @JsonProperty("VolumesFrom") + public String volumesFrom; + + @JsonProperty("ContainerIDFile") + public String containerIDFile; + + @JsonProperty("DnsSearch") + public String dnsSearch; + + @JsonProperty("Links") + public String[] links; + + @JsonProperty("NetworkMode") + public String networkMode; + + + + @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 + + ", networkMode=" + networkMode + + ", dns='" + dns + '\'' + + '}'; + } + +} diff --git a/src/main/java/com/github/dockerjava/client/model/Image.java b/src/main/java/com/github/dockerjava/client/model/Image.java index 5472c3e2..33d81a21 100644 --- a/src/main/java/com/github/dockerjava/client/model/Image.java +++ b/src/main/java/com/github/dockerjava/client/model/Image.java @@ -1,118 +1,118 @@ -package com.github.dockerjava.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 + - '}'; - } -} +package com.github.dockerjava.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/github/dockerjava/client/model/ImageCreateResponse.java b/src/main/java/com/github/dockerjava/client/model/ImageCreateResponse.java index 05cc00b9..d23aff50 100644 --- a/src/main/java/com/github/dockerjava/client/model/ImageCreateResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ImageCreateResponse.java @@ -1,30 +1,30 @@ -package com.github.dockerjava.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 + '\'' + - '}'; - } -} +package com.github.dockerjava.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/github/dockerjava/client/model/ImageInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java index 31bd46b1..b927eb60 100644 --- a/src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java @@ -1,152 +1,152 @@ -package com.github.dockerjava.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 + '\'' + - '}'; - } -} +package com.github.dockerjava.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/github/dockerjava/client/model/Info.java b/src/main/java/com/github/dockerjava/client/model/Info.java index b26531f1..ddbc85fa 100644 --- a/src/main/java/com/github/dockerjava/client/model/Info.java +++ b/src/main/java/com/github/dockerjava/client/model/Info.java @@ -1,230 +1,230 @@ -package com.github.dockerjava.client.model; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -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) -@JsonInclude(Include.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 + - '}'; - } -} +package com.github.dockerjava.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +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) +@JsonInclude(Include.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/github/dockerjava/client/model/SearchItem.java b/src/main/java/com/github/dockerjava/client/model/SearchItem.java index e98a151b..76dadab3 100644 --- a/src/main/java/com/github/dockerjava/client/model/SearchItem.java +++ b/src/main/java/com/github/dockerjava/client/model/SearchItem.java @@ -1,54 +1,54 @@ -package com.github.dockerjava.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 + '\'' + '}'; - } -} +package com.github.dockerjava.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/github/dockerjava/client/model/StartContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java index b04d1331..db5f859d 100644 --- a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java @@ -1,50 +1,50 @@ -package com.github.dockerjava.client.model; - -import java.util.Arrays; - -import com.fasterxml.jackson.annotation.JsonProperty; - - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class StartContainerConfig { - - @JsonProperty("Binds") - public String[] binds; - - @JsonProperty("LxcConf") - public LxcConf[] lxcConf; - - @JsonProperty("PortBindings") - public Ports portBindings; - - @JsonProperty("PublishAllPorts") - public boolean publishAllPorts; - - @JsonProperty("Privileged") - public boolean privileged; - - @JsonProperty("Dns") - public String dns; - - @JsonProperty("VolumesFrom") - public String volumesFrom; - - @Override - public String toString() { - return "StartContainerConfig{" + - "binds=" + Arrays.toString(binds) + - ", lxcConf=" + Arrays.toString(lxcConf) + - ", portBindings=" + portBindings + - ", privileged=" + privileged + - ", publishAllPorts=" + publishAllPorts + - ", dns='" + dns + '\'' + - '}'; - } - - - -} +package com.github.dockerjava.client.model; + +import java.util.Arrays; + +import com.fasterxml.jackson.annotation.JsonProperty; + + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +public class StartContainerConfig { + + @JsonProperty("Binds") + public String[] binds; + + @JsonProperty("LxcConf") + public LxcConf[] lxcConf; + + @JsonProperty("PortBindings") + public Ports portBindings; + + @JsonProperty("PublishAllPorts") + public boolean publishAllPorts; + + @JsonProperty("Privileged") + public boolean privileged; + + @JsonProperty("Dns") + public String dns; + + @JsonProperty("VolumesFrom") + public String volumesFrom; + + @Override + public String toString() { + return "StartContainerConfig{" + + "binds=" + Arrays.toString(binds) + + ", lxcConf=" + Arrays.toString(lxcConf) + + ", portBindings=" + portBindings + + ", privileged=" + privileged + + ", publishAllPorts=" + publishAllPorts + + ", dns='" + dns + '\'' + + '}'; + } + + + +} diff --git a/src/main/java/com/github/dockerjava/client/model/Version.java b/src/main/java/com/github/dockerjava/client/model/Version.java index 35843ca4..ff6af729 100644 --- a/src/main/java/com/github/dockerjava/client/model/Version.java +++ b/src/main/java/com/github/dockerjava/client/model/Version.java @@ -1,103 +1,103 @@ -package com.github.dockerjava.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 + '\'' + - '}'; - } -} +package com.github.dockerjava.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 + '\'' + + '}'; + } +} From 35dbbc1b0e878218f4fafacdb0e3895dd7f92fd5 Mon Sep 17 00:00:00 2001 From: Sean Fitts Date: Thu, 3 Jul 2014 22:23:55 -0700 Subject: [PATCH 023/452] Fix static import --- src/main/java/com/github/dockerjava/client/DockerClient.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index 0b848b94..e3047240 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -1,6 +1,6 @@ package com.github.dockerjava.client; -import static org.apache.commons.io.IOUtils.*; +import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.File; import java.io.IOException; From 7e6bfd464ddfef0aa85bd98a20c351abee5e2296 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 4 Jul 2014 21:24:45 +0200 Subject: [PATCH 024/452] CRLF -> LF --- .../client/model/ContainerConfig.java | 592 +++++++-------- .../model/ContainerInspectResponse.java | 692 +++++++++--------- .../client/model/CreateContainerConfig.java | 550 +++++++------- .../client/model/StartContainerConfig.java | 210 +++--- 4 files changed, 1022 insertions(+), 1022 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java index 7331ce5b..3ca70414 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java @@ -1,296 +1,296 @@ -package com.github.dockerjava.client.model; - -import java.util.Arrays; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * - * @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 Map 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 = ""; - @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts; - @JsonProperty("OnBuild") private int[] onBuild; - - @JsonIgnore - public ExposedPort[] getExposedPorts() { - return exposedPorts.getExposedPorts(); - } - - @JsonIgnore - public void setExposedPorts(ExposedPort[] exposedPorts) { - this.exposedPorts = new ExposedPorts(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 Map getVolumes() { - return volumes; - } - - public ContainerConfig setVolumes(Map 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) + '\'' + - '}'; - } -} +package com.github.dockerjava.client.model; + +import java.util.Arrays; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * + * @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 Map 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 = ""; + @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts; + @JsonProperty("OnBuild") private int[] onBuild; + + @JsonIgnore + public ExposedPort[] getExposedPorts() { + return exposedPorts.getExposedPorts(); + } + + @JsonIgnore + public void setExposedPorts(ExposedPort[] exposedPorts) { + this.exposedPorts = new ExposedPorts(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 Map getVolumes() { + return volumes; + } + + public ContainerConfig setVolumes(Map 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/github/dockerjava/client/model/ContainerInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java index 5acfe7cf..719d93fc 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java @@ -1,347 +1,347 @@ -package com.github.dockerjava.client.model; - - -import java.util.Arrays; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonIgnore; -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 Volumes volumes; - - @JsonProperty("VolumesRW") - private Volumes 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 String getCreated() { - return created; - } - - public String getPath() { - return path; - } - - public String[] getArgs() { - return args; - } - - public ContainerConfig getConfig() { - return config; - } - - public ContainerState getState() { - return state; - } - - public String getImageId() { - return imageId; - } - - public NetworkSettings getNetworkSettings() { - return networkSettings; - } - - public String getSysInitPath() { - return sysInitPath; - } - - public String getResolvConfPath() { - return resolvConfPath; - } - - @JsonIgnore - public Volume[] getVolumes() { - return volumes.getVolumes(); - } - - @JsonIgnore - public Volume[] getVolumesRW() { - return volumesRW.getVolumes(); - } - - public String getHostnamePath() { - return hostnamePath; - } - - public String getHostsPath() { - return hostsPath; - } - - public String getName() { - return name; - } - - public String getDriver() { - return driver; - } - - public HostConfig getHostConfig() { - return hostConfig; - } - - public String getExecDriver() { - return execDriver; - } - - public String getMountLabel() { - return mountLabel; - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public class NetworkSettings { - - @JsonProperty("IPAddress") private String ipAddress; - @JsonProperty("IPPrefixLen") private int ipPrefixLen; - @JsonProperty("Gateway") private String gateway; - @JsonProperty("Bridge") private String bridge; - @JsonProperty("PortMapping") private Map> portMapping; - @JsonProperty("Ports") private Ports ports; - - public String getIpAddress() { - return ipAddress; - } - - public int getIpPrefixLen() { - return ipPrefixLen; - } - - public String getGateway() { - return gateway; - } - - public String getBridge() { - return bridge; - } - - public Map> getPortMapping() { - return portMapping; - } - - public Ports getPorts() { - return ports; - } - - - @Override - public String toString() { - return "NetworkSettings{" + - "ports=" + ports + - ", portMapping=" + portMapping + - ", bridge='" + bridge + '\'' + - ", gateway='" + gateway + '\'' + - ", ipPrefixLen=" + ipPrefixLen + - ", ipAddress='" + ipAddress + '\'' + - '}'; - } - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public class ContainerState { - - @JsonProperty("Running") private boolean running; - @JsonProperty("Paused") private boolean paused; - @JsonProperty("Pid") private int pid; - @JsonProperty("ExitCode") private int exitCode; - @JsonProperty("StartedAt") private String startedAt; - @JsonProperty("FinishedAt") private String finishedAt; - - public boolean isRunning() { - return running; - } - - public boolean isPaused() { - return paused; - } - - public int getPid() { - return pid; - } - - public int getExitCode() { - return exitCode; - } - - public String getStartedAt() { - return startedAt; - } - - public String getFinishedAt() { - return finishedAt; - } - - @Override - public String toString() { - return "ContainerState{" + - "running=" + running + - ", paused=" + paused + - ", pid=" + pid + - ", exitCode=" + exitCode + - ", startedAt='" + startedAt + '\'' + - ", finishedAt='" + finishedAt + '\'' + - '}'; - } - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public class HostConfig { - - @JsonProperty("Binds") - private String[] binds; - - @JsonProperty("LxcConf") - private LxcConf[] lxcConf; - - @JsonProperty("PortBindings") - private Ports portBindings; - - @JsonProperty("PublishAllPorts") - private boolean publishAllPorts; - - @JsonProperty("Privileged") - private boolean privileged; - - @JsonProperty("Dns") - private String dns; - - @JsonProperty("VolumesFrom") - private String volumesFrom; - - @JsonProperty("ContainerIDFile") - private String containerIDFile; - - @JsonProperty("DnsSearch") - private String dnsSearch; - - @JsonProperty("Links") - private String[] links; - - @JsonProperty("NetworkMode") - private String networkMode; - - public String[] getBinds() { - return binds; - } - - public LxcConf[] getLxcConf() { - return lxcConf; - } - - public Ports getPortBindings() { - return portBindings; - } - - public boolean isPublishAllPorts() { - return publishAllPorts; - } - - public boolean isPrivileged() { - return privileged; - } - - public String getDns() { - return dns; - } - - public String getVolumesFrom() { - return volumesFrom; - } - - public String getContainerIDFile() { - return containerIDFile; - } - - public String getDnsSearch() { - return dnsSearch; - } - - public String[] getLinks() { - return links; - } - - public String getNetworkMode() { - return networkMode; - } - - @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 + - ", networkMode=" + networkMode + - ", dns='" + dns + '\'' + - '}'; - } - - } - -} +package com.github.dockerjava.client.model; + + +import java.util.Arrays; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonIgnore; +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 Volumes volumes; + + @JsonProperty("VolumesRW") + private Volumes 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 String getCreated() { + return created; + } + + public String getPath() { + return path; + } + + public String[] getArgs() { + return args; + } + + public ContainerConfig getConfig() { + return config; + } + + public ContainerState getState() { + return state; + } + + public String getImageId() { + return imageId; + } + + public NetworkSettings getNetworkSettings() { + return networkSettings; + } + + public String getSysInitPath() { + return sysInitPath; + } + + public String getResolvConfPath() { + return resolvConfPath; + } + + @JsonIgnore + public Volume[] getVolumes() { + return volumes.getVolumes(); + } + + @JsonIgnore + public Volume[] getVolumesRW() { + return volumesRW.getVolumes(); + } + + public String getHostnamePath() { + return hostnamePath; + } + + public String getHostsPath() { + return hostsPath; + } + + public String getName() { + return name; + } + + public String getDriver() { + return driver; + } + + public HostConfig getHostConfig() { + return hostConfig; + } + + public String getExecDriver() { + return execDriver; + } + + public String getMountLabel() { + return mountLabel; + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public class NetworkSettings { + + @JsonProperty("IPAddress") private String ipAddress; + @JsonProperty("IPPrefixLen") private int ipPrefixLen; + @JsonProperty("Gateway") private String gateway; + @JsonProperty("Bridge") private String bridge; + @JsonProperty("PortMapping") private Map> portMapping; + @JsonProperty("Ports") private Ports ports; + + public String getIpAddress() { + return ipAddress; + } + + public int getIpPrefixLen() { + return ipPrefixLen; + } + + public String getGateway() { + return gateway; + } + + public String getBridge() { + return bridge; + } + + public Map> getPortMapping() { + return portMapping; + } + + public Ports getPorts() { + return ports; + } + + + @Override + public String toString() { + return "NetworkSettings{" + + "ports=" + ports + + ", portMapping=" + portMapping + + ", bridge='" + bridge + '\'' + + ", gateway='" + gateway + '\'' + + ", ipPrefixLen=" + ipPrefixLen + + ", ipAddress='" + ipAddress + '\'' + + '}'; + } + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public class ContainerState { + + @JsonProperty("Running") private boolean running; + @JsonProperty("Paused") private boolean paused; + @JsonProperty("Pid") private int pid; + @JsonProperty("ExitCode") private int exitCode; + @JsonProperty("StartedAt") private String startedAt; + @JsonProperty("FinishedAt") private String finishedAt; + + public boolean isRunning() { + return running; + } + + public boolean isPaused() { + return paused; + } + + public int getPid() { + return pid; + } + + public int getExitCode() { + return exitCode; + } + + public String getStartedAt() { + return startedAt; + } + + public String getFinishedAt() { + return finishedAt; + } + + @Override + public String toString() { + return "ContainerState{" + + "running=" + running + + ", paused=" + paused + + ", pid=" + pid + + ", exitCode=" + exitCode + + ", startedAt='" + startedAt + '\'' + + ", finishedAt='" + finishedAt + '\'' + + '}'; + } + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public class HostConfig { + + @JsonProperty("Binds") + private String[] binds; + + @JsonProperty("LxcConf") + private LxcConf[] lxcConf; + + @JsonProperty("PortBindings") + private Ports portBindings; + + @JsonProperty("PublishAllPorts") + private boolean publishAllPorts; + + @JsonProperty("Privileged") + private boolean privileged; + + @JsonProperty("Dns") + private String dns; + + @JsonProperty("VolumesFrom") + private String volumesFrom; + + @JsonProperty("ContainerIDFile") + private String containerIDFile; + + @JsonProperty("DnsSearch") + private String dnsSearch; + + @JsonProperty("Links") + private String[] links; + + @JsonProperty("NetworkMode") + private String networkMode; + + public String[] getBinds() { + return binds; + } + + public LxcConf[] getLxcConf() { + return lxcConf; + } + + public Ports getPortBindings() { + return portBindings; + } + + public boolean isPublishAllPorts() { + return publishAllPorts; + } + + public boolean isPrivileged() { + return privileged; + } + + public String getDns() { + return dns; + } + + public String getVolumesFrom() { + return volumesFrom; + } + + public String getContainerIDFile() { + return containerIDFile; + } + + public String getDnsSearch() { + return dnsSearch; + } + + public String[] getLinks() { + return links; + } + + public String getNetworkMode() { + return networkMode; + } + + @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 + + ", networkMode=" + networkMode + + ", dns='" + dns + '\'' + + '}'; + } + + } + +} diff --git a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java index 6efbb1e2..ab7dbb32 100644 --- a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java @@ -1,275 +1,275 @@ -package com.github.dockerjava.client.model; - - -import java.util.Arrays; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - * "Hostname":"", - "User":"", - "Memory":0, - "MemorySwap":0, - "AttachStdin":false, - "AttachStdout":true, - "AttachStderr":true, - "PortSpecs":null, - "Tty":false, - "OpenStdin":false, - "StdinOnce":false, - "Env":null, - "Cmd":[ - "date" - ], - "Dns":null, - "Image":"base", - "Volumes":{ - "/tmp": {} - }, - "VolumesFrom":"", - "WorkingDir":"", - "DisableNetwork": false, - "ExposedPorts":{ - "22/tcp": {} - } - * - * - */ -public class CreateContainerConfig { - - @JsonProperty("Hostname") private String hostName = ""; - @JsonProperty("User") private String user = ""; - @JsonProperty("Memory") private long memoryLimit = 0; - @JsonProperty("MemorySwap") private long memorySwap = 0; - @JsonProperty("AttachStdin") private boolean attachStdin = false; - @JsonProperty("AttachStdout") private boolean attachStdout = false; - @JsonProperty("AttachStderr") private boolean attachStderr = false; - @JsonProperty("PortSpecs") private String[] portSpecs; - @JsonProperty("Tty") private boolean tty = false; - @JsonProperty("OpenStdin") private boolean stdinOpen = false; - @JsonProperty("StdinOnce") private boolean stdInOnce = false; - @JsonProperty("Env") private String[] env; - @JsonProperty("Cmd") private String[] cmd; - @JsonProperty("Dns") private String[] dns; - @JsonProperty("Image") private String image; - @JsonProperty("Volumes") private Volumes volumes = new Volumes(); - @JsonProperty("VolumesFrom") private String volumesFrom = ""; - @JsonProperty("WorkingDir") private String workingDir = ""; - @JsonProperty("DisableNetwork") private boolean disableNetwork = false; - @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts = new ExposedPorts(); - - public CreateContainerConfig withExposedPorts(ExposedPort[] exposedPorts) { - this.exposedPorts = new ExposedPorts(exposedPorts); - return this; - } - - @JsonIgnore - public ExposedPort[] getExposedPorts() { - return exposedPorts.getExposedPorts(); - } - - - public boolean isDisableNetwork() { - return disableNetwork; - } - - public String getWorkingDir() { return workingDir; } - - public CreateContainerConfig withWorkingDir(String workingDir) { - this.workingDir = workingDir; - return this; - } - - - public String getHostName() { - return hostName; - } - - public CreateContainerConfig withDisableNetwork(boolean disableNetwork) { - this.disableNetwork = disableNetwork; - return this; - } - - public CreateContainerConfig withHostName(String hostName) { - this.hostName = hostName; - return this; - } - - public String[] getPortSpecs() { - return portSpecs; - } - - public CreateContainerConfig withPortSpecs(String[] portSpecs) { - this.portSpecs = portSpecs; - return this; - } - - public String getUser() { - return user; - } - - public CreateContainerConfig withUser(String user) { - this.user = user; - return this; - } - - public boolean isTty() { - return tty; - } - - public CreateContainerConfig withTty(boolean tty) { - this.tty = tty; - return this; - } - - public boolean isStdinOpen() { - return stdinOpen; - } - - public CreateContainerConfig withStdinOpen(boolean stdinOpen) { - this.stdinOpen = stdinOpen; - return this; - } - - public boolean isStdInOnce() { - return stdInOnce; - } - - public CreateContainerConfig withStdInOnce(boolean stdInOnce) { - this.stdInOnce = stdInOnce; - return this; - } - - public long getMemoryLimit() { - return memoryLimit; - } - - public CreateContainerConfig withMemoryLimit(long memoryLimit) { - this.memoryLimit = memoryLimit; - return this; - } - - public long getMemorySwap() { - return memorySwap; - } - - public CreateContainerConfig withMemorySwap(long memorySwap) { - this.memorySwap = memorySwap; - return this; - } - - - public boolean isAttachStdin() { - return attachStdin; - } - - public CreateContainerConfig withAttachStdin(boolean attachStdin) { - this.attachStdin = attachStdin; - return this; - } - - public boolean isAttachStdout() { - return attachStdout; - } - - public CreateContainerConfig withAttachStdout(boolean attachStdout) { - this.attachStdout = attachStdout; - return this; - } - - public boolean isAttachStderr() { - return attachStderr; - } - - public CreateContainerConfig withAttachStderr(boolean attachStderr) { - this.attachStderr = attachStderr; - return this; - } - - public String[] getEnv() { - return env; - } - - public CreateContainerConfig withEnv(String[] env) { - this.env = env; - return this; - } - - public String[] getCmd() { - return cmd; - } - - public CreateContainerConfig withCmd(String[] cmd) { - this.cmd = cmd; - return this; - } - - public String[] getDns() { - return dns; - } - - public CreateContainerConfig withDns(String[] dns) { - this.dns = dns; - return this; - } - - public String getImage() { - return image; - } - - public CreateContainerConfig withImage(String image) { - this.image = image; - return this; - } - - @JsonIgnore - public Volume[] getVolumes() { - return volumes.getVolumes(); - } - - public CreateContainerConfig withVolumes(Volume[] volumes) { - this.volumes = new Volumes(volumes); - return this; - } - - public String getVolumesFrom() { - return volumesFrom; - } - - public CreateContainerConfig withVolumesFrom(String volumesFrom) { - this.volumesFrom = volumesFrom; - return this; - } - - @Override - public String toString() { - return "CreateContainerConfig{" + - "hostName='" + hostName + '\'' + - ", portSpecs=" + Arrays.toString(portSpecs) + - ", user='" + user + '\'' + - ", tty=" + tty + - ", stdinOpen=" + stdinOpen + - ", stdInOnce=" + stdInOnce + - ", memoryLimit=" + memoryLimit + - ", memorySwap=" + memorySwap + - ", attachStdin=" + attachStdin + - ", attachStdout=" + attachStdout + - ", attachStderr=" + attachStderr + - ", env=" + Arrays.toString(env) + - ", cmd=" + Arrays.toString(cmd) + - ", dns=" + Arrays.toString(dns) + - ", image='" + image + '\'' + - ", volumes=" + volumes + - ", volumesFrom='" + volumesFrom + '\'' + - ", disableNetwork=" + disableNetwork + - ", workingDir='" + workingDir + '\'' + - '}'; - } - - -} +package com.github.dockerjava.client.model; + + +import java.util.Arrays; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + * "Hostname":"", + "User":"", + "Memory":0, + "MemorySwap":0, + "AttachStdin":false, + "AttachStdout":true, + "AttachStderr":true, + "PortSpecs":null, + "Tty":false, + "OpenStdin":false, + "StdinOnce":false, + "Env":null, + "Cmd":[ + "date" + ], + "Dns":null, + "Image":"base", + "Volumes":{ + "/tmp": {} + }, + "VolumesFrom":"", + "WorkingDir":"", + "DisableNetwork": false, + "ExposedPorts":{ + "22/tcp": {} + } + * + * + */ +public class CreateContainerConfig { + + @JsonProperty("Hostname") private String hostName = ""; + @JsonProperty("User") private String user = ""; + @JsonProperty("Memory") private long memoryLimit = 0; + @JsonProperty("MemorySwap") private long memorySwap = 0; + @JsonProperty("AttachStdin") private boolean attachStdin = false; + @JsonProperty("AttachStdout") private boolean attachStdout = false; + @JsonProperty("AttachStderr") private boolean attachStderr = false; + @JsonProperty("PortSpecs") private String[] portSpecs; + @JsonProperty("Tty") private boolean tty = false; + @JsonProperty("OpenStdin") private boolean stdinOpen = false; + @JsonProperty("StdinOnce") private boolean stdInOnce = false; + @JsonProperty("Env") private String[] env; + @JsonProperty("Cmd") private String[] cmd; + @JsonProperty("Dns") private String[] dns; + @JsonProperty("Image") private String image; + @JsonProperty("Volumes") private Volumes volumes = new Volumes(); + @JsonProperty("VolumesFrom") private String volumesFrom = ""; + @JsonProperty("WorkingDir") private String workingDir = ""; + @JsonProperty("DisableNetwork") private boolean disableNetwork = false; + @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts = new ExposedPorts(); + + public CreateContainerConfig withExposedPorts(ExposedPort[] exposedPorts) { + this.exposedPorts = new ExposedPorts(exposedPorts); + return this; + } + + @JsonIgnore + public ExposedPort[] getExposedPorts() { + return exposedPorts.getExposedPorts(); + } + + + public boolean isDisableNetwork() { + return disableNetwork; + } + + public String getWorkingDir() { return workingDir; } + + public CreateContainerConfig withWorkingDir(String workingDir) { + this.workingDir = workingDir; + return this; + } + + + public String getHostName() { + return hostName; + } + + public CreateContainerConfig withDisableNetwork(boolean disableNetwork) { + this.disableNetwork = disableNetwork; + return this; + } + + public CreateContainerConfig withHostName(String hostName) { + this.hostName = hostName; + return this; + } + + public String[] getPortSpecs() { + return portSpecs; + } + + public CreateContainerConfig withPortSpecs(String[] portSpecs) { + this.portSpecs = portSpecs; + return this; + } + + public String getUser() { + return user; + } + + public CreateContainerConfig withUser(String user) { + this.user = user; + return this; + } + + public boolean isTty() { + return tty; + } + + public CreateContainerConfig withTty(boolean tty) { + this.tty = tty; + return this; + } + + public boolean isStdinOpen() { + return stdinOpen; + } + + public CreateContainerConfig withStdinOpen(boolean stdinOpen) { + this.stdinOpen = stdinOpen; + return this; + } + + public boolean isStdInOnce() { + return stdInOnce; + } + + public CreateContainerConfig withStdInOnce(boolean stdInOnce) { + this.stdInOnce = stdInOnce; + return this; + } + + public long getMemoryLimit() { + return memoryLimit; + } + + public CreateContainerConfig withMemoryLimit(long memoryLimit) { + this.memoryLimit = memoryLimit; + return this; + } + + public long getMemorySwap() { + return memorySwap; + } + + public CreateContainerConfig withMemorySwap(long memorySwap) { + this.memorySwap = memorySwap; + return this; + } + + + public boolean isAttachStdin() { + return attachStdin; + } + + public CreateContainerConfig withAttachStdin(boolean attachStdin) { + this.attachStdin = attachStdin; + return this; + } + + public boolean isAttachStdout() { + return attachStdout; + } + + public CreateContainerConfig withAttachStdout(boolean attachStdout) { + this.attachStdout = attachStdout; + return this; + } + + public boolean isAttachStderr() { + return attachStderr; + } + + public CreateContainerConfig withAttachStderr(boolean attachStderr) { + this.attachStderr = attachStderr; + return this; + } + + public String[] getEnv() { + return env; + } + + public CreateContainerConfig withEnv(String[] env) { + this.env = env; + return this; + } + + public String[] getCmd() { + return cmd; + } + + public CreateContainerConfig withCmd(String[] cmd) { + this.cmd = cmd; + return this; + } + + public String[] getDns() { + return dns; + } + + public CreateContainerConfig withDns(String[] dns) { + this.dns = dns; + return this; + } + + public String getImage() { + return image; + } + + public CreateContainerConfig withImage(String image) { + this.image = image; + return this; + } + + @JsonIgnore + public Volume[] getVolumes() { + return volumes.getVolumes(); + } + + public CreateContainerConfig withVolumes(Volume[] volumes) { + this.volumes = new Volumes(volumes); + return this; + } + + public String getVolumesFrom() { + return volumesFrom; + } + + public CreateContainerConfig withVolumesFrom(String volumesFrom) { + this.volumesFrom = volumesFrom; + return this; + } + + @Override + public String toString() { + return "CreateContainerConfig{" + + "hostName='" + hostName + '\'' + + ", portSpecs=" + Arrays.toString(portSpecs) + + ", user='" + user + '\'' + + ", tty=" + tty + + ", stdinOpen=" + stdinOpen + + ", stdInOnce=" + stdInOnce + + ", memoryLimit=" + memoryLimit + + ", memorySwap=" + memorySwap + + ", attachStdin=" + attachStdin + + ", attachStdout=" + attachStdout + + ", attachStderr=" + attachStderr + + ", env=" + Arrays.toString(env) + + ", cmd=" + Arrays.toString(cmd) + + ", dns=" + Arrays.toString(dns) + + ", image='" + image + '\'' + + ", volumes=" + volumes + + ", volumesFrom='" + volumesFrom + '\'' + + ", disableNetwork=" + disableNetwork + + ", workingDir='" + workingDir + '\'' + + '}'; + } + + +} diff --git a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java index 44017cf0..ab2b3a15 100644 --- a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java @@ -1,106 +1,106 @@ -package com.github.dockerjava.client.model; - -import java.util.Arrays; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class StartContainerConfig { - - @JsonProperty("Binds") - private Binds binds = new Binds(); - - @JsonProperty("LxcConf") - private LxcConf[] lxcConf; - - @JsonProperty("PortBindings") - private Ports portBindings; - - @JsonProperty("PublishAllPorts") - private boolean publishAllPorts; - - @JsonProperty("Privileged") - private boolean privileged; - - @JsonProperty("Dns") - private String dns; - - @JsonProperty("VolumesFrom") - private String volumesFrom; - - @JsonIgnore - public Bind[] getBinds() { - return binds.getBinds(); - } - - @JsonIgnore - public void setBinds(Bind[] binds) { - this.binds = new Binds(binds); - } - - public LxcConf[] getLxcConf() { - return lxcConf; - } - - public void setLxcConf(LxcConf[] lxcConf) { - this.lxcConf = lxcConf; - } - - public Ports getPortBindings() { - return portBindings; - } - - public void setPortBindings(Ports portBindings) { - this.portBindings = portBindings; - } - - public boolean isPublishAllPorts() { - return publishAllPorts; - } - - public void setPublishAllPorts(boolean publishAllPorts) { - this.publishAllPorts = publishAllPorts; - } - - public boolean isPrivileged() { - return privileged; - } - - public void setPrivileged(boolean privileged) { - this.privileged = privileged; - } - - public String getDns() { - return dns; - } - - public void setDns(String dns) { - this.dns = dns; - } - - public String getVolumesFrom() { - return volumesFrom; - } - - public void setVolumesFrom(String volumesFrom) { - this.volumesFrom = volumesFrom; - } - - @Override - public String toString() { - return "StartContainerConfig{" + - "binds=" + binds + - ", lxcConf=" + Arrays.toString(lxcConf) + - ", portBindings=" + portBindings + - ", privileged=" + privileged + - ", publishAllPorts=" + publishAllPorts + - ", dns='" + dns + '\'' + - '}'; - } -} +package com.github.dockerjava.client.model; + +import java.util.Arrays; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ +public class StartContainerConfig { + + @JsonProperty("Binds") + private Binds binds = new Binds(); + + @JsonProperty("LxcConf") + private LxcConf[] lxcConf; + + @JsonProperty("PortBindings") + private Ports portBindings; + + @JsonProperty("PublishAllPorts") + private boolean publishAllPorts; + + @JsonProperty("Privileged") + private boolean privileged; + + @JsonProperty("Dns") + private String dns; + + @JsonProperty("VolumesFrom") + private String volumesFrom; + + @JsonIgnore + public Bind[] getBinds() { + return binds.getBinds(); + } + + @JsonIgnore + public void setBinds(Bind[] binds) { + this.binds = new Binds(binds); + } + + public LxcConf[] getLxcConf() { + return lxcConf; + } + + public void setLxcConf(LxcConf[] lxcConf) { + this.lxcConf = lxcConf; + } + + public Ports getPortBindings() { + return portBindings; + } + + public void setPortBindings(Ports portBindings) { + this.portBindings = portBindings; + } + + public boolean isPublishAllPorts() { + return publishAllPorts; + } + + public void setPublishAllPorts(boolean publishAllPorts) { + this.publishAllPorts = publishAllPorts; + } + + public boolean isPrivileged() { + return privileged; + } + + public void setPrivileged(boolean privileged) { + this.privileged = privileged; + } + + public String getDns() { + return dns; + } + + public void setDns(String dns) { + this.dns = dns; + } + + public String getVolumesFrom() { + return volumesFrom; + } + + public void setVolumesFrom(String volumesFrom) { + this.volumesFrom = volumesFrom; + } + + @Override + public String toString() { + return "StartContainerConfig{" + + "binds=" + binds + + ", lxcConf=" + Arrays.toString(lxcConf) + + ", portBindings=" + portBindings + + ", privileged=" + privileged + + ", publishAllPorts=" + publishAllPorts + + ", dns='" + dns + '\'' + + '}'; + } +} From 11c0554daeea5f2028fc185ba5446f35e096658e Mon Sep 17 00:00:00 2001 From: Michael O'Cleirigh Date: Fri, 4 Jul 2014 15:31:52 -0400 Subject: [PATCH 025/452] Add support for environment variable substition for ADD and COPY resources Supports the case where the name of the file is supposed to be resolved using an environment variable. ENV VAR sub ADD files/$VAR.dat /$VAR.dat ADD files/${VAR}.dat /${VAR}.dat In both cases the VAR is substituted for sub. This allows the tar file creation process to capture the real source file. --- .../client/command/BuildImgCmd.java | 67 +++++++++++++++++-- 1 file changed, 62 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java index 76039a33..6070fbb9 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -6,7 +6,9 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -35,7 +37,9 @@ public class BuildImgCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(BuildImgCmd.class); - private static final Pattern ADD_PATTERN = Pattern.compile("^ADD\\s+(.*)\\s+(.*)$"); + private static final Pattern ADD_OR_COPY_PATTERN = Pattern.compile("^(ADD|COPY)\\s+(.*)\\s+(.*)$"); + + private static final Pattern ENV_PATTERN = Pattern.compile("^ENV\\s+(.*)\\s+(.*)$"); private File dockerFolder = null; private InputStream tarInputStream = null; @@ -133,14 +137,40 @@ protected File buildDockerFolderTar() { List filesToAdd = new ArrayList(); filesToAdd.add(dockerFile); + MapenvironmentMap = new HashMap(); + + int lineNumber = 0; + for (String cmd : dockerFileContent) { - final Matcher matcher = ADD_PATTERN.matcher(cmd.trim()); + + lineNumber++; + + if (cmd.trim().isEmpty() || cmd.startsWith("#")) + continue; // skip emtpy and commend lines + + final Matcher envMatcher = ENV_PATTERN.matcher(cmd.trim()); + + if (envMatcher.find()) { + if (envMatcher.groupCount() != 2) + throw new DockerException(String.format("Wrong ENV format on line [%d]", lineNumber)); + + String variable = envMatcher.group(1).trim(); + + String value = envMatcher.group(2).trim(); + + environmentMap.put(variable, value); + } + + + final Matcher matcher = ADD_OR_COPY_PATTERN.matcher(cmd.trim()); if (matcher.find()) { - if (matcher.groupCount() != 2) { - throw new DockerException(String.format("Wrong format on line [%s]", cmd)); + if (matcher.groupCount() != 3) { + throw new DockerException(String.format("Wrong ADD or COPY format on line [%d]", lineNumber)); } - String resource = matcher.group(1).trim(); + String extractedResource = matcher.group(2); + + String resource = filterForEnvironmentVars(extractedResource, environmentMap); if(isFileResource(resource)) { File src = new File(resource); @@ -170,6 +200,33 @@ protected File buildDockerFolderTar() { } } + private String filterForEnvironmentVars(String extractedResource, + Map environmentMap) { + + if (environmentMap.size() > 0) { + + String currentResourceContent = extractedResource; + + for (Map.Entry entry : environmentMap.entrySet()) { + + String variable = entry.getKey(); + + String replacementValue = entry.getValue(); + + // handle: $VARIABLE case + currentResourceContent = currentResourceContent.replaceAll("\\$" + variable, replacementValue); + + // handle ${VARIABLE} case + currentResourceContent = currentResourceContent.replaceAll("\\$\\{" + variable + "\\}", replacementValue); + + } + + return currentResourceContent; + } + else + return extractedResource; + } + private static boolean isFileResource(String resource) { URI uri; try { From 5cbefec285357443230ae5a663f8b60034bee4ab Mon Sep 17 00:00:00 2001 From: Michael O'Cleirigh Date: Mon, 7 Jul 2014 13:41:01 -0400 Subject: [PATCH 026/452] Add extra parameters to the DockerClient constructor's The defaults remain 10 seconds for the read time out and to enable the LoggingFilter. Allows the caller to change the read time out and to disable the LoggingFilter For large images the logging filter spam's the console with the binary data that is being transferred. This new setting allows it to be turned off. --- .../dockerjava/client/DockerClient.java | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index 0dc927f6..deb6ebed 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -67,13 +67,20 @@ public class DockerClient { private AuthConfig authConfig; public DockerClient() throws DockerException { - this(Config.createConfig()); + this(10000, true); + } + public DockerClient(Integer readTimeout, boolean enableLoggingFilter) throws DockerException { + this(Config.createConfig(), readTimeout, enableLoggingFilter); } public DockerClient(String serverUrl) throws DockerException { - this(configWithServerUrl(serverUrl)); + this(serverUrl, 10000, true); } + public DockerClient(String serverUrl, Integer readTimeout, boolean enableLoggingFilter) throws DockerException { + this(configWithServerUrl(serverUrl), readTimeout, enableLoggingFilter); + } + private static Config configWithServerUrl(String serverUrl) throws DockerException { final Config c = Config.createConfig(); @@ -81,7 +88,7 @@ private static Config configWithServerUrl(String serverUrl) return c; } - private DockerClient(Config config) { + public DockerClient(Config config, Integer readTimeout, boolean enableLoggingFilter) { ClientConfig clientConfig = new DefaultClientConfig(); SchemeRegistry schemeRegistry = new SchemeRegistry(); @@ -101,14 +108,19 @@ private DockerClient(Config config) { client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, null, false), clientConfig); - client.setReadTimeout(10000); + // 1 hour + client.setReadTimeout(readTimeout); client.addFilter(new JsonClientFilter()); - client.addFilter(new SelectiveLoggingFilter()); + + if (enableLoggingFilter) + client.addFilter(new SelectiveLoggingFilter()); baseResource = client.resource(config.url + "/v" + config.version); } + + public void setCredentials(String username, String password, String email) { if (username == null) { throw new IllegalArgumentException("username is null"); From e6666f8b77c5df609d61999e96f8cc74772bf483 Mon Sep 17 00:00:00 2001 From: Michael O'Cleirigh Date: Mon, 7 Jul 2014 14:37:09 -0400 Subject: [PATCH 027/452] Add new unit test case for ENV substitution --- .../client/command/BuildImageCmdTest.java | 11 ++++++++ .../resources/testENVSubstitution/Dockerfile | 11 ++++++++ .../subst-file-2-abc123.txt | 1 + .../testENVSubstitution/subst-file-abc123.txt | 1 + .../resources/testENVSubstitution/testrun.sh | 26 +++++++++++++++++++ 5 files changed, 50 insertions(+) create mode 100644 src/test/resources/testENVSubstitution/Dockerfile create mode 100644 src/test/resources/testENVSubstitution/subst-file-2-abc123.txt create mode 100644 src/test/resources/testENVSubstitution/subst-file-abc123.txt create mode 100644 src/test/resources/testENVSubstitution/testrun.sh diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java index 803835ad..6fb5cbcc 100644 --- a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java @@ -12,6 +12,8 @@ import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Method; +import java.net.URI; +import java.net.URISyntaxException; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; @@ -113,6 +115,7 @@ public void testDockerBuilderAddFolder() throws DockerException, dockerfileBuild(baseDir, "Successfully executed testAddFolder.sh"); } + private String dockerfileBuild(File baseDir, String expectedText) throws DockerException, IOException { @@ -222,4 +225,12 @@ public void testNetCatDockerfileBuilder() throws DockerException, dockerClient.stopContainerCmd(container.getId()).withTimeout(0).exec(); } + + @Test + public void testAddAndCopySubstitution () throws DockerException, IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("testENVSubstitution").getFile()); + dockerfileBuild(baseDir, "Successfully executed testAddFolder.sh"); + + } } \ No newline at end of file diff --git a/src/test/resources/testENVSubstitution/Dockerfile b/src/test/resources/testENVSubstitution/Dockerfile new file mode 100644 index 00000000..de06ddbb --- /dev/null +++ b/src/test/resources/testENVSubstitution/Dockerfile @@ -0,0 +1,11 @@ +FROM ubuntu + +# Copy testrun.sh files into the container + +ENV variable abc123 +ADD ./testrun.sh /tmp/ +ADD ./subst-file-$variable.txt /tmp/ +COPY ./subst-file-2-${variable}.txt /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/testENVSubstitution/subst-file-2-abc123.txt b/src/test/resources/testENVSubstitution/subst-file-2-abc123.txt new file mode 100644 index 00000000..ac1acee1 --- /dev/null +++ b/src/test/resources/testENVSubstitution/subst-file-2-abc123.txt @@ -0,0 +1 @@ +Old File \ No newline at end of file diff --git a/src/test/resources/testENVSubstitution/subst-file-abc123.txt b/src/test/resources/testENVSubstitution/subst-file-abc123.txt new file mode 100644 index 00000000..ac1acee1 --- /dev/null +++ b/src/test/resources/testENVSubstitution/subst-file-abc123.txt @@ -0,0 +1 @@ +Old File \ No newline at end of file diff --git a/src/test/resources/testENVSubstitution/testrun.sh b/src/test/resources/testENVSubstitution/testrun.sh new file mode 100644 index 00000000..90a416a1 --- /dev/null +++ b/src/test/resources/testENVSubstitution/testrun.sh @@ -0,0 +1,26 @@ +#!/bin/sh + +echo "Hello Word" > hello.txt +echo "hello.txt Created" + +TEST_FILE=/tmp/subst-file-abc123.txt +TEST_FILE_2=/tmp/subst-file-2-abc123.txt + +if test -f $TEST_FILE +then + + if test -f $TEST_FILE_2 + then + exit 0 + else + echo "$TEST_FILE_2 does not exist" + exit 1 + fi + +else + + echo "$TEST_FILE does not exist" + exit 1 + +fi + From 1a9fd61c2052f9520d5a9ca8e13f9e3dbb56b1ad Mon Sep 17 00:00:00 2001 From: Ritesh Patel Date: Tue, 8 Jul 2014 13:12:32 -0700 Subject: [PATCH 028/452] Adding support for env and hostname --- pom.xml | 2 +- .../client/command/CreateContainerCmd.java | 13 ++++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5aee03c6..f51d774f 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.9.1-SNAPSHOT + 1.0.0-SNAPSHOT docker-java https://github.com/docker-java/docker-java diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index 3326fc57..55ee54de 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -61,7 +61,18 @@ public CreateContainerCmd withVolumes(Volume... volumes) { this.containerCreateConfig.withVolumes(volumes); return this; } - + + public CreateContainerCmd withEnv(String... env) { + Preconditions.checkNotNull(env, "env was not specified"); + this.containerCreateConfig.withEnv(env); + return this; + } + + public CreateContainerCmd withHostName(String hostName) { + Preconditions.checkNotNull(hostName, "hostName was not specified"); + this.containerCreateConfig.withHostName(hostName); + return this; + } public CreateContainerCmd withName(String name) { Preconditions.checkNotNull(name, "name was not specified"); From d7d25151b017dfac3772dd8527f5785017650bfc Mon Sep 17 00:00:00 2001 From: Ritesh Patel Date: Tue, 8 Jul 2014 13:15:54 -0700 Subject: [PATCH 029/452] Revert version number --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f51d774f..5aee03c6 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 1.0.0-SNAPSHOT + 0.9.1-SNAPSHOT docker-java https://github.com/docker-java/docker-java From 369cb01ff08743a36d7a07f3bdf175d25117b6a1 Mon Sep 17 00:00:00 2001 From: Wolfgang Jung Date: Wed, 9 Jul 2014 13:49:13 +0200 Subject: [PATCH 030/452] Added Container-Linking Linking is now available through StartContainerCmd --- .../client/command/StartContainerCmd.java | 11 ++- .../github/dockerjava/client/model/Link.java | 63 +++++++++++++++ .../github/dockerjava/client/model/Links.java | 76 +++++++++++++++++++ .../client/model/StartContainerConfig.java | 13 ++++ 4 files changed, 162 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/github/dockerjava/client/model/Link.java create mode 100644 src/main/java/com/github/dockerjava/client/model/Links.java diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index 9cdc9a63..fb06741e 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -1,3 +1,4 @@ + package com.github.dockerjava.client.command; import javax.ws.rs.core.MediaType; @@ -8,6 +9,7 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.github.dockerjava.client.model.Bind; +import com.github.dockerjava.client.model.Link; import com.github.dockerjava.client.model.LxcConf; import com.github.dockerjava.client.model.Ports; import com.github.dockerjava.client.model.StartContainerConfig; @@ -37,7 +39,14 @@ public StartContainerCmd withBinds(Bind... binds) { return this; } - public StartContainerCmd withLxcConf(LxcConf[] lxcConf) { + public StartContainerCmd withLinks(final Link... links) + { + startContainerConfig.setLinks(links); + return this; + } + + public StartContainerCmd withLxcConf(final LxcConf[] lxcConf) + { startContainerConfig.setLxcConf(lxcConf); return this; } diff --git a/src/main/java/com/github/dockerjava/client/model/Link.java b/src/main/java/com/github/dockerjava/client/model/Link.java new file mode 100644 index 00000000..4e3eb137 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/Link.java @@ -0,0 +1,63 @@ + +package com.github.dockerjava.client.model; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +public class Link +{ + + private final String name; + + private final String alias; + + public Link(final String name, final String alias) + { + this.name = name; + this.alias = alias; + } + + public String getName() + { + return name; + } + + public String getAlias() + { + return alias; + } + + public static Link parse(final String serialized) + { + try { + final String[] parts = serialized.split(":"); + switch (parts.length) { + case 2: { + return new Link(parts[0], parts[1]); + } + default: { + throw new RuntimeException("Error parsing Link '" + serialized + "'"); + } + } + } catch (final Exception e) { + throw new RuntimeException("Error parsing Link '" + serialized + "'"); + } + } + + @Override + public boolean equals(final Object obj) + { + if (obj instanceof Link) { + final Link other = (Link) obj; + return new EqualsBuilder().append(name, other.getName()).append(alias, other.getAlias()).isEquals(); + } else + return super.equals(obj); + } + + @Override + public int hashCode() + { + return new HashCodeBuilder().append(name).append(alias).toHashCode(); + } + +} diff --git a/src/main/java/com/github/dockerjava/client/model/Links.java b/src/main/java/com/github/dockerjava/client/model/Links.java new file mode 100644 index 00000000..24a02bdd --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/model/Links.java @@ -0,0 +1,76 @@ + +package com.github.dockerjava.client.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +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.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.node.NullNode; + +@JsonSerialize(using = Links.Serializer.class) +@JsonDeserialize(using = Links.Deserializer.class) +public class Links +{ + + private final Link[] links; + + public Links(final Link... links) + { + this.links = links; + } + + public Link[] getLinks() + { + return links; + } + + public static class Serializer extends JsonSerializer + { + + @Override + public void serialize(final Links links, final JsonGenerator jsonGen, final SerializerProvider serProvider) throws IOException, JsonProcessingException + { + jsonGen.writeStartArray(); + for (final Link link : links.getLinks()) { + final String s = link.getName() + ":" + link.getAlias(); + jsonGen.writeString(s); + } + jsonGen.writeEndArray(); + } + + } + + public static class Deserializer extends JsonDeserializer + { + + @Override + public Links deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException + { + final List binds = new ArrayList(); + final ObjectCodec oc = jsonParser.getCodec(); + final JsonNode node = oc.readTree(jsonParser); + for (final Iterator> it = node.fields(); it.hasNext();) { + + final Map.Entry field = it.next(); + if (!field.getValue().equals(NullNode.getInstance())) { + binds.add(Link.parse(field.getKey())); + } + } + return new Links(binds.toArray(new Link[0])); + } + } + +} diff --git a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java index ab2b3a15..ae8088f9 100644 --- a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java @@ -15,6 +15,9 @@ public class StartContainerConfig { @JsonProperty("Binds") private Binds binds = new Binds(); + @JsonProperty("Links") + private Links links = new Links(); + @JsonProperty("LxcConf") private LxcConf[] lxcConf; @@ -43,6 +46,16 @@ public void setBinds(Bind[] binds) { this.binds = new Binds(binds); } + @JsonIgnore + public Link[] getLinks() { + return links.getLinks(); + } + + @JsonIgnore + public void setLinks(Link[] links) { + this.links = new Links(links); + } + public LxcConf[] getLxcConf() { return lxcConf; } From 5eb8342bf73533f25308874f73d5c1756e75f8a7 Mon Sep 17 00:00:00 2001 From: Sean Fitts Date: Wed, 9 Jul 2014 14:11:33 -0700 Subject: [PATCH 031/452] Update BuildImgCmd options to match default client behavior --- .../client/command/BuildImgCmd.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java index 5a92fb56..daca11ae 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -38,6 +38,8 @@ public class BuildImgCmd extends AbstrDockerCmd { private InputStream tarInputStream = null; private String tag; private boolean noCache; + private boolean remove = true; + private boolean quiet; public BuildImgCmd(File dockerFolder) { @@ -61,11 +63,23 @@ public BuildImgCmd withNoCache(boolean noCache) { return this; } + public BuildImgCmd withRemove(boolean rm) { + this.remove = rm; + return this; + } + + public BuildImgCmd withQuiet(boolean quiet) { + this.quiet = quiet; + return this; + } + @Override public String toString() { return new StringBuilder("build ") .append(tag != null ? "-t " + tag + " " : "") .append(noCache ? "--nocache=true " : "") + .append(quiet ? "--quiet=true " : "") + .append(!remove ? "--rm=false " : "") .append(dockerFolder != null ? dockerFolder.getPath() : "-") .toString(); } @@ -91,6 +105,12 @@ protected ClientResponse callDocker(final InputStream dockerFolderTarInputStream if (noCache) { params.add("nocache", "true"); } + if (remove) { + params.add("rm", "true"); + } + if (quiet) { + params.add("q", "true"); + } WebResource webResource = baseResource.path("/build").queryParams(params); From daf922b54ce458b3a5163e4227e72e94901973a3 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 10 Jul 2014 00:16:39 +0200 Subject: [PATCH 032/452] basic remote api v1.13 compatibility --- .../client/command/BuildImgCmd.java | 8 +- .../dockerjava/client/command/CommitCmd.java | 95 ++++-- .../client/command/RemoveImageCmd.java | 4 + .../client/command/StartContainerCmd.java | 3 + .../client/command/StopContainerCmd.java | 3 + .../dockerjava/client/model/CommitConfig.java | 228 ++++++++++---- .../model/ContainerInspectResponse.java | 5 +- .../client/model/ImageInspectResponse.java | 105 ++----- .../github/dockerjava/client/model/Info.java | 290 +++++++----------- .../client/utils/JsonClientFilter.java | 2 +- src/main/resources/docker.io.properties | 2 +- .../client/AbstractDockerClientTest.java | 4 +- .../client/command/BuildImageCmdTest.java | 4 +- .../client/command/ListContainersCmdTest.java | 10 +- .../client/command/LogContainerCmdTest.java | 2 +- .../client/command/PushImageCmdTest.java | 2 +- .../client/command/StartContainerCmdTest.java | 61 +++- .../resources/testENVSubstitution/testrun.sh | 1 + 18 files changed, 475 insertions(+), 354 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java index 6070fbb9..f5af321f 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -31,6 +31,8 @@ /** * * Build an image from Dockerfile. + * + * TODO: http://docs.docker.com/reference/builder/#dockerignore * */ public class BuildImgCmd extends AbstrDockerCmd { @@ -63,6 +65,10 @@ public BuildImgCmd withTag(String tag) { return this; } + public BuildImgCmd withNoCache() { + return withNoCache(true); + } + public BuildImgCmd withNoCache(boolean noCache) { this.noCache = noCache; return this; @@ -170,7 +176,7 @@ protected File buildDockerFolderTar() { String extractedResource = matcher.group(2); - String resource = filterForEnvironmentVars(extractedResource, environmentMap); + String resource = filterForEnvironmentVars(extractedResource, environmentMap).trim(); if(isFileResource(resource)) { File src = new File(resource); diff --git a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java index 16a76985..a6f72014 100644 --- a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java @@ -24,11 +24,15 @@ public class CommitCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(CommitCmd.class); - private CommitConfig commitConfig; + private String containerId, repository, tag, message, author; + + private boolean pause = true; + + private CommitConfig commitConfig = new CommitConfig(); public CommitCmd(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); - this.commitConfig = new CommitConfig(containerId); + this.containerId = containerId; } public CommitCmd withCommitConfig(CommitConfig commitConfig) { @@ -37,44 +41,81 @@ public CommitCmd withCommitConfig(CommitConfig commitConfig) { return this; } - public CommitCmd withRepo(String repo) { - Preconditions.checkNotNull(repo, "repo was not specified"); - this.commitConfig.setRepo(repo); + public CommitCmd withAttachStderr(boolean attachStderr) { + this.commitConfig.setAttachStderr(attachStderr); return this; } - public CommitCmd withTag(String tag) { - Preconditions.checkNotNull(tag, "tag was not specified"); - this.commitConfig.setTag(tag); + public CommitCmd withAttachStderr() { + return withAttachStderr(true); + } + + public CommitCmd withAttachStdin(boolean attachStdin) { + this.commitConfig.setAttachStdin(attachStdin); return this; } + + public CommitCmd withAttachStdin() { + return withAttachStdin(true); + } - public CommitCmd withMessage(String message) { - Preconditions.checkNotNull(message, "message was not specified"); - this.commitConfig.setMessage(message); + public CommitCmd withAttachStdout(boolean attachStdout) { + this.commitConfig.setAttachStdout(attachStdout); + return this; + } + + public CommitCmd withAttachStdout() { + return withAttachStdout(true); + } + + public CommitCmd withCmd(String... cmd) { + Preconditions.checkNotNull(cmd, "cmd was not specified"); + this.commitConfig.setCmd(cmd); + return this; + } + + public CommitCmd withDisableNetwork(boolean disableNetwork) { + this.commitConfig.setDisableNetwork(disableNetwork); return this; } public CommitCmd withAuthor(String author) { Preconditions.checkNotNull(author, "author was not specified"); - this.commitConfig.setAuthor(author); + this.author = author; + return this; + } + + public CommitCmd withMessage(String message) { + Preconditions.checkNotNull(message, "message was not specified"); + this.message = message; + return this; + } + + public CommitCmd withTag(String tag) { + Preconditions.checkNotNull(tag, "tag was not specified"); + this.tag = tag; + return this; + } + + public CommitCmd withRepository(String repository) { + Preconditions.checkNotNull(repository, "repository was not specified"); + this.repository = repository; return this; } - public CommitCmd withRun(String run) { - Preconditions.checkNotNull(run, "run was not specified"); - this.commitConfig.setRun(run); + public CommitCmd withPause(boolean pause) { + this.pause = pause; return this; } @Override public String toString() { return new StringBuilder("commit ") - .append(commitConfig.getAuthor() != null ? "--author " + commitConfig.getAuthor() + " " : "") - .append(commitConfig.getMessage() != null ? "--message " + commitConfig.getMessage() + " " : "") - .append(commitConfig.getContainerId()) - .append(commitConfig.getRepo() != null ? " " + commitConfig.getRepo() + ":" : " ") - .append(commitConfig.getTag() != null ? commitConfig.getTag() : "") + .append(author != null ? "--author " + author + " " : "") + .append(message != null ? "--message " + message + " " : "") + .append(containerId) + .append(repository != null ? " " + repository + ":" : " ") + .append(tag != null ? tag : "") .toString(); } @@ -86,12 +127,12 @@ protected String impl() throws DockerException { checkCommitConfig(commitConfig); MultivaluedMap params = new MultivaluedMapImpl(); - params.add("container", commitConfig.getContainerId()); - 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()); + params.add("container", containerId); + params.add("repo", repository); + params.add("tag", tag); + params.add("m", message); + params.add("author", author); + params.add("pause", pause ? "1" : "0"); WebResource webResource = baseResource.path("/commit").queryParams(params); @@ -101,7 +142,7 @@ protected String impl() throws DockerException { return ObjectNode.get("Id").asText(); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 404) { - throw new NotFoundException(String.format("No such container %s", commitConfig.getContainerId())); + throw new NotFoundException(String.format("No such container %s", containerId)); } else if (exception.getResponse().getStatus() == 500) { throw new DockerException("Server error", exception); } else { diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java b/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java index da6f658c..5bc2765c 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java @@ -33,6 +33,10 @@ public RemoveImageCmd withImageId(String imageId) { return this; } + public RemoveImageCmd withForce() { + return withForce(true); + } + public RemoveImageCmd withForce(boolean force) { this.force = force; return this; diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index fb06741e..b78109e5 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -108,6 +108,9 @@ protected Void impl() throws DockerException { } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such container %s", containerId)); + } else if(exception.getResponse().getStatus() == 304) { + //no error + LOGGER.warn("Container already started {}", containerId); } else if (exception.getResponse().getStatus() == 204) { //no error LOGGER.trace("Successfully started container {}", containerId); diff --git a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java index ed395619..9805cae1 100644 --- a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java @@ -59,6 +59,9 @@ protected Void impl() throws DockerException { } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 404) { LOGGER.warn("No such container {}", containerId); + } else if(exception.getResponse().getStatus() == 304) { + //no error + LOGGER.warn("Container already stopped {}", containerId); } else if (exception.getResponse().getStatus() == 204) { //no error LOGGER.trace("Successfully stopped container {}", containerId); diff --git a/src/main/java/com/github/dockerjava/client/model/CommitConfig.java b/src/main/java/com/github/dockerjava/client/model/CommitConfig.java index 734119e8..309570d9 100644 --- a/src/main/java/com/github/dockerjava/client/model/CommitConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/CommitConfig.java @@ -1,6 +1,5 @@ package com.github.dockerjava.client.model; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** @@ -8,80 +7,195 @@ * @author Konstantin Pelykh (kpelykh@gmail.com) * */ -@JsonIgnoreProperties(ignoreUnknown = true) public class CommitConfig { - @JsonProperty("container") - private String containerId; + @JsonProperty("AttachStdin") + private boolean attachStdin; - @JsonProperty("repo") - private String repo; + @JsonProperty("AttachStdout") + private boolean attachStdout; - @JsonProperty("tag") - private String tag; + @JsonProperty("AttachStderr") + private boolean attachStderr; - @JsonProperty("m") - private String message; + @JsonProperty("Cmd") + private String[] cmd; + + @JsonProperty("DisableNetwork") + private boolean disableNetwork; + + @JsonProperty("Env") + private String[] env; + + @JsonProperty("ExposedPorts") + private ExposedPorts exposedPorts; + + @JsonProperty("Hostname") + private String hostname; + + @JsonProperty("Memory") + private Integer memory; + + @JsonProperty("MemorySwap") + private Integer memorySwap; + + @JsonProperty("OpenStdin") + private boolean openStdin; + + @JsonProperty("PortSpecs") + private String[] portSpecs; + + @JsonProperty("StdinOnce") + private boolean stdinOnce; + + @JsonProperty("Tty") + private boolean tty; + + @JsonProperty("User") + private String user; + + @JsonProperty("Volumes") + private Volumes volumes; + + @JsonProperty("WorkingDir") + private String workingDir; + + 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; + } - //author (eg. “John Hannibal Smith â€) - @JsonProperty("author") - private String author; + public void setAttachStderr(boolean attachStderr) { + this.attachStderr = attachStderr; + } - //config automatically applied when the image is run. (ex: {“Cmdâ€: [“catâ€, “/worldâ€], “PortSpecsâ€:[“22â€]}) - @JsonProperty("run") - private String run; + public String[] getCmd() { + return cmd; + } - public String getContainerId() { - return containerId; - } + public void setCmd(String[] cmd) { + this.cmd = cmd; + } - public String getRepo() { - return repo; - } + public boolean isDisableNetwork() { + return disableNetwork; + } - public String getTag() { - return tag; - } + public void setDisableNetwork(boolean disableNetwork) { + this.disableNetwork = disableNetwork; + } - public String getMessage() { - return message; - } + public String[] getEnv() { + return env; + } - public String getAuthor() { - return author; - } + public void setEnv(String[] env) { + this.env = env; + } - public String getRun() { - return run; - } + public ExposedPorts getExposedPorts() { + return exposedPorts; + } - public CommitConfig setRepo(String repo) { - this.repo = repo; - return this; - } + public void setExposedPorts(ExposedPorts exposedPorts) { + this.exposedPorts = exposedPorts; + } - public CommitConfig setTag(String tag) { - this.tag = tag; - return this; - } + public String getHostname() { + return hostname; + } - public CommitConfig setMessage(String message) { - this.message = message; - return this; - } + public void setHostname(String hostname) { + this.hostname = hostname; + } - public CommitConfig setAuthor(String author) { - this.author = author; - return this; - } + public Integer getMemory() { + return memory; + } - public CommitConfig setRun(String run) { - this.run = run; - return this; - } + public void setMemory(Integer memory) { + this.memory = memory; + } - public CommitConfig(String containerId) { - this.containerId = containerId; - } + public Integer getMemorySwap() { + return memorySwap; + } + + public void setMemorySwap(Integer memorySwap) { + this.memorySwap = memorySwap; + } + + public boolean isOpenStdin() { + return openStdin; + } + + public void setOpenStdin(boolean openStdin) { + this.openStdin = openStdin; + } + + public String[] getPortSpecs() { + return portSpecs; + } + + public void setPortSpecs(String[] portSpecs) { + this.portSpecs = portSpecs; + } + + public boolean isStdinOnce() { + return stdinOnce; + } + + public void setStdinOnce(boolean stdinOnce) { + this.stdinOnce = stdinOnce; + } + + public boolean isTty() { + return tty; + } + + public void setTty(boolean tty) { + this.tty = tty; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public Volumes getVolumes() { + return volumes; + } + + public void setVolumes(Volumes volumes) { + this.volumes = volumes; + } + + public String getWorkingDir() { + return workingDir; + } + + public void setWorkingDir(String workingDir) { + this.workingDir = workingDir; + } + + } diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java index 719d93fc..16ce36cb 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java @@ -16,7 +16,7 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class ContainerInspectResponse { - @JsonProperty("ID") + @JsonProperty("Id") private String id; @JsonProperty("Created") @@ -29,7 +29,7 @@ public class ContainerInspectResponse { private String[] args; @JsonProperty("Config") - public ContainerConfig config; + private ContainerConfig config; @JsonProperty("State") private ContainerState state; @@ -276,6 +276,7 @@ public class HostConfig { @JsonProperty("DnsSearch") private String dnsSearch; + // TODO: use Links class here? @JsonProperty("Links") private String[] links; diff --git a/src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java index b927eb60..64b872f3 100644 --- a/src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java @@ -10,129 +10,92 @@ */ @JsonIgnoreProperties(ignoreUnknown = true) public class ImageInspectResponse { - - @JsonProperty("id") + + @JsonProperty("Architecture") + private String arch; + + @JsonProperty("Author") + private String author; + + @JsonProperty("Comment") + private String comment; + + @JsonProperty("Config") + private ContainerConfig config; + + @JsonProperty("Container") + private String container; + + @JsonProperty("ContainerConfig") + private ContainerConfig containerConfig; + + @JsonProperty("Created") + private String created; + + @JsonProperty("DockerVersion") + private String dockerVersion; + + @JsonProperty("Id") private String id; + + @JsonProperty("Os") + private String os; - @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("Parent") + private String parent; - @JsonProperty("author") private String author; - - @JsonProperty("os") private String os; + @JsonProperty("Size") + private long size; 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 + @Override public String toString() { return "ImageInspectResponse{" + "id='" + id + '\'' + diff --git a/src/main/java/com/github/dockerjava/client/model/Info.java b/src/main/java/com/github/dockerjava/client/model/Info.java index ddbc85fa..54185cbe 100644 --- a/src/main/java/com/github/dockerjava/client/model/Info.java +++ b/src/main/java/com/github/dockerjava/client/model/Info.java @@ -6,225 +6,153 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import java.util.Arrays; import java.util.List; /** - * + * * @author Konstantin Pelykh (kpelykh@gmail.com) - * + * */ @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class Info { - @JsonProperty("Debug") - private boolean debug; + @JsonProperty("Containers") + private int containers; - @JsonProperty("Containers") - private int containers; + @JsonProperty("Debug") + private boolean debug; - @JsonProperty("Driver") - private String driver; + @JsonProperty("Driver") + private String driver; - @JsonProperty("DriverStatus") - private List driverStatuses; + @JsonProperty("DriverStatus") + private List driverStatuses; + @JsonProperty("ExecutionDriver") + private String executionDriver; - @JsonProperty("Images") - private int images; + @JsonProperty("IPv4Forwarding") + private String IPv4Forwarding; - @JsonProperty("IPv4Forwarding") - private String IPv4Forwarding; + @JsonProperty("Images") + private int images; - @JsonProperty("IndexServerAddress") - private String IndexServerAddress; + @JsonProperty("IndexServerAddress") + private String IndexServerAddress; + @JsonProperty("InitPath") + private String initPath; - @JsonProperty("InitPath") - private String initPath; + @JsonProperty("InitSha1") + private String initSha1; - @JsonProperty("InitSha1") - private String initSha1; + @JsonProperty("KernelVersion") + private String kernelVersion; - @JsonProperty("KernelVersion") - private String kernelVersion; + @JsonProperty("MemoryLimit") + private boolean memoryLimit; - @JsonProperty("LXCVersion") - private String lxcVersion; + @JsonProperty("NEventsListener") + private long nEventListener; - @JsonProperty("MemoryLimit") - private boolean memoryLimit; + @JsonProperty("NFd") + private int NFd; - @JsonProperty("NEventsListener") - private long nEventListener; + @JsonProperty("NGoroutines") + private int NGoroutines; - @JsonProperty("NFd") - private int NFd; + @JsonProperty("Sockets") + private String[] sockets; - @JsonProperty("NGoroutines") - private int NGoroutines; - - @JsonProperty("SwapLimit") - private int swapLimit; + @JsonProperty("SwapLimit") + private int swapLimit; - @JsonProperty("ExecutionDriver") - private String executionDriver; + public boolean isDebug() { + return debug; + } - public boolean isDebug() { - return debug; - } + public void setDebug(boolean debug) { + this.debug = debug; + } - public void setDebug(boolean debug) { - this.debug = debug; - } + public int getContainers() { + return containers; + } + + public String getDriver() { + return driver; + } - public int getContainers() { - return containers; - } + public List getDriverStatuses() { + return driverStatuses; + } - public void setContainers(int containers) { - this.containers = containers; - } + public int getImages() { + return images; + } - public String getDriver() { - return driver; - } + public String getIPv4Forwarding() { + return IPv4Forwarding; + } - public void setDriver(String driver) { - this.driver = driver; - } + public String getIndexServerAddress() { + return IndexServerAddress; + } - public List getDriverStatuses() { - return driverStatuses; - } + public String getInitPath() { + return initPath; + } - public void setDriverStatuses(List driverStatuses) { - this.driverStatuses = driverStatuses; - } + public String getInitSha1() { + return initSha1; + } - public int getImages() { - return images; - } + public String getKernelVersion() { + return kernelVersion; + } - public void setImages(int images) { - this.images = images; - } + public String[] getSockets() { + return sockets; + } - public String getIPv4Forwarding() { - return IPv4Forwarding; - } + public boolean isMemoryLimit() { + return memoryLimit; + } - public void setIPv4Forwarding(String IPv4Forwarding) { - this.IPv4Forwarding = IPv4Forwarding; - } + public long getnEventListener() { + return nEventListener; + } - 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 + - '}'; - } + public int getNFd() { + return NFd; + } + + public int getNGoroutines() { + return NGoroutines; + } + + public int getSwapLimit() { + return swapLimit; + } + + public String getExecutionDriver() { + return 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 + '\'' + ", sockets='" + Arrays.asList(sockets) + '\'' + + ", memoryLimit=" + memoryLimit + ", nEventListener=" + + nEventListener + ", NFd=" + NFd + ", NGoroutines=" + + NGoroutines + ", swapLimit=" + swapLimit + '}'; + } } diff --git a/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java b/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java index 89633b52..a29255d3 100644 --- a/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java +++ b/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java @@ -16,7 +16,7 @@ public ClientResponse handle(ClientRequest cr) { // Call the next filter ClientResponse resp = getNext().handle(cr); String respContentType = resp.getHeaders().getFirst("Content-Type"); - if (respContentType.startsWith("text/plain")) { + if (respContentType != null && respContentType.startsWith("text/plain")) { String newContentType = "application/json" + respContentType.substring(10); resp.getHeaders().putSingle("Content-Type", newContentType); } diff --git a/src/main/resources/docker.io.properties b/src/main/resources/docker.io.properties index b154e876..6251c969 100644 --- a/src/main/resources/docker.io.properties +++ b/src/main/resources/docker.io.properties @@ -1,2 +1,2 @@ docker.io.url=http://localhost:2375 -docker.io.version=1.11 \ No newline at end of file +docker.io.version=1.13 \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 9adecd30..caead681 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -34,7 +34,7 @@ public void beforeTest() throws DockerException { LOG.info("Pulling image 'busybox'"); // need to block until image is pulled completely - logResponseStream(dockerClient.pullImageCmd("busybox").exec()); + logResponseStream(dockerClient.pullImageCmd("busybox:latest").exec()); @@ -64,6 +64,7 @@ public void afterMethod(ITestResult result) { dockerClient.killContainerCmd(container).exec(); dockerClient.removeContainerCmd(container).exec(); } catch (DockerException ignore) { + ignore.printStackTrace(); } } @@ -72,6 +73,7 @@ public void afterMethod(ITestResult result) { try { dockerClient.removeImageCmd(image).exec(); } catch (DockerException ignore) { + ignore.printStackTrace(); } } diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java index 6fb5cbcc..42860427 100644 --- a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java @@ -174,7 +174,7 @@ public void testNetCatDockerfileBuilder() throws DockerException, File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("netcat").getFile()); - ClientResponse response = dockerClient.buildImageCmd(baseDir).exec(); + ClientResponse response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); StringWriter logwriter = new StringWriter(); @@ -230,7 +230,7 @@ public void testNetCatDockerfileBuilder() throws DockerException, public void testAddAndCopySubstitution () throws DockerException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("testENVSubstitution").getFile()); - dockerfileBuild(baseDir, "Successfully executed testAddFolder.sh"); + dockerfileBuild(baseDir, "testENVSubstitution successfully completed"); } } \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java b/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java index a5fd5cbf..df24a811 100644 --- a/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java @@ -53,12 +53,10 @@ public void afterMethod(ITestResult result) { @Test public void testListContainers() throws DockerException { - String testImage = "hackmann/empty"; + String testImage = "busybox"; - LOG.info("Pulling image 'hackmann/empty'"); // need to block until image is pulled completely logResponseStream(dockerClient.pullImageCmd(testImage).exec()); - tmpImgs.add(testImage); List containers = dockerClient.listContainersCmd().withShowAll(true).exec(); assertThat(containers, notNullValue()); @@ -67,7 +65,7 @@ public void testListContainers() throws DockerException { int size = containers.size(); ContainerCreateResponse container1 = dockerClient - .createContainerCmd(testImage).withCmd(new String[] { "echo" }).exec(); + .createContainerCmd(testImage).withCmd("echo").exec(); assertThat(container1.getId(), not(isEmptyString())); @@ -96,12 +94,12 @@ public void testListContainers() throws DockerException { assertThat(filteredContainers.size(), is(equalTo(1))); for(Container container: filteredContainers) { - LOG.info("filteredContainer: " + container.getImage()); + LOG.info("filteredContainer: " + container); } Container container2 = filteredContainers.get(0); assertThat(container2.getCommand(), not(isEmptyString())); - assertThat(container2.getImage(), equalTo(testImage + ":latest")); + assertThat(container2.getImage(), startsWith(testImage + ":")); } diff --git a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java index b9ac5ad7..4db44621 100644 --- a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java @@ -44,7 +44,7 @@ public void afterMethod(ITestResult result) { } @Test - public void attach() throws DockerException, IOException { + public void logContainer() throws DockerException, IOException { String snippet = "hello world"; diff --git a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java index cc68cd46..f04322ec 100644 --- a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java @@ -62,7 +62,7 @@ public void testPushLatest() throws Exception { tmpContainers.add(container.getId()); LOG.info("Commiting container: {}", container.toString()); - String imageId = dockerClient.commitCmd(container.getId()).withRepo(username + "/busybox").exec(); + String imageId = dockerClient.commitCmd(container.getId()).withRepository(username + "/busybox").exec(); logResponseStream(dockerClient.pushImageCmd(username + "/busybox").exec()); diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java index 1a4a535e..052e64f4 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -25,6 +25,7 @@ import com.github.dockerjava.client.model.ContainerCreateResponse; import com.github.dockerjava.client.model.ContainerInspectResponse; import com.github.dockerjava.client.model.ExposedPort; +import com.github.dockerjava.client.model.Link; import com.github.dockerjava.client.model.Ports; import com.github.dockerjava.client.model.Volume; @@ -129,11 +130,67 @@ public void startContainerWithPortBindings() throws DockerException { tmpContainers.add(container.getId()); } + @Test + public void startContainerWithLinking() throws DockerException { + + ContainerCreateResponse container1 = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999").withName("container1").exec(); + + LOG.info("Created container1 {}", container1.toString()); + assertThat(container1.getId(), not(isEmptyString())); + tmpContainers.add(container1.getId()); + + dockerClient.startContainerCmd(container1.getId()).exec(); + + ContainerInspectResponse containerInspectResponse1 = dockerClient + .inspectContainerCmd(container1.getId()).exec(); + LOG.info("Container1 Inspect: {}", containerInspectResponse1.toString()); + + assertThat(containerInspectResponse1.getConfig(), is(notNullValue())); + assertThat(containerInspectResponse1.getId(), not(isEmptyString())); + assertThat(containerInspectResponse1.getId(), startsWith(container1.getId())); + assertThat(containerInspectResponse1.getName(), equalTo("/container1")); + assertThat(containerInspectResponse1.getImageId(), not(isEmptyString())); + assertThat(containerInspectResponse1.getState(), is(notNullValue())); + assertThat(containerInspectResponse1.getState().isRunning(), is(true)); + + if (!containerInspectResponse1.getState().isRunning()) { + assertThat(containerInspectResponse1.getState().getExitCode(), + is(equalTo(0))); + } + + ContainerCreateResponse container2 = dockerClient + .createContainerCmd("busybox").withCmd("true").withName("container2").exec(); + + LOG.info("Created container2 {}", container2.toString()); + assertThat(container2.getId(), not(isEmptyString())); + tmpContainers.add(container2.getId()); + + dockerClient.startContainerCmd(container2.getId()).withLinks(new Link("container1", "container1Link")).exec(); + + ContainerInspectResponse containerInspectResponse2 = dockerClient + .inspectContainerCmd(container2.getId()).exec(); + LOG.info("Container2 Inspect: {}", containerInspectResponse2.toString()); + + assertThat(containerInspectResponse2.getConfig(), is(notNullValue())); + assertThat(containerInspectResponse2.getId(), not(isEmptyString())); + assertThat(containerInspectResponse2.getHostConfig(), is(notNullValue())); + assertThat(containerInspectResponse2.getHostConfig().getLinks(), is(notNullValue())); + assertThat(containerInspectResponse2.getHostConfig().getLinks(), equalTo(new String[] {"/container1:/container2/container1Link"})); + assertThat(containerInspectResponse2.getId(), startsWith(container2.getId())); + assertThat(containerInspectResponse2.getName(), equalTo("/container2")); + assertThat(containerInspectResponse2.getImageId(), not(isEmptyString())); + assertThat(containerInspectResponse2.getState(), is(notNullValue())); + assertThat(containerInspectResponse2.getState().isRunning(), is(true)); + + } + + @Test public void startContainer() throws DockerException { ContainerCreateResponse container = dockerClient - .createContainerCmd("busybox").withCmd(new String[] { "true" }).exec(); + .createContainerCmd("busybox").withCmd("true").exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); @@ -145,7 +202,7 @@ public void startContainer() throws DockerException { .inspectContainerCmd(container.getId()).exec(); LOG.info("Container Inspect: {}", containerInspectResponse.toString()); - assertThat(containerInspectResponse.config, is(notNullValue())); + assertThat(containerInspectResponse.getConfig(), is(notNullValue())); assertThat(containerInspectResponse.getId(), not(isEmptyString())); assertThat(containerInspectResponse.getId(), diff --git a/src/test/resources/testENVSubstitution/testrun.sh b/src/test/resources/testENVSubstitution/testrun.sh index 90a416a1..e79c944f 100644 --- a/src/test/resources/testENVSubstitution/testrun.sh +++ b/src/test/resources/testENVSubstitution/testrun.sh @@ -11,6 +11,7 @@ then if test -f $TEST_FILE_2 then + echo "testENVSubstitution successfully completed" exit 0 else echo "$TEST_FILE_2 does not exist" From e2f260dd80773e44855360226151f73c0d243005 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Thu, 10 Jul 2014 00:21:17 +0200 Subject: [PATCH 033/452] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5e521f4a..6c566a51 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Java API client for [Docker](http://docs.docker.io/ "Docker") -Supports a subset of the Docker Client API v1.12, Docker Server version 1.0 +Supports a subset of the Docker Client API v1.13, Docker Server version 1.1 Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/docker-java-dev "docker-java") From be4f77ae335e0bba90abd8020777203926b434fd Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 10 Jul 2014 21:28:54 +0200 Subject: [PATCH 034/452] Added tests for ENV and HOSTNAME --- .../command/CreateContainerCmdTest.java | 51 +++++++++++++++++-- 1 file changed, 47 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java index a6a1a7e1..a0eaa48e 100644 --- a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java @@ -1,11 +1,11 @@ package com.github.dockerjava.client.command; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.isEmptyString; -import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.*; + import java.lang.reflect.Method; +import java.util.Arrays; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; @@ -43,11 +43,13 @@ public void afterMethod(ITestResult result) { } @Test - public void createContainer() throws DockerException { + public void createContainerWithVolume() throws DockerException { ContainerCreateResponse container = dockerClient .createContainerCmd("busybox").withVolumes(new Volume("/var/log")).withCmd("true").exec(); + tmpContainers.add(container.getId()); + LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); @@ -58,9 +60,50 @@ public void createContainer() throws DockerException { assertThat(containerInspectResponse.getConfig().getVolumes().keySet(), contains("/var/log")); + + } + + @Test + public void createContainerWithEnv() throws DockerException { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withEnv("VARIABLE=success").withCmd("env").exec(); + tmpContainers.add(container.getId()); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); + + assertThat(Arrays.asList(containerInspectResponse.getConfig().getEnv()), contains("VARIABLE=success","HOME=/","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")); + + dockerClient.startContainerCmd(container.getId()).exec(); + + assertThat(logResponseStream(dockerClient.logContainerCmd(container.getId()).withStdOut().exec()), containsString("VARIABLE=success")); } + @Test + public void createContainerWithHostname() throws DockerException { + + ContainerCreateResponse container = dockerClient + .createContainerCmd("busybox").withHostName("docker-java").withCmd("env").exec(); + + tmpContainers.add(container.getId()); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); + + assertThat(containerInspectResponse.getConfig().getHostName(), equalTo("docker-java")); + + dockerClient.startContainerCmd(container.getId()).exec(); + + assertThat(logResponseStream(dockerClient.logContainerCmd(container.getId()).withStdOut().exec()), containsString("HOSTNAME=docker-java")); + } } From af26a5d8f9fa9d78ee8cd5da257a317f213c2964 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Thu, 10 Jul 2014 21:31:30 +0200 Subject: [PATCH 035/452] Update LICENSE --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index d6456956..38275f2f 100644 --- a/LICENSE +++ b/LICENSE @@ -187,7 +187,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright [2013] [docker-java@googlegroups.com] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. From 8a6441ce95d3a9137d2eca5bba4be8d50451b48a Mon Sep 17 00:00:00 2001 From: Ritesh Patel Date: Mon, 14 Jul 2014 10:01:49 -0700 Subject: [PATCH 036/452] Fixed issue with StartContainerCmd The accept header was being set incorrectly to text instead of json. Also added a defensive null check in JsonClientFilter. --- .../com/github/dockerjava/client/command/StartContainerCmd.java | 2 +- .../com/github/dockerjava/client/utils/JsonClientFilter.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index 9cdc9a63..395fa8d5 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -88,7 +88,7 @@ protected Void impl() throws DockerException { try { LOGGER.trace("POST: {}", webResource); - Builder builder = webResource.accept(MediaType.TEXT_PLAIN); + Builder builder = webResource.accept(MediaType.APPLICATION_JSON); if (startContainerConfig != null) { builder.type(MediaType.APPLICATION_JSON).post(startContainerConfig); } else { diff --git a/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java b/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java index 89633b52..a29255d3 100644 --- a/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java +++ b/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java @@ -16,7 +16,7 @@ public ClientResponse handle(ClientRequest cr) { // Call the next filter ClientResponse resp = getNext().handle(cr); String respContentType = resp.getHeaders().getFirst("Content-Type"); - if (respContentType.startsWith("text/plain")) { + if (respContentType != null && respContentType.startsWith("text/plain")) { String newContentType = "application/json" + respContentType.substring(10); resp.getHeaders().putSingle("Content-Type", newContentType); } From ee778e2a07d7eb6cc265ec9dbe7efb4fc64c3e65 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 14 Jul 2014 21:38:05 +0200 Subject: [PATCH 037/452] Added pause/unpause commands --- .../client/command/PauseContainerCmd.java | 66 +++++++++++++++++++ .../client/command/UnpauseContainerCmd.java | 66 +++++++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java diff --git a/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java new file mode 100644 index 00000000..18ce0b7a --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java @@ -0,0 +1,66 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * Pause a container. + * + * @param containerId - Id of the container + * + */ +public class PauseContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(PauseContainerCmd.class); + + private String containerId; + + public PauseContainerCmd(String containerId) { + withContainerId(containerId); + } + + public PauseContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + @Override + public String toString() { + return new StringBuilder("pause ") + .append(containerId) + .toString(); + } + + protected Integer impl() throws DockerException { + WebResource webResource = baseResource.path(String.format("/containers/%s/pause", containerId)); + + ClientResponse response = null; + + try { + LOGGER.trace("POST: {}", webResource); + response = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ClientResponse.class); + } 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 paused container {}", containerId); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + + return response.getStatus(); + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java new file mode 100644 index 00000000..9ad1c95a --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java @@ -0,0 +1,66 @@ +package com.github.dockerjava.client.command; + +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.client.DockerException; +import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * Unpause a container. + * + * @param containerId - Id of the container + * + */ +public class UnpauseContainerCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(UnpauseContainerCmd.class); + + private String containerId; + + public UnpauseContainerCmd(String containerId) { + withContainerId(containerId); + } + + public UnpauseContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + @Override + public String toString() { + return new StringBuilder("pause ") + .append(containerId) + .toString(); + } + + protected Integer impl() throws DockerException { + WebResource webResource = baseResource.path(String.format("/containers/%s/unpause", containerId)); + + ClientResponse response = null; + + try { + LOGGER.trace("POST: {}", webResource); + response = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ClientResponse.class); + } 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 paused container {}", containerId); + } else if (exception.getResponse().getStatus() == 500) { + throw new DockerException("Server error", exception); + } else { + throw new DockerException(exception); + } + } + + return response.getStatus(); + } +} From c9eec27e86791bd3c592de6ccf321d24cf4ba11d Mon Sep 17 00:00:00 2001 From: Ritesh Patel Date: Mon, 14 Jul 2014 19:28:50 -0700 Subject: [PATCH 038/452] Fixed startContainer use cases Using top command instead of true so that the container keeps running and returns the valid state --- .../dockerjava/client/command/StartContainerCmdTest.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java index 1a4a535e..8734f736 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -82,6 +82,7 @@ public void startContainerWithVolumes() throws DockerException { containerInspectResponse = dockerClient.inspectContainerCmd(container .getId()).exec(); + assertThat(Arrays.asList(containerInspectResponse.getVolumes()), contains(volume1, volume2)); @@ -99,7 +100,7 @@ public void startContainerWithPortBindings() throws DockerException { ContainerCreateResponse container = dockerClient .createContainerCmd("busybox") - .withCmd("true").withExposedPorts(tcp22, tcp23).exec(); + .withCmd("top").withExposedPorts(tcp22, tcp23).exec(); LOG.info("Created container {}", container.toString()); @@ -116,6 +117,8 @@ public void startContainerWithPortBindings() throws DockerException { containerInspectResponse = dockerClient.inspectContainerCmd(container .getId()).exec(); + + assertThat(containerInspectResponse.getState().isRunning(), is(true)); assertThat(Arrays.asList(containerInspectResponse.getConfig().getExposedPorts()), contains(tcp22, tcp23)); @@ -133,7 +136,7 @@ public void startContainerWithPortBindings() throws DockerException { public void startContainer() throws DockerException { ContainerCreateResponse container = dockerClient - .createContainerCmd("busybox").withCmd(new String[] { "true" }).exec(); + .createContainerCmd("busybox").withCmd(new String[] { "top" }).exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); From c95c9675b86cbb5841a1430e0d1669eedca7e2b8 Mon Sep 17 00:00:00 2001 From: Ritesh Patel Date: Mon, 14 Jul 2014 10:01:49 -0700 Subject: [PATCH 039/452] Fixed issue with StartContainerCmd The accept header was being set incorrectly to text instead of json. Also added a defensive null check in JsonClientFilter. --- .../com/github/dockerjava/client/command/StartContainerCmd.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index b78109e5..3a3eebb3 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -97,7 +97,7 @@ protected Void impl() throws DockerException { try { LOGGER.trace("POST: {}", webResource); - Builder builder = webResource.accept(MediaType.TEXT_PLAIN); + Builder builder = webResource.accept(MediaType.APPLICATION_JSON); if (startContainerConfig != null) { builder.type(MediaType.APPLICATION_JSON).post(startContainerConfig); } else { From 622071e4bee343187ee5199fea30516c8d88eba1 Mon Sep 17 00:00:00 2001 From: Ritesh Patel Date: Mon, 14 Jul 2014 22:14:38 -0700 Subject: [PATCH 040/452] Merge branch 'master' of https://github.com/NirmataOSS/docker-java Conflicts: src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest .java --- .../dockerjava/client/command/StartContainerCmdTest.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java index 052e64f4..4a8b9abc 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -83,6 +83,7 @@ public void startContainerWithVolumes() throws DockerException { containerInspectResponse = dockerClient.inspectContainerCmd(container .getId()).exec(); + assertThat(Arrays.asList(containerInspectResponse.getVolumes()), contains(volume1, volume2)); @@ -100,7 +101,7 @@ public void startContainerWithPortBindings() throws DockerException { ContainerCreateResponse container = dockerClient .createContainerCmd("busybox") - .withCmd("true").withExposedPorts(tcp22, tcp23).exec(); + .withCmd("top").withExposedPorts(tcp22, tcp23).exec(); LOG.info("Created container {}", container.toString()); @@ -117,6 +118,8 @@ public void startContainerWithPortBindings() throws DockerException { containerInspectResponse = dockerClient.inspectContainerCmd(container .getId()).exec(); + + assertThat(containerInspectResponse.getState().isRunning(), is(true)); assertThat(Arrays.asList(containerInspectResponse.getConfig().getExposedPorts()), contains(tcp22, tcp23)); @@ -190,7 +193,7 @@ public void startContainerWithLinking() throws DockerException { public void startContainer() throws DockerException { ContainerCreateResponse container = dockerClient - .createContainerCmd("busybox").withCmd("true").exec(); + .createContainerCmd("busybox").withCmd(new String[] { "top" }).exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); From 4a6780bb243377ddcb0dc5a23396876ecbef37e0 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 15 Jul 2014 20:37:33 +0200 Subject: [PATCH 041/452] Cleanup of model classes --- .../com/github/dockerjava/client/Config.java | 4 + .../client/command/CreateContainerCmd.java | 3 - .../client/command/KillContainerCmd.java | 12 +- .../client/command/LogContainerCmd.java | 16 + .../dockerjava/client/model/Container.java | 42 +- .../client/model/ContainerConfig.java | 449 +++++++----------- .../model/ContainerInspectResponse.java | 94 ++-- .../github/dockerjava/client/model/Image.java | 65 +-- .../github/dockerjava/client/model/Info.java | 4 - .../dockerjava/client/model/Version.java | 60 +-- .../client/command/ListImagesCmdTest.java | 10 +- 11 files changed, 290 insertions(+), 469 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/Config.java b/src/main/java/com/github/dockerjava/client/Config.java index e007859e..207d1300 100644 --- a/src/main/java/com/github/dockerjava/client/Config.java +++ b/src/main/java/com/github/dockerjava/client/Config.java @@ -9,6 +9,8 @@ class Config { URI url; String version, username, password, email; + Integer readTimeout; + boolean enableLoggingFilter; private Config() { } @@ -51,6 +53,8 @@ static Config createConfig() throws DockerException { c.username = p.getProperty("docker.io.username"); c.password = p.getProperty("docker.io.password"); c.email = p.getProperty("docker.io.email"); + c.readTimeout = Integer.valueOf(p.getProperty("docker.io.readTimeout", "1000")); + c.enableLoggingFilter = Boolean.valueOf(p.getProperty("docker.io.enableLoggingFilter", "true")); return c; } diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index 55ee54de..267bf52c 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -1,8 +1,5 @@ package com.github.dockerjava.client.command; -import java.util.HashMap; -import java.util.Map; - import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; diff --git a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java index 58ac5564..1c650262 100644 --- a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java @@ -17,7 +17,7 @@ public class KillContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(KillContainerCmd.class); - private String containerId; + private String containerId, signal; public KillContainerCmd(String containerId) { withContainerId(containerId); @@ -29,6 +29,12 @@ public KillContainerCmd withContainerId(String containerId) { return this; } + public KillContainerCmd withSignal(String signal) { + Preconditions.checkNotNull(signal, "signal was not specified"); + this.signal = signal; + return this; + } + @Override public String toString() { return "kill " + containerId; @@ -36,6 +42,10 @@ public String toString() { protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/kill", containerId)); + + if(signal != null) { + webResource = webResource.queryParam("signal", signal); + } try { LOGGER.trace("POST: {}", webResource); diff --git a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java index cda2e090..d18ec9ac 100644 --- a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java @@ -26,6 +26,8 @@ * @param timestamps * - true or false, if true, print timestamps for every log line. * Defaults to false. + * @param tail + * - `all` or ``, Output specified number of lines at the end of logs */ public class LogContainerCmd extends AbstrDockerCmd { @@ -33,6 +35,8 @@ public class LogContainerCmd extends AbstrDockerCmd 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 = ""; - @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts; - @JsonProperty("OnBuild") private int[] onBuild; - - @JsonIgnore - public ExposedPort[] getExposedPorts() { - return exposedPorts.getExposedPorts(); - } - - @JsonIgnore - public void setExposedPorts(ExposedPort[] exposedPorts) { - this.exposedPorts = new ExposedPorts(exposedPorts); + @JsonProperty("AttachStderr") + private boolean attachStderr = false; + + @JsonProperty("AttachStdin") + private boolean attachStdin = false; + + @JsonProperty("AttachStdout") + private boolean attachStdout = false; + + @JsonProperty("Cmd") + private String[] cmd; + + @JsonProperty("CpuShares") + private int cpuShares = 0; + + @JsonProperty("Cpuset") + private String cpuset = ""; + + @JsonProperty("Domainname") + private String domainName = ""; + + @JsonProperty("Entrypoint") + private String[] entrypoint = new String[] {}; + + @JsonProperty("Env") + private String[] env; + + @JsonProperty("ExposedPorts") + private ExposedPorts exposedPorts; + + @JsonProperty("Hostname") + private String hostName = ""; + + @JsonProperty("Image") + private String image; + + @JsonProperty("Memory") + private long memoryLimit = 0; + + @JsonProperty("MemorySwap") + private long memorySwap = 0; + + @JsonProperty("NetworkDisabled") + private boolean networkDisabled = false; + + @JsonProperty("OnBuild") + private int[] onBuild; + + @JsonProperty("OpenStdin") + private boolean stdinOpen = false; + + @JsonProperty("PortSpecs") + private String[] portSpecs; + + @JsonProperty("StdinOnce") + private boolean stdInOnce = false; + + @JsonProperty("Tty") + private boolean tty = false; + + @JsonProperty("User") + private String user = ""; + + @JsonProperty("Volumes") + private Map volumes; + + @JsonProperty("WorkingDir") + private String workingDir = ""; + + @JsonIgnore + public ExposedPort[] getExposedPorts() { + return exposedPorts.getExposedPorts(); + } + + public boolean isNetworkDisabled() { + return networkDisabled; + } + + public String getDomainName() { + return domainName; + } + + public String getWorkingDir() { + return workingDir; + } + + public String getHostName() { + return hostName; + } + + public String[] getPortSpecs() { + return portSpecs; } - 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 Map getVolumes() { - return volumes; - } - - public ContainerConfig setVolumes(Map 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 String getUser() { + return user; } - - public int[] getOnBuild() { + + public boolean isTty() { + return tty; + } + + public boolean isStdinOpen() { + return stdinOpen; + } + + public boolean isStdInOnce() { + return stdInOnce; + } + + public long getMemoryLimit() { + return memoryLimit; + } + + public long getMemorySwap() { + return memorySwap; + } + + public int getCpuShares() { + return cpuShares; + } + + public String getCpuset() { + return cpuset; + } + + public boolean isAttachStdin() { + return attachStdin; + } + + public boolean isAttachStdout() { + return attachStdout; + } + + public boolean isAttachStderr() { + return attachStderr; + } + + public String[] getEnv() { + return env; + } + + public String[] getCmd() { + return cmd; + } + + public String getImage() { + return image; + } + + public Map getVolumes() { + return volumes; + } + + public String[] getEntrypoint() { + return entrypoint; + } + + 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) + + ", image='" + image + '\'' + + ", volumes=" + volumes + + '\'' + ", entrypoint=" + Arrays.toString(entrypoint) + + ", networkDisabled=" + networkDisabled + ", workingDir='" + workingDir + '\'' + + ", domainName='" + domainName + '\'' + ", onBuild='" + + Arrays.toString(onBuild) + '\'' + '}'; } - - - @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/github/dockerjava/client/model/ContainerInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java index 16ce36cb..2469f0d8 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java @@ -16,35 +16,56 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class ContainerInspectResponse { - @JsonProperty("Id") + @JsonProperty("Args") + private String[] args; + + @JsonProperty("Config") + private ContainerConfig config; + + @JsonProperty("Created") + private String created; + + @JsonProperty("Driver") + private String driver; + + @JsonProperty("ExecDriver") + private String execDriver; + + @JsonProperty("HostConfig") + private HostConfig hostConfig; + + @JsonProperty("HostnamePath") + private String hostnamePath; + + @JsonProperty("HostsPath") + private String hostsPath; + + @JsonProperty("Id") private String id; - @JsonProperty("Created") - private String created; + @JsonProperty("Image") + private String imageId; - @JsonProperty("Path") - private String path; - - @JsonProperty("Args") - private String[] args; - - @JsonProperty("Config") - private ContainerConfig config; - - @JsonProperty("State") - private ContainerState state; + @JsonProperty("MountLabel") + private String mountLabel; + + @JsonProperty("Name") + private String name; - @JsonProperty("Image") - private String imageId; + @JsonProperty("NetworkSettings") + private NetworkSettings networkSettings; - @JsonProperty("NetworkSettings") - private NetworkSettings networkSettings; + @JsonProperty("Path") + private String path; - @JsonProperty("SysInitPath") - private String sysInitPath; + @JsonProperty("ProcessLabel") + private String processLabel; + + @JsonProperty("ResolvConfPath") + private String resolvConfPath; - @JsonProperty("ResolvConfPath") - private String resolvConfPath; + @JsonProperty("State") + private ContainerState state; @JsonProperty("Volumes") private Volumes volumes; @@ -52,27 +73,6 @@ public class ContainerInspectResponse { @JsonProperty("VolumesRW") private Volumes 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; } @@ -84,6 +84,10 @@ public String getCreated() { public String getPath() { return path; } + + public String getProcessLabel() { + return processLabel; + } public String[] getArgs() { return args; @@ -105,10 +109,6 @@ public NetworkSettings getNetworkSettings() { return networkSettings; } - public String getSysInitPath() { - return sysInitPath; - } - public String getResolvConfPath() { return resolvConfPath; } diff --git a/src/main/java/com/github/dockerjava/client/model/Image.java b/src/main/java/com/github/dockerjava/client/model/Image.java index 33d81a21..2d6471eb 100644 --- a/src/main/java/com/github/dockerjava/client/model/Image.java +++ b/src/main/java/com/github/dockerjava/client/model/Image.java @@ -13,24 +13,17 @@ @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("Created") + private long created; + @JsonProperty("Id") + private String id; - @JsonProperty("ParentId") - private String parentId; + @JsonProperty("ParentId") + private String parentId; - @JsonProperty("Created") - private long created; + @JsonProperty("RepoTags") + private String[] repoTags; @JsonProperty("Size") private long size; @@ -42,74 +35,32 @@ 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/github/dockerjava/client/model/Info.java b/src/main/java/com/github/dockerjava/client/model/Info.java index 54185cbe..442631d3 100644 --- a/src/main/java/com/github/dockerjava/client/model/Info.java +++ b/src/main/java/com/github/dockerjava/client/model/Info.java @@ -74,10 +74,6 @@ public boolean isDebug() { return debug; } - public void setDebug(boolean debug) { - this.debug = debug; - } - public int getContainers() { return containers; } diff --git a/src/main/java/com/github/dockerjava/client/model/Version.java b/src/main/java/com/github/dockerjava/client/model/Version.java index ff6af729..a01d6c61 100644 --- a/src/main/java/com/github/dockerjava/client/model/Version.java +++ b/src/main/java/com/github/dockerjava/client/model/Version.java @@ -11,79 +11,51 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class Version { - @JsonProperty("Version") - private String version; + @JsonProperty("ApiVersion") + private String apiVersion; - @JsonProperty("GitCommit") - private String gitCommit; + @JsonProperty("Arch") + private String arch; - @JsonProperty("GoVersion") - private String goVersion; - - @JsonProperty("KernelVersion") - private String kernelVersion; + @JsonProperty("GitCommit") + private String gitCommit; - @JsonProperty("Arch") - private String arch; + @JsonProperty("GoVersion") + private String goVersion; + + @JsonProperty("KernelVersion") + private String kernelVersion; - @JsonProperty("Os") - private String operatingSystem; + @JsonProperty("Os") + private String operatingSystem; - @JsonProperty("ApiVersion") - private String apiVersion; + @JsonProperty("Version") + private String version; 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() { + 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; } diff --git a/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java b/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java index 68c8ed01..67e9a6a9 100644 --- a/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java @@ -1,12 +1,7 @@ package com.github.dockerjava.client.command; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isEmptyString; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.*; import java.lang.reflect.Method; import java.util.List; @@ -58,8 +53,7 @@ public void listImages() throws DockerException { 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())); + assertThat(img.getRepoTags(), not(emptyArray())); } From cb9b3f2eb4f2e2342443627321112c729485d34e Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 15 Jul 2014 20:50:48 +0200 Subject: [PATCH 042/452] Moved readTimeout and enableLoggingFilter to config object --- .../github/dockerjava/client/DockerClient.java | 18 ++++++------------ src/main/resources/docker.io.properties | 4 +++- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index deb6ebed..939b7a7c 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -66,19 +66,13 @@ public class DockerClient { private WebResource baseResource; private AuthConfig authConfig; + public DockerClient() throws DockerException { - this(10000, true); - } - public DockerClient(Integer readTimeout, boolean enableLoggingFilter) throws DockerException { - this(Config.createConfig(), readTimeout, enableLoggingFilter); + this(Config.createConfig()); } public DockerClient(String serverUrl) throws DockerException { - this(serverUrl, 10000, true); - } - - public DockerClient(String serverUrl, Integer readTimeout, boolean enableLoggingFilter) throws DockerException { - this(configWithServerUrl(serverUrl), readTimeout, enableLoggingFilter); + this(configWithServerUrl(serverUrl)); } private static Config configWithServerUrl(String serverUrl) @@ -88,7 +82,7 @@ private static Config configWithServerUrl(String serverUrl) return c; } - public DockerClient(Config config, Integer readTimeout, boolean enableLoggingFilter) { + public DockerClient(Config config) { ClientConfig clientConfig = new DefaultClientConfig(); SchemeRegistry schemeRegistry = new SchemeRegistry(); @@ -109,11 +103,11 @@ public DockerClient(Config config, Integer readTimeout, boolean enableLoggingFil null, false), clientConfig); // 1 hour - client.setReadTimeout(readTimeout); + client.setReadTimeout(config.readTimeout); client.addFilter(new JsonClientFilter()); - if (enableLoggingFilter) + if (config.enableLoggingFilter) client.addFilter(new SelectiveLoggingFilter()); baseResource = client.resource(config.url + "/v" + config.version); diff --git a/src/main/resources/docker.io.properties b/src/main/resources/docker.io.properties index 6251c969..c62ca27a 100644 --- a/src/main/resources/docker.io.properties +++ b/src/main/resources/docker.io.properties @@ -1,2 +1,4 @@ docker.io.url=http://localhost:2375 -docker.io.version=1.13 \ No newline at end of file +docker.io.version=1.13 +docker.io.readTimeout=1000 +docker.io.enableLoggingFilter=true \ No newline at end of file From f2191dda51f00eb466e7e71b3d4ce7ba0edab304 Mon Sep 17 00:00:00 2001 From: "Kim A. Betti" Date: Fri, 18 Jul 2014 00:05:14 +0200 Subject: [PATCH 043/452] Added a close method to DockerClient Give programs using DockerClient an opportunity to release resources claimed by the http client created inside DockerClient. --- .../com/github/dockerjava/client/DockerClient.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index 939b7a7c..a2a34c7b 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -2,10 +2,7 @@ import static org.apache.commons.io.IOUtils.closeQuietly; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; +import java.io.*; import java.net.URI; import org.apache.commons.io.IOUtils; @@ -60,7 +57,7 @@ /** * @author Konstantin Pelykh (kpelykh@gmail.com) */ -public class DockerClient { +public class DockerClient implements Closeable { private Client client; private WebResource baseResource; @@ -321,4 +318,10 @@ public static String asString(ClientResponse response) throws IOException { } return out.toString(); } + + @Override + public void close() throws IOException { + client.destroy(); + } + } From dd0105f22db6efb3208feda3bf82b3b9bc7eedaf Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Mon, 14 Jul 2014 20:58:30 -0400 Subject: [PATCH 044/452] Removes username from tests when unused The field is never used in these tests. It should make it easier to separate tests that require a docker.io account from those that do not. --- .../client/command/KillContainerCmdTest.java | 3 --- .../client/command/RemoveContainerCmdTest.java | 7 ++----- .../dockerjava/client/command/RemoveImageCmdTest.java | 7 ++----- .../client/command/StopContainerCmdTest.java | 3 --- .../dockerjava/client/command/TagImageCmdTest.java | 11 ++++------- 5 files changed, 8 insertions(+), 23 deletions(-) diff --git a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java index 95f246c3..35c4ded0 100644 --- a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java @@ -27,12 +27,9 @@ public class KillContainerCmdTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory .getLogger(KillContainerCmdTest.class); - String username; - @BeforeTest public void beforeTest() throws DockerException { super.beforeTest(); - username = dockerClient.authConfig().getUsername(); } @AfterTest diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java index 96ef538d..3e2bf403 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java @@ -24,16 +24,13 @@ import com.github.dockerjava.client.model.ContainerCreateResponse; public class RemoveContainerCmdTest extends AbstractDockerClientTest { - + public static final Logger LOG = LoggerFactory .getLogger(RemoveContainerCmdTest.class); - String username; - @BeforeTest public void beforeTest() throws DockerException { super.beforeTest(); - username = dockerClient.authConfig().getUsername(); } @AfterTest public void afterTest() { @@ -70,6 +67,6 @@ public void removeContainer() throws DockerException { } - + } diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java index 4f640302..81c5dcf5 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java @@ -25,16 +25,13 @@ import com.github.dockerjava.client.model.ContainerCreateResponse; public class RemoveImageCmdTest extends AbstractDockerClientTest { - + public static final Logger LOG = LoggerFactory .getLogger(RemoveImageCmdTest.class); - String username; - @BeforeTest public void beforeTest() throws DockerException { super.beforeTest(); - username = dockerClient.authConfig().getUsername(); } @AfterTest public void afterTest() { @@ -79,6 +76,6 @@ public void testRemoveImage() throws DockerException, InterruptedException { assertThat(containers, matcher); } - + } diff --git a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java index 96059a85..d9151088 100644 --- a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java @@ -27,12 +27,9 @@ public class StopContainerCmdTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory .getLogger(StopContainerCmdTest.class); - String username; - @BeforeTest public void beforeTest() throws DockerException { super.beforeTest(); - username = dockerClient.authConfig().getUsername(); } @AfterTest diff --git a/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java index a756b49f..62fd1d09 100644 --- a/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java @@ -20,16 +20,13 @@ import com.github.dockerjava.client.DockerException; public class TagImageCmdTest extends AbstractDockerClientTest { - + public static final Logger LOG = LoggerFactory .getLogger(TagImageCmdTest.class); - String username; - @BeforeTest public void beforeTest() throws DockerException { super.beforeTest(); - username = dockerClient.authConfig().getUsername(); } @AfterTest public void afterTest() { @@ -49,12 +46,12 @@ public void afterMethod(ITestResult result) { @Test public void testTagImage() throws DockerException, InterruptedException { String tag = String.valueOf(RandomUtils.nextInt(Integer.MAX_VALUE)); - + Integer result = dockerClient.tagImageCmd("busybox:latest", "docker-java/busybox", tag).exec(); assertThat(result, equalTo(Integer.valueOf(201))); - + dockerClient.removeImageCmd("docker-java/busybox:" + tag).exec(); } - + } From 39201090e3453d83a49ef5161d2b6ac424ad791e Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Wed, 16 Jul 2014 16:25:37 -0400 Subject: [PATCH 045/452] Cleans up DockerClient constructor Just doing a little refactoring of the constructor to make it easier to read. --- .../dockerjava/client/DockerClient.java | 89 +++++++------------ 1 file changed, 31 insertions(+), 58 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index 939b7a7c..c17c200d 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -8,6 +8,7 @@ import java.io.StringWriter; import java.net.URI; +import com.github.dockerjava.client.command.*; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.http.client.HttpClient; @@ -18,34 +19,6 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; -import com.github.dockerjava.client.command.AbstrDockerCmd; -import com.github.dockerjava.client.command.AttachContainerCmd; -import com.github.dockerjava.client.command.AuthCmd; -import com.github.dockerjava.client.command.BuildImgCmd; -import com.github.dockerjava.client.command.CommitCmd; -import com.github.dockerjava.client.command.ContainerDiffCmd; -import com.github.dockerjava.client.command.CopyFileFromContainerCmd; -import com.github.dockerjava.client.command.CreateContainerCmd; -import com.github.dockerjava.client.command.ImportImageCmd; -import com.github.dockerjava.client.command.InfoCmd; -import com.github.dockerjava.client.command.InspectContainerCmd; -import com.github.dockerjava.client.command.InspectImageCmd; -import com.github.dockerjava.client.command.KillContainerCmd; -import com.github.dockerjava.client.command.ListContainersCmd; -import com.github.dockerjava.client.command.ListImagesCmd; -import com.github.dockerjava.client.command.LogContainerCmd; -import com.github.dockerjava.client.command.PullImageCmd; -import com.github.dockerjava.client.command.PushImageCmd; -import com.github.dockerjava.client.command.RemoveContainerCmd; -import com.github.dockerjava.client.command.RemoveImageCmd; -import com.github.dockerjava.client.command.RestartContainerCmd; -import com.github.dockerjava.client.command.SearchImagesCmd; -import com.github.dockerjava.client.command.StartContainerCmd; -import com.github.dockerjava.client.command.StopContainerCmd; -import com.github.dockerjava.client.command.TagImageCmd; -import com.github.dockerjava.client.command.TopContainerCmd; -import com.github.dockerjava.client.command.VersionCmd; -import com.github.dockerjava.client.command.WaitContainerCmd; import com.github.dockerjava.client.model.AuthConfig; import com.github.dockerjava.client.model.CreateContainerConfig; import com.github.dockerjava.client.utils.JsonClientFilter; @@ -62,11 +35,10 @@ */ public class DockerClient { - private Client client; - private WebResource baseResource; + private final WebResource baseResource; private AuthConfig authConfig; - + public DockerClient() throws DockerException { this(Config.createConfig()); } @@ -74,7 +46,7 @@ public DockerClient() throws DockerException { public DockerClient(String serverUrl) throws DockerException { this(configWithServerUrl(serverUrl)); } - + private static Config configWithServerUrl(String serverUrl) throws DockerException { final Config c = Config.createConfig(); @@ -82,40 +54,41 @@ private static Config configWithServerUrl(String serverUrl) return c; } - public DockerClient(Config config) { - ClientConfig clientConfig = new DefaultClientConfig(); - - 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, + public DockerClient(Config config) { + HttpClient httpClient = getPoolingHttpClient(config); + ClientConfig clientConfig = new DefaultClientConfig(); + Client client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, null, false), clientConfig); // 1 hour client.setReadTimeout(config.readTimeout); - + client.addFilter(new JsonClientFilter()); - + if (config.enableLoggingFilter) client.addFilter(new SelectiveLoggingFilter()); baseResource = client.resource(config.url + "/v" + config.version); } - + private HttpClient getPoolingHttpClient(Config config) { + 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); + + return new DefaultHttpClient(cm); + } - public void setCredentials(String username, String password, String email) { + + public void setCredentials(String username, String password, String email) { if (username == null) { throw new IllegalArgumentException("username is null"); } @@ -253,8 +226,8 @@ public WaitContainerCmd waitContainerCmd(String containerId) { public AttachContainerCmd attachContainerCmd(String containerId) { return new AttachContainerCmd(containerId).withBaseResource(baseResource); } - - + + public LogContainerCmd logContainerCmd(String containerId) { return new LogContainerCmd(containerId).withBaseResource(baseResource); } @@ -297,11 +270,11 @@ public BuildImgCmd buildImageCmd(InputStream tarInputStream) { public TopContainerCmd topContainerCmd(String containerId) { return new TopContainerCmd(containerId).withBaseResource(baseResource); } - + public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { return new TagImageCmd(imageId, repository, tag).withBaseResource(baseResource); } - + /** * @return The output slurped into a string. From f184f5590141709212a4f56273ca89ef5661d00b Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Wed, 16 Jul 2014 18:51:54 -0400 Subject: [PATCH 046/452] Creates an injectable CommandFactory for DockerClient In order to improve the usability of DockerClient in tests, this introduces a CommandFactory interface (and default implementation). The interface can be injected into the DockerClient at construction, allowing the use of a CommandFactory that returns mock or stub commands for later test assertions. I envision that the methods that create the commands from the DockerClient itself could be deprecated: users of the library could create the commands from the CommandFactory directly and simply pass them into the DockerClient#execute method where teh baseResource and (if appropriate) authConfig would be set on the command before it's executed. Issue #25 --- .../dockerjava/client/DockerClient.java | 64 +++---- .../client/command/CommandFactory.java | 39 +++++ .../client/command/DefaultCommandFactory.java | 158 ++++++++++++++++++ 3 files changed, 232 insertions(+), 29 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/client/command/CommandFactory.java create mode 100644 src/main/java/com/github/dockerjava/client/command/DefaultCommandFactory.java diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index c17c200d..7302dabc 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -35,6 +35,7 @@ */ public class DockerClient { + private final CommandFactory cmdFactory; private final WebResource baseResource; private AuthConfig authConfig; @@ -55,6 +56,12 @@ private static Config configWithServerUrl(String serverUrl) } public DockerClient(Config config) { + this(config, null); + } + + public DockerClient(Config config, CommandFactory cmdFactory) { + this.cmdFactory = cmdFactory; + HttpClient httpClient = getPoolingHttpClient(config); ClientConfig clientConfig = new DefaultClientConfig(); Client client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, @@ -141,15 +148,15 @@ private static AuthConfig authConfigFromProperties() throws DockerException { * Authenticate with the server, useful for checking authentication. */ public AuthCmd authCmd() { - return new AuthCmd(authConfig()).withBaseResource(baseResource); + return cmdFactory.authCmd(authConfig()).withBaseResource(baseResource); } public InfoCmd infoCmd() throws DockerException { - return new InfoCmd().withBaseResource(baseResource); + return cmdFactory.infoCmd().withBaseResource(baseResource); } public VersionCmd versionCmd() throws DockerException { - return new VersionCmd().withBaseResource(baseResource); + return cmdFactory.versionCmd().withBaseResource(baseResource); } /** @@ -157,11 +164,11 @@ public VersionCmd versionCmd() throws DockerException { */ public PullImageCmd pullImageCmd(String repository) { - return new PullImageCmd(repository).withBaseResource(baseResource); + return cmdFactory.pullImageCmd(repository).withBaseResource(baseResource); } public PushImageCmd pushImageCmd(String name) { - return new PushImageCmd(name).withAuthConfig(authConfig()) + return cmdFactory.pushImageCmd(name).withAuthConfig(authConfig()) .withBaseResource(baseResource); } @@ -171,24 +178,24 @@ public PushImageCmd pushImageCmd(String name) { public ImportImageCmd importImageCmd(String repository, InputStream imageStream) { - return new ImportImageCmd(repository, imageStream) + return cmdFactory.importImageCmd(repository, imageStream) .withBaseResource(baseResource); } public SearchImagesCmd searchImagesCmd(String term) { - return new SearchImagesCmd(term).withBaseResource(baseResource); + return cmdFactory.searchImagesCmd(term).withBaseResource(baseResource); } public RemoveImageCmd removeImageCmd(String imageId) { - return new RemoveImageCmd(imageId).withBaseResource(baseResource); + return cmdFactory.removeImageCmd(imageId).withBaseResource(baseResource); } public ListImagesCmd listImagesCmd() { - return new ListImagesCmd().withBaseResource(baseResource); + return cmdFactory.listImagesCmd().withBaseResource(baseResource); } public InspectImageCmd inspectImageCmd(String imageId) { - return new InspectImageCmd(imageId).withBaseResource(baseResource); + return cmdFactory.inspectImageCmd(imageId).withBaseResource(baseResource); } /** @@ -196,83 +203,82 @@ public InspectImageCmd inspectImageCmd(String imageId) { */ public ListContainersCmd listContainersCmd() { - return new ListContainersCmd().withBaseResource(baseResource); + return cmdFactory.listContainersCmd().withBaseResource(baseResource); } public CreateContainerCmd createContainerCmd(String image) { - return new CreateContainerCmd(new CreateContainerConfig()).withImage( - image).withBaseResource(baseResource); + return cmdFactory.createContainerCmd(image).withBaseResource(baseResource); } public StartContainerCmd startContainerCmd(String containerId) { - return new StartContainerCmd(containerId) + return cmdFactory.startContainerCmd(containerId) .withBaseResource(baseResource); } public InspectContainerCmd inspectContainerCmd(String containerId) { - return new InspectContainerCmd(containerId) + return cmdFactory.inspectContainerCmd(containerId) .withBaseResource(baseResource); } public RemoveContainerCmd removeContainerCmd(String containerId) { - return new RemoveContainerCmd(containerId) + return cmdFactory.removeContainerCmd(containerId) .withBaseResource(baseResource); } public WaitContainerCmd waitContainerCmd(String containerId) { - return new WaitContainerCmd(containerId).withBaseResource(baseResource); + return cmdFactory.waitContainerCmd(containerId).withBaseResource(baseResource); } public AttachContainerCmd attachContainerCmd(String containerId) { - return new AttachContainerCmd(containerId).withBaseResource(baseResource); + return cmdFactory.attachContainerCmd(containerId).withBaseResource(baseResource); } public LogContainerCmd logContainerCmd(String containerId) { - return new LogContainerCmd(containerId).withBaseResource(baseResource); + return cmdFactory.logContainerCmd(containerId).withBaseResource(baseResource); } public CopyFileFromContainerCmd copyFileFromContainerCmd( String containerId, String resource) { - return new CopyFileFromContainerCmd(containerId, resource) + return cmdFactory.copyFileFromContainerCmd(containerId, resource) .withBaseResource(baseResource); } public ContainerDiffCmd containerDiffCmd(String containerId) { - return new ContainerDiffCmd(containerId).withBaseResource(baseResource); + return cmdFactory.containerDiffCmd(containerId).withBaseResource(baseResource); } public StopContainerCmd stopContainerCmd(String containerId) { - return new StopContainerCmd(containerId).withBaseResource(baseResource); + return cmdFactory.stopContainerCmd(containerId).withBaseResource(baseResource); } public KillContainerCmd killContainerCmd(String containerId) { - return new KillContainerCmd(containerId).withBaseResource(baseResource); + return cmdFactory.killContainerCmd(containerId).withBaseResource(baseResource); } public RestartContainerCmd restartContainerCmd(String containerId) { - return new RestartContainerCmd(containerId) + return cmdFactory.restartContainerCmd(containerId) .withBaseResource(baseResource); } public CommitCmd commitCmd(String containerId) { - return new CommitCmd(containerId).withBaseResource(baseResource); + return cmdFactory.commitCmd(containerId).withBaseResource(baseResource); } public BuildImgCmd buildImageCmd(File dockerFolder) { - return new BuildImgCmd(dockerFolder).withBaseResource(baseResource); + return cmdFactory.buildImgCmd(dockerFolder).withBaseResource(baseResource); } public BuildImgCmd buildImageCmd(InputStream tarInputStream) { - return new BuildImgCmd(tarInputStream).withBaseResource(baseResource); + return cmdFactory.buildImgCmd(tarInputStream).withBaseResource(baseResource); } public TopContainerCmd topContainerCmd(String containerId) { - return new TopContainerCmd(containerId).withBaseResource(baseResource); + return cmdFactory.topContainerCmd(containerId).withBaseResource(baseResource); } public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { - return new TagImageCmd(imageId, repository, tag).withBaseResource(baseResource); + return cmdFactory.tagImageCmd(imageId, repository, tag).withBaseResource(baseResource); } diff --git a/src/main/java/com/github/dockerjava/client/command/CommandFactory.java b/src/main/java/com/github/dockerjava/client/command/CommandFactory.java new file mode 100644 index 00000000..74585a39 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/CommandFactory.java @@ -0,0 +1,39 @@ +package com.github.dockerjava.client.command; + +import com.github.dockerjava.client.model.AuthConfig; + +import java.io.File; +import java.io.InputStream; + +public interface CommandFactory { + public AttachContainerCmd attachContainerCmd(String containerId); + public AuthCmd authCmd(AuthConfig authConfig); + public BuildImgCmd buildImgCmd(File dockerFolder); + public BuildImgCmd buildImgCmd(InputStream tarInputStream); + public CommitCmd commitCmd(String containerId); + public ContainerDiffCmd containerDiffCmd(String containerId); + public CopyFileFromContainerCmd copyFileFromContainerCmd(String containerId, String resource); + public CreateContainerCmd createContainerCmd(String image); + public ImportImageCmd importImageCmd(String repository, InputStream imageStream); + public InfoCmd infoCmd(); + public InspectContainerCmd inspectContainerCmd(String containerId); + public InspectImageCmd inspectImageCmd(String imageId); + public KillContainerCmd killContainerCmd(String containerId); + public ListContainersCmd listContainersCmd(); + public ListImagesCmd listImagesCmd(); + public LogContainerCmd logContainerCmd(String containerId); + public PauseContainerCmd pauseContainerCmd(String containerId); + public PullImageCmd pullImageCmd(String repository); + public PushImageCmd pushImageCmd(String imageName); + public RemoveContainerCmd removeContainerCmd(String containerId); + public RemoveImageCmd removeImageCmd(String imageId); + public RestartContainerCmd restartContainerCmd(String containerId); + public SearchImagesCmd searchImagesCmd(String searchTerm); + public StartContainerCmd startContainerCmd(String containerId); + public StopContainerCmd stopContainerCmd(String containerId); + public TagImageCmd tagImageCmd(String imageId, String repository, String tag); + public TopContainerCmd topContainerCmd(String containerId); + public UnpauseContainerCmd unpauseContainerCmd(String containerId); + public VersionCmd versionCmd(); + public WaitContainerCmd waitContainerCmd(String containerId); +} diff --git a/src/main/java/com/github/dockerjava/client/command/DefaultCommandFactory.java b/src/main/java/com/github/dockerjava/client/command/DefaultCommandFactory.java new file mode 100644 index 00000000..29f99485 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/DefaultCommandFactory.java @@ -0,0 +1,158 @@ +package com.github.dockerjava.client.command; + +import com.github.dockerjava.client.model.AuthConfig; + +import java.io.File; +import java.io.InputStream; + +public class DefaultCommandFactory implements CommandFactory { + @Override + public AttachContainerCmd attachContainerCmd(String containerId) { + return new AttachContainerCmd(containerId); + } + + @Override + public AuthCmd authCmd(AuthConfig authConfig) { + return new AuthCmd(authConfig); + } + + @Override + public BuildImgCmd buildImgCmd(File dockerFolder) { + return new BuildImgCmd(dockerFolder); + } + + @Override + public BuildImgCmd buildImgCmd(InputStream tarInputStream) { + return new BuildImgCmd(tarInputStream); + } + + @Override + public CommitCmd commitCmd(String containerId) { + return new CommitCmd(containerId); + } + + @Override + public ContainerDiffCmd containerDiffCmd(String containerId) { + return new ContainerDiffCmd(containerId); + } + + @Override + public CopyFileFromContainerCmd copyFileFromContainerCmd(String containerId, String resource) { + return new CopyFileFromContainerCmd(containerId, resource); + } + + @Override + public CreateContainerCmd createContainerCmd(String image) { + return new CreateContainerCmd(image); + } + + @Override + public ImportImageCmd importImageCmd(String repository, InputStream imageStream) { + return new ImportImageCmd(repository, imageStream); + } + + @Override + public InfoCmd infoCmd() { + return new InfoCmd(); + } + + @Override + public InspectContainerCmd inspectContainerCmd(String containerId) { + return new InspectContainerCmd(containerId); + } + + @Override + public InspectImageCmd inspectImageCmd(String imageId) { + return new InspectImageCmd(imageId); + } + + @Override + public KillContainerCmd killContainerCmd(String containerId) { + return new KillContainerCmd(containerId); + } + + @Override + public ListContainersCmd listContainersCmd() { + return new ListContainersCmd(); + } + + @Override + public ListImagesCmd listImagesCmd() { + return new ListImagesCmd(); + } + + @Override + public LogContainerCmd logContainerCmd(String containerId) { + return new LogContainerCmd(containerId); + } + + @Override + public PauseContainerCmd pauseContainerCmd(String containerId) { + return new PauseContainerCmd(containerId); + } + + @Override + public PullImageCmd pullImageCmd(String repository) { + return new PullImageCmd(repository); + } + + @Override + public PushImageCmd pushImageCmd(String imageName) { + return new PushImageCmd(imageName); + } + + @Override + public RemoveContainerCmd removeContainerCmd(String containerId) { + return new RemoveContainerCmd(containerId); + } + + @Override + public RemoveImageCmd removeImageCmd(String imageId) { + return new RemoveImageCmd(imageId); + } + + @Override + public RestartContainerCmd restartContainerCmd(String containerId) { + return new RestartContainerCmd(containerId); + } + + @Override + public SearchImagesCmd searchImagesCmd(String searchTerm) { + return new SearchImagesCmd(searchTerm); + } + + @Override + public StartContainerCmd startContainerCmd(String containerId) { + return new StartContainerCmd(containerId); + } + + @Override + public StopContainerCmd stopContainerCmd(String containerId) { + return new StopContainerCmd(containerId); + } + + @Override + public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { + return new TagImageCmd(imageId, repository, tag); + } + + @Override + public TopContainerCmd topContainerCmd(String containerId) { + return new TopContainerCmd(containerId); + } + + @Override + public UnpauseContainerCmd unpauseContainerCmd(String containerId) { + return new UnpauseContainerCmd(containerId); + } + + @Override + public VersionCmd versionCmd() { + return new VersionCmd(); + } + + @Override + public WaitContainerCmd waitContainerCmd(String containerId) { + return new WaitContainerCmd(containerId); + } +} From 1459ffb0441f049d6d0c674bfe1c12c835fdd7fb Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Fri, 18 Jul 2014 16:09:12 -0400 Subject: [PATCH 047/452] Adds some getters to command objects This only adds getters for fields that are of immutable types (Strings, booleans, ints). For objects that take in Config objects, I'll look at adding getters in a future commit. Ideally all of these things would be immutable. Issue #25 --- .../client/command/AttachContainerCmd.java | 32 ++++- .../client/command/BuildImgCmd.java | 110 +++++++++++------- .../dockerjava/client/command/CommitCmd.java | 70 +++++++---- .../client/command/ContainerDiffCmd.java | 16 ++- .../command/CopyFileFromContainerCmd.java | 22 ++-- .../client/command/CreateContainerCmd.java | 32 ++--- .../client/command/ImportImageCmd.java | 10 +- .../client/command/InspectContainerCmd.java | 12 +- .../client/command/InspectImageCmd.java | 14 ++- .../client/command/KillContainerCmd.java | 22 ++-- .../client/command/ListContainersCmd.java | 40 +++++-- .../client/command/ListImagesCmd.java | 20 +++- .../client/command/LogContainerCmd.java | 42 +++++-- .../client/command/PauseContainerCmd.java | 22 ++-- .../client/command/PullImageCmd.java | 30 +++-- .../client/command/PushImageCmd.java | 18 +-- .../client/command/RemoveContainerCmd.java | 34 ++++-- .../client/command/RemoveImageCmd.java | 42 ++++--- .../client/command/RestartContainerCmd.java | 28 +++-- .../client/command/SearchImagesCmd.java | 20 ++-- .../client/command/StartContainerCmd.java | 24 ++-- .../client/command/StopContainerCmd.java | 28 +++-- .../client/command/TagImageCmd.java | 40 +++++-- .../client/command/TopContainerCmd.java | 32 +++-- .../client/command/UnpauseContainerCmd.java | 22 ++-- .../client/command/WaitContainerCmd.java | 14 ++- 26 files changed, 528 insertions(+), 268 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java index 63dca1ed..1b3acb97 100644 --- a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java @@ -16,9 +16,9 @@ /** * Attach to container - * + * * @param logs - true or false, includes logs. Defaults to false. - * + * * @param followStream * - true or false, return stream. Defaults to false. * @param stdout @@ -42,7 +42,31 @@ public AttachContainerCmd(String containerId) { withContainerId(containerId); } - public AttachContainerCmd withContainerId(String containerId) { + public String getContainerId() { + return containerId; + } + + public boolean hasLogsEnabled() { + return logs; + } + + public boolean hasFollowStreamEnabled() { + return followStream; + } + + public boolean hasTimestampsEnabled() { + return timestamps; + } + + public boolean hasStdoutEnabled() { + return stdout; + } + + public boolean hasStderrEnabled() { + return stderr; + } + + public AttachContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; @@ -91,7 +115,7 @@ protected ClientResponse impl() throws DockerException { params.add("timestamps", timestamps ? "1" : "0"); params.add("stdout", stdout ? "1" : "0"); params.add("stderr", stderr ? "1" : "0"); - params.add("follow", followStream ? "1" : "0"); + params.add("follow", followStream ? "1" : "0"); WebResource webResource = baseResource.path( String.format("/containers/%s/attach", containerId)) diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java index 1aadd7db..34de8a8b 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -29,63 +29,83 @@ import com.sun.jersey.core.util.MultivaluedMapImpl; /** - * + * * Build an image from Dockerfile. - * + * * TODO: http://docs.docker.com/reference/builder/#dockerignore * */ public class BuildImgCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(BuildImgCmd.class); - + private static final Pattern ADD_OR_COPY_PATTERN = Pattern.compile("^(ADD|COPY)\\s+(.*)\\s+(.*)$"); - + private static final Pattern ENV_PATTERN = Pattern.compile("^ENV\\s+(.*)\\s+(.*)$"); - + private File dockerFolder = null; private InputStream tarInputStream = null; private String tag; private boolean noCache; private boolean remove = true; private boolean quiet; - - + + public BuildImgCmd(File dockerFolder) { Preconditions.checkNotNull(dockerFolder, "dockerFolder is null"); this.dockerFolder = dockerFolder; } - + public BuildImgCmd(InputStream tarInputStream) { Preconditions.checkNotNull(tarInputStream, "tarInputStream is null"); this.tarInputStream = tarInputStream; } - + public BuildImgCmd withTag(String tag) { Preconditions.checkNotNull(tag, "Tag is null"); this.tag = tag; return this; } - - public BuildImgCmd withNoCache() { + + public File getDockerFolder() { + return dockerFolder; + } + + public String getTag() { + return tag; + } + + public boolean hasNoCacheEnabled() { + return noCache; + } + + public boolean hasRemoveEnabled() { + return remove; + } + + public boolean isQuiet() { + return quiet; + } + + public BuildImgCmd withNoCache() { return withNoCache(true); } - + public BuildImgCmd withNoCache(boolean noCache) { this.noCache = noCache; return this; } - + public BuildImgCmd withRemove(boolean rm) { this.remove = rm; return this; } - + public BuildImgCmd withQuiet(boolean quiet) { this.quiet = quiet; return this; } - + @Override public String toString() { return new StringBuilder("build ") @@ -96,7 +116,7 @@ public String toString() { .append(dockerFolder != null ? dockerFolder.getPath() : "-") .toString(); } - + protected ClientResponse impl() { if (tarInputStream == null) { File dockerFolderTar = buildDockerFolderTar(); @@ -119,10 +139,10 @@ protected ClientResponse callDocker(final InputStream dockerFolderTarInputStream params.add("nocache", "true"); } if (remove) { - params.add("rm", "true"); + params.add("rm", "true"); } if (quiet) { - params.add("q", "true"); + params.add("q", "true"); } WebResource webResource = baseResource.path("/build").queryParams(params); @@ -141,12 +161,12 @@ protected ClientResponse callDocker(final InputStream dockerFolderTarInputStream } } } - + protected File buildDockerFolderTar() { Preconditions.checkArgument(dockerFolder.exists(), "Path %s doesn't exist", dockerFolder); Preconditions.checkArgument(dockerFolder.isDirectory(), "Folder %s doesn't exist", dockerFolder); Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(), "Dockerfile doesn't exist in " + dockerFolder); - + // ARCHIVE TAR String archiveNameWithOutExtension = UUID.randomUUID().toString(); @@ -164,30 +184,30 @@ protected File buildDockerFolderTar() { filesToAdd.add(dockerFile); MapenvironmentMap = new HashMap(); - + int lineNumber = 0; - + for (String cmd : dockerFileContent) { - + lineNumber++; - + if (cmd.trim().isEmpty() || cmd.startsWith("#")) continue; // skip emtpy and commend lines - + final Matcher envMatcher = ENV_PATTERN.matcher(cmd.trim()); - + if (envMatcher.find()) { if (envMatcher.groupCount() != 2) throw new DockerException(String.format("Wrong ENV format on line [%d]", lineNumber)); - + String variable = envMatcher.group(1).trim(); - + String value = envMatcher.group(2).trim(); - + environmentMap.put(variable, value); } - - + + final Matcher matcher = ADD_OR_COPY_PATTERN.matcher(cmd.trim()); if (matcher.find()) { if (matcher.groupCount() != 3) { @@ -195,9 +215,9 @@ protected File buildDockerFolderTar() { } String extractedResource = matcher.group(2); - + String resource = filterForEnvironmentVars(extractedResource, environmentMap).trim(); - + if(isFileResource(resource)) { File src = new File(resource); if (!src.isAbsolute()) { @@ -214,7 +234,7 @@ protected File buildDockerFolderTar() { } else { filesToAdd.add(src); } - } + } } } @@ -225,31 +245,31 @@ protected File buildDockerFolderTar() { throw new DockerException("Error occurred while preparing Docker context folder.", ex); } } - + private String filterForEnvironmentVars(String extractedResource, Map environmentMap) { - + if (environmentMap.size() > 0) { - + String currentResourceContent = extractedResource; - + for (Map.Entry entry : environmentMap.entrySet()) { - + String variable = entry.getKey(); - + String replacementValue = entry.getValue(); - + // handle: $VARIABLE case currentResourceContent = currentResourceContent.replaceAll("\\$" + variable, replacementValue); - + // handle ${VARIABLE} case currentResourceContent = currentResourceContent.replaceAll("\\$\\{" + variable + "\\}", replacementValue); - + } - + return currentResourceContent; } - else + else return extractedResource; } diff --git a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java index a6f72014..df1a450a 100644 --- a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java @@ -16,45 +16,69 @@ /** - * + * * Create a new image from a container's changes. Returns the new image ID. * */ public class CommitCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(CommitCmd.class); - + private String containerId, repository, tag, message, author; - + private boolean pause = true; - + private CommitConfig commitConfig = new CommitConfig(); - + public CommitCmd(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; } - - public CommitCmd withCommitConfig(CommitConfig commitConfig) { + + public String getContainerId() { + return containerId; + } + + public String getRepository() { + return repository; + } + + public String getTag() { + return tag; + } + + public String getMessage() { + return message; + } + + public String getAuthor() { + return author; + } + + public boolean hasPauseEnabled() { + return pause; + } + + public CommitCmd withCommitConfig(CommitConfig commitConfig) { checkCommitConfig(commitConfig); this.commitConfig = commitConfig; return this; } - + public CommitCmd withAttachStderr(boolean attachStderr) { this.commitConfig.setAttachStderr(attachStderr); return this; } - + public CommitCmd withAttachStderr() { return withAttachStderr(true); } - + public CommitCmd withAttachStdin(boolean attachStdin) { this.commitConfig.setAttachStdin(attachStdin); return this; } - + public CommitCmd withAttachStdin() { return withAttachStdin(true); } @@ -63,51 +87,51 @@ public CommitCmd withAttachStdout(boolean attachStdout) { this.commitConfig.setAttachStdout(attachStdout); return this; } - + public CommitCmd withAttachStdout() { return withAttachStdout(true); } - + public CommitCmd withCmd(String... cmd) { Preconditions.checkNotNull(cmd, "cmd was not specified"); this.commitConfig.setCmd(cmd); return this; } - + public CommitCmd withDisableNetwork(boolean disableNetwork) { this.commitConfig.setDisableNetwork(disableNetwork); return this; } - + public CommitCmd withAuthor(String author) { Preconditions.checkNotNull(author, "author was not specified"); this.author = author; return this; } - + public CommitCmd withMessage(String message) { Preconditions.checkNotNull(message, "message was not specified"); this.message = message; return this; } - + public CommitCmd withTag(String tag) { Preconditions.checkNotNull(tag, "tag was not specified"); this.tag = tag; return this; } - + public CommitCmd withRepository(String repository) { Preconditions.checkNotNull(repository, "repository was not specified"); this.repository = repository; return this; } - + public CommitCmd withPause(boolean pause) { this.pause = pause; return this; } - + @Override public String toString() { return new StringBuilder("commit ") @@ -118,14 +142,14 @@ public String toString() { .append(tag != null ? tag : "") .toString(); } - + private void checkCommitConfig(CommitConfig commitConfig) { Preconditions.checkNotNull(commitConfig, "CommitConfig was not specified"); } - + protected String impl() throws DockerException { checkCommitConfig(commitConfig); - + MultivaluedMap params = new MultivaluedMapImpl(); params.add("container", containerId); params.add("repo", repository); diff --git a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java b/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java index ed684d04..8c16e600 100644 --- a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java @@ -17,26 +17,30 @@ /** * Inspect changes on a container's filesystem - * + * * @param containerId - Id of the container - * + * */ public class ContainerDiffCmd extends AbstrDockerCmd> { private static final Logger LOGGER = LoggerFactory.getLogger(ContainerDiffCmd.class); private String containerId; - + public ContainerDiffCmd(String containerId) { withContainerId(containerId); } - - public ContainerDiffCmd withContainerId(String containerId) { + + public String getContainerId() { + return containerId; + } + + public ContainerDiffCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - + @Override public String toString() { return new StringBuilder("diff ") diff --git a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java index 3e374aa5..dd974278 100644 --- a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java @@ -13,33 +13,41 @@ import com.sun.jersey.api.client.WebResource; /** - * + * * Copy files or folders from a container. - * + * */ public class CopyFileFromContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(CopyFileFromContainerCmd.class); private String containerId, resource; - + public CopyFileFromContainerCmd(String containerId, String resource) { withContainerId(containerId); withResource(resource); } - - public CopyFileFromContainerCmd withContainerId(String containerId) { + + public String getContainerId() { + return containerId; + } + + public String getResource() { + return resource; + } + + public CopyFileFromContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - + public CopyFileFromContainerCmd withResource(String resource) { Preconditions.checkNotNull(resource, "resource was not specified"); this.resource = resource; return this; } - + @Override public String toString() { return new StringBuilder("cp ") diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index 267bf52c..bf671172 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -19,46 +19,50 @@ /** - * + * * Creates a new container. * */ public class CreateContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(CreateContainerCmd.class); - + private CreateContainerConfig containerCreateConfig; private String name; - + public CreateContainerCmd(String image) { this(new CreateContainerConfig()); Preconditions.checkNotNull(image, "image was not specified"); this.containerCreateConfig.withImage(image); } - + public CreateContainerCmd(CreateContainerConfig config) { Preconditions.checkNotNull(config, "config was not specified"); this.containerCreateConfig = config; } - - public CreateContainerCmd withImage(String image) { + + public String getName() { + return name; + } + + public CreateContainerCmd withImage(String image) { Preconditions.checkNotNull(image, "image was not specified"); this.containerCreateConfig.withImage(image); return this; } - + public CreateContainerCmd withCmd(String... cmd) { Preconditions.checkNotNull(cmd, "cmd was not specified"); this.containerCreateConfig.withCmd(cmd); return this; } - + public CreateContainerCmd withVolumes(Volume... volumes) { Preconditions.checkNotNull(volumes, "volumes was not specified"); this.containerCreateConfig.withVolumes(volumes); return this; } - + public CreateContainerCmd withEnv(String... env) { Preconditions.checkNotNull(env, "env was not specified"); this.containerCreateConfig.withEnv(env); @@ -69,21 +73,21 @@ public CreateContainerCmd withHostName(String hostName) { Preconditions.checkNotNull(hostName, "hostName was not specified"); this.containerCreateConfig.withHostName(hostName); return this; - } - + } + public CreateContainerCmd withName(String name) { Preconditions.checkNotNull(name, "name was not specified"); this.name = name; return this; } - + public CreateContainerCmd withExposedPorts(ExposedPort... exposedPorts) { Preconditions.checkNotNull(exposedPorts, "exposedPorts was not specified"); - + this.containerCreateConfig.withExposedPorts(exposedPorts); return this; } - + @Override public String toString() { return new StringBuilder("create container ") diff --git a/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java b/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java index 020d5e75..9d02d592 100644 --- a/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java @@ -34,7 +34,15 @@ public ImportImageCmd(String repository, InputStream imageStream) { withImageStream(imageStream); } - /** + public String getRepository() { + return repository; + } + + public String getTag() { + return tag; + } + + /** * @param repository the repository to import to */ public ImportImageCmd withRepository(String repository) { diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java index ff031537..a5e40dfe 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java @@ -20,17 +20,21 @@ public class InspectContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(InspectImageCmd.class); - + private String imageId; - + public InspectImageCmd(String imageId) { withImageId(imageId); } - - public InspectImageCmd withImageId(String imageId) { + + public String getImageId() { + return imageId; + } + + public InspectImageCmd withImageId(String imageId) { Preconditions.checkNotNull(imageId, "imageId was not specified"); this.imageId = imageId; return this; } - + @Override public String toString() { return "inspect " + imageId; diff --git a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java index 1c650262..9f9cc6a5 100644 --- a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java @@ -18,23 +18,31 @@ public class KillContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(KillContainerCmd.class); private String containerId, signal; - + public KillContainerCmd(String containerId) { withContainerId(containerId); } - - public KillContainerCmd withContainerId(String containerId) { + + public String getContainerId() { + return containerId; + } + + public String getSignal() { + return signal; + } + + public KillContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - + public KillContainerCmd withSignal(String signal) { Preconditions.checkNotNull(signal, "signal was not specified"); this.signal = signal; return this; } - + @Override public String toString() { return "kill " + containerId; @@ -42,7 +50,7 @@ public String toString() { protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/kill", containerId)); - + if(signal != null) { webResource = webResource.queryParam("signal", signal); } @@ -62,7 +70,7 @@ protected Void impl() throws DockerException { throw new DockerException(exception); } } - + return null; } } diff --git a/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java b/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java index 77406155..226e1680 100644 --- a/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java @@ -17,7 +17,7 @@ /** * List containers - * + * * @param showAll - true or false, Show all containers. Only running containers are shown by default. * @param showSize - true or false, Show the containers sizes. This is false by default. * @param limit - Show `limit` last created containers, include non-running ones. There is no limit by default. @@ -28,39 +28,59 @@ public class ListContainersCmd extends AbstrDockerCmd> { private static final Logger LOGGER = LoggerFactory.getLogger(ListContainersCmd.class); - + private int limit = -1; private boolean showSize, showAll = false; String sinceId, beforeId; - - public ListContainersCmd withShowAll(boolean showAll) { + + public int getLimit() { + return limit; + } + + public boolean hasShowSizeEnabled() { + return showSize; + } + + public boolean hasShowAllEnabled() { + return showAll; + } + + public String getSinceId() { + return sinceId; + } + + public String getBeforeId() { + return beforeId; + } + + public ListContainersCmd withShowAll(boolean showAll) { this.showAll = showAll; return this; } - + public ListContainersCmd withShowSize(boolean showSize) { this.showSize = showSize; return this; } - + public ListContainersCmd withLimit(int limit) { Preconditions.checkArgument(limit > 0, "limit must be greater 0"); this.limit = limit; return this; } - + public ListContainersCmd withSince(String since) { Preconditions.checkNotNull(since, "since was not specified"); this.sinceId = since; return this; } - + public ListContainersCmd withBefore(String before) { Preconditions.checkNotNull(before, "before was not specified"); this.beforeId = before; return this; } - + @Override public String toString() { return new StringBuilder("ps ") @@ -76,7 +96,7 @@ protected List impl() { MultivaluedMap params = new MultivaluedMapImpl(); if(limit >= 0) { params.add("limit", String.valueOf(limit)); - } + } params.add("all", showAll ? "1" : "0"); params.add("since", sinceId); params.add("before", beforeId); diff --git a/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java b/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java index e4611f51..27af8ed9 100644 --- a/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java @@ -19,28 +19,36 @@ /** * List images - * + * * @param showAll - Show all images (by default filter out the intermediate images used to build) * @param filter - TODO: undocumented in docker remote api reference */ public class ListImagesCmd extends AbstrDockerCmd> { private static final Logger LOGGER = LoggerFactory.getLogger(ListImagesCmd.class); - + private String filter; private boolean showAll = false; - - public ListImagesCmd withShowAll(boolean showAll) { + + public String getFilter() { + return filter; + } + + public boolean hasShowAllEnabled() { + return showAll; + } + + public ListImagesCmd withShowAll(boolean showAll) { this.showAll = showAll; return this; } - + public ListImagesCmd withFilter(String filter) { Preconditions.checkNotNull(filter, "filter was not specified"); this.filter = filter; return this; } - + @Override public String toString() { return new StringBuilder("images ") diff --git a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java index d18ec9ac..f1feb73a 100644 --- a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java @@ -16,7 +16,7 @@ /** * Get container logs - * + * * @param followStream * - true or false, return stream. Defaults to false. * @param stdout @@ -35,7 +35,7 @@ public class LogContainerCmd extends AbstrDockerCmd params = new MultivaluedMapImpl(); params.add("timestamps", timestamps ? "1" : "0"); params.add("stdout", stdout ? "1" : "0"); params.add("stderr", stderr ? "1" : "0"); - params.add("follow", followStream ? "1" : "0"); - params.add("tail", tail < 0 ? "all" : ""+ tail); + params.add("follow", followStream ? "1" : "0"); + params.add("tail", tail < 0 ? "all" : ""+ tail); WebResource webResource = baseResource.path( String.format("/containers/%s/logs", containerId)) diff --git a/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java index 18ce0b7a..a4508369 100644 --- a/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java @@ -13,38 +13,42 @@ /** * Pause a container. - * + * * @param containerId - Id of the container - * + * */ public class PauseContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(PauseContainerCmd.class); private String containerId; - + public PauseContainerCmd(String containerId) { withContainerId(containerId); } - - public PauseContainerCmd withContainerId(String containerId) { + + public String getContainerId() { + return containerId; + } + + public PauseContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - + @Override public String toString() { return new StringBuilder("pause ") .append(containerId) .toString(); - } + } protected Integer impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/pause", containerId)); ClientResponse response = null; - + try { LOGGER.trace("POST: {}", webResource); response = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ClientResponse.class); @@ -60,7 +64,7 @@ protected Integer impl() throws DockerException { throw new DockerException(exception); } } - + return response.getStatus(); } } diff --git a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java b/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java index 16e0ee71..83832c47 100644 --- a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java @@ -16,45 +16,57 @@ /** - * + * * Pull image from repository. * */ public class PullImageCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(PullImageCmd.class); - + private String repository, tag, registry; - + public PullImageCmd(String repository) { withRepository(repository); } - - public PullImageCmd withRepository(String repository) { + + public String getRepository() { + return repository; + } + + public String getTag() { + return tag; + } + + public String getRegistry() { + return registry; + } + + public PullImageCmd withRepository(String repository) { Preconditions.checkNotNull(repository, "repository was not specified"); this.repository = repository; return this; } - + public PullImageCmd withTag(String tag) { Preconditions.checkNotNull(tag, "tag was not specified"); this.tag = tag; return this; } - + public PullImageCmd withRegistry(String registry) { Preconditions.checkNotNull(registry, "registry was not specified"); this.registry = registry; return this; } - + @Override public String toString() { return new StringBuilder("pull ") .append(repository) .append(tag != null ? ":" + tag : "") .toString(); - } + } protected ClientResponse impl() { Preconditions.checkNotNull(repository, "Repository was not specified"); diff --git a/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java b/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java index 6d54a756..41cdc077 100644 --- a/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java @@ -20,14 +20,18 @@ public class PushImageCmd extends AbstrAuthCfgDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(PushImageCmd.class); - + private String name; - + public PushImageCmd(String name) { withName(name); } - - /** + + public String getName() { + return name; + } + + /** * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. */ public PushImageCmd withName(String name) { @@ -35,13 +39,13 @@ public PushImageCmd withName(String name) { this.name = name; return this; } - + @Override public String toString() { return new StringBuilder("push ") .append(name) .toString(); - } + } protected ClientResponse impl() { WebResource webResource = baseResource.path("/images/" + name(name) + "/push"); @@ -56,7 +60,7 @@ protected ClientResponse impl() { throw new DockerException(e); } } - + private String name(String name) { return name.contains("/") ? name : authConfig.getUsername(); } diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java index e13cd970..3a12cd8e 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java @@ -13,7 +13,7 @@ /** * Remove a container. - * + * * @param removeVolumes - true or false, Remove the volumes associated to the container. Defaults to false * @param force - true or false, Removes the container even if it was running. Defaults to false */ @@ -22,33 +22,45 @@ public class RemoveContainerCmd extends AbstrDockerCmd private static final Logger LOGGER = LoggerFactory.getLogger(RemoveContainerCmd.class); private String containerId; - + private boolean removeVolumes, force; - + public RemoveContainerCmd(String containerId) { withContainerId(containerId); } - - public RemoveContainerCmd withContainerId(String containerId) { + + public String getContainerId() { + return containerId; + } + + public boolean hasRemoveVolumesEnabled() { + return removeVolumes; + } + + public boolean hasForceEnabled() { + return force; + } + + public RemoveContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - + public RemoveContainerCmd withRemoveVolumes(boolean removeVolumes) { this.removeVolumes = removeVolumes; return this; } - + public RemoveContainerCmd withForce() { return withForce(true); } - + public RemoveContainerCmd withForce(boolean force) { this.force = force; return this; } - + @Override public String toString() { return new StringBuilder("rm ") @@ -56,7 +68,7 @@ public String toString() { .append(force ? "--force=true" : "") .append(containerId) .toString(); - } + } protected Void impl() throws DockerException { Preconditions.checkState(!StringUtils.isEmpty(containerId), "Container ID can't be empty"); @@ -82,7 +94,7 @@ protected Void impl() throws DockerException { throw new DockerException(exception); } } - + return null; } } diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java b/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java index 5bc2765c..49707d51 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java @@ -11,42 +11,54 @@ import com.sun.jersey.api.client.WebResource; /** - * + * * Remove an image, deleting any tags it might have. - * + * */ public class RemoveImageCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(RemoveImageCmd.class); private String imageId; - + private boolean force, noPrune; - + public RemoveImageCmd(String imageId) { withImageId(imageId); } - - public RemoveImageCmd withImageId(String imageId) { + + public String getImageId() { + return imageId; + } + + public boolean hasForceEnabled() { + return force; + } + + public boolean hasNoPruneEnabled() { + return noPrune; + } + + public RemoveImageCmd withImageId(String imageId) { Preconditions.checkNotNull(imageId, "imageId was not specified"); this.imageId = imageId; return this; } - + public RemoveImageCmd withForce() { return withForce(true); } - + public RemoveImageCmd withForce(boolean force) { this.force = force; return this; } - + public RemoveImageCmd withNoPrune(boolean noPrune) { this.noPrune = noPrune; return this; } - + @Override public String toString() { return new StringBuilder("rmi ") @@ -54,7 +66,7 @@ public String toString() { .append(force ? "--force=true" : "") .append(imageId) .toString(); - } + } protected Void impl() throws DockerException { Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty"); @@ -62,11 +74,11 @@ protected Void impl() throws DockerException { try { WebResource webResource = baseResource.path("/images/" + imageId) .queryParam("force", force ? "1" : "0").queryParam("noprune", noPrune ? "1" : "0"); - + LOGGER.trace("DELETE: {}", webResource); webResource.delete(ClientResponse.class); - - + + } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 204) { //no error @@ -81,7 +93,7 @@ protected Void impl() throws DockerException { throw new DockerException(exception); } } - + return null; } } diff --git a/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java index 48a436c9..8a383af2 100644 --- a/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java @@ -13,41 +13,49 @@ /** * Restart a running container. - * + * * @param timeout - Timeout in seconds before killing the container. Defaults to 10 seconds. - * + * */ public class RestartContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(RestartContainerCmd.class); private String containerId; - + private int timeout = 10; - + public RestartContainerCmd(String containerId) { withContainerId(containerId); } - - public RestartContainerCmd withContainerId(String containerId) { + + public String getContainerId() { + return containerId; + } + + public int getTimeout() { + return timeout; + } + + public RestartContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - + public RestartContainerCmd withtTimeout(int timeout) { Preconditions.checkArgument(timeout >= 0, "timeout must be greater or equal 0"); this.timeout = timeout; return this; } - + @Override public String toString() { return new StringBuilder("restart ") .append("--time=" + timeout + " ") .append(containerId) .toString(); - } + } protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/restart", containerId)) @@ -68,7 +76,7 @@ protected Void impl() throws DockerException { throw new DockerException(exception); } } - + return null; } } diff --git a/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java b/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java index 90df5b78..6be29606 100644 --- a/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java @@ -16,32 +16,36 @@ /** - * - * + * + * * */ public class SearchImagesCmd extends AbstrDockerCmd> { private static final Logger LOGGER = LoggerFactory.getLogger(SearchImagesCmd.class); - + private String term; - + public SearchImagesCmd(String term) { withTerm(term); } - - public SearchImagesCmd withTerm(String term) { + + public String getTerm() { + return term; + } + + public SearchImagesCmd withTerm(String term) { Preconditions.checkNotNull(term, "term was not specified"); this.term = term; return this; } - + @Override public String toString() { return new StringBuilder("search ") .append(term) .toString(); - } + } protected List impl() { WebResource webResource = baseResource.path("/images/search").queryParam("term", term); diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index 3a3eebb3..49901e93 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -26,15 +26,19 @@ public class StartContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(StartContainerCmd.class); private String containerId; - + private StartContainerConfig startContainerConfig; - + public StartContainerCmd(String containerId) { startContainerConfig = new StartContainerConfig(); withContainerId(containerId); } - - public StartContainerCmd withBinds(Bind... binds) { + + public String getContainerId() { + return containerId; + } + + public StartContainerCmd withBinds(Bind... binds) { startContainerConfig.setBinds(binds); return this; } @@ -76,13 +80,13 @@ public StartContainerCmd withVolumesFrom(String volumesFrom) { startContainerConfig.setVolumesFrom(volumesFrom); return this; } - + public StartContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - + @Override public String toString() { return new StringBuilder("run ") @@ -90,7 +94,7 @@ public String toString() { .append(" using ") .append(startContainerConfig) .toString(); - } + } protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/start", containerId)); @@ -103,8 +107,8 @@ protected Void impl() throws DockerException { } else { builder.post((StartContainerConfig) null); } - - + + } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such container %s", containerId)); @@ -121,7 +125,7 @@ protected Void impl() throws DockerException { throw new DockerException(exception); } } - + return null; } } diff --git a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java index 9805cae1..69f45391 100644 --- a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java @@ -12,42 +12,50 @@ /** * Stop a running container. - * + * * @param containerId - Id of the container * @param timeout - Timeout in seconds before killing the container. Defaults to 10 seconds. - * + * */ public class StopContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(StopContainerCmd.class); private String containerId; - + private int timeout = 10; - + public StopContainerCmd(String containerId) { withContainerId(containerId); } - - public StopContainerCmd withContainerId(String containerId) { + + public String getContainerId() { + return containerId; + } + + public int getTimeout() { + return timeout; + } + + public StopContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - + public StopContainerCmd withTimeout(int timeout) { Preconditions.checkArgument(timeout >= 0, "timeout must be greater or equal 0"); this.timeout = timeout; return this; } - + @Override public String toString() { return new StringBuilder("stop ") .append("--time=" + timeout + " ") .append(containerId) .toString(); - } + } protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/stop", containerId)) @@ -71,7 +79,7 @@ protected Void impl() throws DockerException { throw new DockerException(exception); } } - + return null; } } diff --git a/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java b/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java index 80289050..8b1f281c 100644 --- a/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java @@ -15,7 +15,7 @@ /** * Tag an image into a repository - * + * * @param image * the local image to tag (either a name or an id) * @param repository @@ -27,44 +27,60 @@ public class TagImageCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(TagImageCmd.class); - + private String imageId, repository, tag; - + private boolean force; - + public TagImageCmd(String imageId, String repository, String tag) { withImageId(imageId); withRepository(repository); withTag(tag); } - - public TagImageCmd withImageId(String imageId) { + + public String getImageId() { + return imageId; + } + + public String getRepository() { + return repository; + } + + public String getTag() { + return tag; + } + + public boolean hasForceEnabled() { + return force; + } + + public TagImageCmd withImageId(String imageId) { Preconditions.checkNotNull(imageId, "imageId was not specified"); this.imageId = imageId; return this; } - + public TagImageCmd withRepository(String repository) { Preconditions.checkNotNull(repository, "repository was not specified"); this.repository = repository; return this; } - + public TagImageCmd withTag(String tag) { Preconditions.checkNotNull(tag, "tag was not specified"); this.tag = tag; return this; } - + public TagImageCmd withForce() { return withForce(true); } - + public TagImageCmd withForce(boolean force) { this.force = force; return this; } - + @Override public String toString() { return new StringBuilder("tag ") @@ -73,7 +89,7 @@ public String toString() { .append(imageId) .append(tag != null ? ":" + tag : "") .toString(); - } + } protected Integer impl() { diff --git a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java index 490f1951..8794a2d7 100644 --- a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java @@ -14,47 +14,55 @@ import com.sun.jersey.api.client.WebResource; /** - * + * * @author marcus - * + * */ public class TopContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(TopContainerCmd.class); private String containerId; - + private String psArgs; - + public TopContainerCmd(String containerId) { withContainerId(containerId); } - - public TopContainerCmd withContainerId(String containerId) { + + public String getContainerId() { + return containerId; + } + + public String getPsArgs() { + return psArgs; + } + + public TopContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - - + + public TopContainerCmd withPsArgs(String psArgs) { Preconditions.checkNotNull(psArgs, "psArgs was not specified"); this.psArgs = psArgs; return this; } - + @Override public String toString() { return new StringBuilder("top ") .append(containerId) .append(psArgs != null ? " " + psArgs : "") .toString(); - } + } protected ContainerTopResponse impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/top", containerId)); - - if(!StringUtils.isEmpty(psArgs)) + + if(!StringUtils.isEmpty(psArgs)) webResource = webResource.queryParam("ps_args", psArgs); try { diff --git a/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java index 9ad1c95a..9e75540c 100644 --- a/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java @@ -13,38 +13,42 @@ /** * Unpause a container. - * + * * @param containerId - Id of the container - * + * */ public class UnpauseContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(UnpauseContainerCmd.class); private String containerId; - + public UnpauseContainerCmd(String containerId) { withContainerId(containerId); } - - public UnpauseContainerCmd withContainerId(String containerId) { + + public String getContainerId() { + return containerId; + } + + public UnpauseContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - + @Override public String toString() { return new StringBuilder("pause ") .append(containerId) .toString(); - } + } protected Integer impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/unpause", containerId)); ClientResponse response = null; - + try { LOGGER.trace("POST: {}", webResource); response = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ClientResponse.class); @@ -60,7 +64,7 @@ protected Integer impl() throws DockerException { throw new DockerException(exception); } } - + return response.getStatus(); } } diff --git a/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java index 41202f14..653a86db 100644 --- a/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java @@ -20,21 +20,25 @@ public class WaitContainerCmd extends AbstrDockerCmd private static final Logger LOGGER = LoggerFactory.getLogger(WaitContainerCmd.class); private String containerId; - + public WaitContainerCmd(String containerId) { withContainerId(containerId); } - - public WaitContainerCmd withContainerId(String containerId) { + + public String getContainerId() { + return containerId; + } + + public WaitContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - + @Override public String toString() { return "wait " + containerId; - } + } protected Integer impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/wait", containerId)); From 3340bf0dac5726842ba82af2ffb1f7061982d712 Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Fri, 18 Jul 2014 17:53:19 -0400 Subject: [PATCH 048/452] Makes Config a public, immutable class with a builder This makes Config a public class, so it can be passed into the DockerClient constructor from code in different packages. It also makes Config an immutable object and includes a builder for convenience. Fixes issue #24. --- .../com/github/dockerjava/client/Config.java | 161 +++++++++++++++--- .../dockerjava/client/DockerClient.java | 53 +++--- 2 files changed, 163 insertions(+), 51 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/Config.java b/src/main/java/com/github/dockerjava/client/Config.java index 207d1300..d5b81bae 100644 --- a/src/main/java/com/github/dockerjava/client/Config.java +++ b/src/main/java/com/github/dockerjava/client/Config.java @@ -6,31 +6,75 @@ import java.net.URI; import java.util.Properties; -class Config { - URI url; - String version, username, password, email; - Integer readTimeout; - boolean enableLoggingFilter; +public class Config { + private final URI uri; + private final String version, username, password, email; + private final Integer readTimeout; + private final boolean loggingFilterEnabled; - private Config() { + private Config(DockerClientConfigBuilder builder) { + this.uri = builder.uri; + this.version = builder.version; + this.username = builder.username; + this.password = builder.password; + this.email = builder.email; + this.readTimeout = builder.readTimeout; + this.loggingFilterEnabled = builder.loggingFilterEnabled; } - static Config createConfig() throws DockerException { - final Properties p = new Properties(); + public URI getUri() { + return uri; + } + + public String getVersion() { + return version; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + public String getEmail() { + return email; + } + + public Integer getReadTimeout() { + return readTimeout; + } + + public boolean isLoggingFilterEnabled() { + return loggingFilterEnabled; + } + + public static Properties loadIncludedDockerProperties() { try { + Properties p = new Properties(); p.load(Config.class.getResourceAsStream("/docker.io.properties")); + return p; } catch (IOException e) { throw new DockerException(e); } + } - final File file = new File(System.getProperty("user.home"), ".docker.io.properties"); + /** + * Creates a new Properties object containing values overridden from ${user.home}/.docker.io.properties + * @param p The original set of properties to override + * @return A copy of the original Properties with overridden values + */ + public static Properties overrideDockerPropertiesWithSettingsFromUserHome(Properties p) { + Properties overriddenProperties = new Properties(); + overriddenProperties.putAll(p); - if (file.isFile()) { + final File usersDockerPropertiesFile = new File(System.getProperty("user.home"), ".docker.io.properties"); + if (usersDockerPropertiesFile.isFile()) { try { - final FileInputStream in = new FileInputStream(file); + final FileInputStream in = new FileInputStream(usersDockerPropertiesFile); try { - p.load(in); + overriddenProperties.load(in); } finally { in.close(); } @@ -38,24 +82,93 @@ static Config createConfig() throws DockerException { throw new DockerException(e); } } + return overriddenProperties; + } - for (String s : new String[]{"url", "version", "username", "password", "email"}) { + /** + * Creates a new Properties object containing values overridden from the System properties + * @param p The original set of properties to override + * @return A copy of the original Properties with overridden values + */ + public static Properties overrideDockerPropertiesWithSystemProperties(Properties p) { + Properties overriddenProperties = new Properties(); + overriddenProperties.putAll(p); + + // TODO Add all values from system properties that begin with docker.io.* + 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)); + if (System.getProperties().containsKey(key)) { + overriddenProperties.setProperty(key, System.getProperty(key)); } } + return overriddenProperties; + } + + public static DockerClientConfigBuilder createDefaultConfigBuilder() { + Properties properties = loadIncludedDockerProperties(); + properties = overrideDockerPropertiesWithSettingsFromUserHome(properties); + properties = overrideDockerPropertiesWithSystemProperties(properties); + return new DockerClientConfigBuilder().withProperties(properties); + } - final Config c = new Config(); + public static class DockerClientConfigBuilder { + private URI uri; + private String version, username, password, email; + private Integer readTimeout; + private boolean loggingFilterEnabled; - 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"); - c.readTimeout = Integer.valueOf(p.getProperty("docker.io.readTimeout", "1000")); - c.enableLoggingFilter = Boolean.valueOf(p.getProperty("docker.io.enableLoggingFilter", "true")); + public DockerClientConfigBuilder() { + } + + /** + * This will set all fields in the builder to those contained in the Properties object. The Properties object + * should contain the following docker.io.* keys: url, version, username, password, and email. If + * docker.io.readTimeout or docker.io.enableLoggingFilter are not contained, they will be set to 1000 and true, + * respectively. + * + * @param p + * @return + */ + public DockerClientConfigBuilder withProperties(Properties p) { + return withUri(p.getProperty("docker.io.url")) + .withVersion(p.getProperty("docker.io.version")) + .withUsername(p.getProperty("docker.io.username")) + .withPassword(p.getProperty("docker.io.password")) + .withEmail(p.getProperty("docker.io.email")) + .withReadTimeout(Integer.valueOf(p.getProperty("docker.io.readTimeout", "1000"))) + .withLoggingFilter(Boolean.valueOf(p.getProperty("docker.io.enableLoggingFilter", "true"))); + } - return c; + public final DockerClientConfigBuilder withUri(String uri) { + this.uri = URI.create(uri); + return this; + } + public final DockerClientConfigBuilder withVersion(String version) { + this.version = version; + return this; + } + public final DockerClientConfigBuilder withUsername(String username) { + this.username = username; + return this; + } + public final DockerClientConfigBuilder withPassword(String password) { + this.password = password; + return this; + } + public final DockerClientConfigBuilder withEmail(String email) { + this.email = email; + return this; + } + public final DockerClientConfigBuilder withReadTimeout(int readTimeout) { + this.readTimeout = readTimeout; + return this; + } + public final DockerClientConfigBuilder withLoggingFilter(boolean loggingFilterEnabled) { + this.loggingFilterEnabled = loggingFilterEnabled; + return this; + } + public Config build() { + return new Config(this); + } } } diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index 939b7a7c..a2099ae9 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -6,7 +6,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; -import java.net.URI; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; @@ -66,27 +65,25 @@ public class DockerClient { private WebResource baseResource; private AuthConfig authConfig; - - public DockerClient() throws DockerException { - this(Config.createConfig()); + public DockerClient() { + this(Config.createDefaultConfigBuilder().build()); } - public DockerClient(String serverUrl) throws DockerException { + public DockerClient(String serverUrl) { this(configWithServerUrl(serverUrl)); } - - private static Config configWithServerUrl(String serverUrl) - throws DockerException { - final Config c = Config.createConfig(); - c.url = URI.create(serverUrl); - return c; + + private static Config configWithServerUrl(String serverUrl) { + return Config.createDefaultConfigBuilder() + .withUri(serverUrl) + .build(); } public DockerClient(Config config) { ClientConfig clientConfig = new DefaultClientConfig(); - + SchemeRegistry schemeRegistry = new SchemeRegistry(); - schemeRegistry.register(new Scheme("http", config.url.getPort(), + schemeRegistry.register(new Scheme("http", config.getUri().getPort(), PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory .getSocketFactory())); @@ -103,17 +100,17 @@ public DockerClient(Config config) { null, false), clientConfig); // 1 hour - client.setReadTimeout(config.readTimeout); - + client.setReadTimeout(config.getReadTimeout()); + client.addFilter(new JsonClientFilter()); - - if (config.enableLoggingFilter) + + if (config.isLoggingFilterEnabled()) client.addFilter(new SelectiveLoggingFilter()); - baseResource = client.resource(config.url + "/v" + config.version); + baseResource = client.resource(config.getUri() + "/v" + config.getVersion()); } - + public void setCredentials(String username, String password, String email) { if (username == null) { @@ -143,9 +140,11 @@ public AuthConfig authConfig() throws DockerException { 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); + // TODO This should probably come from the Config used to create the DockerClient. + Config defaultConfig = Config.createDefaultConfigBuilder().build(); + a.setUsername(defaultConfig.getUsername()); + a.setPassword(defaultConfig.getPassword()); + a.setEmail(defaultConfig.getEmail()); if (a.getUsername() == null) { throw new IllegalStateException("username is null"); @@ -228,7 +227,7 @@ public ListContainersCmd listContainersCmd() { public CreateContainerCmd createContainerCmd(String image) { return new CreateContainerCmd(new CreateContainerConfig()).withImage( - image).withBaseResource(baseResource); + image).withBaseResource(baseResource); } public StartContainerCmd startContainerCmd(String containerId) { @@ -253,8 +252,8 @@ public WaitContainerCmd waitContainerCmd(String containerId) { public AttachContainerCmd attachContainerCmd(String containerId) { return new AttachContainerCmd(containerId).withBaseResource(baseResource); } - - + + public LogContainerCmd logContainerCmd(String containerId) { return new LogContainerCmd(containerId).withBaseResource(baseResource); } @@ -297,11 +296,11 @@ public BuildImgCmd buildImageCmd(InputStream tarInputStream) { public TopContainerCmd topContainerCmd(String containerId) { return new TopContainerCmd(containerId).withBaseResource(baseResource); } - + public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { return new TagImageCmd(imageId, repository, tag).withBaseResource(baseResource); } - + /** * @return The output slurped into a string. From 779204b6ac9ee7aa7dc85ff4e4eebe553488be22 Mon Sep 17 00:00:00 2001 From: Vojtech Juranek Date: Thu, 24 Jul 2014 22:09:38 +0200 Subject: [PATCH 049/452] Add ping method --- .../dockerjava/client/DockerClient.java | 5 ++++ .../dockerjava/client/command/PingCmd.java | 29 +++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 src/main/java/com/github/dockerjava/client/command/PingCmd.java diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index 939b7a7c..0c3936db 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -34,6 +34,7 @@ import com.github.dockerjava.client.command.ListContainersCmd; import com.github.dockerjava.client.command.ListImagesCmd; import com.github.dockerjava.client.command.LogContainerCmd; +import com.github.dockerjava.client.command.PingCmd; import com.github.dockerjava.client.command.PullImageCmd; import com.github.dockerjava.client.command.PushImageCmd; import com.github.dockerjava.client.command.RemoveContainerCmd; @@ -174,6 +175,10 @@ public AuthCmd authCmd() { public InfoCmd infoCmd() throws DockerException { return new InfoCmd().withBaseResource(baseResource); } + + public PingCmd pingCmd() { + return new PingCmd().withBaseResource(baseResource); + } public VersionCmd versionCmd() throws DockerException { return new VersionCmd().withBaseResource(baseResource); diff --git a/src/main/java/com/github/dockerjava/client/command/PingCmd.java b/src/main/java/com/github/dockerjava/client/command/PingCmd.java new file mode 100644 index 00000000..e017617a --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/command/PingCmd.java @@ -0,0 +1,29 @@ +package com.github.dockerjava.client.command; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; + +/** + * Ping the Docker server + * + */ +public class PingCmd extends AbstrDockerCmd { + + private static final Logger LOGGER = LoggerFactory.getLogger(PingCmd.class); + + protected Integer impl() { + WebResource webResource = baseResource.path("/_ping"); + + try { + LOGGER.trace("GET: {}", webResource); + ClientResponse resp = webResource.get(ClientResponse.class); + return resp.getStatus(); + } catch (UniformInterfaceException exception) { + return exception.getResponse().getStatus(); + } + } +} From 731ebe9abcc51fa915699535898bed87d1ae8813 Mon Sep 17 00:00:00 2001 From: Viet Nguyen Date: Tue, 29 Jul 2014 14:38:03 -0700 Subject: [PATCH 050/452] Change VolumesFrom to array --- .../client/command/CreateContainerCmd.java | 28 +++++++++++-------- .../model/ContainerInspectResponse.java | 4 +-- .../client/model/CreateContainerConfig.java | 6 ++-- 3 files changed, 22 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index bf671172..2947cf68 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -63,17 +63,23 @@ public CreateContainerCmd withVolumes(Volume... volumes) { return this; } - public CreateContainerCmd withEnv(String... env) { - Preconditions.checkNotNull(env, "env was not specified"); - this.containerCreateConfig.withEnv(env); - return this; - } - - public CreateContainerCmd withHostName(String hostName) { - Preconditions.checkNotNull(hostName, "hostName was not specified"); - this.containerCreateConfig.withHostName(hostName); - return this; - } + public CreateContainerCmd withVolumesFrom(String... volumesFrom) { + Preconditions.checkNotNull(volumesFrom, "volumes was not specified"); + this.containerCreateConfig.withVolumesFrom(volumesFrom); + return this; + } + + public CreateContainerCmd withEnv(String... env) { + Preconditions.checkNotNull(env, "env was not specified"); + this.containerCreateConfig.withEnv(env); + return this; + } + + public CreateContainerCmd withHostName(String hostName) { + Preconditions.checkNotNull(hostName, "hostName was not specified"); + this.containerCreateConfig.withHostName(hostName); + return this; + } public CreateContainerCmd withName(String name) { Preconditions.checkNotNull(name, "name was not specified"); diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java index 2469f0d8..7072037c 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java @@ -268,7 +268,7 @@ public class HostConfig { private String dns; @JsonProperty("VolumesFrom") - private String volumesFrom; + private String[] volumesFrom; @JsonProperty("ContainerIDFile") private String containerIDFile; @@ -307,7 +307,7 @@ public String getDns() { return dns; } - public String getVolumesFrom() { + public String[] getVolumesFrom() { return volumesFrom; } diff --git a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java index ab7dbb32..2ba9c9eb 100644 --- a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java @@ -58,7 +58,7 @@ public class CreateContainerConfig { @JsonProperty("Dns") private String[] dns; @JsonProperty("Image") private String image; @JsonProperty("Volumes") private Volumes volumes = new Volumes(); - @JsonProperty("VolumesFrom") private String volumesFrom = ""; + @JsonProperty("VolumesFrom") private String[] volumesFrom = new String[]{}; @JsonProperty("WorkingDir") private String workingDir = ""; @JsonProperty("DisableNetwork") private boolean disableNetwork = false; @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts = new ExposedPorts(); @@ -237,11 +237,11 @@ public CreateContainerConfig withVolumes(Volume[] volumes) { return this; } - public String getVolumesFrom() { + public String[] getVolumesFrom() { return volumesFrom; } - public CreateContainerConfig withVolumesFrom(String volumesFrom) { + public CreateContainerConfig withVolumesFrom(String[] volumesFrom) { this.volumesFrom = volumesFrom; return this; } From 1436c7ed68b4556292497f7a54070b2b0377ae70 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 31 Jul 2014 19:14:26 +0200 Subject: [PATCH 051/452] Fix for Issue#32 --- .../java/com/github/dockerjava/client/Config.java | 2 +- .../github/dockerjava/client/DockerClient.java | 15 +++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/Config.java b/src/main/java/com/github/dockerjava/client/Config.java index d5b81bae..469de35d 100644 --- a/src/main/java/com/github/dockerjava/client/Config.java +++ b/src/main/java/com/github/dockerjava/client/Config.java @@ -95,7 +95,7 @@ public static Properties overrideDockerPropertiesWithSystemProperties(Properties overriddenProperties.putAll(p); // TODO Add all values from system properties that begin with docker.io.* - for (String s : new String[]{"url", "version", "username", "password", "email"}) { + for (String s : new String[]{ "url", "version", "username", "password", "email"}) { final String key = "docker.io." + s; if (System.getProperties().containsKey(key)) { overriddenProperties.setProperty(key, System.getProperty(key)); diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index 15b73005..2aba605a 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -97,15 +97,22 @@ public DockerClient(Config config, CommandFactory cmdFactory) { client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, null, false), clientConfig); - // 1 hour - client.setReadTimeout(config.getReadTimeout()); + if(config.getReadTimeout() != null) { + client.setReadTimeout(config.getReadTimeout()); + } client.addFilter(new JsonClientFilter()); if (config.isLoggingFilterEnabled()) client.addFilter(new SelectiveLoggingFilter()); - - baseResource = client.resource(config.getUri() + "/v" + config.getVersion()); + + WebResource webResource = client.resource(config.getUri()); + + if(config.getVersion() != null) { + baseResource = webResource.path("v" + config.getVersion()); + } else { + baseResource = webResource; + } } From a17bfb28f6eb62970c09104045865442fe324064 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 31 Jul 2014 20:21:00 +0200 Subject: [PATCH 052/452] not null check for withUri --- .../com/github/dockerjava/client/Config.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/Config.java b/src/main/java/com/github/dockerjava/client/Config.java index 469de35d..08655917 100644 --- a/src/main/java/com/github/dockerjava/client/Config.java +++ b/src/main/java/com/github/dockerjava/client/Config.java @@ -6,6 +6,8 @@ import java.net.URI; import java.util.Properties; +import com.google.common.base.Preconditions; + public class Config { private final URI uri; private final String version, username, password, email; @@ -95,7 +97,7 @@ public static Properties overrideDockerPropertiesWithSystemProperties(Properties overriddenProperties.putAll(p); // TODO Add all values from system properties that begin with docker.io.* - for (String s : new String[]{ "url", "version", "username", "password", "email"}) { + for (String s : new String[]{ "url", "version", "username", "password", "email", "readTimeout", "enableLoggingFilter"}) { final String key = "docker.io." + s; if (System.getProperties().containsKey(key)) { overriddenProperties.setProperty(key, System.getProperty(key)); @@ -140,27 +142,28 @@ public DockerClientConfigBuilder withProperties(Properties p) { } public final DockerClientConfigBuilder withUri(String uri) { + Preconditions.checkNotNull(uri, "uri was not specified"); this.uri = URI.create(uri); return this; } public final DockerClientConfigBuilder withVersion(String version) { - this.version = version; + this.version = version; return this; } public final DockerClientConfigBuilder withUsername(String username) { - this.username = username; + this.username = username; return this; } public final DockerClientConfigBuilder withPassword(String password) { - this.password = password; + this.password = password; return this; } public final DockerClientConfigBuilder withEmail(String email) { - this.email = email; + this.email = email; return this; } - public final DockerClientConfigBuilder withReadTimeout(int readTimeout) { - this.readTimeout = readTimeout; + public final DockerClientConfigBuilder withReadTimeout(Integer readTimeout) { + this.readTimeout = readTimeout; return this; } public final DockerClientConfigBuilder withLoggingFilter(boolean loggingFilterEnabled) { From 5ff93ed3fc148c051c0d686234b6c2682e293890 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 31 Jul 2014 20:22:11 +0200 Subject: [PATCH 053/452] [maven-release-plugin] prepare release docker-java-0.9.1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5aee03c6..33b4ee28 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.9.1-SNAPSHOT + 0.9.1 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-0.9.1 From ffedb6fc460da66e35c23a096f169d0f62d50239 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 31 Jul 2014 20:22:16 +0200 Subject: [PATCH 054/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 33b4ee28..26711f68 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.9.1 + 0.9.2-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.9.1 + HEAD From f4ab2e8903fa0998c9be0f29313e407e2f80fe74 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 31 Jul 2014 21:40:21 +0200 Subject: [PATCH 055/452] Fix issue #33 --- .../java/com/github/dockerjava/client/command/CommitCmd.java | 5 +++-- .../com/github/dockerjava/client/command/CommitCmdTest.java | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java index df1a450a..67bf5b0a 100644 --- a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.slf4j.Logger; @@ -162,8 +163,8 @@ protected String impl() throws DockerException { try { LOGGER.trace("POST: {}", webResource); - ObjectNode ObjectNode = webResource.accept("application/vnd.docker.raw-stream").post(ObjectNode.class, params); - return ObjectNode.get("Id").asText(); + ObjectNode objectNode = webResource.queryParams(params).accept("application/vnd.docker.raw-stream").type(MediaType.APPLICATION_JSON).post(ObjectNode.class, commitConfig); + return objectNode.get("Id").asText(); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such container %s", containerId)); diff --git a/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java index 631b5ddf..2190b3b8 100644 --- a/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java @@ -47,7 +47,7 @@ public void afterMethod(ITestResult result) { public void commit() throws DockerException { ContainerCreateResponse container = dockerClient - .createContainerCmd("busybox").withCmd(new String[] { "touch", "/test" }).exec(); + .createContainerCmd("busybox").withCmd("touch", "/test").exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); From f7896a4d00d5cbc2e62342a0722575d1ba6adbbb Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Thu, 31 Jul 2014 21:46:37 +0200 Subject: [PATCH 056/452] Update README to latest release --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6c566a51..c7c9daef 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ Run build with tests: com.github.docker-java docker-java - 0.9.0 + 0.9.1 Latest SNAPSHOT is available from maven repo: https://oss.sonatype.org/content/groups/public @@ -60,7 +60,7 @@ For code examples, please look at the [Wiki](https://github.com/docker-java/dock There are a couple of configuration items, all of which have sensible defaults: * `url` The Docker URL, e.g. `http://localhost:2375`. -* `version` The API version, e.g. `1.12`. +* `version` The API version, e.g. `1.13`. * `username` Your repository username (required to push containers). * `password` Your repository password. * `email` Your repository email. @@ -87,4 +87,4 @@ In `$HOME/.docker.io.properties`, e.g.: In the class path at `/docker.io.properties`, e.g.: docker.io.url=http://localhost:2375 - docker.io.version=1.12 + docker.io.version=1.13 From 134f241fa1c44a265d1525cb61906da1d65d3d4f Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Thu, 31 Jul 2014 11:31:05 -0400 Subject: [PATCH 057/452] Renames Response objects to match their assoc cmds The Command and Response objects should have names that follow the same form. I've arbitrarily decided on VerbNoun. Since this is an API-breaking change and we're in pre-1.0.0, I've bumped the minor version from 9 to 10. --- pom.xml | 4 +- .../client/command/CreateContainerCmd.java | 10 +- .../client/command/ImportImageCmd.java | 8 +- .../client/command/InspectContainerCmd.java | 8 +- .../client/command/InspectImageCmd.java | 8 +- .../client/command/TopContainerCmd.java | 8 +- ...onse.java => CreateContainerResponse.java} | 4 +- ...Response.java => CreateImageResponse.java} | 4 +- ...nse.java => InspectContainerResponse.java} | 42 ++--- ...esponse.java => InspectImageResponse.java} | 24 +-- ...esponse.java => TopContainerResponse.java} | 18 +-- .../dockerjava/client/DockerClientTest.java | 16 +- .../client/command/BuildImageCmdTest.java | 52 +++---- .../client/command/CommitCmdTest.java | 22 +-- .../client/command/ContainerDiffCmdTest.java | 4 +- .../command/CreateContainerCmdTest.java | 68 ++++----- .../client/command/KillContainerCmdTest.java | 14 +- .../client/command/ListContainersCmdTest.java | 36 ++--- .../client/command/LogContainerCmdTest.java | 6 +- .../client/command/PullImageCmdTest.java | 14 +- .../client/command/PushImageCmdTest.java | 16 +- .../command/RemoveContainerCmdTest.java | 4 +- .../client/command/RemoveImageCmdTest.java | 4 +- .../command/RestartContainerCmdTest.java | 20 +-- .../client/command/StartContainerCmdTest.java | 144 +++++++++--------- .../client/command/StopContainerCmdTest.java | 14 +- .../client/command/WaitContainerCmdTest.java | 16 +- 27 files changed, 289 insertions(+), 299 deletions(-) rename src/main/java/com/github/dockerjava/client/model/{ContainerCreateResponse.java => CreateContainerResponse.java} (91%) rename src/main/java/com/github/dockerjava/client/model/{ImageCreateResponse.java => CreateImageResponse.java} (87%) rename src/main/java/com/github/dockerjava/client/model/{ContainerInspectResponse.java => InspectContainerResponse.java} (97%) rename src/main/java/com/github/dockerjava/client/model/{ImageInspectResponse.java => InspectImageResponse.java} (94%) rename src/main/java/com/github/dockerjava/client/model/{ContainerTopResponse.java => TopContainerResponse.java} (90%) diff --git a/pom.xml b/pom.xml index 26711f68..4d168980 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.9.2-SNAPSHOT + 0.10.0-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -147,7 +147,7 @@ jul-to-slf4j ${slf4j-api.version} - + com.google.guava guava diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index 2947cf68..0d4c6b2a 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -3,12 +3,12 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; +import com.github.dockerjava.client.model.CreateContainerResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; -import com.github.dockerjava.client.model.ContainerCreateResponse; import com.github.dockerjava.client.model.CreateContainerConfig; import com.github.dockerjava.client.model.ExposedPort; import com.github.dockerjava.client.model.Volume; @@ -23,7 +23,7 @@ * Creates a new container. * */ -public class CreateContainerCmd extends AbstrDockerCmd { +public class CreateContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(CreateContainerCmd.class); @@ -68,7 +68,7 @@ public CreateContainerCmd withVolumesFrom(String... volumesFrom) { this.containerCreateConfig.withVolumesFrom(volumesFrom); return this; } - + public CreateContainerCmd withEnv(String... env) { Preconditions.checkNotNull(env, "env was not specified"); this.containerCreateConfig.withEnv(env); @@ -102,7 +102,7 @@ public String toString() { .toString(); } - protected ContainerCreateResponse impl() { + protected CreateContainerResponse impl() { MultivaluedMap params = new MultivaluedMapImpl(); if (name != null) { params.add("name", name); @@ -113,7 +113,7 @@ protected ContainerCreateResponse impl() { LOGGER.trace("POST: {} ", webResource); return webResource.accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) - .post(ContainerCreateResponse.class, containerCreateConfig); + .post(CreateContainerResponse.class, containerCreateConfig); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("%s is an unrecognized image. Please pull the image first.", containerCreateConfig.getImage())); diff --git a/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java b/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java index 9d02d592..cefaa347 100644 --- a/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java @@ -5,11 +5,11 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; +import com.github.dockerjava.client.model.CreateImageResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ImageCreateResponse; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -18,7 +18,7 @@ /** * Create an image by importing the given stream of a tar file. */ -public class ImportImageCmd extends AbstrDockerCmd { +public class ImportImageCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(ImportImageCmd.class); @@ -78,7 +78,7 @@ public String toString() { .toString(); } - protected ImageCreateResponse impl() { + protected CreateImageResponse impl() { MultivaluedMap params = new MultivaluedMapImpl(); params.add("repo", repository); params.add("tag", tag); @@ -89,7 +89,7 @@ protected ImageCreateResponse impl() { try { LOGGER.trace("POST: {}", webResource); return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .post(ImageCreateResponse.class, imageStream); + .post(CreateImageResponse.class, imageStream); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 500) { diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java index a5e40dfe..e8284793 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java @@ -2,12 +2,12 @@ import javax.ws.rs.core.MediaType; +import com.github.dockerjava.client.model.InspectContainerResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; -import com.github.dockerjava.client.model.ContainerInspectResponse; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -15,7 +15,7 @@ /** * Inspect the details of a container. */ -public class InspectContainerCmd extends AbstrDockerCmd { +public class InspectContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(InspectContainerCmd.class); @@ -40,12 +40,12 @@ public String toString() { return "inspect " + containerId; } - protected ContainerInspectResponse impl() throws DockerException { + protected InspectContainerResponse impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/json", containerId)); try { LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(ContainerInspectResponse.class); + return webResource.accept(MediaType.APPLICATION_JSON).get(InspectContainerResponse.class); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such container %s", containerId)); diff --git a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java index 85df63b8..f414e145 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java @@ -7,7 +7,7 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; -import com.github.dockerjava.client.model.ImageInspectResponse; +import com.github.dockerjava.client.model.InspectImageResponse; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -16,7 +16,7 @@ /** * Inspect the details of an image. */ -public class InspectImageCmd extends AbstrDockerCmd { +public class InspectImageCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(InspectImageCmd.class); @@ -41,12 +41,12 @@ public String toString() { return "inspect " + imageId; } - protected ImageInspectResponse impl() { + protected InspectImageResponse impl() { WebResource webResource = baseResource.path(String.format("/images/%s/json", imageId)); try { LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(ImageInspectResponse.class); + return webResource.accept(MediaType.APPLICATION_JSON).get(InspectImageResponse.class); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such image %s", imageId)); diff --git a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java index 8794a2d7..d863dd56 100644 --- a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java @@ -2,13 +2,13 @@ import javax.ws.rs.core.MediaType; +import com.github.dockerjava.client.model.TopContainerResponse; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; -import com.github.dockerjava.client.model.ContainerTopResponse; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -18,7 +18,7 @@ * @author marcus * */ -public class TopContainerCmd extends AbstrDockerCmd { +public class TopContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(TopContainerCmd.class); @@ -59,7 +59,7 @@ public String toString() { .toString(); } - protected ContainerTopResponse impl() throws DockerException { + protected TopContainerResponse impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/top", containerId)); if(!StringUtils.isEmpty(psArgs)) @@ -67,7 +67,7 @@ protected ContainerTopResponse impl() throws DockerException { try { LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(ContainerTopResponse.class); + return webResource.accept(MediaType.APPLICATION_JSON).get(TopContainerResponse.class); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such container %s", containerId)); diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerCreateResponse.java b/src/main/java/com/github/dockerjava/client/model/CreateContainerResponse.java similarity index 91% rename from src/main/java/com/github/dockerjava/client/model/ContainerCreateResponse.java rename to src/main/java/com/github/dockerjava/client/model/CreateContainerResponse.java index d912ecc1..ab1e0a58 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerCreateResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/CreateContainerResponse.java @@ -11,7 +11,7 @@ * */ @JsonIgnoreProperties(ignoreUnknown = true) -public class ContainerCreateResponse { +public class CreateContainerResponse { @JsonProperty("Id") private String id; @@ -37,7 +37,7 @@ public void setWarnings(String[] warnings) { @Override public String toString() { - return "ContainerCreateResponse{" + + return "CreateContainerResponse{" + "id='" + id + '\'' + ", warnings=" + Arrays.toString(warnings) + '}'; diff --git a/src/main/java/com/github/dockerjava/client/model/ImageCreateResponse.java b/src/main/java/com/github/dockerjava/client/model/CreateImageResponse.java similarity index 87% rename from src/main/java/com/github/dockerjava/client/model/ImageCreateResponse.java rename to src/main/java/com/github/dockerjava/client/model/CreateImageResponse.java index d23aff50..30aa5fc0 100644 --- a/src/main/java/com/github/dockerjava/client/model/ImageCreateResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/CreateImageResponse.java @@ -10,7 +10,7 @@ * */ @JsonIgnoreProperties(ignoreUnknown = true) -public class ImageCreateResponse { +public class CreateImageResponse { @JsonProperty("status") private String id; @@ -23,7 +23,7 @@ public String getId() { @Override public String toString() { - return "ContainerCreateResponse{" + + return "CreateImageResponse{" + "id='" + id + '\'' + '}'; } diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/InspectContainerResponse.java similarity index 97% rename from src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java rename to src/main/java/com/github/dockerjava/client/model/InspectContainerResponse.java index 7072037c..53824430 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/InspectContainerResponse.java @@ -14,7 +14,7 @@ * */ @JsonIgnoreProperties(ignoreUnknown = true) -public class ContainerInspectResponse { +public class InspectContainerResponse { @JsonProperty("Args") private String[] args; @@ -30,16 +30,16 @@ public class ContainerInspectResponse { @JsonProperty("ExecDriver") private String execDriver; - + @JsonProperty("HostConfig") private HostConfig hostConfig; @JsonProperty("HostnamePath") private String hostnamePath; - + @JsonProperty("HostsPath") private String hostsPath; - + @JsonProperty("Id") private String id; @@ -48,7 +48,7 @@ public class ContainerInspectResponse { @JsonProperty("MountLabel") private String mountLabel; - + @JsonProperty("Name") private String name; @@ -60,7 +60,7 @@ public class ContainerInspectResponse { @JsonProperty("ProcessLabel") private String processLabel; - + @JsonProperty("ResolvConfPath") private String resolvConfPath; @@ -84,7 +84,7 @@ public String getCreated() { public String getPath() { return path; } - + public String getProcessLabel() { return processLabel; } @@ -142,11 +142,11 @@ public String getDriver() { public HostConfig getHostConfig() { return hostConfig; } - + public String getExecDriver() { return execDriver; } - + public String getMountLabel() { return mountLabel; } @@ -160,7 +160,7 @@ public class NetworkSettings { @JsonProperty("Bridge") private String bridge; @JsonProperty("PortMapping") private Map> portMapping; @JsonProperty("Ports") private Ports ports; - + public String getIpAddress() { return ipAddress; } @@ -208,7 +208,7 @@ public class ContainerState { @JsonProperty("ExitCode") private int exitCode; @JsonProperty("StartedAt") private String startedAt; @JsonProperty("FinishedAt") private String finishedAt; - + public boolean isRunning() { return running; } @@ -245,44 +245,44 @@ public String toString() { '}'; } } - + @JsonIgnoreProperties(ignoreUnknown = true) public class HostConfig { @JsonProperty("Binds") private String[] binds; - + @JsonProperty("LxcConf") private LxcConf[] lxcConf; - + @JsonProperty("PortBindings") private Ports portBindings; - + @JsonProperty("PublishAllPorts") private boolean publishAllPorts; - + @JsonProperty("Privileged") private boolean privileged; - + @JsonProperty("Dns") private String dns; - + @JsonProperty("VolumesFrom") private String[] volumesFrom; @JsonProperty("ContainerIDFile") private String containerIDFile; - + @JsonProperty("DnsSearch") private String dnsSearch; - + // TODO: use Links class here? @JsonProperty("Links") private String[] links; @JsonProperty("NetworkMode") private String networkMode; - + public String[] getBinds() { return binds; } diff --git a/src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java b/src/main/java/com/github/dockerjava/client/model/InspectImageResponse.java similarity index 94% rename from src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java rename to src/main/java/com/github/dockerjava/client/model/InspectImageResponse.java index 64b872f3..b2c42711 100644 --- a/src/main/java/com/github/dockerjava/client/model/ImageInspectResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/InspectImageResponse.java @@ -9,35 +9,35 @@ * */ @JsonIgnoreProperties(ignoreUnknown = true) -public class ImageInspectResponse { - +public class InspectImageResponse { + @JsonProperty("Architecture") private String arch; - + @JsonProperty("Author") private String author; - + @JsonProperty("Comment") private String comment; - + @JsonProperty("Config") private ContainerConfig config; - + @JsonProperty("Container") private String container; - + @JsonProperty("ContainerConfig") private ContainerConfig containerConfig; - + @JsonProperty("Created") private String created; - + @JsonProperty("DockerVersion") private String dockerVersion; @JsonProperty("Id") private String id; - + @JsonProperty("Os") private String os; @@ -45,7 +45,7 @@ public class ImageInspectResponse { private String parent; @JsonProperty("Size") - private long size; + private long size; public String getId() { return id; @@ -97,7 +97,7 @@ public String getOs() { @Override public String toString() { - return "ImageInspectResponse{" + + return "InspectImageResponse{" + "id='" + id + '\'' + ", parent='" + parent + '\'' + ", created='" + created + '\'' + diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerTopResponse.java b/src/main/java/com/github/dockerjava/client/model/TopContainerResponse.java similarity index 90% rename from src/main/java/com/github/dockerjava/client/model/ContainerTopResponse.java rename to src/main/java/com/github/dockerjava/client/model/TopContainerResponse.java index 080bccc2..a258d602 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerTopResponse.java +++ b/src/main/java/com/github/dockerjava/client/model/TopContainerResponse.java @@ -5,39 +5,39 @@ import com.google.common.base.Joiner; /** - * + * * @author marcus - * + * */ @JsonIgnoreProperties(ignoreUnknown = true) -public class ContainerTopResponse { +public class TopContainerResponse { @JsonProperty("Titles") private String[] titles; @JsonProperty("Processes") private String[][] processes; - + public String[] getTitles() { return titles; } - + public String[][] getProcesses() { return processes; } - + @Override public String toString() { Joiner joiner = Joiner.on("; ").skipNulls(); - + StringBuffer buffer = new StringBuffer(); buffer.append("["); for(String[] fields: processes) { buffer.append("[" + joiner.join(fields) + "]"); } buffer.append("]"); - - return "ContainerTopResponse{" + + + return "TopContainerResponse{" + "titles=" + joiner.join(titles) + ", processes=" + buffer.toString() + '}'; diff --git a/src/test/java/com/github/dockerjava/client/DockerClientTest.java b/src/test/java/com/github/dockerjava/client/DockerClientTest.java index 79f651c3..22843ac4 100644 --- a/src/test/java/com/github/dockerjava/client/DockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/DockerClientTest.java @@ -5,6 +5,7 @@ import java.lang.reflect.Method; +import com.github.dockerjava.client.model.CreateContainerResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; @@ -14,12 +15,9 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; -import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; - /** * Unit test for DockerClient. - * + * * @author Konstantin Pelykh (kpelykh@gmail.com) */ public class DockerClientTest extends AbstractDockerClientTest { @@ -45,7 +43,7 @@ public void afterMethod(ITestResult result) { super.afterMethod(result); } - + @Test public void testRunShlex() throws DockerException { @@ -59,7 +57,7 @@ public void testRunShlex() throws DockerException { for (String command : commands) { LOG.info("Running command: [{}]", command); - ContainerCreateResponse container = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd(commands).exec(); dockerClient.startContainerCmd(container.getId()); tmpContainers.add(container.getId()); @@ -67,6 +65,6 @@ public void testRunShlex() throws DockerException { assertThat(exitcode, equalTo(0)); } } - - -} \ No newline at end of file + + +} diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java index 42860427..74a7423c 100644 --- a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java @@ -12,9 +12,9 @@ import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Method; -import java.net.URI; -import java.net.URISyntaxException; +import com.github.dockerjava.client.model.CreateContainerResponse; +import com.github.dockerjava.client.model.InspectImageResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang.StringUtils; @@ -27,9 +27,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; -import com.github.dockerjava.client.model.ContainerInspectResponse; -import com.github.dockerjava.client.model.ImageInspectResponse; +import com.github.dockerjava.client.model.InspectContainerResponse; import com.sun.jersey.api.client.ClientResponse; public class BuildImageCmdTest extends AbstractDockerClientTest { @@ -82,13 +80,13 @@ public void testNginxDockerfileBuilder() throws DockerException, String imageId = StringUtils.substringBetween(fullLog, "Successfully built ", "\\n\"}").trim(); - ImageInspectResponse imageInspectResponse = dockerClient + InspectImageResponse inspectImageResponse = dockerClient .inspectImageCmd(imageId).exec(); - assertThat(imageInspectResponse, not(nullValue())); - LOG.info("Image Inspect: {}", imageInspectResponse.toString()); - tmpImgs.add(imageInspectResponse.getId()); + assertThat(inspectImageResponse, not(nullValue())); + LOG.info("Image Inspect: {}", inspectImageResponse.toString()); + tmpImgs.add(inspectImageResponse.getId()); - assertThat(imageInspectResponse.getAuthor(), + assertThat(inspectImageResponse.getAuthor(), equalTo("Guillaume J. Charmes \"guillaume@dotcloud.com\"")); } @@ -115,7 +113,7 @@ public void testDockerBuilderAddFolder() throws DockerException, dockerfileBuild(baseDir, "Successfully executed testAddFolder.sh"); } - + private String dockerfileBuild(File baseDir, String expectedText) throws DockerException, IOException { @@ -143,7 +141,7 @@ private String dockerfileBuild(File baseDir, String expectedText) "Successfully built ", "\\n\"}").trim(); // Create container based on image - ContainerCreateResponse container = dockerClient.createContainerCmd( + CreateContainerResponse container = dockerClient.createContainerCmd( imageId).exec(); LOG.info("Created container: {}", container.toString()); @@ -162,8 +160,8 @@ private String dockerfileBuild(File baseDir, String expectedText) return container.getId(); } - - + + private ClientResponse logContainer(String containerId) { return dockerClient.logContainerCmd(containerId).withStdErr().withStdOut().exec(); } @@ -196,28 +194,28 @@ public void testNetCatDockerfileBuilder() throws DockerException, String imageId = StringUtils.substringBetween(fullLog, "Successfully built ", "\\n\"}").trim(); - ImageInspectResponse imageInspectResponse = dockerClient + InspectImageResponse inspectImageResponse = dockerClient .inspectImageCmd(imageId).exec(); - assertThat(imageInspectResponse, not(nullValue())); - assertThat(imageInspectResponse.getId(), not(nullValue())); - LOG.info("Image Inspect: {}", imageInspectResponse.toString()); - tmpImgs.add(imageInspectResponse.getId()); + assertThat(inspectImageResponse, not(nullValue())); + assertThat(inspectImageResponse.getId(), not(nullValue())); + LOG.info("Image Inspect: {}", inspectImageResponse.toString()); + tmpImgs.add(inspectImageResponse.getId()); - ContainerCreateResponse container = dockerClient.createContainerCmd( - imageInspectResponse.getId()).exec(); + CreateContainerResponse container = dockerClient.createContainerCmd( + inspectImageResponse.getId()).exec(); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); tmpContainers.add(container.getId()); - ContainerInspectResponse containerInspectResponse = dockerClient + InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); - assertThat(containerInspectResponse.getId(), notNullValue()); - assertThat(containerInspectResponse.getNetworkSettings().getPorts(), + assertThat(inspectContainerResponse.getId(), notNullValue()); + assertThat(inspectContainerResponse.getNetworkSettings().getPorts(), notNullValue()); // No use as such if not running on the server -// for (Ports.Port p : containerInspectResponse.getNetworkSettings().getPorts().getAllPorts()) { +// for (Ports.Port p : inspectContainerResponse.getNetworkSettings().getPorts().getAllPorts()) { // int port = Integer.valueOf(p.getHostPort()); // LOG.info("Checking port {} is open", port); // assertThat(available(port), is(false)); @@ -225,7 +223,7 @@ public void testNetCatDockerfileBuilder() throws DockerException, dockerClient.stopContainerCmd(container.getId()).withTimeout(0).exec(); } - + @Test public void testAddAndCopySubstitution () throws DockerException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() @@ -233,4 +231,4 @@ public void testAddAndCopySubstitution () throws DockerException, IOException { dockerfileBuild(baseDir, "testENVSubstitution successfully completed"); } -} \ No newline at end of file +} diff --git a/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java index 2190b3b8..d4508fd3 100644 --- a/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java @@ -9,6 +9,8 @@ import java.lang.reflect.Method; +import com.github.dockerjava.client.model.CreateContainerResponse; +import com.github.dockerjava.client.model.InspectImageResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -18,8 +20,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; -import com.github.dockerjava.client.model.ImageInspectResponse; public class CommitCmdTest extends AbstractDockerClientTest { @@ -27,7 +27,7 @@ public class CommitCmdTest extends AbstractDockerClientTest { public void beforeTest() throws DockerException { super.beforeTest(); } - + @AfterTest public void afterTest() { super.afterTest(); @@ -42,11 +42,11 @@ public void beforeMethod(Method method) { public void afterMethod(ITestResult result) { super.afterMethod(result); } - + @Test public void commit() throws DockerException { - ContainerCreateResponse container = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("touch", "/test").exec(); LOG.info("Created container: {}", container.toString()); @@ -59,18 +59,18 @@ public void commit() throws DockerException { .commitCmd(container.getId()).exec(); tmpImgs.add(imageId); - ImageInspectResponse imageInspectResponse = dockerClient + InspectImageResponse inspectImageResponse = dockerClient .inspectImageCmd(imageId).exec(); - LOG.info("Image Inspect: {}", imageInspectResponse.toString()); + LOG.info("Image Inspect: {}", inspectImageResponse.toString()); - assertThat(imageInspectResponse, + assertThat(inspectImageResponse, hasField("container", startsWith(container.getId()))); - assertThat(imageInspectResponse.getContainerConfig().getImage(), + assertThat(inspectImageResponse.getContainerConfig().getImage(), equalTo("busybox")); - ImageInspectResponse busyboxImg = dockerClient.inspectImageCmd("busybox").exec(); + InspectImageResponse busyboxImg = dockerClient.inspectImageCmd("busybox").exec(); - assertThat(imageInspectResponse.getParent(), + assertThat(inspectImageResponse.getParent(), equalTo(busyboxImg.getId())); } diff --git a/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java b/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java index 697c08c0..76b292c4 100644 --- a/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java @@ -10,6 +10,7 @@ import java.lang.reflect.Method; import java.util.List; +import com.github.dockerjava.client.model.CreateContainerResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -20,7 +21,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.ChangeLog; -import com.github.dockerjava.client.model.ContainerCreateResponse; public class ContainerDiffCmdTest extends AbstractDockerClientTest { @@ -46,7 +46,7 @@ public void afterMethod(ITestResult result) { @Test public void testDiff() throws DockerException { - ContainerCreateResponse container = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("touch", "/test" ).exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); diff --git a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java index a0eaa48e..45941ec5 100644 --- a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java @@ -7,6 +7,7 @@ import java.lang.reflect.Method; import java.util.Arrays; +import com.github.dockerjava.client.model.CreateContainerResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -16,8 +17,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; -import com.github.dockerjava.client.model.ContainerInspectResponse; +import com.github.dockerjava.client.model.InspectContainerResponse; import com.github.dockerjava.client.model.Volume; public class CreateContainerCmdTest extends AbstractDockerClientTest { @@ -26,7 +26,7 @@ public class CreateContainerCmdTest extends AbstractDockerClientTest { public void beforeTest() throws DockerException { super.beforeTest(); } - + @AfterTest public void afterTest() { super.afterTest(); @@ -41,69 +41,69 @@ public void beforeMethod(Method method) { public void afterMethod(ITestResult result) { super.afterMethod(result); } - + @Test public void createContainerWithVolume() throws DockerException { - - ContainerCreateResponse container = dockerClient + + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withVolumes(new Volume("/var/log")).withCmd("true").exec(); tmpContainers.add(container.getId()); - + LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); - - ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); - - LOG.info("Inspect container {}", containerInspectResponse.getConfig().getVolumes()); - - assertThat(containerInspectResponse.getConfig().getVolumes().keySet(), contains("/var/log")); - - + + InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); + + LOG.info("Inspect container {}", inspectContainerResponse.getConfig().getVolumes()); + + assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), contains("/var/log")); + + } - + @Test public void createContainerWithEnv() throws DockerException { - - ContainerCreateResponse container = dockerClient + + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withEnv("VARIABLE=success").withCmd("env").exec(); tmpContainers.add(container.getId()); - + LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); - - ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); - - assertThat(Arrays.asList(containerInspectResponse.getConfig().getEnv()), contains("VARIABLE=success","HOME=/","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")); + + InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); + + assertThat(Arrays.asList(inspectContainerResponse.getConfig().getEnv()), contains("VARIABLE=success","HOME=/","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")); dockerClient.startContainerCmd(container.getId()).exec(); - + assertThat(logResponseStream(dockerClient.logContainerCmd(container.getId()).withStdOut().exec()), containsString("VARIABLE=success")); } - + @Test public void createContainerWithHostname() throws DockerException { - - ContainerCreateResponse container = dockerClient + + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withHostName("docker-java").withCmd("env").exec(); tmpContainers.add(container.getId()); - + LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); - - ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); - - assertThat(containerInspectResponse.getConfig().getHostName(), equalTo("docker-java")); + + InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); + + assertThat(inspectContainerResponse.getConfig().getHostName(), equalTo("docker-java")); dockerClient.startContainerCmd(container.getId()).exec(); - + assertThat(logResponseStream(dockerClient.logContainerCmd(container.getId()).withStdOut().exec()), containsString("HOSTNAME=docker-java")); } - + } diff --git a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java index 35c4ded0..00fbc244 100644 --- a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java @@ -8,6 +8,7 @@ import java.lang.reflect.Method; +import com.github.dockerjava.client.model.InspectContainerResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; @@ -19,8 +20,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; -import com.github.dockerjava.client.model.ContainerInspectResponse; +import com.github.dockerjava.client.model.CreateContainerResponse; public class KillContainerCmdTest extends AbstractDockerClientTest { @@ -50,7 +50,7 @@ public void afterMethod(ITestResult result) { @Test public void testKillContainer() throws DockerException { - ContainerCreateResponse container = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); @@ -60,13 +60,13 @@ public void testKillContainer() throws DockerException { LOG.info("Killing container: {}", container.getId()); dockerClient.killContainerCmd(container.getId()).exec(); - ContainerInspectResponse containerInspectResponse = dockerClient + InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); - LOG.info("Container Inspect: {}", containerInspectResponse.toString()); + LOG.info("Container Inspect: {}", inspectContainerResponse.toString()); - assertThat(containerInspectResponse.getState().isRunning(), + assertThat(inspectContainerResponse.getState().isRunning(), is(equalTo(false))); - assertThat(containerInspectResponse.getState().getExitCode(), + assertThat(inspectContainerResponse.getState().getExitCode(), not(equalTo(0))); } diff --git a/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java b/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java index df24a811..f52f56e2 100644 --- a/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java @@ -14,6 +14,7 @@ import java.lang.reflect.Method; import java.util.List; +import com.github.dockerjava.client.model.InspectContainerResponse; import org.hamcrest.Matcher; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; @@ -25,8 +26,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Container; -import com.github.dockerjava.client.model.ContainerCreateResponse; -import com.github.dockerjava.client.model.ContainerInspectResponse; +import com.github.dockerjava.client.model.CreateContainerResponse; public class ListContainersCmdTest extends AbstractDockerClientTest { @@ -34,7 +34,7 @@ public class ListContainersCmdTest extends AbstractDockerClientTest { public void beforeTest() throws DockerException { super.beforeTest(); } - + @AfterTest public void afterTest() { super.afterTest(); @@ -49,42 +49,42 @@ public void beforeMethod(Method method) { public void afterMethod(ITestResult result) { super.afterMethod(result); } - + @Test public void testListContainers() throws DockerException { - + String testImage = "busybox"; - + // need to block until image is pulled completely logResponseStream(dockerClient.pullImageCmd(testImage).exec()); - + List containers = dockerClient.listContainersCmd().withShowAll(true).exec(); assertThat(containers, notNullValue()); LOG.info("Container List: {}", containers); int size = containers.size(); - ContainerCreateResponse container1 = dockerClient + CreateContainerResponse container1 = dockerClient .createContainerCmd(testImage).withCmd("echo").exec(); - + assertThat(container1.getId(), not(isEmptyString())); - ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container1.getId()).exec(); - - assertThat(containerInspectResponse.getConfig().getImage(), is(equalTo(testImage))); - - + InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container1.getId()).exec(); + + assertThat(inspectContainerResponse.getConfig().getImage(), is(equalTo(testImage))); + + dockerClient.startContainerCmd(container1.getId()).exec(); tmpContainers.add(container1.getId()); - + LOG.info("container id: " + container1.getId()); List containers2 = dockerClient.listContainersCmd().withShowAll(true).exec(); - + 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); @@ -96,7 +96,7 @@ public void testListContainers() throws DockerException { for(Container container: filteredContainers) { LOG.info("filteredContainer: " + container); } - + Container container2 = filteredContainers.get(0); assertThat(container2.getCommand(), not(isEmptyString())); assertThat(container2.getImage(), startsWith(testImage + ":")); diff --git a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java index 4db44621..a0a07b25 100644 --- a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java @@ -18,7 +18,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.CreateContainerResponse; import com.sun.jersey.api.client.ClientResponse; public class LogContainerCmdTest extends AbstractDockerClientTest { @@ -48,9 +48,9 @@ public void logContainer() throws DockerException, IOException { String snippet = "hello world"; - ContainerCreateResponse container = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("/bin/echo", snippet).exec(); - + LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); diff --git a/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java index e4c77178..825ad19f 100644 --- a/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java @@ -8,6 +8,7 @@ import java.io.IOException; import java.lang.reflect.Method; +import com.github.dockerjava.client.model.InspectImageResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -17,7 +18,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ImageInspectResponse; import com.github.dockerjava.client.model.Info; import com.sun.jersey.api.client.ClientResponse; @@ -47,7 +47,7 @@ public void afterMethod(ITestResult result) { public void testPullImage() throws DockerException, IOException { Info info = dockerClient.infoCmd().exec(); LOG.info("Client info: {}", info.toString()); - + int imgCount = info.getImages(); LOG.info("imgCount1: {}", imgCount); @@ -63,10 +63,10 @@ public void testPullImage() throws DockerException, IOException { info = dockerClient.infoCmd().exec(); LOG.info("Client info: {}", info.toString()); - + imgCount = info.getImages(); LOG.info("imgCount2: {}", imgCount); - + LOG.info("Pulling image: {}", testImage); @@ -81,10 +81,10 @@ public void testPullImage() throws DockerException, IOException { assertThat(imgCount, lessThanOrEqualTo(info.getImages())); - ImageInspectResponse imageInspectResponse = dockerClient + InspectImageResponse inspectImageResponse = dockerClient .inspectImageCmd(testImage).exec(); - LOG.info("Image Inspect: {}", imageInspectResponse.toString()); - assertThat(imageInspectResponse, notNullValue()); + LOG.info("Image Inspect: {}", inspectImageResponse.toString()); + assertThat(inspectImageResponse, notNullValue()); } } diff --git a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java index f04322ec..dbe06729 100644 --- a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java @@ -20,10 +20,10 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.CreateContainerResponse; public class PushImageCmdTest extends AbstractDockerClientTest { - + public static final Logger LOG = LoggerFactory .getLogger(PushImageCmdTest.class); @@ -52,7 +52,7 @@ public void afterMethod(ITestResult result) { @Test public void testPushLatest() throws Exception { - ContainerCreateResponse container = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("true").exec(); LOG.info("Created container {}", container.toString()); @@ -60,16 +60,16 @@ public void testPushLatest() throws Exception { assertThat(container.getId(), not(isEmptyString())); tmpContainers.add(container.getId()); - + LOG.info("Commiting container: {}", container.toString()); String imageId = dockerClient.commitCmd(container.getId()).withRepository(username + "/busybox").exec(); logResponseStream(dockerClient.pushImageCmd(username + "/busybox").exec()); - + dockerClient.removeImageCmd(imageId).exec(); - + assertThat(asString(dockerClient.pullImageCmd(username + "/busybox").exec()), not(containsString("404"))); - + tmpImgs.add(username + "/busybox"); } @@ -79,6 +79,6 @@ public void testNotExistentImage() throws Exception { assertThat(logResponseStream(dockerClient.pushImageCmd(username + "/xxx").exec()), containsString("error")); } - + } diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java index 3e2bf403..454a252a 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java @@ -9,6 +9,7 @@ import java.lang.reflect.Method; import java.util.List; +import com.github.dockerjava.client.model.CreateContainerResponse; import org.hamcrest.Matcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,7 +22,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; public class RemoveContainerCmdTest extends AbstractDockerClientTest { @@ -50,7 +50,7 @@ public void afterMethod(ITestResult result) { @Test public void removeContainer() throws DockerException { - ContainerCreateResponse container = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("true").exec(); dockerClient.startContainerCmd(container.getId()).exec(); diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java index 81c5dcf5..bfee09ec 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java @@ -22,7 +22,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; +import com.github.dockerjava.client.model.CreateContainerResponse; public class RemoveImageCmdTest extends AbstractDockerClientTest { @@ -51,7 +51,7 @@ public void afterMethod(ITestResult result) { @Test public void testRemoveImage() throws DockerException, InterruptedException { - ContainerCreateResponse container = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("touch", "/test").exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); diff --git a/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java index cc65457e..9bcd2be0 100644 --- a/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java @@ -8,6 +8,7 @@ import java.lang.reflect.Method; +import com.github.dockerjava.client.model.InspectContainerResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -17,8 +18,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; -import com.github.dockerjava.client.model.ContainerInspectResponse; +import com.github.dockerjava.client.model.CreateContainerResponse; public class RestartContainerCmdTest extends AbstractDockerClientTest { @@ -45,31 +45,31 @@ public void afterMethod(ITestResult result) { @Test public void restartContainer() throws DockerException { - ContainerCreateResponse container = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); tmpContainers.add(container.getId()); - ContainerInspectResponse containerInspectResponse = dockerClient + InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); - LOG.info("Container Inspect: {}", containerInspectResponse.toString()); + LOG.info("Container Inspect: {}", inspectContainerResponse.toString()); - String startTime = containerInspectResponse.getState().getStartedAt(); + String startTime = inspectContainerResponse.getState().getStartedAt(); dockerClient.restartContainerCmd(container.getId()).withtTimeout(2).exec(); - ContainerInspectResponse containerInspectResponse2 = dockerClient + InspectContainerResponse inspectContainerResponse2 = dockerClient .inspectContainerCmd(container.getId()).exec(); LOG.info("Container Inspect After Restart: {}", - containerInspectResponse2.toString()); + inspectContainerResponse2.toString()); - String startTime2 = containerInspectResponse2.getState().getStartedAt(); + String startTime2 = inspectContainerResponse2.getState().getStartedAt(); assertThat(startTime, not(equalTo(startTime2))); - assertThat(containerInspectResponse.getState().isRunning(), + assertThat(inspectContainerResponse.getState().isRunning(), is(equalTo(true))); dockerClient.killContainerCmd(container.getId()).exec(); diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java index 996d93fa..7b109781 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -12,6 +12,7 @@ import java.lang.reflect.Method; import java.util.Arrays; +import com.github.dockerjava.client.model.*; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -21,14 +22,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.Bind; -import com.github.dockerjava.client.model.ContainerCreateResponse; -import com.github.dockerjava.client.model.ContainerInspectResponse; -import com.github.dockerjava.client.model.ExposedPort; -import com.github.dockerjava.client.model.Link; -import com.github.dockerjava.client.model.Ports; -import com.github.dockerjava.client.model.Volume; - +import com.github.dockerjava.client.model.CreateContainerResponse; public class StartContainerCmdTest extends AbstractDockerClientTest { @@ -58,10 +52,10 @@ public void startContainerWithVolumes() throws DockerException { // see http://docs.docker.io/use/working_with_volumes/ Volume volume1 = new Volume("/opt/webapp1"); - + Volume volume2 = new Volume("/opt/webapp2"); - - ContainerCreateResponse container = dockerClient + + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withVolumes(volume1, volume2) .withCmd("true").exec(); @@ -69,37 +63,37 @@ public void startContainerWithVolumes() throws DockerException { assertThat(container.getId(), not(isEmptyString())); - ContainerInspectResponse containerInspectResponse = dockerClient + InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); - assertThat(containerInspectResponse.getConfig().getVolumes().keySet(), + assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), contains("/opt/webapp1", "/opt/webapp2")); - + dockerClient.startContainerCmd(container.getId()).withBinds(new Bind("/src/webapp1", volume1, true), new Bind("/src/webapp2", volume2)).exec(); dockerClient.waitContainerCmd(container.getId()).exec(); - containerInspectResponse = dockerClient.inspectContainerCmd(container + inspectContainerResponse = dockerClient.inspectContainerCmd(container .getId()).exec(); - - assertThat(Arrays.asList(containerInspectResponse.getVolumes()), + + assertThat(Arrays.asList(inspectContainerResponse.getVolumes()), contains(volume1, volume2)); - assertThat(Arrays.asList(containerInspectResponse.getVolumesRW()), + assertThat(Arrays.asList(inspectContainerResponse.getVolumesRW()), contains(volume1, volume2)); - + tmpContainers.add(container.getId()); } - + @Test public void startContainerWithPortBindings() throws DockerException { - + ExposedPort tcp22 = ExposedPort.tcp(22); ExposedPort tcp23 = ExposedPort.tcp(23); - - ContainerCreateResponse container = dockerClient + + CreateContainerResponse container = dockerClient .createContainerCmd("busybox") .withCmd("true").withExposedPorts(tcp22, tcp23).exec(); @@ -107,7 +101,7 @@ public void startContainerWithPortBindings() throws DockerException { assertThat(container.getId(), not(isEmptyString())); - ContainerInspectResponse containerInspectResponse = dockerClient + InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); Ports portBindings = new Ports(); @@ -116,106 +110,106 @@ public void startContainerWithPortBindings() throws DockerException { dockerClient.startContainerCmd(container.getId()).withPortBindings(portBindings).exec(); - containerInspectResponse = dockerClient.inspectContainerCmd(container + inspectContainerResponse = dockerClient.inspectContainerCmd(container .getId()).exec(); - assertThat(Arrays.asList(containerInspectResponse.getConfig().getExposedPorts()), + assertThat(Arrays.asList(inspectContainerResponse.getConfig().getExposedPorts()), contains(tcp22, tcp23)); - assertThat(containerInspectResponse.getHostConfig().getPortBindings().getBindings().get(tcp22), + assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp22), is(equalTo(Ports.Binding("0.0.0.0", 11022)))); - - assertThat(containerInspectResponse.getHostConfig().getPortBindings().getBindings().get(tcp23), + + assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23), is(equalTo(Ports.Binding("0.0.0.0", 11023)))); - + tmpContainers.add(container.getId()); } - + @Test public void startContainerWithLinking() throws DockerException { - ContainerCreateResponse container1 = dockerClient + CreateContainerResponse container1 = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999").withName("container1").exec(); - + LOG.info("Created container1 {}", container1.toString()); assertThat(container1.getId(), not(isEmptyString())); tmpContainers.add(container1.getId()); dockerClient.startContainerCmd(container1.getId()).exec(); - ContainerInspectResponse containerInspectResponse1 = dockerClient + InspectContainerResponse inspectContainerResponse1 = dockerClient .inspectContainerCmd(container1.getId()).exec(); - LOG.info("Container1 Inspect: {}", containerInspectResponse1.toString()); - - assertThat(containerInspectResponse1.getConfig(), is(notNullValue())); - assertThat(containerInspectResponse1.getId(), not(isEmptyString())); - assertThat(containerInspectResponse1.getId(), startsWith(container1.getId())); - assertThat(containerInspectResponse1.getName(), equalTo("/container1")); - assertThat(containerInspectResponse1.getImageId(), not(isEmptyString())); - assertThat(containerInspectResponse1.getState(), is(notNullValue())); - assertThat(containerInspectResponse1.getState().isRunning(), is(true)); - - if (!containerInspectResponse1.getState().isRunning()) { - assertThat(containerInspectResponse1.getState().getExitCode(), + LOG.info("Container1 Inspect: {}", inspectContainerResponse1.toString()); + + assertThat(inspectContainerResponse1.getConfig(), is(notNullValue())); + assertThat(inspectContainerResponse1.getId(), not(isEmptyString())); + assertThat(inspectContainerResponse1.getId(), startsWith(container1.getId())); + assertThat(inspectContainerResponse1.getName(), equalTo("/container1")); + assertThat(inspectContainerResponse1.getImageId(), not(isEmptyString())); + assertThat(inspectContainerResponse1.getState(), is(notNullValue())); + assertThat(inspectContainerResponse1.getState().isRunning(), is(true)); + + if (!inspectContainerResponse1.getState().isRunning()) { + assertThat(inspectContainerResponse1.getState().getExitCode(), is(equalTo(0))); } - - ContainerCreateResponse container2 = dockerClient + + CreateContainerResponse container2 = dockerClient .createContainerCmd("busybox").withCmd("true").withName("container2").exec(); - + LOG.info("Created container2 {}", container2.toString()); assertThat(container2.getId(), not(isEmptyString())); tmpContainers.add(container2.getId()); dockerClient.startContainerCmd(container2.getId()).withLinks(new Link("container1", "container1Link")).exec(); - ContainerInspectResponse containerInspectResponse2 = dockerClient + InspectContainerResponse inspectContainerResponse2 = dockerClient .inspectContainerCmd(container2.getId()).exec(); - LOG.info("Container2 Inspect: {}", containerInspectResponse2.toString()); - - assertThat(containerInspectResponse2.getConfig(), is(notNullValue())); - assertThat(containerInspectResponse2.getId(), not(isEmptyString())); - assertThat(containerInspectResponse2.getHostConfig(), is(notNullValue())); - assertThat(containerInspectResponse2.getHostConfig().getLinks(), is(notNullValue())); - assertThat(containerInspectResponse2.getHostConfig().getLinks(), equalTo(new String[] {"/container1:/container2/container1Link"})); - assertThat(containerInspectResponse2.getId(), startsWith(container2.getId())); - assertThat(containerInspectResponse2.getName(), equalTo("/container2")); - assertThat(containerInspectResponse2.getImageId(), not(isEmptyString())); - assertThat(containerInspectResponse2.getState(), is(notNullValue())); - assertThat(containerInspectResponse2.getState().isRunning(), is(true)); + LOG.info("Container2 Inspect: {}", inspectContainerResponse2.toString()); + + assertThat(inspectContainerResponse2.getConfig(), is(notNullValue())); + assertThat(inspectContainerResponse2.getId(), not(isEmptyString())); + assertThat(inspectContainerResponse2.getHostConfig(), is(notNullValue())); + assertThat(inspectContainerResponse2.getHostConfig().getLinks(), is(notNullValue())); + assertThat(inspectContainerResponse2.getHostConfig().getLinks(), equalTo(new String[] {"/container1:/container2/container1Link"})); + assertThat(inspectContainerResponse2.getId(), startsWith(container2.getId())); + assertThat(inspectContainerResponse2.getName(), equalTo("/container2")); + assertThat(inspectContainerResponse2.getImageId(), not(isEmptyString())); + assertThat(inspectContainerResponse2.getState(), is(notNullValue())); + assertThat(inspectContainerResponse2.getState().isRunning(), is(true)); } - + @Test public void startContainer() throws DockerException { - ContainerCreateResponse container = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd(new String[] { "top" }).exec(); - + LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); tmpContainers.add(container.getId()); dockerClient.startContainerCmd(container.getId()).exec(); - ContainerInspectResponse containerInspectResponse = dockerClient + InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); - LOG.info("Container Inspect: {}", containerInspectResponse.toString()); + LOG.info("Container Inspect: {}", inspectContainerResponse.toString()); - assertThat(containerInspectResponse.getConfig(), is(notNullValue())); - assertThat(containerInspectResponse.getId(), not(isEmptyString())); + assertThat(inspectContainerResponse.getConfig(), is(notNullValue())); + assertThat(inspectContainerResponse.getId(), not(isEmptyString())); - assertThat(containerInspectResponse.getId(), + assertThat(inspectContainerResponse.getId(), startsWith(container.getId())); - assertThat(containerInspectResponse.getImageId(), not(isEmptyString())); - assertThat(containerInspectResponse.getState(), is(notNullValue())); + assertThat(inspectContainerResponse.getImageId(), not(isEmptyString())); + assertThat(inspectContainerResponse.getState(), is(notNullValue())); - assertThat(containerInspectResponse.getState().isRunning(), is(true)); + assertThat(inspectContainerResponse.getState().isRunning(), is(true)); - if (!containerInspectResponse.getState().isRunning()) { - assertThat(containerInspectResponse.getState().getExitCode(), + if (!inspectContainerResponse.getState().isRunning()) { + assertThat(inspectContainerResponse.getState().getExitCode(), is(equalTo(0))); } diff --git a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java index d9151088..719afe0d 100644 --- a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java @@ -8,6 +8,7 @@ import java.lang.reflect.Method; +import com.github.dockerjava.client.model.InspectContainerResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; @@ -19,8 +20,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; -import com.github.dockerjava.client.model.ContainerInspectResponse; +import com.github.dockerjava.client.model.CreateContainerResponse; public class StopContainerCmdTest extends AbstractDockerClientTest { @@ -50,7 +50,7 @@ public void afterMethod(ITestResult result) { @Test public void testStopContainer() throws DockerException { - ContainerCreateResponse container = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); @@ -60,12 +60,12 @@ public void testStopContainer() throws DockerException { LOG.info("Stopping container: {}", container.getId()); dockerClient.stopContainerCmd(container.getId()).withTimeout(2).exec(); - ContainerInspectResponse containerInspectResponse = dockerClient + InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); - LOG.info("Container Inspect: {}", containerInspectResponse.toString()); + LOG.info("Container Inspect: {}", inspectContainerResponse.toString()); - assertThat(containerInspectResponse.getState().isRunning(), is(equalTo(false))); - assertThat(containerInspectResponse.getState().getExitCode(), not(equalTo(0))); + assertThat(inspectContainerResponse.getState().isRunning(), is(equalTo(false))); + assertThat(inspectContainerResponse.getState().getExitCode(), not(equalTo(0))); } } diff --git a/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java index 0fd5a328..40483648 100644 --- a/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java @@ -8,6 +8,7 @@ import java.lang.reflect.Method; +import com.github.dockerjava.client.model.InspectContainerResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -17,8 +18,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.ContainerCreateResponse; -import com.github.dockerjava.client.model.ContainerInspectResponse; +import com.github.dockerjava.client.model.CreateContainerResponse; public class WaitContainerCmdTest extends AbstractDockerClientTest { @@ -45,9 +45,9 @@ public void afterMethod(ITestResult result) { @Test public void testWaitContainer() throws DockerException { - ContainerCreateResponse container = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("true").exec(); - + LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); tmpContainers.add(container.getId()); @@ -59,12 +59,12 @@ public void testWaitContainer() throws DockerException { assertThat(exitCode, equalTo(0)); - ContainerInspectResponse containerInspectResponse = dockerClient + InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); - LOG.info("Container Inspect: {}", containerInspectResponse.toString()); + LOG.info("Container Inspect: {}", inspectContainerResponse.toString()); - assertThat(containerInspectResponse.getState().isRunning(), is(equalTo(false))); - assertThat(containerInspectResponse.getState().getExitCode(), is(equalTo(exitCode))); + assertThat(inspectContainerResponse.getState().isRunning(), is(equalTo(false))); + assertThat(inspectContainerResponse.getState().getExitCode(), is(equalTo(exitCode))); } From dc0e625d5c6f7c74fc1f1e76f3f3bc37341d95ba Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Thu, 31 Jul 2014 11:36:15 -0400 Subject: [PATCH 058/452] Moves response objects to the commands package This moves the Response objects into the same package as their associated commands, since they're so tightly coupled. --- .../github/dockerjava/client/command/CreateContainerCmd.java | 1 - .../client/{model => command}/CreateContainerResponse.java | 2 +- .../client/{model => command}/CreateImageResponse.java | 2 +- .../com/github/dockerjava/client/command/ImportImageCmd.java | 1 - .../github/dockerjava/client/command/InspectContainerCmd.java | 1 - .../client/{model => command}/InspectContainerResponse.java | 3 ++- .../com/github/dockerjava/client/command/InspectImageCmd.java | 1 - .../client/{model => command}/InspectImageResponse.java | 3 ++- .../com/github/dockerjava/client/command/TopContainerCmd.java | 1 - .../client/{model => command}/TopContainerResponse.java | 2 +- .../java/com/github/dockerjava/client/DockerClientTest.java | 2 +- .../github/dockerjava/client/command/BuildImageCmdTest.java | 3 --- .../com/github/dockerjava/client/command/CommitCmdTest.java | 2 -- .../github/dockerjava/client/command/ContainerDiffCmdTest.java | 1 - .../dockerjava/client/command/CreateContainerCmdTest.java | 2 -- .../github/dockerjava/client/command/KillContainerCmdTest.java | 2 -- .../dockerjava/client/command/ListContainersCmdTest.java | 2 -- .../github/dockerjava/client/command/LogContainerCmdTest.java | 1 - .../com/github/dockerjava/client/command/PullImageCmdTest.java | 1 - .../com/github/dockerjava/client/command/PushImageCmdTest.java | 1 - .../dockerjava/client/command/RemoveContainerCmdTest.java | 1 - .../github/dockerjava/client/command/RemoveImageCmdTest.java | 1 - .../dockerjava/client/command/RestartContainerCmdTest.java | 2 -- .../dockerjava/client/command/StartContainerCmdTest.java | 1 - .../github/dockerjava/client/command/StopContainerCmdTest.java | 2 -- .../github/dockerjava/client/command/WaitContainerCmdTest.java | 2 -- 26 files changed, 8 insertions(+), 35 deletions(-) rename src/main/java/com/github/dockerjava/client/{model => command}/CreateContainerResponse.java (95%) rename src/main/java/com/github/dockerjava/client/{model => command}/CreateImageResponse.java (92%) rename src/main/java/com/github/dockerjava/client/{model => command}/InspectContainerResponse.java (98%) rename src/main/java/com/github/dockerjava/client/{model => command}/InspectImageResponse.java (95%) rename src/main/java/com/github/dockerjava/client/{model => command}/TopContainerResponse.java (95%) diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index 0d4c6b2a..a8456e3b 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -3,7 +3,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; -import com.github.dockerjava.client.model.CreateContainerResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/com/github/dockerjava/client/model/CreateContainerResponse.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java similarity index 95% rename from src/main/java/com/github/dockerjava/client/model/CreateContainerResponse.java rename to src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java index ab1e0a58..c8a5870e 100644 --- a/src/main/java/com/github/dockerjava/client/model/CreateContainerResponse.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.model; +package com.github.dockerjava.client.command; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/github/dockerjava/client/model/CreateImageResponse.java b/src/main/java/com/github/dockerjava/client/command/CreateImageResponse.java similarity index 92% rename from src/main/java/com/github/dockerjava/client/model/CreateImageResponse.java rename to src/main/java/com/github/dockerjava/client/command/CreateImageResponse.java index 30aa5fc0..3c657b9a 100644 --- a/src/main/java/com/github/dockerjava/client/model/CreateImageResponse.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateImageResponse.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.model; +package com.github.dockerjava.client.command; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java b/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java index cefaa347..3744eeb8 100644 --- a/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java @@ -5,7 +5,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; -import com.github.dockerjava.client.model.CreateImageResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java index e8284793..78967e2d 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java @@ -2,7 +2,6 @@ import javax.ws.rs.core.MediaType; -import com.github.dockerjava.client.model.InspectContainerResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/com/github/dockerjava/client/model/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java similarity index 98% rename from src/main/java/com/github/dockerjava/client/model/InspectContainerResponse.java rename to src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java index 53824430..bdfb5ce5 100644 --- a/src/main/java/com/github/dockerjava/client/model/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.model; +package com.github.dockerjava.client.command; import java.util.Arrays; @@ -7,6 +7,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.dockerjava.client.model.*; /** * diff --git a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java index f414e145..0343dc82 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java @@ -7,7 +7,6 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; -import com.github.dockerjava.client.model.InspectImageResponse; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; diff --git a/src/main/java/com/github/dockerjava/client/model/InspectImageResponse.java b/src/main/java/com/github/dockerjava/client/command/InspectImageResponse.java similarity index 95% rename from src/main/java/com/github/dockerjava/client/model/InspectImageResponse.java rename to src/main/java/com/github/dockerjava/client/command/InspectImageResponse.java index b2c42711..82b634e4 100644 --- a/src/main/java/com/github/dockerjava/client/model/InspectImageResponse.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectImageResponse.java @@ -1,7 +1,8 @@ -package com.github.dockerjava.client.model; +package com.github.dockerjava.client.command; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.dockerjava.client.model.ContainerConfig; /** * diff --git a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java index d863dd56..fde5f54e 100644 --- a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java @@ -2,7 +2,6 @@ import javax.ws.rs.core.MediaType; -import com.github.dockerjava.client.model.TopContainerResponse; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/com/github/dockerjava/client/model/TopContainerResponse.java b/src/main/java/com/github/dockerjava/client/command/TopContainerResponse.java similarity index 95% rename from src/main/java/com/github/dockerjava/client/model/TopContainerResponse.java rename to src/main/java/com/github/dockerjava/client/command/TopContainerResponse.java index a258d602..70701ff1 100644 --- a/src/main/java/com/github/dockerjava/client/model/TopContainerResponse.java +++ b/src/main/java/com/github/dockerjava/client/command/TopContainerResponse.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.model; +package com.github.dockerjava.client.command; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/test/java/com/github/dockerjava/client/DockerClientTest.java b/src/test/java/com/github/dockerjava/client/DockerClientTest.java index 22843ac4..9abac0b4 100644 --- a/src/test/java/com/github/dockerjava/client/DockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/DockerClientTest.java @@ -5,7 +5,7 @@ import java.lang.reflect.Method; -import com.github.dockerjava.client.model.CreateContainerResponse; +import com.github.dockerjava.client.command.CreateContainerResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java index 74a7423c..17934c06 100644 --- a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java @@ -13,8 +13,6 @@ import java.io.StringWriter; import java.lang.reflect.Method; -import com.github.dockerjava.client.model.CreateContainerResponse; -import com.github.dockerjava.client.model.InspectImageResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang.StringUtils; @@ -27,7 +25,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.InspectContainerResponse; import com.sun.jersey.api.client.ClientResponse; public class BuildImageCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java index d4508fd3..85bc6227 100644 --- a/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java @@ -9,8 +9,6 @@ import java.lang.reflect.Method; -import com.github.dockerjava.client.model.CreateContainerResponse; -import com.github.dockerjava.client.model.InspectImageResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; diff --git a/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java b/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java index 76b292c4..078d6382 100644 --- a/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java @@ -10,7 +10,6 @@ import java.lang.reflect.Method; import java.util.List; -import com.github.dockerjava.client.model.CreateContainerResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; diff --git a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java index 45941ec5..56fc5ca9 100644 --- a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java @@ -7,7 +7,6 @@ import java.lang.reflect.Method; import java.util.Arrays; -import com.github.dockerjava.client.model.CreateContainerResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -17,7 +16,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.InspectContainerResponse; import com.github.dockerjava.client.model.Volume; public class CreateContainerCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java index 00fbc244..b1ff3027 100644 --- a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java @@ -8,7 +8,6 @@ import java.lang.reflect.Method; -import com.github.dockerjava.client.model.InspectContainerResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; @@ -20,7 +19,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.CreateContainerResponse; public class KillContainerCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java b/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java index f52f56e2..7c4332fc 100644 --- a/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java @@ -14,7 +14,6 @@ import java.lang.reflect.Method; import java.util.List; -import com.github.dockerjava.client.model.InspectContainerResponse; import org.hamcrest.Matcher; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; @@ -26,7 +25,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Container; -import com.github.dockerjava.client.model.CreateContainerResponse; public class ListContainersCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java index a0a07b25..43c54d22 100644 --- a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java @@ -18,7 +18,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.CreateContainerResponse; import com.sun.jersey.api.client.ClientResponse; public class LogContainerCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java index 825ad19f..0472720d 100644 --- a/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java @@ -8,7 +8,6 @@ import java.io.IOException; import java.lang.reflect.Method; -import com.github.dockerjava.client.model.InspectImageResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; diff --git a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java index dbe06729..0e1dcf1b 100644 --- a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java @@ -20,7 +20,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.CreateContainerResponse; public class PushImageCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java index 454a252a..4b614a48 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java @@ -9,7 +9,6 @@ import java.lang.reflect.Method; import java.util.List; -import com.github.dockerjava.client.model.CreateContainerResponse; import org.hamcrest.Matcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java index bfee09ec..5944d8f6 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java @@ -22,7 +22,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.CreateContainerResponse; public class RemoveImageCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java index 9bcd2be0..c25784b9 100644 --- a/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java @@ -8,7 +8,6 @@ import java.lang.reflect.Method; -import com.github.dockerjava.client.model.InspectContainerResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -18,7 +17,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.CreateContainerResponse; public class RestartContainerCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java index 7b109781..4ea95fec 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -22,7 +22,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.CreateContainerResponse; public class StartContainerCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java index 719afe0d..aeb8ed0d 100644 --- a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java @@ -8,7 +8,6 @@ import java.lang.reflect.Method; -import com.github.dockerjava.client.model.InspectContainerResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; @@ -20,7 +19,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.CreateContainerResponse; public class StopContainerCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java index 40483648..fff08321 100644 --- a/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java @@ -8,7 +8,6 @@ import java.lang.reflect.Method; -import com.github.dockerjava.client.model.InspectContainerResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -18,7 +17,6 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.CreateContainerResponse; public class WaitContainerCmdTest extends AbstractDockerClientTest { From e904a40f2a486a92a0418b2e41dde3ecc0e8a39d Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Thu, 31 Jul 2014 11:45:20 -0400 Subject: [PATCH 059/452] Renames ImportImageCmd to CreateImageCmd This renames the command class and related methods to match the method name in the Docker Remote API. https://docs.docker.com/reference/api/docker_remote_api_v1.13/#22-images --- .../com/github/dockerjava/client/DockerClient.java | 13 ++++++------- .../dockerjava/client/command/CommandFactory.java | 2 +- .../{ImportImageCmd.java => CreateImageCmd.java} | 12 ++++++------ .../client/command/DefaultCommandFactory.java | 6 +++--- 4 files changed, 16 insertions(+), 17 deletions(-) rename src/main/java/com/github/dockerjava/client/command/{ImportImageCmd.java => CreateImageCmd.java} (86%) diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index 2aba605a..09bd7017 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -24,7 +24,7 @@ import com.github.dockerjava.client.command.ContainerDiffCmd; import com.github.dockerjava.client.command.CopyFileFromContainerCmd; import com.github.dockerjava.client.command.CreateContainerCmd; -import com.github.dockerjava.client.command.ImportImageCmd; +import com.github.dockerjava.client.command.CreateImageCmd; import com.github.dockerjava.client.command.InfoCmd; import com.github.dockerjava.client.command.InspectContainerCmd; import com.github.dockerjava.client.command.InspectImageCmd; @@ -63,7 +63,7 @@ public class DockerClient implements Closeable { private Client client; - + private final CommandFactory cmdFactory; private final WebResource baseResource; private AuthConfig authConfig; @@ -96,7 +96,7 @@ public DockerClient(Config config, CommandFactory cmdFactory) { ClientConfig clientConfig = new DefaultClientConfig(); client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, null, false), clientConfig); - + if(config.getReadTimeout() != null) { client.setReadTimeout(config.getReadTimeout()); } @@ -195,7 +195,7 @@ public AuthCmd authCmd() { public InfoCmd infoCmd() throws DockerException { return cmdFactory.infoCmd().withBaseResource(baseResource); } - + public PingCmd pingCmd() { return cmdFactory.pingCmd().withBaseResource(baseResource); } @@ -221,9 +221,8 @@ public PushImageCmd pushImageCmd(String name) { // return execute(pushImageCmd(name)); // } - public ImportImageCmd importImageCmd(String repository, - InputStream imageStream) { - return cmdFactory.importImageCmd(repository, imageStream) + public CreateImageCmd createImageCmd(String repository, InputStream imageStream) { + return cmdFactory.createImageCmd(repository, imageStream) .withBaseResource(baseResource); } diff --git a/src/main/java/com/github/dockerjava/client/command/CommandFactory.java b/src/main/java/com/github/dockerjava/client/command/CommandFactory.java index 06f8fe78..ad970a4b 100644 --- a/src/main/java/com/github/dockerjava/client/command/CommandFactory.java +++ b/src/main/java/com/github/dockerjava/client/command/CommandFactory.java @@ -14,7 +14,7 @@ public interface CommandFactory { public ContainerDiffCmd containerDiffCmd(String containerId); public CopyFileFromContainerCmd copyFileFromContainerCmd(String containerId, String resource); public CreateContainerCmd createContainerCmd(String image); - public ImportImageCmd importImageCmd(String repository, InputStream imageStream); + public CreateImageCmd createImageCmd(String repository, InputStream imageStream); public InfoCmd infoCmd(); public InspectContainerCmd inspectContainerCmd(String containerId); public InspectImageCmd inspectImageCmd(String imageId); diff --git a/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java similarity index 86% rename from src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java rename to src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java index 3744eeb8..1254f63e 100644 --- a/src/main/java/com/github/dockerjava/client/command/ImportImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java @@ -17,9 +17,9 @@ /** * Create an image by importing the given stream of a tar file. */ -public class ImportImageCmd extends AbstrDockerCmd { +public class CreateImageCmd extends AbstrDockerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(ImportImageCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CreateImageCmd.class); private String repository, tag; private InputStream imageStream; @@ -28,7 +28,7 @@ public class ImportImageCmd extends AbstrDockerCmd Date: Fri, 1 Aug 2014 18:12:37 +0200 Subject: [PATCH 060/452] Exposing the withTTY method for container creation. --- .../client/command/CreateContainerCmd.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index 2947cf68..04208276 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -1,11 +1,5 @@ package com.github.dockerjava.client.command; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.github.dockerjava.client.model.ContainerCreateResponse; @@ -16,6 +10,11 @@ import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; /** @@ -68,6 +67,11 @@ public CreateContainerCmd withVolumesFrom(String... volumesFrom) { this.containerCreateConfig.withVolumesFrom(volumesFrom); return this; } + + public CreateContainerCmd withTTY(boolean tty) { + this.containerCreateConfig.withTty(tty); + return this; + } public CreateContainerCmd withEnv(String... env) { Preconditions.checkNotNull(env, "env was not specified"); From 4c21760db2c7194f3cbbd4bb60feb43516bdc6e2 Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Fri, 1 Aug 2014 16:48:41 -0400 Subject: [PATCH 061/452] Adds test for CopyFileFromContainer This changes the CopyFileFromContainer's impl method to not call toString on the copyConfig that it uses in the POST body, instead relying on the default JSON serializer and marked fields. This will allow us to use a reflection-based toString. This commit also creates a test around the use of the CopyFileFromContainer command. --- .../command/CopyFileFromContainerCmd.java | 2 +- .../command/CopyFileFromContainerCmdTest.java | 52 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java diff --git a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java index dd974278..60bdf7e7 100644 --- a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java @@ -69,7 +69,7 @@ protected ClientResponse impl() throws DockerException { WebResource.Builder builder = webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).type("application/json"); - return builder.post(ClientResponse.class, copyConfig.toString()); + return builder.post(ClientResponse.class, copyConfig); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 400) { throw new DockerException("bad parameter"); diff --git a/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java new file mode 100644 index 00000000..4ef73988 --- /dev/null +++ b/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java @@ -0,0 +1,52 @@ +package com.github.dockerjava.client.command; + +import com.github.dockerjava.client.AbstractDockerClientTest; +import com.sun.jersey.api.client.ClientResponse; +import org.testng.ITestResult; +import org.testng.annotations.*; + +import java.lang.reflect.Method; + +import static org.hamcrest.Matchers.*; +import static org.hamcrest.MatcherAssert.assertThat; + +public class CopyFileFromContainerCmdTest extends AbstractDockerClientTest { + + @BeforeTest + public void beforeTest() { + 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 copyFromContainer() { + // TODO extract this into a shared method + CreateContainerResponse container = dockerClient.createContainerCmd("busybox") + .withName("docker-java-itest-copyFromContainer") + .withCmd("touch", "/test") + .exec(); + + LOG.info("Created container: {}", container); + assertThat(container.getId(), not(isEmptyOrNullString())); + + dockerClient.startContainerCmd(container.getId()).exec(); + tmpContainers.add(container.getId()); + + ClientResponse response = dockerClient.copyFileFromContainerCmd(container.getId(), "/test").exec(); + assertTrue(response.getStatus() == 200 && response.hasEntity(), "The file was not copied from the container."); + } +} From 65d42253c2e66d7c9a83b734da709da340545a4d Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Thu, 31 Jul 2014 14:02:08 -0400 Subject: [PATCH 062/452] Swaps model toStrings with Commons ToStringBuilder This cuts down on some of the boilerplate code. Since we're already bringing Apache Commons Lang, we might as well use it. --- .../dockerjava/client/model/ChangeLog.java | 6 +-- .../dockerjava/client/model/Container.java | 34 ++++++---------- .../client/model/ContainerConfig.java | 20 ++-------- .../dockerjava/client/model/CopyConfig.java | 3 +- .../client/model/CreateContainerConfig.java | 39 +++++-------------- .../dockerjava/client/model/DriverStatus.java | 6 +-- .../dockerjava/client/model/HostConfig.java | 31 +++++---------- .../github/dockerjava/client/model/Image.java | 10 +---- .../github/dockerjava/client/model/Info.java | 24 ++++-------- .../github/dockerjava/client/model/Ports.java | 23 +++++------ .../dockerjava/client/model/SearchItem.java | 4 +- .../client/model/StartContainerConfig.java | 26 +++++-------- .../dockerjava/client/model/Version.java | 13 ++----- 13 files changed, 76 insertions(+), 163 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/model/ChangeLog.java b/src/main/java/com/github/dockerjava/client/model/ChangeLog.java index cc4c5ece..84005969 100644 --- a/src/main/java/com/github/dockerjava/client/model/ChangeLog.java +++ b/src/main/java/com/github/dockerjava/client/model/ChangeLog.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; /** * @@ -27,9 +28,6 @@ public int getKind() { @Override public String toString() { - return "ChangeLog{" + - "path='" + path + '\'' + - ", kind=" + kind + - '}'; + return ToStringBuilder.reflectionToString(this); } } diff --git a/src/main/java/com/github/dockerjava/client/model/Container.java b/src/main/java/com/github/dockerjava/client/model/Container.java index 11d79e67..d323c86d 100644 --- a/src/main/java/com/github/dockerjava/client/model/Container.java +++ b/src/main/java/com/github/dockerjava/client/model/Container.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; import java.util.Arrays; @@ -28,7 +29,7 @@ public class Container { @JsonProperty("Names") private String[] names; - @JsonProperty("Ports") + @JsonProperty("Ports") public Port[] ports; @JsonProperty("Status") @@ -65,17 +66,9 @@ public String[] getNames() { @Override public String toString() { - return "Container{" + - "id='" + id + '\'' + - ", command='" + command + '\'' + - ", image='" + image + '\'' + - ", created=" + created + - ", status='" + status + '\'' + - ", ports=" + Arrays.toString(ports) + - ", names=" + Arrays.toString(names) + - '}'; + return ToStringBuilder.reflectionToString(this); } - + @JsonIgnoreProperties(ignoreUnknown = true) public static class Port { @@ -87,34 +80,29 @@ public static class Port { @JsonProperty("PublicPort") private Integer publicPort; - + @JsonProperty("Type") private String type; - + public String getIp() { return ip; } - + public Integer getPrivatePort() { return privatePort; } - + public Integer getPublicPort() { return publicPort; } - + public String getType() { return type; } - + @Override public String toString() { - return "Port{" + - "IP='" + ip + '\'' + - ", privatePort='" + privatePort + '\'' + - ", publicPort='" + publicPort + '\'' + - ", type='" + type + '\'' + - '}'; + return ToStringBuilder.reflectionToString(this); } } } diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java index 7389169b..6bbb6eef 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java @@ -6,11 +6,12 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; /** - * + * * @author Konstantin Pelykh (kpelykh@gmail.com) - * + * */ @JsonIgnoreProperties(ignoreUnknown = true) public class ContainerConfig { @@ -179,19 +180,6 @@ public int[] getOnBuild() { @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) - + ", image='" + image + '\'' - + ", volumes=" + volumes - + '\'' + ", entrypoint=" + Arrays.toString(entrypoint) - + ", networkDisabled=" + networkDisabled + ", workingDir='" + workingDir + '\'' - + ", domainName='" + domainName + '\'' + ", onBuild='" - + Arrays.toString(onBuild) + '\'' + '}'; + return ToStringBuilder.reflectionToString(this); } } diff --git a/src/main/java/com/github/dockerjava/client/model/CopyConfig.java b/src/main/java/com/github/dockerjava/client/model/CopyConfig.java index 423cc336..90ab0657 100755 --- a/src/main/java/com/github/dockerjava/client/model/CopyConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/CopyConfig.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; /** * Configuration object for copy command. @@ -57,7 +58,7 @@ public void setHostPath(String hostPath) { @Override public String toString() { - return "{\"HostPath\":\"" + hostPath + "\", \"Resource\":\"" + resource + "\"}"; + return ToStringBuilder.reflectionToString(this); } } diff --git a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java index 2ba9c9eb..d8e00512 100644 --- a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java @@ -6,11 +6,12 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; /** * * @author Konstantin Pelykh (kpelykh@gmail.com) - * + * * "Hostname":"", "User":"", "Memory":0, @@ -37,7 +38,7 @@ "ExposedPorts":{ "22/tcp": {} } - * + * * */ public class CreateContainerConfig { @@ -62,12 +63,12 @@ public class CreateContainerConfig { @JsonProperty("WorkingDir") private String workingDir = ""; @JsonProperty("DisableNetwork") private boolean disableNetwork = false; @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts = new ExposedPorts(); - + public CreateContainerConfig withExposedPorts(ExposedPort[] exposedPorts) { this.exposedPorts = new ExposedPorts(exposedPorts); return this; } - + @JsonIgnore public ExposedPort[] getExposedPorts() { return exposedPorts.getExposedPorts(); @@ -85,7 +86,7 @@ public CreateContainerConfig withWorkingDir(String workingDir) { return this; } - + public String getHostName() { return hostName; } @@ -248,28 +249,8 @@ public CreateContainerConfig withVolumesFrom(String[] volumesFrom) { @Override public String toString() { - return "CreateContainerConfig{" + - "hostName='" + hostName + '\'' + - ", portSpecs=" + Arrays.toString(portSpecs) + - ", user='" + user + '\'' + - ", tty=" + tty + - ", stdinOpen=" + stdinOpen + - ", stdInOnce=" + stdInOnce + - ", memoryLimit=" + memoryLimit + - ", memorySwap=" + memorySwap + - ", attachStdin=" + attachStdin + - ", attachStdout=" + attachStdout + - ", attachStderr=" + attachStderr + - ", env=" + Arrays.toString(env) + - ", cmd=" + Arrays.toString(cmd) + - ", dns=" + Arrays.toString(dns) + - ", image='" + image + '\'' + - ", volumes=" + volumes + - ", volumesFrom='" + volumesFrom + '\'' + - ", disableNetwork=" + disableNetwork + - ", workingDir='" + workingDir + '\'' + - '}'; - } - - + return ToStringBuilder.reflectionToString(this); + } + + } diff --git a/src/main/java/com/github/dockerjava/client/model/DriverStatus.java b/src/main/java/com/github/dockerjava/client/model/DriverStatus.java index 187e35d5..4c2efe71 100644 --- a/src/main/java/com/github/dockerjava/client/model/DriverStatus.java +++ b/src/main/java/com/github/dockerjava/client/model/DriverStatus.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; /** * Created by ben on 12/12/13. @@ -25,9 +26,6 @@ public int getDirs() { @Override public String toString() { - return "DriverStatus{" + - "rootDir='" + rootDir + '\'' + - ", dirs=" + dirs + - '}'; + return ToStringBuilder.reflectionToString(this); } } diff --git a/src/main/java/com/github/dockerjava/client/model/HostConfig.java b/src/main/java/com/github/dockerjava/client/model/HostConfig.java index be78c1bd..4dc55e64 100644 --- a/src/main/java/com/github/dockerjava/client/model/HostConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/HostConfig.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; import java.util.Arrays; @@ -16,52 +17,40 @@ public class HostConfig { @JsonProperty("Binds") public String[] binds; - + @JsonProperty("LxcConf") public LxcConf[] lxcConf; - + @JsonProperty("PortBindings") public Ports portBindings; - + @JsonProperty("PublishAllPorts") public boolean publishAllPorts; - + @JsonProperty("Privileged") public boolean privileged; - + @JsonProperty("Dns") public String dns; - + @JsonProperty("VolumesFrom") public String volumesFrom; @JsonProperty("ContainerIDFile") public String containerIDFile; - + @JsonProperty("DnsSearch") public String dnsSearch; - + @JsonProperty("Links") public String[] links; @JsonProperty("NetworkMode") public String networkMode; - - @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 + - ", networkMode=" + networkMode + - ", dns='" + dns + '\'' + - '}'; + return ToStringBuilder.reflectionToString(this); } } diff --git a/src/main/java/com/github/dockerjava/client/model/Image.java b/src/main/java/com/github/dockerjava/client/model/Image.java index 2d6471eb..a75ebe55 100644 --- a/src/main/java/com/github/dockerjava/client/model/Image.java +++ b/src/main/java/com/github/dockerjava/client/model/Image.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; import java.util.Arrays; @@ -57,13 +58,6 @@ public long getVirtualSize() { @Override public String toString() { - return "Image{" + - "virtualSize=" + virtualSize + - ", id='" + id + '\'' + - ", repoTags=" + Arrays.toString(repoTags) + - ", parentId='" + parentId + '\'' + - ", created=" + created + - ", size=" + size + - '}'; + return ToStringBuilder.reflectionToString(this); } } diff --git a/src/main/java/com/github/dockerjava/client/model/Info.java b/src/main/java/com/github/dockerjava/client/model/Info.java index 442631d3..6e8386e6 100644 --- a/src/main/java/com/github/dockerjava/client/model/Info.java +++ b/src/main/java/com/github/dockerjava/client/model/Info.java @@ -5,14 +5,15 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.apache.commons.lang.builder.ToStringBuilder; import java.util.Arrays; import java.util.List; /** - * + * * @author Konstantin Pelykh (kpelykh@gmail.com) - * + * */ @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @JsonInclude(Include.NON_NULL) @@ -77,7 +78,7 @@ public boolean isDebug() { public int getContainers() { return containers; } - + public String getDriver() { return driver; } @@ -138,17 +139,8 @@ public String getExecutionDriver() { return 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 + '\'' + ", sockets='" + Arrays.asList(sockets) + '\'' - + ", memoryLimit=" + memoryLimit + ", nEventListener=" - + nEventListener + ", NFd=" + NFd + ", NGoroutines=" - + NGoroutines + ", swapLimit=" + swapLimit + '}'; - } + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } } diff --git a/src/main/java/com/github/dockerjava/client/model/Ports.java b/src/main/java/com/github/dockerjava/client/model/Ports.java index f4519a8d..735242ac 100644 --- a/src/main/java/com/github/dockerjava/client/model/Ports.java +++ b/src/main/java/com/github/dockerjava/client/model/Ports.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.node.NullNode; +import org.apache.commons.lang.builder.ToStringBuilder; @JsonDeserialize(using = Ports.Deserializer.class) @JsonSerialize(using = Ports.Serializer.class) @@ -28,8 +29,8 @@ public class Ports { private final Map ports = new HashMap(); public Ports() { } - - public Ports(ExposedPort exposedPort, Binding host) { + + public Ports(ExposedPort exposedPort, Binding host) { bind(exposedPort, host); } @@ -45,7 +46,7 @@ public String toString(){ public Map getBindings(){ return ports; } - + public static Binding Binding(String hostIp, int hostPort) { return new Binding(hostIp, hostPort); } @@ -65,11 +66,11 @@ public Binding(String hostIp, int hostPort) { this.hostIp = hostIp; this.hostPort = hostPort; } - + public Binding(int hostPort) { this("", hostPort); } - + public String getHostIp() { return hostIp; } @@ -78,15 +79,11 @@ public int getHostPort() { return hostPort; } - @Override public String toString() { - return "PortBinding{" + - "hostIp='" + hostIp + '\'' + - ", hostPort='" + hostPort + '\'' + - '}'; + return ToStringBuilder.reflectionToString(this); } - + @Override public boolean equals(Object obj) { if(obj instanceof Binding) { @@ -98,7 +95,7 @@ public boolean equals(Object obj) { return super.equals(obj); } } - + public static class Deserializer extends JsonDeserializer { @Override @@ -110,7 +107,7 @@ public Ports deserialize(JsonParser jsonParser, DeserializationContext deseriali for (Iterator> it = node.fields(); it.hasNext();) { Map.Entry field = it.next(); - if (!field.getValue().equals(NullNode.getInstance())) { + if (!field.getValue().equals(NullNode.getInstance())) { String hostIp = field.getValue().get(0).get("HostIp").textValue(); int hostPort = field.getValue().get(0).get("HostPort").asInt(); out.bind(ExposedPort.parse(field.getKey()), new Binding(hostIp, hostPort)); diff --git a/src/main/java/com/github/dockerjava/client/model/SearchItem.java b/src/main/java/com/github/dockerjava/client/model/SearchItem.java index 76dadab3..18c680bf 100644 --- a/src/main/java/com/github/dockerjava/client/model/SearchItem.java +++ b/src/main/java/com/github/dockerjava/client/model/SearchItem.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; /** * @@ -48,7 +49,6 @@ public String getDescription() { @Override public String toString() { - return "name='" + name + '\'' + - ", description='" + description + '\'' + '}'; + return ToStringBuilder.reflectionToString(this); } } diff --git a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java index ae8088f9..439f1744 100644 --- a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; /** * @@ -14,28 +15,28 @@ public class StartContainerConfig { @JsonProperty("Binds") private Binds binds = new Binds(); - + @JsonProperty("Links") private Links links = new Links(); @JsonProperty("LxcConf") private LxcConf[] lxcConf; - + @JsonProperty("PortBindings") private Ports portBindings; - + @JsonProperty("PublishAllPorts") private boolean publishAllPorts; - + @JsonProperty("Privileged") private boolean privileged; - + @JsonProperty("Dns") private String dns; - + @JsonProperty("VolumesFrom") private String volumesFrom; - + @JsonIgnore public Bind[] getBinds() { return binds.getBinds(); @@ -104,16 +105,9 @@ public void setVolumesFrom(String volumesFrom) { this.volumesFrom = volumesFrom; } - @Override + @Override public String toString() { - return "StartContainerConfig{" + - "binds=" + binds + - ", lxcConf=" + Arrays.toString(lxcConf) + - ", portBindings=" + portBindings + - ", privileged=" + privileged + - ", publishAllPorts=" + publishAllPorts + - ", dns='" + dns + '\'' + - '}'; + return ToStringBuilder.reflectionToString(this); } } diff --git a/src/main/java/com/github/dockerjava/client/model/Version.java b/src/main/java/com/github/dockerjava/client/model/Version.java index a01d6c61..8163802b 100644 --- a/src/main/java/com/github/dockerjava/client/model/Version.java +++ b/src/main/java/com/github/dockerjava/client/model/Version.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; /** * @@ -22,7 +23,7 @@ public class Version { @JsonProperty("GoVersion") private String goVersion; - + @JsonProperty("KernelVersion") private String kernelVersion; @@ -62,14 +63,6 @@ public String getApiVersion() { @Override public String toString() { - return "Version{" + - "version='" + version + '\'' + - ", gitCommit='" + gitCommit + '\'' + - ", goVersion='" + goVersion + '\'' + - ", kernelVersion='" + kernelVersion + '\'' + - ", arch='" + arch + '\'' + - ", operatingSystem='" + operatingSystem + '\'' + - ", apiVersion='" + apiVersion + '\'' + - '}'; + return ToStringBuilder.reflectionToString(this); } } From 442fa8b532ac467aaaaafb978c89d6b0e62984b8 Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Thu, 31 Jul 2014 14:07:58 -0400 Subject: [PATCH 063/452] Swaps responses' toStrings for Commons' ToStringBuilder Replacing more boilder-plate code with something that'll be easier to maintain. --- .../command/CreateContainerResponse.java | 6 +-- .../client/command/CreateImageResponse.java | 7 +--- .../command/InspectContainerResponse.java | 37 ++++--------------- .../client/command/InspectImageResponse.java | 18 ++------- 4 files changed, 14 insertions(+), 54 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java index c8a5870e..3eb9226f 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; import java.util.Arrays; @@ -37,9 +38,6 @@ public void setWarnings(String[] warnings) { @Override public String toString() { - return "CreateContainerResponse{" + - "id='" + id + '\'' + - ", warnings=" + Arrays.toString(warnings) + - '}'; + return ToStringBuilder.reflectionToString(this); } } diff --git a/src/main/java/com/github/dockerjava/client/command/CreateImageResponse.java b/src/main/java/com/github/dockerjava/client/command/CreateImageResponse.java index 3c657b9a..e3f40474 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateImageResponse.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateImageResponse.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; /** * Parse reponses from /images/create @@ -15,16 +16,12 @@ public class CreateImageResponse { @JsonProperty("status") private String id; - public String getId() { return id; } - @Override public String toString() { - return "CreateImageResponse{" + - "id='" + id + '\'' + - '}'; + return ToStringBuilder.reflectionToString(this); } } diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java index bdfb5ce5..352cc7cc 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java @@ -8,6 +8,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.client.model.*; +import org.apache.commons.lang.builder.ToStringBuilder; /** * @@ -187,16 +188,9 @@ public Ports getPorts() { } - @Override + @Override public String toString() { - return "NetworkSettings{" + - "ports=" + ports + - ", portMapping=" + portMapping + - ", bridge='" + bridge + '\'' + - ", gateway='" + gateway + '\'' + - ", ipPrefixLen=" + ipPrefixLen + - ", ipAddress='" + ipAddress + '\'' + - '}'; + return ToStringBuilder.reflectionToString(this); } } @@ -234,16 +228,9 @@ public String getFinishedAt() { return finishedAt; } - @Override + @Override public String toString() { - return "ContainerState{" + - "running=" + running + - ", paused=" + paused + - ", pid=" + pid + - ", exitCode=" + exitCode + - ", startedAt='" + startedAt + '\'' + - ", finishedAt='" + finishedAt + '\'' + - '}'; + return ToStringBuilder.reflectionToString(this); } } @@ -328,19 +315,9 @@ public String getNetworkMode() { return networkMode; } - @Override + @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 + - ", networkMode=" + networkMode + - ", dns='" + dns + '\'' + - '}'; + return ToStringBuilder.reflectionToString(this); } } diff --git a/src/main/java/com/github/dockerjava/client/command/InspectImageResponse.java b/src/main/java/com/github/dockerjava/client/command/InspectImageResponse.java index 82b634e4..9cc164fb 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectImageResponse.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectImageResponse.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.client.model.ContainerConfig; +import org.apache.commons.lang.builder.ToStringBuilder; /** * @@ -96,21 +97,8 @@ public String getOs() { return os; } - @Override + @Override public String toString() { - return "InspectImageResponse{" + - "id='" + id + '\'' + - ", parent='" + parent + '\'' + - ", created='" + created + '\'' + - ", container='" + container + '\'' + - ", containerConfig=" + containerConfig + - ", size=" + size + - ", dockerVersion='" + dockerVersion + '\'' + - ", config=" + config + - ", arch='" + arch + '\'' + - ", comment='" + comment + '\'' + - ", author='" + author + '\'' + - ", os='" + os + '\'' + - '}'; + return ToStringBuilder.reflectionToString(this); } } From 476dafc2ff3a0eda247dc684f8cdd20115b09d6c Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Fri, 1 Aug 2014 12:05:31 -0400 Subject: [PATCH 064/452] Moves CommitConfig into CommitCmd This is the first step toward simplifying or getting rid of the CommitConfig object. --- .../dockerjava/client/command/CommitCmd.java | 216 ++++++++++++++++-- .../dockerjava/client/model/CommitConfig.java | 201 ---------------- 2 files changed, 202 insertions(+), 215 deletions(-) delete mode 100644 src/main/java/com/github/dockerjava/client/model/CommitConfig.java diff --git a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java index 67bf5b0a..12116e7f 100644 --- a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java @@ -3,19 +3,20 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.dockerjava.client.model.ExposedPorts; +import com.github.dockerjava.client.model.Volumes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; -import com.github.dockerjava.client.model.CommitConfig; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; - /** * * Create a new image from a container's changes. Returns the new image ID. @@ -60,12 +61,6 @@ public boolean hasPauseEnabled() { return pause; } - public CommitCmd withCommitConfig(CommitConfig commitConfig) { - checkCommitConfig(commitConfig); - this.commitConfig = commitConfig; - return this; - } - public CommitCmd withAttachStderr(boolean attachStderr) { this.commitConfig.setAttachStderr(attachStderr); return this; @@ -144,13 +139,7 @@ public String toString() { .toString(); } - private void checkCommitConfig(CommitConfig commitConfig) { - Preconditions.checkNotNull(commitConfig, "CommitConfig was not specified"); - } - protected String impl() throws DockerException { - checkCommitConfig(commitConfig); - MultivaluedMap params = new MultivaluedMapImpl(); params.add("container", containerId); params.add("repo", repository); @@ -177,4 +166,203 @@ protected String impl() throws DockerException { throw new DockerException(e); } } + + /** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ + // TODO Simplify this + private static class CommitConfig { + + @JsonProperty("AttachStdin") + private boolean attachStdin; + + @JsonProperty("AttachStdout") + private boolean attachStdout; + + @JsonProperty("AttachStderr") + private boolean attachStderr; + + @JsonProperty("Cmd") + private String[] cmd; + + @JsonProperty("DisableNetwork") + private boolean disableNetwork; + + @JsonProperty("Env") + private String[] env; + + @JsonProperty("ExposedPorts") + private ExposedPorts exposedPorts; + + @JsonProperty("Hostname") + private String hostname; + + @JsonProperty("Memory") + private Integer memory; + + @JsonProperty("MemorySwap") + private Integer memorySwap; + + @JsonProperty("OpenStdin") + private boolean openStdin; + + @JsonProperty("PortSpecs") + private String[] portSpecs; + + @JsonProperty("StdinOnce") + private boolean stdinOnce; + + @JsonProperty("Tty") + private boolean tty; + + @JsonProperty("User") + private String user; + + @JsonProperty("Volumes") + private Volumes volumes; + + @JsonProperty("WorkingDir") + private String workingDir; + + 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[] getCmd() { + return cmd; + } + + public void setCmd(String[] cmd) { + this.cmd = cmd; + } + + public boolean isDisableNetwork() { + return disableNetwork; + } + + public void setDisableNetwork(boolean disableNetwork) { + this.disableNetwork = disableNetwork; + } + + public String[] getEnv() { + return env; + } + + public void setEnv(String[] env) { + this.env = env; + } + + public ExposedPorts getExposedPorts() { + return exposedPorts; + } + + public void setExposedPorts(ExposedPorts exposedPorts) { + this.exposedPorts = exposedPorts; + } + + public String getHostname() { + return hostname; + } + + public void setHostname(String hostname) { + this.hostname = hostname; + } + + public Integer getMemory() { + return memory; + } + + public void setMemory(Integer memory) { + this.memory = memory; + } + + public Integer getMemorySwap() { + return memorySwap; + } + + public void setMemorySwap(Integer memorySwap) { + this.memorySwap = memorySwap; + } + + public boolean isOpenStdin() { + return openStdin; + } + + public void setOpenStdin(boolean openStdin) { + this.openStdin = openStdin; + } + + public String[] getPortSpecs() { + return portSpecs; + } + + public void setPortSpecs(String[] portSpecs) { + this.portSpecs = portSpecs; + } + + public boolean isStdinOnce() { + return stdinOnce; + } + + public void setStdinOnce(boolean stdinOnce) { + this.stdinOnce = stdinOnce; + } + + public boolean isTty() { + return tty; + } + + public void setTty(boolean tty) { + this.tty = tty; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public Volumes getVolumes() { + return volumes; + } + + public void setVolumes(Volumes volumes) { + this.volumes = volumes; + } + + public String getWorkingDir() { + return workingDir; + } + + public void setWorkingDir(String workingDir) { + this.workingDir = workingDir; + } + + + + } } diff --git a/src/main/java/com/github/dockerjava/client/model/CommitConfig.java b/src/main/java/com/github/dockerjava/client/model/CommitConfig.java deleted file mode 100644 index 309570d9..00000000 --- a/src/main/java/com/github/dockerjava/client/model/CommitConfig.java +++ /dev/null @@ -1,201 +0,0 @@ -package com.github.dockerjava.client.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class CommitConfig { - - @JsonProperty("AttachStdin") - private boolean attachStdin; - - @JsonProperty("AttachStdout") - private boolean attachStdout; - - @JsonProperty("AttachStderr") - private boolean attachStderr; - - @JsonProperty("Cmd") - private String[] cmd; - - @JsonProperty("DisableNetwork") - private boolean disableNetwork; - - @JsonProperty("Env") - private String[] env; - - @JsonProperty("ExposedPorts") - private ExposedPorts exposedPorts; - - @JsonProperty("Hostname") - private String hostname; - - @JsonProperty("Memory") - private Integer memory; - - @JsonProperty("MemorySwap") - private Integer memorySwap; - - @JsonProperty("OpenStdin") - private boolean openStdin; - - @JsonProperty("PortSpecs") - private String[] portSpecs; - - @JsonProperty("StdinOnce") - private boolean stdinOnce; - - @JsonProperty("Tty") - private boolean tty; - - @JsonProperty("User") - private String user; - - @JsonProperty("Volumes") - private Volumes volumes; - - @JsonProperty("WorkingDir") - private String workingDir; - - 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[] getCmd() { - return cmd; - } - - public void setCmd(String[] cmd) { - this.cmd = cmd; - } - - public boolean isDisableNetwork() { - return disableNetwork; - } - - public void setDisableNetwork(boolean disableNetwork) { - this.disableNetwork = disableNetwork; - } - - public String[] getEnv() { - return env; - } - - public void setEnv(String[] env) { - this.env = env; - } - - public ExposedPorts getExposedPorts() { - return exposedPorts; - } - - public void setExposedPorts(ExposedPorts exposedPorts) { - this.exposedPorts = exposedPorts; - } - - public String getHostname() { - return hostname; - } - - public void setHostname(String hostname) { - this.hostname = hostname; - } - - public Integer getMemory() { - return memory; - } - - public void setMemory(Integer memory) { - this.memory = memory; - } - - public Integer getMemorySwap() { - return memorySwap; - } - - public void setMemorySwap(Integer memorySwap) { - this.memorySwap = memorySwap; - } - - public boolean isOpenStdin() { - return openStdin; - } - - public void setOpenStdin(boolean openStdin) { - this.openStdin = openStdin; - } - - public String[] getPortSpecs() { - return portSpecs; - } - - public void setPortSpecs(String[] portSpecs) { - this.portSpecs = portSpecs; - } - - public boolean isStdinOnce() { - return stdinOnce; - } - - public void setStdinOnce(boolean stdinOnce) { - this.stdinOnce = stdinOnce; - } - - public boolean isTty() { - return tty; - } - - public void setTty(boolean tty) { - this.tty = tty; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public Volumes getVolumes() { - return volumes; - } - - public void setVolumes(Volumes volumes) { - this.volumes = volumes; - } - - public String getWorkingDir() { - return workingDir; - } - - public void setWorkingDir(String workingDir) { - this.workingDir = workingDir; - } - - - -} From 8d572c6e9ce4e2aead81353ca09713e796bd10f7 Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Fri, 1 Aug 2014 17:09:06 -0400 Subject: [PATCH 065/452] Fixes a bug in the InfoCmdTest If you don't have any of your own containers, the InfoCmd integration test can fail. This commit makes sure there's at least one container present. --- .../client/command/InfoCmdTest.java | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java b/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java index a44e6872..5ef90cd4 100644 --- a/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java @@ -13,13 +13,17 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Info; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.isEmptyOrNullString; +import static org.hamcrest.Matchers.not; + public class InfoCmdTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { super.beforeTest(); } - + @AfterTest public void afterTest() { super.afterTest(); @@ -34,10 +38,23 @@ public void beforeMethod(Method method) { public void afterMethod(ITestResult result) { super.afterMethod(result); } - + @Test public void info() throws DockerException { - Info dockerInfo = dockerClient.infoCmd().exec(); + // Make sure that there is at least one container for the assertion + // TODO extract this into a shared method + CreateContainerResponse container = dockerClient.createContainerCmd("busybox") + .withName("docker-java-itest-info") + .withCmd("touch", "/test") + .exec(); + + LOG.info("Created container: {}", container); + assertThat(container.getId(), not(isEmptyOrNullString())); + + dockerClient.startContainerCmd(container.getId()).exec(); + tmpContainers.add(container.getId()); + + Info dockerInfo = dockerClient.infoCmd().exec(); LOG.info(dockerInfo.toString()); assertTrue(dockerInfo.toString().contains("containers")); From 14f911e5e2a4c5c562dde625abad21f9a1a7e692 Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Fri, 1 Aug 2014 17:10:48 -0400 Subject: [PATCH 066/452] Adds some TODOs --- src/main/java/com/github/dockerjava/client/DockerClient.java | 5 +++-- .../github/dockerjava/client/command/PushImageCmdTest.java | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index 09bd7017..dd39cd76 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -105,9 +105,9 @@ public DockerClient(Config config, CommandFactory cmdFactory) { if (config.isLoggingFilterEnabled()) client.addFilter(new SelectiveLoggingFilter()); - + WebResource webResource = client.resource(config.getUri()); - + if(config.getVersion() != null) { baseResource = webResource.path("v" + config.getVersion()); } else { @@ -326,6 +326,7 @@ public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { } + // TODO This is only being used by the test code for logging. Is it really necessary? /** * @return The output slurped into a string. */ diff --git a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java index 0e1dcf1b..d5e175e1 100644 --- a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java @@ -67,6 +67,7 @@ public void testPushLatest() throws Exception { dockerClient.removeImageCmd(imageId).exec(); + // TODO This can fail intermittently if run with other tests. assertThat(asString(dockerClient.pullImageCmd(username + "/busybox").exec()), not(containsString("404"))); tmpImgs.add(username + "/busybox"); From f8e3d3ad5847eae79367ec0ff5435c91d1b26318 Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Fri, 1 Aug 2014 17:31:01 -0400 Subject: [PATCH 067/452] Moves more Config objects into their assoc Cmds This effectively hides the config objects from the public API, as I expect they'll either go away or get simplified. --- .../command/CopyFileFromContainerCmd.java | 63 ++++- .../client/command/CreateContainerCmd.java | 256 +++++++++++++++++- .../client/command/StartContainerCmd.java | 114 +++++++- .../dockerjava/client/model/CopyConfig.java | 64 ----- .../client/model/CreateContainerConfig.java | 256 ------------------ .../client/model/StartContainerConfig.java | 113 -------- 6 files changed, 423 insertions(+), 443 deletions(-) delete mode 100755 src/main/java/com/github/dockerjava/client/model/CopyConfig.java delete mode 100644 src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java delete mode 100644 src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java diff --git a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java index 60bdf7e7..5b46fe00 100644 --- a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java @@ -2,11 +2,13 @@ import javax.ws.rs.core.MediaType; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.model.CopyConfig; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; @@ -82,4 +84,63 @@ protected ClientResponse impl() throws DockerException { } } } + + /** + * Configuration object for copy command. + * @author Victor Lyuboslavsky + */ + @JsonIgnoreProperties(ignoreUnknown = true) + private static 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 ToStringBuilder.reflectionToString(this); + } + + } } diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index a8456e3b..8934076d 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -3,14 +3,15 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.dockerjava.client.model.*; +import org.apache.commons.lang.builder.ToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; -import com.github.dockerjava.client.model.CreateContainerConfig; -import com.github.dockerjava.client.model.ExposedPort; -import com.github.dockerjava.client.model.Volume; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -35,7 +36,7 @@ public CreateContainerCmd(String image) { this.containerCreateConfig.withImage(image); } - public CreateContainerCmd(CreateContainerConfig config) { + private CreateContainerCmd(CreateContainerConfig config) { Preconditions.checkNotNull(config, "config was not specified"); this.containerCreateConfig = config; } @@ -125,4 +126,251 @@ protected CreateContainerResponse impl() { } } } + + /** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + * "Hostname":"", + "User":"", + "Memory":0, + "MemorySwap":0, + "AttachStdin":false, + "AttachStdout":true, + "AttachStderr":true, + "PortSpecs":null, + "Tty":false, + "OpenStdin":false, + "StdinOnce":false, + "Env":null, + "Cmd":[ + "date" + ], + "Dns":null, + "Image":"base", + "Volumes":{ + "/tmp": {} + }, + "VolumesFrom":"", + "WorkingDir":"", + "DisableNetwork": false, + "ExposedPorts":{ + "22/tcp": {} + } + * + * + */ + private static class CreateContainerConfig { + + @JsonProperty("Hostname") private String hostName = ""; + @JsonProperty("User") private String user = ""; + @JsonProperty("Memory") private long memoryLimit = 0; + @JsonProperty("MemorySwap") private long memorySwap = 0; + @JsonProperty("AttachStdin") private boolean attachStdin = false; + @JsonProperty("AttachStdout") private boolean attachStdout = false; + @JsonProperty("AttachStderr") private boolean attachStderr = false; + @JsonProperty("PortSpecs") private String[] portSpecs; + @JsonProperty("Tty") private boolean tty = false; + @JsonProperty("OpenStdin") private boolean stdinOpen = false; + @JsonProperty("StdinOnce") private boolean stdInOnce = false; + @JsonProperty("Env") private String[] env; + @JsonProperty("Cmd") private String[] cmd; + @JsonProperty("Dns") private String[] dns; + @JsonProperty("Image") private String image; + @JsonProperty("Volumes") private Volumes volumes = new Volumes(); + @JsonProperty("VolumesFrom") private String[] volumesFrom = new String[]{}; + @JsonProperty("WorkingDir") private String workingDir = ""; + @JsonProperty("DisableNetwork") private boolean disableNetwork = false; + @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts = new ExposedPorts(); + + public CreateContainerConfig withExposedPorts(ExposedPort[] exposedPorts) { + this.exposedPorts = new ExposedPorts(exposedPorts); + return this; + } + + @JsonIgnore + public ExposedPort[] getExposedPorts() { + return exposedPorts.getExposedPorts(); + } + + + public boolean isDisableNetwork() { + return disableNetwork; + } + + public String getWorkingDir() { return workingDir; } + + public CreateContainerConfig withWorkingDir(String workingDir) { + this.workingDir = workingDir; + return this; + } + + + public String getHostName() { + return hostName; + } + + public CreateContainerConfig withDisableNetwork(boolean disableNetwork) { + this.disableNetwork = disableNetwork; + return this; + } + + public CreateContainerConfig withHostName(String hostName) { + this.hostName = hostName; + return this; + } + + public String[] getPortSpecs() { + return portSpecs; + } + + public CreateContainerConfig withPortSpecs(String[] portSpecs) { + this.portSpecs = portSpecs; + return this; + } + + public String getUser() { + return user; + } + + public CreateContainerConfig withUser(String user) { + this.user = user; + return this; + } + + public boolean isTty() { + return tty; + } + + public CreateContainerConfig withTty(boolean tty) { + this.tty = tty; + return this; + } + + public boolean isStdinOpen() { + return stdinOpen; + } + + public CreateContainerConfig withStdinOpen(boolean stdinOpen) { + this.stdinOpen = stdinOpen; + return this; + } + + public boolean isStdInOnce() { + return stdInOnce; + } + + public CreateContainerConfig withStdInOnce(boolean stdInOnce) { + this.stdInOnce = stdInOnce; + return this; + } + + public long getMemoryLimit() { + return memoryLimit; + } + + public CreateContainerConfig withMemoryLimit(long memoryLimit) { + this.memoryLimit = memoryLimit; + return this; + } + + public long getMemorySwap() { + return memorySwap; + } + + public CreateContainerConfig withMemorySwap(long memorySwap) { + this.memorySwap = memorySwap; + return this; + } + + + public boolean isAttachStdin() { + return attachStdin; + } + + public CreateContainerConfig withAttachStdin(boolean attachStdin) { + this.attachStdin = attachStdin; + return this; + } + + public boolean isAttachStdout() { + return attachStdout; + } + + public CreateContainerConfig withAttachStdout(boolean attachStdout) { + this.attachStdout = attachStdout; + return this; + } + + public boolean isAttachStderr() { + return attachStderr; + } + + public CreateContainerConfig withAttachStderr(boolean attachStderr) { + this.attachStderr = attachStderr; + return this; + } + + public String[] getEnv() { + return env; + } + + public CreateContainerConfig withEnv(String[] env) { + this.env = env; + return this; + } + + public String[] getCmd() { + return cmd; + } + + public CreateContainerConfig withCmd(String[] cmd) { + this.cmd = cmd; + return this; + } + + public String[] getDns() { + return dns; + } + + public CreateContainerConfig withDns(String[] dns) { + this.dns = dns; + return this; + } + + public String getImage() { + return image; + } + + public CreateContainerConfig withImage(String image) { + this.image = image; + return this; + } + + @JsonIgnore + public Volume[] getVolumes() { + return volumes.getVolumes(); + } + + public CreateContainerConfig withVolumes(Volume[] volumes) { + this.volumes = new Volumes(volumes); + return this; + } + + public String[] getVolumesFrom() { + return volumesFrom; + } + + public CreateContainerConfig withVolumesFrom(String[] volumesFrom) { + this.volumesFrom = volumesFrom; + return this; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + + } } diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index 49901e93..f657c803 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -3,16 +3,15 @@ import javax.ws.rs.core.MediaType; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.dockerjava.client.model.*; +import org.apache.commons.lang.builder.ToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; -import com.github.dockerjava.client.model.Bind; -import com.github.dockerjava.client.model.Link; -import com.github.dockerjava.client.model.LxcConf; -import com.github.dockerjava.client.model.Ports; -import com.github.dockerjava.client.model.StartContainerConfig; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -128,4 +127,109 @@ protected Void impl() throws DockerException { return null; } + + /** + * + * @author Konstantin Pelykh (kpelykh@gmail.com) + * + */ + private static class StartContainerConfig { + + @JsonProperty("Binds") + private Binds binds = new Binds(); + + @JsonProperty("Links") + private Links links = new Links(); + + @JsonProperty("LxcConf") + private LxcConf[] lxcConf; + + @JsonProperty("PortBindings") + private Ports portBindings; + + @JsonProperty("PublishAllPorts") + private boolean publishAllPorts; + + @JsonProperty("Privileged") + private boolean privileged; + + @JsonProperty("Dns") + private String dns; + + @JsonProperty("VolumesFrom") + private String volumesFrom; + + @JsonIgnore + public Bind[] getBinds() { + return binds.getBinds(); + } + + @JsonIgnore + public void setBinds(Bind[] binds) { + this.binds = new Binds(binds); + } + + @JsonIgnore + public Link[] getLinks() { + return links.getLinks(); + } + + @JsonIgnore + public void setLinks(Link[] links) { + this.links = new Links(links); + } + + public LxcConf[] getLxcConf() { + return lxcConf; + } + + public void setLxcConf(LxcConf[] lxcConf) { + this.lxcConf = lxcConf; + } + + public Ports getPortBindings() { + return portBindings; + } + + public void setPortBindings(Ports portBindings) { + this.portBindings = portBindings; + } + + public boolean isPublishAllPorts() { + return publishAllPorts; + } + + public void setPublishAllPorts(boolean publishAllPorts) { + this.publishAllPorts = publishAllPorts; + } + + public boolean isPrivileged() { + return privileged; + } + + public void setPrivileged(boolean privileged) { + this.privileged = privileged; + } + + public String getDns() { + return dns; + } + + public void setDns(String dns) { + this.dns = dns; + } + + public String getVolumesFrom() { + return volumesFrom; + } + + public void setVolumesFrom(String volumesFrom) { + this.volumesFrom = volumesFrom; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + } } diff --git a/src/main/java/com/github/dockerjava/client/model/CopyConfig.java b/src/main/java/com/github/dockerjava/client/model/CopyConfig.java deleted file mode 100755 index 90ab0657..00000000 --- a/src/main/java/com/github/dockerjava/client/model/CopyConfig.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.github.dockerjava.client.model; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang.builder.ToStringBuilder; - -/** - * 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 ToStringBuilder.reflectionToString(this); - } - -} diff --git a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java deleted file mode 100644 index d8e00512..00000000 --- a/src/main/java/com/github/dockerjava/client/model/CreateContainerConfig.java +++ /dev/null @@ -1,256 +0,0 @@ -package com.github.dockerjava.client.model; - - -import java.util.Arrays; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang.builder.ToStringBuilder; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - * "Hostname":"", - "User":"", - "Memory":0, - "MemorySwap":0, - "AttachStdin":false, - "AttachStdout":true, - "AttachStderr":true, - "PortSpecs":null, - "Tty":false, - "OpenStdin":false, - "StdinOnce":false, - "Env":null, - "Cmd":[ - "date" - ], - "Dns":null, - "Image":"base", - "Volumes":{ - "/tmp": {} - }, - "VolumesFrom":"", - "WorkingDir":"", - "DisableNetwork": false, - "ExposedPorts":{ - "22/tcp": {} - } - * - * - */ -public class CreateContainerConfig { - - @JsonProperty("Hostname") private String hostName = ""; - @JsonProperty("User") private String user = ""; - @JsonProperty("Memory") private long memoryLimit = 0; - @JsonProperty("MemorySwap") private long memorySwap = 0; - @JsonProperty("AttachStdin") private boolean attachStdin = false; - @JsonProperty("AttachStdout") private boolean attachStdout = false; - @JsonProperty("AttachStderr") private boolean attachStderr = false; - @JsonProperty("PortSpecs") private String[] portSpecs; - @JsonProperty("Tty") private boolean tty = false; - @JsonProperty("OpenStdin") private boolean stdinOpen = false; - @JsonProperty("StdinOnce") private boolean stdInOnce = false; - @JsonProperty("Env") private String[] env; - @JsonProperty("Cmd") private String[] cmd; - @JsonProperty("Dns") private String[] dns; - @JsonProperty("Image") private String image; - @JsonProperty("Volumes") private Volumes volumes = new Volumes(); - @JsonProperty("VolumesFrom") private String[] volumesFrom = new String[]{}; - @JsonProperty("WorkingDir") private String workingDir = ""; - @JsonProperty("DisableNetwork") private boolean disableNetwork = false; - @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts = new ExposedPorts(); - - public CreateContainerConfig withExposedPorts(ExposedPort[] exposedPorts) { - this.exposedPorts = new ExposedPorts(exposedPorts); - return this; - } - - @JsonIgnore - public ExposedPort[] getExposedPorts() { - return exposedPorts.getExposedPorts(); - } - - - public boolean isDisableNetwork() { - return disableNetwork; - } - - public String getWorkingDir() { return workingDir; } - - public CreateContainerConfig withWorkingDir(String workingDir) { - this.workingDir = workingDir; - return this; - } - - - public String getHostName() { - return hostName; - } - - public CreateContainerConfig withDisableNetwork(boolean disableNetwork) { - this.disableNetwork = disableNetwork; - return this; - } - - public CreateContainerConfig withHostName(String hostName) { - this.hostName = hostName; - return this; - } - - public String[] getPortSpecs() { - return portSpecs; - } - - public CreateContainerConfig withPortSpecs(String[] portSpecs) { - this.portSpecs = portSpecs; - return this; - } - - public String getUser() { - return user; - } - - public CreateContainerConfig withUser(String user) { - this.user = user; - return this; - } - - public boolean isTty() { - return tty; - } - - public CreateContainerConfig withTty(boolean tty) { - this.tty = tty; - return this; - } - - public boolean isStdinOpen() { - return stdinOpen; - } - - public CreateContainerConfig withStdinOpen(boolean stdinOpen) { - this.stdinOpen = stdinOpen; - return this; - } - - public boolean isStdInOnce() { - return stdInOnce; - } - - public CreateContainerConfig withStdInOnce(boolean stdInOnce) { - this.stdInOnce = stdInOnce; - return this; - } - - public long getMemoryLimit() { - return memoryLimit; - } - - public CreateContainerConfig withMemoryLimit(long memoryLimit) { - this.memoryLimit = memoryLimit; - return this; - } - - public long getMemorySwap() { - return memorySwap; - } - - public CreateContainerConfig withMemorySwap(long memorySwap) { - this.memorySwap = memorySwap; - return this; - } - - - public boolean isAttachStdin() { - return attachStdin; - } - - public CreateContainerConfig withAttachStdin(boolean attachStdin) { - this.attachStdin = attachStdin; - return this; - } - - public boolean isAttachStdout() { - return attachStdout; - } - - public CreateContainerConfig withAttachStdout(boolean attachStdout) { - this.attachStdout = attachStdout; - return this; - } - - public boolean isAttachStderr() { - return attachStderr; - } - - public CreateContainerConfig withAttachStderr(boolean attachStderr) { - this.attachStderr = attachStderr; - return this; - } - - public String[] getEnv() { - return env; - } - - public CreateContainerConfig withEnv(String[] env) { - this.env = env; - return this; - } - - public String[] getCmd() { - return cmd; - } - - public CreateContainerConfig withCmd(String[] cmd) { - this.cmd = cmd; - return this; - } - - public String[] getDns() { - return dns; - } - - public CreateContainerConfig withDns(String[] dns) { - this.dns = dns; - return this; - } - - public String getImage() { - return image; - } - - public CreateContainerConfig withImage(String image) { - this.image = image; - return this; - } - - @JsonIgnore - public Volume[] getVolumes() { - return volumes.getVolumes(); - } - - public CreateContainerConfig withVolumes(Volume[] volumes) { - this.volumes = new Volumes(volumes); - return this; - } - - public String[] getVolumesFrom() { - return volumesFrom; - } - - public CreateContainerConfig withVolumesFrom(String[] volumesFrom) { - this.volumesFrom = volumesFrom; - return this; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - -} diff --git a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java deleted file mode 100644 index 439f1744..00000000 --- a/src/main/java/com/github/dockerjava/client/model/StartContainerConfig.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.github.dockerjava.client.model; - -import java.util.Arrays; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang.builder.ToStringBuilder; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -public class StartContainerConfig { - - @JsonProperty("Binds") - private Binds binds = new Binds(); - - @JsonProperty("Links") - private Links links = new Links(); - - @JsonProperty("LxcConf") - private LxcConf[] lxcConf; - - @JsonProperty("PortBindings") - private Ports portBindings; - - @JsonProperty("PublishAllPorts") - private boolean publishAllPorts; - - @JsonProperty("Privileged") - private boolean privileged; - - @JsonProperty("Dns") - private String dns; - - @JsonProperty("VolumesFrom") - private String volumesFrom; - - @JsonIgnore - public Bind[] getBinds() { - return binds.getBinds(); - } - - @JsonIgnore - public void setBinds(Bind[] binds) { - this.binds = new Binds(binds); - } - - @JsonIgnore - public Link[] getLinks() { - return links.getLinks(); - } - - @JsonIgnore - public void setLinks(Link[] links) { - this.links = new Links(links); - } - - public LxcConf[] getLxcConf() { - return lxcConf; - } - - public void setLxcConf(LxcConf[] lxcConf) { - this.lxcConf = lxcConf; - } - - public Ports getPortBindings() { - return portBindings; - } - - public void setPortBindings(Ports portBindings) { - this.portBindings = portBindings; - } - - public boolean isPublishAllPorts() { - return publishAllPorts; - } - - public void setPublishAllPorts(boolean publishAllPorts) { - this.publishAllPorts = publishAllPorts; - } - - public boolean isPrivileged() { - return privileged; - } - - public void setPrivileged(boolean privileged) { - this.privileged = privileged; - } - - public String getDns() { - return dns; - } - - public void setDns(String dns) { - this.dns = dns; - } - - public String getVolumesFrom() { - return volumesFrom; - } - - public void setVolumesFrom(String volumesFrom) { - this.volumesFrom = volumesFrom; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } -} - From 52c7d2abd22b168ad712de4f622ffab6ef31fbf8 Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Fri, 1 Aug 2014 17:36:02 -0400 Subject: [PATCH 068/452] Removes top-level HostConfig The HostConfig is already a sub-class of the InspectContainerResponse object. --- .../dockerjava/client/model/HostConfig.java | 56 ------------------- 1 file changed, 56 deletions(-) delete mode 100644 src/main/java/com/github/dockerjava/client/model/HostConfig.java diff --git a/src/main/java/com/github/dockerjava/client/model/HostConfig.java b/src/main/java/com/github/dockerjava/client/model/HostConfig.java deleted file mode 100644 index 4dc55e64..00000000 --- a/src/main/java/com/github/dockerjava/client/model/HostConfig.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.github.dockerjava.client.model; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang.builder.ToStringBuilder; - - -import java.util.Arrays; - -/** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class HostConfig { - - @JsonProperty("Binds") - public String[] binds; - - @JsonProperty("LxcConf") - public LxcConf[] lxcConf; - - @JsonProperty("PortBindings") - public Ports portBindings; - - @JsonProperty("PublishAllPorts") - public boolean publishAllPorts; - - @JsonProperty("Privileged") - public boolean privileged; - - @JsonProperty("Dns") - public String dns; - - @JsonProperty("VolumesFrom") - public String volumesFrom; - - @JsonProperty("ContainerIDFile") - public String containerIDFile; - - @JsonProperty("DnsSearch") - public String dnsSearch; - - @JsonProperty("Links") - public String[] links; - - @JsonProperty("NetworkMode") - public String networkMode; - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - -} From b7bbcfe73c71db806a1163b11bed00242854513a Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Fri, 1 Aug 2014 17:39:32 -0400 Subject: [PATCH 069/452] Renames Config to DockerClientConfig Having a slightly less generic class name is probably a good thing... --- .../dockerjava/client/DockerClient.java | 40 +++++++++---------- .../{Config.java => DockerClientConfig.java} | 10 ++--- 2 files changed, 25 insertions(+), 25 deletions(-) rename src/main/java/com/github/dockerjava/client/{Config.java => DockerClientConfig.java} (95%) diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index dd39cd76..411e0416 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -70,7 +70,7 @@ public class DockerClient implements Closeable { public DockerClient() { - this(Config.createDefaultConfigBuilder().build()); + this(DockerClientConfig.createDefaultConfigBuilder().build()); } public DockerClient(String serverUrl) { @@ -78,47 +78,47 @@ public DockerClient(String serverUrl) { } - private static Config configWithServerUrl(String serverUrl) { - return Config.createDefaultConfigBuilder() + private static DockerClientConfig configWithServerUrl(String serverUrl) { + return DockerClientConfig.createDefaultConfigBuilder() .withUri(serverUrl) .build(); } - public DockerClient(Config config) { - this(config, new DefaultCommandFactory()); + public DockerClient(DockerClientConfig dockerClientConfig) { + this(dockerClientConfig, new DefaultCommandFactory()); } - public DockerClient(Config config, CommandFactory cmdFactory) { + public DockerClient(DockerClientConfig dockerClientConfig, CommandFactory cmdFactory) { this.cmdFactory = cmdFactory; - HttpClient httpClient = getPoolingHttpClient(config); + HttpClient httpClient = getPoolingHttpClient(dockerClientConfig); ClientConfig clientConfig = new DefaultClientConfig(); client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, null, false), clientConfig); - if(config.getReadTimeout() != null) { - client.setReadTimeout(config.getReadTimeout()); + if(dockerClientConfig.getReadTimeout() != null) { + client.setReadTimeout(dockerClientConfig.getReadTimeout()); } client.addFilter(new JsonClientFilter()); - if (config.isLoggingFilterEnabled()) + if (dockerClientConfig.isLoggingFilterEnabled()) client.addFilter(new SelectiveLoggingFilter()); - WebResource webResource = client.resource(config.getUri()); + WebResource webResource = client.resource(dockerClientConfig.getUri()); - if(config.getVersion() != null) { - baseResource = webResource.path("v" + config.getVersion()); + if(dockerClientConfig.getVersion() != null) { + baseResource = webResource.path("v" + dockerClientConfig.getVersion()); } else { baseResource = webResource; } } - private HttpClient getPoolingHttpClient(Config config) { + private HttpClient getPoolingHttpClient(DockerClientConfig dockerClientConfig) { SchemeRegistry schemeRegistry = new SchemeRegistry(); - schemeRegistry.register(new Scheme("http", config.getUri().getPort(), + schemeRegistry.register(new Scheme("http", dockerClientConfig.getUri().getPort(), PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory .getSocketFactory())); @@ -162,11 +162,11 @@ public AuthConfig authConfig() throws DockerException { private static AuthConfig authConfigFromProperties() throws DockerException { final AuthConfig a = new AuthConfig(); - // TODO This should probably come from the Config used to create the DockerClient. - Config defaultConfig = Config.createDefaultConfigBuilder().build(); - a.setUsername(defaultConfig.getUsername()); - a.setPassword(defaultConfig.getPassword()); - a.setEmail(defaultConfig.getEmail()); + // TODO This should probably come from the DockerClientConfig used to create the DockerClient. + DockerClientConfig defaultDockerClientConfig = DockerClientConfig.createDefaultConfigBuilder().build(); + a.setUsername(defaultDockerClientConfig.getUsername()); + a.setPassword(defaultDockerClientConfig.getPassword()); + a.setEmail(defaultDockerClientConfig.getEmail()); if (a.getUsername() == null) { throw new IllegalStateException("username is null"); diff --git a/src/main/java/com/github/dockerjava/client/Config.java b/src/main/java/com/github/dockerjava/client/DockerClientConfig.java similarity index 95% rename from src/main/java/com/github/dockerjava/client/Config.java rename to src/main/java/com/github/dockerjava/client/DockerClientConfig.java index 08655917..2c9340fa 100644 --- a/src/main/java/com/github/dockerjava/client/Config.java +++ b/src/main/java/com/github/dockerjava/client/DockerClientConfig.java @@ -8,13 +8,13 @@ import com.google.common.base.Preconditions; -public class Config { +public class DockerClientConfig { private final URI uri; private final String version, username, password, email; private final Integer readTimeout; private final boolean loggingFilterEnabled; - private Config(DockerClientConfigBuilder builder) { + private DockerClientConfig(DockerClientConfigBuilder builder) { this.uri = builder.uri; this.version = builder.version; this.username = builder.username; @@ -55,7 +55,7 @@ public boolean isLoggingFilterEnabled() { public static Properties loadIncludedDockerProperties() { try { Properties p = new Properties(); - p.load(Config.class.getResourceAsStream("/docker.io.properties")); + p.load(DockerClientConfig.class.getResourceAsStream("/docker.io.properties")); return p; } catch (IOException e) { throw new DockerException(e); @@ -170,8 +170,8 @@ public final DockerClientConfigBuilder withLoggingFilter(boolean loggingFilterEn this.loggingFilterEnabled = loggingFilterEnabled; return this; } - public Config build() { - return new Config(this); + public DockerClientConfig build() { + return new DockerClientConfig(this); } } } From a2b68c54cf8a60dc1fa6551347ba08563aa1c5bd Mon Sep 17 00:00:00 2001 From: Matt Fulgo Date: Fri, 1 Aug 2014 18:44:40 -0400 Subject: [PATCH 070/452] Removes setCredentials from DockerClient DockerClient is now an immutable class. The only way to set credentials now is at construction of the DockerClient, using the DockerClientConfig object. --- .../dockerjava/client/DockerClient.java | 90 +++---------------- .../client/command/AuthCmdTest.java | 5 +- 2 files changed, 16 insertions(+), 79 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index 411e0416..f938edce 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client; +import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.*; @@ -16,36 +17,6 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; -import com.github.dockerjava.client.command.AbstrDockerCmd; -import com.github.dockerjava.client.command.AttachContainerCmd; -import com.github.dockerjava.client.command.AuthCmd; -import com.github.dockerjava.client.command.BuildImgCmd; -import com.github.dockerjava.client.command.CommitCmd; -import com.github.dockerjava.client.command.ContainerDiffCmd; -import com.github.dockerjava.client.command.CopyFileFromContainerCmd; -import com.github.dockerjava.client.command.CreateContainerCmd; -import com.github.dockerjava.client.command.CreateImageCmd; -import com.github.dockerjava.client.command.InfoCmd; -import com.github.dockerjava.client.command.InspectContainerCmd; -import com.github.dockerjava.client.command.InspectImageCmd; -import com.github.dockerjava.client.command.KillContainerCmd; -import com.github.dockerjava.client.command.ListContainersCmd; -import com.github.dockerjava.client.command.ListImagesCmd; -import com.github.dockerjava.client.command.LogContainerCmd; -import com.github.dockerjava.client.command.PingCmd; -import com.github.dockerjava.client.command.PullImageCmd; -import com.github.dockerjava.client.command.PushImageCmd; -import com.github.dockerjava.client.command.RemoveContainerCmd; -import com.github.dockerjava.client.command.RemoveImageCmd; -import com.github.dockerjava.client.command.RestartContainerCmd; -import com.github.dockerjava.client.command.SearchImagesCmd; -import com.github.dockerjava.client.command.StartContainerCmd; -import com.github.dockerjava.client.command.StopContainerCmd; -import com.github.dockerjava.client.command.TagImageCmd; -import com.github.dockerjava.client.command.TopContainerCmd; -import com.github.dockerjava.client.command.VersionCmd; -import com.github.dockerjava.client.command.WaitContainerCmd; - import com.github.dockerjava.client.model.AuthConfig; import com.github.dockerjava.client.utils.JsonClientFilter; @@ -62,12 +33,11 @@ */ public class DockerClient implements Closeable { - private Client client; + private final Client client; private final CommandFactory cmdFactory; private final WebResource baseResource; - private AuthConfig authConfig; - + private final DockerClientConfig dockerClientConfig; public DockerClient() { this(DockerClientConfig.createDefaultConfigBuilder().build()); @@ -77,20 +47,19 @@ public DockerClient(String serverUrl) { this(configWithServerUrl(serverUrl)); } - private static DockerClientConfig configWithServerUrl(String serverUrl) { return DockerClientConfig.createDefaultConfigBuilder() .withUri(serverUrl) .build(); } - public DockerClient(DockerClientConfig dockerClientConfig) { this(dockerClientConfig, new DefaultCommandFactory()); } public DockerClient(DockerClientConfig dockerClientConfig, CommandFactory cmdFactory) { this.cmdFactory = cmdFactory; + this.dockerClientConfig = dockerClientConfig; HttpClient httpClient = getPoolingHttpClient(dockerClientConfig); ClientConfig clientConfig = new DefaultClientConfig(); @@ -115,7 +84,6 @@ public DockerClient(DockerClientConfig dockerClientConfig, CommandFactory cmdFac } } - private HttpClient getPoolingHttpClient(DockerClientConfig dockerClientConfig) { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", dockerClientConfig.getUri().getPort(), @@ -129,56 +97,25 @@ private HttpClient getPoolingHttpClient(DockerClientConfig dockerClientConfig) { // Increase default max connection per route cm.setDefaultMaxPerRoute(1000); - return new DefaultHttpClient(cm); } - - 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); - } - public RES_T execute(AbstrDockerCmd command) throws DockerException { return command.withBaseResource(baseResource).exec(); } public AuthConfig authConfig() throws DockerException { - return authConfig != null ? authConfig : authConfigFromProperties(); - } - - private static AuthConfig authConfigFromProperties() throws DockerException { - final AuthConfig a = new AuthConfig(); - - // TODO This should probably come from the DockerClientConfig used to create the DockerClient. - DockerClientConfig defaultDockerClientConfig = DockerClientConfig.createDefaultConfigBuilder().build(); - a.setUsername(defaultDockerClientConfig.getUsername()); - a.setPassword(defaultDockerClientConfig.getPassword()); - a.setEmail(defaultDockerClientConfig.getEmail()); + checkNotNull(dockerClientConfig.getUsername(), "Configured username is null."); + checkNotNull(dockerClientConfig.getPassword(), "Configured password is null."); + checkNotNull(dockerClientConfig.getEmail(), "Configured email is null."); - 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; + AuthConfig authConfig = new AuthConfig(); + authConfig.setUsername(dockerClientConfig.getUsername()); + authConfig.setPassword(dockerClientConfig.getPassword()); + authConfig.setEmail(dockerClientConfig.getEmail()); + // TODO Make the registry address configurable + return authConfig; } /** @@ -325,7 +262,6 @@ public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { return cmdFactory.tagImageCmd(imageId, repository, tag).withBaseResource(baseResource); } - // TODO This is only being used by the test code for logging. Is it really necessary? /** * @return The output slurped into a string. diff --git a/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java b/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java index 4ccac663..608d8453 100644 --- a/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java @@ -1,6 +1,7 @@ package com.github.dockerjava.client.command; import com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.client.DockerClient; import com.github.dockerjava.client.DockerException; import com.sun.jersey.api.client.UniformInterfaceException; @@ -42,8 +43,8 @@ public void testAuth() throws Exception { public void testAuthInvalid() throws Exception { System.setProperty("docker.io.password", "garbage"); try { - dockerClient.authCmd().exec(); - fail(); + new DockerClient().authCmd().exec(); + fail("Expected a DockerException caused by a bad password."); } catch (DockerException e) { assertThat(e.getCause(), Matchers.instanceOf(UniformInterfaceException.class)); assertEquals(((UniformInterfaceException) e.getCause()).getResponse().getStatus(), 401); From c0330dc2d9d2223c4e997a18343bfc182fe402a6 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 2 Aug 2014 12:41:34 +0200 Subject: [PATCH 071/452] Fix issue #36 --- .../github/dockerjava/client/command/AttachContainerCmd.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java index 1b3acb97..84b54c36 100644 --- a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java @@ -124,7 +124,7 @@ protected ClientResponse impl() throws DockerException { try { LOGGER.trace("POST: {}", webResource); return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .post(ClientResponse.class, params); + .post(ClientResponse.class); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 400) { throw new DockerException("bad parameter"); From d6efb1bacf1abb6e11da1e2d9837d92a5d48d347 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 2 Aug 2014 13:56:00 +0200 Subject: [PATCH 072/452] Refactored request model classes into commands --- .../dockerjava/client/command/CommitCmd.java | 396 +++++++------- .../command/CopyFileFromContainerCmd.java | 82 +-- .../client/command/CreateContainerCmd.java | 509 +++++++----------- .../client/command/CreateImageCmd.java | 3 +- .../client/command/StartContainerCmd.java | 243 ++++----- 5 files changed, 515 insertions(+), 718 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java index 12116e7f..37b2e1ec 100644 --- a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java @@ -6,6 +6,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.client.model.ExposedPorts; import com.github.dockerjava.client.model.Volumes; + +import org.apache.commons.lang.builder.ToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,7 +32,57 @@ public class CommitCmd extends AbstrDockerCmd { private boolean pause = true; - private CommitConfig commitConfig = new CommitConfig(); + @JsonProperty("AttachStdin") + private boolean attachStdin; + + @JsonProperty("AttachStdout") + private boolean attachStdout; + + @JsonProperty("AttachStderr") + private boolean attachStderr; + + @JsonProperty("Cmd") + private String[] cmd; + + @JsonProperty("DisableNetwork") + private boolean disableNetwork; + + @JsonProperty("Env") + private String[] env; + + @JsonProperty("ExposedPorts") + private ExposedPorts exposedPorts; + + @JsonProperty("Hostname") + private String hostname; + + @JsonProperty("Memory") + private Integer memory; + + @JsonProperty("MemorySwap") + private Integer memorySwap; + + @JsonProperty("OpenStdin") + private boolean openStdin; + + @JsonProperty("PortSpecs") + private String[] portSpecs; + + @JsonProperty("StdinOnce") + private boolean stdinOnce; + + @JsonProperty("Tty") + private boolean tty; + + @JsonProperty("User") + private String user; + + @JsonProperty("Volumes") + private Volumes volumes; + + @JsonProperty("WorkingDir") + private String workingDir; + public CommitCmd(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); @@ -62,7 +114,7 @@ public boolean hasPauseEnabled() { } public CommitCmd withAttachStderr(boolean attachStderr) { - this.commitConfig.setAttachStderr(attachStderr); + this.attachStderr = attachStderr; return this; } @@ -71,7 +123,7 @@ public CommitCmd withAttachStderr() { } public CommitCmd withAttachStdin(boolean attachStdin) { - this.commitConfig.setAttachStdin(attachStdin); + this.attachStdin = attachStdin; return this; } @@ -80,7 +132,7 @@ public CommitCmd withAttachStdin() { } public CommitCmd withAttachStdout(boolean attachStdout) { - this.commitConfig.setAttachStdout(attachStdout); + this.attachStdout = attachStdout; return this; } @@ -90,12 +142,12 @@ public CommitCmd withAttachStdout() { public CommitCmd withCmd(String... cmd) { Preconditions.checkNotNull(cmd, "cmd was not specified"); - this.commitConfig.setCmd(cmd); + this.cmd = cmd; return this; } public CommitCmd withDisableNetwork(boolean disableNetwork) { - this.commitConfig.setDisableNetwork(disableNetwork); + this.disableNetwork = disableNetwork; return this; } @@ -127,10 +179,137 @@ public CommitCmd withPause(boolean pause) { this.pause = pause; return this; } + + public String[] getEnv() { + return env; + } + + public CommitCmd withEnv(String... env) { + Preconditions.checkNotNull(env, "env was not specified"); + this.env = env; + return this; + } + + public ExposedPorts getExposedPorts() { + return exposedPorts; + } + + public CommitCmd withExposedPorts(ExposedPorts exposedPorts) { + Preconditions.checkNotNull(exposedPorts, "exposedPorts was not specified"); + this.exposedPorts = exposedPorts; + return this; + } + + public String getHostname() { + return hostname; + } + + public CommitCmd withHostname(String hostname) { + Preconditions.checkNotNull(hostname, "hostname was not specified"); + this.hostname = hostname; + return this; + } + + public Integer getMemory() { + return memory; + } + + public CommitCmd withMemory(Integer memory) { + Preconditions.checkNotNull(memory, "memory was not specified"); + this.memory = memory; + return this; + } + + public Integer getMemorySwap() { + return memorySwap; + } + + public CommitCmd withMemorySwap(Integer memorySwap) { + Preconditions.checkNotNull(memorySwap, "memorySwap was not specified"); + this.memorySwap = memorySwap; + return this; + } + + public boolean isOpenStdin() { + return openStdin; + } + + public CommitCmd withOpenStdin(boolean openStdin) { + Preconditions.checkNotNull(openStdin, "openStdin was not specified"); + this.openStdin = openStdin; + return this; + } + + public String[] getPortSpecs() { + return portSpecs; + } + + public CommitCmd withPortSpecs(String... portSpecs) { + Preconditions.checkNotNull(portSpecs, "portSpecs was not specified"); + this.portSpecs = portSpecs; + return this; + } + + public boolean isStdinOnce() { + return stdinOnce; + } + + public CommitCmd withStdinOnce(boolean stdinOnce) { + this.stdinOnce = stdinOnce; + return this; + } + + public CommitCmd withStdinOnce() { + return withStdinOnce(true); + } + + public boolean isTty() { + return tty; + } + + public CommitCmd withTty(boolean tty) { + this.tty = tty; + return this; + } + + public CommitCmd withTty() { + return withTty(true); + } + + public String getUser() { + return user; + } + + public CommitCmd withUser(String user) { + Preconditions.checkNotNull(user, "user was not specified"); + this.user = user; + return this; + } + + public Volumes getVolumes() { + return volumes; + } + + public CommitCmd withVolumes(Volumes volumes) { + Preconditions.checkNotNull(volumes, "volumes was not specified"); + this.volumes = volumes; + return this; + } + + public String getWorkingDir() { + return workingDir; + } + + public CommitCmd withWorkingDir(String workingDir) { + Preconditions.checkNotNull(workingDir, "workingDir was not specified"); + this.workingDir = workingDir; + return this; + } + @Override public String toString() { - return new StringBuilder("commit ") + return new ToStringBuilder(this).append("commit ") .append(author != null ? "--author " + author + " " : "") .append(message != null ? "--message " + message + " " : "") .append(containerId) @@ -152,7 +331,7 @@ protected String impl() throws DockerException { try { LOGGER.trace("POST: {}", webResource); - ObjectNode objectNode = webResource.queryParams(params).accept("application/vnd.docker.raw-stream").type(MediaType.APPLICATION_JSON).post(ObjectNode.class, commitConfig); + ObjectNode objectNode = webResource.queryParams(params).accept("application/vnd.docker.raw-stream").type(MediaType.APPLICATION_JSON).post(ObjectNode.class, this); return objectNode.get("Id").asText(); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 404) { @@ -165,204 +344,5 @@ protected String impl() throws DockerException { } catch (Exception e) { throw new DockerException(e); } - } - - /** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ - // TODO Simplify this - private static class CommitConfig { - - @JsonProperty("AttachStdin") - private boolean attachStdin; - - @JsonProperty("AttachStdout") - private boolean attachStdout; - - @JsonProperty("AttachStderr") - private boolean attachStderr; - - @JsonProperty("Cmd") - private String[] cmd; - - @JsonProperty("DisableNetwork") - private boolean disableNetwork; - - @JsonProperty("Env") - private String[] env; - - @JsonProperty("ExposedPorts") - private ExposedPorts exposedPorts; - - @JsonProperty("Hostname") - private String hostname; - - @JsonProperty("Memory") - private Integer memory; - - @JsonProperty("MemorySwap") - private Integer memorySwap; - - @JsonProperty("OpenStdin") - private boolean openStdin; - - @JsonProperty("PortSpecs") - private String[] portSpecs; - - @JsonProperty("StdinOnce") - private boolean stdinOnce; - - @JsonProperty("Tty") - private boolean tty; - - @JsonProperty("User") - private String user; - - @JsonProperty("Volumes") - private Volumes volumes; - - @JsonProperty("WorkingDir") - private String workingDir; - - 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[] getCmd() { - return cmd; - } - - public void setCmd(String[] cmd) { - this.cmd = cmd; - } - - public boolean isDisableNetwork() { - return disableNetwork; - } - - public void setDisableNetwork(boolean disableNetwork) { - this.disableNetwork = disableNetwork; - } - - public String[] getEnv() { - return env; - } - - public void setEnv(String[] env) { - this.env = env; - } - - public ExposedPorts getExposedPorts() { - return exposedPorts; - } - - public void setExposedPorts(ExposedPorts exposedPorts) { - this.exposedPorts = exposedPorts; - } - - public String getHostname() { - return hostname; - } - - public void setHostname(String hostname) { - this.hostname = hostname; - } - - public Integer getMemory() { - return memory; - } - - public void setMemory(Integer memory) { - this.memory = memory; - } - - public Integer getMemorySwap() { - return memorySwap; - } - - public void setMemorySwap(Integer memorySwap) { - this.memorySwap = memorySwap; - } - - public boolean isOpenStdin() { - return openStdin; - } - - public void setOpenStdin(boolean openStdin) { - this.openStdin = openStdin; - } - - public String[] getPortSpecs() { - return portSpecs; - } - - public void setPortSpecs(String[] portSpecs) { - this.portSpecs = portSpecs; - } - - public boolean isStdinOnce() { - return stdinOnce; - } - - public void setStdinOnce(boolean stdinOnce) { - this.stdinOnce = stdinOnce; - } - - public boolean isTty() { - return tty; - } - - public void setTty(boolean tty) { - this.tty = tty; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public Volumes getVolumes() { - return volumes; - } - - public void setVolumes(Volumes volumes) { - this.volumes = volumes; - } - - public String getWorkingDir() { - return workingDir; - } - - public void setWorkingDir(String workingDir) { - this.workingDir = workingDir; - } - - - - } + } } diff --git a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java index 5b46fe00..c9523927 100644 --- a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java @@ -2,7 +2,6 @@ import javax.ws.rs.core.MediaType; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang.builder.ToStringBuilder; import org.slf4j.Logger; @@ -23,7 +22,13 @@ public class CopyFileFromContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(CreateContainerCmd.class); - - private CreateContainerConfig containerCreateConfig; + private String name; - + + @JsonProperty("Hostname") private String hostName = ""; + @JsonProperty("User") private String user = ""; + @JsonProperty("Memory") private long memoryLimit = 0; + @JsonProperty("MemorySwap") private long memorySwap = 0; + @JsonProperty("AttachStdin") private boolean attachStdin = false; + @JsonProperty("AttachStdout") private boolean attachStdout = false; + @JsonProperty("AttachStderr") private boolean attachStderr = false; + @JsonProperty("PortSpecs") private String[] portSpecs; + @JsonProperty("Tty") private boolean tty = false; + @JsonProperty("OpenStdin") private boolean stdinOpen = false; + @JsonProperty("StdinOnce") private boolean stdInOnce = false; + @JsonProperty("Env") private String[] env; + @JsonProperty("Cmd") private String[] cmd; + @JsonProperty("Dns") private String[] dns; + @JsonProperty("Image") private String image; + @JsonProperty("Volumes") private Volumes volumes = new Volumes(); + @JsonProperty("VolumesFrom") private String[] volumesFrom = new String[]{}; + @JsonProperty("WorkingDir") private String workingDir = ""; + @JsonProperty("DisableNetwork") private boolean disableNetwork = false; + @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts = new ExposedPorts(); + public CreateContainerCmd(String image) { - this(new CreateContainerConfig()); Preconditions.checkNotNull(image, "image was not specified"); - this.containerCreateConfig.withImage(image); + withImage(image); } - private CreateContainerCmd(CreateContainerConfig config) { - Preconditions.checkNotNull(config, "config was not specified"); - this.containerCreateConfig = config; - } + public CreateContainerCmd withName(String name) { + Preconditions.checkNotNull(name, "name was not specified"); + this.name = name; + return this; + } public String getName() { return name; } - public CreateContainerCmd withImage(String image) { - Preconditions.checkNotNull(image, "image was not specified"); - this.containerCreateConfig.withImage(image); - return this; - } + public CreateContainerCmd withExposedPorts(ExposedPort... exposedPorts) { + this.exposedPorts = new ExposedPorts(exposedPorts); + return this; + } - public CreateContainerCmd withCmd(String... cmd) { - Preconditions.checkNotNull(cmd, "cmd was not specified"); - this.containerCreateConfig.withCmd(cmd); - return this; - } + @JsonIgnore + public ExposedPort[] getExposedPorts() { + return exposedPorts.getExposedPorts(); + } - public CreateContainerCmd withVolumes(Volume... volumes) { - Preconditions.checkNotNull(volumes, "volumes was not specified"); - this.containerCreateConfig.withVolumes(volumes); - return this; - } - public CreateContainerCmd withVolumesFrom(String... volumesFrom) { - Preconditions.checkNotNull(volumesFrom, "volumes was not specified"); - this.containerCreateConfig.withVolumesFrom(volumesFrom); - return this; - } + public boolean isDisableNetwork() { + return disableNetwork; + } - public CreateContainerCmd withTTY(boolean tty) { - this.containerCreateConfig.withTty(tty); - return this; - } - - public CreateContainerCmd withEnv(String... env) { - Preconditions.checkNotNull(env, "env was not specified"); - this.containerCreateConfig.withEnv(env); - return this; + public String getWorkingDir() { + return workingDir; + } + + public CreateContainerCmd withWorkingDir(String workingDir) { + this.workingDir = workingDir; + return this; + } + + + public String getHostName() { + return hostName; + } + + public CreateContainerCmd withDisableNetwork(boolean disableNetwork) { + this.disableNetwork = disableNetwork; + return this; } public CreateContainerCmd withHostName(String hostName) { - Preconditions.checkNotNull(hostName, "hostName was not specified"); - this.containerCreateConfig.withHostName(hostName); - return this; + this.hostName = hostName; + return this; } - public CreateContainerCmd withName(String name) { - Preconditions.checkNotNull(name, "name was not specified"); - this.name = name; - return this; - } + public String[] getPortSpecs() { + return portSpecs; + } - public CreateContainerCmd withExposedPorts(ExposedPort... exposedPorts) { - Preconditions.checkNotNull(exposedPorts, "exposedPorts was not specified"); + public CreateContainerCmd withPortSpecs(String... portSpecs) { + this.portSpecs = portSpecs; + return this; + } - this.containerCreateConfig.withExposedPorts(exposedPorts); - return this; - } + public String getUser() { + return user; + } + + public CreateContainerCmd withUser(String user) { + this.user = user; + return this; + } + + public boolean isTty() { + return tty; + } + + public CreateContainerCmd withTty(boolean tty) { + this.tty = tty; + return this; + } + + public boolean isStdinOpen() { + return stdinOpen; + } + + public CreateContainerCmd withStdinOpen(boolean stdinOpen) { + this.stdinOpen = stdinOpen; + return this; + } + + public boolean isStdInOnce() { + return stdInOnce; + } + + public CreateContainerCmd withStdInOnce(boolean stdInOnce) { + this.stdInOnce = stdInOnce; + return this; + } + + public long getMemoryLimit() { + return memoryLimit; + } + + public CreateContainerCmd withMemoryLimit(long memoryLimit) { + this.memoryLimit = memoryLimit; + return this; + } + + public long getMemorySwap() { + return memorySwap; + } + + public CreateContainerCmd withMemorySwap(long memorySwap) { + this.memorySwap = memorySwap; + return this; + } + + + public boolean isAttachStdin() { + return attachStdin; + } + + public CreateContainerCmd withAttachStdin(boolean attachStdin) { + this.attachStdin = attachStdin; + return this; + } + + public boolean isAttachStdout() { + return attachStdout; + } + + public CreateContainerCmd withAttachStdout(boolean attachStdout) { + this.attachStdout = attachStdout; + return this; + } + + public boolean isAttachStderr() { + return attachStderr; + } + + public CreateContainerCmd withAttachStderr(boolean attachStderr) { + this.attachStderr = attachStderr; + return this; + } + + public String[] getEnv() { + return env; + } + + public CreateContainerCmd withEnv(String... env) { + this.env = env; + return this; + } + + public String[] getCmd() { + return cmd; + } + + public CreateContainerCmd withCmd(String... cmd) { + this.cmd = cmd; + return this; + } + + public String[] getDns() { + return dns; + } + + public CreateContainerCmd withDns(String... dns) { + this.dns = dns; + return this; + } + + public String getImage() { + return image; + } + + public CreateContainerCmd withImage(String image) { + this.image = image; + return this; + } + + @JsonIgnore + public Volume[] getVolumes() { + return volumes.getVolumes(); + } + + public CreateContainerCmd withVolumes(Volume... volumes) { + this.volumes = new Volumes(volumes); + return this; + } + + public String[] getVolumesFrom() { + return volumesFrom; + } + + public CreateContainerCmd withVolumesFrom(String... volumesFrom) { + this.volumesFrom = volumesFrom; + return this; + } @Override public String toString() { - return new StringBuilder("create container ") + return new ToStringBuilder(this).append("create container ") .append(name != null ? "name=" + name + " " : "") - .append(containerCreateConfig) + .append(this) .toString(); } @@ -118,10 +269,10 @@ protected CreateContainerResponse impl() { LOGGER.trace("POST: {} ", webResource); return webResource.accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) - .post(CreateContainerResponse.class, containerCreateConfig); + .post(CreateContainerResponse.class, this); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 404) { - throw new NotFoundException(String.format("%s is an unrecognized image. Please pull the image first.", containerCreateConfig.getImage())); + throw new NotFoundException(String.format("%s is an unrecognized image. Please pull the image first.", getImage())); } else if (exception.getResponse().getStatus() == 406) { throw new DockerException("impossible to attach (container not running)"); } else if (exception.getResponse().getStatus() == 500) { @@ -132,250 +283,4 @@ protected CreateContainerResponse impl() { } } - /** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - * "Hostname":"", - "User":"", - "Memory":0, - "MemorySwap":0, - "AttachStdin":false, - "AttachStdout":true, - "AttachStderr":true, - "PortSpecs":null, - "Tty":false, - "OpenStdin":false, - "StdinOnce":false, - "Env":null, - "Cmd":[ - "date" - ], - "Dns":null, - "Image":"base", - "Volumes":{ - "/tmp": {} - }, - "VolumesFrom":"", - "WorkingDir":"", - "DisableNetwork": false, - "ExposedPorts":{ - "22/tcp": {} - } - * - * - */ - private static class CreateContainerConfig { - - @JsonProperty("Hostname") private String hostName = ""; - @JsonProperty("User") private String user = ""; - @JsonProperty("Memory") private long memoryLimit = 0; - @JsonProperty("MemorySwap") private long memorySwap = 0; - @JsonProperty("AttachStdin") private boolean attachStdin = false; - @JsonProperty("AttachStdout") private boolean attachStdout = false; - @JsonProperty("AttachStderr") private boolean attachStderr = false; - @JsonProperty("PortSpecs") private String[] portSpecs; - @JsonProperty("Tty") private boolean tty = false; - @JsonProperty("OpenStdin") private boolean stdinOpen = false; - @JsonProperty("StdinOnce") private boolean stdInOnce = false; - @JsonProperty("Env") private String[] env; - @JsonProperty("Cmd") private String[] cmd; - @JsonProperty("Dns") private String[] dns; - @JsonProperty("Image") private String image; - @JsonProperty("Volumes") private Volumes volumes = new Volumes(); - @JsonProperty("VolumesFrom") private String[] volumesFrom = new String[]{}; - @JsonProperty("WorkingDir") private String workingDir = ""; - @JsonProperty("DisableNetwork") private boolean disableNetwork = false; - @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts = new ExposedPorts(); - - public CreateContainerConfig withExposedPorts(ExposedPort[] exposedPorts) { - this.exposedPorts = new ExposedPorts(exposedPorts); - return this; - } - - @JsonIgnore - public ExposedPort[] getExposedPorts() { - return exposedPorts.getExposedPorts(); - } - - - public boolean isDisableNetwork() { - return disableNetwork; - } - - public String getWorkingDir() { return workingDir; } - - public CreateContainerConfig withWorkingDir(String workingDir) { - this.workingDir = workingDir; - return this; - } - - - public String getHostName() { - return hostName; - } - - public CreateContainerConfig withDisableNetwork(boolean disableNetwork) { - this.disableNetwork = disableNetwork; - return this; - } - - public CreateContainerConfig withHostName(String hostName) { - this.hostName = hostName; - return this; - } - - public String[] getPortSpecs() { - return portSpecs; - } - - public CreateContainerConfig withPortSpecs(String[] portSpecs) { - this.portSpecs = portSpecs; - return this; - } - - public String getUser() { - return user; - } - - public CreateContainerConfig withUser(String user) { - this.user = user; - return this; - } - - public boolean isTty() { - return tty; - } - - public CreateContainerConfig withTty(boolean tty) { - this.tty = tty; - return this; - } - - public boolean isStdinOpen() { - return stdinOpen; - } - - public CreateContainerConfig withStdinOpen(boolean stdinOpen) { - this.stdinOpen = stdinOpen; - return this; - } - - public boolean isStdInOnce() { - return stdInOnce; - } - - public CreateContainerConfig withStdInOnce(boolean stdInOnce) { - this.stdInOnce = stdInOnce; - return this; - } - - public long getMemoryLimit() { - return memoryLimit; - } - - public CreateContainerConfig withMemoryLimit(long memoryLimit) { - this.memoryLimit = memoryLimit; - return this; - } - - public long getMemorySwap() { - return memorySwap; - } - - public CreateContainerConfig withMemorySwap(long memorySwap) { - this.memorySwap = memorySwap; - return this; - } - - - public boolean isAttachStdin() { - return attachStdin; - } - - public CreateContainerConfig withAttachStdin(boolean attachStdin) { - this.attachStdin = attachStdin; - return this; - } - - public boolean isAttachStdout() { - return attachStdout; - } - - public CreateContainerConfig withAttachStdout(boolean attachStdout) { - this.attachStdout = attachStdout; - return this; - } - - public boolean isAttachStderr() { - return attachStderr; - } - - public CreateContainerConfig withAttachStderr(boolean attachStderr) { - this.attachStderr = attachStderr; - return this; - } - - public String[] getEnv() { - return env; - } - - public CreateContainerConfig withEnv(String[] env) { - this.env = env; - return this; - } - - public String[] getCmd() { - return cmd; - } - - public CreateContainerConfig withCmd(String[] cmd) { - this.cmd = cmd; - return this; - } - - public String[] getDns() { - return dns; - } - - public CreateContainerConfig withDns(String[] dns) { - this.dns = dns; - return this; - } - - public String getImage() { - return image; - } - - public CreateContainerConfig withImage(String image) { - this.image = image; - return this; - } - - @JsonIgnore - public Volume[] getVolumes() { - return volumes.getVolumes(); - } - - public CreateContainerConfig withVolumes(Volume[] volumes) { - this.volumes = new Volumes(volumes); - return this; - } - - public String[] getVolumesFrom() { - return volumesFrom; - } - - public CreateContainerConfig withVolumesFrom(String[] volumesFrom) { - this.volumesFrom = volumesFrom; - return this; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - - } -} +} diff --git a/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java index 1254f63e..776cf94f 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java @@ -5,6 +5,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; +import org.apache.commons.lang.builder.ToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -71,7 +72,7 @@ public CreateImageCmd withTag(String tag) { @Override public String toString() { - return new StringBuilder("import - ") + return new ToStringBuilder(this).append("import - ") .append(repository != null ? repository + ":" : "") .append(tag != null ? tag : "") .toString(); diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index f657c803..b116d8da 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -1,4 +1,3 @@ - package com.github.dockerjava.client.command; import javax.ws.rs.core.MediaType; @@ -22,100 +21,159 @@ */ public class StartContainerCmd extends AbstrDockerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(StartContainerCmd.class); + private static final Logger LOGGER = LoggerFactory + .getLogger(StartContainerCmd.class); private String containerId; - private StartContainerConfig startContainerConfig; + @JsonProperty("Binds") + private Binds binds = new Binds(); + + @JsonProperty("Links") + private Links links = new Links(); + + @JsonProperty("LxcConf") + private LxcConf[] lxcConf; + + @JsonProperty("PortBindings") + private Ports portBindings; + + @JsonProperty("PublishAllPorts") + private boolean publishAllPorts; + + @JsonProperty("Privileged") + private boolean privileged; + + @JsonProperty("Dns") + private String dns; + @JsonProperty("VolumesFrom") + private String volumesFrom; + public StartContainerCmd(String containerId) { - startContainerConfig = new StartContainerConfig(); withContainerId(containerId); } - public String getContainerId() { - return containerId; - } + @JsonIgnore + public Bind[] getBinds() { + return binds.getBinds(); + } + + @JsonIgnore + public Link[] getLinks() { + return links.getLinks(); + } + + public LxcConf[] getLxcConf() { + return lxcConf; + } + + public Ports getPortBindings() { + return portBindings; + } - public StartContainerCmd withBinds(Bind... binds) { - startContainerConfig.setBinds(binds); + public boolean isPublishAllPorts() { + return publishAllPorts; + } + + public boolean isPrivileged() { + return privileged; + } + + public String getDns() { + return dns; + } + + public String getVolumesFrom() { + return volumesFrom; + } + + + public String getContainerId() { + return containerId; + } + + @JsonIgnore + public StartContainerCmd withBinds(Bind... binds) { + Preconditions.checkNotNull(binds, "binds was not specified"); + this.binds = new Binds(binds); return this; } - public StartContainerCmd withLinks(final Link... links) - { - startContainerConfig.setLinks(links); + @JsonIgnore + public StartContainerCmd withLinks(Link... links) { + Preconditions.checkNotNull(links, "links was not specified"); + this.links = new Links(links); return this; } - public StartContainerCmd withLxcConf(final LxcConf[] lxcConf) - { - startContainerConfig.setLxcConf(lxcConf); + public StartContainerCmd withLxcConf(LxcConf... lxcConf) { + Preconditions.checkNotNull(lxcConf, "lxcConf was not specified"); + this.lxcConf = lxcConf; return this; } public StartContainerCmd withPortBindings(Ports portBindings) { - startContainerConfig.setPortBindings(portBindings); + Preconditions.checkNotNull(portBindings, + "portBindings was not specified"); + this.portBindings = portBindings; return this; } public StartContainerCmd withPrivileged(boolean privileged) { - startContainerConfig.setPrivileged(privileged); + this.privileged = privileged; return this; } public StartContainerCmd withPublishAllPorts(boolean publishAllPorts) { - startContainerConfig.setPublishAllPorts(publishAllPorts); + this.publishAllPorts = publishAllPorts; return this; } public StartContainerCmd withDns(String dns) { - startContainerConfig.setDns(dns); + Preconditions.checkNotNull(dns, "dns was not specified"); + this.dns = dns; return this; } - public StartContainerCmd withVolumesFrom(String volumesFrom) { - startContainerConfig.setVolumesFrom(volumesFrom); + Preconditions + .checkNotNull(volumesFrom, "volumesFrom was not specified"); + this.volumesFrom = volumesFrom; return this; } public StartContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + Preconditions + .checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - @Override - public String toString() { - return new StringBuilder("run ") - .append(containerId) - .append(" using ") - .append(startContainerConfig) - .toString(); - } + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this).toString(); + } protected Void impl() throws DockerException { - WebResource webResource = baseResource.path(String.format("/containers/%s/start", containerId)); + WebResource webResource = baseResource.path(String.format( + "/containers/%s/start", containerId)); try { LOGGER.trace("POST: {}", webResource); Builder builder = webResource.accept(MediaType.APPLICATION_JSON); - if (startContainerConfig != null) { - builder.type(MediaType.APPLICATION_JSON).post(startContainerConfig); - } else { - builder.post((StartContainerConfig) null); - } + builder.type(MediaType.APPLICATION_JSON).post(this); } catch (UniformInterfaceException exception) { if (exception.getResponse().getStatus() == 404) { - throw new NotFoundException(String.format("No such container %s", containerId)); - } else if(exception.getResponse().getStatus() == 304) { - //no error + throw new NotFoundException(String.format( + "No such container %s", containerId)); + } else if (exception.getResponse().getStatus() == 304) { + // no error LOGGER.warn("Container already started {}", containerId); } else if (exception.getResponse().getStatus() == 204) { - //no error + // no error LOGGER.trace("Successfully started container {}", containerId); } else if (exception.getResponse().getStatus() == 500) { LOGGER.error("", exception); @@ -128,108 +186,5 @@ protected Void impl() throws DockerException { return null; } - /** - * - * @author Konstantin Pelykh (kpelykh@gmail.com) - * - */ - private static class StartContainerConfig { - - @JsonProperty("Binds") - private Binds binds = new Binds(); - - @JsonProperty("Links") - private Links links = new Links(); - - @JsonProperty("LxcConf") - private LxcConf[] lxcConf; - - @JsonProperty("PortBindings") - private Ports portBindings; - - @JsonProperty("PublishAllPorts") - private boolean publishAllPorts; - - @JsonProperty("Privileged") - private boolean privileged; - - @JsonProperty("Dns") - private String dns; - - @JsonProperty("VolumesFrom") - private String volumesFrom; - - @JsonIgnore - public Bind[] getBinds() { - return binds.getBinds(); - } - - @JsonIgnore - public void setBinds(Bind[] binds) { - this.binds = new Binds(binds); - } - - @JsonIgnore - public Link[] getLinks() { - return links.getLinks(); - } - - @JsonIgnore - public void setLinks(Link[] links) { - this.links = new Links(links); - } - - public LxcConf[] getLxcConf() { - return lxcConf; - } - - public void setLxcConf(LxcConf[] lxcConf) { - this.lxcConf = lxcConf; - } - - public Ports getPortBindings() { - return portBindings; - } - - public void setPortBindings(Ports portBindings) { - this.portBindings = portBindings; - } - - public boolean isPublishAllPorts() { - return publishAllPorts; - } - - public void setPublishAllPorts(boolean publishAllPorts) { - this.publishAllPorts = publishAllPorts; - } - - public boolean isPrivileged() { - return privileged; - } - - public void setPrivileged(boolean privileged) { - this.privileged = privileged; - } - - public String getDns() { - return dns; - } - - public void setDns(String dns) { - this.dns = dns; - } - - public String getVolumesFrom() { - return volumesFrom; - } - - public void setVolumesFrom(String volumesFrom) { - this.volumesFrom = volumesFrom; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - } + } From d5a0f74780289dba152c3752c464196c633b03ff Mon Sep 17 00:00:00 2001 From: Haney Maxwell Date: Tue, 5 Aug 2014 18:53:39 -0700 Subject: [PATCH 073/452] Remove special-case for one ":" from PullCommand This special treatment breaks images with registries with a port specified, e.g. my-docker-registry:5000/my-namespace/my-image --- .../com/github/dockerjava/client/command/PullImageCmd.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java b/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java index 83832c47..c6fa460e 100644 --- a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java @@ -71,13 +71,6 @@ public String toString() { protected ClientResponse impl() { 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); From 0a623e4ccf678114c63ebf98aa0823a61d368932 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 6 Aug 2014 20:53:39 +0200 Subject: [PATCH 074/452] Refactoring docker-java API --- .../client/BadRequestException.java | 22 +++ .../dockerjava/client/DockerClientConfig.java | 4 +- .../client/DockerClientException.java | 18 ++ .../dockerjava/client/DockerException.java | 21 ++- .../client/InternalServerErrorException.java | 22 +++ .../client/NotAcceptableException.java | 22 +++ .../dockerjava/client/NotFoundException.java | 15 +- .../client/NotModifiedException.java | 22 +++ .../client/command/AbstrAuthCfgDockerCmd.java | 5 +- .../client/command/AbstrDockerCmd.java | 30 ++- .../client/command/AttachContainerCmd.java | 85 +++++---- .../dockerjava/client/command/AuthCmd.java | 20 +- .../client/command/BuildImgCmd.java | 177 +++++++++--------- .../dockerjava/client/command/CommitCmd.java | 32 ++-- .../client/command/ContainerDiffCmd.java | 34 ++-- .../command/CopyFileFromContainerCmd.java | 45 +++-- .../client/command/CreateContainerCmd.java | 36 ++-- .../command/CreateContainerResponse.java | 2 - .../client/command/CreateImageCmd.java | 23 +-- .../dockerjava/client/command/InfoCmd.java | 17 +- .../client/command/InspectContainerCmd.java | 25 ++- .../command/InspectContainerResponse.java | 10 +- .../client/command/InspectImageCmd.java | 24 +-- .../client/command/KillContainerCmd.java | 29 ++- .../client/command/ListImagesCmd.java | 26 +-- .../client/command/LogContainerCmd.java | 36 ++-- .../client/model/ContainerConfig.java | 1 - 27 files changed, 447 insertions(+), 356 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/client/BadRequestException.java create mode 100644 src/main/java/com/github/dockerjava/client/DockerClientException.java create mode 100644 src/main/java/com/github/dockerjava/client/InternalServerErrorException.java create mode 100644 src/main/java/com/github/dockerjava/client/NotAcceptableException.java create mode 100644 src/main/java/com/github/dockerjava/client/NotModifiedException.java diff --git a/src/main/java/com/github/dockerjava/client/BadRequestException.java b/src/main/java/com/github/dockerjava/client/BadRequestException.java new file mode 100644 index 00000000..276a7d19 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/BadRequestException.java @@ -0,0 +1,22 @@ +package com.github.dockerjava.client; + +/** + * + */ +public class BadRequestException extends DockerException { + + private static final long serialVersionUID = -2450396075981100160L; + + public BadRequestException(String message, Throwable cause) { + super(message, 400, cause); + } + + public BadRequestException(String message) { + this(message, null); + } + + public BadRequestException(Throwable cause) { + this(cause.getMessage(), cause); + } + +} diff --git a/src/main/java/com/github/dockerjava/client/DockerClientConfig.java b/src/main/java/com/github/dockerjava/client/DockerClientConfig.java index 2c9340fa..9f1da87e 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/client/DockerClientConfig.java @@ -58,7 +58,7 @@ public static Properties loadIncludedDockerProperties() { p.load(DockerClientConfig.class.getResourceAsStream("/docker.io.properties")); return p; } catch (IOException e) { - throw new DockerException(e); + throw new RuntimeException(e); } } @@ -81,7 +81,7 @@ public static Properties overrideDockerPropertiesWithSettingsFromUserHome(Proper in.close(); } } catch (IOException e) { - throw new DockerException(e); + throw new RuntimeException(e); } } return overriddenProperties; diff --git a/src/main/java/com/github/dockerjava/client/DockerClientException.java b/src/main/java/com/github/dockerjava/client/DockerClientException.java new file mode 100644 index 00000000..3b322e93 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/DockerClientException.java @@ -0,0 +1,18 @@ +package com.github.dockerjava.client; + +/** + * + * + */ +public class DockerClientException extends RuntimeException { + +private static final long serialVersionUID = 7667768099261650608L; + + public DockerClientException(String message) { + super(message); + } + + public DockerClientException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/github/dockerjava/client/DockerException.java b/src/main/java/com/github/dockerjava/client/DockerException.java index f0abbe97..d60c15c8 100644 --- a/src/main/java/com/github/dockerjava/client/DockerException.java +++ b/src/main/java/com/github/dockerjava/client/DockerException.java @@ -1,5 +1,8 @@ package com.github.dockerjava.client; + + + /** * * @author Konstantin Pelykh (kpelykh@gmail.com) @@ -8,18 +11,20 @@ public class DockerException extends RuntimeException { - public DockerException() { - } +private static final long serialVersionUID = 7667768099261650608L; + + private int httpStatus = 0; - public DockerException(String message) { + public DockerException(String message, int httpStatus) { super(message); + this.httpStatus = httpStatus; } - public DockerException(String message, Throwable cause) { + public DockerException(String message, int httpStatus, Throwable cause) { super(message, cause); } - - public DockerException(Throwable cause) { - super(cause); - } + + public int getHttpStatus() { + return httpStatus; + } } diff --git a/src/main/java/com/github/dockerjava/client/InternalServerErrorException.java b/src/main/java/com/github/dockerjava/client/InternalServerErrorException.java new file mode 100644 index 00000000..8f4b11c9 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/InternalServerErrorException.java @@ -0,0 +1,22 @@ +package com.github.dockerjava.client; + +/** + * + */ +public class InternalServerErrorException extends DockerException { + + private static final long serialVersionUID = -2450396075981100160L; + + public InternalServerErrorException(String message, Throwable cause) { + super(message, 500, cause); + } + + public InternalServerErrorException(String message) { + this(message, null); + } + + public InternalServerErrorException(Throwable cause) { + this(cause.getMessage(), cause); + } + +} diff --git a/src/main/java/com/github/dockerjava/client/NotAcceptableException.java b/src/main/java/com/github/dockerjava/client/NotAcceptableException.java new file mode 100644 index 00000000..6f44f41f --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/NotAcceptableException.java @@ -0,0 +1,22 @@ +package com.github.dockerjava.client; + +/** + * + */ +public class NotAcceptableException extends DockerException { + + private static final long serialVersionUID = -1771212181727204375L; + + public NotAcceptableException(String message, Throwable cause) { + super(message, 406, cause); + } + + public NotAcceptableException(String message) { + this(message, null); + } + + public NotAcceptableException(Throwable cause) { + this(cause.getMessage(), cause); + } + +} diff --git a/src/main/java/com/github/dockerjava/client/NotFoundException.java b/src/main/java/com/github/dockerjava/client/NotFoundException.java index dba76e78..3c5f062c 100644 --- a/src/main/java/com/github/dockerjava/client/NotFoundException.java +++ b/src/main/java/com/github/dockerjava/client/NotFoundException.java @@ -7,8 +7,17 @@ */ public class NotFoundException extends DockerException { - public NotFoundException(String message) { - super(message); - } + private static final long serialVersionUID = -2450396075981100160L; + public NotFoundException(String message, Throwable cause) { + super(message, 404, cause); + } + + public NotFoundException(String message) { + this(message, null); + } + + public NotFoundException(Throwable cause) { + this(cause.getMessage(), cause); + } } diff --git a/src/main/java/com/github/dockerjava/client/NotModifiedException.java b/src/main/java/com/github/dockerjava/client/NotModifiedException.java new file mode 100644 index 00000000..6ff41b98 --- /dev/null +++ b/src/main/java/com/github/dockerjava/client/NotModifiedException.java @@ -0,0 +1,22 @@ +package com.github.dockerjava.client; + +/** + * + */ +public class NotModifiedException extends DockerException { + + private static final long serialVersionUID = -290093024775500239L; + + public NotModifiedException(String message, Throwable cause) { + super(message, 304, cause); + } + + public NotModifiedException(String message) { + this(message, null); + } + + public NotModifiedException(Throwable cause) { + this(cause.getMessage(), cause); + } + +} diff --git a/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java b/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java index 425df615..c01b8a44 100644 --- a/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java @@ -5,7 +5,6 @@ import org.apache.commons.codec.binary.Base64; import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.AuthConfig; import com.google.common.base.Preconditions; @@ -21,11 +20,11 @@ public T withAuthConfig(AuthConfig authConfig) { return (T)this; } - protected String registryAuth() throws DockerException { + protected String registryAuth() { try { return Base64.encodeBase64String(new ObjectMapper().writeValueAsString(authConfig).getBytes()); } catch (IOException e) { - throw new DockerException(e); + throw new RuntimeException(e); } } diff --git a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java index e5e2f2be..79ac941a 100644 --- a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java @@ -3,7 +3,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.dockerjava.client.BadRequestException; +import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.InternalServerErrorException; +import com.github.dockerjava.client.NotAcceptableException; +import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.client.NotModifiedException; import com.google.common.base.Preconditions; +import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; public abstract class AbstrDockerCmd, RES_T> implements DockerCmd { @@ -15,15 +22,32 @@ public abstract class AbstrDockerCmd, RES_T> @SuppressWarnings("unchecked") public T withBaseResource(WebResource baseResource) { this.baseResource = baseResource; - return (T)this; + return (T) this; } - abstract RES_T impl(); + protected abstract RES_T impl(); @Override public RES_T exec() { Preconditions.checkNotNull(baseResource, "baseResource was not specified"); LOGGER.debug("Cmd: {}", this); - return impl(); + + try { + return impl(); + } catch (UniformInterfaceException exception) { + int status = exception.getResponse().getStatus(); + switch(status) { + case 304: throw new NotModifiedException(exception.getMessage(), exception); + case 400: throw new BadRequestException(exception.getMessage(), exception); + case 404: throw new NotFoundException(exception.getMessage(), exception); + case 406: throw new NotAcceptableException(exception.getMessage(), exception); + case 500: throw new InternalServerErrorException(exception.getMessage(), exception); + default: throw toDockerException(exception); + } + } } + + protected DockerException toDockerException(UniformInterfaceException exception) { + return new DockerException(exception.getMessage(), exception.getResponse().getStatus(), exception); + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java index 84b54c36..12e100e5 100644 --- a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java @@ -1,24 +1,25 @@ package com.github.dockerjava.client.command; +import java.io.InputStream; + import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; /** * Attach to container - * - * @param logs - true or false, includes logs. Defaults to false. - * + * + * @param logs + * - true or false, includes logs. Defaults to false. + * * @param followStream * - true or false, return stream. Defaults to false. * @param stdout @@ -29,7 +30,8 @@ * - true or false, if true, print timestamps for every log line. * Defaults to false. */ -public class AttachContainerCmd extends AbstrDockerCmd { +public class AttachContainerCmd extends + AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory .getLogger(AttachContainerCmd.class); @@ -42,32 +44,33 @@ public AttachContainerCmd(String containerId) { withContainerId(containerId); } - public String getContainerId() { - return containerId; - } + public String getContainerId() { + return containerId; + } - public boolean hasLogsEnabled() { - return logs; - } + public boolean hasLogsEnabled() { + return logs; + } - public boolean hasFollowStreamEnabled() { - return followStream; - } + public boolean hasFollowStreamEnabled() { + return followStream; + } - public boolean hasTimestampsEnabled() { - return timestamps; - } + public boolean hasTimestampsEnabled() { + return timestamps; + } - public boolean hasStdoutEnabled() { - return stdout; - } + public boolean hasStdoutEnabled() { + return stdout; + } - public boolean hasStderrEnabled() { - return stderr; - } + public boolean hasStderrEnabled() { + return stderr; + } - public AttachContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + public AttachContainerCmd withContainerId(String containerId) { + Preconditions + .checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } @@ -108,8 +111,16 @@ public AttachContainerCmd withLogs(boolean logs) { this.logs = logs; return this; } + + /** + * @throws NotFoundException No such container + */ + @Override + public InputStream exec() throws NotFoundException { + return super.exec(); + } - protected ClientResponse impl() throws DockerException { + protected InputStream impl() { MultivaluedMap params = new MultivaluedMapImpl(); params.add("logs", logs ? "1" : "0"); params.add("timestamps", timestamps ? "1" : "0"); @@ -121,21 +132,9 @@ protected ClientResponse impl() throws DockerException { String.format("/containers/%s/attach", containerId)) .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() == 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); - } - } + LOGGER.trace("POST: {}", webResource); + return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .post(ClientResponse.class).getEntityInputStream(); + } } diff --git a/src/main/java/com/github/dockerjava/client/command/AuthCmd.java b/src/main/java/com/github/dockerjava/client/command/AuthCmd.java index 85f68103..119ff217 100644 --- a/src/main/java/com/github/dockerjava/client/command/AuthCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AuthCmd.java @@ -7,12 +7,11 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.AuthConfig; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** * - * Authenticate with the server, useful for checking authentication. + * Authenticate with the server, useful for checking authentication. * */ public class AuthCmd extends AbstrAuthCfgDockerCmd { @@ -24,17 +23,14 @@ public AuthCmd(AuthConfig authConfig) { } protected Void impl() throws DockerException { - try { - WebResource webResource = baseResource.path("/auth"); - LOGGER.trace("POST: {}", webResource); - webResource.header("Content-Type", MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON).post(authConfig); - return null; - } catch (UniformInterfaceException e) { - throw new DockerException(e); - } + + WebResource webResource = baseResource.path("/auth"); + LOGGER.trace("POST: {}", webResource); + webResource.header("Content-Type", MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON).post(authConfig); + return null; } - + @Override public String toString() { return "authenticate using " + this.authConfig; diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java index 34de8a8b..73793786 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -20,28 +20,31 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.dockerjava.client.DockerClientException; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.utils.CompressArchiveUtil; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; /** - * + * * Build an image from Dockerfile. - * + * * TODO: http://docs.docker.com/reference/builder/#dockerignore - * + * */ -public class BuildImgCmd extends AbstrDockerCmd { +public class BuildImgCmd extends AbstrDockerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(BuildImgCmd.class); + private static final Logger LOGGER = LoggerFactory + .getLogger(BuildImgCmd.class); - private static final Pattern ADD_OR_COPY_PATTERN = Pattern.compile("^(ADD|COPY)\\s+(.*)\\s+(.*)$"); + private static final Pattern ADD_OR_COPY_PATTERN = Pattern + .compile("^(ADD|COPY)\\s+(.*)\\s+(.*)$"); - private static final Pattern ENV_PATTERN = Pattern.compile("^ENV\\s+(.*)\\s+(.*)$"); + private static final Pattern ENV_PATTERN = Pattern + .compile("^ENV\\s+(.*)\\s+(.*)$"); private File dockerFolder = null; private InputStream tarInputStream = null; @@ -50,7 +53,6 @@ public class BuildImgCmd extends AbstrDockerCmd { private boolean remove = true; private boolean quiet; - public BuildImgCmd(File dockerFolder) { Preconditions.checkNotNull(dockerFolder, "dockerFolder is null"); this.dockerFolder = dockerFolder; @@ -67,27 +69,27 @@ public BuildImgCmd withTag(String tag) { return this; } - public File getDockerFolder() { - return dockerFolder; - } + public File getDockerFolder() { + return dockerFolder; + } - public String getTag() { - return tag; - } + public String getTag() { + return tag; + } - public boolean hasNoCacheEnabled() { - return noCache; - } + public boolean hasNoCacheEnabled() { + return noCache; + } - public boolean hasRemoveEnabled() { - return remove; - } + public boolean hasRemoveEnabled() { + return remove; + } - public boolean isQuiet() { - return quiet; - } + public boolean isQuiet() { + return quiet; + } - public BuildImgCmd withNoCache() { + public BuildImgCmd withNoCache() { return withNoCache(true); } @@ -96,34 +98,34 @@ public BuildImgCmd withNoCache(boolean noCache) { return this; } - public BuildImgCmd withRemove(boolean rm) { - this.remove = rm; - return this; - } + public BuildImgCmd withRemove(boolean rm) { + this.remove = rm; + return this; + } - public BuildImgCmd withQuiet(boolean quiet) { - this.quiet = quiet; - return this; - } + public BuildImgCmd withQuiet(boolean quiet) { + this.quiet = quiet; + return this; + } @Override public String toString() { return new StringBuilder("build ") - .append(tag != null ? "-t " + tag + " " : "") - .append(noCache ? "--nocache=true " : "") - .append(quiet ? "--quiet=true " : "") - .append(!remove ? "--rm=false " : "") - .append(dockerFolder != null ? dockerFolder.getPath() : "-") - .toString(); + .append(tag != null ? "-t " + tag + " " : "") + .append(noCache ? "--nocache=true " : "") + .append(quiet ? "--quiet=true " : "") + .append(!remove ? "--rm=false " : "") + .append(dockerFolder != null ? dockerFolder.getPath() : "-") + .toString(); } - - protected ClientResponse impl() { + + protected InputStream impl() throws DockerException { if (tarInputStream == null) { File dockerFolderTar = buildDockerFolderTar(); try { return callDocker(FileUtils.openInputStream(dockerFolderTar)); } catch (IOException e) { - throw new DockerException(e); + throw new RuntimeException(e); } finally { FileUtils.deleteQuietly(dockerFolderTar); } @@ -132,40 +134,35 @@ protected ClientResponse impl() { } } - protected ClientResponse callDocker(final InputStream dockerFolderTarInputStream) { + protected InputStream callDocker(final InputStream dockerFolderTarInputStream) throws DockerException { MultivaluedMap params = new MultivaluedMapImpl(); params.add("t", tag); if (noCache) { params.add("nocache", "true"); } if (remove) { - params.add("rm", "true"); + params.add("rm", "true"); + } + if (quiet) { + params.add("q", "true"); } - if (quiet) { - params.add("q", "true"); - } WebResource webResource = baseResource.path("/build").queryParams(params); - try { - LOGGER.trace("POST: {}", webResource); - return webResource - .type("application/tar") - .accept(MediaType.TEXT_PLAIN) - .post(ClientResponse.class, dockerFolderTarInputStream); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } + LOGGER.trace("POST: {}", webResource); + + return webResource.type("application/tar").accept(MediaType.TEXT_PLAIN) + .post(ClientResponse.class, dockerFolderTarInputStream).getEntityInputStream(); + } protected File buildDockerFolderTar() { - Preconditions.checkArgument(dockerFolder.exists(), "Path %s doesn't exist", dockerFolder); - Preconditions.checkArgument(dockerFolder.isDirectory(), "Folder %s doesn't exist", dockerFolder); - Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(), "Dockerfile doesn't exist in " + dockerFolder); + Preconditions.checkArgument(dockerFolder.exists(), + "Path %s doesn't exist", dockerFolder); + Preconditions.checkArgument(dockerFolder.isDirectory(), + "Folder %s doesn't exist", dockerFolder); + Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(), + "Dockerfile doesn't exist in " + dockerFolder); // ARCHIVE TAR String archiveNameWithOutExtension = UUID.randomUUID().toString(); @@ -177,13 +174,14 @@ protected File buildDockerFolderTar() { List dockerFileContent = FileUtils.readLines(dockerFile); if (dockerFileContent.size() <= 0) { - throw new DockerException(String.format("Dockerfile %s is empty", dockerFile)); + throw new DockerClientException(String.format( + "Dockerfile %s is empty", dockerFile)); } List filesToAdd = new ArrayList(); filesToAdd.add(dockerFile); - MapenvironmentMap = new HashMap(); + Map environmentMap = new HashMap(); int lineNumber = 0; @@ -198,7 +196,8 @@ protected File buildDockerFolderTar() { if (envMatcher.find()) { if (envMatcher.groupCount() != 2) - throw new DockerException(String.format("Wrong ENV format on line [%d]", lineNumber)); + throw new DockerClientException(String.format( + "Wrong ENV format on line [%d]", lineNumber)); String variable = envMatcher.group(1).trim(); @@ -207,30 +206,37 @@ protected File buildDockerFolderTar() { environmentMap.put(variable, value); } - final Matcher matcher = ADD_OR_COPY_PATTERN.matcher(cmd.trim()); if (matcher.find()) { if (matcher.groupCount() != 3) { - throw new DockerException(String.format("Wrong ADD or COPY format on line [%d]", lineNumber)); + throw new DockerClientException(String.format( + "Wrong ADD or COPY format on line [%d]", + lineNumber)); } String extractedResource = matcher.group(2); - String resource = filterForEnvironmentVars(extractedResource, environmentMap).trim(); + String resource = filterForEnvironmentVars( + extractedResource, environmentMap).trim(); - if(isFileResource(resource)) { + if (isFileResource(resource)) { File src = new File(resource); if (!src.isAbsolute()) { - src = new File(dockerFolder, resource).getCanonicalFile(); + src = new File(dockerFolder, resource) + .getCanonicalFile(); } else { - throw new DockerException(String.format("Source file %s must be relative to %s", src, dockerFolder)); + throw new DockerClientException(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)); + throw new DockerClientException(String.format( + "Source file %s doesn't exist", src)); } if (src.isDirectory()) { - filesToAdd.addAll(FileUtils.listFiles(src, null, true)); + filesToAdd.addAll(FileUtils.listFiles(src, null, + true)); } else { filesToAdd.add(src); } @@ -238,11 +244,13 @@ protected File buildDockerFolderTar() { } } - dockerFolderTar = CompressArchiveUtil.archiveTARFiles(dockerFolder, filesToAdd, archiveNameWithOutExtension); + dockerFolderTar = CompressArchiveUtil.archiveTARFiles(dockerFolder, + filesToAdd, archiveNameWithOutExtension); return dockerFolderTar; } catch (IOException ex) { FileUtils.deleteQuietly(dockerFolderTar); - throw new DockerException("Error occurred while preparing Docker context folder.", ex); + throw new DockerClientException( + "Error occurred while preparing Docker context folder.", ex); } } @@ -260,26 +268,27 @@ private String filterForEnvironmentVars(String extractedResource, String replacementValue = entry.getValue(); // handle: $VARIABLE case - currentResourceContent = currentResourceContent.replaceAll("\\$" + variable, replacementValue); + currentResourceContent = currentResourceContent.replaceAll( + "\\$" + variable, replacementValue); // handle ${VARIABLE} case - currentResourceContent = currentResourceContent.replaceAll("\\$\\{" + variable + "\\}", replacementValue); + currentResourceContent = currentResourceContent.replaceAll( + "\\$\\{" + variable + "\\}", replacementValue); } return currentResourceContent; - } - else + } else return extractedResource; } - private static boolean isFileResource(String resource) { - URI uri; + 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()); - } + return uri.getScheme() == null || "file".equals(uri.getScheme()); + } } diff --git a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java index 37b2e1ec..90861363 100644 --- a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java @@ -15,7 +15,6 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; @@ -317,6 +316,14 @@ public String toString() { .append(tag != null ? tag : "") .toString(); } + + /** + * @throws NotFoundException No such container + */ + @Override + public String exec() throws NotFoundException { + return super.exec(); + } protected String impl() throws DockerException { MultivaluedMap params = new MultivaluedMapImpl(); @@ -328,21 +335,12 @@ protected String impl() throws DockerException { params.add("pause", pause ? "1" : "0"); WebResource webResource = baseResource.path("/commit").queryParams(params); + + LOGGER.trace("POST: {}", webResource); + ObjectNode objectNode = webResource.queryParams(params).accept("application/vnd.docker.raw-stream").type(MediaType.APPLICATION_JSON).post(ObjectNode.class, this); + + return objectNode.get("Id").asText(); + } - try { - LOGGER.trace("POST: {}", webResource); - ObjectNode objectNode = webResource.queryParams(params).accept("application/vnd.docker.raw-stream").type(MediaType.APPLICATION_JSON).post(ObjectNode.class, this); - return objectNode.get("Id").asText(); - } 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); - } - } + } diff --git a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java b/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java index 8c16e600..ebe49d54 100644 --- a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java @@ -8,11 +8,11 @@ import org.slf4j.LoggerFactory; import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.InternalServerErrorException; import com.github.dockerjava.client.NotFoundException; import com.github.dockerjava.client.model.ChangeLog; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.GenericType; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** @@ -43,26 +43,24 @@ public ContainerDiffCmd withContainerId(String containerId) { @Override public String toString() { - return new StringBuilder("diff ") - .append(containerId) - .toString(); + return new StringBuilder("diff ").append(containerId).toString(); + } + + /** + * @throws NotFoundException No such container + * @throws InternalServerErrorException server error + * @throws DockerException unexpected http status code + */ + @Override + public List exec() throws NotFoundException { + return super.exec(); } protected List impl() throws DockerException { WebResource webResource = baseResource.path(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); - } - } + + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); } } diff --git a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java index c9523927..89ac1ff4 100644 --- a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java @@ -1,16 +1,19 @@ package com.github.dockerjava.client.command; +import java.io.InputStream; + import javax.ws.rs.core.MediaType; import com.fasterxml.jackson.annotation.JsonProperty; + import org.apache.commons.lang.builder.ToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** @@ -18,7 +21,7 @@ * Copy files or folders from a container. * */ -public class CopyFileFromContainerCmd extends AbstrDockerCmd { +public class CopyFileFromContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(CopyFileFromContainerCmd.class); @@ -73,29 +76,23 @@ public String toString() { .append(resource) .toString(); } + + /** + * @throws NotFoundException No such container + */ + @Override + public InputStream exec() throws NotFoundException { + return super.exec(); + } + + protected InputStream impl() throws DockerException { + + WebResource webResource = baseResource.path(String.format("/containers/%s/copy", containerId)); + + LOGGER.trace("POST: " + webResource.toString()); + WebResource.Builder builder = webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).type("application/json"); - protected ClientResponse impl() throws DockerException { - - WebResource webResource = - baseResource.path(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, this); - } 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); - } - } + return builder.post(ClientResponse.class, this).getEntityInputStream(); } diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index 45bec812..86973c24 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -6,18 +6,17 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.client.model.*; + import org.apache.commons.lang.builder.ToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotAcceptableException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; - /** * * Creates a new container. @@ -257,6 +256,15 @@ public String toString() { .append(this) .toString(); } + + /** + * @throws NotFoundException No such container + * @throws NotAcceptableException Impossible to attach (container not running) + */ + @Override + public CreateContainerResponse exec() throws NotFoundException, NotAcceptableException { + return super.exec(); + } protected CreateContainerResponse impl() { MultivaluedMap params = new MultivaluedMapImpl(); @@ -264,23 +272,11 @@ protected CreateContainerResponse impl() { params.add("name", name); } WebResource webResource = baseResource.path("/containers/create").queryParams(params); - - try { - LOGGER.trace("POST: {} ", webResource); - return webResource.accept(MediaType.APPLICATION_JSON) - .type(MediaType.APPLICATION_JSON) - .post(CreateContainerResponse.class, this); - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 404) { - throw new NotFoundException(String.format("%s is an unrecognized image. Please pull the image first.", 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); - } - } + + LOGGER.trace("POST: {} ", webResource); + return webResource.accept(MediaType.APPLICATION_JSON) + .type(MediaType.APPLICATION_JSON) + .post(CreateContainerResponse.class, this); } } diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java index 3eb9226f..2ea5af78 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java @@ -4,8 +4,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang.builder.ToStringBuilder; -import java.util.Arrays; - /** * * @author Konstantin Pelykh (kpelykh@gmail.com) diff --git a/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java index 776cf94f..8c64bd9e 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java @@ -9,9 +9,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; + import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; @@ -77,7 +76,7 @@ public String toString() { .append(tag != null ? tag : "") .toString(); } - + protected CreateImageResponse impl() { MultivaluedMap params = new MultivaluedMapImpl(); params.add("repo", repository); @@ -85,18 +84,10 @@ protected CreateImageResponse impl() { params.add("fromSrc", "-"); WebResource webResource = baseResource.path("/images/create").queryParams(params); - - try { - LOGGER.trace("POST: {}", webResource); - return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .post(CreateImageResponse.class, imageStream); - - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error.", exception); - } else { - throw new DockerException(exception); - } - } + + LOGGER.trace("POST: {}", webResource); + + return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .post(CreateImageResponse.class, imageStream); } } diff --git a/src/main/java/com/github/dockerjava/client/command/InfoCmd.java b/src/main/java/com/github/dockerjava/client/command/InfoCmd.java index 42985e63..75c03e63 100644 --- a/src/main/java/com/github/dockerjava/client/command/InfoCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InfoCmd.java @@ -7,7 +7,6 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Info; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -22,19 +21,11 @@ public class InfoCmd extends AbstrDockerCmd { public String toString() { return "info"; } - + protected Info impl() throws DockerException { WebResource webResource = baseResource.path("/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); - } - } + + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(Info.class); } } diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java index 78967e2d..c49250d3 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java @@ -8,7 +8,6 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** @@ -38,21 +37,19 @@ public InspectContainerCmd withContainerId(String containerId) { public String toString() { return "inspect " + containerId; } + + /** + * @throws NotFoundException No such container + */ + @Override + public InspectContainerResponse exec() throws NotFoundException { + return super.exec(); + } protected InspectContainerResponse impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/json", containerId)); - - try { - LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(InspectContainerResponse.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); - } - } + + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(InspectContainerResponse.class); } } diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java index 352cc7cc..990b67f9 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java @@ -1,14 +1,18 @@ package com.github.dockerjava.client.command; -import java.util.Arrays; import java.util.Map; +import org.apache.commons.lang.builder.ToStringBuilder; + import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.dockerjava.client.model.*; -import org.apache.commons.lang.builder.ToStringBuilder; +import com.github.dockerjava.client.model.ContainerConfig; +import com.github.dockerjava.client.model.LxcConf; +import com.github.dockerjava.client.model.Ports; +import com.github.dockerjava.client.model.Volume; +import com.github.dockerjava.client.model.Volumes; /** * diff --git a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java index 0343dc82..9fb68b56 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java @@ -5,10 +5,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -39,21 +37,19 @@ public InspectImageCmd withImageId(String imageId) { public String toString() { return "inspect " + imageId; } + + /** + * @throws NotFoundException No such image + */ + @Override + public InspectImageResponse exec() throws NotFoundException { + return super.exec(); + } protected InspectImageResponse impl() { WebResource webResource = baseResource.path(String.format("/images/%s/json", imageId)); - try { - LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(InspectImageResponse.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); - } - } + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(InspectImageResponse.class); } } diff --git a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java index 9f9cc6a5..da68c393 100644 --- a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java @@ -6,8 +6,8 @@ import org.slf4j.LoggerFactory; import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** @@ -47,6 +47,14 @@ public KillContainerCmd withSignal(String signal) { public String toString() { return "kill " + containerId; } + + /** + * @throws NotFoundException No such container + */ + @Override + public Void exec() throws NotFoundException { + return super.exec(); + } protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/kill", containerId)); @@ -54,22 +62,9 @@ protected Void impl() throws DockerException { if(signal != null) { webResource = webResource.queryParam("signal", signal); } - - 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); - } - } + + LOGGER.trace("POST: {}", webResource); + webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(); return null; } diff --git a/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java b/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java index 27af8ed9..64581a61 100644 --- a/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java @@ -8,11 +8,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Image; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.GenericType; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; @@ -56,28 +54,18 @@ public String toString() { .append(filter != null ? "--filter " + filter : "") .toString(); } - + protected List impl() { MultivaluedMap params = new MultivaluedMapImpl(); params.add("filter", filter); params.add("all", showAll ? "1" : "0"); WebResource webResource = baseResource.path("/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(); - } - } + + LOGGER.trace("GET: {}", webResource); + List images = webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); + LOGGER.trace("Response: {}", images); + return images; } } diff --git a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java index f1feb73a..69f0b469 100644 --- a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java @@ -1,5 +1,7 @@ package com.github.dockerjava.client.command; +import java.io.InputStream; + import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -10,7 +12,6 @@ import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; @@ -29,7 +30,7 @@ * @param tail * - `all` or ``, Output specified number of lines at the end of logs */ -public class LogContainerCmd extends AbstrDockerCmd { +public class LogContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory .getLogger(LogContainerCmd.class); @@ -125,8 +126,16 @@ public String toString() { .append(containerId) .toString(); } + + /** + * @throws NotFoundException No such container + */ + @Override + public InputStream exec() throws NotFoundException { + return super.exec(); + } - protected ClientResponse impl() throws DockerException { + protected InputStream impl() throws DockerException { MultivaluedMap params = new MultivaluedMapImpl(); params.add("timestamps", timestamps ? "1" : "0"); params.add("stdout", stdout ? "1" : "0"); @@ -137,22 +146,9 @@ protected ClientResponse impl() throws DockerException { WebResource webResource = baseResource.path( String.format("/containers/%s/logs", containerId)) .queryParams(params); - - try { - LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .get(ClientResponse.class); - } 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); - } - } + + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .get(ClientResponse.class).getEntityInputStream(); } } diff --git a/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java index 6bbb6eef..24b7353d 100644 --- a/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java +++ b/src/main/java/com/github/dockerjava/client/model/ContainerConfig.java @@ -1,6 +1,5 @@ package com.github.dockerjava.client.model; -import java.util.Arrays; import java.util.Map; import com.fasterxml.jackson.annotation.JsonIgnore; From f6ef1dded422f5dd0836a3e076fc3d5e6acaa422 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 6 Aug 2014 21:26:16 +0200 Subject: [PATCH 075/452] Fix tests for work with docker server v1.1.2 --- .../github/dockerjava/client/AbstractDockerClientTest.java | 2 +- .../dockerjava/client/command/StartContainerCmdTest.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index caead681..21c78e54 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -34,7 +34,7 @@ public void beforeTest() throws DockerException { LOG.info("Pulling image 'busybox'"); // need to block until image is pulled completely - logResponseStream(dockerClient.pullImageCmd("busybox:latest").exec()); + logResponseStream(dockerClient.pullImageCmd("busybox").withTag("latest").exec()); diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java index 4ea95fec..5bb2425f 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -116,10 +116,10 @@ public void startContainerWithPortBindings() throws DockerException { contains(tcp22, tcp23)); assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp22), - is(equalTo(Ports.Binding("0.0.0.0", 11022)))); + is(equalTo(Ports.Binding(11022)))); assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23), - is(equalTo(Ports.Binding("0.0.0.0", 11023)))); + is(equalTo(Ports.Binding(11023)))); tmpContainers.add(container.getId()); } From 35ff3fbe21b7ac9294d8756095d24bd5441c5b79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Flemstr=C3=B6m?= Date: Thu, 7 Aug 2014 04:45:58 +0200 Subject: [PATCH 076/452] Port to Jersey/JAX-RS 2.0 --- pom.xml | 34 ++--- .../dockerjava/client/DockerClient.java | 124 +++++++----------- .../client/SelectiveLoggingFilter.java | 25 ++-- .../client/command/AbstrAuthCfgDockerCmd.java | 3 +- .../client/command/AbstrDockerCmd.java | 7 +- .../client/command/AttachContainerCmd.java | 36 +++-- .../dockerjava/client/command/AuthCmd.java | 13 +- .../client/command/BuildImgCmd.java | 42 +++--- .../dockerjava/client/command/CommitCmd.java | 26 ++-- .../client/command/ContainerDiffCmd.java | 14 +- .../command/CopyFileFromContainerCmd.java | 25 ++-- .../client/command/CreateContainerCmd.java | 24 ++-- .../client/command/CreateImageCmd.java | 23 ++-- .../dockerjava/client/command/InfoCmd.java | 10 +- .../client/command/InspectContainerCmd.java | 10 +- .../client/command/InspectImageCmd.java | 10 +- .../client/command/KillContainerCmd.java | 12 +- .../client/command/ListContainersCmd.java | 29 ++-- .../client/command/ListImagesCmd.java | 20 ++- .../client/command/LogContainerCmd.java | 35 +++-- .../client/command/PauseContainerCmd.java | 16 ++- .../dockerjava/client/command/PingCmd.java | 12 +- .../client/command/PullImageCmd.java | 28 ++-- .../client/command/PushImageCmd.java | 19 +-- .../client/command/RemoveContainerCmd.java | 10 +- .../client/command/RemoveImageCmd.java | 13 +- .../client/command/RestartContainerCmd.java | 15 ++- .../client/command/SearchImagesCmd.java | 14 +- .../client/command/StartContainerCmd.java | 18 +-- .../client/command/StopContainerCmd.java | 13 +- .../client/command/TagImageCmd.java | 26 ++-- .../client/command/TopContainerCmd.java | 10 +- .../client/command/UnpauseContainerCmd.java | 15 ++- .../dockerjava/client/command/VersionCmd.java | 10 +- .../client/command/WaitContainerCmd.java | 12 +- .../client/utils/JsonClientFilter.java | 25 ++-- .../client/AbstractDockerClientTest.java | 4 +- .../client/command/AuthCmdTest.java | 6 +- .../client/command/BuildImageCmdTest.java | 36 ++--- .../command/CopyFileFromContainerCmdTest.java | 4 +- .../client/command/LogContainerCmdTest.java | 5 +- .../client/command/PullImageCmdTest.java | 5 +- 42 files changed, 405 insertions(+), 433 deletions(-) diff --git a/pom.xml b/pom.xml index 4d168980..3bb280f2 100644 --- a/pom.xml +++ b/pom.xml @@ -50,13 +50,14 @@ 1.6.1 - 1.18 + 2.11 1.9 2.3.3 4.2.5 1.5 + 1.8 2.3 2.6 1.7.5 @@ -87,38 +88,21 @@ ${jackson-jaxrs.version} - com.sun.jersey - jersey-core - ${jersey.version} - - - com.sun.jersey - jersey-client + org.glassfish.jersey.connectors + jersey-jetty-connector ${jersey.version} - - com.sun.jersey.contribs - jersey-multipart - ${jersey.version} - - - com.sun.jersey.contribs - jersey-apache-client4 - ${jersey-apache-client4.version} - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - org.apache.commons commons-compress ${commons-compress.version} + + commons-codec + commons-codec + ${commons-codec.version} + commons-lang commons-lang diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index f938edce..7dee0cb4 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -1,32 +1,21 @@ package com.github.dockerjava.client; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.apache.commons.io.IOUtils.closeQuietly; - -import java.io.*; - +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.github.dockerjava.client.command.*; - +import com.github.dockerjava.client.model.AuthConfig; +import com.github.dockerjava.client.utils.JsonClientFilter; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; -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.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; -import com.github.dockerjava.client.model.AuthConfig; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; +import java.io.*; -import com.github.dockerjava.client.utils.JsonClientFilter; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.client.apache4.ApacheHttpClient4; -import com.sun.jersey.client.apache4.ApacheHttpClient4Handler; +import static com.google.common.base.Preconditions.checkNotNull; /** * @author Konstantin Pelykh (kpelykh@gmail.com) @@ -36,7 +25,7 @@ public class DockerClient implements Closeable { private final Client client; private final CommandFactory cmdFactory; - private final WebResource baseResource; + private final WebTarget baseResource; private final DockerClientConfig dockerClientConfig; public DockerClient() { @@ -61,43 +50,27 @@ public DockerClient(DockerClientConfig dockerClientConfig, CommandFactory cmdFac this.cmdFactory = cmdFactory; this.dockerClientConfig = dockerClientConfig; - HttpClient httpClient = getPoolingHttpClient(dockerClientConfig); - ClientConfig clientConfig = new DefaultClientConfig(); - client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, - null, false), clientConfig); - - if(dockerClientConfig.getReadTimeout() != null) { - client.setReadTimeout(dockerClientConfig.getReadTimeout()); - } - - client.addFilter(new JsonClientFilter()); + ClientConfig clientConfig = new ClientConfig(); - if (dockerClientConfig.isLoggingFilterEnabled()) - client.addFilter(new SelectiveLoggingFilter()); + if (dockerClientConfig.getReadTimeout() != null) { + clientConfig.property(ClientProperties.READ_TIMEOUT, dockerClientConfig.getReadTimeout()); + } - WebResource webResource = client.resource(dockerClientConfig.getUri()); - - if(dockerClientConfig.getVersion() != null) { - baseResource = webResource.path("v" + dockerClientConfig.getVersion()); - } else { - baseResource = webResource; - } - } + clientConfig.register(JsonClientFilter.class); + clientConfig.register(JacksonJsonProvider.class); - private HttpClient getPoolingHttpClient(DockerClientConfig dockerClientConfig) { - SchemeRegistry schemeRegistry = new SchemeRegistry(); - schemeRegistry.register(new Scheme("http", dockerClientConfig.getUri().getPort(), - PlainSocketFactory.getSocketFactory())); - schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory - .getSocketFactory())); + if (dockerClientConfig.isLoggingFilterEnabled()) { + clientConfig.register(SelectiveLoggingFilter.class); + } - PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); - // Increase max total connection - cm.setMaxTotal(1000); - // Increase default max connection per route - cm.setDefaultMaxPerRoute(1000); + client = ClientBuilder.newBuilder().withConfig(clientConfig).build(); + WebTarget webResource = client.target(dockerClientConfig.getUri()); - return new DefaultHttpClient(cm); + if (dockerClientConfig.getVersion() != null) { + baseResource = webResource.path("v" + dockerClientConfig.getVersion()); + } else { + baseResource = webResource; + } } public RES_T execute(AbstrDockerCmd command) @@ -105,7 +78,7 @@ public RES_T execute(AbstrDockerCmd command) return command.withBaseResource(baseResource).exec(); } - public AuthConfig authConfig() throws DockerException { + public AuthConfig authConfig() throws DockerException { checkNotNull(dockerClientConfig.getUsername(), "Configured username is null."); checkNotNull(dockerClientConfig.getPassword(), "Configured password is null."); checkNotNull(dockerClientConfig.getEmail(), "Configured email is null."); @@ -263,28 +236,29 @@ public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { } // TODO This is only being used by the test code for logging. Is it really necessary? - /** - * @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(); - } + + /** + * @return The output slurped into a string. + */ + public static String asString(Response response) throws IOException { + + StringWriter out = new StringWriter(); + InputStream is = response.readEntity(InputStream.class); + try { + LineIterator itr = IOUtils.lineIterator(is, "UTF-8"); + while (itr.hasNext()) { + String line = itr.next(); + out.write(line + (itr.hasNext() ? "\n" : "")); + } + } finally { + IOUtils.closeQuietly(is); + } + return out.toString(); + } @Override public void close() throws IOException { - client.destroy(); + client.close(); } } diff --git a/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java b/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java index fbdbfc7a..b0f69ebb 100644 --- a/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java +++ b/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java @@ -1,15 +1,15 @@ package com.github.dockerjava.client; +import java.io.IOException; import java.util.Set; +import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import com.google.common.collect.ImmutableSet; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.filter.LoggingFilter; + +import org.glassfish.jersey.filter.LoggingFilter; /** * A version of the logging filter that will avoid trying to log entities which can cause @@ -26,22 +26,13 @@ public class SelectiveLoggingFilter extends LoggingFilter { .build(); @Override - public ClientResponse handle(ClientRequest request) throws ClientHandlerException { + public void filter(ClientRequestContext context) throws IOException { // Unless the content type is in the list of those we want to ellide, then just have // our super-class handle things. - Object contentType = request.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE); - if (contentType != null && SKIPPED_CONTENT.contains(contentType.toString())) { - // Skip logging this. - // - // N.B. -- I'd actually love to reproduce (or better yet just use) the logging code from - // our super-class. However, everything is private (so we can't use it) and the code - // is under a modified GPL which means we can't pull it into an ASL project. Right now - // I don't have the energy to do a clean implementation. - return getNext().handle(request); + Object contentType = context.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE); + if (contentType == null || !SKIPPED_CONTENT.contains(contentType.toString())) { + super.filter(context); } - - // Do what we normally would - return super.handle(request); } } diff --git a/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java b/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java index 425df615..37a3ffd1 100644 --- a/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java @@ -2,12 +2,11 @@ import java.io.IOException; -import org.apache.commons.codec.binary.Base64; - import com.fasterxml.jackson.databind.ObjectMapper; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.AuthConfig; import com.google.common.base.Preconditions; +import org.apache.commons.codec.binary.Base64; public abstract class AbstrAuthCfgDockerCmd, RES_T> extends AbstrDockerCmd { diff --git a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java index e5e2f2be..48ed9a5e 100644 --- a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java @@ -4,16 +4,17 @@ import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.WebResource; + +import javax.ws.rs.client.WebTarget; public abstract class AbstrDockerCmd, RES_T> implements DockerCmd { private final static Logger LOGGER = LoggerFactory.getLogger(AbstrDockerCmd.class); - protected WebResource baseResource; + protected WebTarget baseResource; @SuppressWarnings("unchecked") - public T withBaseResource(WebResource baseResource) { + public T withBaseResource(WebTarget baseResource) { this.baseResource = baseResource; return (T)this; } diff --git a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java index 84b54c36..1a424951 100644 --- a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -9,10 +10,10 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.MultivaluedMapImpl; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import static javax.ws.rs.client.Entity.entity; /** * Attach to container @@ -29,7 +30,7 @@ * - true or false, if true, print timestamps for every log line. * Defaults to false. */ -public class AttachContainerCmd extends AbstrDockerCmd { +public class AttachContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory .getLogger(AttachContainerCmd.class); @@ -109,23 +110,20 @@ public AttachContainerCmd withLogs(boolean logs) { return this; } - protected ClientResponse impl() throws DockerException { - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("logs", logs ? "1" : "0"); - params.add("timestamps", timestamps ? "1" : "0"); - params.add("stdout", stdout ? "1" : "0"); - params.add("stderr", stderr ? "1" : "0"); - params.add("follow", followStream ? "1" : "0"); - - WebResource webResource = baseResource.path( - String.format("/containers/%s/attach", containerId)) - .queryParams(params); + protected Response impl() throws DockerException { + WebTarget webResource = baseResource.path("/containers/{id}/attach") + .resolveTemplate("{id}", containerId) + .queryParam("logs", logs ? "1" : "0") + .queryParam("timestamps", timestamps ? "1" : "0") + .queryParam("stdout", stdout ? "1" : "0") + .queryParam("stderr", stderr ? "1" : "0") + .queryParam("follow", followStream ? "1" : "0"); try { LOGGER.trace("POST: {}", webResource); - return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .post(ClientResponse.class); - } catch (UniformInterfaceException exception) { + return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .post(entity(null, MediaType.APPLICATION_JSON), Response.class); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 400) { throw new DockerException("bad parameter"); } else if (exception.getResponse().getStatus() == 404) { diff --git a/src/main/java/com/github/dockerjava/client/command/AuthCmd.java b/src/main/java/com/github/dockerjava/client/command/AuthCmd.java index 85f68103..7333bf2d 100644 --- a/src/main/java/com/github/dockerjava/client/command/AuthCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AuthCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -7,8 +8,9 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.AuthConfig; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; + +import static javax.ws.rs.client.Entity.entity; /** * @@ -25,12 +27,11 @@ public AuthCmd(AuthConfig authConfig) { protected Void impl() throws DockerException { try { - WebResource webResource = baseResource.path("/auth"); + WebTarget webResource = baseResource.path("/auth"); LOGGER.trace("POST: {}", webResource); - webResource.header("Content-Type", MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON).post(authConfig); + webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(authConfig, MediaType.APPLICATION_JSON)); return null; - } catch (UniformInterfaceException e) { + } catch (ClientErrorException e) { throw new DockerException(e); } } diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java index 34de8a8b..65b6227c 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -13,6 +13,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -23,10 +24,10 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.utils.CompressArchiveUtil; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.MultivaluedMapImpl; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import static javax.ws.rs.client.Entity.entity; /** * @@ -35,7 +36,7 @@ * TODO: http://docs.docker.com/reference/builder/#dockerignore * */ -public class BuildImgCmd extends AbstrDockerCmd { +public class BuildImgCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(BuildImgCmd.class); @@ -117,7 +118,7 @@ public String toString() { .toString(); } - protected ClientResponse impl() { + protected Response impl() { if (tarInputStream == null) { File dockerFolderTar = buildDockerFolderTar(); try { @@ -132,28 +133,27 @@ protected ClientResponse impl() { } } - protected ClientResponse callDocker(final InputStream dockerFolderTarInputStream) { - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("t", tag); - if (noCache) { - params.add("nocache", "true"); - } - if (remove) { - params.add("rm", "true"); - } + protected Response callDocker(final InputStream dockerFolderTarInputStream) { + + WebTarget webResource = baseResource.path("/build") + .queryParam("t", tag); + if (noCache) { + webResource = webResource.queryParam("nocache", "true"); + } + if (remove) { + webResource = webResource.queryParam("rm", "true"); + } if (quiet) { - params.add("q", "true"); + webResource = webResource.queryParam("q", "true"); } - WebResource webResource = baseResource.path("/build").queryParams(params); - try { LOGGER.trace("POST: {}", webResource); return webResource - .type("application/tar") + .request() .accept(MediaType.TEXT_PLAIN) - .post(ClientResponse.class, dockerFolderTarInputStream); - } catch (UniformInterfaceException exception) { + .post(entity(dockerFolderTarInputStream, "application/tar"), Response.class); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 500) { throw new DockerException("Server error", exception); } else { diff --git a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java index 37b2e1ec..dea56792 100644 --- a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -15,9 +16,9 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.MultivaluedMapImpl; +import javax.ws.rs.client.WebTarget; + +import static javax.ws.rs.client.Entity.entity; /** * @@ -319,21 +320,20 @@ public String toString() { } protected String impl() throws DockerException { - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("container", containerId); - params.add("repo", repository); - params.add("tag", tag); - params.add("m", message); - params.add("author", author); - params.add("pause", pause ? "1" : "0"); - WebResource webResource = baseResource.path("/commit").queryParams(params); + WebTarget webResource = baseResource.path("/commit") + .queryParam("container", containerId) + .queryParam("repo", repository) + .queryParam("tag", tag) + .queryParam("m", message) + .queryParam("author", author) + .queryParam("pause", pause ? "1" : "0"); try { LOGGER.trace("POST: {}", webResource); - ObjectNode objectNode = webResource.queryParams(params).accept("application/vnd.docker.raw-stream").type(MediaType.APPLICATION_JSON).post(ObjectNode.class, this); + ObjectNode objectNode = webResource.request().accept("application/vnd.docker.raw-stream").post(entity(this, MediaType.APPLICATION_JSON), ObjectNode.class); return objectNode.get("Id").asText(); - } catch (UniformInterfaceException exception) { + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such container %s", containerId)); } else if (exception.getResponse().getStatus() == 500) { diff --git a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java b/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java index 8c16e600..e5d7df41 100644 --- a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java @@ -2,6 +2,9 @@ import java.util.List; +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -11,9 +14,6 @@ import com.github.dockerjava.client.NotFoundException; import com.github.dockerjava.client.model.ChangeLog; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.GenericType; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; /** * Inspect changes on a container's filesystem @@ -49,13 +49,13 @@ public String toString() { } protected List impl() throws DockerException { - WebResource webResource = baseResource.path(String.format("/containers/%s/changes", containerId)); + WebTarget webResource = baseResource.path("/containers/{id}/changes").resolveTemplate("id", containerId); try { LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() { - }); - } catch (UniformInterfaceException exception) { + return webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such container %s", containerId)); } else if (exception.getResponse().getStatus() == 500) { diff --git a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java index c9523927..2edc6a21 100644 --- a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java @@ -1,5 +1,7 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.client.Invocation; import javax.ws.rs.core.MediaType; import com.fasterxml.jackson.annotation.JsonProperty; @@ -9,16 +11,17 @@ import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import static javax.ws.rs.client.Entity.entity; /** * * Copy files or folders from a container. * */ -public class CopyFileFromContainerCmd extends AbstrDockerCmd { +public class CopyFileFromContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(CopyFileFromContainerCmd.class); @@ -74,18 +77,18 @@ public String toString() { .toString(); } - protected ClientResponse impl() throws DockerException { + protected Response impl() throws DockerException { - WebResource webResource = - baseResource.path(String.format("/containers/%s/copy", containerId)); + WebTarget webResource = + baseResource.path("/containers/{id}/copy").resolveTemplate("id", containerId); try { LOGGER.trace("POST: " + webResource.toString()); - WebResource.Builder builder = - webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).type("application/json"); + Invocation.Builder builder = + webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE); - return builder.post(ClientResponse.class, this); - } catch (UniformInterfaceException exception) { + return builder.post(entity(this, MediaType.APPLICATION_JSON), Response.class); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 400) { throw new DockerException("bad parameter"); } else if (exception.getResponse().getStatus() == 404) { diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index 45bec812..b8f39a34 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -13,9 +14,9 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.MultivaluedMapImpl; +import javax.ws.rs.client.WebTarget; + +import static javax.ws.rs.client.Entity.entity; /** @@ -259,18 +260,17 @@ public String toString() { } protected CreateContainerResponse impl() { - MultivaluedMap params = new MultivaluedMapImpl(); - if (name != null) { - params.add("name", name); - } - WebResource webResource = baseResource.path("/containers/create").queryParams(params); + WebTarget webResource = baseResource.path("/containers/create"); + + if (name != null) { + webResource = webResource.queryParam("name", name); + } try { LOGGER.trace("POST: {} ", webResource); - return webResource.accept(MediaType.APPLICATION_JSON) - .type(MediaType.APPLICATION_JSON) - .post(CreateContainerResponse.class, this); - } catch (UniformInterfaceException exception) { + return webResource.request().accept(MediaType.APPLICATION_JSON) + .post(entity(this, MediaType.APPLICATION_JSON), CreateContainerResponse.class); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("%s is an unrecognized image. Please pull the image first.", getImage())); } else if (exception.getResponse().getStatus() == 406) { diff --git a/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java index 776cf94f..4d34db8e 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateImageCmd.java @@ -2,6 +2,7 @@ import java.io.InputStream; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -11,9 +12,9 @@ import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.MultivaluedMapImpl; +import javax.ws.rs.client.WebTarget; + +import static javax.ws.rs.client.Entity.entity; /** * Create an image by importing the given stream of a tar file. @@ -79,19 +80,19 @@ public String toString() { } protected CreateImageResponse impl() { - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("repo", repository); - params.add("tag", tag); - params.add("fromSrc", "-"); - WebResource webResource = baseResource.path("/images/create").queryParams(params); + WebTarget webResource = baseResource + .path("/images/create") + .queryParam("repo", repository) + .queryParam("tag", tag) + .queryParam("fromSrc", "-"); try { LOGGER.trace("POST: {}", webResource); - return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .post(CreateImageResponse.class, imageStream); + return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .post(entity(imageStream, MediaType.APPLICATION_OCTET_STREAM), CreateImageResponse.class); - } catch (UniformInterfaceException exception) { + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 500) { throw new DockerException("Server error.", exception); } else { diff --git a/src/main/java/com/github/dockerjava/client/command/InfoCmd.java b/src/main/java/com/github/dockerjava/client/command/InfoCmd.java index 42985e63..db503379 100644 --- a/src/main/java/com/github/dockerjava/client/command/InfoCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InfoCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -7,8 +8,7 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Info; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; /** @@ -24,12 +24,12 @@ public String toString() { } protected Info impl() throws DockerException { - WebResource webResource = baseResource.path("/info"); + WebTarget webResource = baseResource.path("/info"); try { LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(Info.class); - } catch (UniformInterfaceException exception) { + return webResource.request().accept(MediaType.APPLICATION_JSON).get(Info.class); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 500) { throw new DockerException("Server error.", exception); } else { diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java index 78967e2d..e08b4eaa 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -8,8 +9,7 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; /** * Inspect the details of a container. @@ -40,12 +40,12 @@ public String toString() { } protected InspectContainerResponse impl() throws DockerException { - WebResource webResource = baseResource.path(String.format("/containers/%s/json", containerId)); + WebTarget webResource = baseResource.path("/containers/{id}/json").resolveTemplate("id", containerId); try { LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(InspectContainerResponse.class); - } catch (UniformInterfaceException exception) { + return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectContainerResponse.class); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such container %s", containerId)); } else if (exception.getResponse().getStatus() == 500) { diff --git a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java index 0343dc82..f334b866 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -8,8 +9,7 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; /** @@ -41,12 +41,12 @@ public String toString() { } protected InspectImageResponse impl() { - WebResource webResource = baseResource.path(String.format("/images/%s/json", imageId)); + WebTarget webResource = baseResource.path("/images/{id}/json").resolveTemplate("id", imageId); try { LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(InspectImageResponse.class); - } catch (UniformInterfaceException exception) { + return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectImageResponse.class); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such image %s", imageId)); } else if (exception.getResponse().getStatus() == 500) { diff --git a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java index 9f9cc6a5..fca7b310 100644 --- a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -7,8 +8,9 @@ import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; + +import static javax.ws.rs.client.Entity.entity; /** * Kill a running container. @@ -49,7 +51,7 @@ public String toString() { } protected Void impl() throws DockerException { - WebResource webResource = baseResource.path(String.format("/containers/%s/kill", containerId)); + WebTarget webResource = baseResource.path("/containers/{id}/kill").resolveTemplate("id", containerId); if(signal != null) { webResource = webResource.queryParam("signal", signal); @@ -57,8 +59,8 @@ protected Void impl() throws DockerException { try { LOGGER.trace("POST: {}", webResource); - webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(); - } catch (UniformInterfaceException exception) { + webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON)); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { LOGGER.warn("No such container {}", containerId); } else if (exception.getResponse().getStatus() == 204) { diff --git a/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java b/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java index 226e1680..e6ea3b5f 100644 --- a/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java @@ -2,6 +2,7 @@ import java.util.List; +import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -10,9 +11,7 @@ import com.github.dockerjava.client.model.Container; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.GenericType; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.MultivaluedMapImpl; +import javax.ws.rs.client.WebTarget; /** @@ -93,19 +92,19 @@ public String toString() { } protected List impl() { - MultivaluedMap params = new MultivaluedMapImpl(); - if(limit >= 0) { - params.add("limit", String.valueOf(limit)); - } - params.add("all", showAll ? "1" : "0"); - params.add("since", sinceId); - params.add("before", beforeId); - params.add("size", showSize ? "1" : "0"); - - WebResource webResource = baseResource.path("/containers/json").queryParams(params); + WebTarget webResource = baseResource.path("/containers/json") + .queryParam("all", showAll ? "1" : "0") + .queryParam("since", sinceId) + .queryParam("before", beforeId) + .queryParam("size", showSize ? "1" : "0"); + + if (limit >= 0) { + webResource = webResource.queryParam("limit", String.valueOf(limit)); + } + LOGGER.trace("GET: {}", webResource); - List containers = webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() { - }); + List containers = webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); LOGGER.trace("Response: {}", containers); return containers; diff --git a/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java b/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java index 27af8ed9..7cf55b3f 100644 --- a/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java @@ -2,6 +2,8 @@ import java.util.List; +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -11,10 +13,7 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Image; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.GenericType; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.MultivaluedMapImpl; +import javax.ws.rs.client.WebTarget; /** @@ -58,19 +57,18 @@ public String toString() { } protected List impl() { - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("filter", filter); - params.add("all", showAll ? "1" : "0"); - - WebResource webResource = baseResource.path("/images/json").queryParams(params); + WebTarget webResource = baseResource + .path("/images/json") + .queryParam("filter", filter) + .queryParam("all", showAll ? "1" : "0"); try { LOGGER.trace("GET: {}", webResource); - List images = webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + List images = webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { }); LOGGER.trace("Response: {}", images); return images; - } catch (UniformInterfaceException exception) { + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 400) { throw new DockerException("bad parameter"); } else if (exception.getResponse().getStatus() == 500) { diff --git a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java index f1feb73a..0e9f29a6 100644 --- a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java @@ -1,18 +1,18 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; +import org.omg.PortableInterceptor.ClientRequestInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.MultivaluedMapImpl; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; /** * Get container logs @@ -29,7 +29,7 @@ * @param tail * - `all` or ``, Output specified number of lines at the end of logs */ -public class LogContainerCmd extends AbstrDockerCmd { +public class LogContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory .getLogger(LogContainerCmd.class); @@ -126,23 +126,22 @@ public String toString() { .toString(); } - protected ClientResponse impl() throws DockerException { - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("timestamps", timestamps ? "1" : "0"); - params.add("stdout", stdout ? "1" : "0"); - params.add("stderr", stderr ? "1" : "0"); - params.add("follow", followStream ? "1" : "0"); - params.add("tail", tail < 0 ? "all" : ""+ tail); + protected Response impl() throws DockerException { - WebResource webResource = baseResource.path( - String.format("/containers/%s/logs", containerId)) - .queryParams(params); + WebTarget webResource = + baseResource.path("/containers/{id}/logs") + .resolveTemplate("id", containerId) + .queryParam("timestamps", timestamps ? "1" : "0") + .queryParam("stdout", stdout ? "1" : "0") + .queryParam("stderr", stderr ? "1" : "0") + .queryParam("follow", followStream ? "1" : "0") + .queryParam("tail", tail < 0 ? "all" : "" + tail); try { LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .get(ClientResponse.class); - } catch (UniformInterfaceException exception) { + return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .get(Response.class); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 400) { throw new DockerException("bad parameter"); } else if (exception.getResponse().getStatus() == 404) { diff --git a/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java index a4508369..86952866 100644 --- a/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -7,9 +8,10 @@ import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import static javax.ws.rs.client.Entity.entity; /** * Pause a container. @@ -45,14 +47,14 @@ public String toString() { } protected Integer impl() throws DockerException { - WebResource webResource = baseResource.path(String.format("/containers/%s/pause", containerId)); + WebTarget webResource = baseResource.path("/containers/{id}/pause").resolveTemplate("id", containerId); - ClientResponse response = null; + Response response = null; try { LOGGER.trace("POST: {}", webResource); - response = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ClientResponse.class); - } catch (UniformInterfaceException exception) { + response = webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON), Response.class); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { LOGGER.warn("No such container {}", containerId); } else if (exception.getResponse().getStatus() == 204) { diff --git a/src/main/java/com/github/dockerjava/client/command/PingCmd.java b/src/main/java/com/github/dockerjava/client/command/PingCmd.java index e017617a..ebbaf49b 100644 --- a/src/main/java/com/github/dockerjava/client/command/PingCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PingCmd.java @@ -3,9 +3,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; /** * Ping the Docker server @@ -16,13 +16,13 @@ public class PingCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(PingCmd.class); protected Integer impl() { - WebResource webResource = baseResource.path("/_ping"); + WebTarget webResource = baseResource.path("/_ping"); try { LOGGER.trace("GET: {}", webResource); - ClientResponse resp = webResource.get(ClientResponse.class); + Response resp = webResource.request().get(Response.class); return resp.getStatus(); - } catch (UniformInterfaceException exception) { + } catch (ClientErrorException exception) { return exception.getResponse().getStatus(); } } diff --git a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java b/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java index 83832c47..3342fdea 100644 --- a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -9,10 +10,10 @@ import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.MultivaluedMapImpl; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import static javax.ws.rs.client.Entity.entity; /** @@ -20,7 +21,7 @@ * Pull image from repository. * */ -public class PullImageCmd extends AbstrDockerCmd { +public class PullImageCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(PullImageCmd.class); @@ -68,7 +69,7 @@ public String toString() { .toString(); } - protected ClientResponse impl() { + protected Response impl() { Preconditions.checkNotNull(repository, "Repository was not specified"); if (StringUtils.countMatches(repository, ":") == 1) { @@ -78,17 +79,16 @@ protected ClientResponse impl() { } - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("tag", tag); - params.add("fromImage", repository); - params.add("registry", registry); - - WebResource webResource = baseResource.path("/images/create").queryParams(params); + WebTarget webResource = baseResource + .path("/images/create") + .queryParam("tag", tag) + .queryParam("fromImage", repository) + .queryParam("registry", registry); try { LOGGER.trace("POST: {}", webResource); - return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ClientResponse.class); - } catch (UniformInterfaceException exception) { + return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(entity(Response.class, MediaType.APPLICATION_JSON)); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 500) { throw new DockerException("Server error.", exception); } else { diff --git a/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java b/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java index 41cdc077..20156068 100644 --- a/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -7,9 +8,10 @@ import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import static javax.ws.rs.client.Entity.entity; /** @@ -17,7 +19,7 @@ * * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. */ -public class PushImageCmd extends AbstrAuthCfgDockerCmd { +public class PushImageCmd extends AbstrAuthCfgDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(PushImageCmd.class); @@ -47,16 +49,17 @@ public String toString() { .toString(); } - protected ClientResponse impl() { - WebResource webResource = baseResource.path("/images/" + name(name) + "/push"); + protected Response impl() { + WebTarget webResource = baseResource.path("/images/" + name(name) + "/push"); try { final String registryAuth = registryAuth(); LOGGER.trace("POST: {}", webResource); return webResource + .request() .header("X-Registry-Auth", registryAuth) .accept(MediaType.APPLICATION_JSON) - .post(ClientResponse.class); - } catch (UniformInterfaceException e) { + .post(entity(Response.class, MediaType.APPLICATION_JSON)); + } catch (ClientErrorException e) { throw new DockerException(e); } } diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java index 3a12cd8e..33a634ec 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import org.apache.commons.lang.StringUtils; @@ -8,8 +9,7 @@ import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; /** * Remove a container. @@ -73,13 +73,13 @@ public String toString() { protected Void impl() throws DockerException { Preconditions.checkState(!StringUtils.isEmpty(containerId), "Container ID can't be empty"); - WebResource webResource = baseResource.path("/containers/" + containerId).queryParam("v", removeVolumes ? "1" : "0").queryParam("force", force ? "1" : "0"); + WebTarget webResource = baseResource.path("/containers/" + containerId).queryParam("v", removeVolumes ? "1" : "0").queryParam("force", force ? "1" : "0"); try { LOGGER.trace("DELETE: {}", webResource); - String response = webResource.accept(MediaType.APPLICATION_JSON).delete(String.class); + String response = webResource.request().accept(MediaType.APPLICATION_JSON).delete(String.class); LOGGER.trace("Response: {}", response); - } catch (UniformInterfaceException exception) { + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 204) { //no error LOGGER.trace("Successfully removed container " + containerId); diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java b/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java index 49707d51..1143919c 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java @@ -6,9 +6,10 @@ import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; + +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; /** * @@ -72,14 +73,14 @@ protected Void impl() throws DockerException { Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty"); try { - WebResource webResource = baseResource.path("/images/" + imageId) + WebTarget webResource = baseResource.path("/images/" + imageId) .queryParam("force", force ? "1" : "0").queryParam("noprune", noPrune ? "1" : "0"); LOGGER.trace("DELETE: {}", webResource); - webResource.delete(ClientResponse.class); + webResource.request().delete(Response.class); - } catch (UniformInterfaceException exception) { + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 204) { //no error LOGGER.trace("Successfully removed image " + imageId); diff --git a/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java index 8a383af2..2f8c9f86 100644 --- a/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java @@ -1,5 +1,7 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -8,8 +10,9 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; + +import static javax.ws.rs.client.Entity.entity; /** * Restart a running container. @@ -58,13 +61,13 @@ public String toString() { } protected Void impl() throws DockerException { - WebResource webResource = baseResource.path(String.format("/containers/%s/restart", containerId)) - .queryParam("t", String.valueOf(timeout));; + WebTarget webResource = baseResource.path("/containers/{id}/restart").resolveTemplate("id", containerId) + .queryParam("t", String.valueOf(timeout)); try { LOGGER.trace("POST: {}", webResource); - webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(); - } catch (UniformInterfaceException exception) { + webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON_TYPE)); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such container %s", containerId)); } else if (exception.getResponse().getStatus() == 204) { diff --git a/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java b/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java index 6be29606..7d0bca70 100644 --- a/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java @@ -2,6 +2,8 @@ import java.util.List; +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -10,9 +12,7 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.SearchItem; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.GenericType; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; /** @@ -48,12 +48,12 @@ public String toString() { } protected List impl() { - WebResource webResource = baseResource.path("/images/search").queryParam("term", term); + WebTarget webResource = baseResource.path("/images/search").queryParam("term", term); try { LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() { - }); - } catch (UniformInterfaceException exception) { + return webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 500) { throw new DockerException("Server error.", exception); } else { diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index b116d8da..1b2534e6 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -1,5 +1,7 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.client.Invocation; import javax.ws.rs.core.MediaType; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -12,9 +14,9 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.WebResource.Builder; +import javax.ws.rs.client.WebTarget; + +import static javax.ws.rs.client.Entity.entity; /** * Run a container @@ -156,16 +158,16 @@ public String toString() { } protected Void impl() throws DockerException { - WebResource webResource = baseResource.path(String.format( - "/containers/%s/start", containerId)); + WebTarget webResource = baseResource.path( + "/containers/{id}/start").resolveTemplate("id", containerId); try { LOGGER.trace("POST: {}", webResource); - Builder builder = webResource.accept(MediaType.APPLICATION_JSON); + Invocation.Builder builder = webResource.request().accept(MediaType.APPLICATION_JSON); - builder.type(MediaType.APPLICATION_JSON).post(this); + builder.post(entity(this, MediaType.APPLICATION_JSON)); - } catch (UniformInterfaceException exception) { + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format( "No such container %s", containerId)); diff --git a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java index 69f45391..7bb0699d 100644 --- a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java @@ -1,5 +1,7 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -7,8 +9,9 @@ import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; + +import static javax.ws.rs.client.Entity.entity; /** * Stop a running container. @@ -58,13 +61,13 @@ public String toString() { } protected Void impl() throws DockerException { - WebResource webResource = baseResource.path(String.format("/containers/%s/stop", containerId)) + WebTarget webResource = baseResource.path("/containers/{id}/stop").resolveTemplate("id", containerId) .queryParam("t", String.valueOf(timeout)); try { LOGGER.trace("POST: {}", webResource); - webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(); - } catch (UniformInterfaceException exception) { + webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON)); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { LOGGER.warn("No such container {}", containerId); } else if(exception.getResponse().getStatus() == 304) { diff --git a/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java b/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java index 8b1f281c..e24f499d 100644 --- a/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java @@ -1,5 +1,7 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.slf4j.Logger; @@ -7,10 +9,10 @@ import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.MultivaluedMapImpl; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import static javax.ws.rs.client.Entity.entity; /** @@ -92,20 +94,16 @@ public String toString() { } protected Integer impl() { - - MultivaluedMap params = new MultivaluedMapImpl(); - params.add("repo", repository); - params.add("tag", tag); - params.add("force", force ? "1" : "0"); - - WebResource webResource = baseResource.path("/images/" + imageId + "/tag").queryParams( - params); + WebTarget webResource = baseResource.path("/images/" + imageId + "/tag") + .queryParam("repo", repository) + .queryParam("tag", tag) + .queryParam("force", force ? "1" : "0"); try { LOGGER.trace("POST: {}", webResource); - ClientResponse resp = webResource.post(ClientResponse.class); + Response resp = webResource.request().post(entity(null, MediaType.APPLICATION_JSON), Response.class); return resp.getStatus(); - } catch (UniformInterfaceException exception) { + } catch (ClientErrorException exception) { throw new DockerException(exception); } } diff --git a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java index fde5f54e..ec0c108b 100644 --- a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import org.apache.commons.lang.StringUtils; @@ -9,8 +10,7 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; /** * @@ -59,15 +59,15 @@ public String toString() { } protected TopContainerResponse impl() throws DockerException { - WebResource webResource = baseResource.path(String.format("/containers/%s/top", containerId)); + WebTarget webResource = baseResource.path("/containers/{id}/top").resolveTemplate("id", containerId); if(!StringUtils.isEmpty(psArgs)) webResource = webResource.queryParam("ps_args", psArgs); try { LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(TopContainerResponse.class); - } catch (UniformInterfaceException exception) { + return webResource.request().accept(MediaType.APPLICATION_JSON).get(TopContainerResponse.class); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such container %s", containerId)); } else if (exception.getResponse().getStatus() == 500) { diff --git a/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java index 9e75540c..2b348805 100644 --- a/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java @@ -1,5 +1,7 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -7,9 +9,8 @@ import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; /** * Unpause a container. @@ -45,14 +46,14 @@ public String toString() { } protected Integer impl() throws DockerException { - WebResource webResource = baseResource.path(String.format("/containers/%s/unpause", containerId)); + WebTarget webResource = baseResource.path("/containers/{id}/unpause").resolveTemplate("id", containerId); - ClientResponse response = null; + Response response = null; try { LOGGER.trace("POST: {}", webResource); - response = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ClientResponse.class); - } catch (UniformInterfaceException exception) { + response = webResource.request().accept(MediaType.APPLICATION_JSON).post(Entity.entity(Response.class, MediaType.APPLICATION_JSON)); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { LOGGER.warn("No such container {}", containerId); } else if (exception.getResponse().getStatus() == 204) { diff --git a/src/main/java/com/github/dockerjava/client/command/VersionCmd.java b/src/main/java/com/github/dockerjava/client/command/VersionCmd.java index c1809e4e..5ad8c961 100644 --- a/src/main/java/com/github/dockerjava/client/command/VersionCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/VersionCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -7,8 +8,7 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Version; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; /** @@ -25,12 +25,12 @@ public String toString() { } protected Version impl() throws DockerException { - WebResource webResource = baseResource.path("/version"); + WebTarget webResource = baseResource.path("/version"); try { LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(Version.class); - } catch (UniformInterfaceException exception) { + return webResource.request().accept(MediaType.APPLICATION_JSON).get(Version.class); + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 500) { throw new DockerException("Server error.", exception); } else { diff --git a/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java index 653a86db..1ddbee86 100644 --- a/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.client.command; +import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; @@ -9,8 +10,9 @@ import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; +import javax.ws.rs.client.WebTarget; + +import static javax.ws.rs.client.Entity.entity; /** * Wait for a container to exit and print its exit code @@ -41,13 +43,13 @@ public String toString() { } protected Integer impl() throws DockerException { - WebResource webResource = baseResource.path(String.format("/containers/%s/wait", containerId)); + WebTarget webResource = baseResource.path("/containers/{id}/wait").resolveTemplate("id", containerId); try { LOGGER.trace("POST: {}", webResource); - ObjectNode ObjectNode = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ObjectNode.class); + ObjectNode ObjectNode = webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON), ObjectNode.class); return ObjectNode.get("StatusCode").asInt(); - } catch (UniformInterfaceException exception) { + } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 404) { throw new NotFoundException(String.format("No such container %s", containerId)); } else if (exception.getResponse().getStatus() == 500) { diff --git a/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java b/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java index a29255d3..31b51845 100644 --- a/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java +++ b/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java @@ -1,26 +1,25 @@ package com.github.dockerjava.client.utils; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.filter.ClientFilter; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.core.MediaType; +import java.io.IOException; /** * * @author Konstantin Pelykh (kpelykh@gmail.com) * */ -public class JsonClientFilter extends ClientFilter { +public class JsonClientFilter implements ClientResponseFilter { - public ClientResponse handle(ClientRequest cr) { - // Call the next filter - ClientResponse resp = getNext().handle(cr); - String respContentType = resp.getHeaders().getFirst("Content-Type"); - if (respContentType != null && respContentType.startsWith("text/plain")) { - String newContentType = "application/json" + respContentType.substring(10); - resp.getHeaders().putSingle("Content-Type", newContentType); + + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { + if (responseContext.getMediaType() != null && responseContext.getMediaType().isCompatible(MediaType.TEXT_PLAIN_TYPE)) { + String newContentType = "application/json" + responseContext.getMediaType().toString().substring(10); + responseContext.getHeaders().putSingle("Content-Type", newContentType); } - return resp; } - } diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 21c78e54..918d51ee 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -2,13 +2,13 @@ import com.github.dockerjava.client.DockerClient; import com.github.dockerjava.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 javax.ws.rs.core.Response; import java.io.IOException; import java.lang.reflect.Method; import java.net.DatagramSocket; @@ -82,7 +82,7 @@ public void afterMethod(ITestResult result) { result.getName()); } - protected String logResponseStream(ClientResponse response) { + protected String logResponseStream(Response response) { String responseString; try { responseString = DockerClient.asString(response); diff --git a/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java b/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java index 608d8453..fd451382 100644 --- a/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java @@ -3,12 +3,12 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerClient; import com.github.dockerjava.client.DockerException; -import com.sun.jersey.api.client.UniformInterfaceException; import org.hamcrest.Matchers; import org.testng.ITestResult; import org.testng.annotations.*; +import javax.ws.rs.ClientErrorException; import java.lang.reflect.Method; import static org.hamcrest.MatcherAssert.assertThat; @@ -46,8 +46,8 @@ public void testAuthInvalid() throws Exception { new DockerClient().authCmd().exec(); fail("Expected a DockerException caused by a bad password."); } catch (DockerException e) { - assertThat(e.getCause(), Matchers.instanceOf(UniformInterfaceException.class)); - assertEquals(((UniformInterfaceException) e.getCause()).getResponse().getStatus(), 401); + assertThat(e.getCause(), Matchers.instanceOf(ClientErrorException.class)); + assertEquals(((ClientErrorException) e.getCause()).getResponse().getStatus(), 401); } } } diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java index 17934c06..bec60309 100644 --- a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java @@ -10,12 +10,14 @@ import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.io.StringWriter; import java.lang.reflect.Method; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang.StringUtils; +import org.glassfish.jersey.client.ClientResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -25,7 +27,8 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.sun.jersey.api.client.ClientResponse; + +import javax.ws.rs.core.Response; public class BuildImageCmdTest extends AbstractDockerClientTest { @@ -55,20 +58,21 @@ public void testNginxDockerfileBuilder() throws DockerException, File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("nginx").getFile()); - ClientResponse response = dockerClient.buildImageCmd(baseDir).exec(); + Response response = dockerClient.buildImageCmd(baseDir).exec(); StringWriter logwriter = new StringWriter(); + InputStream is = response.readEntity(InputStream.class); try { - LineIterator itr = IOUtils.lineIterator( - response.getEntityInputStream(), "UTF-8"); + LineIterator itr = IOUtils.lineIterator( + is, "UTF-8"); while (itr.hasNext()) { String line = itr.next(); logwriter.write(line + "\n"); LOG.info(line); } } finally { - IOUtils.closeQuietly(response.getEntityInputStream()); + IOUtils.closeQuietly(is); } String fullLog = logwriter.toString(); @@ -115,20 +119,21 @@ private String dockerfileBuild(File baseDir, String expectedText) throws DockerException, IOException { // Build image - ClientResponse response = dockerClient.buildImageCmd(baseDir).exec(); + Response response = dockerClient.buildImageCmd(baseDir).exec(); StringWriter logwriter = new StringWriter(); + InputStream is = response.readEntity(InputStream.class); try { - LineIterator itr = IOUtils.lineIterator( - response.getEntityInputStream(), "UTF-8"); + LineIterator itr = IOUtils.lineIterator( + is, "UTF-8"); while (itr.hasNext()) { String line = itr.next(); logwriter.write(line + "\n"); LOG.info(line); } } finally { - IOUtils.closeQuietly(response.getEntityInputStream()); + IOUtils.closeQuietly(is); } String fullLog = logwriter.toString(); @@ -150,7 +155,7 @@ private String dockerfileBuild(File baseDir, String expectedText) tmpContainers.add(container.getId()); // Log container - ClientResponse logResponse = logContainer(container + Response logResponse = logContainer(container .getId()); assertThat(logResponseStream(logResponse), containsString(expectedText)); @@ -159,7 +164,7 @@ private String dockerfileBuild(File baseDir, String expectedText) } - private ClientResponse logContainer(String containerId) { + private Response logContainer(String containerId) { return dockerClient.logContainerCmd(containerId).withStdErr().withStdOut().exec(); } @@ -169,20 +174,21 @@ public void testNetCatDockerfileBuilder() throws DockerException, File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("netcat").getFile()); - ClientResponse response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); + Response response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); StringWriter logwriter = new StringWriter(); + InputStream is = response.readEntity(InputStream.class); try { - LineIterator itr = IOUtils.lineIterator( - response.getEntityInputStream(), "UTF-8"); + LineIterator itr = IOUtils.lineIterator( + is, "UTF-8"); while (itr.hasNext()) { String line = itr.next(); logwriter.write(line + "\n"); LOG.info(line); } } finally { - IOUtils.closeQuietly(response.getEntityInputStream()); + IOUtils.closeQuietly(is); } String fullLog = logwriter.toString(); diff --git a/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java index 4ef73988..3d6f6ff3 100644 --- a/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java @@ -1,10 +1,10 @@ package com.github.dockerjava.client.command; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.sun.jersey.api.client.ClientResponse; import org.testng.ITestResult; import org.testng.annotations.*; +import javax.ws.rs.core.Response; import java.lang.reflect.Method; import static org.hamcrest.Matchers.*; @@ -46,7 +46,7 @@ public void copyFromContainer() { dockerClient.startContainerCmd(container.getId()).exec(); tmpContainers.add(container.getId()); - ClientResponse response = dockerClient.copyFileFromContainerCmd(container.getId(), "/test").exec(); + Response response = dockerClient.copyFileFromContainerCmd(container.getId(), "/test").exec(); assertTrue(response.getStatus() == 200 && response.hasEntity(), "The file was not copied from the container."); } } diff --git a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java index 43c54d22..f09de8e2 100644 --- a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java @@ -18,7 +18,8 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; -import com.sun.jersey.api.client.ClientResponse; + +import javax.ws.rs.core.Response; public class LogContainerCmdTest extends AbstractDockerClientTest { @@ -60,7 +61,7 @@ public void logContainer() throws DockerException, IOException { assertThat(exitCode, equalTo(0)); - ClientResponse response = dockerClient.logContainerCmd(container.getId()).withStdErr().withStdOut().exec(); + Response response = dockerClient.logContainerCmd(container.getId()).withStdErr().withStdOut().exec(); assertThat(logResponseStream(response), endsWith(snippet)); } diff --git a/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java index 0472720d..fd1d0935 100644 --- a/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java @@ -18,7 +18,8 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Info; -import com.sun.jersey.api.client.ClientResponse; + +import javax.ws.rs.core.Response; public class PullImageCmdTest extends AbstractDockerClientTest { @@ -70,7 +71,7 @@ public void testPullImage() throws DockerException, IOException { LOG.info("Pulling image: {}", testImage); tmpImgs.add(testImage); - ClientResponse response = dockerClient.pullImageCmd(testImage).exec(); + Response response = dockerClient.pullImageCmd(testImage).exec(); assertThat(logResponseStream(response), containsString("Download complete")); From 63c41b8cc8cbb68643e2149dc2831feaed7147c8 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 7 Aug 2014 22:51:46 +0200 Subject: [PATCH 077/452] Refactored error handling --- .../{client => api}/BadRequestException.java | 3 +- .../dockerjava/api/ConflictException.java | 23 +++++ .../DockerClientException.java | 2 +- .../{client => api}/DockerException.java | 2 +- .../InternalServerErrorException.java | 2 +- .../NotAcceptableException.java | 2 +- .../{client => api}/NotFoundException.java | 2 +- .../{client => api}/NotModifiedException.java | 2 +- .../dockerjava/client/DockerClient.java | 8 +- .../client/command/AbstrDockerCmd.java | 32 ++++--- .../client/command/AttachContainerCmd.java | 5 +- .../dockerjava/client/command/AuthCmd.java | 2 +- .../client/command/BuildImgCmd.java | 4 +- .../dockerjava/client/command/CommitCmd.java | 4 +- .../client/command/ContainerDiffCmd.java | 6 +- .../command/CopyFileFromContainerCmd.java | 4 +- .../client/command/CreateContainerCmd.java | 18 ++-- .../dockerjava/client/command/InfoCmd.java | 2 +- .../client/command/InspectContainerCmd.java | 4 +- .../client/command/InspectImageCmd.java | 2 +- .../client/command/KillContainerCmd.java | 4 +- .../client/command/LogContainerCmd.java | 4 +- .../client/command/PauseContainerCmd.java | 37 ++++---- .../dockerjava/client/command/PingCmd.java | 31 ++++--- .../client/command/PullImageCmd.java | 28 ++---- .../client/command/PushImageCmd.java | 34 ++++--- .../client/command/RemoveContainerCmd.java | 88 +++++++++---------- .../client/command/RemoveImageCmd.java | 40 ++++----- .../client/command/RestartContainerCmd.java | 39 ++++---- .../client/command/SearchImagesCmd.java | 21 ++--- .../client/command/StartContainerCmd.java | 56 +++++------- .../client/command/StopContainerCmd.java | 41 ++++----- .../client/command/TagImageCmd.java | 24 ++--- .../client/command/TopContainerCmd.java | 32 +++---- .../client/command/UnpauseContainerCmd.java | 36 ++++---- .../dockerjava/client/command/VersionCmd.java | 15 +--- .../client/command/WaitContainerCmd.java | 30 +++---- .../client/AbstractDockerClientTest.java | 12 ++- .../dockerjava/client/DockerClientTest.java | 2 + .../client/command/AuthCmdTest.java | 2 +- .../client/command/BuildImageCmdTest.java | 26 +++--- .../client/command/CommitCmdTest.java | 2 +- .../client/command/ContainerDiffCmdTest.java | 6 +- .../command/CopyFileFromContainerCmdTest.java | 9 +- .../command/CreateContainerCmdTest.java | 29 +++++- .../client/command/InfoCmdTest.java | 2 +- .../client/command/KillContainerCmdTest.java | 2 +- .../client/command/ListContainersCmdTest.java | 2 +- .../client/command/ListImagesCmdTest.java | 2 +- .../client/command/LogContainerCmdTest.java | 6 +- .../client/command/PullImageCmdTest.java | 6 +- .../client/command/PushImageCmdTest.java | 2 +- .../command/RemoveContainerCmdTest.java | 3 +- .../client/command/RemoveImageCmdTest.java | 8 +- .../command/RestartContainerCmdTest.java | 2 +- .../client/command/SearchImagesCmdTest.java | 2 +- .../client/command/StartContainerCmdTest.java | 8 +- .../client/command/StopContainerCmdTest.java | 2 +- .../client/command/TagImageCmdTest.java | 11 +-- .../client/command/VersionCmdTest.java | 2 +- .../client/command/WaitContainerCmdTest.java | 2 +- 61 files changed, 407 insertions(+), 432 deletions(-) rename src/main/java/com/github/dockerjava/{client => api}/BadRequestException.java (91%) create mode 100644 src/main/java/com/github/dockerjava/api/ConflictException.java rename src/main/java/com/github/dockerjava/{client => api}/DockerClientException.java (89%) rename src/main/java/com/github/dockerjava/{client => api}/DockerException.java (93%) rename src/main/java/com/github/dockerjava/{client => api}/InternalServerErrorException.java (92%) rename src/main/java/com/github/dockerjava/{client => api}/NotAcceptableException.java (92%) rename src/main/java/com/github/dockerjava/{client => api}/NotFoundException.java (93%) rename src/main/java/com/github/dockerjava/{client => api}/NotModifiedException.java (91%) diff --git a/src/main/java/com/github/dockerjava/client/BadRequestException.java b/src/main/java/com/github/dockerjava/api/BadRequestException.java similarity index 91% rename from src/main/java/com/github/dockerjava/client/BadRequestException.java rename to src/main/java/com/github/dockerjava/api/BadRequestException.java index 276a7d19..1e04bcb3 100644 --- a/src/main/java/com/github/dockerjava/client/BadRequestException.java +++ b/src/main/java/com/github/dockerjava/api/BadRequestException.java @@ -1,4 +1,5 @@ -package com.github.dockerjava.client; +package com.github.dockerjava.api; + /** * diff --git a/src/main/java/com/github/dockerjava/api/ConflictException.java b/src/main/java/com/github/dockerjava/api/ConflictException.java new file mode 100644 index 00000000..bed2a375 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/ConflictException.java @@ -0,0 +1,23 @@ +package com.github.dockerjava.api; + + +/** + * + */ +public class ConflictException extends DockerException { + + private static final long serialVersionUID = -290093024775500239L; + + public ConflictException(String message, Throwable cause) { + super(message, 409, cause); + } + + public ConflictException(String message) { + this(message, null); + } + + public ConflictException(Throwable cause) { + this(cause.getMessage(), cause); + } + +} diff --git a/src/main/java/com/github/dockerjava/client/DockerClientException.java b/src/main/java/com/github/dockerjava/api/DockerClientException.java similarity index 89% rename from src/main/java/com/github/dockerjava/client/DockerClientException.java rename to src/main/java/com/github/dockerjava/api/DockerClientException.java index 3b322e93..85efc349 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClientException.java +++ b/src/main/java/com/github/dockerjava/api/DockerClientException.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client; +package com.github.dockerjava.api; /** * diff --git a/src/main/java/com/github/dockerjava/client/DockerException.java b/src/main/java/com/github/dockerjava/api/DockerException.java similarity index 93% rename from src/main/java/com/github/dockerjava/client/DockerException.java rename to src/main/java/com/github/dockerjava/api/DockerException.java index d60c15c8..673bf2cc 100644 --- a/src/main/java/com/github/dockerjava/client/DockerException.java +++ b/src/main/java/com/github/dockerjava/api/DockerException.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client; +package com.github.dockerjava.api; diff --git a/src/main/java/com/github/dockerjava/client/InternalServerErrorException.java b/src/main/java/com/github/dockerjava/api/InternalServerErrorException.java similarity index 92% rename from src/main/java/com/github/dockerjava/client/InternalServerErrorException.java rename to src/main/java/com/github/dockerjava/api/InternalServerErrorException.java index 8f4b11c9..366484e5 100644 --- a/src/main/java/com/github/dockerjava/client/InternalServerErrorException.java +++ b/src/main/java/com/github/dockerjava/api/InternalServerErrorException.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client; +package com.github.dockerjava.api; /** * diff --git a/src/main/java/com/github/dockerjava/client/NotAcceptableException.java b/src/main/java/com/github/dockerjava/api/NotAcceptableException.java similarity index 92% rename from src/main/java/com/github/dockerjava/client/NotAcceptableException.java rename to src/main/java/com/github/dockerjava/api/NotAcceptableException.java index 6f44f41f..affa4ce9 100644 --- a/src/main/java/com/github/dockerjava/client/NotAcceptableException.java +++ b/src/main/java/com/github/dockerjava/api/NotAcceptableException.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client; +package com.github.dockerjava.api; /** * diff --git a/src/main/java/com/github/dockerjava/client/NotFoundException.java b/src/main/java/com/github/dockerjava/api/NotFoundException.java similarity index 93% rename from src/main/java/com/github/dockerjava/client/NotFoundException.java rename to src/main/java/com/github/dockerjava/api/NotFoundException.java index 3c5f062c..10f328cd 100644 --- a/src/main/java/com/github/dockerjava/client/NotFoundException.java +++ b/src/main/java/com/github/dockerjava/api/NotFoundException.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client; +package com.github.dockerjava.api; /** * Indicates that the given entity does not exist. diff --git a/src/main/java/com/github/dockerjava/client/NotModifiedException.java b/src/main/java/com/github/dockerjava/api/NotModifiedException.java similarity index 91% rename from src/main/java/com/github/dockerjava/client/NotModifiedException.java rename to src/main/java/com/github/dockerjava/api/NotModifiedException.java index 6ff41b98..d521bae2 100644 --- a/src/main/java/com/github/dockerjava/client/NotModifiedException.java +++ b/src/main/java/com/github/dockerjava/api/NotModifiedException.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client; +package com.github.dockerjava.api; /** * diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java index f938edce..449a1b79 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ b/src/main/java/com/github/dockerjava/client/DockerClient.java @@ -5,6 +5,7 @@ import java.io.*; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.command.*; import org.apache.commons.io.IOUtils; @@ -18,7 +19,6 @@ import org.apache.http.impl.conn.PoolingClientConnectionManager; import com.github.dockerjava.client.model.AuthConfig; - import com.github.dockerjava.client.utils.JsonClientFilter; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; @@ -266,18 +266,18 @@ public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { /** * @return The output slurped into a string. */ - public static String asString(ClientResponse response) throws IOException { + public static String asString(InputStream response) throws IOException { StringWriter out = new StringWriter(); try { LineIterator itr = IOUtils.lineIterator( - response.getEntityInputStream(), "UTF-8"); + response, "UTF-8"); while (itr.hasNext()) { String line = itr.next(); out.write(line + (itr.hasNext() ? "\n" : "")); } } finally { - closeQuietly(response.getEntityInputStream()); + closeQuietly(response); } return out.toString(); } diff --git a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java index 79ac941a..65f30026 100644 --- a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java @@ -3,12 +3,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.BadRequestException; -import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.InternalServerErrorException; -import com.github.dockerjava.client.NotAcceptableException; -import com.github.dockerjava.client.NotFoundException; -import com.github.dockerjava.client.NotModifiedException; +import com.github.dockerjava.api.BadRequestException; +import com.github.dockerjava.api.ConflictException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.InternalServerErrorException; +import com.github.dockerjava.api.NotAcceptableException; +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.NotModifiedException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -27,8 +28,11 @@ public T withBaseResource(WebResource baseResource) { protected abstract RES_T impl(); + /** + * @throws DockerException If something gets wrong + */ @Override - public RES_T exec() { + public RES_T exec() throws DockerException { Preconditions.checkNotNull(baseResource, "baseResource was not specified"); LOGGER.debug("Cmd: {}", this); @@ -37,12 +41,14 @@ public RES_T exec() { } catch (UniformInterfaceException exception) { int status = exception.getResponse().getStatus(); switch(status) { - case 304: throw new NotModifiedException(exception.getMessage(), exception); - case 400: throw new BadRequestException(exception.getMessage(), exception); - case 404: throw new NotFoundException(exception.getMessage(), exception); - case 406: throw new NotAcceptableException(exception.getMessage(), exception); - case 500: throw new InternalServerErrorException(exception.getMessage(), exception); - default: throw toDockerException(exception); + case 204: return null; + case 304: throw new NotModifiedException(exception); + case 400: throw new BadRequestException(exception); + case 404: throw new NotFoundException(exception); + case 406: throw new NotAcceptableException(exception); + case 409: throw new ConflictException(exception); + case 500: throw new InternalServerErrorException(exception); + default: throw toDockerException(exception); } } } diff --git a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java index 12e100e5..5ee1a1db 100644 --- a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java @@ -8,7 +8,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; @@ -30,8 +30,7 @@ * - true or false, if true, print timestamps for every log line. * Defaults to false. */ -public class AttachContainerCmd extends - AbstrDockerCmd { +public class AttachContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory .getLogger(AttachContainerCmd.class); diff --git a/src/main/java/com/github/dockerjava/client/command/AuthCmd.java b/src/main/java/com/github/dockerjava/client/command/AuthCmd.java index 119ff217..3ee1221b 100644 --- a/src/main/java/com/github/dockerjava/client/command/AuthCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AuthCmd.java @@ -5,7 +5,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.model.AuthConfig; import com.sun.jersey.api.client.WebResource; diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java index 73793786..0699bfa5 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java @@ -20,8 +20,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerClientException; -import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.api.DockerClientException; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.utils.CompressArchiveUtil; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; diff --git a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java index 90861363..6da0a3ea 100644 --- a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CommitCmd.java @@ -4,6 +4,8 @@ import javax.ws.rs.core.MultivaluedMap; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.client.model.ExposedPorts; import com.github.dockerjava.client.model.Volumes; @@ -12,8 +14,6 @@ import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; diff --git a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java b/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java index ebe49d54..ec7a6319 100644 --- a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java @@ -7,9 +7,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.InternalServerErrorException; -import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.InternalServerErrorException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.client.model.ChangeLog; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.GenericType; diff --git a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java index 89ac1ff4..e08e697b 100644 --- a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java @@ -10,8 +10,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java index 86973c24..f63d1b8a 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/CreateContainerCmd.java @@ -3,16 +3,18 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.dockerjava.client.model.*; - import org.apache.commons.lang.builder.ToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.NotAcceptableException; -import com.github.dockerjava.client.NotFoundException; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.dockerjava.api.ConflictException; +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.client.model.ExposedPort; +import com.github.dockerjava.client.model.ExposedPorts; +import com.github.dockerjava.client.model.Volume; +import com.github.dockerjava.client.model.Volumes; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; @@ -259,10 +261,10 @@ public String toString() { /** * @throws NotFoundException No such container - * @throws NotAcceptableException Impossible to attach (container not running) + * @throws ConflictException Named container already exists */ @Override - public CreateContainerResponse exec() throws NotFoundException, NotAcceptableException { + public CreateContainerResponse exec() throws NotFoundException, ConflictException { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/client/command/InfoCmd.java b/src/main/java/com/github/dockerjava/client/command/InfoCmd.java index 75c03e63..09f256bf 100644 --- a/src/main/java/com/github/dockerjava/client/command/InfoCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InfoCmd.java @@ -5,7 +5,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.model.Info; import com.sun.jersey.api.client.WebResource; diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java index c49250d3..f0353c5f 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java @@ -5,8 +5,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; diff --git a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java index 9fb68b56..fecf0f42 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java @@ -5,7 +5,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; diff --git a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java index da68c393..58bd90d9 100644 --- a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java @@ -5,8 +5,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; diff --git a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java index 69f0b469..a4c39272 100644 --- a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java @@ -8,8 +8,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; diff --git a/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java index a4508369..994ee6e6 100644 --- a/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PauseContainerCmd.java @@ -5,10 +5,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** @@ -17,7 +17,7 @@ * @param containerId - Id of the container * */ -public class PauseContainerCmd extends AbstrDockerCmd { +public class PauseContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(PauseContainerCmd.class); @@ -43,28 +43,21 @@ public String toString() { .append(containerId) .toString(); } + + /** + * @throws NotFoundException No such container + */ + @Override + public Void exec() throws NotFoundException { + return super.exec(); + } - protected Integer impl() throws DockerException { + protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/pause", containerId)); - ClientResponse response = null; - - try { - LOGGER.trace("POST: {}", webResource); - response = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ClientResponse.class); - } 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 paused container {}", containerId); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } + LOGGER.trace("POST: {}", webResource); + webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ClientResponse.class); - return response.getStatus(); + return null; } } diff --git a/src/main/java/com/github/dockerjava/client/command/PingCmd.java b/src/main/java/com/github/dockerjava/client/command/PingCmd.java index e017617a..7bf0fb50 100644 --- a/src/main/java/com/github/dockerjava/client/command/PingCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PingCmd.java @@ -3,6 +3,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.dockerjava.api.DockerException; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -11,19 +12,23 @@ * Ping the Docker server * */ -public class PingCmd extends AbstrDockerCmd { +public class PingCmd extends AbstrDockerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(PingCmd.class); - - protected Integer impl() { - WebResource webResource = baseResource.path("/_ping"); + private static final Logger LOGGER = LoggerFactory.getLogger(PingCmd.class); - try { - LOGGER.trace("GET: {}", webResource); - ClientResponse resp = webResource.get(ClientResponse.class); - return resp.getStatus(); - } catch (UniformInterfaceException exception) { - return exception.getResponse().getStatus(); - } - } + /** + * A {@link DockerException} is thrown if something gets wrong + */ + @Override + public Void exec() { + return super.exec(); + } + + protected Void impl() { + WebResource webResource = baseResource.path("/_ping"); + + LOGGER.trace("GET: {}", webResource); + webResource.get(ClientResponse.class); + return null; + } } diff --git a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java b/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java index 83832c47..b595a77b 100644 --- a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java @@ -1,16 +1,15 @@ package com.github.dockerjava.client.command; +import java.io.InputStream; + import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; -import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; @@ -20,7 +19,7 @@ * Pull image from repository. * */ -public class PullImageCmd extends AbstrDockerCmd { +public class PullImageCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(PullImageCmd.class); @@ -68,15 +67,8 @@ public String toString() { .toString(); } - protected ClientResponse impl() { - Preconditions.checkNotNull(repository, "Repository was not specified"); - - if (StringUtils.countMatches(repository, ":") == 1) { - String repositoryTag[] = StringUtils.split(repository, ':'); - repository = repositoryTag[0]; - tag = repositoryTag[1]; - } + protected InputStream impl() { MultivaluedMap params = new MultivaluedMapImpl(); params.add("tag", tag); @@ -85,15 +77,7 @@ protected ClientResponse impl() { WebResource webResource = baseResource.path("/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); - } - } + LOGGER.trace("POST: {}", webResource); + return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ClientResponse.class).getEntityInputStream(); } } diff --git a/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java b/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java index 41cdc077..7ffc97ed 100644 --- a/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java @@ -1,14 +1,15 @@ package com.github.dockerjava.client.command; +import java.io.InputStream; + import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -17,7 +18,7 @@ * * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. */ -public class PushImageCmd extends AbstrAuthCfgDockerCmd { +public class PushImageCmd extends AbstrAuthCfgDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(PushImageCmd.class); @@ -46,19 +47,24 @@ public String toString() { .append(name) .toString(); } + + /** + * @throws NotFoundException No such image + */ + @Override + public InputStream exec() throws NotFoundException { + return super.exec(); + } - protected ClientResponse impl() { + protected InputStream impl() { WebResource webResource = baseResource.path("/images/" + name(name) + "/push"); - try { - final String registryAuth = registryAuth(); - LOGGER.trace("POST: {}", webResource); - return webResource - .header("X-Registry-Auth", registryAuth) - .accept(MediaType.APPLICATION_JSON) - .post(ClientResponse.class); - } catch (UniformInterfaceException e) { - throw new DockerException(e); - } + + final String registryAuth = registryAuth(); + LOGGER.trace("POST: {}", webResource); + return webResource + .header("X-Registry-Auth", registryAuth) + .accept(MediaType.APPLICATION_JSON) + .post(ClientResponse.class).getEntityInputStream(); } private String name(String name) { diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java index 3a12cd8e..a68e2bfc 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java @@ -6,20 +6,21 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** * Remove a container. - * + * * @param removeVolumes - true or false, Remove the volumes associated to the container. Defaults to false * @param force - true or false, Removes the container even if it was running. Defaults to false */ -public class RemoveContainerCmd extends AbstrDockerCmd { +public class RemoveContainerCmd extends AbstrDockerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(RemoveContainerCmd.class); + private static final Logger LOGGER = LoggerFactory + .getLogger(RemoveContainerCmd.class); private String containerId; @@ -29,19 +30,19 @@ public RemoveContainerCmd(String containerId) { withContainerId(containerId); } - public String getContainerId() { - return containerId; - } + public String getContainerId() { + return containerId; + } - public boolean hasRemoveVolumesEnabled() { - return removeVolumes; - } + public boolean hasRemoveVolumesEnabled() { + return removeVolumes; + } - public boolean hasForceEnabled() { - return force; - } + public boolean hasForceEnabled() { + return force; + } - public RemoveContainerCmd withContainerId(String containerId) { + public RemoveContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; @@ -61,39 +62,34 @@ public RemoveContainerCmd withForce(boolean force) { return this; } - @Override - public String toString() { - return new StringBuilder("rm ") - .append(removeVolumes ? "--volumes=true" : "") - .append(force ? "--force=true" : "") - .append(containerId) - .toString(); - } + @Override + public String toString() { + return new StringBuilder("rm ") + .append(removeVolumes ? "--volumes=true" : "") + .append(force ? "--force=true" : "").append(containerId) + .toString(); + } + + /** + * @throws NotFoundException No such container + */ + @Override + public Void exec() throws NotFoundException { + return super.exec(); + } protected Void impl() throws DockerException { - Preconditions.checkState(!StringUtils.isEmpty(containerId), "Container ID can't be empty"); - - WebResource webResource = baseResource.path("/containers/" + containerId).queryParam("v", removeVolumes ? "1" : "0").queryParam("force", force ? "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); - } - } + Preconditions.checkState(!StringUtils.isEmpty(containerId), + "Container ID can't be empty"); + + WebResource webResource = baseResource + .path("/containers/" + containerId) + .queryParam("v", removeVolumes ? "1" : "0") + .queryParam("force", force ? "1" : "0"); + + LOGGER.trace("DELETE: {}", webResource); + String response = webResource.accept(MediaType.APPLICATION_JSON).delete(String.class); + LOGGER.trace("Response: {}", response); return null; } diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java b/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java index 49707d51..d1a23fb0 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java @@ -4,10 +4,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** @@ -67,32 +67,24 @@ public String toString() { .append(imageId) .toString(); } + + /** + * @throws NotFoundException No such image + */ + @Override + public Void exec() throws NotFoundException { + return super.exec(); + } protected Void impl() throws DockerException { Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty"); + + WebResource webResource = baseResource.path("/images/" + imageId) + .queryParam("force", force ? "1" : "0") + .queryParam("noprune", noPrune ? "1" : "0"); - try { - WebResource webResource = baseResource.path("/images/" + imageId) - .queryParam("force", force ? "1" : "0").queryParam("noprune", noPrune ? "1" : "0"); - - LOGGER.trace("DELETE: {}", webResource); - webResource.delete(ClientResponse.class); - - - } 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); - } - } + LOGGER.trace("DELETE: {}", webResource); + webResource.delete(ClientResponse.class); return null; } diff --git a/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java index 8a383af2..3c368a17 100644 --- a/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java @@ -5,10 +5,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** @@ -56,27 +55,23 @@ public String toString() { .append(containerId) .toString(); } + + /** + * @throws NotFoundException No such container + */ + @Override + public Void exec() throws NotFoundException { + return super.exec(); + } protected Void impl() throws DockerException { - WebResource webResource = baseResource.path(String.format("/containers/%s/restart", 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) { - 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); - } - } - + WebResource webResource = baseResource.path( + String.format("/containers/%s/restart", containerId)) + .queryParam("t", String.valueOf(timeout)); + + LOGGER.trace("POST: {}", webResource); + webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(); + return null; } } diff --git a/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java b/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java index 6be29606..a34e3365 100644 --- a/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java @@ -7,17 +7,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.SearchItem; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.GenericType; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; - /** + * Search images * - * + * @param term - search trem * */ public class SearchImagesCmd extends AbstrDockerCmd> { @@ -49,16 +47,9 @@ public String toString() { protected List impl() { WebResource webResource = baseResource.path("/images/search").queryParam("term", term); - try { - LOGGER.trace("GET: {}", webResource); - 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); - } - } + + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); } } diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index b116d8da..c5a13637 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -2,19 +2,23 @@ import javax.ws.rs.core.MediaType; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.dockerjava.client.model.*; import org.apache.commons.lang.builder.ToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.NotFoundException; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.NotModifiedException; +import com.github.dockerjava.client.model.Bind; +import com.github.dockerjava.client.model.Binds; +import com.github.dockerjava.client.model.Link; +import com.github.dockerjava.client.model.Links; +import com.github.dockerjava.client.model.LxcConf; +import com.github.dockerjava.client.model.Ports; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.WebResource.Builder; /** * Run a container @@ -154,35 +158,23 @@ public StartContainerCmd withContainerId(String containerId) { public String toString() { return ToStringBuilder.reflectionToString(this).toString(); } + + /** + * @throws NotFoundException No such container + * @throws NotModifiedException Container already started + */ + @Override + public Void exec() throws NotFoundException, NotModifiedException { + return super.exec(); + } protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format( "/containers/%s/start", containerId)); - - try { - LOGGER.trace("POST: {}", webResource); - Builder builder = webResource.accept(MediaType.APPLICATION_JSON); - - builder.type(MediaType.APPLICATION_JSON).post(this); - - } catch (UniformInterfaceException exception) { - if (exception.getResponse().getStatus() == 404) { - throw new NotFoundException(String.format( - "No such container %s", containerId)); - } else if (exception.getResponse().getStatus() == 304) { - // no error - LOGGER.warn("Container already started {}", containerId); - } else if (exception.getResponse().getStatus() == 204) { - // no error - LOGGER.trace("Successfully started container {}", containerId); - } else if (exception.getResponse().getStatus() == 500) { - LOGGER.error("", exception); - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } - + + LOGGER.trace("POST: {}", webResource); + webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(this); + return null; } diff --git a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java index 69f45391..8df2da37 100644 --- a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java @@ -5,9 +5,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.NotModifiedException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** @@ -56,29 +57,23 @@ public String toString() { .append(containerId) .toString(); } + + /** + * @throws NotFoundException No such container + * @throws NotModifiedException Container already stopped + */ + @Override + public Void exec() throws NotFoundException, NotModifiedException { + return super.exec(); + } protected Void impl() throws DockerException { - WebResource webResource = baseResource.path(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() == 304) { - //no error - LOGGER.warn("Container already stopped {}", 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); - } - } + WebResource webResource = baseResource.path( + String.format("/containers/%s/stop", containerId)).queryParam( + "t", String.valueOf(timeout)); + + LOGGER.trace("POST: {}", webResource); + webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(); return null; } diff --git a/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java b/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java index 8b1f281c..ae96072d 100644 --- a/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java @@ -5,14 +5,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; - /** * Tag an image into a repository * @@ -24,7 +21,7 @@ * (not documented) * @return the HTTP status code (201 for success) */ -public class TagImageCmd extends AbstrDockerCmd { +public class TagImageCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(TagImageCmd.class); @@ -91,22 +88,19 @@ public String toString() { .toString(); } - protected Integer impl() { + protected Void impl() { MultivaluedMap params = new MultivaluedMapImpl(); params.add("repo", repository); params.add("tag", tag); params.add("force", force ? "1" : "0"); - WebResource webResource = baseResource.path("/images/" + imageId + "/tag").queryParams( - params); - - try { - LOGGER.trace("POST: {}", webResource); - ClientResponse resp = webResource.post(ClientResponse.class); - return resp.getStatus(); - } catch (UniformInterfaceException exception) { - throw new DockerException(exception); - } + WebResource webResource = baseResource + .path("/images/" + imageId + "/tag") + .queryParams(params); + + LOGGER.trace("POST: {}", webResource); + webResource.post(ClientResponse.class); + return null; } } diff --git a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java index fde5f54e..ccecf28b 100644 --- a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java @@ -6,15 +6,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** - * - * @author marcus + * List processes running inside a container * */ public class TopContainerCmd extends AbstrDockerCmd { @@ -58,23 +56,21 @@ public String toString() { .toString(); } + /** + * @throws NotFoundException No such container + */ + @Override + public TopContainerResponse exec() throws NotFoundException { + return super.exec(); + } + protected TopContainerResponse impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/top", containerId)); if(!StringUtils.isEmpty(psArgs)) webResource = webResource.queryParam("ps_args", psArgs); - - try { - LOGGER.trace("GET: {}", webResource); - return webResource.accept(MediaType.APPLICATION_JSON).get(TopContainerResponse.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); - } - } + + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(TopContainerResponse.class); } } diff --git a/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java index 9e75540c..18b65d31 100644 --- a/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java @@ -5,10 +5,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** @@ -17,7 +17,7 @@ * @param containerId - Id of the container * */ -public class UnpauseContainerCmd extends AbstrDockerCmd { +public class UnpauseContainerCmd extends AbstrDockerCmd { private static final Logger LOGGER = LoggerFactory.getLogger(UnpauseContainerCmd.class); @@ -43,28 +43,22 @@ public String toString() { .append(containerId) .toString(); } + + /** + * @throws NotFoundException No such container + */ + @Override + public Void exec() throws NotFoundException { + return super.exec(); + } - protected Integer impl() throws DockerException { + protected Void impl() throws DockerException { WebResource webResource = baseResource.path(String.format("/containers/%s/unpause", containerId)); - ClientResponse response = null; - try { - LOGGER.trace("POST: {}", webResource); - response = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ClientResponse.class); - } 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 paused container {}", containerId); - } else if (exception.getResponse().getStatus() == 500) { - throw new DockerException("Server error", exception); - } else { - throw new DockerException(exception); - } - } + LOGGER.trace("POST: {}", webResource); + webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ClientResponse.class); - return response.getStatus(); + return null; } } diff --git a/src/main/java/com/github/dockerjava/client/command/VersionCmd.java b/src/main/java/com/github/dockerjava/client/command/VersionCmd.java index c1809e4e..78dda057 100644 --- a/src/main/java/com/github/dockerjava/client/command/VersionCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/VersionCmd.java @@ -5,9 +5,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.model.Version; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; @@ -27,15 +26,7 @@ public String toString() { protected Version impl() throws DockerException { WebResource webResource = baseResource.path("/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); - } - } + LOGGER.trace("GET: {}", webResource); + return webResource.accept(MediaType.APPLICATION_JSON).get(Version.class); } } diff --git a/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java index 653a86db..ce91eec1 100644 --- a/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java @@ -6,14 +6,14 @@ import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.github.dockerjava.client.DockerException; -import com.github.dockerjava.client.NotFoundException; +import com.github.dockerjava.api.DockerException; import com.google.common.base.Preconditions; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** - * Wait for a container to exit and print its exit code + * Wait a container + * + * Block until container stops, then returns the exit code */ public class WaitContainerCmd extends AbstrDockerCmd { @@ -40,23 +40,13 @@ public String toString() { return "wait " + containerId; } - protected Integer impl() throws DockerException { + protected Integer impl() { WebResource webResource = baseResource.path(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); - } + LOGGER.trace("POST: {}", webResource); + ObjectNode ObjectNode = webResource.accept(MediaType.APPLICATION_JSON) + .type(MediaType.APPLICATION_JSON).post(ObjectNode.class); + + return ObjectNode.get("StatusCode").asInt(); } } diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index caead681..652ca6bf 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -1,7 +1,7 @@ package com.github.dockerjava.client; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.DockerClient; -import com.github.dockerjava.client.DockerException; import com.sun.jersey.api.client.ClientResponse; import org.slf4j.Logger; @@ -10,6 +10,7 @@ import org.testng.ITestResult; import java.io.IOException; +import java.io.InputStream; import java.lang.reflect.Method; import java.net.DatagramSocket; import java.net.ServerSocket; @@ -34,7 +35,7 @@ public void beforeTest() throws DockerException { LOG.info("Pulling image 'busybox'"); // need to block until image is pulled completely - logResponseStream(dockerClient.pullImageCmd("busybox:latest").exec()); + logResponseStream(dockerClient.pullImageCmd("busybox").withTag("latest").exec()); @@ -62,6 +63,11 @@ public void afterMethod(ITestResult result) { try { dockerClient.stopContainerCmd(container).exec(); dockerClient.killContainerCmd(container).exec(); + } catch (DockerException ignore) { + //ignore.printStackTrace(); + } + + try { dockerClient.removeContainerCmd(container).exec(); } catch (DockerException ignore) { ignore.printStackTrace(); @@ -82,7 +88,7 @@ public void afterMethod(ITestResult result) { result.getName()); } - protected String logResponseStream(ClientResponse response) { + protected String logResponseStream(InputStream response) { String responseString; try { responseString = DockerClient.asString(response); diff --git a/src/test/java/com/github/dockerjava/client/DockerClientTest.java b/src/test/java/com/github/dockerjava/client/DockerClientTest.java index 9abac0b4..8278accf 100644 --- a/src/test/java/com/github/dockerjava/client/DockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/DockerClientTest.java @@ -5,7 +5,9 @@ import java.lang.reflect.Method; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.command.CreateContainerResponse; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; diff --git a/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java b/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java index 608d8453..628b1414 100644 --- a/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java @@ -1,8 +1,8 @@ package com.github.dockerjava.client.command; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerClient; -import com.github.dockerjava.client.DockerException; import com.sun.jersey.api.client.UniformInterfaceException; import org.hamcrest.Matchers; diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java index 17934c06..04adec3f 100644 --- a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java @@ -10,6 +10,7 @@ import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.io.StringWriter; import java.lang.reflect.Method; @@ -23,9 +24,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; -import com.sun.jersey.api.client.ClientResponse; public class BuildImageCmdTest extends AbstractDockerClientTest { @@ -55,20 +55,20 @@ public void testNginxDockerfileBuilder() throws DockerException, File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("nginx").getFile()); - ClientResponse response = dockerClient.buildImageCmd(baseDir).exec(); + InputStream response = dockerClient.buildImageCmd(baseDir).exec(); StringWriter logwriter = new StringWriter(); try { LineIterator itr = IOUtils.lineIterator( - response.getEntityInputStream(), "UTF-8"); + response, "UTF-8"); while (itr.hasNext()) { String line = itr.next(); logwriter.write(line + "\n"); LOG.info(line); } } finally { - IOUtils.closeQuietly(response.getEntityInputStream()); + IOUtils.closeQuietly(response); } String fullLog = logwriter.toString(); @@ -115,20 +115,20 @@ private String dockerfileBuild(File baseDir, String expectedText) throws DockerException, IOException { // Build image - ClientResponse response = dockerClient.buildImageCmd(baseDir).exec(); + InputStream response = dockerClient.buildImageCmd(baseDir).exec(); StringWriter logwriter = new StringWriter(); try { LineIterator itr = IOUtils.lineIterator( - response.getEntityInputStream(), "UTF-8"); + response, "UTF-8"); while (itr.hasNext()) { String line = itr.next(); logwriter.write(line + "\n"); LOG.info(line); } } finally { - IOUtils.closeQuietly(response.getEntityInputStream()); + IOUtils.closeQuietly(response); } String fullLog = logwriter.toString(); @@ -150,7 +150,7 @@ private String dockerfileBuild(File baseDir, String expectedText) tmpContainers.add(container.getId()); // Log container - ClientResponse logResponse = logContainer(container + InputStream logResponse = logContainer(container .getId()); assertThat(logResponseStream(logResponse), containsString(expectedText)); @@ -159,7 +159,7 @@ private String dockerfileBuild(File baseDir, String expectedText) } - private ClientResponse logContainer(String containerId) { + private InputStream logContainer(String containerId) { return dockerClient.logContainerCmd(containerId).withStdErr().withStdOut().exec(); } @@ -169,20 +169,20 @@ public void testNetCatDockerfileBuilder() throws DockerException, File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("netcat").getFile()); - ClientResponse response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); + InputStream response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); StringWriter logwriter = new StringWriter(); try { LineIterator itr = IOUtils.lineIterator( - response.getEntityInputStream(), "UTF-8"); + response, "UTF-8"); while (itr.hasNext()) { String line = itr.next(); logwriter.write(line + "\n"); LOG.info(line); } } finally { - IOUtils.closeQuietly(response.getEntityInputStream()); + IOUtils.closeQuietly(response); } String fullLog = logwriter.toString(); diff --git a/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java index 85bc6227..52885248 100644 --- a/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java @@ -16,8 +16,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; public class CommitCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java b/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java index 078d6382..ac7fdf02 100644 --- a/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java @@ -17,8 +17,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.ChangeLog; public class ContainerDiffCmdTest extends AbstractDockerClientTest { @@ -50,11 +50,11 @@ public void testDiff() throws DockerException { LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); - boolean add = tmpContainers.add(container.getId()); + tmpContainers.add(container.getId()); int exitCode = dockerClient.waitContainerCmd(container.getId()).exec(); assertThat(exitCode, equalTo(0)); - List filesystemDiff = dockerClient.containerDiffCmd(container.getId()).exec(); + List filesystemDiff = dockerClient.containerDiffCmd(container.getId()).exec(); LOG.info("Container DIFF: {}", filesystemDiff.toString()); assertThat(filesystemDiff.size(), equalTo(1)); diff --git a/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java index 4ef73988..29f47a15 100644 --- a/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java @@ -1,10 +1,11 @@ package com.github.dockerjava.client.command; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.sun.jersey.api.client.ClientResponse; + import org.testng.ITestResult; import org.testng.annotations.*; +import java.io.InputStream; import java.lang.reflect.Method; import static org.hamcrest.Matchers.*; @@ -33,7 +34,7 @@ public void afterMethod(ITestResult result) { } @Test - public void copyFromContainer() { + public void copyFromContainer() throws Exception { // TODO extract this into a shared method CreateContainerResponse container = dockerClient.createContainerCmd("busybox") .withName("docker-java-itest-copyFromContainer") @@ -46,7 +47,7 @@ public void copyFromContainer() { dockerClient.startContainerCmd(container.getId()).exec(); tmpContainers.add(container.getId()); - ClientResponse response = dockerClient.copyFileFromContainerCmd(container.getId(), "/test").exec(); - assertTrue(response.getStatus() == 200 && response.hasEntity(), "The file was not copied from the container."); + InputStream response = dockerClient.copyFileFromContainerCmd(container.getId(), "/test").exec(); + assertTrue(response.available() > 0, "The file was not copied from the container."); } } diff --git a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java index 56fc5ca9..69752e6f 100644 --- a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java @@ -3,7 +3,6 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; - import java.lang.reflect.Method; import java.util.Arrays; @@ -14,8 +13,9 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.ConflictException; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Volume; public class CreateContainerCmdTest extends AbstractDockerClientTest { @@ -102,6 +102,31 @@ public void createContainerWithHostname() throws DockerException { assertThat(logResponseStream(dockerClient.logContainerCmd(container.getId()).withStdOut().exec()), containsString("HOSTNAME=docker-java")); } + + @Test + public void createContainerWithName() throws DockerException { + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withName("container").withCmd("env").exec(); + + tmpContainers.add(container.getId()); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); + + assertThat(inspectContainerResponse.getName(), equalTo("/container")); + + + try { + dockerClient.createContainerCmd("busybox").withName("container").withCmd("env").exec(); + fail("Expected ConflictException"); + } catch (ConflictException e) { + } + + } } diff --git a/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java b/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java index 5ef90cd4..b8e0c048 100644 --- a/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java @@ -9,8 +9,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Info; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java index b1ff3027..47546407 100644 --- a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java @@ -17,8 +17,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; public class KillContainerCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java b/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java index 7c4332fc..83f3f42a 100644 --- a/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java @@ -22,8 +22,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Container; public class ListContainersCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java b/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java index 67e9a6a9..1e77f39a 100644 --- a/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java @@ -13,8 +13,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Image; import com.github.dockerjava.client.model.Info; diff --git a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java index 43c54d22..164dfde2 100644 --- a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java @@ -7,6 +7,7 @@ import static org.hamcrest.Matchers.not; import java.io.IOException; +import java.io.InputStream; import java.lang.reflect.Method; import org.testng.ITestResult; @@ -16,9 +17,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; -import com.sun.jersey.api.client.ClientResponse; public class LogContainerCmdTest extends AbstractDockerClientTest { @@ -60,7 +60,7 @@ public void logContainer() throws DockerException, IOException { assertThat(exitCode, equalTo(0)); - ClientResponse response = dockerClient.logContainerCmd(container.getId()).withStdErr().withStdOut().exec(); + InputStream response = dockerClient.logContainerCmd(container.getId()).withStdErr().withStdOut().exec(); assertThat(logResponseStream(response), endsWith(snippet)); } diff --git a/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java index 0472720d..8ee51568 100644 --- a/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java @@ -6,6 +6,7 @@ import static org.hamcrest.Matchers.notNullValue; import java.io.IOException; +import java.io.InputStream; import java.lang.reflect.Method; import org.testng.ITestResult; @@ -15,10 +16,9 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Info; -import com.sun.jersey.api.client.ClientResponse; public class PullImageCmdTest extends AbstractDockerClientTest { @@ -70,7 +70,7 @@ public void testPullImage() throws DockerException, IOException { LOG.info("Pulling image: {}", testImage); tmpImgs.add(testImage); - ClientResponse response = dockerClient.pullImageCmd(testImage).exec(); + InputStream response = dockerClient.pullImageCmd(testImage).exec(); assertThat(logResponseStream(response), containsString("Download complete")); diff --git a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java index d5e175e1..1c704347 100644 --- a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java @@ -18,8 +18,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; public class PushImageCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java index 4b614a48..d9b2855c 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java @@ -19,8 +19,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; public class RemoveContainerCmdTest extends AbstractDockerClientTest { @@ -54,7 +54,6 @@ public void removeContainer() throws DockerException { dockerClient.startContainerCmd(container.getId()).exec(); dockerClient.waitContainerCmd(container.getId()).exec(); - tmpContainers.add(container.getId()); LOG.info("Removing container: {}", container.getId()); dockerClient.removeContainerCmd(container.getId()).exec(); diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java index 5944d8f6..196a6dd5 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java @@ -20,8 +20,9 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; +import com.github.dockerjava.client.model.Container; public class RemoveImageCmdTest extends AbstractDockerClientTest { @@ -51,7 +52,7 @@ public void afterMethod(ITestResult result) { public void testRemoveImage() throws DockerException, InterruptedException { CreateContainerResponse container = dockerClient - .createContainerCmd("busybox").withCmd("touch", "/test").exec(); + .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); @@ -70,7 +71,8 @@ public void testRemoveImage() throws DockerException, InterruptedException { LOG.info("Removing image: {}", imageId); dockerClient.removeImageCmd(imageId).exec(); - List containers = dockerClient.listContainersCmd().withShowAll(true).exec(); + List containers = dockerClient.listContainersCmd().withShowAll(true).exec(); + Matcher matcher = not(hasItem(hasField("id", startsWith(imageId)))); assertThat(containers, matcher); } diff --git a/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java index c25784b9..ebce1ec8 100644 --- a/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java @@ -15,8 +15,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; public class RestartContainerCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/SearchImagesCmdTest.java b/src/test/java/com/github/dockerjava/client/command/SearchImagesCmdTest.java index 73ed9e35..584de5c3 100644 --- a/src/test/java/com/github/dockerjava/client/command/SearchImagesCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/SearchImagesCmdTest.java @@ -18,8 +18,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.SearchItem; public class SearchImagesCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java index 4ea95fec..5cb856fa 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -12,7 +12,9 @@ import java.lang.reflect.Method; import java.util.Arrays; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.model.*; + import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -21,7 +23,6 @@ import org.testng.annotations.Test; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; public class StartContainerCmdTest extends AbstractDockerClientTest { @@ -68,7 +69,6 @@ public void startContainerWithVolumes() throws DockerException { assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), contains("/opt/webapp1", "/opt/webapp2")); - dockerClient.startContainerCmd(container.getId()).withBinds(new Bind("/src/webapp1", volume1, true), new Bind("/src/webapp2", volume2)).exec(); dockerClient.waitContainerCmd(container.getId()).exec(); @@ -116,10 +116,10 @@ public void startContainerWithPortBindings() throws DockerException { contains(tcp22, tcp23)); assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp22), - is(equalTo(Ports.Binding("0.0.0.0", 11022)))); + is(equalTo(Ports.Binding(11022)))); assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23), - is(equalTo(Ports.Binding("0.0.0.0", 11023)))); + is(equalTo(Ports.Binding(11023)))); tmpContainers.add(container.getId()); } diff --git a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java index aeb8ed0d..0ecc82b5 100644 --- a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java @@ -17,8 +17,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; public class StopContainerCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java index 62fd1d09..12b538a4 100644 --- a/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java @@ -1,9 +1,5 @@ package com.github.dockerjava.client.command; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; - import java.lang.reflect.Method; import org.apache.commons.lang.math.RandomUtils; @@ -16,8 +12,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; public class TagImageCmdTest extends AbstractDockerClientTest { @@ -44,11 +40,10 @@ public void afterMethod(ITestResult result) { } @Test - public void testTagImage() throws DockerException, InterruptedException { + public void testTagImage() throws Exception { String tag = String.valueOf(RandomUtils.nextInt(Integer.MAX_VALUE)); - Integer result = dockerClient.tagImageCmd("busybox:latest", "docker-java/busybox", tag).exec(); - assertThat(result, equalTo(Integer.valueOf(201))); + dockerClient.tagImageCmd("busybox:latest", "docker-java/busybox", tag).exec(); dockerClient.removeImageCmd("docker-java/busybox:" + tag).exec(); } diff --git a/src/test/java/com/github/dockerjava/client/command/VersionCmdTest.java b/src/test/java/com/github/dockerjava/client/command/VersionCmdTest.java index 75d7c207..a808e488 100644 --- a/src/test/java/com/github/dockerjava/client/command/VersionCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/VersionCmdTest.java @@ -10,8 +10,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.Version; public class VersionCmdTest extends AbstractDockerClientTest { diff --git a/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java index fff08321..adc0f75d 100644 --- a/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java @@ -15,8 +15,8 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerException; public class WaitContainerCmdTest extends AbstractDockerClientTest { From 31662d5e7bba342471f2233f7d9e6dccb40aaa36 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 7 Aug 2014 23:20:49 +0200 Subject: [PATCH 078/452] Fix PushImageCmdTest --- .../github/dockerjava/client/command/PushImageCmdTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java index 1c704347..917c4b38 100644 --- a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java @@ -66,9 +66,10 @@ public void testPushLatest() throws Exception { logResponseStream(dockerClient.pushImageCmd(username + "/busybox").exec()); dockerClient.removeImageCmd(imageId).exec(); + + String response = asString(dockerClient.pullImageCmd(username + "/busybox").exec()); - // TODO This can fail intermittently if run with other tests. - assertThat(asString(dockerClient.pullImageCmd(username + "/busybox").exec()), not(containsString("404"))); + assertThat(response, not(containsString("HTTP code: 404"))); tmpImgs.add(username + "/busybox"); } From 061921485bc23ad1834eb175a45814ab76cd1f02 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 9 Aug 2014 20:52:50 +0200 Subject: [PATCH 079/452] Extracted command interfaces --- .../github/dockerjava/api/DockerClient.java | 118 ++++++ .../api/command/AttachContainerCmd.java | 61 +++ .../dockerjava/api/command/AuthCmd.java | 10 + .../dockerjava/api/command/BuildImageCmd.java | 35 ++ .../dockerjava/api/command/CommitCmd.java | 112 ++++++ .../api/command/ContainerDiffCmd.java | 25 ++ .../api/command/CopyFileFromContainerCmd.java | 26 ++ .../api/command/CreateContainerCmd.java | 102 +++++ .../command/CreateContainerResponse.java | 2 +- .../api/command/CreateImageCmd.java | 27 ++ .../command/CreateImageResponse.java | 2 +- .../{client => api}/command/DockerCmd.java | 2 +- .../dockerjava/api/command/InfoCmd.java | 7 + .../api/command/InspectContainerCmd.java | 16 + .../command/InspectContainerResponse.java | 2 +- .../api/command/InspectImageCmd.java | 19 + .../command/InspectImageResponse.java | 2 +- .../api/command/KillContainerCmd.java | 23 ++ .../api/command/ListContainersCmd.java | 39 ++ .../dockerjava/api/command/ListImagesCmd.java | 23 ++ .../api/command/LogContainerCmd.java | 61 +++ .../api/command/PauseContainerCmd.java | 22 ++ .../dockerjava/api/command/PingCmd.java | 10 + .../dockerjava/api/command/PullImageCmd.java | 24 ++ .../dockerjava/api/command/PushImageCmd.java | 26 ++ .../api/command/RemoveContainerCmd.java | 32 ++ .../api/command/RemoveImageCmd.java | 31 ++ .../api/command/RestartContainerCmd.java | 26 ++ .../api/command/SearchImagesCmd.java | 19 + .../api/command/StartContainerCmd.java | 57 +++ .../api/command/StopContainerCmd.java | 29 ++ .../dockerjava/api/command/TagImageCmd.java | 32 ++ .../api/command/TopContainerCmd.java | 23 ++ .../command/TopContainerResponse.java | 2 +- .../api/command/UnpauseContainerCmd.java | 22 ++ .../dockerjava/api/command/VersionCmd.java | 10 + .../api/command/WaitContainerCmd.java | 15 + .../dockerjava/client/DockerClient.java | 290 -------------- .../dockerjava/client/DockerClientConfig.java | 2 +- .../client/command/AbstrDockerCmd.java | 1 + .../client/command/CommandFactory.java | 40 -- .../client/command/DefaultCommandFactory.java | 163 -------- .../dockerjava/jaxrs1/JaxRs1Client.java | 358 ++++++++++++++++++ .../command/AttachContainerCommand.java} | 25 +- .../command/AuthCommand.java} | 10 +- .../command/BuildImageCommand.java} | 32 +- .../command/CommitCommand.java} | 156 +++++--- .../command/ContainerDiffCommand.java} | 20 +- .../CopyFileFromContainerCommand.java} | 30 +- .../command/CreateContainerCommand.java} | 141 ++++--- .../command/CreateImageCommand.java} | 29 +- .../command/InfoCommand.java} | 10 +- .../command/InspectContainerCommand.java} | 19 +- .../command/InspectImageCommand.java} | 19 +- .../command/KillContainerCommand.java} | 22 +- .../command/ListContainersCommand.java} | 30 +- .../command/ListImagesCommand.java} | 18 +- .../command/LogContainerCommand.java} | 42 +- .../command/PauseContainerCommand.java} | 16 +- .../command/PingCommand.java} | 18 +- .../command/PullImageCommand.java} | 24 +- .../command/PushImageCommand.java} | 16 +- .../command/RemoveContainerCommand.java} | 17 +- .../command/RemoveImageCommand.java} | 27 +- .../command/RestartContainerCommand.java} | 22 +- .../command/SearchImagesCommand.java} | 18 +- .../command/StartContainerCommand.java} | 30 +- .../command/StopContainerCommand.java} | 20 +- .../command/TagImageCommand.java} | 40 +- .../command/TopContainerCommand.java} | 24 +- .../command/UnpauseContainerCommand.java} | 16 +- .../command/VersionCommand.java} | 11 +- .../command/WaitContainerCommand.java} | 19 +- .../client/AbstractDockerClientTest.java | 7 +- .../JaxRs1ClientTest.java} | 9 +- .../command/AuthCommandTest.java} | 8 +- .../command/BuildImageCommandTest.java} | 11 +- .../command/CommitCommandTest.java} | 6 +- .../command/ContainerDiffCommandTest.java} | 5 +- .../CopyFileFromContainerCommandTest.java} | 5 +- .../command/CreateContainerCommandTest.java} | 6 +- .../command/InfoCommandTest.java} | 5 +- .../command/KillContainerCommandTest.java} | 8 +- .../command/ListContainersCommandTest.java} | 6 +- .../command/ListImagesCommandTest.java} | 4 +- .../command/LogContainerCommandTest.java} | 5 +- .../command/PullImageCommandTest.java} | 5 +- .../command/PushImageCommandTest.java} | 9 +- .../command/RemoveContainerCommandTest.java} | 7 +- .../command/RemoveImageCommandTest.java} | 7 +- .../command/RestartContainerCommandTest.java} | 6 +- .../command/SearchImagesCommandTest.java} | 4 +- .../command/StartContainerCommandTest.java} | 6 +- .../command/StopContainerCommandTest.java} | 8 +- .../command/TagImageCommandTest.java} | 6 +- .../command/VersionCommandTest.java} | 4 +- .../command/WaitContainerCommandTest.java} | 6 +- 97 files changed, 2144 insertions(+), 878 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/DockerClient.java create mode 100644 src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/AuthCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/CommitCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/ContainerDiffCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java rename src/main/java/com/github/dockerjava/{client => api}/command/CreateContainerResponse.java (94%) create mode 100644 src/main/java/com/github/dockerjava/api/command/CreateImageCmd.java rename src/main/java/com/github/dockerjava/{client => api}/command/CreateImageResponse.java (92%) rename src/main/java/com/github/dockerjava/{client => api}/command/DockerCmd.java (57%) create mode 100644 src/main/java/com/github/dockerjava/api/command/InfoCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/InspectContainerCmd.java rename src/main/java/com/github/dockerjava/{client => api}/command/InspectContainerResponse.java (99%) create mode 100644 src/main/java/com/github/dockerjava/api/command/InspectImageCmd.java rename src/main/java/com/github/dockerjava/{client => api}/command/InspectImageResponse.java (97%) create mode 100644 src/main/java/com/github/dockerjava/api/command/KillContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/ListContainersCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/ListImagesCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/PauseContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/PingCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/PullImageCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/PushImageCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/RemoveContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/RestartContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/SearchImagesCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/StopContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/TagImageCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/TopContainerCmd.java rename src/main/java/com/github/dockerjava/{client => api}/command/TopContainerResponse.java (95%) create mode 100644 src/main/java/com/github/dockerjava/api/command/UnpauseContainerCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/VersionCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/WaitContainerCmd.java delete mode 100644 src/main/java/com/github/dockerjava/client/DockerClient.java delete mode 100644 src/main/java/com/github/dockerjava/client/command/CommandFactory.java delete mode 100644 src/main/java/com/github/dockerjava/client/command/DefaultCommandFactory.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs1/JaxRs1Client.java rename src/main/java/com/github/dockerjava/{client/command/AttachContainerCmd.java => jaxrs1/command/AttachContainerCommand.java} (85%) rename src/main/java/com/github/dockerjava/{client/command/AuthCmd.java => jaxrs1/command/AuthCommand.java} (71%) rename src/main/java/com/github/dockerjava/{client/command/BuildImgCmd.java => jaxrs1/command/BuildImageCommand.java} (90%) rename src/main/java/com/github/dockerjava/{client/command/CommitCmd.java => jaxrs1/command/CommitCommand.java} (66%) rename src/main/java/com/github/dockerjava/{client/command/ContainerDiffCmd.java => jaxrs1/command/ContainerDiffCommand.java} (76%) rename src/main/java/com/github/dockerjava/{client/command/CopyFileFromContainerCmd.java => jaxrs1/command/CopyFileFromContainerCommand.java} (73%) rename src/main/java/com/github/dockerjava/{client/command/CreateContainerCmd.java => jaxrs1/command/CreateContainerCommand.java} (64%) rename src/main/java/com/github/dockerjava/{client/command/CreateImageCmd.java => jaxrs1/command/CreateImageCommand.java} (73%) rename src/main/java/com/github/dockerjava/{client/command/InfoCmd.java => jaxrs1/command/InfoCommand.java} (69%) rename src/main/java/com/github/dockerjava/{client/command/InspectContainerCmd.java => jaxrs1/command/InspectContainerCommand.java} (67%) rename src/main/java/com/github/dockerjava/{client/command/InspectImageCmd.java => jaxrs1/command/InspectImageCommand.java} (66%) rename src/main/java/com/github/dockerjava/{client/command/KillContainerCmd.java => jaxrs1/command/KillContainerCommand.java} (73%) rename src/main/java/com/github/dockerjava/{client/command/ListContainersCmd.java => jaxrs1/command/ListContainersCommand.java} (81%) rename src/main/java/com/github/dockerjava/{client/command/ListImagesCmd.java => jaxrs1/command/ListImagesCommand.java} (78%) rename src/main/java/com/github/dockerjava/{client/command/LogContainerCmd.java => jaxrs1/command/LogContainerCommand.java} (80%) rename src/main/java/com/github/dockerjava/{client/command/PauseContainerCmd.java => jaxrs1/command/PauseContainerCommand.java} (73%) rename src/main/java/com/github/dockerjava/{client/command/PingCmd.java => jaxrs1/command/PingCommand.java} (54%) rename src/main/java/com/github/dockerjava/{client/command/PullImageCmd.java => jaxrs1/command/PullImageCommand.java} (75%) rename src/main/java/com/github/dockerjava/{client/command/PushImageCmd.java => jaxrs1/command/PushImageCommand.java} (80%) rename src/main/java/com/github/dockerjava/{client/command/RemoveContainerCmd.java => jaxrs1/command/RemoveContainerCommand.java} (83%) rename src/main/java/com/github/dockerjava/{client/command/RemoveImageCmd.java => jaxrs1/command/RemoveImageCommand.java} (75%) rename src/main/java/com/github/dockerjava/{client/command/RestartContainerCmd.java => jaxrs1/command/RestartContainerCommand.java} (75%) rename src/main/java/com/github/dockerjava/{client/command/SearchImagesCmd.java => jaxrs1/command/SearchImagesCommand.java} (67%) rename src/main/java/com/github/dockerjava/{client/command/StartContainerCmd.java => jaxrs1/command/StartContainerCommand.java} (87%) rename src/main/java/com/github/dockerjava/{client/command/StopContainerCmd.java => jaxrs1/command/StopContainerCommand.java} (77%) rename src/main/java/com/github/dockerjava/{client/command/TagImageCmd.java => jaxrs1/command/TagImageCommand.java} (71%) rename src/main/java/com/github/dockerjava/{client/command/TopContainerCmd.java => jaxrs1/command/TopContainerCommand.java} (73%) rename src/main/java/com/github/dockerjava/{client/command/UnpauseContainerCmd.java => jaxrs1/command/UnpauseContainerCommand.java} (72%) rename src/main/java/com/github/dockerjava/{client/command/VersionCmd.java => jaxrs1/command/VersionCommand.java} (66%) rename src/main/java/com/github/dockerjava/{client/command/WaitContainerCmd.java => jaxrs1/command/WaitContainerCommand.java} (65%) rename src/test/java/com/github/dockerjava/{client/DockerClientTest.java => jaxrs1/JaxRs1ClientTest.java} (86%) rename src/test/java/com/github/dockerjava/{client/command/AuthCmdTest.java => jaxrs1/command/AuthCommandTest.java} (85%) rename src/test/java/com/github/dockerjava/{client/command/BuildImageCmdTest.java => jaxrs1/command/BuildImageCommandTest.java} (93%) rename src/test/java/com/github/dockerjava/{client/command/CommitCmdTest.java => jaxrs1/command/CommitCommandTest.java} (89%) rename src/test/java/com/github/dockerjava/{client/command/ContainerDiffCmdTest.java => jaxrs1/command/ContainerDiffCommandTest.java} (91%) rename src/test/java/com/github/dockerjava/{client/command/CopyFileFromContainerCmdTest.java => jaxrs1/command/CopyFileFromContainerCommandTest.java} (88%) rename src/test/java/com/github/dockerjava/{client/command/CreateContainerCmdTest.java => jaxrs1/command/CreateContainerCommandTest.java} (94%) rename src/test/java/com/github/dockerjava/{client/command/InfoCmdTest.java => jaxrs1/command/InfoCommandTest.java} (92%) rename src/test/java/com/github/dockerjava/{client/command/KillContainerCmdTest.java => jaxrs1/command/KillContainerCommandTest.java} (86%) rename src/test/java/com/github/dockerjava/{client/command/ListContainersCmdTest.java => jaxrs1/command/ListContainersCommandTest.java} (92%) rename src/test/java/com/github/dockerjava/{client/command/ListImagesCmdTest.java => jaxrs1/command/ListImagesCommandTest.java} (92%) rename src/test/java/com/github/dockerjava/{client/command/LogContainerCmdTest.java => jaxrs1/command/LogContainerCommandTest.java} (90%) rename src/test/java/com/github/dockerjava/{client/command/PullImageCmdTest.java => jaxrs1/command/PullImageCommandTest.java} (93%) rename src/test/java/com/github/dockerjava/{client/command/PushImageCmdTest.java => jaxrs1/command/PushImageCommandTest.java} (88%) rename src/test/java/com/github/dockerjava/{client/command/RemoveContainerCmdTest.java => jaxrs1/command/RemoveContainerCommandTest.java} (88%) rename src/test/java/com/github/dockerjava/{client/command/RemoveImageCmdTest.java => jaxrs1/command/RemoveImageCommandTest.java} (91%) rename src/test/java/com/github/dockerjava/{client/command/RestartContainerCmdTest.java => jaxrs1/command/RestartContainerCommandTest.java} (89%) rename src/test/java/com/github/dockerjava/{client/command/SearchImagesCmdTest.java => jaxrs1/command/SearchImagesCommandTest.java} (92%) rename src/test/java/com/github/dockerjava/{client/command/StartContainerCmdTest.java => jaxrs1/command/StartContainerCommandTest.java} (96%) rename src/test/java/com/github/dockerjava/{client/command/StopContainerCmdTest.java => jaxrs1/command/StopContainerCommandTest.java} (86%) rename src/test/java/com/github/dockerjava/{client/command/TagImageCmdTest.java => jaxrs1/command/TagImageCommandTest.java} (88%) rename src/test/java/com/github/dockerjava/{client/command/VersionCmdTest.java => jaxrs1/command/VersionCommandTest.java} (91%) rename src/test/java/com/github/dockerjava/{client/command/WaitContainerCmdTest.java => jaxrs1/command/WaitContainerCommandTest.java} (88%) diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java new file mode 100644 index 00000000..505db3f5 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -0,0 +1,118 @@ +package com.github.dockerjava.api; + +import java.io.*; + +import com.github.dockerjava.api.command.AttachContainerCmd; +import com.github.dockerjava.api.command.AuthCmd; +import com.github.dockerjava.api.command.BuildImageCmd; +import com.github.dockerjava.api.command.CommitCmd; +import com.github.dockerjava.api.command.ContainerDiffCmd; +import com.github.dockerjava.api.command.CopyFileFromContainerCmd; +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.command.CreateImageCmd; +import com.github.dockerjava.api.command.InfoCmd; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectImageCmd; +import com.github.dockerjava.api.command.KillContainerCmd; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.command.ListImagesCmd; +import com.github.dockerjava.api.command.LogContainerCmd; +import com.github.dockerjava.api.command.PauseContainerCmd; +import com.github.dockerjava.api.command.PingCmd; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.command.PushImageCmd; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.command.RemoveImageCmd; +import com.github.dockerjava.api.command.RestartContainerCmd; +import com.github.dockerjava.api.command.SearchImagesCmd; +import com.github.dockerjava.api.command.StartContainerCmd; +import com.github.dockerjava.api.command.StopContainerCmd; +import com.github.dockerjava.api.command.TagImageCmd; +import com.github.dockerjava.api.command.TopContainerCmd; +import com.github.dockerjava.api.command.UnpauseContainerCmd; +import com.github.dockerjava.api.command.VersionCmd; +import com.github.dockerjava.api.command.WaitContainerCmd; +import com.github.dockerjava.client.model.AuthConfig; + +public interface DockerClient extends Closeable { + + public AuthConfig authConfig() throws DockerException; + + /** + * Authenticate with the server, useful for checking authentication. + */ + public AuthCmd authCmd(); + + public InfoCmd infoCmd() throws DockerException; + + public PingCmd pingCmd(); + + public VersionCmd versionCmd() throws DockerException; + + /** + * * IMAGE API * + */ + + public PullImageCmd pullImageCmd(String repository); + + public PushImageCmd pushImageCmd(String name); + + public CreateImageCmd createImageCmd(String repository, + InputStream imageStream); + + public SearchImagesCmd searchImagesCmd(String term); + + public RemoveImageCmd removeImageCmd(String imageId); + + public ListImagesCmd listImagesCmd(); + + public InspectImageCmd inspectImageCmd(String imageId); + + /** + * * CONTAINER API * + */ + + public ListContainersCmd listContainersCmd(); + + public CreateContainerCmd createContainerCmd(String image); + + public StartContainerCmd startContainerCmd(String containerId); + + public InspectContainerCmd inspectContainerCmd(String containerId); + + public RemoveContainerCmd removeContainerCmd(String containerId); + + public WaitContainerCmd waitContainerCmd(String containerId); + + public AttachContainerCmd attachContainerCmd(String containerId); + + public LogContainerCmd logContainerCmd(String containerId); + + public CopyFileFromContainerCmd copyFileFromContainerCmd( + String containerId, String resource); + + public ContainerDiffCmd containerDiffCmd(String containerId); + + public StopContainerCmd stopContainerCmd(String containerId); + + public KillContainerCmd killContainerCmd(String containerId); + + public RestartContainerCmd restartContainerCmd(String containerId); + + public CommitCmd commitCmd(String containerId); + + public BuildImageCmd buildImageCmd(File dockerFolder); + + public BuildImageCmd buildImageCmd(InputStream tarInputStream); + + public TopContainerCmd topContainerCmd(String containerId); + + public TagImageCmd tagImageCmd(String imageId, String repository, String tag); + + public PauseContainerCmd pauseContainerCmd(String containerId); + + public UnpauseContainerCmd unpauseContainerCmd(String containerId); + + public void close() throws IOException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java new file mode 100644 index 00000000..c4561d3d --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java @@ -0,0 +1,61 @@ +package com.github.dockerjava.api.command; + +import java.io.InputStream; + +import com.github.dockerjava.api.NotFoundException; + +/** + * Attach to container + * + * @param logs + * - true or false, includes logs. Defaults to false. + * + * @param followStream + * - true or false, return stream. Defaults to false. + * @param stdout + * - true or false, includes stdout log. Defaults to false. + * @param stderr + * - true or false, includes stderr log. Defaults to false. + * @param timestamps + * - true or false, if true, print timestamps for every log line. + * Defaults to false. + */ +public interface AttachContainerCmd extends DockerCmd{ + + public String getContainerId(); + + public boolean hasLogsEnabled(); + + public boolean hasFollowStreamEnabled(); + + public boolean hasTimestampsEnabled(); + + public boolean hasStdoutEnabled(); + + public boolean hasStderrEnabled(); + + public AttachContainerCmd withContainerId(String containerId); + + public AttachContainerCmd withFollowStream(); + + public AttachContainerCmd withFollowStream(boolean followStream); + + public AttachContainerCmd withTimestamps(boolean timestamps); + + public AttachContainerCmd withStdOut(); + + public AttachContainerCmd withStdOut(boolean stdout); + + public AttachContainerCmd withStdErr(); + + public AttachContainerCmd withStdErr(boolean stderr); + + public AttachContainerCmd withLogs(boolean logs); + + /** + * @throws NotFoundException No such container + */ + @Override + public InputStream exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/AuthCmd.java b/src/main/java/com/github/dockerjava/api/command/AuthCmd.java new file mode 100644 index 00000000..79a4617e --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/AuthCmd.java @@ -0,0 +1,10 @@ +package com.github.dockerjava.api.command; + +/** + * + * Authenticate with the server, useful for checking authentication. + * + */ +public interface AuthCmd extends DockerCmd{ + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java new file mode 100644 index 00000000..d1a2d020 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java @@ -0,0 +1,35 @@ +package com.github.dockerjava.api.command; + +import java.io.File; +import java.io.InputStream; + +/** + * + * Build an image from Dockerfile. + * + * TODO: http://docs.docker.com/reference/builder/#dockerignore + * + */ +public interface BuildImageCmd extends DockerCmd{ + + public BuildImageCmd withTag(String tag); + + public File getDockerFolder(); + + public String getTag(); + + public boolean hasNoCacheEnabled(); + + public boolean hasRemoveEnabled(); + + public boolean isQuiet(); + + public BuildImageCmd withNoCache(); + + public BuildImageCmd withNoCache(boolean noCache); + + public BuildImageCmd withRemove(boolean rm); + + public BuildImageCmd withQuiet(boolean quiet); + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/CommitCmd.java b/src/main/java/com/github/dockerjava/api/command/CommitCmd.java new file mode 100644 index 00000000..6933a025 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/CommitCmd.java @@ -0,0 +1,112 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.client.model.ExposedPorts; +import com.github.dockerjava.client.model.Volumes; +import com.github.dockerjava.jaxrs1.command.CommitCommand; + +/** +* +* Create a new image from a container's changes. Returns the new image ID. +* +*/ +public interface CommitCmd extends DockerCmd{ + + public String getContainerId(); + + public CommitCommand withContainerId(String containerId); + + public String getRepository(); + + public String getTag(); + + public String getMessage(); + + public String getAuthor(); + + public boolean hasPauseEnabled(); + + public CommitCmd withAttachStderr(boolean attachStderr); + + public CommitCmd withAttachStderr(); + + public CommitCmd withAttachStdin(boolean attachStdin); + + public CommitCmd withAttachStdin(); + + public CommitCmd withAttachStdout(boolean attachStdout); + + public CommitCmd withAttachStdout(); + + public CommitCmd withCmd(String... cmd); + + public CommitCmd withDisableNetwork(boolean disableNetwork); + + public CommitCmd withAuthor(String author); + + public CommitCmd withMessage(String message); + + public CommitCmd withTag(String tag); + + public CommitCmd withRepository(String repository); + + public CommitCmd withPause(boolean pause); + + public String[] getEnv(); + + public CommitCmd withEnv(String... env); + + public ExposedPorts getExposedPorts(); + + public CommitCmd withExposedPorts(ExposedPorts exposedPorts); + + public String getHostname(); + + public CommitCmd withHostname(String hostname); + + public Integer getMemory(); + + public CommitCmd withMemory(Integer memory); + + public Integer getMemorySwap(); + + public CommitCmd withMemorySwap(Integer memorySwap); + + public boolean isOpenStdin(); + + public CommitCmd withOpenStdin(boolean openStdin); + + public String[] getPortSpecs(); + + public CommitCmd withPortSpecs(String... portSpecs); + + public boolean isStdinOnce(); + + public CommitCmd withStdinOnce(boolean stdinOnce); + + public CommitCmd withStdinOnce(); + + public boolean isTty(); + + public CommitCmd withTty(boolean tty); + + public CommitCmd withTty(); + + public String getUser(); + + public CommitCmd withUser(String user); + + public Volumes getVolumes(); + + public CommitCmd withVolumes(Volumes volumes); + + public String getWorkingDir(); + + public CommitCmd withWorkingDir(String workingDir); + + /** + * @throws NotFoundException No such container + */ + public String exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/ContainerDiffCmd.java b/src/main/java/com/github/dockerjava/api/command/ContainerDiffCmd.java new file mode 100644 index 00000000..9358a23f --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/ContainerDiffCmd.java @@ -0,0 +1,25 @@ +package com.github.dockerjava.api.command; + +import java.util.List; + +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.InternalServerErrorException; +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.client.model.ChangeLog; + +public interface ContainerDiffCmd extends DockerCmd> { + + public String getContainerId(); + + public ContainerDiffCmd withContainerId(String containerId); + + public String toString(); + + /** + * @throws NotFoundException No such container + * @throws InternalServerErrorException server error + * @throws DockerException unexpected http status code + */ + public List exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java new file mode 100644 index 00000000..d6109e8f --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java @@ -0,0 +1,26 @@ +package com.github.dockerjava.api.command; + +import java.io.InputStream; + +import com.github.dockerjava.api.NotFoundException; + +public interface CopyFileFromContainerCmd extends DockerCmd { + + public String getContainerId(); + + public String getResource(); + + public CopyFileFromContainerCmd withContainerId(String containerId); + + public CopyFileFromContainerCmd withResource(String resource); + + public String getHostPath(); + + public CopyFileFromContainerCmd withHostPath(String hostPath); + + /** + * @throws NotFoundException No such container + */ + public InputStream exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java new file mode 100644 index 00000000..5b40958a --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java @@ -0,0 +1,102 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.ConflictException; +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.client.model.ExposedPort; +import com.github.dockerjava.client.model.Volume; + +public interface CreateContainerCmd extends DockerCmd{ + + public CreateContainerCmd withName(String name); + + public String getName(); + + public CreateContainerCmd withExposedPorts(ExposedPort... exposedPorts); + + public ExposedPort[] getExposedPorts(); + + public boolean isDisableNetwork(); + + public String getWorkingDir(); + + public CreateContainerCmd withWorkingDir(String workingDir); + + public String getHostName(); + + public CreateContainerCmd withDisableNetwork(boolean disableNetwork); + + public CreateContainerCmd withHostName(String hostName); + + public String[] getPortSpecs(); + + public CreateContainerCmd withPortSpecs(String... portSpecs); + + public String getUser(); + + public CreateContainerCmd withUser(String user); + + public boolean isTty(); + + public CreateContainerCmd withTty(boolean tty); + + public boolean isStdinOpen(); + + public CreateContainerCmd withStdinOpen(boolean stdinOpen); + + public boolean isStdInOnce(); + + public CreateContainerCmd withStdInOnce(boolean stdInOnce); + + public long getMemoryLimit(); + + public CreateContainerCmd withMemoryLimit(long memoryLimit); + + public long getMemorySwap(); + + public CreateContainerCmd withMemorySwap(long memorySwap); + + public boolean isAttachStdin(); + + public CreateContainerCmd withAttachStdin(boolean attachStdin); + + public boolean isAttachStdout(); + + public CreateContainerCmd withAttachStdout(boolean attachStdout); + + public boolean isAttachStderr(); + + public CreateContainerCmd withAttachStderr(boolean attachStderr); + + public String[] getEnv(); + + public CreateContainerCmd withEnv(String... env); + + public String[] getCmd(); + + public CreateContainerCmd withCmd(String... cmd); + + public String[] getDns(); + + public CreateContainerCmd withDns(String... dns); + + public String getImage(); + + public CreateContainerCmd withImage(String image); + + public Volume[] getVolumes(); + + public CreateContainerCmd withVolumes(Volume... volumes); + + public String[] getVolumesFrom(); + + public CreateContainerCmd withVolumesFrom(String... volumesFrom); + + + /** + * @throws NotFoundException No such container + * @throws ConflictException Named container already exists + */ + public CreateContainerResponse exec() throws NotFoundException, + ConflictException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerResponse.java similarity index 94% rename from src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java rename to src/main/java/com/github/dockerjava/api/command/CreateContainerResponse.java index 2ea5af78..5b0b5a53 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerResponse.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.api.command; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/github/dockerjava/api/command/CreateImageCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateImageCmd.java new file mode 100644 index 00000000..279fe5d2 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/CreateImageCmd.java @@ -0,0 +1,27 @@ +package com.github.dockerjava.api.command; + +import java.io.InputStream; + +public interface CreateImageCmd extends DockerCmd { + + public String getRepository(); + + public String getTag(); + + /** + * @param repository the repository to import to + */ + public CreateImageCmd withRepository(String repository); + + /** + * @param imageStream the InputStream of the tar file + */ + public CreateImageCmd withImageStream(InputStream imageStream); + + /** + * @param tag any tag for this image + */ + public CreateImageCmd withTag(String tag); + + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/client/command/CreateImageResponse.java b/src/main/java/com/github/dockerjava/api/command/CreateImageResponse.java similarity index 92% rename from src/main/java/com/github/dockerjava/client/command/CreateImageResponse.java rename to src/main/java/com/github/dockerjava/api/command/CreateImageResponse.java index e3f40474..43731703 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateImageResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateImageResponse.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.api.command; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/github/dockerjava/client/command/DockerCmd.java b/src/main/java/com/github/dockerjava/api/command/DockerCmd.java similarity index 57% rename from src/main/java/com/github/dockerjava/client/command/DockerCmd.java rename to src/main/java/com/github/dockerjava/api/command/DockerCmd.java index dd3d8759..4c30382b 100644 --- a/src/main/java/com/github/dockerjava/client/command/DockerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/DockerCmd.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.api.command; public interface DockerCmd { diff --git a/src/main/java/com/github/dockerjava/api/command/InfoCmd.java b/src/main/java/com/github/dockerjava/api/command/InfoCmd.java new file mode 100644 index 00000000..943aaa17 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/InfoCmd.java @@ -0,0 +1,7 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.client.model.Info; + +public interface InfoCmd extends DockerCmd { + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerCmd.java new file mode 100644 index 00000000..fe350248 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerCmd.java @@ -0,0 +1,16 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; + +public interface InspectContainerCmd extends DockerCmd { + + public String getContainerId(); + + public InspectContainerCmd withContainerId(String containerId); + + /** + * @throws NotFoundException No such container + */ + public InspectContainerResponse exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java similarity index 99% rename from src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java rename to src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java index 990b67f9..05ccbf4a 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.api.command; import java.util.Map; diff --git a/src/main/java/com/github/dockerjava/api/command/InspectImageCmd.java b/src/main/java/com/github/dockerjava/api/command/InspectImageCmd.java new file mode 100644 index 00000000..3f4dc476 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/InspectImageCmd.java @@ -0,0 +1,19 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; + +/** + * Inspect the details of an image. + */ +public interface InspectImageCmd extends DockerCmd{ + + public String getImageId(); + + public InspectImageCmd withImageId(String imageId); + + /** + * @throws NotFoundException No such image + */ + public InspectImageResponse exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/client/command/InspectImageResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectImageResponse.java similarity index 97% rename from src/main/java/com/github/dockerjava/client/command/InspectImageResponse.java rename to src/main/java/com/github/dockerjava/api/command/InspectImageResponse.java index 9cc164fb..2ef2a75c 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectImageResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectImageResponse.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.api.command; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/github/dockerjava/api/command/KillContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/KillContainerCmd.java new file mode 100644 index 00000000..7ba13d5f --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/KillContainerCmd.java @@ -0,0 +1,23 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; + +/** + * Kill a running container. + */ +public interface KillContainerCmd extends DockerCmd { + + public String getContainerId(); + + public String getSignal(); + + public KillContainerCmd withContainerId(String containerId); + + public KillContainerCmd withSignal(String signal); + + /** + * @throws NotFoundException No such container + */ + public Void exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/ListContainersCmd.java b/src/main/java/com/github/dockerjava/api/command/ListContainersCmd.java new file mode 100644 index 00000000..6e527663 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/ListContainersCmd.java @@ -0,0 +1,39 @@ +package com.github.dockerjava.api.command; + +import java.util.List; + +import com.github.dockerjava.client.model.Container; + +/** + * List containers + * + * @param showAll - true or false, Show all containers. Only running containers are shown by default. + * @param showSize - true or false, Show the containers sizes. This is false by default. + * @param limit - Show `limit` last created containers, include non-running ones. There is no limit by default. + * @param sinceId - Show only containers created since Id, include non-running ones. + * @param beforeId - Show only containers created before Id, include non-running ones. + * + */ +public interface ListContainersCmd extends DockerCmd>{ + + public int getLimit(); + + public boolean hasShowSizeEnabled(); + + public boolean hasShowAllEnabled(); + + public String getSinceId(); + + public String getBeforeId(); + + public ListContainersCmd withShowAll(boolean showAll); + + public ListContainersCmd withShowSize(boolean showSize); + + public ListContainersCmd withLimit(int limit); + + public ListContainersCmd withSince(String since); + + public ListContainersCmd withBefore(String before); + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/ListImagesCmd.java b/src/main/java/com/github/dockerjava/api/command/ListImagesCmd.java new file mode 100644 index 00000000..4e67ce4c --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/ListImagesCmd.java @@ -0,0 +1,23 @@ +package com.github.dockerjava.api.command; + +import java.util.List; + +import com.github.dockerjava.client.model.Image; + +/** + * List images + * + * @param showAll - Show all images (by default filter out the intermediate images used to build) + * @param filter - TODO: undocumented in docker remote api reference + */ +public interface ListImagesCmd extends DockerCmd> { + + public String getFilter(); + + public boolean hasShowAllEnabled(); + + public ListImagesCmd withShowAll(boolean showAll); + + public ListImagesCmd withFilter(String filter); + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java new file mode 100644 index 00000000..4c00f2be --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java @@ -0,0 +1,61 @@ +package com.github.dockerjava.api.command; + +import java.io.InputStream; + +import com.github.dockerjava.api.NotFoundException; + +/** + * Get container logs + * + * @param followStream + * - true or false, return stream. Defaults to false. + * @param stdout + * - true or false, includes stdout log. Defaults to false. + * @param stderr + * - true or false, includes stderr log. Defaults to false. + * @param timestamps + * - true or false, if true, print timestamps for every log line. + * Defaults to false. + * @param tail + * - `all` or ``, Output specified number of lines at the end of logs + */ +public interface LogContainerCmd extends DockerCmd{ + + public String getContainerId(); + + public int getTail(); + + public boolean hasFollowStreamEnabled(); + + public boolean hasTimestampsEnabled(); + + public boolean hasStdoutEnabled(); + + public boolean hasStderrEnabled(); + + public LogContainerCmd withContainerId(String containerId); + + public LogContainerCmd withFollowStream(); + + public LogContainerCmd withFollowStream(boolean followStream); + + public LogContainerCmd withTimestamps(boolean timestamps); + + public LogContainerCmd withStdOut(); + + public LogContainerCmd withStdOut(boolean stdout); + + public LogContainerCmd withStdErr(); + + public LogContainerCmd withStdErr(boolean stderr); + + public LogContainerCmd withTailAll(); + + public LogContainerCmd withTail(int tail); + + /** + * @throws NotFoundException No such container + */ + public InputStream exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/PauseContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/PauseContainerCmd.java new file mode 100644 index 00000000..0b26498f --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/PauseContainerCmd.java @@ -0,0 +1,22 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; + +/** + * Pause a container. + * + * @param containerId - Id of the container + * + */ +public interface PauseContainerCmd extends DockerCmd{ + + public String getContainerId(); + + public PauseContainerCmd withContainerId(String containerId); + + /** + * @throws NotFoundException No such container + */ + public Void exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/PingCmd.java b/src/main/java/com/github/dockerjava/api/command/PingCmd.java new file mode 100644 index 00000000..287a78c1 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/PingCmd.java @@ -0,0 +1,10 @@ +package com.github.dockerjava.api.command; + + +/** + * Ping the Docker server + * + */ +public interface PingCmd extends DockerCmd { + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java b/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java new file mode 100644 index 00000000..3663b392 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java @@ -0,0 +1,24 @@ +package com.github.dockerjava.api.command; + +import java.io.InputStream; + +/** +* +* Pull image from repository. +* +*/ +public interface PullImageCmd extends DockerCmd{ + + public String getRepository(); + + public String getTag(); + + public String getRegistry(); + + public PullImageCmd withRepository(String repository); + + public PullImageCmd withTag(String tag); + + public PullImageCmd withRegistry(String registry); + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java b/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java new file mode 100644 index 00000000..4163b867 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java @@ -0,0 +1,26 @@ +package com.github.dockerjava.api.command; + +import java.io.InputStream; + +import com.github.dockerjava.api.NotFoundException; + +/** + * 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 interface PushImageCmd extends DockerCmd{ + + public String getName(); + + /** + * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. + */ + public PushImageCmd withName(String name); + + /** + * @throws NotFoundException No such image + */ + public InputStream exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/RemoveContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/RemoveContainerCmd.java new file mode 100644 index 00000000..2225516d --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/RemoveContainerCmd.java @@ -0,0 +1,32 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; + +/** + * Remove a container. + * + * @param removeVolumes - true or false, Remove the volumes associated to the container. Defaults to false + * @param force - true or false, Removes the container even if it was running. Defaults to false + */ +public interface RemoveContainerCmd extends DockerCmd { + + public String getContainerId(); + + public boolean hasRemoveVolumesEnabled(); + + public boolean hasForceEnabled(); + + public RemoveContainerCmd withContainerId(String containerId); + + public RemoveContainerCmd withRemoveVolumes(boolean removeVolumes); + + public RemoveContainerCmd withForce(); + + public RemoveContainerCmd withForce(boolean force); + + /** + * @throws NotFoundException No such container + */ + public Void exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java b/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java new file mode 100644 index 00000000..67637477 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java @@ -0,0 +1,31 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; + +/** +* +* Remove an image, deleting any tags it might have. +* +*/ +public interface RemoveImageCmd extends DockerCmd{ + + public String getImageId(); + + public boolean hasForceEnabled(); + + public boolean hasNoPruneEnabled(); + + public RemoveImageCmd withImageId(String imageId); + + public RemoveImageCmd withForce(); + + public RemoveImageCmd withForce(boolean force); + + public RemoveImageCmd withNoPrune(boolean noPrune); + + /** + * @throws NotFoundException No such image + */ + public Void exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/RestartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/RestartContainerCmd.java new file mode 100644 index 00000000..82a61b00 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/RestartContainerCmd.java @@ -0,0 +1,26 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; + +/** + * Restart a running container. + * + * @param timeout - Timeout in seconds before killing the container. Defaults to 10 seconds. + * + */ +public interface RestartContainerCmd extends DockerCmd { + + public String getContainerId(); + + public int getTimeout(); + + public RestartContainerCmd withContainerId(String containerId); + + public RestartContainerCmd withtTimeout(int timeout); + + /** + * @throws NotFoundException No such container + */ + public Void exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/SearchImagesCmd.java b/src/main/java/com/github/dockerjava/api/command/SearchImagesCmd.java new file mode 100644 index 00000000..4104b1ac --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/SearchImagesCmd.java @@ -0,0 +1,19 @@ +package com.github.dockerjava.api.command; + +import java.util.List; + +import com.github.dockerjava.client.model.SearchItem; + +/** + * Search images + * + * @param term - search term + * + */ +public interface SearchImagesCmd extends DockerCmd> { + + public String getTerm(); + + public SearchImagesCmd withTerm(String term); + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java new file mode 100644 index 00000000..d170bda2 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -0,0 +1,57 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.NotModifiedException; +import com.github.dockerjava.client.model.Bind; +import com.github.dockerjava.client.model.Link; +import com.github.dockerjava.client.model.LxcConf; +import com.github.dockerjava.client.model.Ports; + +/** + * Start a container + */ +public interface StartContainerCmd extends DockerCmd { + + public Bind[] getBinds(); + + public Link[] getLinks(); + + public LxcConf[] getLxcConf(); + + public Ports getPortBindings(); + + public boolean isPublishAllPorts(); + + public boolean isPrivileged(); + + public String getDns(); + + public String getVolumesFrom(); + + public String getContainerId(); + + public StartContainerCmd withBinds(Bind... binds); + + public StartContainerCmd withLinks(Link... links); + + public StartContainerCmd withLxcConf(LxcConf... lxcConf); + + public StartContainerCmd withPortBindings(Ports portBindings); + + public StartContainerCmd withPrivileged(boolean privileged); + + public StartContainerCmd withPublishAllPorts(boolean publishAllPorts); + + public StartContainerCmd withDns(String dns); + + public StartContainerCmd withVolumesFrom(String volumesFrom); + + public StartContainerCmd withContainerId(String containerId); + + /** + * @throws NotFoundException No such container + * @throws NotModifiedException Container already started + */ + public Void exec() throws NotFoundException, NotModifiedException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/StopContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StopContainerCmd.java new file mode 100644 index 00000000..4c373386 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/StopContainerCmd.java @@ -0,0 +1,29 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.NotModifiedException; + +/** + * Stop a running container. + * + * @param containerId - Id of the container + * @param timeout - Timeout in seconds before killing the container. Defaults to 10 seconds. + * + */ +public interface StopContainerCmd extends DockerCmd { + + public String getContainerId(); + + public int getTimeout(); + + public StopContainerCmd withContainerId(String containerId); + + public StopContainerCmd withTimeout(int timeout); + + /** + * @throws NotFoundException No such container + * @throws NotModifiedException Container already stopped + */ + public Void exec() throws NotFoundException, NotModifiedException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/TagImageCmd.java b/src/main/java/com/github/dockerjava/api/command/TagImageCmd.java new file mode 100644 index 00000000..9e2b2210 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/TagImageCmd.java @@ -0,0 +1,32 @@ +package com.github.dockerjava.api.command; + + +/** + * 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 force (not documented) + * + */ +public interface TagImageCmd extends DockerCmd { + + public String getImageId(); + + public String getRepository(); + + public String getTag(); + + public boolean hasForceEnabled(); + + public TagImageCmd withImageId(String imageId); + + public TagImageCmd withRepository(String repository); + + public TagImageCmd withTag(String tag); + + public TagImageCmd withForce(); + + public TagImageCmd withForce(boolean force); + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/TopContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/TopContainerCmd.java new file mode 100644 index 00000000..846599bd --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/TopContainerCmd.java @@ -0,0 +1,23 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; + +/** + * List processes running inside a container + */ +public interface TopContainerCmd extends DockerCmd { + + public String getContainerId(); + + public String getPsArgs(); + + public TopContainerCmd withContainerId(String containerId); + + public TopContainerCmd withPsArgs(String psArgs); + + /** + * @throws NotFoundException No such container + */ + public TopContainerResponse exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/client/command/TopContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java similarity index 95% rename from src/main/java/com/github/dockerjava/client/command/TopContainerResponse.java rename to src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java index 70701ff1..e8840768 100644 --- a/src/main/java/com/github/dockerjava/client/command/TopContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.api.command; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/github/dockerjava/api/command/UnpauseContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/UnpauseContainerCmd.java new file mode 100644 index 00000000..916c9b11 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/UnpauseContainerCmd.java @@ -0,0 +1,22 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; + +/** + * Unpause a container. + * + * @param containerId - Id of the container + * + */ +public interface UnpauseContainerCmd extends DockerCmd { + + public String getContainerId(); + + public UnpauseContainerCmd withContainerId(String containerId); + + /** + * @throws NotFoundException No such container + */ + public Void exec() throws NotFoundException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/VersionCmd.java b/src/main/java/com/github/dockerjava/api/command/VersionCmd.java new file mode 100644 index 00000000..482e4306 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/VersionCmd.java @@ -0,0 +1,10 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.client.model.Version; + +/** + * Returns the Docker version info. + */ +public interface VersionCmd extends DockerCmd{ + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/WaitContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/WaitContainerCmd.java new file mode 100644 index 00000000..d59eaa14 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/WaitContainerCmd.java @@ -0,0 +1,15 @@ +package com.github.dockerjava.api.command; + + +/** + * Wait a container + * + * Block until container stops, then returns its exit code + */ +public interface WaitContainerCmd extends DockerCmd { + + public String getContainerId(); + + public WaitContainerCmd withContainerId(String containerId); + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/client/DockerClient.java b/src/main/java/com/github/dockerjava/client/DockerClient.java deleted file mode 100644 index 449a1b79..00000000 --- a/src/main/java/com/github/dockerjava/client/DockerClient.java +++ /dev/null @@ -1,290 +0,0 @@ -package com.github.dockerjava.client; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.apache.commons.io.IOUtils.closeQuietly; - -import java.io.*; - -import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.client.command.*; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.io.LineIterator; -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 com.github.dockerjava.client.model.AuthConfig; -import com.github.dockerjava.client.utils.JsonClientFilter; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.client.apache4.ApacheHttpClient4; -import com.sun.jersey.client.apache4.ApacheHttpClient4Handler; - -/** - * @author Konstantin Pelykh (kpelykh@gmail.com) - */ -public class DockerClient implements Closeable { - - private final Client client; - - private final CommandFactory cmdFactory; - private final WebResource baseResource; - private final DockerClientConfig dockerClientConfig; - - public DockerClient() { - this(DockerClientConfig.createDefaultConfigBuilder().build()); - } - - public DockerClient(String serverUrl) { - this(configWithServerUrl(serverUrl)); - } - - private static DockerClientConfig configWithServerUrl(String serverUrl) { - return DockerClientConfig.createDefaultConfigBuilder() - .withUri(serverUrl) - .build(); - } - - public DockerClient(DockerClientConfig dockerClientConfig) { - this(dockerClientConfig, new DefaultCommandFactory()); - } - - public DockerClient(DockerClientConfig dockerClientConfig, CommandFactory cmdFactory) { - this.cmdFactory = cmdFactory; - this.dockerClientConfig = dockerClientConfig; - - HttpClient httpClient = getPoolingHttpClient(dockerClientConfig); - ClientConfig clientConfig = new DefaultClientConfig(); - client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, - null, false), clientConfig); - - if(dockerClientConfig.getReadTimeout() != null) { - client.setReadTimeout(dockerClientConfig.getReadTimeout()); - } - - client.addFilter(new JsonClientFilter()); - - if (dockerClientConfig.isLoggingFilterEnabled()) - client.addFilter(new SelectiveLoggingFilter()); - - WebResource webResource = client.resource(dockerClientConfig.getUri()); - - if(dockerClientConfig.getVersion() != null) { - baseResource = webResource.path("v" + dockerClientConfig.getVersion()); - } else { - baseResource = webResource; - } - } - - private HttpClient getPoolingHttpClient(DockerClientConfig dockerClientConfig) { - SchemeRegistry schemeRegistry = new SchemeRegistry(); - schemeRegistry.register(new Scheme("http", dockerClientConfig.getUri().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); - - return new DefaultHttpClient(cm); - } - - public RES_T execute(AbstrDockerCmd command) - throws DockerException { - return command.withBaseResource(baseResource).exec(); - } - - public AuthConfig authConfig() throws DockerException { - checkNotNull(dockerClientConfig.getUsername(), "Configured username is null."); - checkNotNull(dockerClientConfig.getPassword(), "Configured password is null."); - checkNotNull(dockerClientConfig.getEmail(), "Configured email is null."); - - AuthConfig authConfig = new AuthConfig(); - authConfig.setUsername(dockerClientConfig.getUsername()); - authConfig.setPassword(dockerClientConfig.getPassword()); - authConfig.setEmail(dockerClientConfig.getEmail()); - // TODO Make the registry address configurable - return authConfig; - } - - /** - * * MISC API * - */ - - /** - * Authenticate with the server, useful for checking authentication. - */ - public AuthCmd authCmd() { - return cmdFactory.authCmd(authConfig()).withBaseResource(baseResource); - } - - public InfoCmd infoCmd() throws DockerException { - return cmdFactory.infoCmd().withBaseResource(baseResource); - } - - public PingCmd pingCmd() { - return cmdFactory.pingCmd().withBaseResource(baseResource); - } - - public VersionCmd versionCmd() throws DockerException { - return cmdFactory.versionCmd().withBaseResource(baseResource); - } - - /** - * * IMAGE API * - */ - - public PullImageCmd pullImageCmd(String repository) { - return cmdFactory.pullImageCmd(repository).withBaseResource(baseResource); - } - - public PushImageCmd pushImageCmd(String name) { - return cmdFactory.pushImageCmd(name).withAuthConfig(authConfig()) - .withBaseResource(baseResource); - } - -// public ClientResponse pushImage(String name) { -// return execute(pushImageCmd(name)); -// } - - public CreateImageCmd createImageCmd(String repository, InputStream imageStream) { - return cmdFactory.createImageCmd(repository, imageStream) - .withBaseResource(baseResource); - } - - public SearchImagesCmd searchImagesCmd(String term) { - return cmdFactory.searchImagesCmd(term).withBaseResource(baseResource); - } - - public RemoveImageCmd removeImageCmd(String imageId) { - return cmdFactory.removeImageCmd(imageId).withBaseResource(baseResource); - } - - public ListImagesCmd listImagesCmd() { - return cmdFactory.listImagesCmd().withBaseResource(baseResource); - } - - public InspectImageCmd inspectImageCmd(String imageId) { - return cmdFactory.inspectImageCmd(imageId).withBaseResource(baseResource); - } - - /** - * * CONTAINER API * - */ - - public ListContainersCmd listContainersCmd() { - return cmdFactory.listContainersCmd().withBaseResource(baseResource); - } - - public CreateContainerCmd createContainerCmd(String image) { - return cmdFactory.createContainerCmd(image).withBaseResource(baseResource); - } - - public StartContainerCmd startContainerCmd(String containerId) { - return cmdFactory.startContainerCmd(containerId) - .withBaseResource(baseResource); - } - - public InspectContainerCmd inspectContainerCmd(String containerId) { - return cmdFactory.inspectContainerCmd(containerId) - .withBaseResource(baseResource); - } - - public RemoveContainerCmd removeContainerCmd(String containerId) { - return cmdFactory.removeContainerCmd(containerId) - .withBaseResource(baseResource); - } - - public WaitContainerCmd waitContainerCmd(String containerId) { - return cmdFactory.waitContainerCmd(containerId).withBaseResource(baseResource); - } - - public AttachContainerCmd attachContainerCmd(String containerId) { - return cmdFactory.attachContainerCmd(containerId).withBaseResource(baseResource); - } - - - public LogContainerCmd logContainerCmd(String containerId) { - return cmdFactory.logContainerCmd(containerId).withBaseResource(baseResource); - } - - public CopyFileFromContainerCmd copyFileFromContainerCmd( - String containerId, String resource) { - return cmdFactory.copyFileFromContainerCmd(containerId, resource) - .withBaseResource(baseResource); - } - - public ContainerDiffCmd containerDiffCmd(String containerId) { - return cmdFactory.containerDiffCmd(containerId).withBaseResource(baseResource); - } - - public StopContainerCmd stopContainerCmd(String containerId) { - return cmdFactory.stopContainerCmd(containerId).withBaseResource(baseResource); - } - - public KillContainerCmd killContainerCmd(String containerId) { - return cmdFactory.killContainerCmd(containerId).withBaseResource(baseResource); - } - - public RestartContainerCmd restartContainerCmd(String containerId) { - return cmdFactory.restartContainerCmd(containerId) - .withBaseResource(baseResource); - } - - public CommitCmd commitCmd(String containerId) { - return cmdFactory.commitCmd(containerId).withBaseResource(baseResource); - } - - public BuildImgCmd buildImageCmd(File dockerFolder) { - return cmdFactory.buildImgCmd(dockerFolder).withBaseResource(baseResource); - } - - public BuildImgCmd buildImageCmd(InputStream tarInputStream) { - return cmdFactory.buildImgCmd(tarInputStream).withBaseResource(baseResource); - } - - public TopContainerCmd topContainerCmd(String containerId) { - return cmdFactory.topContainerCmd(containerId).withBaseResource(baseResource); - } - - public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { - return cmdFactory.tagImageCmd(imageId, repository, tag).withBaseResource(baseResource); - } - - // TODO This is only being used by the test code for logging. Is it really necessary? - /** - * @return The output slurped into a string. - */ - public static String asString(InputStream response) throws IOException { - - StringWriter out = new StringWriter(); - try { - LineIterator itr = IOUtils.lineIterator( - response, "UTF-8"); - while (itr.hasNext()) { - String line = itr.next(); - out.write(line + (itr.hasNext() ? "\n" : "")); - } - } finally { - closeQuietly(response); - } - return out.toString(); - } - - @Override - public void close() throws IOException { - client.destroy(); - } - -} diff --git a/src/main/java/com/github/dockerjava/client/DockerClientConfig.java b/src/main/java/com/github/dockerjava/client/DockerClientConfig.java index 9f1da87e..19a79419 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/client/DockerClientConfig.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client; + package com.github.dockerjava.client; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java index 65f30026..2c042f5b 100644 --- a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java @@ -10,6 +10,7 @@ import com.github.dockerjava.api.NotAcceptableException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; +import com.github.dockerjava.api.command.DockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; diff --git a/src/main/java/com/github/dockerjava/client/command/CommandFactory.java b/src/main/java/com/github/dockerjava/client/command/CommandFactory.java deleted file mode 100644 index ad970a4b..00000000 --- a/src/main/java/com/github/dockerjava/client/command/CommandFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.github.dockerjava.client.command; - -import com.github.dockerjava.client.model.AuthConfig; - -import java.io.File; -import java.io.InputStream; - -public interface CommandFactory { - public AttachContainerCmd attachContainerCmd(String containerId); - public AuthCmd authCmd(AuthConfig authConfig); - public BuildImgCmd buildImgCmd(File dockerFolder); - public BuildImgCmd buildImgCmd(InputStream tarInputStream); - public CommitCmd commitCmd(String containerId); - public ContainerDiffCmd containerDiffCmd(String containerId); - public CopyFileFromContainerCmd copyFileFromContainerCmd(String containerId, String resource); - public CreateContainerCmd createContainerCmd(String image); - public CreateImageCmd createImageCmd(String repository, InputStream imageStream); - public InfoCmd infoCmd(); - public InspectContainerCmd inspectContainerCmd(String containerId); - public InspectImageCmd inspectImageCmd(String imageId); - public KillContainerCmd killContainerCmd(String containerId); - public ListContainersCmd listContainersCmd(); - public ListImagesCmd listImagesCmd(); - public LogContainerCmd logContainerCmd(String containerId); - public PauseContainerCmd pauseContainerCmd(String containerId); - public PullImageCmd pullImageCmd(String repository); - public PushImageCmd pushImageCmd(String imageName); - public RemoveContainerCmd removeContainerCmd(String containerId); - public RemoveImageCmd removeImageCmd(String imageId); - public RestartContainerCmd restartContainerCmd(String containerId); - public SearchImagesCmd searchImagesCmd(String searchTerm); - public StartContainerCmd startContainerCmd(String containerId); - public StopContainerCmd stopContainerCmd(String containerId); - public TagImageCmd tagImageCmd(String imageId, String repository, String tag); - public TopContainerCmd topContainerCmd(String containerId); - public UnpauseContainerCmd unpauseContainerCmd(String containerId); - public VersionCmd versionCmd(); - public WaitContainerCmd waitContainerCmd(String containerId); - public PingCmd pingCmd(); -} diff --git a/src/main/java/com/github/dockerjava/client/command/DefaultCommandFactory.java b/src/main/java/com/github/dockerjava/client/command/DefaultCommandFactory.java deleted file mode 100644 index a8b6d254..00000000 --- a/src/main/java/com/github/dockerjava/client/command/DefaultCommandFactory.java +++ /dev/null @@ -1,163 +0,0 @@ -package com.github.dockerjava.client.command; - -import com.github.dockerjava.client.model.AuthConfig; - -import java.io.File; -import java.io.InputStream; - -public class DefaultCommandFactory implements CommandFactory { - @Override - public AttachContainerCmd attachContainerCmd(String containerId) { - return new AttachContainerCmd(containerId); - } - - @Override - public AuthCmd authCmd(AuthConfig authConfig) { - return new AuthCmd(authConfig); - } - - @Override - public BuildImgCmd buildImgCmd(File dockerFolder) { - return new BuildImgCmd(dockerFolder); - } - - @Override - public BuildImgCmd buildImgCmd(InputStream tarInputStream) { - return new BuildImgCmd(tarInputStream); - } - - @Override - public CommitCmd commitCmd(String containerId) { - return new CommitCmd(containerId); - } - - @Override - public ContainerDiffCmd containerDiffCmd(String containerId) { - return new ContainerDiffCmd(containerId); - } - - @Override - public CopyFileFromContainerCmd copyFileFromContainerCmd(String containerId, String resource) { - return new CopyFileFromContainerCmd(containerId, resource); - } - - @Override - public CreateContainerCmd createContainerCmd(String image) { - return new CreateContainerCmd(image); - } - - @Override - public CreateImageCmd createImageCmd(String repository, InputStream imageStream) { - return new CreateImageCmd(repository, imageStream); - } - - @Override - public InfoCmd infoCmd() { - return new InfoCmd(); - } - - @Override - public InspectContainerCmd inspectContainerCmd(String containerId) { - return new InspectContainerCmd(containerId); - } - - @Override - public InspectImageCmd inspectImageCmd(String imageId) { - return new InspectImageCmd(imageId); - } - - @Override - public KillContainerCmd killContainerCmd(String containerId) { - return new KillContainerCmd(containerId); - } - - @Override - public ListContainersCmd listContainersCmd() { - return new ListContainersCmd(); - } - - @Override - public ListImagesCmd listImagesCmd() { - return new ListImagesCmd(); - } - - @Override - public LogContainerCmd logContainerCmd(String containerId) { - return new LogContainerCmd(containerId); - } - - @Override - public PauseContainerCmd pauseContainerCmd(String containerId) { - return new PauseContainerCmd(containerId); - } - - @Override - public PullImageCmd pullImageCmd(String repository) { - return new PullImageCmd(repository); - } - - @Override - public PushImageCmd pushImageCmd(String imageName) { - return new PushImageCmd(imageName); - } - - @Override - public RemoveContainerCmd removeContainerCmd(String containerId) { - return new RemoveContainerCmd(containerId); - } - - @Override - public RemoveImageCmd removeImageCmd(String imageId) { - return new RemoveImageCmd(imageId); - } - - @Override - public RestartContainerCmd restartContainerCmd(String containerId) { - return new RestartContainerCmd(containerId); - } - - @Override - public SearchImagesCmd searchImagesCmd(String searchTerm) { - return new SearchImagesCmd(searchTerm); - } - - @Override - public StartContainerCmd startContainerCmd(String containerId) { - return new StartContainerCmd(containerId); - } - - @Override - public StopContainerCmd stopContainerCmd(String containerId) { - return new StopContainerCmd(containerId); - } - - @Override - public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { - return new TagImageCmd(imageId, repository, tag); - } - - @Override - public TopContainerCmd topContainerCmd(String containerId) { - return new TopContainerCmd(containerId); - } - - @Override - public UnpauseContainerCmd unpauseContainerCmd(String containerId) { - return new UnpauseContainerCmd(containerId); - } - - @Override - public VersionCmd versionCmd() { - return new VersionCmd(); - } - - @Override - public WaitContainerCmd waitContainerCmd(String containerId) { - return new WaitContainerCmd(containerId); - } - - @Override - public PingCmd pingCmd() { - return new PingCmd(); - } -} diff --git a/src/main/java/com/github/dockerjava/jaxrs1/JaxRs1Client.java b/src/main/java/com/github/dockerjava/jaxrs1/JaxRs1Client.java new file mode 100644 index 00000000..d2ebe974 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs1/JaxRs1Client.java @@ -0,0 +1,358 @@ +package com.github.dockerjava.jaxrs1; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.apache.commons.io.IOUtils.closeQuietly; + +import java.io.*; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.AttachContainerCmd; +import com.github.dockerjava.api.command.AuthCmd; +import com.github.dockerjava.api.command.BuildImageCmd; +import com.github.dockerjava.api.command.CommitCmd; +import com.github.dockerjava.api.command.ContainerDiffCmd; +import com.github.dockerjava.api.command.CopyFileFromContainerCmd; +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.command.CreateImageCmd; +import com.github.dockerjava.api.command.InfoCmd; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectImageCmd; +import com.github.dockerjava.api.command.KillContainerCmd; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.command.ListImagesCmd; +import com.github.dockerjava.api.command.LogContainerCmd; +import com.github.dockerjava.api.command.PauseContainerCmd; +import com.github.dockerjava.api.command.PingCmd; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.command.PushImageCmd; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.command.RemoveImageCmd; +import com.github.dockerjava.api.command.RestartContainerCmd; +import com.github.dockerjava.api.command.SearchImagesCmd; +import com.github.dockerjava.api.command.StartContainerCmd; +import com.github.dockerjava.api.command.StopContainerCmd; +import com.github.dockerjava.api.command.TagImageCmd; +import com.github.dockerjava.api.command.TopContainerCmd; +import com.github.dockerjava.api.command.UnpauseContainerCmd; +import com.github.dockerjava.api.command.VersionCmd; +import com.github.dockerjava.api.command.WaitContainerCmd; +import com.github.dockerjava.client.DockerClientConfig; +import com.github.dockerjava.client.SelectiveLoggingFilter; +import com.github.dockerjava.client.command.*; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.io.LineIterator; +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 com.github.dockerjava.client.model.AuthConfig; +import com.github.dockerjava.client.utils.JsonClientFilter; +import com.github.dockerjava.jaxrs1.command.AttachContainerCommand; +import com.github.dockerjava.jaxrs1.command.AuthCommand; +import com.github.dockerjava.jaxrs1.command.BuildImageCommand; +import com.github.dockerjava.jaxrs1.command.CommitCommand; +import com.github.dockerjava.jaxrs1.command.ContainerDiffCommand; +import com.github.dockerjava.jaxrs1.command.CopyFileFromContainerCommand; +import com.github.dockerjava.jaxrs1.command.CreateContainerCommand; +import com.github.dockerjava.jaxrs1.command.CreateImageCommand; +import com.github.dockerjava.jaxrs1.command.InfoCommand; +import com.github.dockerjava.jaxrs1.command.InspectContainerCommand; +import com.github.dockerjava.jaxrs1.command.InspectImageCommand; +import com.github.dockerjava.jaxrs1.command.KillContainerCommand; +import com.github.dockerjava.jaxrs1.command.ListContainersCommand; +import com.github.dockerjava.jaxrs1.command.ListImagesCommand; +import com.github.dockerjava.jaxrs1.command.LogContainerCommand; +import com.github.dockerjava.jaxrs1.command.PauseContainerCommand; +import com.github.dockerjava.jaxrs1.command.PingCommand; +import com.github.dockerjava.jaxrs1.command.PullImageCommand; +import com.github.dockerjava.jaxrs1.command.PushImageCommand; +import com.github.dockerjava.jaxrs1.command.RemoveContainerCommand; +import com.github.dockerjava.jaxrs1.command.RemoveImageCommand; +import com.github.dockerjava.jaxrs1.command.RestartContainerCommand; +import com.github.dockerjava.jaxrs1.command.SearchImagesCommand; +import com.github.dockerjava.jaxrs1.command.StartContainerCommand; +import com.github.dockerjava.jaxrs1.command.StopContainerCommand; +import com.github.dockerjava.jaxrs1.command.TagImageCommand; +import com.github.dockerjava.jaxrs1.command.TopContainerCommand; +import com.github.dockerjava.jaxrs1.command.UnpauseContainerCommand; +import com.github.dockerjava.jaxrs1.command.VersionCommand; +import com.github.dockerjava.jaxrs1.command.WaitContainerCommand; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.client.apache4.ApacheHttpClient4; +import com.sun.jersey.client.apache4.ApacheHttpClient4Handler; + +/** + * @author Konstantin Pelykh (kpelykh@gmail.com) + */ +public class JaxRs1Client implements DockerClient { + + private final Client client; + private final WebResource baseResource; + private final DockerClientConfig config; + + public JaxRs1Client() { + this(DockerClientConfig.createDefaultConfigBuilder().build()); + } + + public JaxRs1Client(String serverUrl) { + this(configWithServerUrl(serverUrl)); + } + + private static DockerClientConfig configWithServerUrl(String serverUrl) { + return DockerClientConfig.createDefaultConfigBuilder() + .withUri(serverUrl).build(); + } + + public JaxRs1Client(DockerClientConfig config) { + this.config = config; + + HttpClient httpClient = getPoolingHttpClient(config); + ClientConfig clientConfig = new DefaultClientConfig(); + client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, + null, false), clientConfig); + + if (config.getReadTimeout() != null) { + client.setReadTimeout(config.getReadTimeout()); + } + + client.addFilter(new JsonClientFilter()); + + if (config.isLoggingFilterEnabled()) + client.addFilter(new SelectiveLoggingFilter()); + + WebResource webResource = client.resource(config.getUri()); + + if (config.getVersion() != null) { + baseResource = webResource.path("v" + config.getVersion()); + } else { + baseResource = webResource; + } + + } + + private HttpClient getPoolingHttpClient( + DockerClientConfig dockerClientConfig) { + SchemeRegistry schemeRegistry = new SchemeRegistry(); + schemeRegistry.register(new Scheme("http", dockerClientConfig.getUri() + .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); + + return new DefaultHttpClient(cm); + } + + @Override + public AuthConfig authConfig() throws DockerException { + checkNotNull(config.getUsername(), + "Configured username is null."); + checkNotNull(config.getPassword(), + "Configured password is null."); + checkNotNull(config.getEmail(), "Configured email is null."); + + AuthConfig authConfig = new AuthConfig(); + authConfig.setUsername(config.getUsername()); + authConfig.setPassword(config.getPassword()); + authConfig.setEmail(config.getEmail()); + // TODO Make the registry address configurable + return authConfig; + } + + @Override + public AttachContainerCmd attachContainerCmd(String containerId) { + return new AttachContainerCommand(containerId).withBaseResource(baseResource); + } + + @Override + public AuthCmd authCmd() { + return new AuthCommand(authConfig()).withBaseResource(baseResource); + } + + @Override + public BuildImageCmd buildImageCmd(File dockerFolder) { + return new BuildImageCommand(dockerFolder).withBaseResource(baseResource); + } + + @Override + public BuildImageCmd buildImageCmd(InputStream tarInputStream) { + return new BuildImageCommand(tarInputStream).withBaseResource(baseResource); + } + + @Override + public CommitCmd commitCmd(String containerId) { + return new CommitCommand(containerId).withBaseResource(baseResource); + } + + @Override + public ContainerDiffCmd containerDiffCmd(String containerId) { + return new ContainerDiffCommand(containerId).withBaseResource(baseResource); + } + + @Override + public CopyFileFromContainerCmd copyFileFromContainerCmd(String containerId, String resource) { + return new CopyFileFromContainerCommand(containerId, resource).withBaseResource(baseResource); + } + + @Override + public CreateContainerCmd createContainerCmd(String image) { + return new CreateContainerCommand(image).withBaseResource(baseResource); + } + + @Override + public CreateImageCmd createImageCmd(String repository, InputStream imageStream) { + return new CreateImageCommand(repository, imageStream).withBaseResource(baseResource); + } + + @Override + public InfoCmd infoCmd() { + return new InfoCommand().withBaseResource(baseResource); + } + + @Override + public InspectContainerCmd inspectContainerCmd(String containerId) { + return new InspectContainerCommand(containerId).withBaseResource(baseResource); + } + + @Override + public InspectImageCmd inspectImageCmd(String imageId) { + return new InspectImageCommand(imageId).withBaseResource(baseResource); + } + + @Override + public KillContainerCmd killContainerCmd(String containerId) { + return new KillContainerCommand(containerId).withBaseResource(baseResource); + } + + @Override + public ListContainersCmd listContainersCmd() { + return new ListContainersCommand().withBaseResource(baseResource); + } + + @Override + public ListImagesCmd listImagesCmd() { + return new ListImagesCommand().withBaseResource(baseResource); + } + + @Override + public LogContainerCmd logContainerCmd(String containerId) { + return new LogContainerCommand(containerId).withBaseResource(baseResource); + } + + @Override + public PauseContainerCmd pauseContainerCmd(String containerId) { + return new PauseContainerCommand(containerId).withBaseResource(baseResource); + } + + @Override + public PullImageCmd pullImageCmd(String repository) { + return new PullImageCommand(repository).withBaseResource(baseResource); + } + + @Override + public PushImageCmd pushImageCmd(String imageName) { + return new PushImageCommand(imageName).withBaseResource(baseResource); + } + + @Override + public RemoveContainerCmd removeContainerCmd(String containerId) { + return new RemoveContainerCommand(containerId).withBaseResource(baseResource); + } + + @Override + public RemoveImageCmd removeImageCmd(String imageId) { + return new RemoveImageCommand(imageId).withBaseResource(baseResource); + } + + @Override + public RestartContainerCmd restartContainerCmd(String containerId) { + return new RestartContainerCommand(containerId).withBaseResource(baseResource); + } + + @Override + public SearchImagesCmd searchImagesCmd(String searchTerm) { + return new SearchImagesCommand(searchTerm).withBaseResource(baseResource); + } + + @Override + public StartContainerCmd startContainerCmd(String containerId) { + return new StartContainerCommand(containerId).withBaseResource(baseResource); + } + + @Override + public StopContainerCmd stopContainerCmd(String containerId) { + return new StopContainerCommand(containerId).withBaseResource(baseResource); + } + + @Override + public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { + return new TagImageCommand(imageId, repository, tag).withBaseResource(baseResource); + } + + @Override + public TopContainerCmd topContainerCmd(String containerId) { + return new TopContainerCommand(containerId).withBaseResource(baseResource); + } + + @Override + public UnpauseContainerCmd unpauseContainerCmd(String containerId) { + return new UnpauseContainerCommand(containerId).withBaseResource(baseResource); + } + + @Override + public VersionCmd versionCmd() { + return new VersionCommand().withBaseResource(baseResource); + } + + @Override + public WaitContainerCmd waitContainerCmd(String containerId) { + return new WaitContainerCommand(containerId).withBaseResource(baseResource); + } + + @Override + public PingCmd pingCmd() { + return new PingCommand().withBaseResource(baseResource); + } + + @Override + public void close() throws IOException { + client.destroy(); + } + + // TODO This is only being used by the test code for logging. Is it really + // necessary? + /** + * @return The output slurped into a string. + */ + public static String asString(InputStream response) throws IOException { + + StringWriter out = new StringWriter(); + try { + LineIterator itr = IOUtils.lineIterator(response, "UTF-8"); + while (itr.hasNext()) { + String line = itr.next(); + out.write(line + (itr.hasNext() ? "\n" : "")); + } + } finally { + closeQuietly(response); + } + return out.toString(); + } + + + +} diff --git a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/AttachContainerCommand.java similarity index 85% rename from src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/AttachContainerCommand.java index 5ee1a1db..b1cdaf38 100644 --- a/src/main/java/com/github/dockerjava/client/command/AttachContainerCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/AttachContainerCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.io.InputStream; @@ -9,6 +9,8 @@ import org.slf4j.LoggerFactory; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.AttachContainerCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; @@ -30,43 +32,50 @@ * - true or false, if true, print timestamps for every log line. * Defaults to false. */ -public class AttachContainerCmd extends AbstrDockerCmd { +public class AttachContainerCommand extends AbstrDockerCmd implements AttachContainerCmd { private static final Logger LOGGER = LoggerFactory - .getLogger(AttachContainerCmd.class); + .getLogger(AttachContainerCommand.class); private String containerId; private boolean logs, followStream, timestamps, stdout, stderr; - public AttachContainerCmd(String containerId) { + public AttachContainerCommand(String containerId) { withContainerId(containerId); } + @Override public String getContainerId() { return containerId; } + @Override public boolean hasLogsEnabled() { return logs; } + @Override public boolean hasFollowStreamEnabled() { return followStream; } + @Override public boolean hasTimestampsEnabled() { return timestamps; } + @Override public boolean hasStdoutEnabled() { return stdout; } + @Override public boolean hasStderrEnabled() { return stderr; } + @Override public AttachContainerCmd withContainerId(String containerId) { Preconditions .checkNotNull(containerId, "containerId was not specified"); @@ -74,38 +83,46 @@ public AttachContainerCmd withContainerId(String containerId) { return this; } + @Override public AttachContainerCmd withFollowStream() { return withFollowStream(true); } + @Override public AttachContainerCmd withFollowStream(boolean followStream) { this.followStream = followStream; return this; } + @Override public AttachContainerCmd withTimestamps(boolean timestamps) { this.timestamps = timestamps; return this; } + @Override public AttachContainerCmd withStdOut() { return withStdOut(true); } + @Override public AttachContainerCmd withStdOut(boolean stdout) { this.stdout = stdout; return this; } + @Override public AttachContainerCmd withStdErr() { return withStdErr(true); } + @Override public AttachContainerCmd withStdErr(boolean stderr) { this.stderr = stderr; return this; } + @Override public AttachContainerCmd withLogs(boolean logs) { this.logs = logs; return this; diff --git a/src/main/java/com/github/dockerjava/client/command/AuthCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/AuthCommand.java similarity index 71% rename from src/main/java/com/github/dockerjava/client/command/AuthCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/AuthCommand.java index 3ee1221b..d1e66ecd 100644 --- a/src/main/java/com/github/dockerjava/client/command/AuthCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/AuthCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; @@ -6,6 +6,8 @@ import org.slf4j.LoggerFactory; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.AuthCmd; +import com.github.dockerjava.client.command.AbstrAuthCfgDockerCmd; import com.github.dockerjava.client.model.AuthConfig; import com.sun.jersey.api.client.WebResource; @@ -14,11 +16,11 @@ * Authenticate with the server, useful for checking authentication. * */ -public class AuthCmd extends AbstrAuthCfgDockerCmd { +public class AuthCommand extends AbstrAuthCfgDockerCmd implements AuthCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(AuthCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(AuthCommand.class); - public AuthCmd(AuthConfig authConfig) { + public AuthCommand(AuthConfig authConfig) { withAuthConfig(authConfig); } diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/BuildImageCommand.java similarity index 90% rename from src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/BuildImageCommand.java index 0699bfa5..1d1fb4dd 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImgCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/BuildImageCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.io.File; import java.io.IOException; @@ -22,6 +22,8 @@ import com.github.dockerjava.api.DockerClientException; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.BuildImageCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.github.dockerjava.client.utils.CompressArchiveUtil; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; @@ -35,10 +37,10 @@ * TODO: http://docs.docker.com/reference/builder/#dockerignore * */ -public class BuildImgCmd extends AbstrDockerCmd { +public class BuildImageCommand extends AbstrDockerCmd implements BuildImageCmd { private static final Logger LOGGER = LoggerFactory - .getLogger(BuildImgCmd.class); + .getLogger(BuildImageCommand.class); private static final Pattern ADD_OR_COPY_PATTERN = Pattern .compile("^(ADD|COPY)\\s+(.*)\\s+(.*)$"); @@ -53,57 +55,67 @@ public class BuildImgCmd extends AbstrDockerCmd { private boolean remove = true; private boolean quiet; - public BuildImgCmd(File dockerFolder) { + public BuildImageCommand(File dockerFolder) { Preconditions.checkNotNull(dockerFolder, "dockerFolder is null"); this.dockerFolder = dockerFolder; } - public BuildImgCmd(InputStream tarInputStream) { + public BuildImageCommand(InputStream tarInputStream) { Preconditions.checkNotNull(tarInputStream, "tarInputStream is null"); this.tarInputStream = tarInputStream; } - public BuildImgCmd withTag(String tag) { + @Override + public BuildImageCommand withTag(String tag) { Preconditions.checkNotNull(tag, "Tag is null"); this.tag = tag; return this; } + @Override public File getDockerFolder() { return dockerFolder; } + @Override public String getTag() { return tag; } + @Override public boolean hasNoCacheEnabled() { return noCache; } + @Override public boolean hasRemoveEnabled() { return remove; } + @Override public boolean isQuiet() { return quiet; } - public BuildImgCmd withNoCache() { + @Override + public BuildImageCommand withNoCache() { return withNoCache(true); } - public BuildImgCmd withNoCache(boolean noCache) { + @Override + public BuildImageCommand withNoCache(boolean noCache) { this.noCache = noCache; return this; } - public BuildImgCmd withRemove(boolean rm) { + @Override + public BuildImageCommand withRemove(boolean rm) { this.remove = rm; return this; } - public BuildImgCmd withQuiet(boolean quiet) { + @Override + public BuildImageCommand withQuiet(boolean quiet) { this.quiet = quiet; return this; } diff --git a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/CommitCommand.java similarity index 66% rename from src/main/java/com/github/dockerjava/client/command/CommitCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/CommitCommand.java index 6da0a3ea..e3dec0d8 100644 --- a/src/main/java/com/github/dockerjava/client/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/CommitCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -6,6 +6,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.CommitCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.github.dockerjava.client.model.ExposedPorts; import com.github.dockerjava.client.model.Volumes; @@ -23,9 +25,9 @@ * Create a new image from a container's changes. Returns the new image ID. * */ -public class CommitCmd extends AbstrDockerCmd { +public class CommitCommand extends AbstrDockerCmd implements CommitCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(CommitCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CommitCommand.class); private String containerId, repository, tag, message, author; @@ -83,223 +85,277 @@ public class CommitCmd extends AbstrDockerCmd { private String workingDir; - public CommitCmd(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); - this.containerId = containerId; + public CommitCommand(String containerId) { + withContainerId(containerId); } - public String getContainerId() { + @Override + public String getContainerId() { return containerId; } - public String getRepository() { + @Override + public CommitCommand withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + + @Override + public String getRepository() { return repository; } - public String getTag() { + @Override + public String getTag() { return tag; } - public String getMessage() { + @Override + public String getMessage() { return message; } - public String getAuthor() { + @Override + public String getAuthor() { return author; } - public boolean hasPauseEnabled() { + @Override + public boolean hasPauseEnabled() { return pause; } + + - public CommitCmd withAttachStderr(boolean attachStderr) { + @Override + public CommitCommand withAttachStderr(boolean attachStderr) { this.attachStderr = attachStderr; return this; } - public CommitCmd withAttachStderr() { + @Override + public CommitCommand withAttachStderr() { return withAttachStderr(true); } - public CommitCmd withAttachStdin(boolean attachStdin) { + @Override + public CommitCommand withAttachStdin(boolean attachStdin) { this.attachStdin = attachStdin; return this; } - public CommitCmd withAttachStdin() { + @Override + public CommitCommand withAttachStdin() { return withAttachStdin(true); } - public CommitCmd withAttachStdout(boolean attachStdout) { + @Override + public CommitCommand withAttachStdout(boolean attachStdout) { this.attachStdout = attachStdout; return this; } - public CommitCmd withAttachStdout() { + @Override + public CommitCommand withAttachStdout() { return withAttachStdout(true); } - public CommitCmd withCmd(String... cmd) { + @Override + public CommitCommand withCmd(String... cmd) { Preconditions.checkNotNull(cmd, "cmd was not specified"); this.cmd = cmd; return this; } - public CommitCmd withDisableNetwork(boolean disableNetwork) { + @Override + public CommitCommand withDisableNetwork(boolean disableNetwork) { this.disableNetwork = disableNetwork; return this; } - public CommitCmd withAuthor(String author) { + @Override + public CommitCommand withAuthor(String author) { Preconditions.checkNotNull(author, "author was not specified"); this.author = author; return this; } - public CommitCmd withMessage(String message) { + @Override + public CommitCommand withMessage(String message) { Preconditions.checkNotNull(message, "message was not specified"); this.message = message; return this; } - public CommitCmd withTag(String tag) { + @Override + public CommitCommand withTag(String tag) { Preconditions.checkNotNull(tag, "tag was not specified"); this.tag = tag; return this; } - public CommitCmd withRepository(String repository) { + @Override + public CommitCommand withRepository(String repository) { Preconditions.checkNotNull(repository, "repository was not specified"); this.repository = repository; return this; } - public CommitCmd withPause(boolean pause) { + @Override + public CommitCommand withPause(boolean pause) { this.pause = pause; return this; } + @Override public String[] getEnv() { return env; } - public CommitCmd withEnv(String... env) { + @Override + public CommitCommand withEnv(String... env) { Preconditions.checkNotNull(env, "env was not specified"); this.env = env; return this; } - public ExposedPorts getExposedPorts() { + @Override + public ExposedPorts getExposedPorts() { return exposedPorts; } - public CommitCmd withExposedPorts(ExposedPorts exposedPorts) { + @Override + public CommitCommand withExposedPorts(ExposedPorts exposedPorts) { Preconditions.checkNotNull(exposedPorts, "exposedPorts was not specified"); this.exposedPorts = exposedPorts; return this; } - public String getHostname() { + @Override + public String getHostname() { return hostname; } - public CommitCmd withHostname(String hostname) { + @Override + public CommitCommand withHostname(String hostname) { Preconditions.checkNotNull(hostname, "hostname was not specified"); this.hostname = hostname; return this; } - public Integer getMemory() { + @Override + public Integer getMemory() { return memory; } - public CommitCmd withMemory(Integer memory) { + @Override + public CommitCommand withMemory(Integer memory) { Preconditions.checkNotNull(memory, "memory was not specified"); this.memory = memory; return this; } - public Integer getMemorySwap() { + @Override + public Integer getMemorySwap() { return memorySwap; } - public CommitCmd withMemorySwap(Integer memorySwap) { + @Override + public CommitCommand withMemorySwap(Integer memorySwap) { Preconditions.checkNotNull(memorySwap, "memorySwap was not specified"); this.memorySwap = memorySwap; return this; } - public boolean isOpenStdin() { + @Override + public boolean isOpenStdin() { return openStdin; } - public CommitCmd withOpenStdin(boolean openStdin) { + @Override + public CommitCommand withOpenStdin(boolean openStdin) { Preconditions.checkNotNull(openStdin, "openStdin was not specified"); this.openStdin = openStdin; return this; } - public String[] getPortSpecs() { + @Override + public String[] getPortSpecs() { return portSpecs; } - public CommitCmd withPortSpecs(String... portSpecs) { + @Override + public CommitCommand withPortSpecs(String... portSpecs) { Preconditions.checkNotNull(portSpecs, "portSpecs was not specified"); this.portSpecs = portSpecs; return this; } - public boolean isStdinOnce() { + @Override + public boolean isStdinOnce() { return stdinOnce; } - public CommitCmd withStdinOnce(boolean stdinOnce) { + @Override + public CommitCommand withStdinOnce(boolean stdinOnce) { this.stdinOnce = stdinOnce; return this; } - public CommitCmd withStdinOnce() { + @Override + public CommitCommand withStdinOnce() { return withStdinOnce(true); } - public boolean isTty() { + @Override + public boolean isTty() { return tty; } - public CommitCmd withTty(boolean tty) { + @Override + public CommitCommand withTty(boolean tty) { this.tty = tty; return this; } - public CommitCmd withTty() { + @Override + public CommitCommand withTty() { return withTty(true); } - public String getUser() { + @Override + public String getUser() { return user; } - public CommitCmd withUser(String user) { + @Override + public CommitCommand withUser(String user) { Preconditions.checkNotNull(user, "user was not specified"); this.user = user; return this; } - public Volumes getVolumes() { + @Override + public Volumes getVolumes() { return volumes; } - public CommitCmd withVolumes(Volumes volumes) { + @Override + public CommitCommand withVolumes(Volumes volumes) { Preconditions.checkNotNull(volumes, "volumes was not specified"); this.volumes = volumes; return this; } - public String getWorkingDir() { + @Override + public String getWorkingDir() { return workingDir; } - public CommitCmd withWorkingDir(String workingDir) { + @Override + public CommitCommand withWorkingDir(String workingDir) { Preconditions.checkNotNull(workingDir, "workingDir was not specified"); this.workingDir = workingDir; return this; diff --git a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/ContainerDiffCommand.java similarity index 76% rename from src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/ContainerDiffCommand.java index ec7a6319..bcafe6db 100644 --- a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/ContainerDiffCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.util.List; @@ -10,6 +10,8 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.InternalServerErrorException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.ContainerDiffCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.github.dockerjava.client.model.ChangeLog; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.GenericType; @@ -21,27 +23,29 @@ * @param containerId - Id of the container * */ -public class ContainerDiffCmd extends AbstrDockerCmd> { +public class ContainerDiffCommand extends AbstrDockerCmd> implements ContainerDiffCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(ContainerDiffCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ContainerDiffCommand.class); private String containerId; - public ContainerDiffCmd(String containerId) { + public ContainerDiffCommand(String containerId) { withContainerId(containerId); } - public String getContainerId() { + @Override + public String getContainerId() { return containerId; } - public ContainerDiffCmd withContainerId(String containerId) { + @Override + public ContainerDiffCommand withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } - @Override + @Override public String toString() { return new StringBuilder("diff ").append(containerId).toString(); } @@ -51,7 +55,7 @@ public String toString() { * @throws InternalServerErrorException server error * @throws DockerException unexpected http status code */ - @Override + @Override public List exec() throws NotFoundException { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/CopyFileFromContainerCommand.java similarity index 73% rename from src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/CopyFileFromContainerCommand.java index e08e697b..62ad1e1a 100644 --- a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/CopyFileFromContainerCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.io.InputStream; @@ -12,6 +12,8 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.CopyFileFromContainerCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; @@ -21,9 +23,9 @@ * Copy files or folders from a container. * */ -public class CopyFileFromContainerCmd extends AbstrDockerCmd { +public class CopyFileFromContainerCommand extends AbstrDockerCmd implements CopyFileFromContainerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(CopyFileFromContainerCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CopyFileFromContainerCommand.class); private String containerId; @@ -33,42 +35,48 @@ public class CopyFileFromContainerCmd extends AbstrDockerCmd { +public class CreateContainerCommand extends AbstrDockerCmd implements CreateContainerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(CreateContainerCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CreateContainerCommand.class); private String name; @@ -51,207 +54,249 @@ public class CreateContainerCmd extends AbstrDockerCmd { +public class CreateImageCommand extends AbstrDockerCmd implements CreateImageCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(CreateImageCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CreateImageCommand.class); private String repository, tag; private InputStream imageStream; @@ -28,23 +30,26 @@ public class CreateImageCmd extends AbstrDockerCmd { +public class InfoCommand extends AbstrDockerCmd implements InfoCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(InfoCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(InfoCommand.class); - @Override + @Override public String toString() { return "info"; } diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/InspectContainerCommand.java similarity index 67% rename from src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/InspectContainerCommand.java index f0353c5f..5f4d4197 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectContainerCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/InspectContainerCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; @@ -7,27 +7,32 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; /** * Inspect the details of a container. */ -public class InspectContainerCmd extends AbstrDockerCmd { +public class InspectContainerCommand extends AbstrDockerCmd implements InspectContainerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(InspectContainerCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(InspectContainerCommand.class); private String containerId; - public InspectContainerCmd(String containerId) { + public InspectContainerCommand(String containerId) { withContainerId(containerId); } - public String getContainerId() { + @Override + public String getContainerId() { return containerId; } - public InspectContainerCmd withContainerId(String containerId) { + @Override + public InspectContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; @@ -41,7 +46,7 @@ public String toString() { /** * @throws NotFoundException No such container */ - @Override + @Override public InspectContainerResponse exec() throws NotFoundException { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/InspectImageCommand.java similarity index 66% rename from src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/InspectImageCommand.java index fecf0f42..2653eb48 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectImageCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/InspectImageCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; @@ -6,6 +6,9 @@ import org.slf4j.LoggerFactory; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.InspectImageCmd; +import com.github.dockerjava.api.command.InspectImageResponse; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; @@ -13,21 +16,23 @@ /** * Inspect the details of an image. */ -public class InspectImageCmd extends AbstrDockerCmd { +public class InspectImageCommand extends AbstrDockerCmd implements InspectImageCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(InspectImageCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(InspectImageCommand.class); private String imageId; - public InspectImageCmd(String imageId) { + public InspectImageCommand(String imageId) { withImageId(imageId); } - public String getImageId() { + @Override + public String getImageId() { return imageId; } - public InspectImageCmd withImageId(String imageId) { + @Override + public InspectImageCmd withImageId(String imageId) { Preconditions.checkNotNull(imageId, "imageId was not specified"); this.imageId = imageId; return this; @@ -41,7 +46,7 @@ public String toString() { /** * @throws NotFoundException No such image */ - @Override + @Override public InspectImageResponse exec() throws NotFoundException { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/KillContainerCommand.java similarity index 73% rename from src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/KillContainerCommand.java index 58bd90d9..5e37da85 100644 --- a/src/main/java/com/github/dockerjava/client/command/KillContainerCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/KillContainerCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; @@ -7,36 +7,42 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.KillContainerCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; /** * Kill a running container. */ -public class KillContainerCmd extends AbstrDockerCmd { +public class KillContainerCommand extends AbstrDockerCmd implements KillContainerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(KillContainerCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(KillContainerCommand.class); private String containerId, signal; - public KillContainerCmd(String containerId) { + public KillContainerCommand(String containerId) { withContainerId(containerId); } - public String getContainerId() { + @Override + public String getContainerId() { return containerId; } - public String getSignal() { + @Override + public String getSignal() { return signal; } - public KillContainerCmd withContainerId(String containerId) { + @Override + public KillContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } + @Override public KillContainerCmd withSignal(String signal) { Preconditions.checkNotNull(signal, "signal was not specified"); this.signal = signal; @@ -51,7 +57,7 @@ public String toString() { /** * @throws NotFoundException No such container */ - @Override + @Override public Void exec() throws NotFoundException { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/ListContainersCommand.java similarity index 81% rename from src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/ListContainersCommand.java index 226e1680..d0d8b147 100644 --- a/src/main/java/com/github/dockerjava/client/command/ListContainersCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/ListContainersCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.util.List; @@ -8,6 +8,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.github.dockerjava.client.model.Container; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.GenericType; @@ -25,56 +27,66 @@ * @param beforeId - Show only containers created before Id, include non-running ones. * */ -public class ListContainersCmd extends AbstrDockerCmd> { +public class ListContainersCommand extends AbstrDockerCmd> implements ListContainersCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(ListContainersCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ListContainersCommand.class); private int limit = -1; private boolean showSize, showAll = false; String sinceId, beforeId; - public int getLimit() { + @Override + public int getLimit() { return limit; } - public boolean hasShowSizeEnabled() { + @Override + public boolean hasShowSizeEnabled() { return showSize; } - public boolean hasShowAllEnabled() { + @Override + public boolean hasShowAllEnabled() { return showAll; } - public String getSinceId() { + @Override + public String getSinceId() { return sinceId; } - public String getBeforeId() { + @Override + public String getBeforeId() { return beforeId; } - public ListContainersCmd withShowAll(boolean showAll) { + @Override + public ListContainersCmd withShowAll(boolean showAll) { this.showAll = showAll; return this; } + @Override public ListContainersCmd withShowSize(boolean showSize) { this.showSize = showSize; return this; } + @Override public ListContainersCmd withLimit(int limit) { Preconditions.checkArgument(limit > 0, "limit must be greater 0"); this.limit = limit; return this; } + @Override public ListContainersCmd withSince(String since) { Preconditions.checkNotNull(since, "since was not specified"); this.sinceId = since; return this; } + @Override public ListContainersCmd withBefore(String before) { Preconditions.checkNotNull(before, "before was not specified"); this.beforeId = before; diff --git a/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/ListImagesCommand.java similarity index 78% rename from src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/ListImagesCommand.java index 64581a61..18382bd8 100644 --- a/src/main/java/com/github/dockerjava/client/command/ListImagesCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/ListImagesCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.util.List; @@ -8,6 +8,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.dockerjava.api.command.ListImagesCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.github.dockerjava.client.model.Image; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.GenericType; @@ -21,26 +23,30 @@ * @param showAll - Show all images (by default filter out the intermediate images used to build) * @param filter - TODO: undocumented in docker remote api reference */ -public class ListImagesCmd extends AbstrDockerCmd> { +public class ListImagesCommand extends AbstrDockerCmd> implements ListImagesCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(ListImagesCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ListImagesCommand.class); private String filter; private boolean showAll = false; - public String getFilter() { + @Override + public String getFilter() { return filter; } - public boolean hasShowAllEnabled() { + @Override + public boolean hasShowAllEnabled() { return showAll; } - public ListImagesCmd withShowAll(boolean showAll) { + @Override + public ListImagesCmd withShowAll(boolean showAll) { this.showAll = showAll; return this; } + @Override public ListImagesCmd withFilter(String filter) { Preconditions.checkNotNull(filter, "filter was not specified"); this.filter = filter; diff --git a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/LogContainerCommand.java similarity index 80% rename from src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/LogContainerCommand.java index a4c39272..95fd6325 100644 --- a/src/main/java/com/github/dockerjava/client/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/LogContainerCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.io.InputStream; @@ -10,6 +10,8 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.LogContainerCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; @@ -30,10 +32,10 @@ * @param tail * - `all` or ``, Output specified number of lines at the end of logs */ -public class LogContainerCmd extends AbstrDockerCmd { +public class LogContainerCommand extends AbstrDockerCmd implements LogContainerCmd { private static final Logger LOGGER = LoggerFactory - .getLogger(LogContainerCmd.class); + .getLogger(LogContainerCommand.class); private String containerId; @@ -41,78 +43,94 @@ public class LogContainerCmd extends AbstrDockerCmd { +public class PauseContainerCommand extends AbstrDockerCmd implements PauseContainerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(PauseContainerCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PauseContainerCommand.class); private String containerId; - public PauseContainerCmd(String containerId) { + public PauseContainerCommand(String containerId) { withContainerId(containerId); } - public String getContainerId() { + @Override + public String getContainerId() { return containerId; } - public PauseContainerCmd withContainerId(String containerId) { + @Override + public PauseContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; diff --git a/src/main/java/com/github/dockerjava/client/command/PingCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/PingCommand.java similarity index 54% rename from src/main/java/com/github/dockerjava/client/command/PingCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/PingCommand.java index 7bf0fb50..537eb4d9 100644 --- a/src/main/java/com/github/dockerjava/client/command/PingCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/PingCommand.java @@ -1,28 +1,20 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.PingCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** * Ping the Docker server * */ -public class PingCmd extends AbstrDockerCmd { +public class PingCommand extends AbstrDockerCmd implements PingCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(PingCmd.class); - - /** - * A {@link DockerException} is thrown if something gets wrong - */ - @Override - public Void exec() { - return super.exec(); - } + private static final Logger LOGGER = LoggerFactory.getLogger(PingCommand.class); protected Void impl() { WebResource webResource = baseResource.path("/_ping"); diff --git a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/PullImageCommand.java similarity index 75% rename from src/main/java/com/github/dockerjava/client/command/PullImageCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/PullImageCommand.java index b595a77b..e1b64fa9 100644 --- a/src/main/java/com/github/dockerjava/client/command/PullImageCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/PullImageCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.io.InputStream; @@ -8,6 +8,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; @@ -19,40 +21,46 @@ * Pull image from repository. * */ -public class PullImageCmd extends AbstrDockerCmd { +public class PullImageCommand extends AbstrDockerCmd implements PullImageCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(PullImageCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PullImageCommand.class); private String repository, tag, registry; - public PullImageCmd(String repository) { + public PullImageCommand(String repository) { withRepository(repository); } - public String getRepository() { + @Override + public String getRepository() { return repository; } - public String getTag() { + @Override + public String getTag() { return tag; } - public String getRegistry() { + @Override + public String getRegistry() { return registry; } - public PullImageCmd withRepository(String repository) { + @Override + public PullImageCmd withRepository(String repository) { Preconditions.checkNotNull(repository, "repository was not specified"); this.repository = repository; return this; } + @Override public PullImageCmd withTag(String tag) { Preconditions.checkNotNull(tag, "tag was not specified"); this.tag = tag; return this; } + @Override public PullImageCmd withRegistry(String registry) { Preconditions.checkNotNull(registry, "registry was not specified"); this.registry = registry; diff --git a/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/PushImageCommand.java similarity index 80% rename from src/main/java/com/github/dockerjava/client/command/PushImageCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/PushImageCommand.java index 7ffc97ed..d0423a19 100644 --- a/src/main/java/com/github/dockerjava/client/command/PushImageCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/PushImageCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.io.InputStream; @@ -8,6 +8,8 @@ import org.slf4j.LoggerFactory; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.PushImageCmd; +import com.github.dockerjava.client.command.AbstrAuthCfgDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; @@ -18,23 +20,25 @@ * * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. */ -public class PushImageCmd extends AbstrAuthCfgDockerCmd { +public class PushImageCommand extends AbstrAuthCfgDockerCmd implements PushImageCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(PushImageCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PushImageCommand.class); private String name; - public PushImageCmd(String name) { + public PushImageCommand(String name) { withName(name); } - public String getName() { + @Override + public String getName() { return name; } /** * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. */ + @Override public PushImageCmd withName(String name) { Preconditions.checkNotNull(name, "name was not specified"); this.name = name; @@ -51,7 +55,7 @@ public String toString() { /** * @throws NotFoundException No such image */ - @Override + @Override public InputStream exec() throws NotFoundException { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/RemoveContainerCommand.java similarity index 83% rename from src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/RemoveContainerCommand.java index a68e2bfc..7f459a36 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/RemoveContainerCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; @@ -8,6 +8,8 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; @@ -17,46 +19,53 @@ * @param removeVolumes - true or false, Remove the volumes associated to the container. Defaults to false * @param force - true or false, Removes the container even if it was running. Defaults to false */ -public class RemoveContainerCmd extends AbstrDockerCmd { +public class RemoveContainerCommand extends AbstrDockerCmd implements RemoveContainerCmd { private static final Logger LOGGER = LoggerFactory - .getLogger(RemoveContainerCmd.class); + .getLogger(RemoveContainerCommand.class); private String containerId; private boolean removeVolumes, force; - public RemoveContainerCmd(String containerId) { + public RemoveContainerCommand(String containerId) { withContainerId(containerId); } + @Override public String getContainerId() { return containerId; } + @Override public boolean hasRemoveVolumesEnabled() { return removeVolumes; } + @Override public boolean hasForceEnabled() { return force; } + @Override public RemoveContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } + @Override public RemoveContainerCmd withRemoveVolumes(boolean removeVolumes) { this.removeVolumes = removeVolumes; return this; } + @Override public RemoveContainerCmd withForce() { return withForce(true); } + @Override public RemoveContainerCmd withForce(boolean force) { this.force = force; return this; diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/RemoveImageCommand.java similarity index 75% rename from src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/RemoveImageCommand.java index d1a23fb0..46d6e061 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveImageCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/RemoveImageCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; @@ -6,6 +6,8 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.RemoveImageCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; @@ -15,45 +17,52 @@ * Remove an image, deleting any tags it might have. * */ -public class RemoveImageCmd extends AbstrDockerCmd { +public class RemoveImageCommand extends AbstrDockerCmd implements RemoveImageCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(RemoveImageCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(RemoveImageCommand.class); private String imageId; private boolean force, noPrune; - public RemoveImageCmd(String imageId) { + public RemoveImageCommand(String imageId) { withImageId(imageId); } - public String getImageId() { + @Override + public String getImageId() { return imageId; } - public boolean hasForceEnabled() { + @Override + public boolean hasForceEnabled() { return force; } - public boolean hasNoPruneEnabled() { + @Override + public boolean hasNoPruneEnabled() { return noPrune; } - public RemoveImageCmd withImageId(String imageId) { + @Override + public RemoveImageCmd withImageId(String imageId) { Preconditions.checkNotNull(imageId, "imageId was not specified"); this.imageId = imageId; return this; } + @Override public RemoveImageCmd withForce() { return withForce(true); } + @Override public RemoveImageCmd withForce(boolean force) { this.force = force; return this; } + @Override public RemoveImageCmd withNoPrune(boolean noPrune) { this.noPrune = noPrune; return this; @@ -71,7 +80,7 @@ public String toString() { /** * @throws NotFoundException No such image */ - @Override + @Override public Void exec() throws NotFoundException { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/RestartContainerCommand.java similarity index 75% rename from src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/RestartContainerCommand.java index 3c368a17..297f2231 100644 --- a/src/main/java/com/github/dockerjava/client/command/RestartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/RestartContainerCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; @@ -7,6 +7,8 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.RestartContainerCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; @@ -16,32 +18,36 @@ * @param timeout - Timeout in seconds before killing the container. Defaults to 10 seconds. * */ -public class RestartContainerCmd extends AbstrDockerCmd { +public class RestartContainerCommand extends AbstrDockerCmd implements RestartContainerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(RestartContainerCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(RestartContainerCommand.class); private String containerId; private int timeout = 10; - public RestartContainerCmd(String containerId) { + public RestartContainerCommand(String containerId) { withContainerId(containerId); } - public String getContainerId() { + @Override + public String getContainerId() { return containerId; } - public int getTimeout() { + @Override + public int getTimeout() { return timeout; } - public RestartContainerCmd withContainerId(String containerId) { + @Override + public RestartContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } + @Override public RestartContainerCmd withtTimeout(int timeout) { Preconditions.checkArgument(timeout >= 0, "timeout must be greater or equal 0"); this.timeout = timeout; @@ -59,7 +65,7 @@ public String toString() { /** * @throws NotFoundException No such container */ - @Override + @Override public Void exec() throws NotFoundException { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/SearchImagesCommand.java similarity index 67% rename from src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/SearchImagesCommand.java index a34e3365..40b61f66 100644 --- a/src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/SearchImagesCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.util.List; @@ -7,6 +7,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.dockerjava.api.command.SearchImagesCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.github.dockerjava.client.model.SearchItem; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.GenericType; @@ -15,24 +17,26 @@ /** * Search images * - * @param term - search trem + * @param term - search term * */ -public class SearchImagesCmd extends AbstrDockerCmd> { +public class SearchImagesCommand extends AbstrDockerCmd> implements SearchImagesCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(SearchImagesCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SearchImagesCommand.class); private String term; - public SearchImagesCmd(String term) { + public SearchImagesCommand(String term) { withTerm(term); } - public String getTerm() { + @Override + public String getTerm() { return term; } - public SearchImagesCmd withTerm(String term) { + @Override + public SearchImagesCmd withTerm(String term) { Preconditions.checkNotNull(term, "term was not specified"); this.term = term; return this; diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/StartContainerCommand.java similarity index 87% rename from src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/StartContainerCommand.java index c5a13637..1ec452db 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/StartContainerCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; @@ -11,6 +11,8 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; +import com.github.dockerjava.api.command.StartContainerCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.github.dockerjava.client.model.Bind; import com.github.dockerjava.client.model.Binds; import com.github.dockerjava.client.model.Link; @@ -21,12 +23,12 @@ import com.sun.jersey.api.client.WebResource; /** - * Run a container + * Start a container */ -public class StartContainerCmd extends AbstrDockerCmd { +public class StartContainerCommand extends AbstrDockerCmd implements StartContainerCmd { private static final Logger LOGGER = LoggerFactory - .getLogger(StartContainerCmd.class); + .getLogger(StartContainerCommand.class); private String containerId; @@ -54,49 +56,59 @@ public class StartContainerCmd extends AbstrDockerCmd { @JsonProperty("VolumesFrom") private String volumesFrom; - public StartContainerCmd(String containerId) { + public StartContainerCommand(String containerId) { withContainerId(containerId); } + @Override @JsonIgnore public Bind[] getBinds() { return binds.getBinds(); } + @Override @JsonIgnore public Link[] getLinks() { return links.getLinks(); } + @Override public LxcConf[] getLxcConf() { return lxcConf; } + @Override public Ports getPortBindings() { return portBindings; } + @Override public boolean isPublishAllPorts() { return publishAllPorts; } + @Override public boolean isPrivileged() { return privileged; } + @Override public String getDns() { return dns; } + @Override public String getVolumesFrom() { return volumesFrom; } + @Override public String getContainerId() { return containerId; } + @Override @JsonIgnore public StartContainerCmd withBinds(Bind... binds) { Preconditions.checkNotNull(binds, "binds was not specified"); @@ -104,6 +116,7 @@ public StartContainerCmd withBinds(Bind... binds) { return this; } + @Override @JsonIgnore public StartContainerCmd withLinks(Link... links) { Preconditions.checkNotNull(links, "links was not specified"); @@ -111,12 +124,14 @@ public StartContainerCmd withLinks(Link... links) { return this; } + @Override public StartContainerCmd withLxcConf(LxcConf... lxcConf) { Preconditions.checkNotNull(lxcConf, "lxcConf was not specified"); this.lxcConf = lxcConf; return this; } + @Override public StartContainerCmd withPortBindings(Ports portBindings) { Preconditions.checkNotNull(portBindings, "portBindings was not specified"); @@ -124,22 +139,26 @@ public StartContainerCmd withPortBindings(Ports portBindings) { return this; } + @Override public StartContainerCmd withPrivileged(boolean privileged) { this.privileged = privileged; return this; } + @Override public StartContainerCmd withPublishAllPorts(boolean publishAllPorts) { this.publishAllPorts = publishAllPorts; return this; } + @Override public StartContainerCmd withDns(String dns) { Preconditions.checkNotNull(dns, "dns was not specified"); this.dns = dns; return this; } + @Override public StartContainerCmd withVolumesFrom(String volumesFrom) { Preconditions .checkNotNull(volumesFrom, "volumesFrom was not specified"); @@ -147,6 +166,7 @@ public StartContainerCmd withVolumesFrom(String volumesFrom) { return this; } + @Override public StartContainerCmd withContainerId(String containerId) { Preconditions .checkNotNull(containerId, "containerId was not specified"); diff --git a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/StopContainerCommand.java similarity index 77% rename from src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/StopContainerCommand.java index 8df2da37..2ed57b58 100644 --- a/src/main/java/com/github/dockerjava/client/command/StopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/StopContainerCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; @@ -8,6 +8,8 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; +import com.github.dockerjava.api.command.StopContainerCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; @@ -18,32 +20,36 @@ * @param timeout - Timeout in seconds before killing the container. Defaults to 10 seconds. * */ -public class StopContainerCmd extends AbstrDockerCmd { +public class StopContainerCommand extends AbstrDockerCmd implements StopContainerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(StopContainerCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(StopContainerCommand.class); private String containerId; private int timeout = 10; - public StopContainerCmd(String containerId) { + public StopContainerCommand(String containerId) { withContainerId(containerId); } - public String getContainerId() { + @Override + public String getContainerId() { return containerId; } - public int getTimeout() { + @Override + public int getTimeout() { return timeout; } - public StopContainerCmd withContainerId(String containerId) { + @Override + public StopContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } + @Override public StopContainerCmd withTimeout(int timeout) { Preconditions.checkArgument(timeout >= 0, "timeout must be greater or equal 0"); this.timeout = timeout; diff --git a/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/TagImageCommand.java similarity index 71% rename from src/main/java/com/github/dockerjava/client/command/TagImageCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/TagImageCommand.java index ae96072d..9bf3ec09 100644 --- a/src/main/java/com/github/dockerjava/client/command/TagImageCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/TagImageCommand.java @@ -1,10 +1,12 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MultivaluedMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.dockerjava.api.command.TagImageCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; @@ -13,66 +15,72 @@ /** * 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 force - * (not documented) - * @return the HTTP status code (201 for success) + * @param image The local image to tag (either a name or an id) + * @param repository The repository to tag in + * @param force (not documented) + * */ -public class TagImageCmd extends AbstrDockerCmd { +public class TagImageCommand extends AbstrDockerCmd implements TagImageCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(TagImageCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TagImageCommand.class); private String imageId, repository, tag; private boolean force; - public TagImageCmd(String imageId, String repository, String tag) { + public TagImageCommand(String imageId, String repository, String tag) { withImageId(imageId); withRepository(repository); withTag(tag); } - public String getImageId() { + @Override + public String getImageId() { return imageId; } - public String getRepository() { + @Override + public String getRepository() { return repository; } - public String getTag() { + @Override + public String getTag() { return tag; } - public boolean hasForceEnabled() { + @Override + public boolean hasForceEnabled() { return force; } - public TagImageCmd withImageId(String imageId) { + @Override + public TagImageCmd withImageId(String imageId) { Preconditions.checkNotNull(imageId, "imageId was not specified"); this.imageId = imageId; return this; } + @Override public TagImageCmd withRepository(String repository) { Preconditions.checkNotNull(repository, "repository was not specified"); this.repository = repository; return this; } + @Override public TagImageCmd withTag(String tag) { Preconditions.checkNotNull(tag, "tag was not specified"); this.tag = tag; return this; } + @Override public TagImageCmd withForce() { return withForce(true); } + @Override public TagImageCmd withForce(boolean force) { this.force = force; return this; diff --git a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/TopContainerCommand.java similarity index 73% rename from src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/TopContainerCommand.java index ccecf28b..55673993 100644 --- a/src/main/java/com/github/dockerjava/client/command/TopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/TopContainerCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; @@ -8,40 +8,46 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.TopContainerCmd; +import com.github.dockerjava.api.command.TopContainerResponse; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; /** * List processes running inside a container - * */ -public class TopContainerCmd extends AbstrDockerCmd { +public class TopContainerCommand extends AbstrDockerCmd implements TopContainerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(TopContainerCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TopContainerCommand.class); private String containerId; private String psArgs; - public TopContainerCmd(String containerId) { + public TopContainerCommand(String containerId) { withContainerId(containerId); } - public String getContainerId() { + @Override + public String getContainerId() { return containerId; } - public String getPsArgs() { + @Override + public String getPsArgs() { return psArgs; } - public TopContainerCmd withContainerId(String containerId) { + @Override + public TopContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } + @Override public TopContainerCmd withPsArgs(String psArgs) { Preconditions.checkNotNull(psArgs, "psArgs was not specified"); this.psArgs = psArgs; @@ -59,7 +65,7 @@ public String toString() { /** * @throws NotFoundException No such container */ - @Override + @Override public TopContainerResponse exec() throws NotFoundException { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/UnpauseContainerCommand.java similarity index 72% rename from src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/UnpauseContainerCommand.java index 18b65d31..15329805 100644 --- a/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/UnpauseContainerCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; @@ -7,6 +7,8 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.UnpauseContainerCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; @@ -17,21 +19,23 @@ * @param containerId - Id of the container * */ -public class UnpauseContainerCmd extends AbstrDockerCmd { +public class UnpauseContainerCommand extends AbstrDockerCmd implements UnpauseContainerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(UnpauseContainerCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(UnpauseContainerCommand.class); private String containerId; - public UnpauseContainerCmd(String containerId) { + public UnpauseContainerCommand(String containerId) { withContainerId(containerId); } - public String getContainerId() { + @Override + public String getContainerId() { return containerId; } - public UnpauseContainerCmd withContainerId(String containerId) { + @Override + public UnpauseContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; diff --git a/src/main/java/com/github/dockerjava/client/command/VersionCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/VersionCommand.java similarity index 66% rename from src/main/java/com/github/dockerjava/client/command/VersionCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/VersionCommand.java index 78dda057..907ee89f 100644 --- a/src/main/java/com/github/dockerjava/client/command/VersionCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/VersionCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; @@ -6,17 +6,18 @@ import org.slf4j.LoggerFactory; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.VersionCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.github.dockerjava.client.model.Version; import com.sun.jersey.api.client.WebResource; /** - * Return the Docker version info. + * Returns the Docker version info. */ -public class VersionCmd extends AbstrDockerCmd { +public class VersionCommand extends AbstrDockerCmd implements VersionCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(VersionCmd.class); - + private static final Logger LOGGER = LoggerFactory.getLogger(VersionCommand.class); @Override public String toString() { diff --git a/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java b/src/main/java/com/github/dockerjava/jaxrs1/command/WaitContainerCommand.java similarity index 65% rename from src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java rename to src/main/java/com/github/dockerjava/jaxrs1/command/WaitContainerCommand.java index ce91eec1..d301fe24 100644 --- a/src/main/java/com/github/dockerjava/client/command/WaitContainerCmd.java +++ b/src/main/java/com/github/dockerjava/jaxrs1/command/WaitContainerCommand.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import javax.ws.rs.core.MediaType; @@ -6,30 +6,33 @@ import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.WaitContainerCmd; +import com.github.dockerjava.client.command.AbstrDockerCmd; import com.google.common.base.Preconditions; import com.sun.jersey.api.client.WebResource; /** * Wait a container * - * Block until container stops, then returns the exit code + * Block until container stops, then returns its exit code */ -public class WaitContainerCmd extends AbstrDockerCmd { +public class WaitContainerCommand extends AbstrDockerCmd implements WaitContainerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(WaitContainerCmd.class); + private static final Logger LOGGER = LoggerFactory.getLogger(WaitContainerCommand.class); private String containerId; - public WaitContainerCmd(String containerId) { + public WaitContainerCommand(String containerId) { withContainerId(containerId); } - public String getContainerId() { + @Override + public String getContainerId() { return containerId; } - public WaitContainerCmd withContainerId(String containerId) { + @Override + public WaitContainerCmd withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 652ca6bf..09100c10 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -1,7 +1,8 @@ package com.github.dockerjava.client; +import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.client.DockerClient; +import com.github.dockerjava.jaxrs1.JaxRs1Client; import com.sun.jersey.api.client.ClientResponse; import org.slf4j.Logger; @@ -31,7 +32,7 @@ public abstract class AbstractDockerClientTest extends Assert { public void beforeTest() throws DockerException { LOG.info("======================= BEFORETEST ======================="); LOG.info("Connecting to Docker server"); - dockerClient = new DockerClient(); + dockerClient = new JaxRs1Client(); LOG.info("Pulling image 'busybox'"); // need to block until image is pulled completely @@ -91,7 +92,7 @@ public void afterMethod(ITestResult result) { protected String logResponseStream(InputStream response) { String responseString; try { - responseString = DockerClient.asString(response); + responseString = JaxRs1Client.asString(response); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/src/test/java/com/github/dockerjava/client/DockerClientTest.java b/src/test/java/com/github/dockerjava/jaxrs1/JaxRs1ClientTest.java similarity index 86% rename from src/test/java/com/github/dockerjava/client/DockerClientTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/JaxRs1ClientTest.java index 8278accf..ea270170 100644 --- a/src/test/java/com/github/dockerjava/client/DockerClientTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/JaxRs1ClientTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client; +package com.github.dockerjava.jaxrs1; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -6,7 +6,8 @@ import java.lang.reflect.Method; import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.client.command.CreateContainerResponse; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.client.AbstractDockerClientTest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,9 +23,9 @@ * * @author Konstantin Pelykh (kpelykh@gmail.com) */ -public class DockerClientTest extends AbstractDockerClientTest { +public class JaxRs1ClientTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(DockerClientTest.class); + .getLogger(JaxRs1ClientTest.class); @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/AuthCommandTest.java similarity index 85% rename from src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/AuthCommandTest.java index 628b1414..76e8824f 100644 --- a/src/test/java/com/github/dockerjava/client/command/AuthCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/AuthCommandTest.java @@ -1,8 +1,8 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerClient; +import com.github.dockerjava.jaxrs1.JaxRs1Client; import com.sun.jersey.api.client.UniformInterfaceException; import org.hamcrest.Matchers; @@ -13,7 +13,7 @@ import static org.hamcrest.MatcherAssert.assertThat; -public class AuthCmdTest extends AbstractDockerClientTest { +public class AuthCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { @@ -43,7 +43,7 @@ public void testAuth() throws Exception { public void testAuthInvalid() throws Exception { System.setProperty("docker.io.password", "garbage"); try { - new DockerClient().authCmd().exec(); + new JaxRs1Client().authCmd().exec(); fail("Expected a DockerException caused by a bad password."); } catch (DockerException e) { assertThat(e.getCause(), Matchers.instanceOf(UniformInterfaceException.class)); diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/BuildImageCommandTest.java similarity index 93% rename from src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/BuildImageCommandTest.java index 04adec3f..0bd306b5 100644 --- a/src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/BuildImageCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -25,9 +25,12 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class BuildImageCmdTest extends AbstractDockerClientTest { +public class BuildImageCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { @@ -55,7 +58,7 @@ public void testNginxDockerfileBuilder() throws DockerException, File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("nginx").getFile()); - InputStream response = dockerClient.buildImageCmd(baseDir).exec(); + InputStream response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); StringWriter logwriter = new StringWriter(); @@ -115,7 +118,7 @@ private String dockerfileBuild(File baseDir, String expectedText) throws DockerException, IOException { // Build image - InputStream response = dockerClient.buildImageCmd(baseDir).exec(); + InputStream response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); StringWriter logwriter = new StringWriter(); diff --git a/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/CommitCommandTest.java similarity index 89% rename from src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/CommitCommandTest.java index 52885248..4ce4a206 100644 --- a/src/test/java/com/github/dockerjava/client/command/CommitCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/CommitCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -17,9 +17,11 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class CommitCmdTest extends AbstractDockerClientTest { +public class CommitCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/ContainerDiffCommandTest.java similarity index 91% rename from src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/ContainerDiffCommandTest.java index ac7fdf02..b9bbd1d9 100644 --- a/src/test/java/com/github/dockerjava/client/command/ContainerDiffCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/ContainerDiffCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static ch.lambdaj.Lambda.selectUnique; import static org.hamcrest.MatcherAssert.assertThat; @@ -18,10 +18,11 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.model.ChangeLog; -public class ContainerDiffCmdTest extends AbstractDockerClientTest { +public class ContainerDiffCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/CopyFileFromContainerCommandTest.java similarity index 88% rename from src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/CopyFileFromContainerCommandTest.java index 29f47a15..978604af 100644 --- a/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/CopyFileFromContainerCommandTest.java @@ -1,5 +1,6 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; +import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; import org.testng.ITestResult; @@ -11,7 +12,7 @@ import static org.hamcrest.Matchers.*; import static org.hamcrest.MatcherAssert.assertThat; -public class CopyFileFromContainerCmdTest extends AbstractDockerClientTest { +public class CopyFileFromContainerCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() { diff --git a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/CreateContainerCommandTest.java similarity index 94% rename from src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/CreateContainerCommandTest.java index 69752e6f..ddddcb91 100644 --- a/src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/CreateContainerCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @@ -15,10 +15,12 @@ import com.github.dockerjava.api.ConflictException; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.model.Volume; -public class CreateContainerCmdTest extends AbstractDockerClientTest { +public class CreateContainerCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/InfoCommandTest.java similarity index 92% rename from src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/InfoCommandTest.java index b8e0c048..224c5b3d 100644 --- a/src/test/java/com/github/dockerjava/client/command/InfoCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/InfoCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.lang.reflect.Method; @@ -10,6 +10,7 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.model.Info; @@ -17,7 +18,7 @@ import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.hamcrest.Matchers.not; -public class InfoCmdTest extends AbstractDockerClientTest { +public class InfoCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/KillContainerCommandTest.java similarity index 86% rename from src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/KillContainerCommandTest.java index 47546407..aee87bfa 100644 --- a/src/test/java/com/github/dockerjava/client/command/KillContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/KillContainerCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -18,12 +18,14 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class KillContainerCmdTest extends AbstractDockerClientTest { +public class KillContainerCommandTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(KillContainerCmdTest.class); + .getLogger(KillContainerCommandTest.class); @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/ListContainersCommandTest.java similarity index 92% rename from src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/ListContainersCommandTest.java index 83f3f42a..fecdbaf4 100644 --- a/src/test/java/com/github/dockerjava/client/command/ListContainersCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/ListContainersCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static ch.lambdaj.Lambda.filter; import static org.hamcrest.MatcherAssert.assertThat; @@ -23,10 +23,12 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.model.Container; -public class ListContainersCmdTest extends AbstractDockerClientTest { +public class ListContainersCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/ListImagesCommandTest.java similarity index 92% rename from src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/ListImagesCommandTest.java index 1e77f39a..b949fa6e 100644 --- a/src/test/java/com/github/dockerjava/client/command/ListImagesCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/ListImagesCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @@ -18,7 +18,7 @@ import com.github.dockerjava.client.model.Image; import com.github.dockerjava.client.model.Info; -public class ListImagesCmdTest extends AbstractDockerClientTest { +public class ListImagesCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/LogContainerCommandTest.java similarity index 90% rename from src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/LogContainerCommandTest.java index 164dfde2..b0f11c14 100644 --- a/src/test/java/com/github/dockerjava/client/command/LogContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/LogContainerCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; @@ -18,9 +18,10 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class LogContainerCmdTest extends AbstractDockerClientTest { +public class LogContainerCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/PullImageCommandTest.java similarity index 93% rename from src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/PullImageCommandTest.java index 8ee51568..3a64a27b 100644 --- a/src/test/java/com/github/dockerjava/client/command/PullImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/PullImageCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -17,10 +17,11 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.model.Info; -public class PullImageCmdTest extends AbstractDockerClientTest { +public class PullImageCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/PushImageCommandTest.java similarity index 88% rename from src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/PushImageCommandTest.java index 917c4b38..3ab9c8ff 100644 --- a/src/test/java/com/github/dockerjava/client/command/PushImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/PushImageCommandTest.java @@ -1,7 +1,7 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; -import static com.github.dockerjava.client.DockerClient.asString; +import static com.github.dockerjava.jaxrs1.JaxRs1Client.asString; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.isEmptyString; @@ -19,12 +19,13 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class PushImageCmdTest extends AbstractDockerClientTest { +public class PushImageCommandTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(PushImageCmdTest.class); + .getLogger(PushImageCommandTest.class); String username; diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/RemoveContainerCommandTest.java similarity index 88% rename from src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/RemoveContainerCommandTest.java index d9b2855c..e1b761a5 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/RemoveContainerCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; @@ -20,12 +20,13 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class RemoveContainerCmdTest extends AbstractDockerClientTest { +public class RemoveContainerCommandTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(RemoveContainerCmdTest.class); + .getLogger(RemoveContainerCommandTest.class); @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/RemoveImageCommandTest.java similarity index 91% rename from src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/RemoveImageCommandTest.java index 196a6dd5..46c0029a 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/RemoveImageCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; @@ -21,13 +21,14 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.model.Container; -public class RemoveImageCmdTest extends AbstractDockerClientTest { +public class RemoveImageCommandTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(RemoveImageCmdTest.class); + .getLogger(RemoveImageCommandTest.class); @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/RestartContainerCommandTest.java similarity index 89% rename from src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/RestartContainerCommandTest.java index ebce1ec8..f068b15d 100644 --- a/src/test/java/com/github/dockerjava/client/command/RestartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/RestartContainerCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -16,9 +16,11 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class RestartContainerCmdTest extends AbstractDockerClientTest { +public class RestartContainerCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/SearchImagesCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/SearchImagesCommandTest.java similarity index 92% rename from src/test/java/com/github/dockerjava/client/command/SearchImagesCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/SearchImagesCommandTest.java index 584de5c3..dca60951 100644 --- a/src/test/java/com/github/dockerjava/client/command/SearchImagesCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/SearchImagesCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static ch.lambdaj.Lambda.filter; import static org.hamcrest.MatcherAssert.assertThat; @@ -22,7 +22,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.model.SearchItem; -public class SearchImagesCmdTest extends AbstractDockerClientTest { +public class SearchImagesCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/StartContainerCommandTest.java similarity index 96% rename from src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/StartContainerCommandTest.java index 5cb856fa..ce49b449 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/StartContainerCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; @@ -13,6 +13,8 @@ import java.util.Arrays; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.model.*; import org.testng.ITestResult; @@ -25,7 +27,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; -public class StartContainerCmdTest extends AbstractDockerClientTest { +public class StartContainerCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/StopContainerCommandTest.java similarity index 86% rename from src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/StopContainerCommandTest.java index 0ecc82b5..362321f6 100644 --- a/src/test/java/com/github/dockerjava/client/command/StopContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/StopContainerCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -18,12 +18,14 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class StopContainerCmdTest extends AbstractDockerClientTest { +public class StopContainerCommandTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(StopContainerCmdTest.class); + .getLogger(StopContainerCommandTest.class); @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/TagImageCommandTest.java similarity index 88% rename from src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/TagImageCommandTest.java index 12b538a4..df6ae219 100644 --- a/src/test/java/com/github/dockerjava/client/command/TagImageCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/TagImageCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.lang.reflect.Method; @@ -15,10 +15,10 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -public class TagImageCmdTest extends AbstractDockerClientTest { +public class TagImageCommandTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(TagImageCmdTest.class); + .getLogger(TagImageCommandTest.class); @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/VersionCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/VersionCommandTest.java similarity index 91% rename from src/test/java/com/github/dockerjava/client/command/VersionCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/VersionCommandTest.java index a808e488..727a873b 100644 --- a/src/test/java/com/github/dockerjava/client/command/VersionCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/VersionCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import java.lang.reflect.Method; @@ -14,7 +14,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.model.Version; -public class VersionCmdTest extends AbstractDockerClientTest { +public class VersionCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java b/src/test/java/com/github/dockerjava/jaxrs1/command/WaitContainerCommandTest.java similarity index 88% rename from src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java rename to src/test/java/com/github/dockerjava/jaxrs1/command/WaitContainerCommandTest.java index adc0f75d..9af4ce74 100644 --- a/src/test/java/com/github/dockerjava/client/command/WaitContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/jaxrs1/command/WaitContainerCommandTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs1.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -16,9 +16,11 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class WaitContainerCmdTest extends AbstractDockerClientTest { +public class WaitContainerCommandTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { From 685819a3948822590840844374d2732a47e2fbf7 Mon Sep 17 00:00:00 2001 From: Ritesh Patel Date: Sat, 16 Aug 2014 17:14:43 -0700 Subject: [PATCH 080/452] Adding support for networkMode Adding support for networkMode in startContainerCmd. Also added the test case --- .../client/command/StartContainerCmd.java | 18 ++++++++++++-- .../client/command/StartContainerCmdTest.java | 24 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java index b116d8da..e4c370b7 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/client/command/StartContainerCmd.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.client.model.*; + import org.apache.commons.lang.builder.ToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,6 +51,10 @@ public class StartContainerCmd extends AbstrDockerCmd { @JsonProperty("VolumesFrom") private String volumesFrom; + @JsonProperty("NetworkMode") + private String networkMode = "bridge"; + + public StartContainerCmd(String containerId) { withContainerId(containerId); } @@ -88,10 +93,13 @@ public String getVolumesFrom() { return volumesFrom; } - public String getContainerId() { return containerId; } + + public String getNetworkMode() { + return networkMode; + } @JsonIgnore public StartContainerCmd withBinds(Bind... binds) { @@ -148,7 +156,13 @@ public StartContainerCmd withContainerId(String containerId) { .checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; - } + } + + public StartContainerCmd withNetworkMode(String networkMode) { + Preconditions.checkNotNull(networkMode, "networkMode was not specified"); + this.networkMode = networkMode; + return this; + } @Override public String toString() { diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java index 5bb2425f..205da301 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java +++ b/src/test/java/com/github/dockerjava/client/command/StartContainerCmdTest.java @@ -214,5 +214,29 @@ public void startContainer() throws DockerException { } + @Test + public void startContainerWithNetworkMode() throws DockerException { + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox") + .withCmd("true").exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + dockerClient.startContainerCmd(container.getId()).withNetworkMode("host").exec(); + + inspectContainerResponse = dockerClient.inspectContainerCmd(container + .getId()).exec(); + + assertThat(inspectContainerResponse.getHostConfig().getNetworkMode(), + is(equalTo("host"))); + + tmpContainers.add(container.getId()); + } } From 7ff216e8aa65120a508e29209893f713d4de19db Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 19 Aug 2014 23:09:10 +0200 Subject: [PATCH 081/452] Separate packages for API, Core and Implementation --- .../github/dockerjava/api/DockerClient.java | 4 +- .../api/command/AttachContainerCmd.java | 3 + .../dockerjava/api/command/AuthCmd.java | 8 + .../dockerjava/api/command/BuildImageCmd.java | 8 +- .../dockerjava/api/command/CommitCmd.java | 5 + .../api/command/ContainerDiffCmd.java | 3 + .../api/command/CopyFileFromContainerCmd.java | 3 + .../api/command/CreateContainerCmd.java | 3 + .../api/command/CreateImageCmd.java | 5 + .../dockerjava/api/command/DockerCmdExec.java | 7 + .../api/command/DockerCmdExecFactory.java | 74 +++++ .../dockerjava/api/command/InfoCmd.java | 3 + .../api/command/InspectContainerCmd.java | 3 + .../api/command/InspectImageCmd.java | 3 + .../api/command/KillContainerCmd.java | 3 + .../api/command/ListContainersCmd.java | 3 + .../dockerjava/api/command/ListImagesCmd.java | 3 + .../api/command/LogContainerCmd.java | 4 + .../api/command/PauseContainerCmd.java | 3 + .../dockerjava/api/command/PingCmd.java | 3 + .../dockerjava/api/command/PullImageCmd.java | 3 + .../dockerjava/api/command/PushImageCmd.java | 8 + .../api/command/RemoveContainerCmd.java | 3 + .../api/command/RemoveImageCmd.java | 3 + .../api/command/RestartContainerCmd.java | 3 + .../api/command/SearchImagesCmd.java | 3 + .../api/command/StartContainerCmd.java | 6 + .../api/command/StopContainerCmd.java | 3 + .../dockerjava/api/command/TagImageCmd.java | 3 + .../api/command/TopContainerCmd.java | 3 + .../api/command/TopContainerResponse.java | 1 - .../api/command/UnpauseContainerCmd.java | 3 + .../dockerjava/api/command/VersionCmd.java | 5 +- .../api/command/WaitContainerCmd.java | 4 +- .../dockerjava/api/model/AuthConfig.java | 1 - .../dockerjava/client/DockerClientImpl.java | 301 ------------------ .../client/command/AuthCommand.java | 51 --- .../client/command/InfoCommand.java | 31 -- .../client/command/PauseContainerCommand.java | 71 ----- .../client/command/PushImageCommand.java | 80 ----- .../client/command/SearchImagesCommand.java | 60 ---- .../command/UnpauseContainerCommand.java | 70 ---- .../client/command/VersionCommand.java | 32 -- .../client/command/WaitContainerCommand.java | 57 ---- .../utils => core}/CompressArchiveUtil.java | 2 +- .../{client => core}/DockerClientConfig.java | 2 +- .../dockerjava/core/DockerClientImpl.java | 245 ++++++++++++++ .../utils => core}/JsonClientFilter.java | 2 +- .../SelectiveLoggingFilter.java | 2 +- .../command/AbstrAuthCfgDockerCmd.java | 16 +- .../command/AbstrDockerCmd.java | 26 +- .../command/AttachContainerCmdImpl.java} | 65 ++-- .../dockerjava/core/command/AuthCmdImpl.java | 29 ++ .../command/BuildImageCmdImpl.java} | 127 ++++---- .../command/CommitCmdImpl.java} | 109 +++---- .../command/ContainerDiffCmdImpl.java} | 35 +- .../CopyFileFromContainerCmdImpl.java} | 52 ++- .../command/CreateContainerCmdImpl.java} | 80 +++-- .../command/CreateImageCmdImpl.java} | 55 ++-- .../dockerjava/core/command/InfoCmdImpl.java | 27 ++ .../command/InspectContainerCmdImpl.java} | 29 +- .../command/InspectImageCmdImpl.java} | 28 +- .../command/KillContainerCmdImpl.java} | 43 +-- .../command/ListContainersCmdImpl.java} | 59 ++-- .../command/ListImagesCmdImpl.java} | 45 ++- .../command/LogContainerCmdImpl.java} | 45 ++- .../core/command/PauseContainerCmdImpl.java | 61 ++++ .../dockerjava/core/command/PingCmdImpl.java | 24 ++ .../command/PullImageCmdImpl.java} | 43 +-- .../core/command/PushImageCmdImpl.java | 69 ++++ .../command/RemoveContainerCmdImpl.java} | 45 ++- .../command/RemoveImageCmdImpl.java} | 42 +-- .../command/RestartContainerCmdImpl.java} | 39 +-- .../core/command/SearchImagesCmdImpl.java | 52 +++ .../command/StartContainerCmdImpl.java} | 40 +-- .../command/StopContainerCmdImpl.java} | 39 +-- .../command/TagImageCmdImpl.java} | 39 +-- .../command/TopContainerCmdImpl.java} | 38 +-- .../core/command/UnpauseContainerCmdImpl.java | 60 ++++ .../core/command/VersionCmdImpl.java | 28 ++ .../core/command/WaitContainerCmdImpl.java | 48 +++ .../dockerjava/jaxrs/AbstrDockerCmdExec.java | 35 ++ .../jaxrs/AttachContainerCmdExec.java | 41 +++ .../github/dockerjava/jaxrs/AuthCmdExec.java | 37 +++ .../dockerjava/jaxrs/BuildImageCmdExec.java | 50 +++ .../dockerjava/jaxrs/CommitCmdExec.java | 38 +++ .../jaxrs/ContainerDiffCmdExec.java | 33 ++ .../jaxrs/CopyFileFromContainerCmdExec.java | 36 +++ .../jaxrs/CreateContainerCmdExec.java | 35 ++ .../dockerjava/jaxrs/CreateImageCmdExec.java | 36 +++ .../jaxrs/DockerCmdExecFactoryImpl.java | 245 ++++++++++++++ .../github/dockerjava/jaxrs/InfoCmdExec.java | 28 ++ .../jaxrs/InspectContainerCmdExec.java | 29 ++ .../dockerjava/jaxrs/InspectImageCmdExec.java | 29 ++ .../jaxrs/KillContainerCmdExec.java | 36 +++ .../jaxrs/ListContainersCmdExec.java | 43 +++ .../dockerjava/jaxrs/ListImagesCmdExec.java | 39 +++ .../dockerjava/jaxrs/LogContainerCmdExec.java | 35 ++ .../jaxrs/PauseContainerCmdExec.java | 35 ++ .../PingCmdExec.java} | 22 +- .../dockerjava/jaxrs/PullImageCmdExec.java | 37 +++ .../dockerjava/jaxrs/PushImageCmdExec.java | 44 +++ .../jaxrs/RemoveContainerCmdExec.java | 32 ++ .../dockerjava/jaxrs/RemoveImageCmdExec.java | 31 ++ .../jaxrs/RestartContainerCmdExec.java | 33 ++ .../dockerjava/jaxrs/SearchImagesCmdExec.java | 32 ++ .../jaxrs/StartContainerCmdExec.java | 32 ++ .../jaxrs/StopContainerCmdExec.java | 33 ++ .../dockerjava/jaxrs/TagImageCmdExec.java | 37 +++ .../dockerjava/jaxrs/TopContainerCmdExec.java | 34 ++ .../jaxrs/UnpauseContainerCmdExec.java | 33 ++ .../dockerjava/jaxrs/VersionCmdExec.java | 30 ++ .../jaxrs/WaitContainerCmdExec.java | 35 ++ .../client/AbstractDockerClientTest.java | 1 + .../command/AuthCmdImplTest.java} | 8 +- .../command/BuildImageCmdImplTest.java} | 4 +- .../command/CommitCmdImplTest.java} | 4 +- .../command/ContainerDiffCmdImplTest.java} | 4 +- .../CopyFileFromContainerCmdImplTest.java} | 4 +- .../command/CreateContainerCmdImplTest.java} | 4 +- .../command/InfoCmdImplTest.java} | 4 +- .../command/KillContainerCmdImplTest.java} | 6 +- .../command/ListContainersCmdImplTest.java} | 4 +- .../command/ListImagesCmdImplTest.java} | 4 +- .../command/LogContainerCmdImplTest.java} | 4 +- .../command/PullImageCmdImplTest.java} | 4 +- .../command/PushImageCmdImplTest.java} | 6 +- .../command/RemoveContainerCmdImplTest.java} | 10 +- .../command/RemoveImageCmdImplTest.java} | 6 +- .../command/RestartContainerCmdImplTest.java} | 4 +- .../command/SearchImagesCmdImplTest.java} | 4 +- .../command/StartContainerCmdImplTest.java} | 4 +- .../command/StopContainerCmdImplTest.java} | 6 +- .../command/TagImageCmdImplTest.java} | 6 +- .../command/VersionCmdImplTest.java} | 4 +- .../command/WaitContainerCmdImplTest.java} | 4 +- 136 files changed, 2706 insertions(+), 1474 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/command/DockerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java delete mode 100644 src/main/java/com/github/dockerjava/client/DockerClientImpl.java delete mode 100644 src/main/java/com/github/dockerjava/client/command/AuthCommand.java delete mode 100644 src/main/java/com/github/dockerjava/client/command/InfoCommand.java delete mode 100644 src/main/java/com/github/dockerjava/client/command/PauseContainerCommand.java delete mode 100644 src/main/java/com/github/dockerjava/client/command/PushImageCommand.java delete mode 100644 src/main/java/com/github/dockerjava/client/command/SearchImagesCommand.java delete mode 100644 src/main/java/com/github/dockerjava/client/command/UnpauseContainerCommand.java delete mode 100644 src/main/java/com/github/dockerjava/client/command/VersionCommand.java delete mode 100644 src/main/java/com/github/dockerjava/client/command/WaitContainerCommand.java rename src/main/java/com/github/dockerjava/{client/utils => core}/CompressArchiveUtil.java (96%) rename src/main/java/com/github/dockerjava/{client => core}/DockerClientConfig.java (99%) create mode 100644 src/main/java/com/github/dockerjava/core/DockerClientImpl.java rename src/main/java/com/github/dockerjava/{client/utils => core}/JsonClientFilter.java (94%) rename src/main/java/com/github/dockerjava/{client => core}/SelectiveLoggingFilter.java (96%) rename src/main/java/com/github/dockerjava/{client => core}/command/AbstrAuthCfgDockerCmd.java (61%) rename src/main/java/com/github/dockerjava/{client => core}/command/AbstrDockerCmd.java (76%) rename src/main/java/com/github/dockerjava/{client/command/AttachContainerCommand.java => core/command/AttachContainerCmdImpl.java} (62%) create mode 100644 src/main/java/com/github/dockerjava/core/command/AuthCmdImpl.java rename src/main/java/com/github/dockerjava/{client/command/BuildImageCommand.java => core/command/BuildImageCmdImpl.java} (71%) rename src/main/java/com/github/dockerjava/{client/command/CommitCommand.java => core/command/CommitCmdImpl.java} (70%) rename src/main/java/com/github/dockerjava/{client/command/ContainerDiffCommand.java => core/command/ContainerDiffCmdImpl.java} (56%) rename src/main/java/com/github/dockerjava/{client/command/CopyFileFromContainerCommand.java => core/command/CopyFileFromContainerCmdImpl.java} (55%) rename src/main/java/com/github/dockerjava/{client/command/CreateContainerCommand.java => core/command/CreateContainerCmdImpl.java} (73%) rename src/main/java/com/github/dockerjava/{client/command/CreateImageCommand.java => core/command/CreateImageCmdImpl.java} (57%) create mode 100644 src/main/java/com/github/dockerjava/core/command/InfoCmdImpl.java rename src/main/java/com/github/dockerjava/{client/command/InspectContainerCommand.java => core/command/InspectContainerCmdImpl.java} (52%) rename src/main/java/com/github/dockerjava/{client/command/InspectImageCommand.java => core/command/InspectImageCmdImpl.java} (53%) rename src/main/java/com/github/dockerjava/{client/command/KillContainerCommand.java => core/command/KillContainerCmdImpl.java} (52%) rename src/main/java/com/github/dockerjava/{client/command/ListContainersCommand.java => core/command/ListContainersCmdImpl.java} (66%) rename src/main/java/com/github/dockerjava/{client/command/ListImagesCommand.java => core/command/ListImagesCmdImpl.java} (56%) rename src/main/java/com/github/dockerjava/{client/command/LogContainerCommand.java => core/command/LogContainerCmdImpl.java} (71%) create mode 100644 src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java create mode 100644 src/main/java/com/github/dockerjava/core/command/PingCmdImpl.java rename src/main/java/com/github/dockerjava/{client/command/PullImageCommand.java => core/command/PullImageCmdImpl.java} (55%) create mode 100644 src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java rename src/main/java/com/github/dockerjava/{client/command/RemoveContainerCommand.java => core/command/RemoveContainerCmdImpl.java} (60%) rename src/main/java/com/github/dockerjava/{client/command/RemoveImageCommand.java => core/command/RemoveImageCmdImpl.java} (60%) rename src/main/java/com/github/dockerjava/{client/command/RestartContainerCommand.java => core/command/RestartContainerCmdImpl.java} (58%) create mode 100644 src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java rename src/main/java/com/github/dockerjava/{client/command/StartContainerCommand.java => core/command/StartContainerCmdImpl.java} (81%) rename src/main/java/com/github/dockerjava/{client/command/StopContainerCommand.java => core/command/StopContainerCmdImpl.java} (61%) rename src/main/java/com/github/dockerjava/{client/command/TagImageCommand.java => core/command/TagImageCmdImpl.java} (65%) rename src/main/java/com/github/dockerjava/{client/command/TopContainerCommand.java => core/command/TopContainerCmdImpl.java} (57%) create mode 100644 src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java create mode 100644 src/main/java/com/github/dockerjava/core/command/VersionCmdImpl.java create mode 100644 src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/AuthCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/CommitCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/ContainerDiffCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/CreateContainerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/CreateImageCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/InspectContainerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/InspectImageCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/ListContainersCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java rename src/main/java/com/github/dockerjava/{client/command/PingCommand.java => jaxrs/PingCmdExec.java} (52%) create mode 100644 src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/SearchImagesCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/TopContainerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/VersionCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/WaitContainerCmdExec.java rename src/test/java/com/github/dockerjava/{client/command/AuthCommandTest.java => core/command/AuthCmdImplTest.java} (86%) rename src/test/java/com/github/dockerjava/{client/command/BuildImageCommandTest.java => core/command/BuildImageCmdImplTest.java} (98%) rename src/test/java/com/github/dockerjava/{client/command/CommitCommandTest.java => core/command/CommitCmdImplTest.java} (95%) rename src/test/java/com/github/dockerjava/{client/command/ContainerDiffCommandTest.java => core/command/ContainerDiffCmdImplTest.java} (95%) rename src/test/java/com/github/dockerjava/{client/command/CopyFileFromContainerCommandTest.java => core/command/CopyFileFromContainerCmdImplTest.java} (93%) rename src/test/java/com/github/dockerjava/{client/command/CreateContainerCommandTest.java => core/command/CreateContainerCmdImplTest.java} (97%) rename src/test/java/com/github/dockerjava/{client/command/InfoCommandTest.java => core/command/InfoCmdImplTest.java} (95%) rename src/test/java/com/github/dockerjava/{client/command/KillContainerCommandTest.java => core/command/KillContainerCmdImplTest.java} (93%) rename src/test/java/com/github/dockerjava/{client/command/ListContainersCommandTest.java => core/command/ListContainersCmdImplTest.java} (96%) rename src/test/java/com/github/dockerjava/{client/command/ListImagesCommandTest.java => core/command/ListImagesCmdImplTest.java} (93%) rename src/test/java/com/github/dockerjava/{client/command/LogContainerCommandTest.java => core/command/LogContainerCmdImplTest.java} (94%) rename src/test/java/com/github/dockerjava/{client/command/PullImageCommandTest.java => core/command/PullImageCmdImplTest.java} (95%) rename src/test/java/com/github/dockerjava/{client/command/PushImageCommandTest.java => core/command/PushImageCmdImplTest.java} (93%) rename src/test/java/com/github/dockerjava/{client/command/RemoveContainerCommandTest.java => core/command/RemoveContainerCmdImplTest.java} (85%) rename src/test/java/com/github/dockerjava/{client/command/RemoveImageCommandTest.java => core/command/RemoveImageCmdImplTest.java} (93%) rename src/test/java/com/github/dockerjava/{client/command/RestartContainerCommandTest.java => core/command/RestartContainerCmdImplTest.java} (95%) rename src/test/java/com/github/dockerjava/{client/command/SearchImagesCommandTest.java => core/command/SearchImagesCmdImplTest.java} (93%) rename src/test/java/com/github/dockerjava/{client/command/StartContainerCommandTest.java => core/command/StartContainerCmdImplTest.java} (98%) rename src/test/java/com/github/dockerjava/{client/command/StopContainerCommandTest.java => core/command/StopContainerCmdImplTest.java} (93%) rename src/test/java/com/github/dockerjava/{client/command/TagImageCommandTest.java => core/command/TagImageCmdImplTest.java} (88%) rename src/test/java/com/github/dockerjava/{client/command/VersionCommandTest.java => core/command/VersionCmdImplTest.java} (91%) rename src/test/java/com/github/dockerjava/{client/command/WaitContainerCommandTest.java => core/command/WaitContainerCmdImplTest.java} (94%) diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index 2edfce27..3420773a 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -43,11 +43,11 @@ public interface DockerClient extends Closeable { */ public AuthCmd authCmd(); - public InfoCmd infoCmd() throws DockerException; + public InfoCmd infoCmd(); public PingCmd pingCmd(); - public VersionCmd versionCmd() throws DockerException; + public VersionCmd versionCmd(); /** * * IMAGE API * diff --git a/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java index c4561d3d..8abbef72 100644 --- a/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java @@ -57,5 +57,8 @@ public interface AttachContainerCmd extends DockerCmd{ */ @Override public InputStream exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/AuthCmd.java b/src/main/java/com/github/dockerjava/api/command/AuthCmd.java index 7db2951e..f71a132b 100644 --- a/src/main/java/com/github/dockerjava/api/command/AuthCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/AuthCmd.java @@ -1,6 +1,7 @@ package com.github.dockerjava.api.command; import com.github.dockerjava.api.UnauthorizedException; +import com.github.dockerjava.api.model.AuthConfig; /** * @@ -9,7 +10,14 @@ */ public interface AuthCmd extends DockerCmd { + public AuthConfig getAuthConfig(); + + public AuthCmd withAuthConfig(AuthConfig authConfig); + @Override public Void exec() throws UnauthorizedException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java index d1a2d020..99afa6f1 100644 --- a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java @@ -1,6 +1,5 @@ package com.github.dockerjava.api.command; -import java.io.File; import java.io.InputStream; /** @@ -14,7 +13,7 @@ public interface BuildImageCmd extends DockerCmd{ public BuildImageCmd withTag(String tag); - public File getDockerFolder(); + public InputStream getTarInputStream(); public String getTag(); @@ -23,6 +22,8 @@ public interface BuildImageCmd extends DockerCmd{ public boolean hasRemoveEnabled(); public boolean isQuiet(); + + public BuildImageCmd withTarInputStream(InputStream tarInputStream); public BuildImageCmd withNoCache(); @@ -31,5 +32,8 @@ public interface BuildImageCmd extends DockerCmd{ public BuildImageCmd withRemove(boolean rm); public BuildImageCmd withQuiet(boolean quiet); + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/CommitCmd.java b/src/main/java/com/github/dockerjava/api/command/CommitCmd.java index 077f951d..effb8292 100644 --- a/src/main/java/com/github/dockerjava/api/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CommitCmd.java @@ -1,5 +1,7 @@ package com.github.dockerjava.api.command; +import java.io.InputStream; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.model.ExposedPorts; import com.github.dockerjava.api.model.Volumes; @@ -107,5 +109,8 @@ public interface CommitCmd extends DockerCmd{ * @throws NotFoundException No such container */ public String exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/ContainerDiffCmd.java b/src/main/java/com/github/dockerjava/api/command/ContainerDiffCmd.java index 3d05a004..516ea365 100644 --- a/src/main/java/com/github/dockerjava/api/command/ContainerDiffCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/ContainerDiffCmd.java @@ -21,5 +21,8 @@ public interface ContainerDiffCmd extends DockerCmd> { * @throws DockerException unexpected http status code */ public List exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec> { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java index d6109e8f..0ebd3cc1 100644 --- a/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java @@ -22,5 +22,8 @@ public interface CopyFileFromContainerCmd extends DockerCmd { * @throws NotFoundException No such container */ public InputStream exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java index 82ef0d6b..a8b55435 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java @@ -98,5 +98,8 @@ public interface CreateContainerCmd extends DockerCmd{ */ public CreateContainerResponse exec() throws NotFoundException, ConflictException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/CreateImageCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateImageCmd.java index 279fe5d2..5d7fc990 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateImageCmd.java @@ -7,6 +7,8 @@ public interface CreateImageCmd extends DockerCmd { public String getRepository(); public String getTag(); + + public InputStream getImageStream(); /** * @param repository the repository to import to @@ -22,6 +24,9 @@ public interface CreateImageCmd extends DockerCmd { * @param tag any tag for this image */ public CreateImageCmd withTag(String tag); + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/DockerCmdExec.java b/src/main/java/com/github/dockerjava/api/command/DockerCmdExec.java new file mode 100644 index 00000000..8cf13e7b --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/DockerCmdExec.java @@ -0,0 +1,7 @@ +package com.github.dockerjava.api.command; + +public interface DockerCmdExec, RES_T> { + + public RES_T exec(CMD_T command); + +} diff --git a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java new file mode 100644 index 00000000..6534bb54 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java @@ -0,0 +1,74 @@ +package com.github.dockerjava.api.command; + +import java.io.Closeable; +import java.io.IOException; + +import com.github.dockerjava.core.DockerClientConfig; + +public interface DockerCmdExecFactory extends Closeable { + + public void init(DockerClientConfig dockerClientConfig); + + public AuthCmd.Exec createAuthCmdExec(); + + public InfoCmd.Exec createInfoCmdExec(); + + public PingCmd.Exec createPingCmdExec(); + + public VersionCmd.Exec createVersionCmdExec(); + + public PullImageCmd.Exec createPullImageCmdExec(); + + public PushImageCmd.Exec createPushImageCmdExec(); + + public CreateImageCmd.Exec createCreateImageCmdExec(); + + public SearchImagesCmd.Exec createSearchImagesCmdExec(); + + public RemoveImageCmd.Exec createRemoveImageCmdExec(); + + public ListImagesCmd.Exec createListImagesCmdExec(); + + public InspectImageCmd.Exec createInspectImageCmdExec(); + + public ListContainersCmd.Exec createListContainersCmdExec(); + + public CreateContainerCmd.Exec createCreateContainerCmdExec(); + + public StartContainerCmd.Exec createStartContainerCmdExec(); + + public InspectContainerCmd.Exec createInspectContainerCmdExec(); + + public RemoveContainerCmd.Exec createRemoveContainerCmdExec(); + + public WaitContainerCmd.Exec createWaitContainerCmdExec(); + + public AttachContainerCmd.Exec createAttachContainerCmdExec(); + + public LogContainerCmd.Exec createLogContainerCmdExec(); + + public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec(); + + public StopContainerCmd.Exec createStopContainerCmdExec(); + + public ContainerDiffCmd.Exec createContainerDiffCmdExec(); + + public KillContainerCmd.Exec createKillContainerCmdExec(); + + public RestartContainerCmd.Exec createRestartContainerCmdExec(); + + public CommitCmd.Exec createCommitCmdExec(); + + public BuildImageCmd.Exec createBuildImageCmdExec(); + + public TopContainerCmd.Exec createTopContainerCmdExec(); + + public TagImageCmd.Exec createTagImageCmdExec(); + + public PauseContainerCmd.Exec createPauseContainerCmdExec(); + + public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec(); + + public void close() throws IOException; + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/InfoCmd.java b/src/main/java/com/github/dockerjava/api/command/InfoCmd.java index f0239e94..d340fe26 100644 --- a/src/main/java/com/github/dockerjava/api/command/InfoCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/InfoCmd.java @@ -4,4 +4,7 @@ public interface InfoCmd extends DockerCmd { + public static interface Exec extends DockerCmdExec { + } + } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerCmd.java index fe350248..ca6a9a69 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerCmd.java @@ -12,5 +12,8 @@ public interface InspectContainerCmd extends DockerCmd * @throws NotFoundException No such container */ public InspectContainerResponse exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/InspectImageCmd.java b/src/main/java/com/github/dockerjava/api/command/InspectImageCmd.java index 3f4dc476..f2523487 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectImageCmd.java @@ -15,5 +15,8 @@ public interface InspectImageCmd extends DockerCmd{ * @throws NotFoundException No such image */ public InspectImageResponse exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/KillContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/KillContainerCmd.java index 7ba13d5f..aff39f9e 100644 --- a/src/main/java/com/github/dockerjava/api/command/KillContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/KillContainerCmd.java @@ -19,5 +19,8 @@ public interface KillContainerCmd extends DockerCmd { * @throws NotFoundException No such container */ public Void exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/ListContainersCmd.java b/src/main/java/com/github/dockerjava/api/command/ListContainersCmd.java index 7d13dd0b..ed457dab 100644 --- a/src/main/java/com/github/dockerjava/api/command/ListContainersCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/ListContainersCmd.java @@ -35,5 +35,8 @@ public interface ListContainersCmd extends DockerCmd>{ public ListContainersCmd withSince(String since); public ListContainersCmd withBefore(String before); + + public static interface Exec extends DockerCmdExec> { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/ListImagesCmd.java b/src/main/java/com/github/dockerjava/api/command/ListImagesCmd.java index 4c608ea1..502af84c 100644 --- a/src/main/java/com/github/dockerjava/api/command/ListImagesCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/ListImagesCmd.java @@ -19,5 +19,8 @@ public interface ListImagesCmd extends DockerCmd> { public ListImagesCmd withShowAll(boolean showAll); public ListImagesCmd withFilter(String filter); + + public static interface Exec extends DockerCmdExec> { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java index 54bec77c..e0f20f9a 100644 --- a/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java @@ -59,5 +59,9 @@ public interface LogContainerCmd extends DockerCmd{ * @throws NotFoundException No such container */ public InputStream exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } + } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/PauseContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/PauseContainerCmd.java index 0b26498f..a05733f9 100644 --- a/src/main/java/com/github/dockerjava/api/command/PauseContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/PauseContainerCmd.java @@ -18,5 +18,8 @@ public interface PauseContainerCmd extends DockerCmd{ * @throws NotFoundException No such container */ public Void exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/PingCmd.java b/src/main/java/com/github/dockerjava/api/command/PingCmd.java index 287a78c1..7d5af1e3 100644 --- a/src/main/java/com/github/dockerjava/api/command/PingCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/PingCmd.java @@ -6,5 +6,8 @@ * */ public interface PingCmd extends DockerCmd { + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java b/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java index 3663b392..f938542d 100644 --- a/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java @@ -20,5 +20,8 @@ public interface PullImageCmd extends DockerCmd{ public PullImageCmd withTag(String tag); public PullImageCmd withRegistry(String registry); + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java b/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java index 4163b867..cd3e6681 100644 --- a/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java @@ -3,6 +3,7 @@ import java.io.InputStream; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.model.AuthConfig; /** * Push the latest image to the repository. @@ -17,10 +18,17 @@ public interface PushImageCmd extends DockerCmd{ * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. */ public PushImageCmd withName(String name); + + public AuthConfig getAuthConfig(); + + public PushImageCmd withAuthConfig(AuthConfig authConfig); /** * @throws NotFoundException No such image */ public InputStream exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/RemoveContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/RemoveContainerCmd.java index 2225516d..be9b9d25 100644 --- a/src/main/java/com/github/dockerjava/api/command/RemoveContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/RemoveContainerCmd.java @@ -28,5 +28,8 @@ public interface RemoveContainerCmd extends DockerCmd { * @throws NotFoundException No such container */ public Void exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java b/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java index 67637477..021a3766 100644 --- a/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java @@ -27,5 +27,8 @@ public interface RemoveImageCmd extends DockerCmd{ * @throws NotFoundException No such image */ public Void exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/RestartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/RestartContainerCmd.java index 82a61b00..793919c2 100644 --- a/src/main/java/com/github/dockerjava/api/command/RestartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/RestartContainerCmd.java @@ -22,5 +22,8 @@ public interface RestartContainerCmd extends DockerCmd { * @throws NotFoundException No such container */ public Void exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/SearchImagesCmd.java b/src/main/java/com/github/dockerjava/api/command/SearchImagesCmd.java index b03bd3c1..c609e6e8 100644 --- a/src/main/java/com/github/dockerjava/api/command/SearchImagesCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/SearchImagesCmd.java @@ -15,5 +15,8 @@ public interface SearchImagesCmd extends DockerCmd> { public String getTerm(); public SearchImagesCmd withTerm(String term); + + public static interface Exec extends DockerCmdExec> { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index 13ce736e..5675adb0 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -1,11 +1,14 @@ package com.github.dockerjava.api.command; +import java.util.List; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Link; import com.github.dockerjava.api.model.LxcConf; import com.github.dockerjava.api.model.Ports; +import com.github.dockerjava.api.model.SearchItem; /** * Start a container @@ -53,5 +56,8 @@ public interface StartContainerCmd extends DockerCmd { * @throws NotModifiedException Container already started */ public Void exec() throws NotFoundException, NotModifiedException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/StopContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StopContainerCmd.java index 4c373386..7e706c06 100644 --- a/src/main/java/com/github/dockerjava/api/command/StopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StopContainerCmd.java @@ -25,5 +25,8 @@ public interface StopContainerCmd extends DockerCmd { * @throws NotModifiedException Container already stopped */ public Void exec() throws NotFoundException, NotModifiedException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/TagImageCmd.java b/src/main/java/com/github/dockerjava/api/command/TagImageCmd.java index 9e2b2210..ace84996 100644 --- a/src/main/java/com/github/dockerjava/api/command/TagImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/TagImageCmd.java @@ -28,5 +28,8 @@ public interface TagImageCmd extends DockerCmd { public TagImageCmd withForce(); public TagImageCmd withForce(boolean force); + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/TopContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/TopContainerCmd.java index 846599bd..c7818a79 100644 --- a/src/main/java/com/github/dockerjava/api/command/TopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/TopContainerCmd.java @@ -19,5 +19,8 @@ public interface TopContainerCmd extends DockerCmd { * @throws NotFoundException No such container */ public TopContainerResponse exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java index e8840768..e479b269 100644 --- a/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java @@ -42,5 +42,4 @@ public String toString() { ", processes=" + buffer.toString() + '}'; } - } diff --git a/src/main/java/com/github/dockerjava/api/command/UnpauseContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/UnpauseContainerCmd.java index 916c9b11..e74df14c 100644 --- a/src/main/java/com/github/dockerjava/api/command/UnpauseContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/UnpauseContainerCmd.java @@ -18,5 +18,8 @@ public interface UnpauseContainerCmd extends DockerCmd { * @throws NotFoundException No such container */ public Void exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/VersionCmd.java b/src/main/java/com/github/dockerjava/api/command/VersionCmd.java index d801a782..740a335e 100644 --- a/src/main/java/com/github/dockerjava/api/command/VersionCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/VersionCmd.java @@ -5,6 +5,9 @@ /** * Returns the Docker version info. */ -public interface VersionCmd extends DockerCmd{ +public interface VersionCmd extends DockerCmd { + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/WaitContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/WaitContainerCmd.java index d59eaa14..3216ead2 100644 --- a/src/main/java/com/github/dockerjava/api/command/WaitContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/WaitContainerCmd.java @@ -1,6 +1,5 @@ package com.github.dockerjava.api.command; - /** * Wait a container * @@ -11,5 +10,8 @@ public interface WaitContainerCmd extends DockerCmd { public String getContainerId(); public WaitContainerCmd withContainerId(String containerId); + + public static interface Exec extends DockerCmdExec { + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/model/AuthConfig.java b/src/main/java/com/github/dockerjava/api/model/AuthConfig.java index 371bc83e..3c61fe4d 100644 --- a/src/main/java/com/github/dockerjava/api/model/AuthConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/AuthConfig.java @@ -3,7 +3,6 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -@JsonIgnoreProperties(ignoreUnknown = true) public class AuthConfig { @JsonProperty private String username; diff --git a/src/main/java/com/github/dockerjava/client/DockerClientImpl.java b/src/main/java/com/github/dockerjava/client/DockerClientImpl.java deleted file mode 100644 index 306f0973..00000000 --- a/src/main/java/com/github/dockerjava/client/DockerClientImpl.java +++ /dev/null @@ -1,301 +0,0 @@ -package com.github.dockerjava.client; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; - -import org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.client.ClientProperties; - -import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; -import com.github.dockerjava.api.command.AttachContainerCmd; -import com.github.dockerjava.api.command.AuthCmd; -import com.github.dockerjava.api.command.BuildImageCmd; -import com.github.dockerjava.api.command.CommitCmd; -import com.github.dockerjava.api.command.ContainerDiffCmd; -import com.github.dockerjava.api.command.CopyFileFromContainerCmd; -import com.github.dockerjava.api.command.CreateContainerCmd; -import com.github.dockerjava.api.command.CreateImageCmd; -import com.github.dockerjava.api.command.InfoCmd; -import com.github.dockerjava.api.command.InspectContainerCmd; -import com.github.dockerjava.api.command.InspectImageCmd; -import com.github.dockerjava.api.command.KillContainerCmd; -import com.github.dockerjava.api.command.ListContainersCmd; -import com.github.dockerjava.api.command.ListImagesCmd; -import com.github.dockerjava.api.command.LogContainerCmd; -import com.github.dockerjava.api.command.PauseContainerCmd; -import com.github.dockerjava.api.command.PingCmd; -import com.github.dockerjava.api.command.PullImageCmd; -import com.github.dockerjava.api.command.PushImageCmd; -import com.github.dockerjava.api.command.RemoveContainerCmd; -import com.github.dockerjava.api.command.RemoveImageCmd; -import com.github.dockerjava.api.command.RestartContainerCmd; -import com.github.dockerjava.api.command.SearchImagesCmd; -import com.github.dockerjava.api.command.StartContainerCmd; -import com.github.dockerjava.api.command.StopContainerCmd; -import com.github.dockerjava.api.command.TagImageCmd; -import com.github.dockerjava.api.command.TopContainerCmd; -import com.github.dockerjava.api.command.UnpauseContainerCmd; -import com.github.dockerjava.api.command.VersionCmd; -import com.github.dockerjava.api.command.WaitContainerCmd; -import com.github.dockerjava.api.model.AuthConfig; -import com.github.dockerjava.client.command.AttachContainerCommand; -import com.github.dockerjava.client.command.AuthCommand; -import com.github.dockerjava.client.command.BuildImageCommand; -import com.github.dockerjava.client.command.CommitCommand; -import com.github.dockerjava.client.command.ContainerDiffCommand; -import com.github.dockerjava.client.command.CopyFileFromContainerCommand; -import com.github.dockerjava.client.command.CreateContainerCommand; -import com.github.dockerjava.client.command.CreateImageCommand; -import com.github.dockerjava.client.command.InfoCommand; -import com.github.dockerjava.client.command.InspectContainerCommand; -import com.github.dockerjava.client.command.InspectImageCommand; -import com.github.dockerjava.client.command.KillContainerCommand; -import com.github.dockerjava.client.command.ListContainersCommand; -import com.github.dockerjava.client.command.ListImagesCommand; -import com.github.dockerjava.client.command.LogContainerCommand; -import com.github.dockerjava.client.command.PauseContainerCommand; -import com.github.dockerjava.client.command.PingCommand; -import com.github.dockerjava.client.command.PullImageCommand; -import com.github.dockerjava.client.command.PushImageCommand; -import com.github.dockerjava.client.command.RemoveContainerCommand; -import com.github.dockerjava.client.command.RemoveImageCommand; -import com.github.dockerjava.client.command.RestartContainerCommand; -import com.github.dockerjava.client.command.SearchImagesCommand; -import com.github.dockerjava.client.command.StartContainerCommand; -import com.github.dockerjava.client.command.StopContainerCommand; -import com.github.dockerjava.client.command.TagImageCommand; -import com.github.dockerjava.client.command.TopContainerCommand; -import com.github.dockerjava.client.command.UnpauseContainerCommand; -import com.github.dockerjava.client.command.VersionCommand; -import com.github.dockerjava.client.command.WaitContainerCommand; -import com.github.dockerjava.client.utils.JsonClientFilter; - -/** - * @author Konstantin Pelykh (kpelykh@gmail.com) - */ -public class DockerClientImpl implements Closeable, com.github.dockerjava.api.DockerClient { - - private final Client client; - - private final WebTarget baseResource; - private final DockerClientConfig dockerClientConfig; - - public DockerClientImpl() { - this(DockerClientConfig.createDefaultConfigBuilder().build()); - } - - public DockerClientImpl(String serverUrl) { - this(configWithServerUrl(serverUrl)); - } - - private static DockerClientConfig configWithServerUrl(String serverUrl) { - return DockerClientConfig.createDefaultConfigBuilder() - .withUri(serverUrl) - .build(); - } - - public DockerClientImpl(DockerClientConfig dockerClientConfig) { - this.dockerClientConfig = dockerClientConfig; - - ClientConfig clientConfig = new ClientConfig(); - - clientConfig.register(JsonClientFilter.class); - clientConfig.register(JacksonJsonProvider.class); - - if (dockerClientConfig.isLoggingFilterEnabled()) { - clientConfig.register(SelectiveLoggingFilter.class); - } - - if (dockerClientConfig.getReadTimeout() != null) { - int readTimeout = dockerClientConfig.getReadTimeout(); - clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); - } - client = ClientBuilder.newClient(clientConfig); - - - - WebTarget webResource = client.target(dockerClientConfig.getUri()); - - if (dockerClientConfig.getVersion() != null) { - baseResource = webResource.path("v" + dockerClientConfig.getVersion()); - } else { - baseResource = webResource; - } - } - - public AuthConfig authConfig() { - checkNotNull(dockerClientConfig.getUsername(), "Configured username is null."); - checkNotNull(dockerClientConfig.getPassword(), "Configured password is null."); - checkNotNull(dockerClientConfig.getEmail(), "Configured email is null."); - - AuthConfig authConfig = new AuthConfig(); - authConfig.setUsername(dockerClientConfig.getUsername()); - authConfig.setPassword(dockerClientConfig.getPassword()); - authConfig.setEmail(dockerClientConfig.getEmail()); - // TODO Make the registry address configurable - return authConfig; - } - - /** - * * MISC API * - */ - - /** - * Authenticate with the server, useful for checking authentication. - */ - public AuthCmd authCmd() { - return new AuthCommand(authConfig()).withBaseResource(baseResource); - } - - public InfoCmd infoCmd() { - return new InfoCommand().withBaseResource(baseResource); - } - - public PingCmd pingCmd() { - return new PingCommand().withBaseResource(baseResource); - } - - public VersionCmd versionCmd() { - return new VersionCommand().withBaseResource(baseResource); - } - - /** - * * IMAGE API * - */ - - public PullImageCmd pullImageCmd(String repository) { - return new PullImageCommand(repository).withBaseResource(baseResource); - } - - public PushImageCmd pushImageCmd(String name) { - return new PushImageCommand(name).withAuthConfig(authConfig()) - .withBaseResource(baseResource); - } - - public CreateImageCmd createImageCmd(String repository, InputStream imageStream) { - return new CreateImageCommand(repository, imageStream) - .withBaseResource(baseResource); - } - - public SearchImagesCmd searchImagesCmd(String term) { - return new SearchImagesCommand(term).withBaseResource(baseResource); - } - - public RemoveImageCmd removeImageCmd(String imageId) { - return new RemoveImageCommand(imageId).withBaseResource(baseResource); - } - - public ListImagesCmd listImagesCmd() { - return new ListImagesCommand().withBaseResource(baseResource); - } - - public InspectImageCmd inspectImageCmd(String imageId) { - return new InspectImageCommand(imageId).withBaseResource(baseResource); - } - - /** - * * CONTAINER API * - */ - - public ListContainersCmd listContainersCmd() { - return new ListContainersCommand().withBaseResource(baseResource); - } - - public CreateContainerCmd createContainerCmd(String image) { - return new CreateContainerCommand(image).withBaseResource(baseResource); - } - - public StartContainerCmd startContainerCmd(String containerId) { - return new StartContainerCommand(containerId) - .withBaseResource(baseResource); - } - - public InspectContainerCmd inspectContainerCmd(String containerId) { - return new InspectContainerCommand(containerId) - .withBaseResource(baseResource); - } - - public RemoveContainerCmd removeContainerCmd(String containerId) { - return new RemoveContainerCommand(containerId) - .withBaseResource(baseResource); - } - - public WaitContainerCmd waitContainerCmd(String containerId) { - return new WaitContainerCommand(containerId).withBaseResource(baseResource); - } - - public AttachContainerCmd attachContainerCmd(String containerId) { - return new AttachContainerCommand(containerId).withBaseResource(baseResource); - } - - public LogContainerCmd logContainerCmd(String containerId) { - return new LogContainerCommand(containerId).withBaseResource(baseResource); - } - - public CopyFileFromContainerCmd copyFileFromContainerCmd( - String containerId, String resource) { - return new CopyFileFromContainerCommand(containerId, resource) - .withBaseResource(baseResource); - } - - public ContainerDiffCmd containerDiffCmd(String containerId) { - return new ContainerDiffCommand(containerId).withBaseResource(baseResource); - } - - public StopContainerCmd stopContainerCmd(String containerId) { - return new StopContainerCommand(containerId).withBaseResource(baseResource); - } - - public KillContainerCmd killContainerCmd(String containerId) { - return new KillContainerCommand(containerId).withBaseResource(baseResource); - } - - public RestartContainerCmd restartContainerCmd(String containerId) { - return new RestartContainerCommand(containerId) - .withBaseResource(baseResource); - } - - public CommitCmd commitCmd(String containerId) { - return new CommitCommand(containerId).withBaseResource(baseResource); - } - - public BuildImageCmd buildImageCmd(File dockerFolder) { - return new BuildImageCommand(dockerFolder).withBaseResource(baseResource); - } - - public BuildImageCmd buildImageCmd(InputStream tarInputStream) { - return new BuildImageCommand(tarInputStream).withBaseResource(baseResource); - } - - public TopContainerCmd topContainerCmd(String containerId) { - return new TopContainerCommand(containerId).withBaseResource(baseResource); - } - - public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { - return new TagImageCommand(imageId, repository, tag).withBaseResource(baseResource); - } - - @Override - public PauseContainerCmd pauseContainerCmd(String containerId) { - return new PauseContainerCommand(containerId).withBaseResource(baseResource); - } - - @Override - public UnpauseContainerCmd unpauseContainerCmd(String containerId) { - return new UnpauseContainerCommand(containerId).withBaseResource(baseResource); - } - - @Override - public void close() throws IOException { - client.close(); - } - -} diff --git a/src/main/java/com/github/dockerjava/client/command/AuthCommand.java b/src/main/java/com/github/dockerjava/client/command/AuthCommand.java deleted file mode 100644 index a5710542..00000000 --- a/src/main/java/com/github/dockerjava/client/command/AuthCommand.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.github.dockerjava.client.command; - -import static javax.ws.rs.client.Entity.entity; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.api.UnauthorizedException; -import com.github.dockerjava.api.command.AuthCmd; -import com.github.dockerjava.api.model.AuthConfig; - -/** - * - * Authenticate with the server, useful for checking authentication. - * - */ -public class AuthCommand extends AbstrAuthCfgDockerCmd implements AuthCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(AuthCommand.class); - - public AuthCommand(AuthConfig authConfig) { - withAuthConfig(authConfig); - } - - @Override - public Void exec() throws UnauthorizedException { - return super.exec(); - } - - protected Void impl() throws UnauthorizedException { - WebTarget webResource = baseResource.path("/auth"); - LOGGER.trace("POST: {}", webResource); - Response response = webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(authConfig, MediaType.APPLICATION_JSON)); - - if(response.getStatus() == 401) { - throw new UnauthorizedException("Unauthorized"); - }; - - return null; - } - - @Override - public String toString() { - return "authenticate using " + this.authConfig; - } -} diff --git a/src/main/java/com/github/dockerjava/client/command/InfoCommand.java b/src/main/java/com/github/dockerjava/client/command/InfoCommand.java deleted file mode 100644 index 791cec74..00000000 --- a/src/main/java/com/github/dockerjava/client/command/InfoCommand.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.github.dockerjava.client.command; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.api.command.InfoCmd; -import com.github.dockerjava.api.model.Info; - -/** - * Return Docker server info - */ -public class InfoCommand extends AbstrDockerCmd implements InfoCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(InfoCommand.class); - - @Override - public String toString() { - return "info"; - } - - protected Info impl() throws DockerException { - WebTarget webResource = baseResource.path("/info"); - - LOGGER.trace("GET: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON).get(Info.class); - } -} diff --git a/src/main/java/com/github/dockerjava/client/command/PauseContainerCommand.java b/src/main/java/com/github/dockerjava/client/command/PauseContainerCommand.java deleted file mode 100644 index 952218a1..00000000 --- a/src/main/java/com/github/dockerjava/client/command/PauseContainerCommand.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.github.dockerjava.client.command; - -import static javax.ws.rs.client.Entity.entity; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.PauseContainerCmd; -import com.google.common.base.Preconditions; - -/** - * Pause a container. - * - * @param containerId - Id of the container - * - */ -public class PauseContainerCommand extends AbstrDockerCmd implements PauseContainerCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(PauseContainerCommand.class); - - private String containerId; - - public PauseContainerCommand(String containerId) { - withContainerId(containerId); - } - - @Override - public String getContainerId() { - return containerId; - } - - @Override - public PauseContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); - this.containerId = containerId; - return this; - } - - @Override - public String toString() { - return new StringBuilder("pause ") - .append(containerId) - .toString(); - } - - /** - * @throws NotFoundException No such container - */ - @Override - public Void exec() throws NotFoundException { - return super.exec(); - } - - protected Void impl() throws DockerException { - WebTarget webResource = baseResource.path("/containers/{id}/pause") - .resolveTemplate("id", containerId); - - LOGGER.trace("POST: {}", webResource); - webResource.request() - .accept(MediaType.APPLICATION_JSON) - .post(entity(null, MediaType.APPLICATION_JSON), Response.class); - - return null; - } -} diff --git a/src/main/java/com/github/dockerjava/client/command/PushImageCommand.java b/src/main/java/com/github/dockerjava/client/command/PushImageCommand.java deleted file mode 100644 index d4db38be..00000000 --- a/src/main/java/com/github/dockerjava/client/command/PushImageCommand.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.github.dockerjava.client.command; - -import java.io.InputStream; - -import javax.ws.rs.ClientErrorException; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.PushImageCmd; -import com.google.common.base.Preconditions; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; - -import static javax.ws.rs.client.Entity.entity; - -/** - * 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 class PushImageCommand extends AbstrAuthCfgDockerCmd implements PushImageCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(PushImageCommand.class); - - private String name; - - public PushImageCommand(String name) { - withName(name); - } - - @Override - public String getName() { - return name; - } - - /** - * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. - */ - @Override - public PushImageCmd withName(String name) { - Preconditions.checkNotNull(name, "name was not specified"); - this.name = name; - return this; - } - - @Override - public String toString() { - return new StringBuilder("push ") - .append(name) - .toString(); - } - - /** - * @throws NotFoundException No such image - */ - @Override - public InputStream exec() throws NotFoundException { - return super.exec(); - } - - protected InputStream impl() { - WebTarget webResource = baseResource.path("/images/" + name(name) + "/push"); - - final String registryAuth = registryAuth(); - LOGGER.trace("POST: {}", webResource); - return webResource - .request() - .header("X-Registry-Auth", registryAuth) - .accept(MediaType.APPLICATION_JSON) - .post(entity(Response.class, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); - } - - private String name(String name) { - return name.contains("/") ? name : authConfig.getUsername(); - } -} diff --git a/src/main/java/com/github/dockerjava/client/command/SearchImagesCommand.java b/src/main/java/com/github/dockerjava/client/command/SearchImagesCommand.java deleted file mode 100644 index 9844c2a3..00000000 --- a/src/main/java/com/github/dockerjava/client/command/SearchImagesCommand.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.github.dockerjava.client.command; - -import java.util.List; - -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.command.SearchImagesCmd; -import com.github.dockerjava.api.model.SearchItem; -import com.google.common.base.Preconditions; - -import javax.ws.rs.client.WebTarget; - -/** - * Search images - * - * @param term - search term - * - */ -public class SearchImagesCommand extends AbstrDockerCmd> implements SearchImagesCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(SearchImagesCommand.class); - - private String term; - - public SearchImagesCommand(String term) { - withTerm(term); - } - - @Override - public String getTerm() { - return term; - } - - @Override - public SearchImagesCmd withTerm(String term) { - Preconditions.checkNotNull(term, "term was not specified"); - this.term = term; - return this; - } - - @Override - public String toString() { - return new StringBuilder("search ") - .append(term) - .toString(); - } - - protected List impl() { - - WebTarget webResource = baseResource.path("/images/search").queryParam("term", term); - - LOGGER.trace("GET: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { - }); - } -} diff --git a/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCommand.java b/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCommand.java deleted file mode 100644 index d6006ed9..00000000 --- a/src/main/java/com/github/dockerjava/client/command/UnpauseContainerCommand.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.github.dockerjava.client.command; - -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.UnpauseContainerCmd; -import com.google.common.base.Preconditions; - - -/** - * Unpause a container. - * - * @param containerId - Id of the container - * - */ -public class UnpauseContainerCommand extends AbstrDockerCmd implements UnpauseContainerCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(UnpauseContainerCommand.class); - - private String containerId; - - public UnpauseContainerCommand(String containerId) { - withContainerId(containerId); - } - - @Override - public String getContainerId() { - return containerId; - } - - @Override - public UnpauseContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); - this.containerId = containerId; - return this; - } - - @Override - public String toString() { - return new StringBuilder("pause ") - .append(containerId) - .toString(); - } - - /** - * @throws NotFoundException No such container - */ - @Override - public Void exec() throws NotFoundException { - return super.exec(); - } - - protected Void impl() throws DockerException { - WebTarget webResource = baseResource.path("/containers/{id}/unpause") - .resolveTemplate("id", containerId); - - LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON) - .post(Entity.entity(Response.class, MediaType.APPLICATION_JSON)); - - return null; - } -} diff --git a/src/main/java/com/github/dockerjava/client/command/VersionCommand.java b/src/main/java/com/github/dockerjava/client/command/VersionCommand.java deleted file mode 100644 index 4b1da4d5..00000000 --- a/src/main/java/com/github/dockerjava/client/command/VersionCommand.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.github.dockerjava.client.command; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.api.command.VersionCmd; -import com.github.dockerjava.api.model.Version; - - -/** - * Returns the Docker version info. - */ -public class VersionCommand extends AbstrDockerCmd implements VersionCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(VersionCommand.class); - - @Override - public String toString() { - return "version"; - } - - protected Version impl() throws DockerException { - WebTarget webResource = baseResource.path("/version"); - - LOGGER.trace("GET: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON).get(Version.class); - } -} diff --git a/src/main/java/com/github/dockerjava/client/command/WaitContainerCommand.java b/src/main/java/com/github/dockerjava/client/command/WaitContainerCommand.java deleted file mode 100644 index 1b765287..00000000 --- a/src/main/java/com/github/dockerjava/client/command/WaitContainerCommand.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.github.dockerjava.client.command; - -import static javax.ws.rs.client.Entity.entity; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.github.dockerjava.api.command.WaitContainerCmd; -import com.google.common.base.Preconditions; - -/** - * Wait a container - * - * Block until container stops, then returns its exit code - */ -public class WaitContainerCommand extends AbstrDockerCmd implements WaitContainerCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(WaitContainerCommand.class); - - private String containerId; - - public WaitContainerCommand(String containerId) { - withContainerId(containerId); - } - - @Override - public String getContainerId() { - return containerId; - } - - @Override - public WaitContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); - this.containerId = containerId; - return this; - } - - @Override - public String toString() { - return "wait " + containerId; - } - - protected Integer impl() { - WebTarget webResource = baseResource.path("/containers/{id}/wait") - .resolveTemplate("id", containerId); - - LOGGER.trace("POST: {}", webResource); - ObjectNode ObjectNode = webResource.request().accept(MediaType.APPLICATION_JSON) - .post(entity(null, MediaType.APPLICATION_JSON), ObjectNode.class); - - return ObjectNode.get("StatusCode").asInt(); - } -} diff --git a/src/main/java/com/github/dockerjava/client/utils/CompressArchiveUtil.java b/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java similarity index 96% rename from src/main/java/com/github/dockerjava/client/utils/CompressArchiveUtil.java rename to src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java index 4da0cdac..4fbb227a 100644 --- a/src/main/java/com/github/dockerjava/client/utils/CompressArchiveUtil.java +++ b/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.utils; +package com.github.dockerjava.core; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; diff --git a/src/main/java/com/github/dockerjava/client/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java similarity index 99% rename from src/main/java/com/github/dockerjava/client/DockerClientConfig.java rename to src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 1038047c..b2adea7f 100644 --- a/src/main/java/com/github/dockerjava/client/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -1,4 +1,4 @@ - package com.github.dockerjava.client; + package com.github.dockerjava.core; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java new file mode 100644 index 00000000..ed4c4615 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -0,0 +1,245 @@ +package com.github.dockerjava.core; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; + +import com.github.dockerjava.api.command.*; +import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.core.command.*; +import com.github.dockerjava.jaxrs.DockerCmdExecFactoryImpl; +import com.google.common.base.Preconditions; + +/** + * @author Konstantin Pelykh (kpelykh@gmail.com) + */ +public class DockerClientImpl implements Closeable, com.github.dockerjava.api.DockerClient { + + private final DockerClientConfig dockerClientConfig; + + private DockerCmdExecFactoryImpl dockerCmdExecFactory; + + public DockerClientImpl() { + this(DockerClientConfig.createDefaultConfigBuilder().build()); + } + + public DockerClientImpl(String serverUrl) { + this(configWithServerUrl(serverUrl)); + } + + private static DockerClientConfig configWithServerUrl(String serverUrl) { + return DockerClientConfig.createDefaultConfigBuilder() + .withUri(serverUrl) + .build(); + } + + public DockerClientImpl(DockerClientConfig dockerClientConfig) { + Preconditions.checkNotNull(dockerClientConfig, "config was not specified"); + this.dockerClientConfig = dockerClientConfig; + setDockerCmdExecFactory(new DockerCmdExecFactoryImpl()); + } + + public void setDockerCmdExecFactory( + DockerCmdExecFactoryImpl dockerCmdExecFactory) { + Preconditions.checkNotNull(dockerCmdExecFactory, "dockerCmdExecFactory was not specified"); + this.dockerCmdExecFactory = dockerCmdExecFactory; + this.dockerCmdExecFactory.init(dockerClientConfig); + } + + public DockerCmdExecFactoryImpl getDockerCmdExecFactory() { + return dockerCmdExecFactory; + } + + + public AuthConfig authConfig() { + checkNotNull(dockerClientConfig.getUsername(), "Configured username is null."); + checkNotNull(dockerClientConfig.getPassword(), "Configured password is null."); + checkNotNull(dockerClientConfig.getEmail(), "Configured email is null."); + + AuthConfig authConfig = new AuthConfig(); + authConfig.setUsername(dockerClientConfig.getUsername()); + authConfig.setPassword(dockerClientConfig.getPassword()); + authConfig.setEmail(dockerClientConfig.getEmail()); + // TODO Make the registry address configurable + return authConfig; + } + + /** + * * MISC API * + */ + + /** + * Authenticate with the server, useful for checking authentication. + */ + @Override + public AuthCmd authCmd() { + return new AuthCmdImpl(getDockerCmdExecFactory().createAuthCmdExec(), authConfig()); + } + + @Override + public InfoCmd infoCmd() { + return new InfoCmdImpl(getDockerCmdExecFactory().createInfoCmdExec()); + } + + @Override + public PingCmd pingCmd() { + return new PingCmdImpl(getDockerCmdExecFactory().createPingCmdExec()); + } + + @Override + public VersionCmd versionCmd() { + return new VersionCmdImpl(getDockerCmdExecFactory().createVersionCmdExec()); + } + + /** + * * IMAGE API * + */ + + @Override + public PullImageCmd pullImageCmd(String repository) { + return new PullImageCmdImpl(getDockerCmdExecFactory().createPullImageCmdExec(), repository); + } + + @Override + public PushImageCmd pushImageCmd(String name) { + return new PushImageCmdImpl(getDockerCmdExecFactory().createPushImageCmdExec(), name); + } + + @Override + public CreateImageCmd createImageCmd(String repository, InputStream imageStream) { + return new CreateImageCmdImpl(getDockerCmdExecFactory().createCreateImageCmdExec(), repository, imageStream); + } + + @Override + public SearchImagesCmd searchImagesCmd(String term) { + return new SearchImagesCmdImpl(getDockerCmdExecFactory().createSearchImagesCmdExec(), term); + } + + @Override + public RemoveImageCmd removeImageCmd(String imageId) { + return new RemoveImageCmdImpl(getDockerCmdExecFactory().createRemoveImageCmdExec(), imageId); + } + + @Override + public ListImagesCmd listImagesCmd() { + return new ListImagesCmdImpl(getDockerCmdExecFactory().createListImagesCmdExec()); + } + + @Override + public InspectImageCmd inspectImageCmd(String imageId) { + return new InspectImageCmdImpl(getDockerCmdExecFactory().createInspectImageCmdExec(), imageId); + } + + /** + * * CONTAINER API * + */ + + @Override + public ListContainersCmd listContainersCmd() { + return new ListContainersCmdImpl(getDockerCmdExecFactory().createListContainersCmdExec()); + } + + @Override + public CreateContainerCmd createContainerCmd(String image) { + return new CreateContainerCmdImpl(getDockerCmdExecFactory().createCreateContainerCmdExec(), image); + } + + @Override + public StartContainerCmd startContainerCmd(String containerId) { + return new StartContainerCmdImpl(getDockerCmdExecFactory().createStartContainerCmdExec(), containerId); + } + + @Override + public InspectContainerCmd inspectContainerCmd(String containerId) { + return new InspectContainerCmdImpl(getDockerCmdExecFactory().createInspectContainerCmdExec(), containerId); + } + + @Override + public RemoveContainerCmd removeContainerCmd(String containerId) { + return new RemoveContainerCmdImpl(getDockerCmdExecFactory().createRemoveContainerCmdExec(), containerId); + } + + @Override + public WaitContainerCmd waitContainerCmd(String containerId) { + return new WaitContainerCmdImpl(getDockerCmdExecFactory().createWaitContainerCmdExec(), containerId); + } + + @Override + public AttachContainerCmd attachContainerCmd(String containerId) { + return new AttachContainerCmdImpl(getDockerCmdExecFactory().createAttachContainerCmdExec(), containerId); + } + + @Override + public LogContainerCmd logContainerCmd(String containerId) { + return new LogContainerCmdImpl(getDockerCmdExecFactory().createLogContainerCmdExec(), containerId); + } + + @Override + public CopyFileFromContainerCmd copyFileFromContainerCmd(String containerId, String resource) { + return new CopyFileFromContainerCmdImpl(getDockerCmdExecFactory().createCopyFileFromContainerCmdExec(), containerId, resource); + } + + @Override + public ContainerDiffCmd containerDiffCmd(String containerId) { + return new ContainerDiffCmdImpl(getDockerCmdExecFactory().createContainerDiffCmdExec(), containerId); + } + + @Override + public StopContainerCmd stopContainerCmd(String containerId) { + return new StopContainerCmdImpl(getDockerCmdExecFactory().createStopContainerCmdExec(), containerId); + } + + @Override + public KillContainerCmd killContainerCmd(String containerId) { + return new KillContainerCmdImpl(getDockerCmdExecFactory().createKillContainerCmdExec(), containerId); + } + + @Override + public RestartContainerCmd restartContainerCmd(String containerId) { + return new RestartContainerCmdImpl(getDockerCmdExecFactory().createRestartContainerCmdExec(), containerId); + } + + @Override + public CommitCmd commitCmd(String containerId) { + return new CommitCmdImpl(getDockerCmdExecFactory().createCommitCmdExec(), containerId); + } + + @Override + public BuildImageCmd buildImageCmd(File dockerFolder) { + return new BuildImageCmdImpl(getDockerCmdExecFactory().createBuildImageCmdExec(), dockerFolder); + } + + @Override + public BuildImageCmd buildImageCmd(InputStream tarInputStream) { + return new BuildImageCmdImpl(getDockerCmdExecFactory().createBuildImageCmdExec(), tarInputStream); + } + + @Override + public TopContainerCmd topContainerCmd(String containerId) { + return new TopContainerCmdImpl(getDockerCmdExecFactory().createTopContainerCmdExec(), containerId); + } + + @Override + public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { + return new TagImageCmdImpl(getDockerCmdExecFactory().createTagImageCmdExec(), imageId, repository, tag); + } + + @Override + public PauseContainerCmd pauseContainerCmd(String containerId) { + return new PauseContainerCmdImpl(getDockerCmdExecFactory().createPauseContainerCmdExec(), containerId); + } + + @Override + public UnpauseContainerCmd unpauseContainerCmd(String containerId) { + return new UnpauseContainerCmdImpl(getDockerCmdExecFactory().createUnpauseContainerCmdExec(), containerId); + } + + @Override + public void close() throws IOException { + getDockerCmdExecFactory().close(); + } + +} diff --git a/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java b/src/main/java/com/github/dockerjava/core/JsonClientFilter.java similarity index 94% rename from src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java rename to src/main/java/com/github/dockerjava/core/JsonClientFilter.java index 31b51845..cb44dacc 100644 --- a/src/main/java/com/github/dockerjava/client/utils/JsonClientFilter.java +++ b/src/main/java/com/github/dockerjava/core/JsonClientFilter.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.utils; +package com.github.dockerjava.core; import javax.ws.rs.client.ClientRequestContext; diff --git a/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java b/src/main/java/com/github/dockerjava/core/SelectiveLoggingFilter.java similarity index 96% rename from src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java rename to src/main/java/com/github/dockerjava/core/SelectiveLoggingFilter.java index b0f69ebb..114e658f 100644 --- a/src/main/java/com/github/dockerjava/client/SelectiveLoggingFilter.java +++ b/src/main/java/com/github/dockerjava/core/SelectiveLoggingFilter.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client; +package com.github.dockerjava.core; import java.io.IOException; import java.util.Set; diff --git a/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java similarity index 61% rename from src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java rename to src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java index 46630ea8..4ce7f0b4 100644 --- a/src/main/java/com/github/dockerjava/client/command/AbstrAuthCfgDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java @@ -1,17 +1,27 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.command.DockerCmd; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.model.AuthConfig; import com.google.common.base.Preconditions; import org.apache.commons.codec.binary.Base64; -public abstract class AbstrAuthCfgDockerCmd, RES_T> extends +public abstract class AbstrAuthCfgDockerCmd, RES_T> extends AbstrDockerCmd { - protected AuthConfig authConfig; + public AbstrAuthCfgDockerCmd(DockerCmdExec execution) { + super(execution); + } + + private AuthConfig authConfig; + + public AuthConfig getAuthConfig() { + return authConfig; + } @SuppressWarnings("unchecked") public T withAuthConfig(AuthConfig authConfig) { diff --git a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java similarity index 76% rename from src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java rename to src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java index cff52d22..b01d5d97 100644 --- a/src/main/java/com/github/dockerjava/client/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -11,36 +11,34 @@ import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; import com.github.dockerjava.api.command.DockerCmd; +import com.github.dockerjava.api.command.DockerCmdExec; import com.google.common.base.Preconditions; import javax.ws.rs.ClientErrorException; -import javax.ws.rs.client.WebTarget; - -public abstract class AbstrDockerCmd, RES_T> implements DockerCmd { +public abstract class AbstrDockerCmd, RES_T> implements DockerCmd { private final static Logger LOGGER = LoggerFactory.getLogger(AbstrDockerCmd.class); - protected WebTarget baseResource; - - @SuppressWarnings("unchecked") - public T withBaseResource(WebTarget baseResource) { - this.baseResource = baseResource; - return (T) this; - } + protected DockerCmdExec execution; - protected abstract RES_T impl(); + public AbstrDockerCmd(DockerCmdExec execution) { + Preconditions.checkNotNull(execution, "execution was not specified"); + this.execution = execution; + } + + //protected abstract RES_T impl(); /** * @throws DockerException If something gets wrong */ @Override public RES_T exec() throws DockerException { - Preconditions.checkNotNull(baseResource, "baseResource was not specified"); + LOGGER.debug("Cmd: {}", this); try { - return impl(); + return execution.exec((CMD_T)this); } catch (ClientErrorException exception) { int status = exception.getResponse().getStatus(); switch(status) { diff --git a/src/main/java/com/github/dockerjava/client/command/AttachContainerCommand.java b/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java similarity index 62% rename from src/main/java/com/github/dockerjava/client/command/AttachContainerCommand.java rename to src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java index e17c3c3a..310cea0c 100644 --- a/src/main/java/com/github/dockerjava/client/command/AttachContainerCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java @@ -1,24 +1,12 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import java.io.InputStream; -import javax.ws.rs.ClientErrorException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.AttachContainerCmd; +import com.github.dockerjava.api.command.DockerCmdExec; import com.google.common.base.Preconditions; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; - -import static javax.ws.rs.client.Entity.entity; - /** * Attach to container * @@ -35,16 +23,14 @@ * - true or false, if true, print timestamps for every log line. * Defaults to false. */ -public class AttachContainerCommand extends AbstrDockerCmd implements AttachContainerCmd { - - private static final Logger LOGGER = LoggerFactory - .getLogger(AttachContainerCommand.class); +public class AttachContainerCmdImpl extends AbstrDockerCmd implements AttachContainerCmd { private String containerId; private boolean logs, followStream, timestamps, stdout, stderr; - public AttachContainerCommand(String containerId) { + public AttachContainerCmdImpl(DockerCmdExec exec, String containerId) { + super(exec); withContainerId(containerId); } @@ -80,8 +66,7 @@ public boolean hasStderrEnabled() { @Override public AttachContainerCmd withContainerId(String containerId) { - Preconditions - .checkNotNull(containerId, "containerId was not specified"); + Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } @@ -138,18 +123,28 @@ public AttachContainerCmd withLogs(boolean logs) { public InputStream exec() throws NotFoundException { return super.exec(); } - - protected InputStream impl() throws DockerException { - WebTarget webResource = baseResource.path("/containers/{id}/attach") - .resolveTemplate("{id}", containerId) - .queryParam("logs", logs ? "1" : "0") - .queryParam("timestamps", timestamps ? "1" : "0") - .queryParam("stdout", stdout ? "1" : "0") - .queryParam("stderr", stderr ? "1" : "0") - .queryParam("follow", followStream ? "1" : "0"); - - LOGGER.trace("POST: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .post(entity(null, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); - } + + public static interface Exec extends DockerCmdExec { + + } + +// protected InputStream impl() throws DockerException { +// +// AttachContainerCmd command = this; +// +// WebTarget webResource = baseResource.path("/containers/{id}/attach") +// .resolveTemplate("{id}", command.getContainerId()) +// .queryParam("logs", command.hasLogsEnabled() ? "1" : "0") +// .queryParam("timestamps",command.hasTimestampsEnabled() ? "1" : "0") +// .queryParam("stdout", command.hasStdoutEnabled() ? "1" : "0") +// .queryParam("stderr", command.hasStderrEnabled() ? "1" : "0") +// .queryParam("follow", command.hasFollowStreamEnabled() ? "1" : "0"); +// +// LOGGER.trace("POST: {}", webResource); +// +// return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) +// .post(entity(null, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); +// } + + } diff --git a/src/main/java/com/github/dockerjava/core/command/AuthCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/AuthCmdImpl.java new file mode 100644 index 00000000..f7f52cf4 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/AuthCmdImpl.java @@ -0,0 +1,29 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.UnauthorizedException; +import com.github.dockerjava.api.command.AuthCmd; +import com.github.dockerjava.api.command.DockerCmdExec; +import com.github.dockerjava.api.model.AuthConfig; + +/** + * + * Authenticate with the server, useful for checking authentication. + * + */ +public class AuthCmdImpl extends AbstrAuthCfgDockerCmd implements AuthCmd { + + public AuthCmdImpl(DockerCmdExec exec, AuthConfig authConfig) { + super(exec); + withAuthConfig(authConfig); + } + + @Override + public Void exec() throws UnauthorizedException { + return super.exec(); + } + + @Override + public String toString() { + return "authenticate using " + this.getAuthConfig(); + } +} diff --git a/src/main/java/com/github/dockerjava/client/command/BuildImageCommand.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java similarity index 71% rename from src/main/java/com/github/dockerjava/client/command/BuildImageCommand.java rename to src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 31489f7c..184ffcf1 100644 --- a/src/main/java/com/github/dockerjava/client/command/BuildImageCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -1,6 +1,4 @@ -package com.github.dockerjava.client.command; - -import static javax.ws.rs.client.Entity.entity; +package com.github.dockerjava.core.command; import java.io.File; import java.io.IOException; @@ -15,18 +13,12 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - import org.apache.commons.io.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.github.dockerjava.api.DockerClientException; -import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.command.BuildImageCmd; -import com.github.dockerjava.client.utils.CompressArchiveUtil; +import com.github.dockerjava.api.command.DockerCmdExec; +import com.github.dockerjava.core.CompressArchiveUtil; import com.google.common.base.Preconditions; /** @@ -36,10 +28,7 @@ * TODO: http://docs.docker.com/reference/builder/#dockerignore * */ -public class BuildImageCommand extends AbstrDockerCmd implements BuildImageCmd { - - private static final Logger LOGGER = LoggerFactory - .getLogger(BuildImageCommand.class); +public class BuildImageCmdImpl extends AbstrDockerCmd implements BuildImageCmd { private static final Pattern ADD_OR_COPY_PATTERN = Pattern .compile("^(ADD|COPY)\\s+(.*)\\s+(.*)$"); @@ -47,33 +36,41 @@ public class BuildImageCommand extends AbstrDockerCmd exec, File dockerFolder) { + super(exec); Preconditions.checkNotNull(dockerFolder, "dockerFolder is null"); - this.dockerFolder = dockerFolder; + withTarInputStream(buildDockerFolderTar(dockerFolder)); } - public BuildImageCommand(InputStream tarInputStream) { + public BuildImageCmdImpl(DockerCmdExec exec, InputStream tarInputStream) { + super(exec); Preconditions.checkNotNull(tarInputStream, "tarInputStream is null"); - this.tarInputStream = tarInputStream; + withTarInputStream(tarInputStream); + } + + @Override + public InputStream getTarInputStream() { + return tarInputStream; } @Override - public BuildImageCommand withTag(String tag) { - Preconditions.checkNotNull(tag, "Tag is null"); - this.tag = tag; + public BuildImageCmdImpl withTarInputStream(InputStream tarInputStream) { + Preconditions.checkNotNull(tarInputStream, "tarInputStream is null"); + this.tarInputStream = tarInputStream; return this; } - + @Override - public File getDockerFolder() { - return dockerFolder; + public BuildImageCmdImpl withTag(String tag) { + Preconditions.checkNotNull(tag, "Tag is null"); + this.tag = tag; + return this; } @Override @@ -97,24 +94,24 @@ public boolean isQuiet() { } @Override - public BuildImageCommand withNoCache() { + public BuildImageCmdImpl withNoCache() { return withNoCache(true); } @Override - public BuildImageCommand withNoCache(boolean noCache) { + public BuildImageCmdImpl withNoCache(boolean noCache) { this.noCache = noCache; return this; } @Override - public BuildImageCommand withRemove(boolean rm) { + public BuildImageCmdImpl withRemove(boolean rm) { this.remove = rm; return this; } @Override - public BuildImageCommand withQuiet(boolean quiet) { + public BuildImageCmdImpl withQuiet(boolean quiet) { this.quiet = quiet; return this; } @@ -126,48 +123,36 @@ public String toString() { .append(noCache ? "--nocache=true " : "") .append(quiet ? "--quiet=true " : "") .append(!remove ? "--rm=false " : "") - .append(dockerFolder != null ? dockerFolder.getPath() : "-") .toString(); } - protected InputStream impl() throws DockerException { - if (tarInputStream == null) { - File dockerFolderTar = buildDockerFolderTar(); - try { - return callDocker(FileUtils.openInputStream(dockerFolderTar)); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - FileUtils.deleteQuietly(dockerFolderTar); - } - } else { - return callDocker(tarInputStream); - } - } - - - protected InputStream callDocker(final InputStream dockerFolderTarInputStream) { - - WebTarget webResource = baseResource.path("/build") - .queryParam("t", tag); - if (noCache) { - webResource = webResource.queryParam("nocache", "true"); - } - if (remove) { - webResource = webResource.queryParam("rm", "true"); - } - if (quiet) { - webResource = webResource.queryParam("q", "true"); - } - - LOGGER.trace("POST: {}", webResource); - return webResource - .request() - .accept(MediaType.TEXT_PLAIN) - .post(entity(dockerFolderTarInputStream, "application/tar"), Response.class).readEntity(InputStream.class); - - } - - protected File buildDockerFolderTar() { + + + +// protected InputStream impl() { +// +// BuildImageCmd command = this; +// +// WebTarget webResource = baseResource.path("/build") +// .queryParam("t", tag); +// if (command.hasNoCacheEnabled()) { +// webResource = webResource.queryParam("nocache", "true"); +// } +// if (command.hasRemoveEnabled()) { +// webResource = webResource.queryParam("rm", "true"); +// } +// if (command.isQuiet()) { +// webResource = webResource.queryParam("q", "true"); +// } +// +// LOGGER.trace("POST: {}", webResource); +// return webResource +// .request() +// .accept(MediaType.TEXT_PLAIN) +// .post(entity(command.getTarInputStream(), "application/tar"), Response.class).readEntity(InputStream.class); +// +// } + + protected InputStream buildDockerFolderTar(File dockerFolder) { Preconditions.checkArgument(dockerFolder.exists(), "Path %s doesn't exist", dockerFolder); Preconditions.checkArgument(dockerFolder.isDirectory(), @@ -257,7 +242,7 @@ protected File buildDockerFolderTar() { dockerFolderTar = CompressArchiveUtil.archiveTARFiles(dockerFolder, filesToAdd, archiveNameWithOutExtension); - return dockerFolderTar; + return FileUtils.openInputStream(dockerFolderTar); } catch (IOException ex) { FileUtils.deleteQuietly(dockerFolderTar); throw new DockerClientException( diff --git a/src/main/java/com/github/dockerjava/client/command/CommitCommand.java b/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java similarity index 70% rename from src/main/java/com/github/dockerjava/client/command/CommitCommand.java rename to src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java index 73010297..5f0325f0 100644 --- a/src/main/java/com/github/dockerjava/client/command/CommitCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java @@ -1,19 +1,11 @@ -package com.github.dockerjava.client.command; - -import static javax.ws.rs.client.Entity.entity; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; +package com.github.dockerjava.core.command; import org.apache.commons.lang.builder.ToStringBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CommitCmd; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.model.ExposedPorts; import com.github.dockerjava.api.model.Volumes; import com.google.common.base.Preconditions; @@ -23,9 +15,7 @@ * Create a new image from a container's changes. Returns the new image ID. * */ -public class CommitCommand extends AbstrDockerCmd implements CommitCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(CommitCommand.class); +public class CommitCmdImpl extends AbstrDockerCmd implements CommitCmd { private String containerId, repository, tag, message, author; @@ -83,7 +73,8 @@ public class CommitCommand extends AbstrDockerCmd impleme private String workingDir; - public CommitCommand(String containerId) { + public CommitCmdImpl(DockerCmdExec exec, String containerId) { + super(exec); withContainerId(containerId); } @@ -93,7 +84,7 @@ public String getContainerId() { } @Override - public CommitCommand withContainerId(String containerId) { + public CommitCmdImpl withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; @@ -128,81 +119,81 @@ public boolean hasPauseEnabled() { @Override - public CommitCommand withAttachStderr(boolean attachStderr) { + public CommitCmdImpl withAttachStderr(boolean attachStderr) { this.attachStderr = attachStderr; return this; } @Override - public CommitCommand withAttachStderr() { + public CommitCmdImpl withAttachStderr() { return withAttachStderr(true); } @Override - public CommitCommand withAttachStdin(boolean attachStdin) { + public CommitCmdImpl withAttachStdin(boolean attachStdin) { this.attachStdin = attachStdin; return this; } @Override - public CommitCommand withAttachStdin() { + public CommitCmdImpl withAttachStdin() { return withAttachStdin(true); } @Override - public CommitCommand withAttachStdout(boolean attachStdout) { + public CommitCmdImpl withAttachStdout(boolean attachStdout) { this.attachStdout = attachStdout; return this; } @Override - public CommitCommand withAttachStdout() { + public CommitCmdImpl withAttachStdout() { return withAttachStdout(true); } @Override - public CommitCommand withCmd(String... cmd) { + public CommitCmdImpl withCmd(String... cmd) { Preconditions.checkNotNull(cmd, "cmd was not specified"); this.cmd = cmd; return this; } @Override - public CommitCommand withDisableNetwork(boolean disableNetwork) { + public CommitCmdImpl withDisableNetwork(boolean disableNetwork) { this.disableNetwork = disableNetwork; return this; } @Override - public CommitCommand withAuthor(String author) { + public CommitCmdImpl withAuthor(String author) { Preconditions.checkNotNull(author, "author was not specified"); this.author = author; return this; } @Override - public CommitCommand withMessage(String message) { + public CommitCmdImpl withMessage(String message) { Preconditions.checkNotNull(message, "message was not specified"); this.message = message; return this; } @Override - public CommitCommand withTag(String tag) { + public CommitCmdImpl withTag(String tag) { Preconditions.checkNotNull(tag, "tag was not specified"); this.tag = tag; return this; } @Override - public CommitCommand withRepository(String repository) { + public CommitCmdImpl withRepository(String repository) { Preconditions.checkNotNull(repository, "repository was not specified"); this.repository = repository; return this; } @Override - public CommitCommand withPause(boolean pause) { + public CommitCmdImpl withPause(boolean pause) { this.pause = pause; return this; } @@ -213,7 +204,7 @@ public String[] getEnv() { } @Override - public CommitCommand withEnv(String... env) { + public CommitCmdImpl withEnv(String... env) { Preconditions.checkNotNull(env, "env was not specified"); this.env = env; return this; @@ -225,7 +216,7 @@ public ExposedPorts getExposedPorts() { } @Override - public CommitCommand withExposedPorts(ExposedPorts exposedPorts) { + public CommitCmdImpl withExposedPorts(ExposedPorts exposedPorts) { Preconditions.checkNotNull(exposedPorts, "exposedPorts was not specified"); this.exposedPorts = exposedPorts; return this; @@ -237,7 +228,7 @@ public String getHostname() { } @Override - public CommitCommand withHostname(String hostname) { + public CommitCmdImpl withHostname(String hostname) { Preconditions.checkNotNull(hostname, "hostname was not specified"); this.hostname = hostname; return this; @@ -249,7 +240,7 @@ public Integer getMemory() { } @Override - public CommitCommand withMemory(Integer memory) { + public CommitCmdImpl withMemory(Integer memory) { Preconditions.checkNotNull(memory, "memory was not specified"); this.memory = memory; return this; @@ -261,7 +252,7 @@ public Integer getMemorySwap() { } @Override - public CommitCommand withMemorySwap(Integer memorySwap) { + public CommitCmdImpl withMemorySwap(Integer memorySwap) { Preconditions.checkNotNull(memorySwap, "memorySwap was not specified"); this.memorySwap = memorySwap; return this; @@ -273,19 +264,19 @@ public boolean isOpenStdin() { } @Override - public CommitCommand withOpenStdin(boolean openStdin) { + public CommitCmdImpl withOpenStdin(boolean openStdin) { Preconditions.checkNotNull(openStdin, "openStdin was not specified"); this.openStdin = openStdin; return this; } - + @Override public String[] getPortSpecs() { return portSpecs; } @Override - public CommitCommand withPortSpecs(String... portSpecs) { + public CommitCmdImpl withPortSpecs(String... portSpecs) { Preconditions.checkNotNull(portSpecs, "portSpecs was not specified"); this.portSpecs = portSpecs; return this; @@ -297,13 +288,13 @@ public boolean isStdinOnce() { } @Override - public CommitCommand withStdinOnce(boolean stdinOnce) { + public CommitCmdImpl withStdinOnce(boolean stdinOnce) { this.stdinOnce = stdinOnce; return this; } @Override - public CommitCommand withStdinOnce() { + public CommitCmdImpl withStdinOnce() { return withStdinOnce(true); } @@ -313,13 +304,13 @@ public boolean isTty() { } @Override - public CommitCommand withTty(boolean tty) { + public CommitCmdImpl withTty(boolean tty) { this.tty = tty; return this; } @Override - public CommitCommand withTty() { + public CommitCmdImpl withTty() { return withTty(true); } @@ -329,7 +320,7 @@ public String getUser() { } @Override - public CommitCommand withUser(String user) { + public CommitCmdImpl withUser(String user) { Preconditions.checkNotNull(user, "user was not specified"); this.user = user; return this; @@ -341,7 +332,7 @@ public Volumes getVolumes() { } @Override - public CommitCommand withVolumes(Volumes volumes) { + public CommitCmdImpl withVolumes(Volumes volumes) { Preconditions.checkNotNull(volumes, "volumes was not specified"); this.volumes = volumes; return this; @@ -353,7 +344,7 @@ public String getWorkingDir() { } @Override - public CommitCommand withWorkingDir(String workingDir) { + public CommitCmdImpl withWorkingDir(String workingDir) { Preconditions.checkNotNull(workingDir, "workingDir was not specified"); this.workingDir = workingDir; return this; @@ -379,19 +370,21 @@ public String exec() throws NotFoundException { return super.exec(); } - protected String impl() throws DockerException { - - WebTarget webResource = baseResource.path("/commit") - .queryParam("container", containerId) - .queryParam("repo", repository) - .queryParam("tag", tag) - .queryParam("m", message) - .queryParam("author", author) - .queryParam("pause", pause ? "1" : "0"); - - LOGGER.trace("POST: {}", webResource); - ObjectNode objectNode = webResource.request().accept("application/vnd.docker.raw-stream").post(entity(this, MediaType.APPLICATION_JSON), ObjectNode.class); - return objectNode.get("Id").asText(); - - } +// protected String impl() throws DockerException { +// +// CommitCmd command = this; +// +// WebTarget webResource = baseResource.path("/commit") +// .queryParam("container", command.getContainerId()) +// .queryParam("repo", command.getRepository()) +// .queryParam("tag", command.getTag()) +// .queryParam("m", command.getMessage()) +// .queryParam("author", command.getAuthor()) +// .queryParam("pause", command.hasPauseEnabled() ? "1" : "0"); +// +// LOGGER.trace("POST: {}", webResource); +// ObjectNode objectNode = webResource.request().accept("application/vnd.docker.raw-stream").post(entity(this, MediaType.APPLICATION_JSON), ObjectNode.class); +// return objectNode.get("Id").asText(); +// +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCommand.java b/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java similarity index 56% rename from src/main/java/com/github/dockerjava/client/command/ContainerDiffCommand.java rename to src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java index 3055f9df..40a99eaf 100644 --- a/src/main/java/com/github/dockerjava/client/command/ContainerDiffCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java @@ -1,18 +1,12 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import java.util.List; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.InternalServerErrorException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.ContainerDiffCmd; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.model.ChangeLog; import com.google.common.base.Preconditions; @@ -23,13 +17,12 @@ * @param containerId - Id of the container * */ -public class ContainerDiffCommand extends AbstrDockerCmd> implements ContainerDiffCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(ContainerDiffCommand.class); +public class ContainerDiffCmdImpl extends AbstrDockerCmd> implements ContainerDiffCmd { private String containerId; - public ContainerDiffCommand(String containerId) { + public ContainerDiffCmdImpl(DockerCmdExec> exec, String containerId) { + super(exec); withContainerId(containerId); } @@ -39,7 +32,7 @@ public String getContainerId() { } @Override - public ContainerDiffCommand withContainerId(String containerId) { + public ContainerDiffCmdImpl withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; @@ -60,11 +53,13 @@ public List exec() throws NotFoundException { return super.exec(); } - protected List impl() throws DockerException { - WebTarget webResource = baseResource.path("/containers/{id}/changes").resolveTemplate("id", containerId); - - LOGGER.trace("GET: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { - }); - } +// protected List impl() throws DockerException { +// ContainerDiffCmd command = this; +// +// WebTarget webResource = baseResource.path("/containers/{id}/changes").resolveTemplate("id", command.getContainerId()); +// +// LOGGER.trace("GET: {}", webResource); +// return webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { +// }); +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCommand.java b/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java similarity index 55% rename from src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCommand.java rename to src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java index b65eb58a..d0515952 100644 --- a/src/main/java/com/github/dockerjava/client/command/CopyFileFromContainerCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java @@ -1,34 +1,21 @@ -package com.github.dockerjava.client.command; - -import static javax.ws.rs.client.Entity.entity; +package com.github.dockerjava.core.command; import java.io.InputStream; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import com.fasterxml.jackson.annotation.JsonProperty; - import org.apache.commons.lang.builder.ToStringBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.github.dockerjava.api.DockerException; +import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CopyFileFromContainerCmd; +import com.github.dockerjava.api.command.DockerCmdExec; import com.google.common.base.Preconditions; - /** * * Copy files or folders from a container. * */ -public class CopyFileFromContainerCommand extends AbstrDockerCmd implements CopyFileFromContainerCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(CopyFileFromContainerCommand.class); +public class CopyFileFromContainerCmdImpl extends AbstrDockerCmd implements CopyFileFromContainerCmd { private String containerId; @@ -38,7 +25,8 @@ public class CopyFileFromContainerCommand extends AbstrDockerCmd exec, String containerId, String resource) { + super(exec); withContainerId(containerId); withResource(resource); } @@ -54,14 +42,14 @@ public String getResource() { } @Override - public CopyFileFromContainerCommand withContainerId(String containerId) { + public CopyFileFromContainerCmdImpl withContainerId(String containerId) { Preconditions.checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } @Override - public CopyFileFromContainerCommand withResource(String resource) { + public CopyFileFromContainerCmdImpl withResource(String resource) { Preconditions.checkNotNull(resource, "resource was not specified"); this.resource = resource; return this; @@ -73,7 +61,7 @@ public String getHostPath() { } @Override - public CopyFileFromContainerCommand withHostPath(String hostPath) { + public CopyFileFromContainerCmdImpl withHostPath(String hostPath) { Preconditions.checkNotNull(hostPath, "hostPath was not specified"); this.hostPath = hostPath; return this; @@ -96,17 +84,17 @@ public InputStream exec() throws NotFoundException { return super.exec(); } - protected InputStream impl() throws DockerException { - - WebTarget webResource = - baseResource.path("/containers/{id}/copy").resolveTemplate("id", containerId); - - LOGGER.trace("POST: " + webResource.toString()); - Invocation.Builder builder = - webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE); - - return builder.post(entity(this, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); - } +// protected InputStream impl() throws DockerException { +// +// CopyFileFromContainerCmd command = this; +// +// WebTarget webResource = +// baseResource.path("/containers/{id}/copy").resolveTemplate("id", command.getContainerId()); +// +// LOGGER.trace("POST: " + webResource.toString()); +// +// return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(entity(command, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/CreateContainerCommand.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java similarity index 73% rename from src/main/java/com/github/dockerjava/client/command/CreateContainerCommand.java rename to src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index 5030ab48..65e7cb61 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateContainerCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -1,13 +1,6 @@ -package com.github.dockerjava.client.command; - -import static javax.ws.rs.client.Entity.entity; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; +package com.github.dockerjava.core.command; import org.apache.commons.lang.builder.ToStringBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @@ -15,6 +8,7 @@ import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.ExposedPorts; import com.github.dockerjava.api.model.Volume; @@ -26,10 +20,8 @@ * Creates a new container. * */ -public class CreateContainerCommand extends AbstrDockerCmd implements CreateContainerCmd { +public class CreateContainerCmdImpl extends AbstrDockerCmd implements CreateContainerCmd { - private static final Logger LOGGER = LoggerFactory.getLogger(CreateContainerCommand.class); - private String name; @JsonProperty("Hostname") private String hostName = ""; @@ -53,13 +45,14 @@ public class CreateContainerCommand extends AbstrDockerCmd exec, String image) { + super(exec); Preconditions.checkNotNull(image, "image was not specified"); withImage(image); } @Override - public CreateContainerCommand withName(String name) { + public CreateContainerCmdImpl withName(String name) { Preconditions.checkNotNull(name, "name was not specified"); this.name = name; return this; @@ -71,7 +64,7 @@ public String getName() { } @Override - public CreateContainerCommand withExposedPorts(ExposedPort... exposedPorts) { + public CreateContainerCmdImpl withExposedPorts(ExposedPort... exposedPorts) { this.exposedPorts = new ExposedPorts(exposedPorts); return this; } @@ -94,7 +87,7 @@ public String getWorkingDir() { } @Override - public CreateContainerCommand withWorkingDir(String workingDir) { + public CreateContainerCmdImpl withWorkingDir(String workingDir) { this.workingDir = workingDir; return this; } @@ -106,13 +99,13 @@ public String getHostName() { } @Override - public CreateContainerCommand withDisableNetwork(boolean disableNetwork) { + public CreateContainerCmdImpl withDisableNetwork(boolean disableNetwork) { this.disableNetwork = disableNetwork; return this; } @Override - public CreateContainerCommand withHostName(String hostName) { + public CreateContainerCmdImpl withHostName(String hostName) { this.hostName = hostName; return this; } @@ -123,7 +116,7 @@ public String[] getPortSpecs() { } @Override - public CreateContainerCommand withPortSpecs(String... portSpecs) { + public CreateContainerCmdImpl withPortSpecs(String... portSpecs) { this.portSpecs = portSpecs; return this; } @@ -134,7 +127,7 @@ public String getUser() { } @Override - public CreateContainerCommand withUser(String user) { + public CreateContainerCmdImpl withUser(String user) { this.user = user; return this; } @@ -145,7 +138,7 @@ public boolean isTty() { } @Override - public CreateContainerCommand withTty(boolean tty) { + public CreateContainerCmdImpl withTty(boolean tty) { this.tty = tty; return this; } @@ -156,7 +149,7 @@ public boolean isStdinOpen() { } @Override - public CreateContainerCommand withStdinOpen(boolean stdinOpen) { + public CreateContainerCmdImpl withStdinOpen(boolean stdinOpen) { this.stdinOpen = stdinOpen; return this; } @@ -167,7 +160,7 @@ public boolean isStdInOnce() { } @Override - public CreateContainerCommand withStdInOnce(boolean stdInOnce) { + public CreateContainerCmdImpl withStdInOnce(boolean stdInOnce) { this.stdInOnce = stdInOnce; return this; } @@ -178,7 +171,7 @@ public long getMemoryLimit() { } @Override - public CreateContainerCommand withMemoryLimit(long memoryLimit) { + public CreateContainerCmdImpl withMemoryLimit(long memoryLimit) { this.memoryLimit = memoryLimit; return this; } @@ -189,7 +182,7 @@ public long getMemorySwap() { } @Override - public CreateContainerCommand withMemorySwap(long memorySwap) { + public CreateContainerCmdImpl withMemorySwap(long memorySwap) { this.memorySwap = memorySwap; return this; } @@ -201,7 +194,7 @@ public boolean isAttachStdin() { } @Override - public CreateContainerCommand withAttachStdin(boolean attachStdin) { + public CreateContainerCmdImpl withAttachStdin(boolean attachStdin) { this.attachStdin = attachStdin; return this; } @@ -212,7 +205,7 @@ public boolean isAttachStdout() { } @Override - public CreateContainerCommand withAttachStdout(boolean attachStdout) { + public CreateContainerCmdImpl withAttachStdout(boolean attachStdout) { this.attachStdout = attachStdout; return this; } @@ -223,7 +216,7 @@ public boolean isAttachStderr() { } @Override - public CreateContainerCommand withAttachStderr(boolean attachStderr) { + public CreateContainerCmdImpl withAttachStderr(boolean attachStderr) { this.attachStderr = attachStderr; return this; } @@ -234,7 +227,7 @@ public String[] getEnv() { } @Override - public CreateContainerCommand withEnv(String... env) { + public CreateContainerCmdImpl withEnv(String... env) { this.env = env; return this; } @@ -245,7 +238,7 @@ public String[] getCmd() { } @Override - public CreateContainerCommand withCmd(String... cmd) { + public CreateContainerCmdImpl withCmd(String... cmd) { this.cmd = cmd; return this; } @@ -256,7 +249,7 @@ public String[] getDns() { } @Override - public CreateContainerCommand withDns(String... dns) { + public CreateContainerCmdImpl withDns(String... dns) { this.dns = dns; return this; } @@ -267,7 +260,7 @@ public String getImage() { } @Override - public CreateContainerCommand withImage(String image) { + public CreateContainerCmdImpl withImage(String image) { this.image = image; return this; } @@ -279,7 +272,7 @@ public Volume[] getVolumes() { } @Override - public CreateContainerCommand withVolumes(Volume... volumes) { + public CreateContainerCmdImpl withVolumes(Volume... volumes) { this.volumes = new Volumes(volumes); return this; } @@ -290,7 +283,7 @@ public String[] getVolumesFrom() { } @Override - public CreateContainerCommand withVolumesFrom(String... volumesFrom) { + public CreateContainerCmdImpl withVolumesFrom(String... volumesFrom) { this.volumesFrom = volumesFrom; return this; } @@ -312,16 +305,15 @@ public CreateContainerResponse exec() throws NotFoundException, ConflictExceptio return super.exec(); } - protected CreateContainerResponse impl() { - WebTarget webResource = baseResource.path("/containers/create"); - - if (name != null) { - webResource = webResource.queryParam("name", name); - } - - LOGGER.trace("POST: {} ", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON) - .post(entity(this, MediaType.APPLICATION_JSON), CreateContainerResponse.class); - } +// protected CreateContainerResponse impl() { +// WebTarget webResource = baseResource.path("/containers/create"); +// +// if (name != null) { +// webResource = webResource.queryParam("name", name); +// } +// +// LOGGER.trace("POST: {} ", webResource); +// return webResource.request().accept(MediaType.APPLICATION_JSON) +// .post(entity(this, MediaType.APPLICATION_JSON), CreateContainerResponse.class); } diff --git a/src/main/java/com/github/dockerjava/client/command/CreateImageCommand.java b/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java similarity index 57% rename from src/main/java/com/github/dockerjava/client/command/CreateImageCommand.java rename to src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java index 6c4341ec..c3d1bfb1 100644 --- a/src/main/java/com/github/dockerjava/client/command/CreateImageCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java @@ -1,35 +1,29 @@ -package com.github.dockerjava.client.command; - -import static javax.ws.rs.client.Entity.entity; +package com.github.dockerjava.core.command; import java.io.InputStream; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - import org.apache.commons.lang.builder.ToStringBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.github.dockerjava.api.command.CreateImageCmd; import com.github.dockerjava.api.command.CreateImageResponse; +import com.github.dockerjava.api.command.DockerCmdExec; import com.google.common.base.Preconditions; /** * Create an image by importing the given stream of a tar file. */ -public class CreateImageCommand extends AbstrDockerCmd implements CreateImageCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(CreateImageCommand.class); +public class CreateImageCmdImpl extends AbstrDockerCmd implements CreateImageCmd { private String repository, tag; + private InputStream imageStream; /** * @param repository the repository to import to * @param imageStream the InputStream of the tar file */ - public CreateImageCommand(String repository, InputStream imageStream) { + public CreateImageCmdImpl(DockerCmdExec exec, String repository, InputStream imageStream) { + super(exec); withRepository(repository); withImageStream(imageStream); } @@ -43,12 +37,17 @@ public String getRepository() { public String getTag() { return tag; } + + @Override + public InputStream getImageStream() { + return imageStream; + } /** * @param repository the repository to import to */ @Override - public CreateImageCommand withRepository(String repository) { + public CreateImageCmdImpl withRepository(String repository) { Preconditions.checkNotNull(repository, "repository was not specified"); this.repository = repository; return this; @@ -58,7 +57,7 @@ public CreateImageCommand withRepository(String repository) { * @param imageStream the InputStream of the tar file */ @Override - public CreateImageCommand withImageStream(InputStream imageStream) { + public CreateImageCmdImpl withImageStream(InputStream imageStream) { Preconditions .checkNotNull(imageStream, "imageStream was not specified"); this.imageStream = imageStream; @@ -69,7 +68,7 @@ public CreateImageCommand withImageStream(InputStream imageStream) { * @param tag any tag for this image */ @Override - public CreateImageCommand withTag(String tag) { + public CreateImageCmdImpl withTag(String tag) { Preconditions.checkNotNull(tag, "tag was not specified"); this.tag = tag; return this; @@ -83,17 +82,17 @@ public String toString() { .toString(); } - protected CreateImageResponse impl() { - - WebTarget webResource = baseResource - .path("/images/create") - .queryParam("repo", repository) - .queryParam("tag", tag) - .queryParam("fromSrc", "-"); - - LOGGER.trace("POST: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .post(entity(imageStream, MediaType.APPLICATION_OCTET_STREAM), CreateImageResponse.class); - - } +// protected CreateImageResponse impl() { +// +// WebTarget webResource = baseResource +// .path("/images/create") +// .queryParam("repo", repository) +// .queryParam("tag", tag) +// .queryParam("fromSrc", "-"); +// +// LOGGER.trace("POST: {}", webResource); +// return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) +// .post(entity(imageStream, MediaType.APPLICATION_OCTET_STREAM), CreateImageResponse.class); +// +// } } diff --git a/src/main/java/com/github/dockerjava/core/command/InfoCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/InfoCmdImpl.java new file mode 100644 index 00000000..4493db0d --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/InfoCmdImpl.java @@ -0,0 +1,27 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.command.DockerCmdExec; +import com.github.dockerjava.api.command.InfoCmd; +import com.github.dockerjava.api.model.Info; + +/** + * Return Docker server info + */ +public class InfoCmdImpl extends AbstrDockerCmd implements InfoCmd { + + public InfoCmdImpl(DockerCmdExec exec) { + super(exec); + } + + @Override + public String toString() { + return "info"; + } + +// protected Info impl() throws DockerException { +// WebTarget webResource = baseResource.path("/info"); +// +// LOGGER.trace("GET: {}", webResource); +// return webResource.request().accept(MediaType.APPLICATION_JSON).get(Info.class); +// } +} diff --git a/src/main/java/com/github/dockerjava/client/command/InspectContainerCommand.java b/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java similarity index 52% rename from src/main/java/com/github/dockerjava/client/command/InspectContainerCommand.java rename to src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java index 9b0b8a34..20e47f6d 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectContainerCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java @@ -1,13 +1,7 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectContainerResponse; import com.google.common.base.Preconditions; @@ -15,13 +9,12 @@ /** * Inspect the details of a container. */ -public class InspectContainerCommand extends AbstrDockerCmd implements InspectContainerCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(InspectContainerCommand.class); +public class InspectContainerCmdImpl extends AbstrDockerCmd implements InspectContainerCmd { private String containerId; - public InspectContainerCommand(String containerId) { + public InspectContainerCmdImpl(DockerCmdExec exec, String containerId) { + super(exec); withContainerId(containerId); } @@ -50,10 +43,10 @@ public InspectContainerResponse exec() throws NotFoundException { return super.exec(); } - protected InspectContainerResponse impl() throws DockerException { - WebTarget webResource = baseResource.path(String.format("/containers/%s/json", containerId)); - - LOGGER.trace("GET: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectContainerResponse.class); - } +// protected InspectContainerResponse impl() throws DockerException { +// WebTarget webResource = baseResource.path(String.format("/containers/%s/json", containerId)); +// +// LOGGER.trace("GET: {}", webResource); +// return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectContainerResponse.class); +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/InspectImageCommand.java b/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java similarity index 53% rename from src/main/java/com/github/dockerjava/client/command/InspectImageCommand.java rename to src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java index 085e745d..f0e9457c 100644 --- a/src/main/java/com/github/dockerjava/client/command/InspectImageCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java @@ -1,12 +1,7 @@ -package com.github.dockerjava.client.command; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +package com.github.dockerjava.core.command; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.InspectImageCmd; import com.github.dockerjava.api.command.InspectImageResponse; import com.google.common.base.Preconditions; @@ -14,13 +9,12 @@ /** * Inspect the details of an image. */ -public class InspectImageCommand extends AbstrDockerCmd implements InspectImageCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(InspectImageCommand.class); +public class InspectImageCmdImpl extends AbstrDockerCmd implements InspectImageCmd { private String imageId; - public InspectImageCommand(String imageId) { + public InspectImageCmdImpl(DockerCmdExec exec,String imageId) { + super(exec); withImageId(imageId); } @@ -49,10 +43,10 @@ public InspectImageResponse exec() throws NotFoundException { return super.exec(); } - protected InspectImageResponse impl() { - WebTarget webResource = baseResource.path("/images/{id}/json").resolveTemplate("id", imageId); - - LOGGER.trace("GET: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectImageResponse.class); - } +// protected InspectImageResponse impl() { +// WebTarget webResource = baseResource.path("/images/{id}/json").resolveTemplate("id", imageId); +// +// LOGGER.trace("GET: {}", webResource); +// return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectImageResponse.class); +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/KillContainerCommand.java b/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java similarity index 52% rename from src/main/java/com/github/dockerjava/client/command/KillContainerCommand.java rename to src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java index 9ec446d4..4ed15abf 100644 --- a/src/main/java/com/github/dockerjava/client/command/KillContainerCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java @@ -1,28 +1,19 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; -import static javax.ws.rs.client.Entity.entity; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.KillContainerCmd; import com.google.common.base.Preconditions; /** * Kill a running container. */ -public class KillContainerCommand extends AbstrDockerCmd implements KillContainerCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(KillContainerCommand.class); +public class KillContainerCmdImpl extends AbstrDockerCmd implements KillContainerCmd { private String containerId, signal; - public KillContainerCommand(String containerId) { + public KillContainerCmdImpl(DockerCmdExec exec, String containerId) { + super(exec); withContainerId(containerId); } @@ -63,16 +54,16 @@ public Void exec() throws NotFoundException { return super.exec(); } - protected Void impl() throws DockerException { - WebTarget webResource = baseResource.path("/containers/{id}/kill").resolveTemplate("id", containerId); - - if(signal != null) { - webResource = webResource.queryParam("signal", signal); - } - - LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON)); - - return null; - } +// protected Void impl() throws DockerException { +// WebTarget webResource = baseResource.path("/containers/{id}/kill").resolveTemplate("id", containerId); +// +// if(signal != null) { +// webResource = webResource.queryParam("signal", signal); +// } +// +// LOGGER.trace("POST: {}", webResource); +// webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON)); +// +// return null; +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/ListContainersCommand.java b/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java similarity index 66% rename from src/main/java/com/github/dockerjava/client/command/ListContainersCommand.java rename to src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java index 2261fc70..cf91ef22 100644 --- a/src/main/java/com/github/dockerjava/client/command/ListContainersCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java @@ -1,19 +1,12 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import java.util.List; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.ListContainersCmd; import com.github.dockerjava.api.model.Container; import com.google.common.base.Preconditions; -import javax.ws.rs.client.WebTarget; - /** * List containers * @@ -24,13 +17,17 @@ * @param beforeId - Show only containers created before Id, include non-running ones. * */ -public class ListContainersCommand extends AbstrDockerCmd> implements ListContainersCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(ListContainersCommand.class); +public class ListContainersCmdImpl extends AbstrDockerCmd> implements ListContainersCmd { private int limit = -1; + private boolean showSize, showAll = false; - String sinceId, beforeId; + + private String sinceId, beforeId; + + public ListContainersCmdImpl(DockerCmdExec> exec) { + super(exec); + } @Override public int getLimit() { @@ -101,22 +98,22 @@ public String toString() { .toString(); } - protected List impl() { - WebTarget webResource = baseResource.path("/containers/json") - .queryParam("all", showAll ? "1" : "0") - .queryParam("since", sinceId) - .queryParam("before", beforeId) - .queryParam("size", showSize ? "1" : "0"); - - if (limit >= 0) { - webResource = webResource.queryParam("limit", String.valueOf(limit)); - } - - LOGGER.trace("GET: {}", webResource); - List containers = webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { - }); - LOGGER.trace("Response: {}", containers); - - return containers; - } +// protected List impl() { +// WebTarget webResource = baseResource.path("/containers/json") +// .queryParam("all", showAll ? "1" : "0") +// .queryParam("since", sinceId) +// .queryParam("before", beforeId) +// .queryParam("size", showSize ? "1" : "0"); +// +// if (limit >= 0) { +// webResource = webResource.queryParam("limit", String.valueOf(limit)); +// } +// +// LOGGER.trace("GET: {}", webResource); +// List containers = webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { +// }); +// LOGGER.trace("Response: {}", containers); +// +// return containers; +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/ListImagesCommand.java b/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java similarity index 56% rename from src/main/java/com/github/dockerjava/client/command/ListImagesCommand.java rename to src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java index f510e5cc..71a27b92 100644 --- a/src/main/java/com/github/dockerjava/client/command/ListImagesCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java @@ -1,14 +1,8 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import java.util.List; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.ListImagesCmd; import com.github.dockerjava.api.model.Image; import com.google.common.base.Preconditions; @@ -19,12 +13,15 @@ * @param showAll - Show all images (by default filter out the intermediate images used to build) * @param filter - TODO: undocumented in docker remote api reference */ -public class ListImagesCommand extends AbstrDockerCmd> implements ListImagesCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(ListImagesCommand.class); +public class ListImagesCmdImpl extends AbstrDockerCmd> implements ListImagesCmd { private String filter; + private boolean showAll = false; + + public ListImagesCmdImpl(DockerCmdExec> exec) { + super(exec); + } @Override public String getFilter() { @@ -57,17 +54,17 @@ public String toString() { .toString(); } - protected List impl() { - - WebTarget webResource = baseResource - .path("/images/json") - .queryParam("filter", filter) - .queryParam("all", showAll ? "1" : "0"); - - LOGGER.trace("GET: {}", webResource); - List images = webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { - }); - LOGGER.trace("Response: {}", images); - return images; - } +// protected List impl() { +// +// WebTarget webResource = baseResource +// .path("/images/json") +// .queryParam("filter", filter) +// .queryParam("all", showAll ? "1" : "0"); +// +// LOGGER.trace("GET: {}", webResource); +// List images = webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { +// }); +// LOGGER.trace("Response: {}", images); +// return images; +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/LogContainerCommand.java b/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java similarity index 71% rename from src/main/java/com/github/dockerjava/client/command/LogContainerCommand.java rename to src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java index 7d7e8027..14294771 100644 --- a/src/main/java/com/github/dockerjava/client/command/LogContainerCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java @@ -1,16 +1,9 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import java.io.InputStream; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.LogContainerCmd; import com.google.common.base.Preconditions; @@ -29,10 +22,7 @@ * @param tail * - `all` or ``, Output specified number of lines at the end of logs */ -public class LogContainerCommand extends AbstrDockerCmd implements LogContainerCmd { - - private static final Logger LOGGER = LoggerFactory - .getLogger(LogContainerCommand.class); +public class LogContainerCmdImpl extends AbstrDockerCmd implements LogContainerCmd { private String containerId; @@ -40,7 +30,8 @@ public class LogContainerCommand extends AbstrDockerCmd exec, String containerId) { + super(exec); withContainerId(containerId); } @@ -156,17 +147,17 @@ public InputStream exec() throws NotFoundException { } - protected InputStream impl() throws DockerException { - - WebTarget webResource = baseResource.path("/containers/{id}/logs") - .resolveTemplate("id", containerId) - .queryParam("timestamps", timestamps ? "1" : "0") - .queryParam("stdout", stdout ? "1" : "0") - .queryParam("stderr", stderr ? "1" : "0") - .queryParam("follow", followStream ? "1" : "0") - .queryParam("tail", tail < 0 ? "all" : "" + tail); - - LOGGER.trace("GET: {}", webResource); - return webResource.request().get(Response.class).readEntity(InputStream.class); - } +// protected InputStream impl() throws DockerException { +// +// WebTarget webResource = baseResource.path("/containers/{id}/logs") +// .resolveTemplate("id", containerId) +// .queryParam("timestamps", timestamps ? "1" : "0") +// .queryParam("stdout", stdout ? "1" : "0") +// .queryParam("stderr", stderr ? "1" : "0") +// .queryParam("follow", followStream ? "1" : "0") +// .queryParam("tail", tail < 0 ? "all" : "" + tail); +// +// LOGGER.trace("GET: {}", webResource); +// return webResource.request().get(Response.class).readEntity(InputStream.class); +// } } diff --git a/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java new file mode 100644 index 00000000..cf5bb8ea --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java @@ -0,0 +1,61 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.DockerCmdExec; +import com.github.dockerjava.api.command.PauseContainerCmd; +import com.google.common.base.Preconditions; + +/** + * Pause a container. + * + * @param containerId - Id of the container + * + */ +public class PauseContainerCmdImpl extends AbstrDockerCmd implements PauseContainerCmd { + + private String containerId; + + public PauseContainerCmdImpl(DockerCmdExec exec, String containerId) { + super(exec); + withContainerId(containerId); + } + + @Override + public String getContainerId() { + return containerId; + } + + @Override + public PauseContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + @Override + public String toString() { + return new StringBuilder("pause ") + .append(containerId) + .toString(); + } + + /** + * @throws NotFoundException No such container + */ + @Override + public Void exec() throws NotFoundException { + return super.exec(); + } + +// protected Void impl() throws DockerException { +// WebTarget webResource = baseResource.path("/containers/{id}/pause") +// .resolveTemplate("id", containerId); +// +// LOGGER.trace("POST: {}", webResource); +// webResource.request() +// .accept(MediaType.APPLICATION_JSON) +// .post(entity(null, MediaType.APPLICATION_JSON), Response.class); +// +// return null; +// } +} diff --git a/src/main/java/com/github/dockerjava/core/command/PingCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PingCmdImpl.java new file mode 100644 index 00000000..4f7d0f48 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/PingCmdImpl.java @@ -0,0 +1,24 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.command.DockerCmdExec; +import com.github.dockerjava.api.command.PingCmd; + +/** + * Ping the Docker server + * + */ +public class PingCmdImpl extends AbstrDockerCmd implements PingCmd { + + public PingCmdImpl(DockerCmdExec exec) { + super(exec); + } + +// protected Void impl() { +// WebTarget webResource = baseResource.path("/_ping"); +// +// LOGGER.trace("GET: {}", webResource); +// webResource.request().get(Response.class); +// +// return null; +// } +} diff --git a/src/main/java/com/github/dockerjava/client/command/PullImageCommand.java b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java similarity index 55% rename from src/main/java/com/github/dockerjava/client/command/PullImageCommand.java rename to src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java index d33bd2a9..41e0e85c 100644 --- a/src/main/java/com/github/dockerjava/client/command/PullImageCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java @@ -1,16 +1,8 @@ -package com.github.dockerjava.client.command; - -import static javax.ws.rs.client.Entity.entity; +package com.github.dockerjava.core.command; import java.io.InputStream; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.PullImageCmd; import com.google.common.base.Preconditions; @@ -19,13 +11,12 @@ * Pull image from repository. * */ -public class PullImageCommand extends AbstrDockerCmd implements PullImageCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(PullImageCommand.class); +public class PullImageCmdImpl extends AbstrDockerCmd implements PullImageCmd { private String repository, tag, registry; - public PullImageCommand(String repository) { + public PullImageCmdImpl(DockerCmdExec exec, String repository) { + super(exec); withRepository(repository); } @@ -73,16 +64,16 @@ public String toString() { .toString(); } - protected InputStream impl() { - - WebTarget webResource = baseResource.path("/images/create") - .queryParam("tag", tag) - .queryParam("fromImage", repository) - .queryParam("registry", registry); - - LOGGER.trace("POST: {}", webResource); - return webResource.request() - .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .post(entity(Response.class, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); - } +// protected InputStream impl() { +// +// WebTarget webResource = baseResource.path("/images/create") +// .queryParam("tag", tag) +// .queryParam("fromImage", repository) +// .queryParam("registry", registry); +// +// LOGGER.trace("POST: {}", webResource); +// return webResource.request() +// .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) +// .post(entity(Response.class, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); +// } } diff --git a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java new file mode 100644 index 00000000..63098637 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java @@ -0,0 +1,69 @@ +package com.github.dockerjava.core.command; + +import java.io.InputStream; + +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.DockerCmdExec; +import com.github.dockerjava.api.command.PushImageCmd; +import com.google.common.base.Preconditions; + +/** + * 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 class PushImageCmdImpl extends AbstrAuthCfgDockerCmd implements PushImageCmd { + + private String name; + + public PushImageCmdImpl(DockerCmdExec exec, String name) { + super(exec); + withName(name); + } + + @Override + public String getName() { + return name; + } + + /** + * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. + */ + @Override + public PushImageCmd withName(String name) { + Preconditions.checkNotNull(name, "name was not specified"); + this.name = name; + return this; + } + + @Override + public String toString() { + return new StringBuilder("push ") + .append(name) + .toString(); + } + + /** + * @throws NotFoundException No such image + */ + @Override + public InputStream exec() throws NotFoundException { + return super.exec(); + } + +// protected InputStream impl() { +// WebTarget webResource = baseResource.path("/images/" + name(name) + "/push"); +// +// final String registryAuth = registryAuth(); +// LOGGER.trace("POST: {}", webResource); +// return webResource +// .request() +// .header("X-Registry-Auth", registryAuth) +// .accept(MediaType.APPLICATION_JSON) +// .post(entity(Response.class, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); +// } +// +// private String name(String name) { +// return name.contains("/") ? name : authConfig.getUsername(); +// } +} diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCommand.java b/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java similarity index 60% rename from src/main/java/com/github/dockerjava/client/command/RemoveContainerCommand.java rename to src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java index 917f6582..258938bc 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveContainerCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java @@ -1,14 +1,7 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.RemoveContainerCmd; import com.google.common.base.Preconditions; @@ -18,16 +11,14 @@ * @param removeVolumes - true or false, Remove the volumes associated to the container. Defaults to false * @param force - true or false, Removes the container even if it was running. Defaults to false */ -public class RemoveContainerCommand extends AbstrDockerCmd implements RemoveContainerCmd { - - private static final Logger LOGGER = LoggerFactory - .getLogger(RemoveContainerCommand.class); +public class RemoveContainerCmdImpl extends AbstrDockerCmd implements RemoveContainerCmd { private String containerId; private boolean removeVolumes, force; - public RemoveContainerCommand(String containerId) { + public RemoveContainerCmdImpl(DockerCmdExec exec, String containerId) { + super(exec); withContainerId(containerId); } @@ -86,17 +77,17 @@ public Void exec() throws NotFoundException { return super.exec(); } - protected Void impl() throws DockerException { - Preconditions.checkState(!StringUtils.isEmpty(containerId), "Container ID can't be empty"); - - WebTarget webResource = baseResource.path("/containers/" + containerId) - .queryParam("v", removeVolumes ? "1" : "0") - .queryParam("force", force ? "1" : "0"); - - LOGGER.trace("DELETE: {}", webResource); - String response = webResource.request().accept(MediaType.APPLICATION_JSON).delete(String.class); - LOGGER.trace("Response: {}", response); - - return null; - } +// protected Void impl() throws DockerException { +// Preconditions.checkState(!StringUtils.isEmpty(containerId), "Container ID can't be empty"); +// +// WebTarget webResource = baseResource.path("/containers/" + containerId) +// .queryParam("v", removeVolumes ? "1" : "0") +// .queryParam("force", force ? "1" : "0"); +// +// LOGGER.trace("DELETE: {}", webResource); +// String response = webResource.request().accept(MediaType.APPLICATION_JSON).delete(String.class); +// LOGGER.trace("Response: {}", response); +// +// return null; +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/RemoveImageCommand.java b/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java similarity index 60% rename from src/main/java/com/github/dockerjava/client/command/RemoveImageCommand.java rename to src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java index da54c4c6..caf88bd7 100644 --- a/src/main/java/com/github/dockerjava/client/command/RemoveImageCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java @@ -1,31 +1,23 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.RemoveImageCmd; import com.google.common.base.Preconditions; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; - /** * * Remove an image, deleting any tags it might have. * */ -public class RemoveImageCommand extends AbstrDockerCmd implements RemoveImageCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(RemoveImageCommand.class); +public class RemoveImageCmdImpl extends AbstrDockerCmd implements RemoveImageCmd { private String imageId; private boolean force, noPrune; - public RemoveImageCommand(String imageId) { + public RemoveImageCmdImpl(DockerCmdExec exec, String imageId) { + super(exec); withImageId(imageId); } @@ -85,16 +77,16 @@ public Void exec() throws NotFoundException { return super.exec(); } - protected Void impl() throws DockerException { - Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty"); - - WebTarget webResource = baseResource.path("/images/" + imageId) - .queryParam("force", force ? "1" : "0") - .queryParam("noprune", noPrune ? "1" : "0"); - - LOGGER.trace("DELETE: {}", webResource); - webResource.request().delete(Response.class); - - return null; - } +// protected Void impl() throws DockerException { +// Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty"); +// +// WebTarget webResource = baseResource.path("/images/" + imageId) +// .queryParam("force", force ? "1" : "0") +// .queryParam("noprune", noPrune ? "1" : "0"); +// +// LOGGER.trace("DELETE: {}", webResource); +// webResource.request().delete(Response.class); +// +// return null; +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/RestartContainerCommand.java b/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java similarity index 58% rename from src/main/java/com/github/dockerjava/client/command/RestartContainerCommand.java rename to src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java index b34cd9a0..84a84622 100644 --- a/src/main/java/com/github/dockerjava/client/command/RestartContainerCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java @@ -1,15 +1,7 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; -import static javax.ws.rs.client.Entity.entity; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.RestartContainerCmd; import com.google.common.base.Preconditions; @@ -19,15 +11,14 @@ * @param timeout - Timeout in seconds before killing the container. Defaults to 10 seconds. * */ -public class RestartContainerCommand extends AbstrDockerCmd implements RestartContainerCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(RestartContainerCommand.class); +public class RestartContainerCmdImpl extends AbstrDockerCmd implements RestartContainerCmd { private String containerId; private int timeout = 10; - public RestartContainerCommand(String containerId) { + public RestartContainerCmdImpl(DockerCmdExec exec, String containerId) { + super(exec); withContainerId(containerId); } @@ -71,14 +62,14 @@ public Void exec() throws NotFoundException { return super.exec(); } - protected Void impl() throws DockerException { - WebTarget webResource = baseResource.path("/containers/{id}/restart") - .resolveTemplate("id", containerId) - .queryParam("t", String.valueOf(timeout)); - - LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON_TYPE)); - - return null; - } +// protected Void impl() throws DockerException { +// WebTarget webResource = baseResource.path("/containers/{id}/restart") +// .resolveTemplate("id", containerId) +// .queryParam("t", String.valueOf(timeout)); +// +// LOGGER.trace("POST: {}", webResource); +// webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON_TYPE)); +// +// return null; +// } } diff --git a/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java new file mode 100644 index 00000000..f378c875 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java @@ -0,0 +1,52 @@ +package com.github.dockerjava.core.command; + +import java.util.List; + +import com.github.dockerjava.api.command.DockerCmdExec; +import com.github.dockerjava.api.command.SearchImagesCmd; +import com.github.dockerjava.api.model.SearchItem; +import com.google.common.base.Preconditions; + +/** + * Search images + * + * @param term - search term + * + */ +public class SearchImagesCmdImpl extends AbstrDockerCmd> implements SearchImagesCmd { + + private String term; + + public SearchImagesCmdImpl(DockerCmdExec> exec, String term) { + super(exec); + withTerm(term); + } + + @Override + public String getTerm() { + return term; + } + + @Override + public SearchImagesCmd withTerm(String term) { + Preconditions.checkNotNull(term, "term was not specified"); + this.term = term; + return this; + } + + @Override + public String toString() { + return new StringBuilder("search ") + .append(term) + .toString(); + } + +// protected List impl() { +// +// WebTarget webResource = baseResource.path("/images/search").queryParam("term", term); +// +// LOGGER.trace("GET: {}", webResource); +// return webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { +// }); +// } +} diff --git a/src/main/java/com/github/dockerjava/client/command/StartContainerCommand.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java similarity index 81% rename from src/main/java/com/github/dockerjava/client/command/StartContainerCommand.java rename to src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index d7a86129..6054062e 100644 --- a/src/main/java/com/github/dockerjava/client/command/StartContainerCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -1,16 +1,12 @@ -package com.github.dockerjava.client.command; - -import javax.ws.rs.core.MediaType; +package com.github.dockerjava.core.command; import org.apache.commons.lang.builder.ToStringBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.StartContainerCmd; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Binds; @@ -20,17 +16,10 @@ import com.github.dockerjava.api.model.Ports; import com.google.common.base.Preconditions; -import javax.ws.rs.client.WebTarget; - -import static javax.ws.rs.client.Entity.entity; - /** * Start a container */ -public class StartContainerCommand extends AbstrDockerCmd implements StartContainerCmd { - - private static final Logger LOGGER = LoggerFactory - .getLogger(StartContainerCommand.class); +public class StartContainerCmdImpl extends AbstrDockerCmd implements StartContainerCmd { private String containerId; @@ -58,7 +47,8 @@ public class StartContainerCommand extends AbstrDockerCmd exec, String containerId) { + super(exec); withContainerId(containerId); } @@ -190,14 +180,14 @@ public Void exec() throws NotFoundException, NotModifiedException { return super.exec(); } - protected Void impl() throws DockerException { - - WebTarget webResource = baseResource.path("/containers/{id}/start") - .resolveTemplate("id", containerId); - - LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(this, MediaType.APPLICATION_JSON)); - - return null; - } +// protected Void impl() throws DockerException { +// +// WebTarget webResource = baseResource.path("/containers/{id}/start") +// .resolveTemplate("id", containerId); +// +// LOGGER.trace("POST: {}", webResource); +// webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(this, MediaType.APPLICATION_JSON)); +// +// return null; +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/StopContainerCommand.java b/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java similarity index 61% rename from src/main/java/com/github/dockerjava/client/command/StopContainerCommand.java rename to src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java index 3be4eefa..074412d9 100644 --- a/src/main/java/com/github/dockerjava/client/command/StopContainerCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java @@ -1,16 +1,8 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; -import static javax.ws.rs.client.Entity.entity; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.StopContainerCmd; import com.google.common.base.Preconditions; @@ -21,15 +13,14 @@ * @param timeout - Timeout in seconds before killing the container. Defaults to 10 seconds. * */ -public class StopContainerCommand extends AbstrDockerCmd implements StopContainerCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(StopContainerCommand.class); +public class StopContainerCmdImpl extends AbstrDockerCmd implements StopContainerCmd { private String containerId; private int timeout = 10; - public StopContainerCommand(String containerId) { + public StopContainerCmdImpl(DockerCmdExec exec, String containerId) { + super(exec); withContainerId(containerId); } @@ -74,14 +65,14 @@ public Void exec() throws NotFoundException, NotModifiedException { return super.exec(); } - protected Void impl() throws DockerException { - WebTarget webResource = baseResource.path("/containers/{id}/stop") - .resolveTemplate("id", containerId) - .queryParam("t", String.valueOf(timeout)); - - LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON)); - - return null; - } +// protected Void impl() throws DockerException { +// WebTarget webResource = baseResource.path("/containers/{id}/stop") +// .resolveTemplate("id", containerId) +// .queryParam("t", String.valueOf(timeout)); +// +// LOGGER.trace("POST: {}", webResource); +// webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON)); +// +// return null; +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/TagImageCommand.java b/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java similarity index 65% rename from src/main/java/com/github/dockerjava/client/command/TagImageCommand.java rename to src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java index fdd77f03..5ac73b8f 100644 --- a/src/main/java/com/github/dockerjava/client/command/TagImageCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java @@ -1,14 +1,6 @@ -package com.github.dockerjava.client.command; - -import static javax.ws.rs.client.Entity.entity; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +package com.github.dockerjava.core.command; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.TagImageCmd; import com.google.common.base.Preconditions; @@ -20,15 +12,14 @@ * @param force (not documented) * */ -public class TagImageCommand extends AbstrDockerCmd implements TagImageCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(TagImageCommand.class); +public class TagImageCmdImpl extends AbstrDockerCmd implements TagImageCmd { private String imageId, repository, tag; private boolean force; - public TagImageCommand(String imageId, String repository, String tag) { + public TagImageCmdImpl(DockerCmdExec exec, String imageId, String repository, String tag) { + super(exec); withImageId(imageId); withRepository(repository); withTag(tag); @@ -97,14 +88,14 @@ public String toString() { } - protected Void impl() { - WebTarget webResource = baseResource.path("/images/" + imageId + "/tag") - .queryParam("repo", repository) - .queryParam("tag", tag) - .queryParam("force", force ? "1" : "0"); - - LOGGER.trace("POST: {}", webResource); - webResource.request().post(entity(null, MediaType.APPLICATION_JSON), Response.class); - return null; - } +// protected Void impl() { +// WebTarget webResource = baseResource.path("/images/" + imageId + "/tag") +// .queryParam("repo", repository) +// .queryParam("tag", tag) +// .queryParam("force", force ? "1" : "0"); +// +// LOGGER.trace("POST: {}", webResource); +// webResource.request().post(entity(null, MediaType.APPLICATION_JSON), Response.class); +// return null; +// } } diff --git a/src/main/java/com/github/dockerjava/client/command/TopContainerCommand.java b/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java similarity index 57% rename from src/main/java/com/github/dockerjava/client/command/TopContainerCommand.java rename to src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java index 90eb0271..233439c5 100644 --- a/src/main/java/com/github/dockerjava/client/command/TopContainerCommand.java +++ b/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java @@ -1,14 +1,7 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.TopContainerCmd; import com.github.dockerjava.api.command.TopContainerResponse; import com.google.common.base.Preconditions; @@ -16,15 +9,14 @@ /** * List processes running inside a container */ -public class TopContainerCommand extends AbstrDockerCmd implements TopContainerCmd { - - private static final Logger LOGGER = LoggerFactory.getLogger(TopContainerCommand.class); +public class TopContainerCmdImpl extends AbstrDockerCmd implements TopContainerCmd { private String containerId; private String psArgs; - public TopContainerCommand(String containerId) { + public TopContainerCmdImpl(DockerCmdExec exec, String containerId) { + super(exec); withContainerId(containerId); } @@ -69,14 +61,14 @@ public TopContainerResponse exec() throws NotFoundException { return super.exec(); } - protected TopContainerResponse impl() throws DockerException { - WebTarget webResource = baseResource.path("/containers/{id}/top") - .resolveTemplate("id", containerId); - - if(!StringUtils.isEmpty(psArgs)) - webResource = webResource.queryParam("ps_args", psArgs); - - LOGGER.trace("GET: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON).get(TopContainerResponse.class); - } +// protected TopContainerResponse impl() throws DockerException { +// WebTarget webResource = baseResource.path("/containers/{id}/top") +// .resolveTemplate("id", containerId); +// +// if(!StringUtils.isEmpty(psArgs)) +// webResource = webResource.queryParam("ps_args", psArgs); +// +// LOGGER.trace("GET: {}", webResource); +// return webResource.request().accept(MediaType.APPLICATION_JSON).get(TopContainerResponse.class); +// } } diff --git a/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java new file mode 100644 index 00000000..8eaf9ed2 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java @@ -0,0 +1,60 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.DockerCmdExec; +import com.github.dockerjava.api.command.UnpauseContainerCmd; +import com.google.common.base.Preconditions; + +/** + * Unpause a container. + * + * @param containerId - Id of the container + * + */ +public class UnpauseContainerCmdImpl extends AbstrDockerCmd implements UnpauseContainerCmd { + + private String containerId; + + public UnpauseContainerCmdImpl(DockerCmdExec exec, String containerId) { + super(exec); + withContainerId(containerId); + } + + @Override + public String getContainerId() { + return containerId; + } + + @Override + public UnpauseContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + @Override + public String toString() { + return new StringBuilder("pause ") + .append(containerId) + .toString(); + } + + /** + * @throws NotFoundException No such container + */ + @Override + public Void exec() throws NotFoundException { + return super.exec(); + } + +// protected Void impl() throws DockerException { +// WebTarget webResource = baseResource.path("/containers/{id}/unpause") +// .resolveTemplate("id", containerId); +// +// LOGGER.trace("POST: {}", webResource); +// webResource.request().accept(MediaType.APPLICATION_JSON) +// .post(Entity.entity(Response.class, MediaType.APPLICATION_JSON)); +// +// return null; +// } +} diff --git a/src/main/java/com/github/dockerjava/core/command/VersionCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/VersionCmdImpl.java new file mode 100644 index 00000000..5da1cde4 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/VersionCmdImpl.java @@ -0,0 +1,28 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.command.DockerCmdExec; +import com.github.dockerjava.api.command.VersionCmd; +import com.github.dockerjava.api.model.Version; + + +/** + * Returns the Docker version info. + */ +public class VersionCmdImpl extends AbstrDockerCmd implements VersionCmd { + + @Override + public String toString() { + return "version"; + } + + public VersionCmdImpl(DockerCmdExec exec) { + super(exec); + } + +// protected Version impl() throws DockerException { +// WebTarget webResource = baseResource.path("/version"); +// +// LOGGER.trace("GET: {}", webResource); +// return webResource.request().accept(MediaType.APPLICATION_JSON).get(Version.class); +// } +} diff --git a/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java new file mode 100644 index 00000000..86e2b91d --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java @@ -0,0 +1,48 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.command.DockerCmdExec; +import com.github.dockerjava.api.command.WaitContainerCmd; +import com.google.common.base.Preconditions; + +/** + * Wait a container + * + * Block until container stops, then returns its exit code + */ +public class WaitContainerCmdImpl extends AbstrDockerCmd implements WaitContainerCmd { + + private String containerId; + + public WaitContainerCmdImpl(DockerCmdExec exec, String containerId) { + super(exec); + withContainerId(containerId); + } + + @Override + public String getContainerId() { + return containerId; + } + + @Override + public WaitContainerCmd withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + @Override + public String toString() { + return "wait " + containerId; + } + +// protected Integer impl() { +// WebTarget webResource = baseResource.path("/containers/{id}/wait") +// .resolveTemplate("id", containerId); +// +// LOGGER.trace("POST: {}", webResource); +// ObjectNode ObjectNode = webResource.request().accept(MediaType.APPLICATION_JSON) +// .post(entity(null, MediaType.APPLICATION_JSON), ObjectNode.class); +// +// return ObjectNode.get("StatusCode").asInt(); +// } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java new file mode 100644 index 00000000..e9a5b6d6 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java @@ -0,0 +1,35 @@ +package com.github.dockerjava.jaxrs; + +import java.io.IOException; + +import javax.ws.rs.client.WebTarget; + +import org.apache.commons.codec.binary.Base64; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.command.DockerCmd; +import com.github.dockerjava.api.command.DockerCmdExec; +import com.github.dockerjava.api.model.AuthConfig; +import com.google.common.base.Preconditions; + +public abstract class AbstrDockerCmdExec, RES_T> implements DockerCmdExec { + + private WebTarget baseResource; + + public AbstrDockerCmdExec(WebTarget baseResource) { + Preconditions.checkNotNull(baseResource, "baseResource was not specified"); + this.baseResource = baseResource; + } + + protected WebTarget getBaseResource() { + return baseResource; + } + + protected String registryAuth(AuthConfig authConfig) { + try { + return Base64.encodeBase64String(new ObjectMapper().writeValueAsString(authConfig).getBytes()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java new file mode 100644 index 00000000..6c659d0f --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java @@ -0,0 +1,41 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import java.io.InputStream; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.AttachContainerCmd; + +public class AttachContainerCmdExec extends AbstrDockerCmdExec implements AttachContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(AttachContainerCmdExec.class); + + public AttachContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public InputStream exec(AttachContainerCmd command) { + WebTarget webResource = getBaseResource().path("/containers/{id}/attach") + .resolveTemplate("{id}", command.getContainerId()) + .queryParam("logs", command.hasLogsEnabled() ? "1" : "0") + .queryParam("timestamps",command.hasTimestampsEnabled() ? "1" : "0") + .queryParam("stdout", command.hasStdoutEnabled() ? "1" : "0") + .queryParam("stderr", command.hasStderrEnabled() ? "1" : "0") + .queryParam("follow", command.hasFollowStreamEnabled() ? "1" : "0"); + + LOGGER.trace("POST: {}", webResource); + + return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .post(entity(null, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/AuthCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AuthCmdExec.java new file mode 100644 index 00000000..3fc9329f --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/AuthCmdExec.java @@ -0,0 +1,37 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.UnauthorizedException; +import com.github.dockerjava.api.command.AuthCmd; + +public class AuthCmdExec extends AbstrDockerCmdExec implements AuthCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(AuthCmdExec.class); + + public AuthCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Void exec(AuthCmd command) { + WebTarget webResource = getBaseResource().path("/auth"); + LOGGER.trace("POST: {}", webResource); + Response response = webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command.getAuthConfig(), MediaType.APPLICATION_JSON)); + + if(response.getStatus() == 401) { + throw new UnauthorizedException("Unauthorized"); + }; + + return null; + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java new file mode 100644 index 00000000..866cdfd9 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -0,0 +1,50 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import java.io.InputStream; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.BuildImageCmd; + +public class BuildImageCmdExec extends AbstrDockerCmdExec implements BuildImageCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(BuildImageCmdExec.class); + + public BuildImageCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public InputStream exec(BuildImageCmd command) { + WebTarget webResource = getBaseResource().path("/build"); + + if(command.getTag() != null) { + webResource = webResource.queryParam("t", command.getTag()); + } + if (command.hasNoCacheEnabled()) { + webResource = webResource.queryParam("nocache", "true"); + } + if (command.hasRemoveEnabled()) { + webResource = webResource.queryParam("rm", "true"); + } + if (command.isQuiet()) { + webResource = webResource.queryParam("q", "true"); + } + + LOGGER.trace("POST: {}", webResource); + return webResource + .request() + .accept(MediaType.TEXT_PLAIN) + .post(entity(command.getTarInputStream(), "application/tar"), Response.class).readEntity(InputStream.class); + + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/CommitCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/CommitCmdExec.java new file mode 100644 index 00000000..6e11c818 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/CommitCmdExec.java @@ -0,0 +1,38 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.github.dockerjava.api.command.CommitCmd; + +public class CommitCmdExec extends AbstrDockerCmdExec implements CommitCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(CommitCmdExec.class); + + public CommitCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public String exec(CommitCmd command) { + WebTarget webResource = getBaseResource().path("/commit") + .queryParam("container", command.getContainerId()) + .queryParam("repo", command.getRepository()) + .queryParam("tag", command.getTag()) + .queryParam("m", command.getMessage()) + .queryParam("author", command.getAuthor()) + .queryParam("pause", command.hasPauseEnabled() ? "1" : "0"); + + LOGGER.trace("POST: {}", webResource); + ObjectNode objectNode = webResource.request().accept("application/vnd.docker.raw-stream").post(entity(command, MediaType.APPLICATION_JSON), ObjectNode.class); + return objectNode.get("Id").asText(); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/ContainerDiffCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ContainerDiffCmdExec.java new file mode 100644 index 00000000..efa0284f --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/ContainerDiffCmdExec.java @@ -0,0 +1,33 @@ +package com.github.dockerjava.jaxrs; + +import java.util.List; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.ContainerDiffCmd; +import com.github.dockerjava.api.model.ChangeLog; + +public class ContainerDiffCmdExec extends AbstrDockerCmdExec> implements ContainerDiffCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(ContainerDiffCmdExec.class); + + public ContainerDiffCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public List exec(ContainerDiffCmd command) { + WebTarget webResource = getBaseResource().path("/containers/{id}/changes").resolveTemplate("id", command.getContainerId()); + + LOGGER.trace("GET: {}", webResource); + return webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java new file mode 100644 index 00000000..f1f197d0 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java @@ -0,0 +1,36 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import java.io.InputStream; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.CopyFileFromContainerCmd; + +public class CopyFileFromContainerCmdExec extends AbstrDockerCmdExec implements CopyFileFromContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(CopyFileFromContainerCmdExec.class); + + public CopyFileFromContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public InputStream exec(CopyFileFromContainerCmd command) { + WebTarget webResource = getBaseResource() + .path("/containers/{id}/copy") + .resolveTemplate("id", command.getContainerId()); + + LOGGER.trace("POST: " + webResource.toString()); + + return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(entity(command, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/CreateContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/CreateContainerCmdExec.java new file mode 100644 index 00000000..fd3be29d --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/CreateContainerCmdExec.java @@ -0,0 +1,35 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.command.CreateContainerResponse; + +public class CreateContainerCmdExec extends AbstrDockerCmdExec implements CreateContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(CreateContainerCmdExec.class); + + public CreateContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public CreateContainerResponse exec(CreateContainerCmd command) { + WebTarget webResource = getBaseResource().path("/containers/create"); + + if (command.getName() != null) { + webResource = webResource.queryParam("name", command.getName()); + } + + LOGGER.trace("POST: {} ", webResource); + return webResource.request().accept(MediaType.APPLICATION_JSON) + .post(entity(command, MediaType.APPLICATION_JSON), CreateContainerResponse.class); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/CreateImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/CreateImageCmdExec.java new file mode 100644 index 00000000..80e2fd3c --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/CreateImageCmdExec.java @@ -0,0 +1,36 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.CreateImageCmd; +import com.github.dockerjava.api.command.CreateImageResponse; + +public class CreateImageCmdExec extends AbstrDockerCmdExec implements CreateImageCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(CreateImageCmdExec.class); + + public CreateImageCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public CreateImageResponse exec(CreateImageCmd command) { + WebTarget webResource = getBaseResource() + .path("/images/create") + .queryParam("repo", command.getRepository()) + .queryParam("tag", command.getTag()) + .queryParam("fromSrc", "-"); + + LOGGER.trace("POST: {}", webResource); + return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .post(entity(command.getImageStream(), MediaType.APPLICATION_OCTET_STREAM), CreateImageResponse.class); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java new file mode 100644 index 00000000..ad9a059a --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -0,0 +1,245 @@ +package com.github.dockerjava.jaxrs; + +import java.io.IOException; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import com.github.dockerjava.api.command.AttachContainerCmd; +import com.github.dockerjava.api.command.AuthCmd; +import com.github.dockerjava.api.command.BuildImageCmd; +import com.github.dockerjava.api.command.CommitCmd; +import com.github.dockerjava.api.command.ContainerDiffCmd; +import com.github.dockerjava.api.command.CopyFileFromContainerCmd; +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.command.CreateImageCmd; +import com.github.dockerjava.api.command.DockerCmdExecFactory; +import com.github.dockerjava.api.command.InfoCmd; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectImageCmd; +import com.github.dockerjava.api.command.KillContainerCmd; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.command.ListImagesCmd; +import com.github.dockerjava.api.command.LogContainerCmd; +import com.github.dockerjava.api.command.PauseContainerCmd; +import com.github.dockerjava.api.command.PingCmd; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.command.PushImageCmd; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.command.RemoveImageCmd; +import com.github.dockerjava.api.command.RestartContainerCmd; +import com.github.dockerjava.api.command.SearchImagesCmd; +import com.github.dockerjava.api.command.StartContainerCmd; +import com.github.dockerjava.api.command.StopContainerCmd; +import com.github.dockerjava.api.command.TagImageCmd; +import com.github.dockerjava.api.command.TopContainerCmd; +import com.github.dockerjava.api.command.UnpauseContainerCmd; +import com.github.dockerjava.api.command.VersionCmd; +import com.github.dockerjava.api.command.WaitContainerCmd; +import com.github.dockerjava.core.DockerClientConfig; +import com.github.dockerjava.core.JsonClientFilter; +import com.github.dockerjava.core.SelectiveLoggingFilter; +import com.google.common.base.Preconditions; + +public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { + + private Client client; + + private WebTarget baseResource; + + @Override + public void init(DockerClientConfig dockerClientConfig) { + Preconditions.checkNotNull(dockerClientConfig, "config was not specified"); + + ClientConfig clientConfig = new ClientConfig(); + + clientConfig.register(JsonClientFilter.class); + clientConfig.register(JacksonJsonProvider.class); + + if (dockerClientConfig.isLoggingFilterEnabled()) { + clientConfig.register(SelectiveLoggingFilter.class); + } + + if (dockerClientConfig.getReadTimeout() != null) { + int readTimeout = dockerClientConfig.getReadTimeout(); + clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); + } + client = ClientBuilder.newClient(clientConfig); + + WebTarget webResource = client.target(dockerClientConfig.getUri()); + + if (dockerClientConfig.getVersion() != null) { + baseResource = webResource.path("v" + dockerClientConfig.getVersion()); + } else { + baseResource = webResource; + } + + } + + private WebTarget getBaseResource() { + Preconditions.checkNotNull(baseResource, "Factory not initialized. You probably forgot to call init()!"); + return baseResource; + } + + @Override + public AuthCmd.Exec createAuthCmdExec() { + return new AuthCmdExec(getBaseResource()); + } + + @Override + public InfoCmd.Exec createInfoCmdExec() { + return new InfoCmdExec(getBaseResource()); + } + + @Override + public PingCmd.Exec createPingCmdExec() { + return new PingCmdExec(getBaseResource()); + } + + @Override + public VersionCmd.Exec createVersionCmdExec() { + return new VersionCmdExec(getBaseResource()); + } + + @Override + public PullImageCmd.Exec createPullImageCmdExec() { + return new PullImageCmdExec(getBaseResource()); + } + + @Override + public PushImageCmd.Exec createPushImageCmdExec() { + return new PushImageCmdExec(getBaseResource()); + } + + @Override + public CreateImageCmd.Exec createCreateImageCmdExec() { + return new CreateImageCmdExec(getBaseResource()); + } + + @Override + public SearchImagesCmd.Exec createSearchImagesCmdExec() { + return new SearchImagesCmdExec(getBaseResource()); + } + + @Override + public RemoveImageCmd.Exec createRemoveImageCmdExec() { + return new RemoveImageCmdExec(getBaseResource()); + } + + @Override + public ListImagesCmd.Exec createListImagesCmdExec() { + return new ListImagesCmdExec(getBaseResource()); + } + + @Override + public InspectImageCmd.Exec createInspectImageCmdExec() { + return new InspectImageCmdExec(getBaseResource()); + } + + @Override + public ListContainersCmd.Exec createListContainersCmdExec() { + return new ListContainersCmdExec(getBaseResource()); + } + + @Override + public CreateContainerCmd.Exec createCreateContainerCmdExec() { + return new CreateContainerCmdExec(getBaseResource()); + } + + @Override + public StartContainerCmd.Exec createStartContainerCmdExec() { + return new StartContainerCmdExec(getBaseResource()); + } + + @Override + public InspectContainerCmd.Exec createInspectContainerCmdExec() { + return new InspectContainerCmdExec(getBaseResource()); + } + + @Override + public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { + return new RemoveContainerCmdExec(getBaseResource()); + } + + @Override + public WaitContainerCmd.Exec createWaitContainerCmdExec() { + return new WaitContainerCmdExec(getBaseResource()); + } + + @Override + public AttachContainerCmd.Exec createAttachContainerCmdExec() { + return new AttachContainerCmdExec(getBaseResource()); + } + + @Override + public LogContainerCmd.Exec createLogContainerCmdExec() { + return new LogContainerCmdExec(getBaseResource()); + } + + @Override + public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() { + return new CopyFileFromContainerCmdExec(getBaseResource()); + } + + @Override + public StopContainerCmd.Exec createStopContainerCmdExec() { + return new StopContainerCmdExec(getBaseResource()); + } + + @Override + public ContainerDiffCmd.Exec createContainerDiffCmdExec() { + return new ContainerDiffCmdExec(getBaseResource()); + } + + @Override + public KillContainerCmd.Exec createKillContainerCmdExec() { + return new KillContainerCmdExec(getBaseResource()); + } + + @Override + public RestartContainerCmd.Exec createRestartContainerCmdExec() { + return new RestartContainerCmdExec(getBaseResource()); + } + + @Override + public CommitCmd.Exec createCommitCmdExec() { + return new CommitCmdExec(getBaseResource()); + } + + @Override + public BuildImageCmd.Exec createBuildImageCmdExec() { + return new BuildImageCmdExec(getBaseResource()); + } + + @Override + public TopContainerCmd.Exec createTopContainerCmdExec() { + return new TopContainerCmdExec(getBaseResource()); + } + + @Override + public TagImageCmd.Exec createTagImageCmdExec() { + return new TagImageCmdExec(getBaseResource()); + } + + @Override + public PauseContainerCmd.Exec createPauseContainerCmdExec() { + return new PauseContainerCmdExec(getBaseResource()); + } + + @Override + public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { + return new UnpauseContainerCmdExec(baseResource); + } + + @Override + public void close() throws IOException { + Preconditions.checkNotNull(client, "Factory not initialized. You probably forgot to call init()!"); + client.close(); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java new file mode 100644 index 00000000..9ca8eb7f --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java @@ -0,0 +1,28 @@ +package com.github.dockerjava.jaxrs; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.InfoCmd; +import com.github.dockerjava.api.model.Info; + +public class InfoCmdExec extends AbstrDockerCmdExec implements InfoCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(InfoCmdExec.class); + + public InfoCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Info exec(InfoCmd command) { + WebTarget webResource = getBaseResource().path("/info"); + + LOGGER.trace("GET: {}", webResource); + return webResource.request().accept(MediaType.APPLICATION_JSON).get(Info.class); } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/InspectContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/InspectContainerCmdExec.java new file mode 100644 index 00000000..bca28232 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/InspectContainerCmdExec.java @@ -0,0 +1,29 @@ +package com.github.dockerjava.jaxrs; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectContainerResponse; + +public class InspectContainerCmdExec extends AbstrDockerCmdExec implements InspectContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(InspectContainerCmdExec.class); + + public InspectContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public InspectContainerResponse exec(InspectContainerCmd command) { + WebTarget webResource = getBaseResource().path(String.format("/containers/%s/json", command.getContainerId())); + + LOGGER.trace("GET: {}", webResource); + return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectContainerResponse.class); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/InspectImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/InspectImageCmdExec.java new file mode 100644 index 00000000..3d226374 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/InspectImageCmdExec.java @@ -0,0 +1,29 @@ +package com.github.dockerjava.jaxrs; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.InspectImageCmd; +import com.github.dockerjava.api.command.InspectImageResponse; + +public class InspectImageCmdExec extends AbstrDockerCmdExec implements InspectImageCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(InspectImageCmdExec.class); + + public InspectImageCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public InspectImageResponse exec(InspectImageCmd command) { + WebTarget webResource = getBaseResource().path("/images/{id}/json").resolveTemplate("id", command.getImageId()); + + LOGGER.trace("GET: {}", webResource); + return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectImageResponse.class); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java new file mode 100644 index 00000000..396dc772 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java @@ -0,0 +1,36 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.KillContainerCmd; + +public class KillContainerCmdExec extends AbstrDockerCmdExec implements KillContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(KillContainerCmdExec.class); + + public KillContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Void exec(KillContainerCmd command) { + WebTarget webResource = getBaseResource().path("/containers/{id}/kill").resolveTemplate("id", command.getContainerId()); + + if(command.getSignal() != null) { + webResource = webResource.queryParam("signal", command.getSignal()); + } + + LOGGER.trace("POST: {}", webResource); + webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON)); + + return null; + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/ListContainersCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ListContainersCmdExec.java new file mode 100644 index 00000000..3a4ae6dc --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/ListContainersCmdExec.java @@ -0,0 +1,43 @@ +package com.github.dockerjava.jaxrs; + +import java.util.List; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.model.Container; + +public class ListContainersCmdExec extends AbstrDockerCmdExec> implements ListContainersCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(ListContainersCmdExec.class); + + public ListContainersCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public List exec(ListContainersCmd command) { + WebTarget webResource = getBaseResource().path("/containers/json") + .queryParam("all", command.hasShowAllEnabled() ? "1" : "0") + .queryParam("since", command.getSinceId()) + .queryParam("before", command.getBeforeId()) + .queryParam("size", command.hasShowSizeEnabled() ? "1" : "0"); + + if (command.getLimit() >= 0) { + webResource = webResource.queryParam("limit", String.valueOf(command.getLimit())); + } + + LOGGER.trace("GET: {}", webResource); + List containers = webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); + LOGGER.trace("Response: {}", containers); + + return containers; + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java new file mode 100644 index 00000000..c20e4bde --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java @@ -0,0 +1,39 @@ +package com.github.dockerjava.jaxrs; + +import java.util.List; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.ListImagesCmd; +import com.github.dockerjava.api.model.Image; + +public class ListImagesCmdExec extends AbstrDockerCmdExec> implements ListImagesCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(ListImagesCmdExec.class); + + public ListImagesCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public List exec(ListImagesCmd command) { + WebTarget webResource = getBaseResource() + .path("/images/json") + .queryParam("filter", command.getFilter()) + .queryParam("all", command.hasShowAllEnabled() ? "1" : "0"); + + LOGGER.trace("GET: {}", webResource); + + List images = webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); + LOGGER.trace("Response: {}", images); + + return images; + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java new file mode 100644 index 00000000..0ae71a7a --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java @@ -0,0 +1,35 @@ +package com.github.dockerjava.jaxrs; + +import java.io.InputStream; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.LogContainerCmd; + +public class LogContainerCmdExec extends AbstrDockerCmdExec implements LogContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(LogContainerCmdExec.class); + + public LogContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public InputStream exec(LogContainerCmd command) { + WebTarget webResource = getBaseResource().path("/containers/{id}/logs") + .resolveTemplate("id", command.getContainerId()) + .queryParam("timestamps", command.hasTimestampsEnabled() ? "1" : "0") + .queryParam("stdout", command.hasStdoutEnabled() ? "1" : "0") + .queryParam("stderr", command.hasStderrEnabled() ? "1" : "0") + .queryParam("follow", command.hasFollowStreamEnabled() ? "1" : "0") + .queryParam("tail", command.getTail() < 0 ? "all" : "" + command.getTail()); + + LOGGER.trace("GET: {}", webResource); + return webResource.request().get(Response.class).readEntity(InputStream.class); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java new file mode 100644 index 00000000..0271fce5 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java @@ -0,0 +1,35 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.PauseContainerCmd; + +public class PauseContainerCmdExec extends AbstrDockerCmdExec implements PauseContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(PauseContainerCmdExec.class); + + public PauseContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Void exec(PauseContainerCmd command) { + WebTarget webResource = getBaseResource().path("/containers/{id}/pause") + .resolveTemplate("id", command.getContainerId()); + + LOGGER.trace("POST: {}", webResource); + webResource.request() + .accept(MediaType.APPLICATION_JSON) + .post(entity(null, MediaType.APPLICATION_JSON), Response.class); + + return null; + } + +} diff --git a/src/main/java/com/github/dockerjava/client/command/PingCommand.java b/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java similarity index 52% rename from src/main/java/com/github/dockerjava/client/command/PingCommand.java rename to src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java index 83ffef24..eede5765 100644 --- a/src/main/java/com/github/dockerjava/client/command/PingCommand.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.jaxrs; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; @@ -8,20 +8,22 @@ import com.github.dockerjava.api.command.PingCmd; -/** - * Ping the Docker server - * - */ -public class PingCommand extends AbstrDockerCmd implements PingCmd { +public class PingCmdExec extends AbstrDockerCmdExec implements PingCmd.Exec { - private static final Logger LOGGER = LoggerFactory.getLogger(PingCommand.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PingCmdExec.class); - protected Void impl() { - WebTarget webResource = baseResource.path("/_ping"); - + public PingCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Void exec(PingCmd command) { + WebTarget webResource = getBaseResource().path("/_ping"); + LOGGER.trace("GET: {}", webResource); webResource.request().get(Response.class); return null; } + } diff --git a/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java new file mode 100644 index 00000000..0785e029 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java @@ -0,0 +1,37 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import java.io.InputStream; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.PullImageCmd; + +public class PullImageCmdExec extends AbstrDockerCmdExec implements PullImageCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(PullImageCmdExec.class); + + public PullImageCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public InputStream exec(PullImageCmd command) { + WebTarget webResource = getBaseResource().path("/images/create") + .queryParam("tag", command.getTag()) + .queryParam("fromImage", command.getRepository()) + .queryParam("registry", command.getRegistry()); + + LOGGER.trace("POST: {}", webResource); + return webResource.request() + .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .post(entity(Response.class, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java new file mode 100644 index 00000000..a329834f --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java @@ -0,0 +1,44 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import java.io.InputStream; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.PushImageCmd; +import com.github.dockerjava.api.model.AuthConfig; + +public class PushImageCmdExec extends AbstrDockerCmdExec implements PushImageCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(PushImageCmdExec.class); + + public PushImageCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public InputStream exec(PushImageCmd command) { + WebTarget webResource = getBaseResource().path("/images/" + name(command) + "/push"); + + final String registryAuth = registryAuth(command.getAuthConfig()); + LOGGER.trace("POST: {}", webResource); + return webResource + .request() + .header("X-Registry-Auth", registryAuth) + .accept(MediaType.APPLICATION_JSON) + .post(entity(Response.class, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); + } + + private String name(PushImageCmd command) { + String name = command.getName(); + AuthConfig authConfig = command.getAuthConfig(); + return name.contains("/") ? name : authConfig.getUsername(); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java new file mode 100644 index 00000000..1b8bdf0c --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java @@ -0,0 +1,32 @@ +package com.github.dockerjava.jaxrs; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.RemoveContainerCmd; + +public class RemoveContainerCmdExec extends AbstrDockerCmdExec implements RemoveContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(RemoveContainerCmdExec.class); + + public RemoveContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Void exec(RemoveContainerCmd command) { + WebTarget webResource = getBaseResource().path("/containers/" + command.getContainerId()) + .queryParam("v", command.hasRemoveVolumesEnabled() ? "1" : "0") + .queryParam("force", command.hasForceEnabled() ? "1" : "0"); + + LOGGER.trace("DELETE: {}", webResource); + String response = webResource.request().accept(MediaType.APPLICATION_JSON).delete(String.class); + LOGGER.trace("Response: {}", response); + + return null; + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java new file mode 100644 index 00000000..292a4c0f --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java @@ -0,0 +1,31 @@ +package com.github.dockerjava.jaxrs; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.RemoveImageCmd; + +public class RemoveImageCmdExec extends AbstrDockerCmdExec implements RemoveImageCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(RemoveImageCmdExec.class); + + public RemoveImageCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Void exec(RemoveImageCmd command) { + WebTarget webResource = getBaseResource().path("/images/" + command.getImageId()) + .queryParam("force", command.hasForceEnabled() ? "1" : "0") + .queryParam("noprune", command.hasNoPruneEnabled() ? "1" : "0"); + + LOGGER.trace("DELETE: {}", webResource); + webResource.request().delete(Response.class); + + return null; + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java new file mode 100644 index 00000000..eaf4d1e9 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java @@ -0,0 +1,33 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.RestartContainerCmd; + +public class RestartContainerCmdExec extends AbstrDockerCmdExec implements RestartContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(RestartContainerCmdExec.class); + + public RestartContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Void exec(RestartContainerCmd command) { + WebTarget webResource = getBaseResource().path("/containers/{id}/restart") + .resolveTemplate("id", command.getContainerId()) + .queryParam("t", String.valueOf(command.getTimeout())); + + LOGGER.trace("POST: {}", webResource); + webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON_TYPE)); + + return null; + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/SearchImagesCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/SearchImagesCmdExec.java new file mode 100644 index 00000000..feddf017 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/SearchImagesCmdExec.java @@ -0,0 +1,32 @@ +package com.github.dockerjava.jaxrs; + +import java.util.List; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.SearchImagesCmd; +import com.github.dockerjava.api.model.SearchItem; + +public class SearchImagesCmdExec extends AbstrDockerCmdExec> implements SearchImagesCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(SearchImagesCmdExec.class); + + public SearchImagesCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public List exec(SearchImagesCmd command) { + WebTarget webResource = getBaseResource().path("/images/search").queryParam("term", command.getTerm()); + + LOGGER.trace("GET: {}", webResource); + return webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + }); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java new file mode 100644 index 00000000..1d63a1b5 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java @@ -0,0 +1,32 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.StartContainerCmd; + +public class StartContainerCmdExec extends AbstrDockerCmdExec implements StartContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(StartContainerCmdExec.class); + + public StartContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Void exec(StartContainerCmd command) { + WebTarget webResource = getBaseResource().path("/containers/{id}/start") + .resolveTemplate("id", command.getContainerId()); + + LOGGER.trace("POST: {}", webResource); + webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command, MediaType.APPLICATION_JSON)); + + return null; + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java new file mode 100644 index 00000000..24f10f0a --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java @@ -0,0 +1,33 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.StopContainerCmd; + +public class StopContainerCmdExec extends AbstrDockerCmdExec implements StopContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(StopContainerCmdExec.class); + + public StopContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Void exec(StopContainerCmd command) { + WebTarget webResource = getBaseResource().path("/containers/{id}/stop") + .resolveTemplate("id", command.getContainerId()) + .queryParam("t", String.valueOf(command.getTimeout())); + + LOGGER.trace("POST: {}", webResource); + webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON)); + + return null; + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java new file mode 100644 index 00000000..56f94cd5 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java @@ -0,0 +1,37 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.TagImageCmd; + +public class TagImageCmdExec extends AbstrDockerCmdExec implements TagImageCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(TagImageCmdExec.class); + + public TagImageCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Void exec(TagImageCmd command) { + WebTarget webResource = getBaseResource().path("/images/" + command.getImageId() + "/tag") + .queryParam("repo", command.getRepository()) + .queryParam("tag", command.getTag()) + .queryParam("force", command.hasForceEnabled() ? "1" : "0"); + + LOGGER.trace("POST: {}", webResource); + webResource.request().post(entity(null, MediaType.APPLICATION_JSON), Response.class); + return null; + } + + + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/TopContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/TopContainerCmdExec.java new file mode 100644 index 00000000..13b7f44c --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/TopContainerCmdExec.java @@ -0,0 +1,34 @@ +package com.github.dockerjava.jaxrs; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.lang.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.TopContainerCmd; +import com.github.dockerjava.api.command.TopContainerResponse; + +public class TopContainerCmdExec extends AbstrDockerCmdExec implements TopContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(TopContainerCmdExec.class); + + public TopContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public TopContainerResponse exec(TopContainerCmd command) { + WebTarget webResource = getBaseResource().path("/containers/{id}/top") + .resolveTemplate("id", command.getContainerId()); + + if(!StringUtils.isEmpty(command.getPsArgs())) + webResource = webResource.queryParam("ps_args", command.getPsArgs()); + + LOGGER.trace("GET: {}", webResource); + return webResource.request().accept(MediaType.APPLICATION_JSON).get(TopContainerResponse.class); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java new file mode 100644 index 00000000..dac47319 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java @@ -0,0 +1,33 @@ +package com.github.dockerjava.jaxrs; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.UnpauseContainerCmd; + +public class UnpauseContainerCmdExec extends AbstrDockerCmdExec implements UnpauseContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(UnpauseContainerCmdExec.class); + + public UnpauseContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Void exec(UnpauseContainerCmd command) { + WebTarget webResource = getBaseResource().path("/containers/{id}/unpause") + .resolveTemplate("id", command.getContainerId()); + + LOGGER.trace("POST: {}", webResource); + webResource.request().accept(MediaType.APPLICATION_JSON) + .post(Entity.entity(Response.class, MediaType.APPLICATION_JSON)); + + return null; + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/VersionCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/VersionCmdExec.java new file mode 100644 index 00000000..b1ab6d63 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/VersionCmdExec.java @@ -0,0 +1,30 @@ +package com.github.dockerjava.jaxrs; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.VersionCmd; +import com.github.dockerjava.api.model.Version; + +public class VersionCmdExec extends AbstrDockerCmdExec implements VersionCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(VersionCmdExec.class); + + public VersionCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Version exec(VersionCmd command) { + WebTarget webResource = getBaseResource().path("/version"); + + LOGGER.trace("GET: {}", webResource); + return webResource.request().accept(MediaType.APPLICATION_JSON) + .get(Version.class); + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/WaitContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/WaitContainerCmdExec.java new file mode 100644 index 00000000..37f79987 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/WaitContainerCmdExec.java @@ -0,0 +1,35 @@ +package com.github.dockerjava.jaxrs; + +import static javax.ws.rs.client.Entity.entity; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.github.dockerjava.api.command.WaitContainerCmd; + +public class WaitContainerCmdExec extends AbstrDockerCmdExec implements WaitContainerCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(WaitContainerCmdExec.class); + + public WaitContainerCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public Integer exec(WaitContainerCmd command) { + WebTarget webResource = getBaseResource().path("/containers/{id}/wait") + .resolveTemplate("id", command.getContainerId()); + + LOGGER.trace("POST: {}", webResource); + ObjectNode ObjectNode = webResource.request().accept(MediaType.APPLICATION_JSON) + .post(entity(null, MediaType.APPLICATION_JSON), ObjectNode.class); + + return ObjectNode.get("StatusCode").asInt(); + } + +} diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 749a9c8f..e5aed596 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -2,6 +2,7 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.core.DockerClientImpl; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; diff --git a/src/test/java/com/github/dockerjava/client/command/AuthCommandTest.java b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java similarity index 86% rename from src/test/java/com/github/dockerjava/client/command/AuthCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java index 0959553c..fbd1d171 100644 --- a/src/test/java/com/github/dockerjava/client/command/AuthCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import java.lang.reflect.Method; @@ -13,10 +13,10 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.UnauthorizedException; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.github.dockerjava.client.DockerClientConfig; -import com.github.dockerjava.client.DockerClientImpl; +import com.github.dockerjava.core.DockerClientConfig; +import com.github.dockerjava.core.DockerClientImpl; -public class AuthCommandTest extends AbstractDockerClientTest { +public class AuthCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/BuildImageCommandTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java similarity index 98% rename from src/test/java/com/github/dockerjava/client/command/BuildImageCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index 9250c058..544e93f3 100644 --- a/src/test/java/com/github/dockerjava/client/command/BuildImageCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -28,7 +28,7 @@ import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class BuildImageCommandTest extends AbstractDockerClientTest { +public class BuildImageCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/CommitCommandTest.java b/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java similarity index 95% rename from src/test/java/com/github/dockerjava/client/command/CommitCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java index 38975982..bc69d950 100644 --- a/src/test/java/com/github/dockerjava/client/command/CommitCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -21,7 +21,7 @@ import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class CommitCommandTest extends AbstractDockerClientTest { +public class CommitCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/ContainerDiffCommandTest.java b/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java similarity index 95% rename from src/test/java/com/github/dockerjava/client/command/ContainerDiffCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java index 27d6b323..c689e220 100644 --- a/src/test/java/com/github/dockerjava/client/command/ContainerDiffCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static ch.lambdaj.Lambda.selectUnique; import static org.hamcrest.MatcherAssert.assertThat; @@ -22,7 +22,7 @@ import com.github.dockerjava.api.model.ChangeLog; import com.github.dockerjava.client.AbstractDockerClientTest; -public class ContainerDiffCommandTest extends AbstractDockerClientTest { +public class ContainerDiffCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCommandTest.java b/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java similarity index 93% rename from src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java index a02e961a..15c6d80e 100644 --- a/src/test/java/com/github/dockerjava/client/command/CopyFileFromContainerCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -12,7 +12,7 @@ import static org.hamcrest.Matchers.*; import static org.hamcrest.MatcherAssert.assertThat; -public class CopyFileFromContainerCommandTest extends AbstractDockerClientTest { +public class CopyFileFromContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() { diff --git a/src/test/java/com/github/dockerjava/client/command/CreateContainerCommandTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java similarity index 97% rename from src/test/java/com/github/dockerjava/client/command/CreateContainerCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index a0167c0d..e0332d41 100644 --- a/src/test/java/com/github/dockerjava/client/command/CreateContainerCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @@ -20,7 +20,7 @@ import com.github.dockerjava.api.model.Volume; import com.github.dockerjava.client.AbstractDockerClientTest; -public class CreateContainerCommandTest extends AbstractDockerClientTest { +public class CreateContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/InfoCommandTest.java b/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java similarity index 95% rename from src/test/java/com/github/dockerjava/client/command/InfoCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java index 1eae4f36..c8333966 100644 --- a/src/test/java/com/github/dockerjava/client/command/InfoCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import java.lang.reflect.Method; @@ -18,7 +18,7 @@ import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.hamcrest.Matchers.not; -public class InfoCommandTest extends AbstractDockerClientTest { +public class InfoCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/KillContainerCommandTest.java b/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java similarity index 93% rename from src/test/java/com/github/dockerjava/client/command/KillContainerCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java index cfb64e6e..c68c57ef 100644 --- a/src/test/java/com/github/dockerjava/client/command/KillContainerCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -22,10 +22,10 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class KillContainerCommandTest extends AbstractDockerClientTest { +public class KillContainerCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(KillContainerCommandTest.class); + .getLogger(KillContainerCmdImplTest.class); @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/ListContainersCommandTest.java b/src/test/java/com/github/dockerjava/core/command/ListContainersCmdImplTest.java similarity index 96% rename from src/test/java/com/github/dockerjava/client/command/ListContainersCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/ListContainersCmdImplTest.java index 37e9f8a1..c0f85d92 100644 --- a/src/test/java/com/github/dockerjava/client/command/ListContainersCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ListContainersCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static ch.lambdaj.Lambda.filter; import static org.hamcrest.MatcherAssert.assertThat; @@ -28,7 +28,7 @@ import com.github.dockerjava.api.model.Container; import com.github.dockerjava.client.AbstractDockerClientTest; -public class ListContainersCommandTest extends AbstractDockerClientTest { +public class ListContainersCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/ListImagesCommandTest.java b/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java similarity index 93% rename from src/test/java/com/github/dockerjava/client/command/ListImagesCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java index f2164abe..3d892b0f 100644 --- a/src/test/java/com/github/dockerjava/client/command/ListImagesCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @@ -18,7 +18,7 @@ import com.github.dockerjava.api.model.Info; import com.github.dockerjava.client.AbstractDockerClientTest; -public class ListImagesCommandTest extends AbstractDockerClientTest { +public class ListImagesCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/LogContainerCommandTest.java b/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java similarity index 94% rename from src/test/java/com/github/dockerjava/client/command/LogContainerCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java index e1dbb734..1ebcb40d 100644 --- a/src/test/java/com/github/dockerjava/client/command/LogContainerCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; @@ -21,7 +21,7 @@ import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class LogContainerCommandTest extends AbstractDockerClientTest { +public class LogContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/PullImageCommandTest.java b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java similarity index 95% rename from src/test/java/com/github/dockerjava/client/command/PullImageCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java index ef4c5d92..cea292ac 100644 --- a/src/test/java/com/github/dockerjava/client/command/PullImageCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -21,7 +21,7 @@ import com.github.dockerjava.api.model.Info; import com.github.dockerjava.client.AbstractDockerClientTest; -public class PullImageCommandTest extends AbstractDockerClientTest { +public class PullImageCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/PushImageCommandTest.java b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java similarity index 93% rename from src/test/java/com/github/dockerjava/client/command/PushImageCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java index 6c9fc061..952f0b28 100644 --- a/src/test/java/com/github/dockerjava/client/command/PushImageCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -20,10 +20,10 @@ import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class PushImageCommandTest extends AbstractDockerClientTest { +public class PushImageCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(PushImageCommandTest.class); + .getLogger(PushImageCmdImplTest.class); String username; diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCommandTest.java b/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java similarity index 85% rename from src/test/java/com/github/dockerjava/client/command/RemoveContainerCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java index 34766bb8..b4ab9d93 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveContainerCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; @@ -21,12 +21,13 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.model.Container; import com.github.dockerjava.client.AbstractDockerClientTest; -public class RemoveContainerCommandTest extends AbstractDockerClientTest { +public class RemoveContainerCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(RemoveContainerCommandTest.class); + .getLogger(RemoveContainerCmdImplTest.class); @BeforeTest public void beforeTest() throws DockerException { @@ -59,7 +60,8 @@ public void removeContainer() throws DockerException { LOG.info("Removing container: {}", container.getId()); dockerClient.removeContainerCmd(container.getId()).exec(); - List containers2 = dockerClient.listContainersCmd().withShowAll(true).exec(); + List containers2 = dockerClient.listContainersCmd().withShowAll(true).exec(); + Matcher matcher = not(hasItem(hasField("id", startsWith(container.getId())))); assertThat(containers2, matcher); diff --git a/src/test/java/com/github/dockerjava/client/command/RemoveImageCommandTest.java b/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java similarity index 93% rename from src/test/java/com/github/dockerjava/client/command/RemoveImageCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java index 079a58d7..e5bda718 100644 --- a/src/test/java/com/github/dockerjava/client/command/RemoveImageCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; @@ -25,10 +25,10 @@ import com.github.dockerjava.api.model.Container; import com.github.dockerjava.client.AbstractDockerClientTest; -public class RemoveImageCommandTest extends AbstractDockerClientTest { +public class RemoveImageCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(RemoveImageCommandTest.class); + .getLogger(RemoveImageCmdImplTest.class); @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/RestartContainerCommandTest.java b/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java similarity index 95% rename from src/test/java/com/github/dockerjava/client/command/RestartContainerCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java index 4b45989d..b637d5e7 100644 --- a/src/test/java/com/github/dockerjava/client/command/RestartContainerCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -20,7 +20,7 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class RestartContainerCommandTest extends AbstractDockerClientTest { +public class RestartContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/SearchImagesCommandTest.java b/src/test/java/com/github/dockerjava/core/command/SearchImagesCmdImplTest.java similarity index 93% rename from src/test/java/com/github/dockerjava/client/command/SearchImagesCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/SearchImagesCmdImplTest.java index 52ad6afb..5d9f60f0 100644 --- a/src/test/java/com/github/dockerjava/client/command/SearchImagesCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/SearchImagesCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static ch.lambdaj.Lambda.filter; import static org.hamcrest.MatcherAssert.assertThat; @@ -22,7 +22,7 @@ import com.github.dockerjava.api.model.SearchItem; import com.github.dockerjava.client.AbstractDockerClientTest; -public class SearchImagesCommandTest extends AbstractDockerClientTest { +public class SearchImagesCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/StartContainerCommandTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java similarity index 98% rename from src/test/java/com/github/dockerjava/client/command/StartContainerCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index f2930920..e3dded0d 100644 --- a/src/test/java/com/github/dockerjava/client/command/StartContainerCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; @@ -31,7 +31,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; -public class StartContainerCommandTest extends AbstractDockerClientTest { +public class StartContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/StopContainerCommandTest.java b/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java similarity index 93% rename from src/test/java/com/github/dockerjava/client/command/StopContainerCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java index dd008f7c..588f3296 100644 --- a/src/test/java/com/github/dockerjava/client/command/StopContainerCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -22,10 +22,10 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class StopContainerCommandTest extends AbstractDockerClientTest { +public class StopContainerCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(StopContainerCommandTest.class); + .getLogger(StopContainerCmdImplTest.class); @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/TagImageCommandTest.java b/src/test/java/com/github/dockerjava/core/command/TagImageCmdImplTest.java similarity index 88% rename from src/test/java/com/github/dockerjava/client/command/TagImageCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/TagImageCmdImplTest.java index 9cc0d699..706dc1b7 100644 --- a/src/test/java/com/github/dockerjava/client/command/TagImageCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/TagImageCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import java.lang.reflect.Method; @@ -15,10 +15,10 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.client.AbstractDockerClientTest; -public class TagImageCommandTest extends AbstractDockerClientTest { +public class TagImageCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(TagImageCommandTest.class); + .getLogger(TagImageCmdImplTest.class); @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/VersionCommandTest.java b/src/test/java/com/github/dockerjava/core/command/VersionCmdImplTest.java similarity index 91% rename from src/test/java/com/github/dockerjava/client/command/VersionCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/VersionCmdImplTest.java index 6071d7b2..0f9883ee 100644 --- a/src/test/java/com/github/dockerjava/client/command/VersionCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/VersionCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import java.lang.reflect.Method; @@ -14,7 +14,7 @@ import com.github.dockerjava.api.model.Version; import com.github.dockerjava.client.AbstractDockerClientTest; -public class VersionCommandTest extends AbstractDockerClientTest { +public class VersionCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { diff --git a/src/test/java/com/github/dockerjava/client/command/WaitContainerCommandTest.java b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java similarity index 94% rename from src/test/java/com/github/dockerjava/client/command/WaitContainerCommandTest.java rename to src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java index be4718cb..f8d439ae 100644 --- a/src/test/java/com/github/dockerjava/client/command/WaitContainerCommandTest.java +++ b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.client.command; +package com.github.dockerjava.core.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -20,7 +20,7 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; -public class WaitContainerCommandTest extends AbstractDockerClientTest { +public class WaitContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { From 70336339f1350049025ae6e6dcb22726ad5a2234 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Tue, 19 Aug 2014 23:13:52 +0200 Subject: [PATCH 082/452] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c7c9daef..acfe43cd 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ Latest SNAPSHOT is available from maven repo: https://oss.sonatype.org/content/g ## Documentation -For code examples, please look at the [Wiki](https://github.com/docker-java/docker-java/wiki) or [Test cases](https://github.com/docker-java/docker-java/tree/master/src/test/java/com/github/dockerjava/client/command "Test cases") +For code examples, please look at the [Wiki](https://github.com/docker-java/docker-java/wiki) or [Test cases](https://github.com/docker-java/docker-java/tree/master/src/test/java/com/github/dockerjava/core/command "Test cases") ## Configuration @@ -70,7 +70,7 @@ There are three ways to configure, in descending order of precedence: ##### Programatic: In your application, e.g. - DockerClient docker = new DockerClient("http://localhost:2375"); + DockerClient docker = new DockerClientImpl("http://localhost:2375"); docker.setCredentials("dockeruser", "ilovedocker", "dockeruser@github.com");` ##### System Properties: From c9bd59a255045f1bcf10c5cd11cfba93ad311152 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 20 Aug 2014 08:30:58 +0200 Subject: [PATCH 083/452] Code cleanup --- .../core/command/AbstrAuthCfgDockerCmd.java | 2 ++ .../core/command/AbstrDockerCmd.java | 1 + .../core/command/AttachContainerCmdImpl.java | 28 ++-------------- .../dockerjava/core/command/AuthCmdImpl.java | 3 +- .../core/command/BuildImageCmdImpl.java | 32 ++----------------- .../core/command/CommitCmdImpl.java | 25 ++------------- .../core/command/ContainerDiffCmdImpl.java | 15 ++------- .../command/CopyFileFromContainerCmdImpl.java | 5 +-- .../core/command/CreateContainerCmdImpl.java | 17 ++-------- .../core/command/CreateImageCmdImpl.java | 18 ++--------- .../dockerjava/core/command/InfoCmdImpl.java | 10 +----- .../core/command/InspectContainerCmdImpl.java | 11 ++----- .../core/command/InspectImageCmdImpl.java | 11 ++----- .../core/command/KillContainerCmdImpl.java | 17 ++-------- .../core/command/ListContainersCmdImpl.java | 23 ++----------- .../core/command/ListImagesCmdImpl.java | 18 ++--------- .../core/command/LogContainerCmdImpl.java | 19 ++--------- .../core/command/PauseContainerCmdImpl.java | 16 ++-------- .../dockerjava/core/command/PingCmdImpl.java | 12 +------ .../core/command/PullImageCmdImpl.java | 17 ++-------- .../core/command/PushImageCmdImpl.java | 20 ++---------- .../core/command/RemoveContainerCmdImpl.java | 18 ++--------- .../core/command/RemoveImageCmdImpl.java | 17 ++-------- .../core/command/RestartContainerCmdImpl.java | 15 ++------- .../core/command/SearchImagesCmdImpl.java | 13 ++------ .../core/command/StartContainerCmdImpl.java | 14 +------- .../core/command/StopContainerCmdImpl.java | 15 ++------- .../core/command/TagImageCmdImpl.java | 16 ++-------- .../core/command/TopContainerCmdImpl.java | 15 ++------- .../core/command/UnpauseContainerCmdImpl.java | 15 ++------- .../core/command/VersionCmdImpl.java | 11 +------ .../core/command/WaitContainerCmdImpl.java | 14 +------- .../command/StartContainerCmdImplTest.java | 10 ++++++ 33 files changed, 71 insertions(+), 422 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java index 4ce7f0b4..72aa94d8 100644 --- a/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java @@ -3,9 +3,11 @@ import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; + import com.github.dockerjava.api.command.DockerCmd; import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.model.AuthConfig; + import com.google.common.base.Preconditions; import org.apache.commons.codec.binary.Base64; diff --git a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java index b01d5d97..74241573 100644 --- a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java @@ -12,6 +12,7 @@ import com.github.dockerjava.api.NotModifiedException; import com.github.dockerjava.api.command.DockerCmd; import com.github.dockerjava.api.command.DockerCmdExec; + import com.google.common.base.Preconditions; import javax.ws.rs.ClientErrorException; diff --git a/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java index 310cea0c..d52ceabe 100644 --- a/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java @@ -4,7 +4,7 @@ import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.AttachContainerCmd; -import com.github.dockerjava.api.command.DockerCmdExec; + import com.google.common.base.Preconditions; /** @@ -29,7 +29,7 @@ public class AttachContainerCmdImpl extends AbstrDockerCmd exec, String containerId) { + public AttachContainerCmdImpl(AttachContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -123,28 +123,4 @@ public AttachContainerCmd withLogs(boolean logs) { public InputStream exec() throws NotFoundException { return super.exec(); } - - public static interface Exec extends DockerCmdExec { - - } - -// protected InputStream impl() throws DockerException { -// -// AttachContainerCmd command = this; -// -// WebTarget webResource = baseResource.path("/containers/{id}/attach") -// .resolveTemplate("{id}", command.getContainerId()) -// .queryParam("logs", command.hasLogsEnabled() ? "1" : "0") -// .queryParam("timestamps",command.hasTimestampsEnabled() ? "1" : "0") -// .queryParam("stdout", command.hasStdoutEnabled() ? "1" : "0") -// .queryParam("stderr", command.hasStderrEnabled() ? "1" : "0") -// .queryParam("follow", command.hasFollowStreamEnabled() ? "1" : "0"); -// -// LOGGER.trace("POST: {}", webResource); -// -// return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) -// .post(entity(null, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); -// } - - } diff --git a/src/main/java/com/github/dockerjava/core/command/AuthCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/AuthCmdImpl.java index f7f52cf4..259333e5 100644 --- a/src/main/java/com/github/dockerjava/core/command/AuthCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/AuthCmdImpl.java @@ -2,7 +2,6 @@ import com.github.dockerjava.api.UnauthorizedException; import com.github.dockerjava.api.command.AuthCmd; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.model.AuthConfig; /** @@ -12,7 +11,7 @@ */ public class AuthCmdImpl extends AbstrAuthCfgDockerCmd implements AuthCmd { - public AuthCmdImpl(DockerCmdExec exec, AuthConfig authConfig) { + public AuthCmdImpl(AuthCmd.Exec exec, AuthConfig authConfig) { super(exec); withAuthConfig(authConfig); } diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 184ffcf1..0aa09ad8 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -17,8 +17,8 @@ import com.github.dockerjava.api.DockerClientException; import com.github.dockerjava.api.command.BuildImageCmd; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.core.CompressArchiveUtil; + import com.google.common.base.Preconditions; /** @@ -42,13 +42,13 @@ public class BuildImageCmdImpl extends AbstrDockerCmd exec, File dockerFolder) { + public BuildImageCmdImpl(BuildImageCmd.Exec exec, File dockerFolder) { super(exec); Preconditions.checkNotNull(dockerFolder, "dockerFolder is null"); withTarInputStream(buildDockerFolderTar(dockerFolder)); } - public BuildImageCmdImpl(DockerCmdExec exec, InputStream tarInputStream) { + public BuildImageCmdImpl(BuildImageCmd.Exec exec, InputStream tarInputStream) { super(exec); Preconditions.checkNotNull(tarInputStream, "tarInputStream is null"); withTarInputStream(tarInputStream); @@ -125,32 +125,6 @@ public String toString() { .append(!remove ? "--rm=false " : "") .toString(); } - - - -// protected InputStream impl() { -// -// BuildImageCmd command = this; -// -// WebTarget webResource = baseResource.path("/build") -// .queryParam("t", tag); -// if (command.hasNoCacheEnabled()) { -// webResource = webResource.queryParam("nocache", "true"); -// } -// if (command.hasRemoveEnabled()) { -// webResource = webResource.queryParam("rm", "true"); -// } -// if (command.isQuiet()) { -// webResource = webResource.queryParam("q", "true"); -// } -// -// LOGGER.trace("POST: {}", webResource); -// return webResource -// .request() -// .accept(MediaType.TEXT_PLAIN) -// .post(entity(command.getTarInputStream(), "application/tar"), Response.class).readEntity(InputStream.class); -// -// } protected InputStream buildDockerFolderTar(File dockerFolder) { Preconditions.checkArgument(dockerFolder.exists(), diff --git a/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java index 5f0325f0..ee9c4db6 100644 --- a/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java @@ -3,11 +3,12 @@ import org.apache.commons.lang.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonProperty; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CommitCmd; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.model.ExposedPorts; import com.github.dockerjava.api.model.Volumes; + import com.google.common.base.Preconditions; /** @@ -73,7 +74,7 @@ public class CommitCmdImpl extends AbstrDockerCmd implements private String workingDir; - public CommitCmdImpl(DockerCmdExec exec, String containerId) { + public CommitCmdImpl(CommitCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -115,8 +116,6 @@ public String getAuthor() { public boolean hasPauseEnabled() { return pause; } - - @Override public CommitCmdImpl withAttachStderr(boolean attachStderr) { @@ -369,22 +368,4 @@ public String toString() { public String exec() throws NotFoundException { return super.exec(); } - -// protected String impl() throws DockerException { -// -// CommitCmd command = this; -// -// WebTarget webResource = baseResource.path("/commit") -// .queryParam("container", command.getContainerId()) -// .queryParam("repo", command.getRepository()) -// .queryParam("tag", command.getTag()) -// .queryParam("m", command.getMessage()) -// .queryParam("author", command.getAuthor()) -// .queryParam("pause", command.hasPauseEnabled() ? "1" : "0"); -// -// LOGGER.trace("POST: {}", webResource); -// ObjectNode objectNode = webResource.request().accept("application/vnd.docker.raw-stream").post(entity(this, MediaType.APPLICATION_JSON), ObjectNode.class); -// return objectNode.get("Id").asText(); -// -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java index 40a99eaf..f6a414b1 100644 --- a/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java @@ -6,10 +6,9 @@ import com.github.dockerjava.api.InternalServerErrorException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.ContainerDiffCmd; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.model.ChangeLog; -import com.google.common.base.Preconditions; +import com.google.common.base.Preconditions; /** * Inspect changes on a container's filesystem @@ -21,7 +20,7 @@ public class ContainerDiffCmdImpl extends AbstrDockerCmd> exec, String containerId) { + public ContainerDiffCmdImpl(ContainerDiffCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -52,14 +51,4 @@ public String toString() { public List exec() throws NotFoundException { return super.exec(); } - -// protected List impl() throws DockerException { -// ContainerDiffCmd command = this; -// -// WebTarget webResource = baseResource.path("/containers/{id}/changes").resolveTemplate("id", command.getContainerId()); -// -// LOGGER.trace("GET: {}", webResource); -// return webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { -// }); -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java index d0515952..929b6bf5 100644 --- a/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java @@ -5,9 +5,10 @@ import org.apache.commons.lang.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonProperty; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CopyFileFromContainerCmd; -import com.github.dockerjava.api.command.DockerCmdExec; + import com.google.common.base.Preconditions; /** @@ -25,7 +26,7 @@ public class CopyFileFromContainerCmdImpl extends AbstrDockerCmd exec, String containerId, String resource) { + public CopyFileFromContainerCmdImpl(CopyFileFromContainerCmd.Exec exec, String containerId, String resource) { super(exec); withContainerId(containerId); withResource(resource); diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index 65e7cb61..4d3ab26e 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -4,15 +4,16 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; + import com.github.dockerjava.api.ConflictException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateContainerResponse; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.ExposedPorts; import com.github.dockerjava.api.model.Volume; import com.github.dockerjava.api.model.Volumes; + import com.google.common.base.Preconditions; /** @@ -45,7 +46,7 @@ public class CreateContainerCmdImpl extends AbstrDockerCmd exec, String image) { + public CreateContainerCmdImpl(CreateContainerCmd.Exec exec, String image) { super(exec); Preconditions.checkNotNull(image, "image was not specified"); withImage(image); @@ -304,16 +305,4 @@ public String toString() { public CreateContainerResponse exec() throws NotFoundException, ConflictException { return super.exec(); } - -// protected CreateContainerResponse impl() { -// WebTarget webResource = baseResource.path("/containers/create"); -// -// if (name != null) { -// webResource = webResource.queryParam("name", name); -// } -// -// LOGGER.trace("POST: {} ", webResource); -// return webResource.request().accept(MediaType.APPLICATION_JSON) -// .post(entity(this, MediaType.APPLICATION_JSON), CreateContainerResponse.class); - } diff --git a/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java index c3d1bfb1..99a570ff 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java @@ -6,7 +6,7 @@ import com.github.dockerjava.api.command.CreateImageCmd; import com.github.dockerjava.api.command.CreateImageResponse; -import com.github.dockerjava.api.command.DockerCmdExec; + import com.google.common.base.Preconditions; /** @@ -22,7 +22,7 @@ public class CreateImageCmdImpl extends AbstrDockerCmd exec, String repository, InputStream imageStream) { + public CreateImageCmdImpl(CreateImageCmd.Exec exec, String repository, InputStream imageStream) { super(exec); withRepository(repository); withImageStream(imageStream); @@ -81,18 +81,4 @@ public String toString() { .append(tag != null ? tag : "") .toString(); } - -// protected CreateImageResponse impl() { -// -// WebTarget webResource = baseResource -// .path("/images/create") -// .queryParam("repo", repository) -// .queryParam("tag", tag) -// .queryParam("fromSrc", "-"); -// -// LOGGER.trace("POST: {}", webResource); -// return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) -// .post(entity(imageStream, MediaType.APPLICATION_OCTET_STREAM), CreateImageResponse.class); -// -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/InfoCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/InfoCmdImpl.java index 4493db0d..767da204 100644 --- a/src/main/java/com/github/dockerjava/core/command/InfoCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/InfoCmdImpl.java @@ -1,6 +1,5 @@ package com.github.dockerjava.core.command; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.InfoCmd; import com.github.dockerjava.api.model.Info; @@ -9,7 +8,7 @@ */ public class InfoCmdImpl extends AbstrDockerCmd implements InfoCmd { - public InfoCmdImpl(DockerCmdExec exec) { + public InfoCmdImpl(InfoCmd.Exec exec) { super(exec); } @@ -17,11 +16,4 @@ public InfoCmdImpl(DockerCmdExec exec) { public String toString() { return "info"; } - -// protected Info impl() throws DockerException { -// WebTarget webResource = baseResource.path("/info"); -// -// LOGGER.trace("GET: {}", webResource); -// return webResource.request().accept(MediaType.APPLICATION_JSON).get(Info.class); -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java index 20e47f6d..0fd55b76 100644 --- a/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java @@ -1,9 +1,9 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectContainerResponse; + import com.google.common.base.Preconditions; /** @@ -13,7 +13,7 @@ public class InspectContainerCmdImpl extends AbstrDockerCmd exec, String containerId) { + public InspectContainerCmdImpl(InspectContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -42,11 +42,4 @@ public String toString() { public InspectContainerResponse exec() throws NotFoundException { return super.exec(); } - -// protected InspectContainerResponse impl() throws DockerException { -// WebTarget webResource = baseResource.path(String.format("/containers/%s/json", containerId)); -// -// LOGGER.trace("GET: {}", webResource); -// return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectContainerResponse.class); -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java index f0e9457c..b52b15d5 100644 --- a/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java @@ -1,9 +1,9 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.InspectImageCmd; import com.github.dockerjava.api.command.InspectImageResponse; + import com.google.common.base.Preconditions; /** @@ -13,7 +13,7 @@ public class InspectImageCmdImpl extends AbstrDockerCmd exec,String imageId) { + public InspectImageCmdImpl(InspectImageCmd.Exec exec, String imageId) { super(exec); withImageId(imageId); } @@ -42,11 +42,4 @@ public String toString() { public InspectImageResponse exec() throws NotFoundException { return super.exec(); } - -// protected InspectImageResponse impl() { -// WebTarget webResource = baseResource.path("/images/{id}/json").resolveTemplate("id", imageId); -// -// LOGGER.trace("GET: {}", webResource); -// return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectImageResponse.class); -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java index 4ed15abf..f8ca070f 100644 --- a/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java @@ -1,8 +1,8 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.KillContainerCmd; + import com.google.common.base.Preconditions; /** @@ -12,7 +12,7 @@ public class KillContainerCmdImpl extends AbstrDockerCmd private String containerId, signal; - public KillContainerCmdImpl(DockerCmdExec exec, String containerId) { + public KillContainerCmdImpl(KillContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -53,17 +53,4 @@ public String toString() { public Void exec() throws NotFoundException { return super.exec(); } - -// protected Void impl() throws DockerException { -// WebTarget webResource = baseResource.path("/containers/{id}/kill").resolveTemplate("id", containerId); -// -// if(signal != null) { -// webResource = webResource.queryParam("signal", signal); -// } -// -// LOGGER.trace("POST: {}", webResource); -// webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON)); -// -// return null; -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java index cf91ef22..c2ebd491 100644 --- a/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java @@ -2,9 +2,9 @@ import java.util.List; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.ListContainersCmd; import com.github.dockerjava.api.model.Container; + import com.google.common.base.Preconditions; /** @@ -25,7 +25,7 @@ public class ListContainersCmdImpl extends AbstrDockerCmd> exec) { + public ListContainersCmdImpl(ListContainersCmd.Exec exec) { super(exec); } @@ -97,23 +97,4 @@ public String toString() { .append(limit != -1 ? "-n " + limit : "") .toString(); } - -// protected List impl() { -// WebTarget webResource = baseResource.path("/containers/json") -// .queryParam("all", showAll ? "1" : "0") -// .queryParam("since", sinceId) -// .queryParam("before", beforeId) -// .queryParam("size", showSize ? "1" : "0"); -// -// if (limit >= 0) { -// webResource = webResource.queryParam("limit", String.valueOf(limit)); -// } -// -// LOGGER.trace("GET: {}", webResource); -// List containers = webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { -// }); -// LOGGER.trace("Response: {}", containers); -// -// return containers; -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java index 71a27b92..95e36af8 100644 --- a/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java @@ -2,9 +2,9 @@ import java.util.List; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.ListImagesCmd; import com.github.dockerjava.api.model.Image; + import com.google.common.base.Preconditions; /** @@ -19,7 +19,7 @@ public class ListImagesCmdImpl extends AbstrDockerCmd private boolean showAll = false; - public ListImagesCmdImpl(DockerCmdExec> exec) { + public ListImagesCmdImpl(ListImagesCmd.Exec exec) { super(exec); } @@ -53,18 +53,4 @@ public String toString() { .append(filter != null ? "--filter " + filter : "") .toString(); } - -// protected List impl() { -// -// WebTarget webResource = baseResource -// .path("/images/json") -// .queryParam("filter", filter) -// .queryParam("all", showAll ? "1" : "0"); -// -// LOGGER.trace("GET: {}", webResource); -// List images = webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { -// }); -// LOGGER.trace("Response: {}", images); -// return images; -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java index 14294771..26c9a3b0 100644 --- a/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java @@ -3,8 +3,8 @@ import java.io.InputStream; import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.LogContainerCmd; + import com.google.common.base.Preconditions; /** @@ -30,7 +30,7 @@ public class LogContainerCmdImpl extends AbstrDockerCmd exec, String containerId) { + public LogContainerCmdImpl(LogContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -145,19 +145,4 @@ public String toString() { public InputStream exec() throws NotFoundException { return super.exec(); } - - -// protected InputStream impl() throws DockerException { -// -// WebTarget webResource = baseResource.path("/containers/{id}/logs") -// .resolveTemplate("id", containerId) -// .queryParam("timestamps", timestamps ? "1" : "0") -// .queryParam("stdout", stdout ? "1" : "0") -// .queryParam("stderr", stderr ? "1" : "0") -// .queryParam("follow", followStream ? "1" : "0") -// .queryParam("tail", tail < 0 ? "all" : "" + tail); -// -// LOGGER.trace("GET: {}", webResource); -// return webResource.request().get(Response.class).readEntity(InputStream.class); -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java index cf5bb8ea..fa6b816f 100644 --- a/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java @@ -1,8 +1,8 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.PauseContainerCmd; + import com.google.common.base.Preconditions; /** @@ -15,7 +15,7 @@ public class PauseContainerCmdImpl extends AbstrDockerCmd exec, String containerId) { + public PauseContainerCmdImpl(PauseContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -46,16 +46,4 @@ public String toString() { public Void exec() throws NotFoundException { return super.exec(); } - -// protected Void impl() throws DockerException { -// WebTarget webResource = baseResource.path("/containers/{id}/pause") -// .resolveTemplate("id", containerId); -// -// LOGGER.trace("POST: {}", webResource); -// webResource.request() -// .accept(MediaType.APPLICATION_JSON) -// .post(entity(null, MediaType.APPLICATION_JSON), Response.class); -// -// return null; -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/PingCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PingCmdImpl.java index 4f7d0f48..15cc1f5b 100644 --- a/src/main/java/com/github/dockerjava/core/command/PingCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PingCmdImpl.java @@ -1,6 +1,5 @@ package com.github.dockerjava.core.command; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.PingCmd; /** @@ -9,16 +8,7 @@ */ public class PingCmdImpl extends AbstrDockerCmd implements PingCmd { - public PingCmdImpl(DockerCmdExec exec) { + public PingCmdImpl(PingCmd.Exec exec) { super(exec); } - -// protected Void impl() { -// WebTarget webResource = baseResource.path("/_ping"); -// -// LOGGER.trace("GET: {}", webResource); -// webResource.request().get(Response.class); -// -// return null; -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java index 41e0e85c..b0ec0251 100644 --- a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java @@ -2,8 +2,8 @@ import java.io.InputStream; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.PullImageCmd; + import com.google.common.base.Preconditions; /** @@ -15,7 +15,7 @@ public class PullImageCmdImpl extends AbstrDockerCmd private String repository, tag, registry; - public PullImageCmdImpl(DockerCmdExec exec, String repository) { + public PullImageCmdImpl(PullImageCmd.Exec exec, String repository) { super(exec); withRepository(repository); } @@ -63,17 +63,4 @@ public String toString() { .append(tag != null ? ":" + tag : "") .toString(); } - -// protected InputStream impl() { -// -// WebTarget webResource = baseResource.path("/images/create") -// .queryParam("tag", tag) -// .queryParam("fromImage", repository) -// .queryParam("registry", registry); -// -// LOGGER.trace("POST: {}", webResource); -// return webResource.request() -// .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) -// .post(entity(Response.class, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java index 63098637..65ea843f 100644 --- a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java @@ -3,8 +3,8 @@ import java.io.InputStream; import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.PushImageCmd; + import com.google.common.base.Preconditions; /** @@ -16,7 +16,7 @@ public class PushImageCmdImpl extends AbstrAuthCfgDockerCmd exec, String name) { + public PushImageCmdImpl(PushImageCmd.Exec exec, String name) { super(exec); withName(name); } @@ -50,20 +50,4 @@ public String toString() { public InputStream exec() throws NotFoundException { return super.exec(); } - -// protected InputStream impl() { -// WebTarget webResource = baseResource.path("/images/" + name(name) + "/push"); -// -// final String registryAuth = registryAuth(); -// LOGGER.trace("POST: {}", webResource); -// return webResource -// .request() -// .header("X-Registry-Auth", registryAuth) -// .accept(MediaType.APPLICATION_JSON) -// .post(entity(Response.class, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); -// } -// -// private String name(String name) { -// return name.contains("/") ? name : authConfig.getUsername(); -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java index 258938bc..31344fdb 100644 --- a/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java @@ -1,8 +1,8 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.RemoveContainerCmd; + import com.google.common.base.Preconditions; /** @@ -17,7 +17,7 @@ public class RemoveContainerCmdImpl extends AbstrDockerCmd exec, String containerId) { + public RemoveContainerCmdImpl(RemoveContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -76,18 +76,4 @@ public String toString() { public Void exec() throws NotFoundException { return super.exec(); } - -// protected Void impl() throws DockerException { -// Preconditions.checkState(!StringUtils.isEmpty(containerId), "Container ID can't be empty"); -// -// WebTarget webResource = baseResource.path("/containers/" + containerId) -// .queryParam("v", removeVolumes ? "1" : "0") -// .queryParam("force", force ? "1" : "0"); -// -// LOGGER.trace("DELETE: {}", webResource); -// String response = webResource.request().accept(MediaType.APPLICATION_JSON).delete(String.class); -// LOGGER.trace("Response: {}", response); -// -// return null; -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java index caf88bd7..231fecb4 100644 --- a/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java @@ -1,8 +1,8 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.RemoveImageCmd; + import com.google.common.base.Preconditions; /** @@ -16,7 +16,7 @@ public class RemoveImageCmdImpl extends AbstrDockerCmd imp private boolean force, noPrune; - public RemoveImageCmdImpl(DockerCmdExec exec, String imageId) { + public RemoveImageCmdImpl(RemoveImageCmd.Exec exec, String imageId) { super(exec); withImageId(imageId); } @@ -76,17 +76,4 @@ public String toString() { public Void exec() throws NotFoundException { return super.exec(); } - -// protected Void impl() throws DockerException { -// Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty"); -// -// WebTarget webResource = baseResource.path("/images/" + imageId) -// .queryParam("force", force ? "1" : "0") -// .queryParam("noprune", noPrune ? "1" : "0"); -// -// LOGGER.trace("DELETE: {}", webResource); -// webResource.request().delete(Response.class); -// -// return null; -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java index 84a84622..f82a65b6 100644 --- a/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java @@ -1,8 +1,8 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.RestartContainerCmd; + import com.google.common.base.Preconditions; /** @@ -17,7 +17,7 @@ public class RestartContainerCmdImpl extends AbstrDockerCmd exec, String containerId) { + public RestartContainerCmdImpl(RestartContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -61,15 +61,4 @@ public String toString() { public Void exec() throws NotFoundException { return super.exec(); } - -// protected Void impl() throws DockerException { -// WebTarget webResource = baseResource.path("/containers/{id}/restart") -// .resolveTemplate("id", containerId) -// .queryParam("t", String.valueOf(timeout)); -// -// LOGGER.trace("POST: {}", webResource); -// webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON_TYPE)); -// -// return null; -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java index f378c875..3ca878f1 100644 --- a/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java @@ -2,9 +2,9 @@ import java.util.List; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.SearchImagesCmd; import com.github.dockerjava.api.model.SearchItem; + import com.google.common.base.Preconditions; /** @@ -17,7 +17,7 @@ public class SearchImagesCmdImpl extends AbstrDockerCmd> exec, String term) { + public SearchImagesCmdImpl(SearchImagesCmd.Exec exec, String term) { super(exec); withTerm(term); } @@ -40,13 +40,4 @@ public String toString() { .append(term) .toString(); } - -// protected List impl() { -// -// WebTarget webResource = baseResource.path("/images/search").queryParam("term", term); -// -// LOGGER.trace("GET: {}", webResource); -// return webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { -// }); -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index 113f9bea..a86ceb97 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -7,7 +7,6 @@ import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.StartContainerCmd; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Binds; @@ -52,7 +51,7 @@ public class StartContainerCmdImpl extends AbstrDockerCmd exec, String containerId) { + public StartContainerCmdImpl(StartContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -195,15 +194,4 @@ public String toString() { public Void exec() throws NotFoundException, NotModifiedException { return super.exec(); } - -// protected Void impl() throws DockerException { -// -// WebTarget webResource = baseResource.path("/containers/{id}/start") -// .resolveTemplate("id", containerId); -// -// LOGGER.trace("POST: {}", webResource); -// webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(this, MediaType.APPLICATION_JSON)); -// -// return null; -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java index 074412d9..7033cad6 100644 --- a/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java @@ -2,8 +2,8 @@ import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.StopContainerCmd; + import com.google.common.base.Preconditions; /** @@ -19,7 +19,7 @@ public class StopContainerCmdImpl extends AbstrDockerCmd private int timeout = 10; - public StopContainerCmdImpl(DockerCmdExec exec, String containerId) { + public StopContainerCmdImpl(StopContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -64,15 +64,4 @@ public String toString() { public Void exec() throws NotFoundException, NotModifiedException { return super.exec(); } - -// protected Void impl() throws DockerException { -// WebTarget webResource = baseResource.path("/containers/{id}/stop") -// .resolveTemplate("id", containerId) -// .queryParam("t", String.valueOf(timeout)); -// -// LOGGER.trace("POST: {}", webResource); -// webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON)); -// -// return null; -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java index 5ac73b8f..fe981218 100644 --- a/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java @@ -1,7 +1,7 @@ package com.github.dockerjava.core.command; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.TagImageCmd; + import com.google.common.base.Preconditions; /** @@ -18,7 +18,7 @@ public class TagImageCmdImpl extends AbstrDockerCmd implement private boolean force; - public TagImageCmdImpl(DockerCmdExec exec, String imageId, String repository, String tag) { + public TagImageCmdImpl(TagImageCmd.Exec exec, String imageId, String repository, String tag) { super(exec); withImageId(imageId); withRepository(repository); @@ -86,16 +86,4 @@ public String toString() { .append(tag != null ? ":" + tag : "") .toString(); } - - -// protected Void impl() { -// WebTarget webResource = baseResource.path("/images/" + imageId + "/tag") -// .queryParam("repo", repository) -// .queryParam("tag", tag) -// .queryParam("force", force ? "1" : "0"); -// -// LOGGER.trace("POST: {}", webResource); -// webResource.request().post(entity(null, MediaType.APPLICATION_JSON), Response.class); -// return null; -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java index 233439c5..92b82523 100644 --- a/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java @@ -1,9 +1,9 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.TopContainerCmd; import com.github.dockerjava.api.command.TopContainerResponse; + import com.google.common.base.Preconditions; /** @@ -15,7 +15,7 @@ public class TopContainerCmdImpl extends AbstrDockerCmd exec, String containerId) { + public TopContainerCmdImpl(TopContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -60,15 +60,4 @@ public String toString() { public TopContainerResponse exec() throws NotFoundException { return super.exec(); } - -// protected TopContainerResponse impl() throws DockerException { -// WebTarget webResource = baseResource.path("/containers/{id}/top") -// .resolveTemplate("id", containerId); -// -// if(!StringUtils.isEmpty(psArgs)) -// webResource = webResource.queryParam("ps_args", psArgs); -// -// LOGGER.trace("GET: {}", webResource); -// return webResource.request().accept(MediaType.APPLICATION_JSON).get(TopContainerResponse.class); -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java index 8eaf9ed2..3ecc0acb 100644 --- a/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java @@ -1,8 +1,8 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.UnpauseContainerCmd; + import com.google.common.base.Preconditions; /** @@ -15,7 +15,7 @@ public class UnpauseContainerCmdImpl extends AbstrDockerCmd exec, String containerId) { + public UnpauseContainerCmdImpl(UnpauseContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -46,15 +46,4 @@ public String toString() { public Void exec() throws NotFoundException { return super.exec(); } - -// protected Void impl() throws DockerException { -// WebTarget webResource = baseResource.path("/containers/{id}/unpause") -// .resolveTemplate("id", containerId); -// -// LOGGER.trace("POST: {}", webResource); -// webResource.request().accept(MediaType.APPLICATION_JSON) -// .post(Entity.entity(Response.class, MediaType.APPLICATION_JSON)); -// -// return null; -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/VersionCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/VersionCmdImpl.java index 5da1cde4..211ed140 100644 --- a/src/main/java/com/github/dockerjava/core/command/VersionCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/VersionCmdImpl.java @@ -1,10 +1,8 @@ package com.github.dockerjava.core.command; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.VersionCmd; import com.github.dockerjava.api.model.Version; - /** * Returns the Docker version info. */ @@ -15,14 +13,7 @@ public String toString() { return "version"; } - public VersionCmdImpl(DockerCmdExec exec) { + public VersionCmdImpl(VersionCmd.Exec exec) { super(exec); } - -// protected Version impl() throws DockerException { -// WebTarget webResource = baseResource.path("/version"); -// -// LOGGER.trace("GET: {}", webResource); -// return webResource.request().accept(MediaType.APPLICATION_JSON).get(Version.class); -// } } diff --git a/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java index 86e2b91d..80baf2cc 100644 --- a/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java @@ -1,6 +1,5 @@ package com.github.dockerjava.core.command; -import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.command.WaitContainerCmd; import com.google.common.base.Preconditions; @@ -13,7 +12,7 @@ public class WaitContainerCmdImpl extends AbstrDockerCmd exec, String containerId) { + public WaitContainerCmdImpl(WaitContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @@ -34,15 +33,4 @@ public WaitContainerCmd withContainerId(String containerId) { public String toString() { return "wait " + containerId; } - -// protected Integer impl() { -// WebTarget webResource = baseResource.path("/containers/{id}/wait") -// .resolveTemplate("id", containerId); -// -// LOGGER.trace("POST: {}", webResource); -// ObjectNode ObjectNode = webResource.request().accept(MediaType.APPLICATION_JSON) -// .post(entity(null, MediaType.APPLICATION_JSON), ObjectNode.class); -// -// return ObjectNode.get("StatusCode").asInt(); -// } } diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index ecd04a2e..6fa7ddc6 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -220,6 +220,16 @@ public void startContainer() throws DockerException { } + + /** + * This tests support for --net option for the docker run command: + * --net="bridge" Set the Network mode for the container + * 'bridge': creates a new network stack for the container on the docker bridge + * 'none': no networking for this container + * 'container:': reuses another container network stack + * 'host': use the host network stack inside the container. + * Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure. + */ @Test public void startContainerWithNetworkMode() throws DockerException { From 875fbaab1965563d2de169c46ca3fb7abc71c72b Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Thu, 21 Aug 2014 08:34:47 +0200 Subject: [PATCH 084/452] Fixed documentation of programmatic configuration --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index acfe43cd..699df949 100644 --- a/README.md +++ b/README.md @@ -70,8 +70,12 @@ There are three ways to configure, in descending order of precedence: ##### Programatic: In your application, e.g. - DockerClient docker = new DockerClientImpl("http://localhost:2375"); - docker.setCredentials("dockeruser", "ilovedocker", "dockeruser@github.com");` + DockerClientConfig config = DockerClientConfig.createDefaultConfigBuilder(); + config.withVersion("1.12"); + config.withUsername("dockeruser"); + config.withPassword("ilovedocker"); + config.withEmail("dockeruser@github.com); + DockerClient docker = new DockerClientImpl(config); ##### System Properties: E.g. From 4ce9b29d37d0c9aa3353ac60c626f7645ce33cee Mon Sep 17 00:00:00 2001 From: Aldrin Piri Date: Fri, 22 Aug 2014 23:23:42 -0400 Subject: [PATCH 085/452] Adjusting DNS property type to be a String array as specified by the Docker Remote API. --- .../api/command/InspectContainerResponse.java | 4 +-- .../api/command/StartContainerCmd.java | 7 ++--- .../core/command/StartContainerCmdImpl.java | 6 ++-- .../command/StartContainerCmdImplTest.java | 28 +++++++++++++++++++ 4 files changed, 35 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java index 2f63e5d6..d3375ffc 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java @@ -257,7 +257,7 @@ public class HostConfig { private boolean privileged; @JsonProperty("Dns") - private String dns; + private String[] dns; @JsonProperty("VolumesFrom") private String[] volumesFrom; @@ -295,7 +295,7 @@ public boolean isPrivileged() { return privileged; } - public String getDns() { + public String[] getDns() { return dns; } diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index 0998ea76..8f0a9d8c 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -1,14 +1,11 @@ package com.github.dockerjava.api.command; -import java.util.List; - import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Link; import com.github.dockerjava.api.model.LxcConf; import com.github.dockerjava.api.model.Ports; -import com.github.dockerjava.api.model.SearchItem; /** * Start a container @@ -27,7 +24,7 @@ public interface StartContainerCmd extends DockerCmd { public boolean isPrivileged(); - public String getDns(); + public String[] getDns(); public String getVolumesFrom(); @@ -45,7 +42,7 @@ public interface StartContainerCmd extends DockerCmd { public StartContainerCmd withPublishAllPorts(boolean publishAllPorts); - public StartContainerCmd withDns(String dns); + public StartContainerCmd withDns(String... dns); public StartContainerCmd withVolumesFrom(String volumesFrom); diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index 113f9bea..01b4e1a3 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -44,7 +44,7 @@ public class StartContainerCmdImpl extends AbstrDockerCmd Date: Sat, 23 Aug 2014 09:30:54 +0200 Subject: [PATCH 086/452] [maven-release-plugin] prepare release docker-java-0.10.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 3bb280f2..2f23cd19 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.0-SNAPSHOT + 0.10.0 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-0.10.0 From 82aff7ec9753f5b65eb274eb2d16a21f6bd74c81 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 23 Aug 2014 09:30:59 +0200 Subject: [PATCH 087/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2f23cd19..1ed10c4f 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.0 + 0.10.1-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.10.0 + HEAD From ddb82ce702d94f6d1430fbdd80be869b5b38c7da Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 23 Aug 2014 09:31:24 +0200 Subject: [PATCH 088/452] [maven-release-plugin] rollback the release of docker-java-0.10.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1ed10c4f..3bb280f2 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.1-SNAPSHOT + 0.10.0-SNAPSHOT docker-java https://github.com/docker-java/docker-java From e87f901cda10472a3428e7b15b58c839450434c3 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 23 Aug 2014 09:34:57 +0200 Subject: [PATCH 089/452] [maven-release-plugin] prepare release docker-java-0.10.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 3bb280f2..2f23cd19 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.0-SNAPSHOT + 0.10.0 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-0.10.0 From 14f8a72a121e0c3568b6ccc6d91f04b98ea1320f Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 23 Aug 2014 09:36:01 +0200 Subject: [PATCH 090/452] [maven-release-plugin] rollback the release of docker-java-0.10.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2f23cd19..3bb280f2 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.0 + 0.10.0-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.10.0 + HEAD From 2dcff68d40c1b0172fd00bafc99f06c67eec1384 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 23 Aug 2014 09:36:38 +0200 Subject: [PATCH 091/452] [maven-release-plugin] prepare release docker-java-0.10.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 3bb280f2..2f23cd19 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.0-SNAPSHOT + 0.10.0 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-0.10.0 From 892ed06e4c053004805c175e6bd44eb5f6e5e2d5 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 23 Aug 2014 09:38:05 +0200 Subject: [PATCH 092/452] [maven-release-plugin] rollback the release of docker-java-0.10.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2f23cd19..3bb280f2 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.0 + 0.10.0-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.10.0 + HEAD From 83892847cb214012179a65ee82a80691569d4f37 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 23 Aug 2014 09:38:43 +0200 Subject: [PATCH 093/452] [maven-release-plugin] prepare release docker-java-0.10.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 3bb280f2..2f23cd19 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.0-SNAPSHOT + 0.10.0 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-0.10.0 From ae86e3cae4db528da75459f57625b1d5f7ba02dc Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 23 Aug 2014 09:39:23 +0200 Subject: [PATCH 094/452] [maven-release-plugin] rollback the release of docker-java-0.10.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2f23cd19..3bb280f2 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.0 + 0.10.0-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.10.0 + HEAD From 19849b4a84c49eaebc17f969d37724055ded6970 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 23 Aug 2014 09:40:30 +0200 Subject: [PATCH 095/452] [maven-release-plugin] prepare release docker-java-0.10.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 3bb280f2..2f23cd19 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.0-SNAPSHOT + 0.10.0 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-0.10.0 From a2508e604888f56691900e29e9c12b3a8f870b70 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 23 Aug 2014 09:40:35 +0200 Subject: [PATCH 096/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2f23cd19..1ed10c4f 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.0 + 0.10.1-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.10.0 + HEAD From 99f43b0a29fb5c11ba0109e24efea59094c2173f Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sat, 23 Aug 2014 12:48:38 +0200 Subject: [PATCH 097/452] updated version --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 699df949..e77d4ada 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ Run build with tests: com.github.docker-java docker-java - 0.9.1 + 0.10.0 Latest SNAPSHOT is available from maven repo: https://oss.sonatype.org/content/groups/public From 596d9ad61a202408c1f192b5a12091e0c47c4ace Mon Sep 17 00:00:00 2001 From: getvictor Date: Sun, 24 Aug 2014 19:05:39 -0500 Subject: [PATCH 098/452] Fixes to AttachContainerCmd and CreateContainerCmd. - Fixed AttachContainerCmd so it works. - Added back CpuShares to CreateContainerCmd. It is documented in the command line reference but not in the API. --- .../dockerjava/api/command/CreateContainerCmd.java | 7 ++++++- .../core/command/CreateContainerCmdImpl.java | 11 +++++++++++ .../dockerjava/jaxrs/AttachContainerCmdExec.java | 6 +++--- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java index a8b55435..aaa23ad5 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java @@ -55,6 +55,10 @@ public interface CreateContainerCmd extends DockerCmd{ public CreateContainerCmd withMemorySwap(long memorySwap); + public int getCpuShares(); + + public CreateContainerCmd withCpuShares(int cpuShares); + public boolean isAttachStdin(); public CreateContainerCmd withAttachStdin(boolean attachStdin); @@ -96,10 +100,11 @@ public interface CreateContainerCmd extends DockerCmd{ * @throws NotFoundException No such container * @throws ConflictException Named container already exists */ + @Override public CreateContainerResponse exec() throws NotFoundException, ConflictException; public static interface Exec extends DockerCmdExec { } -} \ No newline at end of file +} diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index 4d3ab26e..b3f020f9 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -29,6 +29,7 @@ public class CreateContainerCmdImpl extends AbstrDockerCmd Date: Mon, 25 Aug 2014 21:13:34 +0200 Subject: [PATCH 099/452] Fix BuildImage test --- .../com/github/dockerjava/api/command/CreateContainerCmd.java | 2 +- .../github/dockerjava/core/command/BuildImageCmdImplTest.java | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java index aaa23ad5..e6e2e2c7 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java @@ -100,7 +100,7 @@ public interface CreateContainerCmd extends DockerCmd{ * @throws NotFoundException No such container * @throws ConflictException Named container already exists */ - @Override + @Override public CreateContainerResponse exec() throws NotFoundException, ConflictException; diff --git a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index 544e93f3..b689c81d 100644 --- a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -57,8 +57,7 @@ public void testNginxDockerfileBuilder() { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("nginx").getFile()); - - InputStream response = dockerClient.buildImageCmd(baseDir).exec(); + InputStream response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); String fullLog = asString(response); assertThat(fullLog, containsString("Successfully built")); From 57b7932af7dc245ad62c81a7cdcea9c59ccaabd3 Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Tue, 26 Aug 2014 22:47:57 +0200 Subject: [PATCH 100/452] let CompressArchiveUtil preserve executable flags --- .../dockerjava/core/CompressArchiveUtil.java | 6 ++ .../core/CompressArchiveUtilTest.java | 59 +++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 src/test/java/com/github/dockerjava/core/CompressArchiveUtilTest.java diff --git a/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java b/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java index 4fbb227a..2cf341bd 100644 --- a/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java +++ b/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java @@ -17,6 +17,12 @@ public static File archiveTARFiles(File base, Iterable files, String archi TarArchiveEntry tarEntry = new TarArchiveEntry(file); tarEntry.setName(relativize(base, file)); + if (!file.isDirectory()) { + if (file.canExecute()) { + tarEntry.setMode(tarEntry.getMode() | 0755); + } + } + tos.putArchiveEntry(tarEntry); if (!file.isDirectory()) { diff --git a/src/test/java/com/github/dockerjava/core/CompressArchiveUtilTest.java b/src/test/java/com/github/dockerjava/core/CompressArchiveUtilTest.java new file mode 100644 index 00000000..5212fe50 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/CompressArchiveUtilTest.java @@ -0,0 +1,59 @@ +package com.github.dockerjava.core; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +import static java.util.Arrays.asList; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class CompressArchiveUtilTest { + + @Test + public void testExecutableFlagIsPreserved() throws Exception { + File executableFile = createExecutableFile(); + File archive = CompressArchiveUtil.archiveTARFiles(executableFile.getParentFile(), asList(executableFile), "archive"); + File expectedFile = extractFileByName(archive, "executableFile.sh.result"); + + assertThat("should be executable", expectedFile.canExecute()); + } + + private File createExecutableFile() throws IOException { + File baseDir = new File(FileUtils.getTempDirectoryPath()); + File executableFile = new File(baseDir, "executableFile.sh"); + executableFile.createNewFile(); + executableFile.setExecutable(true); + assertThat(executableFile.canExecute(), is(true)); + return executableFile; + } + + private File extractFileByName(File archive, String filenameToExtract) throws IOException { + File baseDir = new File(FileUtils.getTempDirectoryPath()); + File expectedFile = new File(baseDir, filenameToExtract); + expectedFile.delete(); + assertThat(expectedFile.exists(), is(false)); + + TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(new FileInputStream(archive)); + TarArchiveEntry entry; + while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) { + String individualFiles = entry.getName(); + // there should be only one file in this archive + assertThat(individualFiles, equalTo("executableFile.sh")); + IOUtils.copy(tarArchiveInputStream, new FileOutputStream(expectedFile)); + if ((entry.getMode() & 0755) == 0755) { + expectedFile.setExecutable(true); + } + } + tarArchiveInputStream.close(); + return expectedFile; + } +} From 99424b6063b6f815927f0b3ff25cf85edcf4c0f2 Mon Sep 17 00:00:00 2001 From: Panu Wetterstrand Date: Wed, 27 Aug 2014 10:24:06 +0300 Subject: [PATCH 101/452] Container inspect can now return where the volumes are binded --- .../api/command/InspectContainerResponse.java | 16 ++-- .../dockerjava/api/model/VolumeBinds.java | 76 +++++++++++++++++++ 2 files changed, 84 insertions(+), 8 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/VolumeBinds.java diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java index d3375ffc..8c1f632d 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java @@ -3,16 +3,12 @@ import java.util.Map; +import com.github.dockerjava.api.model.*; import org.apache.commons.lang.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.dockerjava.api.model.ContainerConfig; -import com.github.dockerjava.api.model.LxcConf; -import com.github.dockerjava.api.model.Ports; -import com.github.dockerjava.api.model.Volume; -import com.github.dockerjava.api.model.Volumes; /** * @@ -74,7 +70,7 @@ public class InspectContainerResponse { private ContainerState state; @JsonProperty("Volumes") - private Volumes volumes; + private VolumeBinds volumes; @JsonProperty("VolumesRW") private Volumes volumesRW; @@ -120,10 +116,14 @@ public String getResolvConfPath() { } @JsonIgnore - public Volume[] getVolumes() { - return volumes.getVolumes(); + public Bind[] getBinds() { + return volumes.getBinds(); } + @JsonIgnore + public Volume[] getVolumes() { return volumes.getVolumes(); } + + @JsonIgnore public Volume[] getVolumesRW() { return volumesRW.getVolumes(); diff --git a/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java b/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java new file mode 100644 index 00000000..b4816568 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java @@ -0,0 +1,76 @@ +package com.github.dockerjava.api.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.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +@JsonSerialize(using = VolumeBinds.Serializer.class) +@JsonDeserialize(using = VolumeBinds.Deserializer.class) +public class VolumeBinds { + private final Bind[] binds; + private final Volume[] volumes; + + public VolumeBinds(Bind... binds) { + this.binds = binds; + this.volumes = new Volume[binds.length]; + for(int i=0; i { + + @Override + public void serialize(VolumeBinds binds, JsonGenerator jsonGen, + SerializerProvider serProvider) throws IOException, + JsonProcessingException { + + jsonGen.writeStartObject(); + for (Bind bind : binds.getBinds()) { + jsonGen.writeFieldName(bind.getPath()); + jsonGen.writeString(Boolean.toString(!bind.isReadOnly())); + } + jsonGen.writeEndObject(); + } + + } + + public static class Deserializer extends JsonDeserializer { + @Override + public VolumeBinds deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { + + List binds = new ArrayList(); + 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())) { + Bind bind = new Bind(field.getValue().toString(),Volume.parse(field.getKey())); + binds.add(bind); + } + } + return new VolumeBinds(binds.toArray(new Bind[binds.size()])); + } + } + +} From 229e08226e384176e80174618c2d5bbb3bc30962 Mon Sep 17 00:00:00 2001 From: Panu Wetterstrand Date: Wed, 27 Aug 2014 13:03:49 +0300 Subject: [PATCH 102/452] Refactored code a little and added test for parsing volume binds JSON --- .../api/command/InspectContainerResponse.java | 6 +-- .../dockerjava/api/model/VolumeBind.java | 19 +++++++ .../dockerjava/api/model/VolumeBinds.java | 49 +++++-------------- .../dockerjava/api/model/VolumeBindsTest.java | 33 +++++++++++++ .../command/StartContainerCmdImplTest.java | 17 +++---- 5 files changed, 74 insertions(+), 50 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/VolumeBind.java create mode 100644 src/test/java/com/github/dockerjava/api/model/VolumeBindsTest.java diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java index 8c1f632d..34bc15af 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java @@ -116,14 +116,10 @@ public String getResolvConfPath() { } @JsonIgnore - public Bind[] getBinds() { + public VolumeBind[] getVolumes() { return volumes.getBinds(); } - @JsonIgnore - public Volume[] getVolumes() { return volumes.getVolumes(); } - - @JsonIgnore public Volume[] getVolumesRW() { return volumesRW.getVolumes(); diff --git a/src/main/java/com/github/dockerjava/api/model/VolumeBind.java b/src/main/java/com/github/dockerjava/api/model/VolumeBind.java new file mode 100644 index 00000000..d662f2b8 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/VolumeBind.java @@ -0,0 +1,19 @@ +package com.github.dockerjava.api.model; + +public class VolumeBind { + private final String hostPath; + private final String containerPath; + + public VolumeBind(String hostPath, String containerPath){ + this.hostPath = hostPath; + this.containerPath = containerPath; + } + + public String getContainerPath() { + return containerPath; + } + + public String getHostPath() { + return hostPath; + } +} diff --git a/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java b/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java index b4816568..fd0223ca 100644 --- a/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java +++ b/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java @@ -15,61 +15,38 @@ import java.util.List; import java.util.Map; -@JsonSerialize(using = VolumeBinds.Serializer.class) +// This is not going to be serialized @JsonDeserialize(using = VolumeBinds.Deserializer.class) public class VolumeBinds { - private final Bind[] binds; - private final Volume[] volumes; + private final VolumeBind[] binds; - public VolumeBinds(Bind... binds) { + public VolumeBinds(VolumeBind... binds) { this.binds = binds; - this.volumes = new Volume[binds.length]; - for(int i=0; i { - - @Override - public void serialize(VolumeBinds binds, JsonGenerator jsonGen, - SerializerProvider serProvider) throws IOException, - JsonProcessingException { - - jsonGen.writeStartObject(); - for (Bind bind : binds.getBinds()) { - jsonGen.writeFieldName(bind.getPath()); - jsonGen.writeString(Boolean.toString(!bind.isReadOnly())); - } - jsonGen.writeEndObject(); - } - - } - - public static class Deserializer extends JsonDeserializer { + public static final class Deserializer extends JsonDeserializer { @Override public VolumeBinds deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { - List binds = new ArrayList(); + List binds = new ArrayList(); 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())) { - Bind bind = new Bind(field.getValue().toString(),Volume.parse(field.getKey())); + JsonNode value = field.getValue(); + if (!value.equals(NullNode.getInstance())) { + if (!value.isTextual()){ + throw deserializationContext.mappingException("Expected path for '"+field.getKey()+"'in host but got '"+ value+"'."); + } + VolumeBind bind = new VolumeBind(value.asText(),field.getKey()); binds.add(bind); } } - return new VolumeBinds(binds.toArray(new Bind[binds.size()])); + return new VolumeBinds(binds.toArray(new VolumeBind[binds.size()])); } } diff --git a/src/test/java/com/github/dockerjava/api/model/VolumeBindsTest.java b/src/test/java/com/github/dockerjava/api/model/VolumeBindsTest.java new file mode 100644 index 00000000..182f4e05 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/VolumeBindsTest.java @@ -0,0 +1,33 @@ +package com.github.dockerjava.api.model; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import jdk.nashorn.internal.parser.JSONParser; +import org.testng.annotations.Test; + +import java.io.IOException; + +import static org.testng.Assert.*; + +public class VolumeBindsTest { + @Test + public void t() throws IOException { + String s = "{\"/data\":\"/some/path\"}"; + ObjectMapper objectMapper = new ObjectMapper(); + VolumeBinds volumeBinds = objectMapper.readValue(s, VolumeBinds.class); + VolumeBind[] binds = volumeBinds.getBinds(); + assertEquals(binds.length,1); + assertEquals(binds[0].getHostPath(),"/some/path"); + assertEquals(binds[0].getContainerPath(), "/data"); + } + + @Test(expectedExceptions = JsonMappingException.class) + public void t1() throws IOException { + String s = "{\"/data\": {} }"; + ObjectMapper objectMapper = new ObjectMapper(); + VolumeBinds volumeBinds = objectMapper.readValue(s, VolumeBinds.class); + } + + +} \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index 41ea8973..79bc3488 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -10,16 +10,12 @@ import static org.hamcrest.Matchers.startsWith; import java.lang.reflect.Method; -import java.util.Arrays; +import java.util.*; import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; -import com.github.dockerjava.api.model.Bind; -import com.github.dockerjava.api.model.ExposedPort; -import com.github.dockerjava.api.model.Link; -import com.github.dockerjava.api.model.Ports; -import com.github.dockerjava.api.model.Volume; +import com.github.dockerjava.api.model.*; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; @@ -82,9 +78,12 @@ public void startContainerWithVolumes() throws DockerException { inspectContainerResponse = dockerClient.inspectContainerCmd(container .getId()).exec(); - - assertThat(Arrays.asList(inspectContainerResponse.getVolumes()), - contains(volume1, volume2)); + VolumeBind[] volumeBinds = inspectContainerResponse.getVolumes(); + List volumes = new ArrayList(); + for(VolumeBind bind :volumeBinds){ + volumes.add(bind.getContainerPath()); + } + assertThat(volumes, contains(volume1.getPath(), volume2.getPath())); assertThat(Arrays.asList(inspectContainerResponse.getVolumesRW()), contains(volume1, volume2)); From 2895f261fd1e39ff9d66f0ee013ad5f2b0751dd9 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 27 Aug 2014 19:03:54 +0200 Subject: [PATCH 103/452] Use DockerCmdExecFactory instead of DockerCmdExecFactoryImpl --- .../com/github/dockerjava/core/DockerClientImpl.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index ed4c4615..812127e3 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -7,6 +7,7 @@ import java.io.IOException; import java.io.InputStream; +import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.*; import com.github.dockerjava.api.model.AuthConfig; import com.github.dockerjava.core.command.*; @@ -16,11 +17,11 @@ /** * @author Konstantin Pelykh (kpelykh@gmail.com) */ -public class DockerClientImpl implements Closeable, com.github.dockerjava.api.DockerClient { +public class DockerClientImpl implements Closeable, DockerClient { private final DockerClientConfig dockerClientConfig; - private DockerCmdExecFactoryImpl dockerCmdExecFactory; + private DockerCmdExecFactory dockerCmdExecFactory; public DockerClientImpl() { this(DockerClientConfig.createDefaultConfigBuilder().build()); @@ -43,13 +44,13 @@ public DockerClientImpl(DockerClientConfig dockerClientConfig) { } public void setDockerCmdExecFactory( - DockerCmdExecFactoryImpl dockerCmdExecFactory) { + DockerCmdExecFactory dockerCmdExecFactory) { Preconditions.checkNotNull(dockerCmdExecFactory, "dockerCmdExecFactory was not specified"); this.dockerCmdExecFactory = dockerCmdExecFactory; this.dockerCmdExecFactory.init(dockerClientConfig); } - public DockerCmdExecFactoryImpl getDockerCmdExecFactory() { + public DockerCmdExecFactory getDockerCmdExecFactory() { return dockerCmdExecFactory; } From 48e921cf7fea0345dca47b8eb65da57934d8557a Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 27 Aug 2014 21:07:28 +0200 Subject: [PATCH 104/452] Fixed import --- .../com/github/dockerjava/api/model/VolumeBindsTest.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/github/dockerjava/api/model/VolumeBindsTest.java b/src/test/java/com/github/dockerjava/api/model/VolumeBindsTest.java index 182f4e05..e8bafc46 100644 --- a/src/test/java/com/github/dockerjava/api/model/VolumeBindsTest.java +++ b/src/test/java/com/github/dockerjava/api/model/VolumeBindsTest.java @@ -1,9 +1,8 @@ package com.github.dockerjava.api.model; -import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import jdk.nashorn.internal.parser.JSONParser; + import org.testng.annotations.Test; import java.io.IOException; @@ -26,7 +25,7 @@ public void t() throws IOException { public void t1() throws IOException { String s = "{\"/data\": {} }"; ObjectMapper objectMapper = new ObjectMapper(); - VolumeBinds volumeBinds = objectMapper.readValue(s, VolumeBinds.class); + objectMapper.readValue(s, VolumeBinds.class); } From fc810660c5f5f92cfc8457138c90fd608b3253e0 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 2 Sep 2014 20:16:09 +0200 Subject: [PATCH 105/452] Removed jersey-jetty-connector from dependencies --- pom.xml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1ed10c4f..b9f6c757 100644 --- a/pom.xml +++ b/pom.xml @@ -87,9 +87,14 @@ jackson-jaxrs-json-provider ${jackson-jaxrs.version} + + + + + - org.glassfish.jersey.connectors - jersey-jetty-connector + org.glassfish.jersey.core + jersey-client ${jersey.version} From 9dbf07c932e308ce74c433be5c0c15ce8eb8363b Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Thu, 11 Sep 2014 21:30:17 +0200 Subject: [PATCH 106/452] Added CloudBees logo --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e77d4ada..0f0ee313 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ -# docker-java + + +# docker-java ![Build on CloudBees](http://cloudbees.prod.acquia-sites.com/sites/default/files/styles/large/public/Button-Powered-by-CB.png?itok=uMDWINfY) Java API client for [Docker](http://docs.docker.io/ "Docker") From 11d884024b853c47bc06fe2488c6fc27091d32f9 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Thu, 11 Sep 2014 21:34:12 +0200 Subject: [PATCH 107/452] Update README.md --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0f0ee313..3ec79e1e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,4 @@ - - -# docker-java ![Build on CloudBees](http://cloudbees.prod.acquia-sites.com/sites/default/files/styles/large/public/Button-Powered-by-CB.png?itok=uMDWINfY) +# docker-java Java API client for [Docker](http://docs.docker.io/ "Docker") @@ -51,7 +49,7 @@ Run build with tests: 0.10.0 -Latest SNAPSHOT is available from maven repo: https://oss.sonatype.org/content/groups/public +Latest SNAPSHOT is published to maven repo: https://oss.sonatype.org/content/groups/public via ![Build on CloudBees](http://cloudbees.prod.acquia-sites.com/sites/default/files/styles/large/public/Button-Powered-by-CB.png?itok=uMDWINfY) ## Documentation From b725d3ad4d5c71f1aa8c22e617d1c3b0256798f3 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 12 Sep 2014 21:55:29 +0200 Subject: [PATCH 108/452] Create DockerClient via DockerClientFactory now --- .../dockerjava/core/DockerClientImpl.java | 35 +++++++++++++------ .../dockerjava/jaxrs/DockerClientFactory.java | 24 +++++++++++++ .../client/AbstractDockerClientTest.java | 3 +- .../core/command/AuthCmdImplTest.java | 3 +- 4 files changed, 53 insertions(+), 12 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/jaxrs/DockerClientFactory.java diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 812127e3..ba90156d 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -16,6 +16,8 @@ /** * @author Konstantin Pelykh (kpelykh@gmail.com) + * + * @see https://github.com/docker/docker/blob/master/api/client/commands.go */ public class DockerClientImpl implements Closeable, DockerClient { @@ -23,34 +25,47 @@ public class DockerClientImpl implements Closeable, DockerClient { private DockerCmdExecFactory dockerCmdExecFactory; - public DockerClientImpl() { + private DockerClientImpl() { this(DockerClientConfig.createDefaultConfigBuilder().build()); } - public DockerClientImpl(String serverUrl) { + private DockerClientImpl(String serverUrl) { this(configWithServerUrl(serverUrl)); } - private static DockerClientConfig configWithServerUrl(String serverUrl) { + private DockerClientImpl(DockerClientConfig dockerClientConfig) { + Preconditions.checkNotNull(dockerClientConfig, "config was not specified"); + this.dockerClientConfig = dockerClientConfig; + } + + private static DockerClientConfig configWithServerUrl(String serverUrl) { return DockerClientConfig.createDefaultConfigBuilder() .withUri(serverUrl) .build(); } - - public DockerClientImpl(DockerClientConfig dockerClientConfig) { - Preconditions.checkNotNull(dockerClientConfig, "config was not specified"); - this.dockerClientConfig = dockerClientConfig; - setDockerCmdExecFactory(new DockerCmdExecFactoryImpl()); + + public static DockerClientImpl getInstance() { + return new DockerClientImpl(); + } + + public static DockerClientImpl getInstance(DockerClientConfig dockerClientConfig) { + return new DockerClientImpl(dockerClientConfig); + } + + public static DockerClientImpl getInstance(String serverUrl) { + return new DockerClientImpl(serverUrl); } - public void setDockerCmdExecFactory( + public DockerClient withDockerCmdExecFactory( DockerCmdExecFactory dockerCmdExecFactory) { Preconditions.checkNotNull(dockerCmdExecFactory, "dockerCmdExecFactory was not specified"); this.dockerCmdExecFactory = dockerCmdExecFactory; this.dockerCmdExecFactory.init(dockerClientConfig); + return this; } - public DockerCmdExecFactory getDockerCmdExecFactory() { + private DockerCmdExecFactory getDockerCmdExecFactory() { + Preconditions.checkNotNull(dockerCmdExecFactory, "dockerCmdExecFactory was not specified"); return dockerCmdExecFactory; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerClientFactory.java b/src/main/java/com/github/dockerjava/jaxrs/DockerClientFactory.java new file mode 100644 index 00000000..989bf959 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerClientFactory.java @@ -0,0 +1,24 @@ +package com.github.dockerjava.jaxrs; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.core.DockerClientConfig; +import com.github.dockerjava.core.DockerClientImpl; + +public class DockerClientFactory { + + public static DockerClient getInstance() { + return withDockerCmdExecFactory(DockerClientImpl.getInstance()); + } + + public static DockerClient getInstance(DockerClientConfig dockerClientConfig) { + return withDockerCmdExecFactory(DockerClientImpl.getInstance(dockerClientConfig)); + } + + public static DockerClient getInstance(String serverUrl) { + return withDockerCmdExecFactory(DockerClientImpl.getInstance(serverUrl)); + } + + private static DockerClient withDockerCmdExecFactory(DockerClientImpl dockerClient) { + return dockerClient.withDockerCmdExecFactory(new DockerCmdExecFactoryImpl()); + } +} diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index e5aed596..fd1d4f23 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -3,6 +3,7 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.DockerException; import com.github.dockerjava.core.DockerClientImpl; +import com.github.dockerjava.jaxrs.DockerClientFactory; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; @@ -34,7 +35,7 @@ public abstract class AbstractDockerClientTest extends Assert { public void beforeTest() { LOG.info("======================= BEFORETEST ======================="); LOG.info("Connecting to Docker server"); - dockerClient = new DockerClientImpl(); + dockerClient = DockerClientFactory.getInstance(); LOG.info("Pulling image 'busybox'"); // need to block until image is pulled completely diff --git a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java index fbd1d171..067d14a2 100644 --- a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java @@ -15,6 +15,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.core.DockerClientConfig; import com.github.dockerjava.core.DockerClientImpl; +import com.github.dockerjava.jaxrs.DockerClientFactory; public class AuthCmdImplTest extends AbstractDockerClientTest { @@ -46,7 +47,7 @@ public void testAuth() throws Exception { @Test public void testAuthInvalid() throws Exception { DockerClientConfig config = DockerClientConfig.createDefaultConfigBuilder().withPassword("garbage").build(); - DockerClient client = new DockerClientImpl(config); + DockerClient client = DockerClientFactory.getInstance(config); try { client.authCmd().exec(); From 218ab1e396d5ac742cd2b37561d4cf67e7f44359 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 12 Sep 2014 21:58:09 +0200 Subject: [PATCH 109/452] Added CapAdd and CapDrop functionality --- README.md | 24 ++++++++++---- .../api/command/CreateImageCmd.java | 2 ++ .../api/command/InspectContainerResponse.java | 14 ++++++++ .../api/command/StartContainerCmd.java | 16 ++++++++-- .../core/command/StartContainerCmdImpl.java | 32 +++++++++++++++++-- .../dockerjava/jaxrs/CreateImageCmdExec.java | 1 - src/main/resources/docker.io.properties | 2 +- .../command/StartContainerCmdImplTest.java | 30 +++++++++++++++++ 8 files changed, 108 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 3ec79e1e..3c6111cf 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Java API client for [Docker](http://docs.docker.io/ "Docker") -Supports a subset of the Docker Client API v1.13, Docker Server version 1.1 +Supports a subset of the Docker Client API v1.14, Docker Server version 1.2.0 Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/docker-java-dev "docker-java") @@ -31,17 +31,19 @@ Now make sure that docker is up: $ docker -H tcp://127.0.0.1:2375 version Client version: 0.8.0 - Go version (client): go1.2 - Git commit (client): cc3a8c8 - Server version: 1.0.0 - Git commit (server): 63fe64c - Go version (server): go1.2.1 + Go version (client): go1.2 + Git commit (client): cc3a8c8 + Server version: 1.2.0 + Git commit (server): fa7b24f + Go version (server): go1.3.1 Run build with tests: $ mvn clean install -DskipTests=false -## Docker-Java maven dependency: +## Docker-Java maven dependencies + +### Latest release version com.github.docker-java @@ -49,6 +51,14 @@ Run build with tests: 0.10.0 +### Latest SNAPSHOT version + + + com.github.docker-java + docker-java + 0.10.1-SNAPSHOT + + Latest SNAPSHOT is published to maven repo: https://oss.sonatype.org/content/groups/public via ![Build on CloudBees](http://cloudbees.prod.acquia-sites.com/sites/default/files/styles/large/public/Button-Powered-by-CB.png?itok=uMDWINfY) ## Documentation diff --git a/src/main/java/com/github/dockerjava/api/command/CreateImageCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateImageCmd.java index 5d7fc990..d2682471 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateImageCmd.java @@ -6,6 +6,7 @@ public interface CreateImageCmd extends DockerCmd { public String getRepository(); + // TODO remove method public String getTag(); public InputStream getImageStream(); @@ -22,6 +23,7 @@ public interface CreateImageCmd extends DockerCmd { /** * @param tag any tag for this image + * @deprecated use repo:tag format for repository */ public CreateImageCmd withTag(String tag); diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java index 34bc15af..06e1ca0e 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java @@ -270,6 +270,12 @@ public class HostConfig { @JsonProperty("NetworkMode") private String networkMode; + + @JsonProperty("CapAdd") + private String[] capAdd; + + @JsonProperty("CapDrop") + private String[] capDrop; public String[] getBinds() { return binds; @@ -314,6 +320,14 @@ public String[] getLinks() { public String getNetworkMode() { return networkMode; } + + public String[] getCapAdd() { + return capAdd; + } + + public String[] getCapDrop() { + return capDrop; + } @Override public String toString() { diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index 8f0a9d8c..f6dcd94a 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -29,6 +29,12 @@ public interface StartContainerCmd extends DockerCmd { public String getVolumesFrom(); public String getContainerId(); + + public String getNetworkMode(); + + public String[] getCapAdd(); + + public String[] getCapDrop(); public StartContainerCmd withBinds(Bind... binds); @@ -47,6 +53,12 @@ public interface StartContainerCmd extends DockerCmd { public StartContainerCmd withVolumesFrom(String volumesFrom); public StartContainerCmd withContainerId(String containerId); + + public StartContainerCmd withNetworkMode(String networkMode); + + public StartContainerCmd withCapAdd(String... capAdd); + + public StartContainerCmd withCapDrop(String... capDrop); /** * @throws NotFoundException No such container @@ -54,9 +66,9 @@ public interface StartContainerCmd extends DockerCmd { */ public Void exec() throws NotFoundException, NotModifiedException; - public abstract String getNetworkMode(); + - public abstract StartContainerCmd withNetworkMode(String networkMode); + public static interface Exec extends DockerCmdExec { } diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index 97ebba1d..69847a3d 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; - import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; import com.github.dockerjava.api.command.StartContainerCmd; @@ -14,7 +13,6 @@ import com.github.dockerjava.api.model.Links; import com.github.dockerjava.api.model.LxcConf; import com.github.dockerjava.api.model.Ports; - import com.google.common.base.Preconditions; /** @@ -51,6 +49,12 @@ public class StartContainerCmdImpl extends AbstrDockerCmd Date: Sat, 13 Sep 2014 01:19:26 +0200 Subject: [PATCH 110/452] Fixed missing http entity (json) logging --- .../github/dockerjava/core/SelectiveLoggingFilter.java | 7 ++++++- .../github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java | 8 +++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/SelectiveLoggingFilter.java b/src/main/java/com/github/dockerjava/core/SelectiveLoggingFilter.java index 114e658f..ca79ea70 100644 --- a/src/main/java/com/github/dockerjava/core/SelectiveLoggingFilter.java +++ b/src/main/java/com/github/dockerjava/core/SelectiveLoggingFilter.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.util.Set; +import java.util.logging.Logger; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.core.HttpHeaders; @@ -25,7 +26,11 @@ public class SelectiveLoggingFilter extends LoggingFilter { .add("application/tar") .build(); - @Override + public SelectiveLoggingFilter(Logger logger, boolean b) { + super(logger, b); + } + + @Override public void filter(ClientRequestContext context) throws IOException { // Unless the content type is in the list of those we want to ellide, then just have // our super-class handle things. diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index ad9a059a..79ab7a9f 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -1,6 +1,7 @@ package com.github.dockerjava.jaxrs; import java.io.IOException; +import java.util.logging.Logger; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; @@ -52,6 +53,9 @@ public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { private WebTarget baseResource; + private static final Logger LOGGER = Logger.getLogger(DockerCmdExecFactoryImpl.class.getName()); + + @Override public void init(DockerClientConfig dockerClientConfig) { Preconditions.checkNotNull(dockerClientConfig, "config was not specified"); @@ -62,9 +66,11 @@ public void init(DockerClientConfig dockerClientConfig) { clientConfig.register(JacksonJsonProvider.class); if (dockerClientConfig.isLoggingFilterEnabled()) { - clientConfig.register(SelectiveLoggingFilter.class); + clientConfig.register(new SelectiveLoggingFilter(LOGGER, true)); } + //clientConfig.register(new LoggingFilter(LOGGER, true)); + if (dockerClientConfig.getReadTimeout() != null) { int readTimeout = dockerClientConfig.getReadTimeout(); clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); From 2b7e714fab87af93d6b6fdeb3a7f84f99e8097c8 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 13 Sep 2014 01:20:42 +0200 Subject: [PATCH 111/452] Added devices support for start and inspect container --- .../api/command/InspectContainerResponse.java | 7 ++ .../api/command/StartContainerCmd.java | 5 ++ .../github/dockerjava/api/model/Device.java | 64 +++++++++++++++++++ .../core/command/StartContainerCmdImpl.java | 23 +++++++ .../command/StartContainerCmdImplTest.java | 30 ++++++++- 5 files changed, 127 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/Device.java diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java index 06e1ca0e..146e6e8c 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java @@ -271,6 +271,9 @@ public class HostConfig { @JsonProperty("NetworkMode") private String networkMode; + @JsonProperty("Devices") + private Device[] devices; + @JsonProperty("CapAdd") private String[] capAdd; @@ -321,6 +324,10 @@ public String getNetworkMode() { return networkMode; } + public Device[] getDevices() { + return devices; + } + public String[] getCapAdd() { return capAdd; } diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index f6dcd94a..9e21b919 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -3,6 +3,7 @@ import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; import com.github.dockerjava.api.model.Bind; +import com.github.dockerjava.api.model.Device; import com.github.dockerjava.api.model.Link; import com.github.dockerjava.api.model.LxcConf; import com.github.dockerjava.api.model.Ports; @@ -32,6 +33,8 @@ public interface StartContainerCmd extends DockerCmd { public String getNetworkMode(); + public Device[] getDevices(); + public String[] getCapAdd(); public String[] getCapDrop(); @@ -56,6 +59,8 @@ public interface StartContainerCmd extends DockerCmd { public StartContainerCmd withNetworkMode(String networkMode); + public StartContainerCmd withDevices(Device... devices); + public StartContainerCmd withCapAdd(String... capAdd); public StartContainerCmd withCapDrop(String... capDrop); diff --git a/src/main/java/com/github/dockerjava/api/model/Device.java b/src/main/java/com/github/dockerjava/api/model/Device.java new file mode 100644 index 00000000..b0b32515 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/Device.java @@ -0,0 +1,64 @@ +package com.github.dockerjava.api.model; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.common.base.Preconditions; + +public class Device { + + @JsonProperty("CgroupPermissions") + private String cGroupPermissions = ""; + + @JsonProperty("PathOnHost") + private String pathOnHost = null; + + @JsonProperty("PathInContainer") + private String pathInContainer = null; + + public Device() { + } + + public Device(String cGroupPermissions, String pathInContainer, + String pathOnHost) { + Preconditions.checkNotNull(cGroupPermissions, + "cGroupPermissions is null"); + Preconditions.checkNotNull(pathInContainer, "pathInContainer is null"); + Preconditions.checkNotNull(pathOnHost, "pathOnHost is null"); + this.cGroupPermissions = cGroupPermissions; + this.pathInContainer = pathInContainer; + this.pathOnHost = pathOnHost; + } + + public String getcGroupPermissions() { + return cGroupPermissions; + } + + public String getPathInContainer() { + return pathInContainer; + } + + public String getPathOnHost() { + return pathOnHost; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Device) { + Device other = (Device) obj; + return new EqualsBuilder() + .append(cGroupPermissions, other.getcGroupPermissions()) + .append(pathInContainer, other.getPathInContainer()) + .append(pathOnHost, other.getPathOnHost()).isEquals(); + } else + return super.equals(obj); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(cGroupPermissions) + .append(pathInContainer).append(pathOnHost).toHashCode(); + } + +} diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index 69847a3d..1924a439 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -9,6 +9,7 @@ import com.github.dockerjava.api.command.StartContainerCmd; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Binds; +import com.github.dockerjava.api.model.Device; import com.github.dockerjava.api.model.Link; import com.github.dockerjava.api.model.Links; import com.github.dockerjava.api.model.LxcConf; @@ -49,6 +50,9 @@ public class StartContainerCmdImpl extends AbstrDockerCmd Date: Sat, 13 Sep 2014 01:21:00 +0200 Subject: [PATCH 112/452] Code cleanup --- .../dockerjava/api/model/AuthConfig.java | 5 +- .../com/github/dockerjava/api/model/Bind.java | 99 +++++-------------- .../dockerjava/api/model/Container.java | 5 +- .../github/dockerjava/api/model/Image.java | 5 +- .../com/github/dockerjava/api/model/Info.java | 10 +- .../dockerjava/api/model/VolumeBinds.java | 18 ++-- 6 files changed, 47 insertions(+), 95 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/model/AuthConfig.java b/src/main/java/com/github/dockerjava/api/model/AuthConfig.java index 3c61fe4d..7212d823 100644 --- a/src/main/java/com/github/dockerjava/api/model/AuthConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/AuthConfig.java @@ -1,15 +1,18 @@ package com.github.dockerjava.api.model; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; 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/"; diff --git a/src/main/java/com/github/dockerjava/api/model/Bind.java b/src/main/java/com/github/dockerjava/api/model/Bind.java index 020c708a..6779e258 100644 --- a/src/main/java/com/github/dockerjava/api/model/Bind.java +++ b/src/main/java/com/github/dockerjava/api/model/Bind.java @@ -1,38 +1,20 @@ package com.github.dockerjava.api.model; -import java.io.IOException; -import java.util.Map.Entry; - import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; -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.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.node.NullNode; - -//@JsonDeserialize(using = Bind.Deserializer.class) -//@JsonSerialize(using = Bind.Serializer.class) public class Bind { private String path; - + private Volume volume; - + private boolean readOnly = false; public Bind(String path, Volume volume) { this(path, volume, false); } - + public Bind(String path, Volume volume, boolean readOnly) { this.path = path; this.volume = volume; @@ -54,21 +36,25 @@ public boolean isReadOnly() { public static Bind parse(String serialized) { try { String[] parts = serialized.split(":"); - switch(parts.length) { - case 2: { - return new Bind(parts[0], Volume.parse(parts[1])); - } - case 3: { - if("rw".equals(parts[3].toLowerCase())) - return new Bind(parts[0], Volume.parse(parts[1]), true); - else throw new RuntimeException("Error parsing Bind '" + serialized + "'"); - } - default: { - throw new RuntimeException("Error parsing Bind '" + serialized + "'"); - } + switch (parts.length) { + case 2: { + return new Bind(parts[0], Volume.parse(parts[1])); + } + case 3: { + if ("rw".equals(parts[3].toLowerCase())) + return new Bind(parts[0], Volume.parse(parts[1]), true); + else + throw new RuntimeException("Error parsing Bind '" + + serialized + "'"); + } + default: { + throw new RuntimeException("Error parsing Bind '" + serialized + + "'"); + } } } catch (Exception e) { - throw new RuntimeException("Error parsing Bind '" + serialized + "'"); + throw new RuntimeException("Error parsing Bind '" + serialized + + "'"); } } @@ -76,51 +62,16 @@ public static Bind parse(String serialized) { public boolean equals(Object obj) { if (obj instanceof Bind) { Bind other = (Bind) obj; - return new EqualsBuilder().append(path, other.getPath()).append(volume, other.getVolume()).append(readOnly, other.isReadOnly()) - .isEquals(); + return new EqualsBuilder().append(path, other.getPath()) + .append(volume, other.getVolume()) + .append(readOnly, other.isReadOnly()).isEquals(); } else return super.equals(obj); } @Override public int hashCode() { - return new HashCodeBuilder().append(path).append(volume).append(readOnly).toHashCode(); + return new HashCodeBuilder().append(path).append(volume) + .append(readOnly).toHashCode(); } - - public static class Serializer extends JsonSerializer { - - @Override - public void serialize(Bind bind, JsonGenerator jsonGen, - SerializerProvider serProvider) throws IOException, - JsonProcessingException { - - - - //jsonGen.writeStartObject(); - //jsonGen.writeFieldName(s); -// jsonGen.writeStartObject(); -// jsonGen.writeEndObject(); -// jsonGen.writeEndObject(); - } - - } - - public static class Deserializer extends JsonDeserializer { - @Override - public Bind deserialize(JsonParser jsonParser, - DeserializationContext deserializationContext) - throws IOException, JsonProcessingException { - ObjectCodec oc = jsonParser.getCodec(); - JsonNode node = oc.readTree(jsonParser); - if (!node.equals(NullNode.getInstance())) { - Entry field = node.fields().next(); - return Bind.parse(field.getKey()); - } else { - return null; - } - } - } - - - } diff --git a/src/main/java/com/github/dockerjava/api/model/Container.java b/src/main/java/com/github/dockerjava/api/model/Container.java index eaa88e0a..5b38ce48 100644 --- a/src/main/java/com/github/dockerjava/api/model/Container.java +++ b/src/main/java/com/github/dockerjava/api/model/Container.java @@ -1,10 +1,9 @@ package com.github.dockerjava.api.model; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang.builder.ToStringBuilder; -import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; /** * diff --git a/src/main/java/com/github/dockerjava/api/model/Image.java b/src/main/java/com/github/dockerjava/api/model/Image.java index 248b7f5c..8c694dab 100644 --- a/src/main/java/com/github/dockerjava/api/model/Image.java +++ b/src/main/java/com/github/dockerjava/api/model/Image.java @@ -1,10 +1,9 @@ package com.github.dockerjava.api.model; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang.builder.ToStringBuilder; -import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; /** * diff --git a/src/main/java/com/github/dockerjava/api/model/Info.java b/src/main/java/com/github/dockerjava/api/model/Info.java index 8979593a..f71b75c9 100644 --- a/src/main/java/com/github/dockerjava/api/model/Info.java +++ b/src/main/java/com/github/dockerjava/api/model/Info.java @@ -1,16 +1,16 @@ package com.github.dockerjava.api.model; +import java.util.List; + +import org.apache.commons.lang.builder.ToStringBuilder; + import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import org.apache.commons.lang.builder.ToStringBuilder; - -import java.util.Arrays; -import java.util.List; -/** +/**Ø * * @author Konstantin Pelykh (kpelykh@gmail.com) * diff --git a/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java b/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java index fd0223ca..62ebc118 100644 --- a/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java +++ b/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java @@ -1,20 +1,20 @@ package com.github.dockerjava.api.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.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.node.NullNode; + // This is not going to be serialized @JsonDeserialize(using = VolumeBinds.Deserializer.class) public class VolumeBinds { From 170826719cf0f49e01e7fa3a93247bd167ce1379 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sat, 13 Sep 2014 01:21:59 +0200 Subject: [PATCH 113/452] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3c6111cf..f63d4096 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ For code examples, please look at the [Wiki](https://github.com/docker-java/dock There are a couple of configuration items, all of which have sensible defaults: * `url` The Docker URL, e.g. `http://localhost:2375`. -* `version` The API version, e.g. `1.13`. +* `version` The API version, e.g. `1.14`. * `username` Your repository username (required to push containers). * `password` Your repository password. * `email` Your repository email. @@ -81,7 +81,7 @@ There are three ways to configure, in descending order of precedence: In your application, e.g. DockerClientConfig config = DockerClientConfig.createDefaultConfigBuilder(); - config.withVersion("1.12"); + config.withVersion("1.14"); config.withUsername("dockeruser"); config.withPassword("ilovedocker"); config.withEmail("dockeruser@github.com); From 4efff138c0f2c89078f4f93417aae8b2e14ec7bf Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 13 Sep 2014 11:59:27 +0200 Subject: [PATCH 114/452] Replace DockerClientFactory with DockerClientBuilder --- .../dockerjava/core/DockerClientImpl.java | 2 +- .../dockerjava/jaxrs/DockerClientBuilder.java | 46 +++++++++++++++++++ .../dockerjava/jaxrs/DockerClientFactory.java | 24 ---------- .../client/AbstractDockerClientTest.java | 4 +- .../core/command/AuthCmdImplTest.java | 4 +- 5 files changed, 51 insertions(+), 29 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/jaxrs/DockerClientBuilder.java delete mode 100644 src/main/java/com/github/dockerjava/jaxrs/DockerClientFactory.java diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index ba90156d..1f4590b9 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -56,7 +56,7 @@ public static DockerClientImpl getInstance(String serverUrl) { return new DockerClientImpl(serverUrl); } - public DockerClient withDockerCmdExecFactory( + public DockerClientImpl withDockerCmdExecFactory( DockerCmdExecFactory dockerCmdExecFactory) { Preconditions.checkNotNull(dockerCmdExecFactory, "dockerCmdExecFactory was not specified"); this.dockerCmdExecFactory = dockerCmdExecFactory; diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerClientBuilder.java b/src/main/java/com/github/dockerjava/jaxrs/DockerClientBuilder.java new file mode 100644 index 00000000..96065b20 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerClientBuilder.java @@ -0,0 +1,46 @@ +package com.github.dockerjava.jaxrs; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.DockerCmdExecFactory; +import com.github.dockerjava.core.DockerClientConfig; +import com.github.dockerjava.core.DockerClientImpl; + +public class DockerClientBuilder { + + private DockerClientImpl dockerClient = null; + + private DockerClientBuilder(DockerClientImpl dockerClient) { + this.dockerClient = dockerClient; + } + + public static DockerClientBuilder getInstance() { + return new DockerClientBuilder(withDefaultDockerCmdExecFactory(DockerClientImpl.getInstance())); + } + + public static DockerClientBuilder getInstance(DockerClientConfig dockerClientConfig) { + return new DockerClientBuilder(withDefaultDockerCmdExecFactory(DockerClientImpl + .getInstance(dockerClientConfig))); + } + + public static DockerClientBuilder getInstance(String serverUrl) { + return new DockerClientBuilder(withDefaultDockerCmdExecFactory(DockerClientImpl + .getInstance(serverUrl))); + } + + private static DockerClientImpl withDefaultDockerCmdExecFactory( + DockerClientImpl dockerClient) { + return dockerClient + .withDockerCmdExecFactory(new DockerCmdExecFactoryImpl()); + } + + public DockerClientBuilder withDockerCmdExecFactory( + DockerCmdExecFactory dockerCmdExecFactory) { + dockerClient = dockerClient + .withDockerCmdExecFactory(dockerCmdExecFactory); + return this; + } + + public DockerClient build() { + return dockerClient; + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerClientFactory.java b/src/main/java/com/github/dockerjava/jaxrs/DockerClientFactory.java deleted file mode 100644 index 989bf959..00000000 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerClientFactory.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.github.dockerjava.jaxrs; - -import com.github.dockerjava.api.DockerClient; -import com.github.dockerjava.core.DockerClientConfig; -import com.github.dockerjava.core.DockerClientImpl; - -public class DockerClientFactory { - - public static DockerClient getInstance() { - return withDockerCmdExecFactory(DockerClientImpl.getInstance()); - } - - public static DockerClient getInstance(DockerClientConfig dockerClientConfig) { - return withDockerCmdExecFactory(DockerClientImpl.getInstance(dockerClientConfig)); - } - - public static DockerClient getInstance(String serverUrl) { - return withDockerCmdExecFactory(DockerClientImpl.getInstance(serverUrl)); - } - - private static DockerClient withDockerCmdExecFactory(DockerClientImpl dockerClient) { - return dockerClient.withDockerCmdExecFactory(new DockerCmdExecFactoryImpl()); - } -} diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index fd1d4f23..14f3091c 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -3,7 +3,7 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.DockerException; import com.github.dockerjava.core.DockerClientImpl; -import com.github.dockerjava.jaxrs.DockerClientFactory; +import com.github.dockerjava.jaxrs.DockerClientBuilder; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; @@ -35,7 +35,7 @@ public abstract class AbstractDockerClientTest extends Assert { public void beforeTest() { LOG.info("======================= BEFORETEST ======================="); LOG.info("Connecting to Docker server"); - dockerClient = DockerClientFactory.getInstance(); + dockerClient = DockerClientBuilder.getInstance().build(); LOG.info("Pulling image 'busybox'"); // need to block until image is pulled completely diff --git a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java index 067d14a2..9f1b0d5c 100644 --- a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java @@ -15,7 +15,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.core.DockerClientConfig; import com.github.dockerjava.core.DockerClientImpl; -import com.github.dockerjava.jaxrs.DockerClientFactory; +import com.github.dockerjava.jaxrs.DockerClientBuilder; public class AuthCmdImplTest extends AbstractDockerClientTest { @@ -47,7 +47,7 @@ public void testAuth() throws Exception { @Test public void testAuthInvalid() throws Exception { DockerClientConfig config = DockerClientConfig.createDefaultConfigBuilder().withPassword("garbage").build(); - DockerClient client = DockerClientFactory.getInstance(config); + DockerClient client = DockerClientBuilder.getInstance(config).build(); try { client.authCmd().exec(); From b5ec4f0eba027781a1fe280362a494a0332eca0d Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 13 Sep 2014 12:26:14 +0200 Subject: [PATCH 115/452] Added RestartPolicy handling --- .../api/command/InspectContainerResponse.java | 7 ++ .../api/command/StartContainerCmd.java | 5 ++ .../dockerjava/api/model/RestartPolicy.java | 75 +++++++++++++++++++ .../core/command/StartContainerCmdImpl.java | 23 ++++-- .../command/StartContainerCmdImplTest.java | 28 +++++++ 5 files changed, 131 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/RestartPolicy.java diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java index 146e6e8c..7c44e77a 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java @@ -274,6 +274,9 @@ public class HostConfig { @JsonProperty("Devices") private Device[] devices; + @JsonProperty("RestartPolicy") + private RestartPolicy restartPolicy; + @JsonProperty("CapAdd") private String[] capAdd; @@ -328,6 +331,10 @@ public Device[] getDevices() { return devices; } + public RestartPolicy getRestartPolicy() { + return restartPolicy; + } + public String[] getCapAdd() { return capAdd; } diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index 9e21b919..ab0798eb 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -7,6 +7,7 @@ import com.github.dockerjava.api.model.Link; import com.github.dockerjava.api.model.LxcConf; import com.github.dockerjava.api.model.Ports; +import com.github.dockerjava.api.model.RestartPolicy; /** * Start a container @@ -35,6 +36,8 @@ public interface StartContainerCmd extends DockerCmd { public Device[] getDevices(); + public RestartPolicy getRestartPolicy(); + public String[] getCapAdd(); public String[] getCapDrop(); @@ -61,6 +64,8 @@ public interface StartContainerCmd extends DockerCmd { public StartContainerCmd withDevices(Device... devices); + public StartContainerCmd withRestartPolicy(RestartPolicy restartPolicy); + public StartContainerCmd withCapAdd(String... capAdd); public StartContainerCmd withCapDrop(String... capDrop); diff --git a/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java b/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java new file mode 100644 index 00000000..936a5b81 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java @@ -0,0 +1,75 @@ +package com.github.dockerjava.api.model; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.common.base.Preconditions; + +/** + * Container restart policy + * + * no – Do not restart the container if it dies. (default) + * on-failure – Restart the container if it exits with a non-zero exit code. + * Can also accept an optional maximum restart count (e.g. on-failure:5). + * always – Always restart the container no matter what exit code is returned. + * + * @author marcus + * + */ +public class RestartPolicy { + + @JsonProperty("MaximumRetryCount") + private int maximumRetryCount = 0; + + @JsonProperty("Name") + private String name = "no"; + + public RestartPolicy() { + } + + private RestartPolicy(int maximumRetryCount, String name) { + Preconditions.checkNotNull(name, "name is null"); + this.maximumRetryCount = maximumRetryCount; + this.name = name; + } + + public static RestartPolicy noRestart() { + return new RestartPolicy(); + } + + public static RestartPolicy alwaysRestart() { + return new RestartPolicy(0, "always"); + } + + public static RestartPolicy onFailureRestart(int maximumRetryCount) { + return new RestartPolicy(maximumRetryCount, "on-failure"); + } + + public int getMaximumRetryCount() { + return maximumRetryCount; + } + + public String getName() { + return name; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof RestartPolicy) { + RestartPolicy other = (RestartPolicy) obj; + return new EqualsBuilder() + .append(maximumRetryCount, other.getMaximumRetryCount()) + .append(name, other.getName()) + .isEquals(); + } else + return super.equals(obj); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(maximumRetryCount) + .append(name).toHashCode(); + } + +} diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index 1924a439..f7a1c9c3 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -14,6 +14,7 @@ import com.github.dockerjava.api.model.Links; import com.github.dockerjava.api.model.LxcConf; import com.github.dockerjava.api.model.Ports; +import com.github.dockerjava.api.model.RestartPolicy; import com.google.common.base.Preconditions; /** @@ -53,6 +54,9 @@ public class StartContainerCmdImpl extends AbstrDockerCmd Date: Sat, 13 Sep 2014 12:36:51 +0200 Subject: [PATCH 116/452] [maven-release-plugin] prepare release docker-java-0.10.1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index b9f6c757..a531b11d 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.1-SNAPSHOT + 0.10.1 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-0.10.1 From feb82c156a6377fa4f2552b55ca69040bb3a2aa1 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 13 Sep 2014 12:36:56 +0200 Subject: [PATCH 117/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index a531b11d..99a6c603 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.1 + 0.10.2-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.10.1 + HEAD From 3472f062afc71eac58763fee83e50fc5862569ec Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sat, 13 Sep 2014 12:40:11 +0200 Subject: [PATCH 118/452] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f63d4096..9d269649 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ Run build with tests: com.github.docker-java docker-java - 0.10.0 + 0.10.1 ### Latest SNAPSHOT version @@ -56,7 +56,7 @@ Run build with tests: com.github.docker-java docker-java - 0.10.1-SNAPSHOT + 0.10.2-SNAPSHOT Latest SNAPSHOT is published to maven repo: https://oss.sonatype.org/content/groups/public via ![Build on CloudBees](http://cloudbees.prod.acquia-sites.com/sites/default/files/styles/large/public/Button-Powered-by-CB.png?itok=uMDWINfY) From 0815e2fc7bf88f21f59ea506319c4e3797d942bb Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 13 Sep 2014 21:23:51 +0200 Subject: [PATCH 119/452] Use special DockerCmdExecFactory in tests to realize automatic image/container cleanup. --- .../jaxrs/DockerCmdExecFactoryImpl.java | 2 +- .../client/AbstractDockerClientTest.java | 18 ++-- .../dockerjava/client/DockerClientTest.java | 2 +- .../core/command/BuildImageCmdImplTest.java | 8 +- .../core/command/CommitCmdImplTest.java | 2 - .../command/ContainerDiffCmdImplTest.java | 2 +- .../CopyFileFromContainerCmdImplTest.java | 1 - .../command/CreateContainerCmdImplTest.java | 10 --- .../core/command/InfoCmdImplTest.java | 1 - .../command/KillContainerCmdImplTest.java | 1 - .../command/ListContainersCmdImplTest.java | 2 - .../core/command/LogContainerCmdImplTest.java | 2 - .../core/command/PullImageCmdImplTest.java | 2 - .../core/command/PushImageCmdImplTest.java | 4 - .../core/command/RemoveImageCmdImplTest.java | 7 +- .../command/RestartContainerCmdImplTest.java | 3 +- .../command/StartContainerCmdImplTest.java | 20 +---- .../command/StopContainerCmdImplTest.java | 3 +- .../command/WaitContainerCmdImplTest.java | 3 +- .../jaxrs/TestDockerCmdExecFactory.java | 84 +++++++++++++++++++ 20 files changed, 110 insertions(+), 67 deletions(-) create mode 100644 src/test/java/com/github/dockerjava/jaxrs/TestDockerCmdExecFactory.java diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 79ab7a9f..5975206d 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -87,7 +87,7 @@ public void init(DockerClientConfig dockerClientConfig) { } - private WebTarget getBaseResource() { + protected WebTarget getBaseResource() { Preconditions.checkNotNull(baseResource, "Factory not initialized. You probably forgot to call init()!"); return baseResource; } diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 14f3091c..3b61d636 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -4,6 +4,7 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.core.DockerClientImpl; import com.github.dockerjava.jaxrs.DockerClientBuilder; +import com.github.dockerjava.jaxrs.TestDockerCmdExecFactory; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; @@ -28,14 +29,17 @@ public abstract class AbstractDockerClientTest extends Assert { protected DockerClient dockerClient; - protected List tmpImgs; - protected List tmpContainers; +// protected List tmpImgs; +// protected List tmpContainers; + private TestDockerCmdExecFactory dockerCmdExecFactory = new TestDockerCmdExecFactory(); public void beforeTest() { LOG.info("======================= BEFORETEST ======================="); LOG.info("Connecting to Docker server"); - dockerClient = DockerClientBuilder.getInstance().build(); + dockerClient = DockerClientBuilder.getInstance() + .withDockerCmdExecFactory(dockerCmdExecFactory) + .build(); LOG.info("Pulling image 'busybox'"); // need to block until image is pulled completely @@ -53,8 +57,8 @@ public void afterTest() { public void beforeMethod(Method method) { - tmpContainers = new ArrayList(); - tmpImgs = new ArrayList(); +// tmpContainers = new ArrayList(); +// tmpImgs = new ArrayList(); LOG.info(String .format("################################## STARTING %s ##################################", method.getName())); @@ -62,7 +66,7 @@ public void beforeMethod(Method method) { public void afterMethod(ITestResult result) { - for (String container : tmpContainers) { + for (String container : dockerCmdExecFactory.getContainerIds()) { LOG.info("Cleaning up temporary container {}", container); try { dockerClient.stopContainerCmd(container).exec(); @@ -78,7 +82,7 @@ public void afterMethod(ITestResult result) { } } - for (String image : tmpImgs) { + for (String image : dockerCmdExecFactory.getImagesIds()) { LOG.info("Cleaning up temporary image {}", image); try { dockerClient.removeImageCmd(image).exec(); diff --git a/src/test/java/com/github/dockerjava/client/DockerClientTest.java b/src/test/java/com/github/dockerjava/client/DockerClientTest.java index 06852c03..b06ded00 100644 --- a/src/test/java/com/github/dockerjava/client/DockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/DockerClientTest.java @@ -62,7 +62,7 @@ public void testRunShlex() throws DockerException { CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd(commands).exec(); dockerClient.startContainerCmd(container.getId()); - tmpContainers.add(container.getId()); + int exitcode = dockerClient.waitContainerCmd(container.getId()).exec(); assertThat(exitcode, equalTo(0)); } diff --git a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index b689c81d..0cb0da80 100644 --- a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -69,7 +69,7 @@ public void testNginxDockerfileBuilder() { .inspectImageCmd(imageId).exec(); assertThat(inspectImageResponse, not(nullValue())); LOG.info("Image Inspect: {}", inspectImageResponse.toString()); - tmpImgs.add(inspectImageResponse.getId()); + //tmpImgs.add(inspectImageResponse.getId()); assertThat(inspectImageResponse.getAuthor(), equalTo("Guillaume J. Charmes \"guillaume@dotcloud.com\"")); @@ -120,7 +120,7 @@ private String dockerfileBuild(File baseDir, String expectedText) { dockerClient.startContainerCmd(container.getId()).exec(); dockerClient.waitContainerCmd(container.getId()).exec(); - tmpContainers.add(container.getId()); + //tmpContainers.add(container.getId()); // Log container InputStream logResponse = logContainer(container @@ -155,13 +155,13 @@ public void testNetCatDockerfileBuilder() throws InterruptedException { assertThat(inspectImageResponse, not(nullValue())); assertThat(inspectImageResponse.getId(), not(nullValue())); LOG.info("Image Inspect: {}", inspectImageResponse.toString()); - tmpImgs.add(inspectImageResponse.getId()); + //tmpImgs.add(inspectImageResponse.getId()); CreateContainerResponse container = dockerClient.createContainerCmd( inspectImageResponse.getId()).exec(); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); - tmpContainers.add(container.getId()); + //tmpContainers.add(container.getId()); InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); diff --git a/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java index bc69d950..78442b57 100644 --- a/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java @@ -52,12 +52,10 @@ public void commit() throws DockerException { LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); - tmpContainers.add(container.getId()); LOG.info("Commiting container: {}", container.toString()); String imageId = dockerClient .commitCmd(container.getId()).exec(); - tmpImgs.add(imageId); InspectImageResponse inspectImageResponse = dockerClient .inspectImageCmd(imageId).exec(); diff --git a/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java index c689e220..6817cc18 100644 --- a/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java @@ -51,7 +51,7 @@ public void testDiff() throws DockerException { LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); - tmpContainers.add(container.getId()); + int exitCode = dockerClient.waitContainerCmd(container.getId()).exec(); assertThat(exitCode, equalTo(0)); diff --git a/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java index 15c6d80e..467d664a 100644 --- a/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java @@ -46,7 +46,6 @@ public void copyFromContainer() throws Exception { assertThat(container.getId(), not(isEmptyOrNullString())); dockerClient.startContainerCmd(container.getId()).exec(); - tmpContainers.add(container.getId()); InputStream response = dockerClient.copyFileFromContainerCmd(container.getId(), "/test").exec(); assertTrue(response.available() > 0, "The file was not copied from the container."); diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index e0332d41..b0647e4b 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -48,8 +48,6 @@ public void createContainerWithVolume() throws DockerException { CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withVolumes(new Volume("/var/log")).withCmd("true").exec(); - tmpContainers.add(container.getId()); - LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); @@ -59,8 +57,6 @@ public void createContainerWithVolume() throws DockerException { LOG.info("Inspect container {}", inspectContainerResponse.getConfig().getVolumes()); assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), contains("/var/log")); - - } @Test @@ -69,8 +65,6 @@ public void createContainerWithEnv() throws DockerException { CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withEnv("VARIABLE=success").withCmd("env").exec(); - tmpContainers.add(container.getId()); - LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); @@ -90,8 +84,6 @@ public void createContainerWithHostname() throws DockerException { CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withHostName("docker-java").withCmd("env").exec(); - tmpContainers.add(container.getId()); - LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); @@ -111,8 +103,6 @@ public void createContainerWithName() throws DockerException { CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withName("container").withCmd("env").exec(); - tmpContainers.add(container.getId()); - LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); diff --git a/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java index c8333966..cbd55697 100644 --- a/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java @@ -53,7 +53,6 @@ public void info() throws DockerException { assertThat(container.getId(), not(isEmptyOrNullString())); dockerClient.startContainerCmd(container.getId()).exec(); - tmpContainers.add(container.getId()); Info dockerInfo = dockerClient.infoCmd().exec(); LOG.info(dockerInfo.toString()); diff --git a/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java index c68c57ef..e6507c6f 100644 --- a/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java @@ -55,7 +55,6 @@ public void testKillContainer() throws DockerException { LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); - tmpContainers.add(container.getId()); LOG.info("Killing container: {}", container.getId()); dockerClient.killContainerCmd(container.getId()).exec(); diff --git a/src/test/java/com/github/dockerjava/core/command/ListContainersCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ListContainersCmdImplTest.java index c0f85d92..49b61aab 100644 --- a/src/test/java/com/github/dockerjava/core/command/ListContainersCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ListContainersCmdImplTest.java @@ -73,9 +73,7 @@ public void testListContainers() throws DockerException { assertThat(inspectContainerResponse.getConfig().getImage(), is(equalTo(testImage))); - dockerClient.startContainerCmd(container1.getId()).exec(); - tmpContainers.add(container1.getId()); LOG.info("container id: " + container1.getId()); diff --git a/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java index 1ebcb40d..84b2a5ff 100644 --- a/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java @@ -56,8 +56,6 @@ public void logContainer() throws Exception { dockerClient.startContainerCmd(container.getId()).exec(); - tmpContainers.add(container.getId()); - int exitCode = dockerClient.waitContainerCmd(container.getId()).exec(); assertThat(exitCode, equalTo(0)); diff --git a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java index cea292ac..a3dbd64c 100644 --- a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java @@ -70,10 +70,8 @@ public void testPullImage() throws DockerException, IOException { LOG.info("Pulling image: {}", testImage); - tmpImgs.add(testImage); InputStream response = dockerClient.pullImageCmd(testImage).exec(); - assertThat(asString(response), containsString("Download complete")); diff --git a/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java index 952f0b28..b3d890ba 100644 --- a/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java @@ -57,8 +57,6 @@ public void testPushLatest() throws Exception { assertThat(container.getId(), not(isEmptyString())); - tmpContainers.add(container.getId()); - LOG.info("Commiting container: {}", container.toString()); String imageId = dockerClient.commitCmd(container.getId()).withRepository(username + "/busybox").exec(); @@ -70,8 +68,6 @@ public void testPushLatest() throws Exception { String response = asString(dockerClient.pullImageCmd(username + "/busybox").exec()); assertThat(response, not(containsString("HTTP code: 404"))); - - tmpImgs.add(username + "/busybox"); } @Test diff --git a/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java index e5bda718..c44a786c 100644 --- a/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java @@ -57,18 +57,15 @@ public void testRemoveImage() throws DockerException, InterruptedException { LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); - tmpContainers.add(container.getId()); - + LOG.info("Commiting container {}", container.toString()); String imageId = dockerClient .commitCmd(container.getId()).exec(); - tmpImgs.add(imageId); - + dockerClient.stopContainerCmd(container.getId()).exec(); dockerClient.killContainerCmd(container.getId()).exec(); dockerClient.removeContainerCmd(container.getId()).exec(); - tmpContainers.remove(container.getId()); LOG.info("Removing image: {}", imageId); dockerClient.removeImageCmd(imageId).exec(); diff --git a/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java index b637d5e7..ab947e81 100644 --- a/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java @@ -50,8 +50,7 @@ public void restartContainer() throws DockerException { LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); - tmpContainers.add(container.getId()); - + InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); LOG.info("Container Inspect: {}", inspectContainerResponse.toString()); diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index bf7f24d8..b0e0482f 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -88,7 +88,6 @@ public void startContainerWithVolumes() throws DockerException { assertThat(Arrays.asList(inspectContainerResponse.getVolumesRW()), contains(volume1, volume2)); - tmpContainers.add(container.getId()); } @Test @@ -116,7 +115,6 @@ public void startContainerWithDns() throws DockerException { assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getDns()), contains(aDnsServer, anotherDnsServer)); - tmpContainers.add(container.getId()); } @Test @@ -154,7 +152,6 @@ public void startContainerWithPortBindings() throws DockerException { assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23), is(equalTo(Ports.Binding(11023)))); - tmpContainers.add(container.getId()); } @Test @@ -165,8 +162,7 @@ public void startContainerWithLinking() throws DockerException { LOG.info("Created container1 {}", container1.toString()); assertThat(container1.getId(), not(isEmptyString())); - tmpContainers.add(container1.getId()); - + dockerClient.startContainerCmd(container1.getId()).exec(); InspectContainerResponse inspectContainerResponse1 = dockerClient @@ -191,8 +187,7 @@ public void startContainerWithLinking() throws DockerException { LOG.info("Created container2 {}", container2.toString()); assertThat(container2.getId(), not(isEmptyString())); - tmpContainers.add(container2.getId()); - + dockerClient.startContainerCmd(container2.getId()).withLinks(new Link("container1", "container1Link")).exec(); InspectContainerResponse inspectContainerResponse2 = dockerClient @@ -221,8 +216,7 @@ public void startContainer() throws DockerException { LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); - tmpContainers.add(container.getId()); - + dockerClient.startContainerCmd(container.getId()).exec(); InspectContainerResponse inspectContainerResponse = dockerClient @@ -268,8 +262,6 @@ public void startContainerWithNetworkMode() throws DockerException { assertThat(container.getId(), not(isEmptyString())); - tmpContainers.add(container.getId()); - InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); @@ -294,8 +286,6 @@ public void startContainerWithCapAddAndCapDrop() throws DockerException { assertThat(container.getId(), not(isEmptyString())); - tmpContainers.add(container.getId()); - dockerClient.startContainerCmd(container.getId()) .withCapAdd("NET_ADMIN") .withCapDrop("MKNOD").exec(); @@ -323,8 +313,6 @@ public void startContainerWithDevices() throws DockerException { assertThat(container.getId(), not(isEmptyString())); - tmpContainers.add(container.getId()); - dockerClient.startContainerCmd(container.getId()) .withDevices(new Device("rwm", "/dev/nulo", "/dev/zero")) .exec(); @@ -349,8 +337,6 @@ public void startContainerWithRestartPolicy() throws DockerException { assertThat(container.getId(), not(isEmptyString())); - tmpContainers.add(container.getId()); - RestartPolicy restartPolicy = RestartPolicy.onFailureRestart(5); dockerClient.startContainerCmd(container.getId()) diff --git a/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java index 588f3296..df0045fa 100644 --- a/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java @@ -55,8 +55,7 @@ public void testStopContainer() throws DockerException { LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); - tmpContainers.add(container.getId()); - + LOG.info("Stopping container: {}", container.getId()); dockerClient.stopContainerCmd(container.getId()).withTimeout(2).exec(); diff --git a/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java index f8d439ae..e8693de5 100644 --- a/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java @@ -50,8 +50,7 @@ public void testWaitContainer() throws DockerException { LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); - tmpContainers.add(container.getId()); - + dockerClient.startContainerCmd(container.getId()).exec(); int exitCode = dockerClient.waitContainerCmd(container.getId()).exec(); diff --git a/src/test/java/com/github/dockerjava/jaxrs/TestDockerCmdExecFactory.java b/src/test/java/com/github/dockerjava/jaxrs/TestDockerCmdExecFactory.java new file mode 100644 index 00000000..ba1d2c5c --- /dev/null +++ b/src/test/java/com/github/dockerjava/jaxrs/TestDockerCmdExecFactory.java @@ -0,0 +1,84 @@ +package com.github.dockerjava.jaxrs; + +import java.util.ArrayList; +import java.util.List; + +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.CreateImageCmd; +import com.github.dockerjava.api.command.CreateImageResponse; +import com.github.dockerjava.api.command.DockerCmdExecFactory; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.command.RemoveImageCmd; + +/** + * Special {@link DockerCmdExecFactory} implementation that collects container and image creations + * while test execution for the purpose of automatically cleanup. + * + * @author marcus + * + */ +public class TestDockerCmdExecFactory extends DockerCmdExecFactoryImpl { + + private List containerIds = new ArrayList(); + + private List imagesIds = new ArrayList(); + + @Override + public CreateContainerCmd.Exec createCreateContainerCmdExec() { + return new CreateContainerCmdExec(getBaseResource()) { + @Override + public CreateContainerResponse exec(CreateContainerCmd command) { + CreateContainerResponse createContainerResponse = super.exec(command); + containerIds.add(createContainerResponse.getId()); + return createContainerResponse; + } + }; + } + + @Override + public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { + return new RemoveContainerCmdExec(getBaseResource()) { + @Override + public Void exec(RemoveContainerCmd command) { + super.exec(command); + containerIds.remove(command.getContainerId()); + return null; + } + }; + } + + @Override + public CreateImageCmd.Exec createCreateImageCmdExec() { + return new CreateImageCmdExec(getBaseResource()) { + @Override + public CreateImageResponse exec(CreateImageCmd command) { + CreateImageResponse createImageResponse = super.exec(command); + imagesIds.add(createImageResponse.getId()); + return createImageResponse; + } + }; + } + + @Override + public RemoveImageCmd.Exec createRemoveImageCmdExec() { + return new RemoveImageCmdExec(getBaseResource()) { + @Override + public Void exec(RemoveImageCmd command) { + super.exec(command); + imagesIds.remove(command.getImageId()); + return null; + } + }; + } + + public List getContainerIds() { + return new ArrayList(containerIds); + } + + public List getImagesIds() { + return new ArrayList(imagesIds); + } + + +} From ecb631e50af2e13fa28bde85873ad671a91f55b0 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 14 Sep 2014 14:20:34 +0200 Subject: [PATCH 120/452] Fix TestDockerCmdExecFactory --- .../client/AbstractDockerClientTest.java | 50 +++++++------------ .../core/command/AuthCmdImplTest.java | 3 +- .../jaxrs/TestDockerCmdExecFactory.java | 42 ++++++++++++---- 3 files changed, 51 insertions(+), 44 deletions(-) diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 3b61d636..f8e67478 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -1,10 +1,11 @@ package com.github.dockerjava.client; -import com.github.dockerjava.api.DockerClient; -import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.core.DockerClientImpl; -import com.github.dockerjava.jaxrs.DockerClientBuilder; -import com.github.dockerjava.jaxrs.TestDockerCmdExecFactory; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.net.DatagramSocket; +import java.net.ServerSocket; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; @@ -13,14 +14,10 @@ import org.testng.Assert; import org.testng.ITestResult; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.net.DatagramSocket; -import java.net.ServerSocket; -import java.util.ArrayList; -import java.util.List; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.jaxrs.DockerClientBuilder; +import com.github.dockerjava.jaxrs.TestDockerCmdExecFactory; public abstract class AbstractDockerClientTest extends Assert { @@ -29,10 +26,7 @@ public abstract class AbstractDockerClientTest extends Assert { protected DockerClient dockerClient; -// protected List tmpImgs; -// protected List tmpContainers; - - private TestDockerCmdExecFactory dockerCmdExecFactory = new TestDockerCmdExecFactory(); + protected TestDockerCmdExecFactory dockerCmdExecFactory = new TestDockerCmdExecFactory(); public void beforeTest() { LOG.info("======================= BEFORETEST ======================="); @@ -57,8 +51,6 @@ public void afterTest() { public void beforeMethod(Method method) { -// tmpContainers = new ArrayList(); -// tmpImgs = new ArrayList(); LOG.info(String .format("################################## STARTING %s ##################################", method.getName())); @@ -66,31 +58,25 @@ public void beforeMethod(Method method) { public void afterMethod(ITestResult result) { - for (String container : dockerCmdExecFactory.getContainerIds()) { + for (String container : dockerCmdExecFactory.getContainerNames()) { LOG.info("Cleaning up temporary container {}", container); - try { - dockerClient.stopContainerCmd(container).exec(); - dockerClient.killContainerCmd(container).exec(); - } catch (DockerException ignore) { - //ignore.printStackTrace(); - } try { - dockerClient.removeContainerCmd(container).exec(); + dockerClient.removeContainerCmd(container).withForce().exec(); } catch (DockerException ignore) { ignore.printStackTrace(); } } - for (String image : dockerCmdExecFactory.getImagesIds()) { - LOG.info("Cleaning up temporary image {}", image); + for (String image : dockerCmdExecFactory.getImageNames()) { + LOG.info("Cleaning up temporary image with {}", image); try { - dockerClient.removeImageCmd(image).exec(); + dockerClient.removeImageCmd(image).withForce().exec(); } catch (DockerException ignore) { ignore.printStackTrace(); } - } - + } + LOG.info( "################################## END OF {} ##################################\n", result.getName()); diff --git a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java index 9f1b0d5c..babe6b59 100644 --- a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java @@ -14,7 +14,6 @@ import com.github.dockerjava.api.UnauthorizedException; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.core.DockerClientConfig; -import com.github.dockerjava.core.DockerClientImpl; import com.github.dockerjava.jaxrs.DockerClientBuilder; public class AuthCmdImplTest extends AbstractDockerClientTest { @@ -47,7 +46,7 @@ public void testAuth() throws Exception { @Test public void testAuthInvalid() throws Exception { DockerClientConfig config = DockerClientConfig.createDefaultConfigBuilder().withPassword("garbage").build(); - DockerClient client = DockerClientBuilder.getInstance(config).build(); + DockerClient client = DockerClientBuilder.getInstance(config).withDockerCmdExecFactory(dockerCmdExecFactory).build(); try { client.authCmd().exec(); diff --git a/src/test/java/com/github/dockerjava/jaxrs/TestDockerCmdExecFactory.java b/src/test/java/com/github/dockerjava/jaxrs/TestDockerCmdExecFactory.java index ba1d2c5c..8ff44a9a 100644 --- a/src/test/java/com/github/dockerjava/jaxrs/TestDockerCmdExecFactory.java +++ b/src/test/java/com/github/dockerjava/jaxrs/TestDockerCmdExecFactory.java @@ -1,8 +1,11 @@ package com.github.dockerjava.jaxrs; +import java.io.InputStream; +import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; +import com.github.dockerjava.api.command.BuildImageCmd; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.CreateImageCmd; @@ -20,9 +23,9 @@ */ public class TestDockerCmdExecFactory extends DockerCmdExecFactoryImpl { - private List containerIds = new ArrayList(); + private List containerNames = new ArrayList(); - private List imagesIds = new ArrayList(); + private List imageNames = new ArrayList(); @Override public CreateContainerCmd.Exec createCreateContainerCmdExec() { @@ -30,7 +33,7 @@ public CreateContainerCmd.Exec createCreateContainerCmdExec() { @Override public CreateContainerResponse exec(CreateContainerCmd command) { CreateContainerResponse createContainerResponse = super.exec(command); - containerIds.add(createContainerResponse.getId()); + containerNames.add(createContainerResponse.getId()); return createContainerResponse; } }; @@ -42,7 +45,7 @@ public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { @Override public Void exec(RemoveContainerCmd command) { super.exec(command); - containerIds.remove(command.getContainerId()); + containerNames.remove(command.getContainerId()); return null; } }; @@ -54,31 +57,50 @@ public CreateImageCmd.Exec createCreateImageCmdExec() { @Override public CreateImageResponse exec(CreateImageCmd command) { CreateImageResponse createImageResponse = super.exec(command); - imagesIds.add(createImageResponse.getId()); + imageNames.add(createImageResponse.getId()); return createImageResponse; } }; } + + @Override public RemoveImageCmd.Exec createRemoveImageCmdExec() { return new RemoveImageCmdExec(getBaseResource()) { @Override public Void exec(RemoveImageCmd command) { super.exec(command); - imagesIds.remove(command.getImageId()); + imageNames.remove(command.getImageId()); return null; } }; } - public List getContainerIds() { - return new ArrayList(containerIds); + @Override + public BuildImageCmd.Exec createBuildImageCmdExec() { + return new BuildImageCmdExec(getBaseResource()) { + @Override + public InputStream exec(BuildImageCmd command) { + // can't detect image id here so tagging it + String tag = command.getTag(); + if(tag == null || "".equals(tag.trim())) { + tag = "" + new SecureRandom().nextInt(Integer.MAX_VALUE); + command.withTag(tag); + } + InputStream inputStream = super.exec(command); + imageNames.add(tag); + return inputStream; + } + }; } - public List getImagesIds() { - return new ArrayList(imagesIds); + public List getContainerNames() { + return new ArrayList(containerNames); } + public List getImageNames() { + return new ArrayList(imageNames); + } } From 45311797c80d95f35567f8c3a2879055bdcd4896 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 14 Sep 2014 14:22:07 +0200 Subject: [PATCH 121/452] Added some shortcut methods in the API --- .../dockerjava/api/command/BuildImageCmd.java | 4 ++++ .../dockerjava/api/command/RemoveImageCmd.java | 17 ++++++++++++++++- .../core/command/BuildImageCmdImpl.java | 10 ++++++++++ .../core/command/RemoveImageCmdImpl.java | 5 +++++ .../dockerjava/jaxrs/BuildImageCmdExec.java | 2 +- 5 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java index 99afa6f1..7c2deb63 100644 --- a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java @@ -28,8 +28,12 @@ public interface BuildImageCmd extends DockerCmd{ public BuildImageCmd withNoCache(); public BuildImageCmd withNoCache(boolean noCache); + + public BuildImageCmd withRemove(); public BuildImageCmd withRemove(boolean rm); + + public BuildImageCmd withQuiet(); public BuildImageCmd withQuiet(boolean quiet); diff --git a/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java b/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java index 021a3766..212c9290 100644 --- a/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java @@ -16,11 +16,26 @@ public interface RemoveImageCmd extends DockerCmd{ public boolean hasNoPruneEnabled(); public RemoveImageCmd withImageId(String imageId); - + + /** + * force delete of an image, even if it's tagged in multiple repositories + */ public RemoveImageCmd withForce(); + /** + * force parameter to force delete of an image, even if it's tagged in multiple repositories + */ public RemoveImageCmd withForce(boolean force); + /** + * prevent the deletion of parent images + */ + public RemoveImageCmd withNoPrune(); + + /** + * noprune parameter to prevent the deletion of parent images + * + */ public RemoveImageCmd withNoPrune(boolean noPrune); /** diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 0aa09ad8..4948ce45 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -103,12 +103,22 @@ public BuildImageCmdImpl withNoCache(boolean noCache) { this.noCache = noCache; return this; } + + @Override + public BuildImageCmdImpl withRemove() { + return withRemove(true); + } @Override public BuildImageCmdImpl withRemove(boolean rm) { this.remove = rm; return this; } + + @Override + public BuildImageCmdImpl withQuiet() { + return withQuiet(true); + } @Override public BuildImageCmdImpl withQuiet(boolean quiet) { diff --git a/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java index 231fecb4..dda905fe 100644 --- a/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java @@ -53,6 +53,11 @@ public RemoveImageCmd withForce(boolean force) { this.force = force; return this; } + + @Override + public RemoveImageCmd withNoPrune() { + return withNoPrune(true); + } @Override public RemoveImageCmd withNoPrune(boolean noPrune) { diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index 866cdfd9..572f0ea7 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -39,7 +39,7 @@ public InputStream exec(BuildImageCmd command) { webResource = webResource.queryParam("q", "true"); } - LOGGER.trace("POST: {}", webResource); + LOGGER.debug("POST: {}", webResource); return webResource .request() .accept(MediaType.TEXT_PLAIN) From 8b8fc378ab00b208be1b16d0128ed17f78bab330 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 14 Sep 2014 14:22:49 +0200 Subject: [PATCH 122/452] Code formatting --- .../dockerjava/jaxrs/DockerCmdExecFactoryImpl.java | 2 -- .../core/command/BuildImageCmdImplTest.java | 13 +++---------- 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 5975206d..dfd83deb 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -68,8 +68,6 @@ public void init(DockerClientConfig dockerClientConfig) { if (dockerClientConfig.isLoggingFilterEnabled()) { clientConfig.register(new SelectiveLoggingFilter(LOGGER, true)); } - - //clientConfig.register(new LoggingFilter(LOGGER, true)); if (dockerClientConfig.getReadTimeout() != null) { int readTimeout = dockerClientConfig.getReadTimeout(); diff --git a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index 0cb0da80..353fea12 100644 --- a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -49,9 +49,7 @@ public void beforeMethod(Method method) { public void afterMethod(ITestResult result) { super.afterMethod(result); } - - @Test public void testNginxDockerfileBuilder() { File baseDir = new File(Thread.currentThread().getContextClassLoader() @@ -69,8 +67,7 @@ public void testNginxDockerfileBuilder() { .inspectImageCmd(imageId).exec(); assertThat(inspectImageResponse, not(nullValue())); LOG.info("Image Inspect: {}", inspectImageResponse.toString()); - //tmpImgs.add(inspectImageResponse.getId()); - + assertThat(inspectImageResponse.getAuthor(), equalTo("Guillaume J. Charmes \"guillaume@dotcloud.com\"")); } @@ -120,8 +117,6 @@ private String dockerfileBuild(File baseDir, String expectedText) { dockerClient.startContainerCmd(container.getId()).exec(); dockerClient.waitContainerCmd(container.getId()).exec(); - //tmpContainers.add(container.getId()); - // Log container InputStream logResponse = logContainer(container .getId()); @@ -155,14 +150,12 @@ public void testNetCatDockerfileBuilder() throws InterruptedException { assertThat(inspectImageResponse, not(nullValue())); assertThat(inspectImageResponse.getId(), not(nullValue())); LOG.info("Image Inspect: {}", inspectImageResponse.toString()); - //tmpImgs.add(inspectImageResponse.getId()); - + CreateContainerResponse container = dockerClient.createContainerCmd( inspectImageResponse.getId()).exec(); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); - //tmpContainers.add(container.getId()); - + InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); From 0abdfebe4e46ddfa178c05ce6d8be27b87c2e312 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 17 Sep 2014 19:47:42 +0200 Subject: [PATCH 123/452] Fix for Issue#54 Missing DnsSearch Option --- .../github/dockerjava/api/DockerClient.java | 1 + .../dockerjava/api/command/CommitCmd.java | 2 -- .../api/command/InspectContainerResponse.java | 8 +++---- .../api/command/StartContainerCmd.java | 6 +++++ .../core/command/StartContainerCmdImpl.java | 15 ++++++++++++ .../command/StartContainerCmdImplTest.java | 24 +++++++++++++++++++ 6 files changed, 50 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index 3420773a..15e66bef 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -34,6 +34,7 @@ import com.github.dockerjava.api.command.WaitContainerCmd; import com.github.dockerjava.api.model.AuthConfig; +// https://godoc.org/github.com/fsouza/go-dockerclient public interface DockerClient extends Closeable { public AuthConfig authConfig() throws DockerException; diff --git a/src/main/java/com/github/dockerjava/api/command/CommitCmd.java b/src/main/java/com/github/dockerjava/api/command/CommitCmd.java index effb8292..5eb5a3e8 100644 --- a/src/main/java/com/github/dockerjava/api/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CommitCmd.java @@ -1,7 +1,5 @@ package com.github.dockerjava.api.command; -import java.io.InputStream; - import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.model.ExposedPorts; import com.github.dockerjava.api.model.Volumes; diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java index 7c44e77a..32156745 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java @@ -254,6 +254,9 @@ public class HostConfig { @JsonProperty("Dns") private String[] dns; + + @JsonProperty("DnsSearch") + private String[] dnsSearch; @JsonProperty("VolumesFrom") private String[] volumesFrom; @@ -261,9 +264,6 @@ public class HostConfig { @JsonProperty("ContainerIDFile") private String containerIDFile; - @JsonProperty("DnsSearch") - private String dnsSearch; - // TODO: use Links class here? @JsonProperty("Links") private String[] links; @@ -315,7 +315,7 @@ public String getContainerIDFile() { return containerIDFile; } - public String getDnsSearch() { + public String[] getDnsSearch() { return dnsSearch; } diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index ab0798eb..54c7b144 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -27,6 +27,8 @@ public interface StartContainerCmd extends DockerCmd { public boolean isPrivileged(); public String[] getDns(); + + public String[] getDnsSearch(); public String getVolumesFrom(); @@ -54,7 +56,11 @@ public interface StartContainerCmd extends DockerCmd { public StartContainerCmd withPublishAllPorts(boolean publishAllPorts); + // Set custom DNS servers public StartContainerCmd withDns(String... dns); + + // Set custom DNS search domains + public StartContainerCmd withDnsSearch(String... dnsSearch); public StartContainerCmd withVolumesFrom(String volumesFrom); diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index f7a1c9c3..9cf83083 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -44,6 +44,9 @@ public class StartContainerCmdImpl extends AbstrDockerCmd Date: Thu, 18 Sep 2014 10:43:39 +0200 Subject: [PATCH 124/452] Update README.md Since the version 0.10.1, the constructor for DockerClientImpl is now private. --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9d269649..77b1c2c7 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,10 @@ In your application, e.g. config.withUsername("dockeruser"); config.withPassword("ilovedocker"); config.withEmail("dockeruser@github.com); - DockerClient docker = new DockerClientImpl(config); + DockerClient docker = DockerClientBuilder + .getInstance( config ) + .withDockerCmdExecFactory( new DockerCmdExecFactoryImpl()) + .build(); ##### System Properties: E.g. From 59160250f02fe303cfaebf5b477d517ac9c01825 Mon Sep 17 00:00:00 2001 From: Vincent Zurczak Date: Thu, 18 Sep 2014 11:04:07 +0200 Subject: [PATCH 125/452] Update README.md (again) The DockerCmdExecFactoryImpl is in fact useless --- README.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/README.md b/README.md index 77b1c2c7..6dcb096e 100644 --- a/README.md +++ b/README.md @@ -85,10 +85,7 @@ In your application, e.g. config.withUsername("dockeruser"); config.withPassword("ilovedocker"); config.withEmail("dockeruser@github.com); - DockerClient docker = DockerClientBuilder - .getInstance( config ) - .withDockerCmdExecFactory( new DockerCmdExecFactoryImpl()) - .build(); + DockerClient docker = DockerClientBuilder.getInstance( config ).build(); ##### System Properties: E.g. From 17c7a353e3b7c9b93ce27dc2e7ff3546aeb361a6 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 18 Sep 2014 21:22:45 +0200 Subject: [PATCH 126/452] Fix issue #54 - Exception handling --- .../api/command/StartContainerCmd.java | 76 +++++++++++++----- .../api/command/WaitContainerCmd.java | 8 ++ .../core/command/AbstrDockerCmd.java | 23 +----- .../dockerjava/jaxrs/AbstrDockerCmdExec.java | 36 +++++++-- .../jaxrs/AttachContainerCmdExec.java | 2 +- .../github/dockerjava/jaxrs/AuthCmdExec.java | 2 +- .../dockerjava/jaxrs/BuildImageCmdExec.java | 2 +- .../dockerjava/jaxrs/CommitCmdExec.java | 2 +- .../jaxrs/ContainerDiffCmdExec.java | 2 +- .../jaxrs/CopyFileFromContainerCmdExec.java | 2 +- .../jaxrs/CreateContainerCmdExec.java | 2 +- .../dockerjava/jaxrs/CreateImageCmdExec.java | 2 +- .../jaxrs/DockerCmdExecFactoryImpl.java | 6 +- .../github/dockerjava/jaxrs/InfoCmdExec.java | 2 +- .../jaxrs/InspectContainerCmdExec.java | 5 +- .../dockerjava/jaxrs/InspectImageCmdExec.java | 2 +- .../jaxrs/KillContainerCmdExec.java | 2 +- .../jaxrs/ListContainersCmdExec.java | 2 +- .../dockerjava/jaxrs/ListImagesCmdExec.java | 2 +- .../dockerjava/jaxrs/LogContainerCmdExec.java | 2 +- .../jaxrs/PauseContainerCmdExec.java | 2 +- .../github/dockerjava/jaxrs/PingCmdExec.java | 2 +- .../dockerjava/jaxrs/PullImageCmdExec.java | 2 +- .../dockerjava/jaxrs/PushImageCmdExec.java | 2 +- .../jaxrs/RemoveContainerCmdExec.java | 2 +- .../dockerjava/jaxrs/RemoveImageCmdExec.java | 2 +- .../jaxrs/RestartContainerCmdExec.java | 2 +- .../dockerjava/jaxrs/SearchImagesCmdExec.java | 2 +- .../jaxrs/StartContainerCmdExec.java | 2 +- .../jaxrs/StopContainerCmdExec.java | 3 +- .../dockerjava/jaxrs/TagImageCmdExec.java | 2 +- .../dockerjava/jaxrs/TopContainerCmdExec.java | 2 +- .../jaxrs/UnpauseContainerCmdExec.java | 2 +- .../dockerjava/jaxrs/VersionCmdExec.java | 2 +- .../jaxrs/WaitContainerCmdExec.java | 4 +- .../util}/JsonClientFilter.java | 2 +- .../util/ResponseStatusExceptionFilter.java | 65 ++++++++++++++++ .../util}/SelectiveLoggingFilter.java | 2 +- .../core/command/CommitCmdImplTest.java | 11 +++ .../command/ContainerDiffCmdImplTest.java | 12 ++- .../CopyFileFromContainerCmdImplTest.java | 10 +++ .../command/CreateContainerCmdImplTest.java | 77 ++++++++++++++----- .../command/KillContainerCmdImplTest.java | 13 +++- .../core/command/LogContainerCmdImplTest.java | 12 ++- .../core/command/PullImageCmdImplTest.java | 20 ++++- .../core/command/PushImageCmdImplTest.java | 4 +- .../command/RemoveContainerCmdImplTest.java | 10 +++ .../core/command/RemoveImageCmdImplTest.java | 13 +++- .../command/RestartContainerCmdImplTest.java | 11 +++ .../command/StartContainerCmdImplTest.java | 13 +++- .../command/StopContainerCmdImplTest.java | 11 +++ .../core/command/TagImageCmdImplTest.java | 16 +++- .../command/WaitContainerCmdImplTest.java | 17 +++- 53 files changed, 411 insertions(+), 123 deletions(-) rename src/main/java/com/github/dockerjava/{core => jaxrs/util}/JsonClientFilter.java (95%) create mode 100644 src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java rename src/main/java/com/github/dockerjava/{core => jaxrs/util}/SelectiveLoggingFilter.java (96%) diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index 54c7b144..ed16a727 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -27,25 +27,28 @@ public interface StartContainerCmd extends DockerCmd { public boolean isPrivileged(); public String[] getDns(); - + public String[] getDnsSearch(); public String getVolumesFrom(); public String getContainerId(); - + public String getNetworkMode(); - + public Device[] getDevices(); - + public RestartPolicy getRestartPolicy(); - + public String[] getCapAdd(); - + public String[] getCapDrop(); public StartContainerCmd withBinds(Bind... binds); + /** + * Add link to another container. + */ public StartContainerCmd withLinks(Link... links); public StartContainerCmd withLxcConf(LxcConf... lxcConf); @@ -56,35 +59,68 @@ public interface StartContainerCmd extends DockerCmd { public StartContainerCmd withPublishAllPorts(boolean publishAllPorts); - // Set custom DNS servers + /** + * Set custom DNS servers + */ public StartContainerCmd withDns(String... dns); - - // Set custom DNS search domains + + /** + * Set custom DNS search domains + */ public StartContainerCmd withDnsSearch(String... dnsSearch); public StartContainerCmd withVolumesFrom(String volumesFrom); public StartContainerCmd withContainerId(String containerId); - + + /** + * Set the Network mode for the container + *
    + *
  • 'bridge': creates a new network stack for the container on the docker + * bridge
  • + *
  • 'none': no networking for this container
  • + *
  • 'container:': reuses another container network stack
  • + *
  • 'host': use the host network stack inside the container. Note: the + * host mode gives the container full access to local system services such + * as D-bus and is therefore considered insecure.
  • + *
+ */ public StartContainerCmd withNetworkMode(String networkMode); - + + /** + * Add host devices to the container + */ public StartContainerCmd withDevices(Device... devices); - + + /** + * Set custom {@link RestartPolicy} for the container. Defaults to + * {@link RestartPolicy#noRestart()} + */ public StartContainerCmd withRestartPolicy(RestartPolicy restartPolicy); - + + /** + * Add linux kernel + * capability to the container. For example: adding capability "MKNOD" + * allows the container to create special files using the 'mknod' command. + */ public StartContainerCmd withCapAdd(String... capAdd); - + + /** + * Drop linux kernel + * capability from the container. For example: dropping capability + * "CHOWN" prevents the container from changing the owner of any files. + */ public StartContainerCmd withCapDrop(String... capDrop); /** - * @throws NotFoundException No such container - * @throws NotModifiedException Container already started + * @throws NotFoundException + * No such container + * @throws NotModifiedException + * Container already started */ public Void exec() throws NotFoundException, NotModifiedException; - - - - public static interface Exec extends DockerCmdExec { } diff --git a/src/main/java/com/github/dockerjava/api/command/WaitContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/WaitContainerCmd.java index 3216ead2..e7183155 100644 --- a/src/main/java/com/github/dockerjava/api/command/WaitContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/WaitContainerCmd.java @@ -1,5 +1,7 @@ package com.github.dockerjava.api.command; +import com.github.dockerjava.api.NotFoundException; + /** * Wait a container * @@ -11,6 +13,12 @@ public interface WaitContainerCmd extends DockerCmd { public WaitContainerCmd withContainerId(String containerId); + /** + * @throws NotFoundException container not found + */ + @Override + public Integer exec() throws NotFoundException; + public static interface Exec extends DockerCmdExec { } diff --git a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java index 74241573..f4d5f8cc 100644 --- a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java @@ -28,31 +28,10 @@ public AbstrDockerCmd(DockerCmdExec execution) { this.execution = execution; } - //protected abstract RES_T impl(); - - /** - * @throws DockerException If something gets wrong - */ @Override public RES_T exec() throws DockerException { - LOGGER.debug("Cmd: {}", this); - - try { - return execution.exec((CMD_T)this); - } catch (ClientErrorException exception) { - int status = exception.getResponse().getStatus(); - switch(status) { - case 204: return null; - case 304: throw new NotModifiedException(exception); - case 400: throw new BadRequestException(exception); - case 404: throw new NotFoundException(exception); - case 406: throw new NotAcceptableException(exception); - case 409: throw new ConflictException(exception); - case 500: throw new InternalServerErrorException(exception); - default: throw toDockerException(exception); - } - } + return execution.exec((CMD_T)this); } protected DockerException toDockerException(ClientErrorException exception) { diff --git a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java index e9a5b6d6..34414d73 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java @@ -2,34 +2,58 @@ import java.io.IOException; +import javax.ws.rs.ProcessingException; import javax.ws.rs.client.WebTarget; import org.apache.commons.codec.binary.Base64; import com.fasterxml.jackson.databind.ObjectMapper; + +import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.command.DockerCmd; import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.model.AuthConfig; + import com.google.common.base.Preconditions; -public abstract class AbstrDockerCmdExec, RES_T> implements DockerCmdExec { +public abstract class AbstrDockerCmdExec, RES_T> + implements DockerCmdExec { private WebTarget baseResource; - + public AbstrDockerCmdExec(WebTarget baseResource) { - Preconditions.checkNotNull(baseResource, "baseResource was not specified"); + Preconditions.checkNotNull(baseResource, + "baseResource was not specified"); this.baseResource = baseResource; } - + protected WebTarget getBaseResource() { return baseResource; } - + protected String registryAuth(AuthConfig authConfig) { try { - return Base64.encodeBase64String(new ObjectMapper().writeValueAsString(authConfig).getBytes()); + return Base64.encodeBase64String(new ObjectMapper() + .writeValueAsString(authConfig).getBytes()); } catch (IOException e) { throw new RuntimeException(e); } } + + public RES_T exec(CMD_T command) { + // this hack works because of ResponseStatusExceptionFilter + RES_T result; + try { + result = execute(command); + } catch (ProcessingException e) { + if(e.getCause() instanceof DockerException) { + throw (DockerException)e.getCause(); + } else { + throw e; + } + } + return result; + } + + protected abstract RES_T execute(CMD_T command); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java index 2b469da9..5ed84c34 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java @@ -23,7 +23,7 @@ public AttachContainerCmdExec(WebTarget baseResource) { } @Override - public InputStream exec(AttachContainerCmd command) { + protected InputStream execute(AttachContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/attach") .resolveTemplate("id", command.getContainerId()) .queryParam("logs", command.hasLogsEnabled() ? "1" : "0") diff --git a/src/main/java/com/github/dockerjava/jaxrs/AuthCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AuthCmdExec.java index 3fc9329f..d73487bb 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/AuthCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/AuthCmdExec.java @@ -22,7 +22,7 @@ public AuthCmdExec(WebTarget baseResource) { } @Override - public Void exec(AuthCmd command) { + protected Void execute(AuthCmd command) { WebTarget webResource = getBaseResource().path("/auth"); LOGGER.trace("POST: {}", webResource); Response response = webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command.getAuthConfig(), MediaType.APPLICATION_JSON)); diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index 572f0ea7..71d3f902 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -23,7 +23,7 @@ public BuildImageCmdExec(WebTarget baseResource) { } @Override - public InputStream exec(BuildImageCmd command) { + protected InputStream execute(BuildImageCmd command) { WebTarget webResource = getBaseResource().path("/build"); if(command.getTag() != null) { diff --git a/src/main/java/com/github/dockerjava/jaxrs/CommitCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/CommitCmdExec.java index 6e11c818..f1f4fe33 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/CommitCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/CommitCmdExec.java @@ -21,7 +21,7 @@ public CommitCmdExec(WebTarget baseResource) { } @Override - public String exec(CommitCmd command) { + protected String execute(CommitCmd command) { WebTarget webResource = getBaseResource().path("/commit") .queryParam("container", command.getContainerId()) .queryParam("repo", command.getRepository()) diff --git a/src/main/java/com/github/dockerjava/jaxrs/ContainerDiffCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ContainerDiffCmdExec.java index efa0284f..0a657ed9 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ContainerDiffCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ContainerDiffCmdExec.java @@ -22,7 +22,7 @@ public ContainerDiffCmdExec(WebTarget baseResource) { } @Override - public List exec(ContainerDiffCmd command) { + protected List execute(ContainerDiffCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/changes").resolveTemplate("id", command.getContainerId()); LOGGER.trace("GET: {}", webResource); diff --git a/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java index f1f197d0..27b4d5bd 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java @@ -23,7 +23,7 @@ public CopyFileFromContainerCmdExec(WebTarget baseResource) { } @Override - public InputStream exec(CopyFileFromContainerCmd command) { + protected InputStream execute(CopyFileFromContainerCmd command) { WebTarget webResource = getBaseResource() .path("/containers/{id}/copy") .resolveTemplate("id", command.getContainerId()); diff --git a/src/main/java/com/github/dockerjava/jaxrs/CreateContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/CreateContainerCmdExec.java index fd3be29d..26dc25cd 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/CreateContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/CreateContainerCmdExec.java @@ -20,7 +20,7 @@ public CreateContainerCmdExec(WebTarget baseResource) { } @Override - public CreateContainerResponse exec(CreateContainerCmd command) { + protected CreateContainerResponse execute(CreateContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/create"); if (command.getName() != null) { diff --git a/src/main/java/com/github/dockerjava/jaxrs/CreateImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/CreateImageCmdExec.java index 139a6bd5..4c7bae8b 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/CreateImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/CreateImageCmdExec.java @@ -21,7 +21,7 @@ public CreateImageCmdExec(WebTarget baseResource) { } @Override - public CreateImageResponse exec(CreateImageCmd command) { + protected CreateImageResponse execute(CreateImageCmd command) { WebTarget webResource = getBaseResource() .path("/images/create") .queryParam("repo", command.getRepository()) diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index dfd83deb..8ba7edd5 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -43,8 +43,9 @@ import com.github.dockerjava.api.command.VersionCmd; import com.github.dockerjava.api.command.WaitContainerCmd; import com.github.dockerjava.core.DockerClientConfig; -import com.github.dockerjava.core.JsonClientFilter; -import com.github.dockerjava.core.SelectiveLoggingFilter; +import com.github.dockerjava.jaxrs.util.JsonClientFilter; +import com.github.dockerjava.jaxrs.util.ResponseStatusExceptionFilter; +import com.github.dockerjava.jaxrs.util.SelectiveLoggingFilter; import com.google.common.base.Preconditions; public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { @@ -62,6 +63,7 @@ public void init(DockerClientConfig dockerClientConfig) { ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(ResponseStatusExceptionFilter.class); clientConfig.register(JsonClientFilter.class); clientConfig.register(JacksonJsonProvider.class); diff --git a/src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java index 9ca8eb7f..aff72fab 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java @@ -19,7 +19,7 @@ public InfoCmdExec(WebTarget baseResource) { } @Override - public Info exec(InfoCmd command) { + protected Info execute(InfoCmd command) { WebTarget webResource = getBaseResource().path("/info"); LOGGER.trace("GET: {}", webResource); diff --git a/src/main/java/com/github/dockerjava/jaxrs/InspectContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/InspectContainerCmdExec.java index bca28232..1cacd1e8 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/InspectContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/InspectContainerCmdExec.java @@ -3,6 +3,7 @@ import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,10 +20,10 @@ public InspectContainerCmdExec(WebTarget baseResource) { } @Override - public InspectContainerResponse exec(InspectContainerCmd command) { + protected InspectContainerResponse execute(InspectContainerCmd command) { WebTarget webResource = getBaseResource().path(String.format("/containers/%s/json", command.getContainerId())); - LOGGER.trace("GET: {}", webResource); + LOGGER.debug("GET: {}", webResource); return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectContainerResponse.class); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/InspectImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/InspectImageCmdExec.java index 3d226374..78426609 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/InspectImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/InspectImageCmdExec.java @@ -19,7 +19,7 @@ public InspectImageCmdExec(WebTarget baseResource) { } @Override - public InspectImageResponse exec(InspectImageCmd command) { + protected InspectImageResponse execute(InspectImageCmd command) { WebTarget webResource = getBaseResource().path("/images/{id}/json").resolveTemplate("id", command.getImageId()); LOGGER.trace("GET: {}", webResource); diff --git a/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java index 396dc772..28496edc 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java @@ -20,7 +20,7 @@ public KillContainerCmdExec(WebTarget baseResource) { } @Override - public Void exec(KillContainerCmd command) { + protected Void execute(KillContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/kill").resolveTemplate("id", command.getContainerId()); if(command.getSignal() != null) { diff --git a/src/main/java/com/github/dockerjava/jaxrs/ListContainersCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ListContainersCmdExec.java index 3a4ae6dc..018db9a5 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ListContainersCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ListContainersCmdExec.java @@ -21,7 +21,7 @@ public ListContainersCmdExec(WebTarget baseResource) { } @Override - public List exec(ListContainersCmd command) { + protected List execute(ListContainersCmd command) { WebTarget webResource = getBaseResource().path("/containers/json") .queryParam("all", command.hasShowAllEnabled() ? "1" : "0") .queryParam("since", command.getSinceId()) diff --git a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java index c20e4bde..5a000a29 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java @@ -21,7 +21,7 @@ public ListImagesCmdExec(WebTarget baseResource) { } @Override - public List exec(ListImagesCmd command) { + protected List execute(ListImagesCmd command) { WebTarget webResource = getBaseResource() .path("/images/json") .queryParam("filter", command.getFilter()) diff --git a/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java index 0ae71a7a..46d25942 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java @@ -19,7 +19,7 @@ public LogContainerCmdExec(WebTarget baseResource) { } @Override - public InputStream exec(LogContainerCmd command) { + protected InputStream execute(LogContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/logs") .resolveTemplate("id", command.getContainerId()) .queryParam("timestamps", command.hasTimestampsEnabled() ? "1" : "0") diff --git a/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java index 0271fce5..ee84a320 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java @@ -20,7 +20,7 @@ public PauseContainerCmdExec(WebTarget baseResource) { } @Override - public Void exec(PauseContainerCmd command) { + protected Void execute(PauseContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/pause") .resolveTemplate("id", command.getContainerId()); diff --git a/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java index eede5765..abfb0f4c 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java @@ -17,7 +17,7 @@ public PingCmdExec(WebTarget baseResource) { } @Override - public Void exec(PingCmd command) { + protected Void execute(PingCmd command) { WebTarget webResource = getBaseResource().path("/_ping"); LOGGER.trace("GET: {}", webResource); diff --git a/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java index 0785e029..4ac190be 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java @@ -22,7 +22,7 @@ public PullImageCmdExec(WebTarget baseResource) { } @Override - public InputStream exec(PullImageCmd command) { + protected InputStream execute(PullImageCmd command) { WebTarget webResource = getBaseResource().path("/images/create") .queryParam("tag", command.getTag()) .queryParam("fromImage", command.getRepository()) diff --git a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java index a329834f..8d5aabef 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java @@ -23,7 +23,7 @@ public PushImageCmdExec(WebTarget baseResource) { } @Override - public InputStream exec(PushImageCmd command) { + protected InputStream execute(PushImageCmd command) { WebTarget webResource = getBaseResource().path("/images/" + name(command) + "/push"); final String registryAuth = registryAuth(command.getAuthConfig()); diff --git a/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java index 1b8bdf0c..7f45bdda 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java @@ -17,7 +17,7 @@ public RemoveContainerCmdExec(WebTarget baseResource) { } @Override - public Void exec(RemoveContainerCmd command) { + protected Void execute(RemoveContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/" + command.getContainerId()) .queryParam("v", command.hasRemoveVolumesEnabled() ? "1" : "0") .queryParam("force", command.hasForceEnabled() ? "1" : "0"); diff --git a/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java index 292a4c0f..54fb327b 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java @@ -17,7 +17,7 @@ public RemoveImageCmdExec(WebTarget baseResource) { } @Override - public Void exec(RemoveImageCmd command) { + protected Void execute(RemoveImageCmd command) { WebTarget webResource = getBaseResource().path("/images/" + command.getImageId()) .queryParam("force", command.hasForceEnabled() ? "1" : "0") .queryParam("noprune", command.hasNoPruneEnabled() ? "1" : "0"); diff --git a/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java index eaf4d1e9..fe544f13 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java @@ -19,7 +19,7 @@ public RestartContainerCmdExec(WebTarget baseResource) { } @Override - public Void exec(RestartContainerCmd command) { + protected Void execute(RestartContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/restart") .resolveTemplate("id", command.getContainerId()) .queryParam("t", String.valueOf(command.getTimeout())); diff --git a/src/main/java/com/github/dockerjava/jaxrs/SearchImagesCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/SearchImagesCmdExec.java index feddf017..a7b6ddbc 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/SearchImagesCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/SearchImagesCmdExec.java @@ -21,7 +21,7 @@ public SearchImagesCmdExec(WebTarget baseResource) { } @Override - public List exec(SearchImagesCmd command) { + protected List execute(SearchImagesCmd command) { WebTarget webResource = getBaseResource().path("/images/search").queryParam("term", command.getTerm()); LOGGER.trace("GET: {}", webResource); diff --git a/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java index 1d63a1b5..8a2c09a4 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java @@ -19,7 +19,7 @@ public StartContainerCmdExec(WebTarget baseResource) { } @Override - public Void exec(StartContainerCmd command) { + protected Void execute(StartContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/start") .resolveTemplate("id", command.getContainerId()); diff --git a/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java index 24f10f0a..337c71b2 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java @@ -19,7 +19,7 @@ public StopContainerCmdExec(WebTarget baseResource) { } @Override - public Void exec(StopContainerCmd command) { + protected Void execute(StopContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/stop") .resolveTemplate("id", command.getContainerId()) .queryParam("t", String.valueOf(command.getTimeout())); @@ -29,5 +29,4 @@ public Void exec(StopContainerCmd command) { return null; } - } diff --git a/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java index 56f94cd5..d8545e33 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java @@ -21,7 +21,7 @@ public TagImageCmdExec(WebTarget baseResource) { } @Override - public Void exec(TagImageCmd command) { + protected Void execute(TagImageCmd command) { WebTarget webResource = getBaseResource().path("/images/" + command.getImageId() + "/tag") .queryParam("repo", command.getRepository()) .queryParam("tag", command.getTag()) diff --git a/src/main/java/com/github/dockerjava/jaxrs/TopContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/TopContainerCmdExec.java index 13b7f44c..55c431cc 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/TopContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/TopContainerCmdExec.java @@ -20,7 +20,7 @@ public TopContainerCmdExec(WebTarget baseResource) { } @Override - public TopContainerResponse exec(TopContainerCmd command) { + protected TopContainerResponse execute(TopContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/top") .resolveTemplate("id", command.getContainerId()); diff --git a/src/main/java/com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java index dac47319..361f9adc 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java @@ -19,7 +19,7 @@ public UnpauseContainerCmdExec(WebTarget baseResource) { } @Override - public Void exec(UnpauseContainerCmd command) { + protected Void execute(UnpauseContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/unpause") .resolveTemplate("id", command.getContainerId()); diff --git a/src/main/java/com/github/dockerjava/jaxrs/VersionCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/VersionCmdExec.java index b1ab6d63..9b4ac817 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/VersionCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/VersionCmdExec.java @@ -19,7 +19,7 @@ public VersionCmdExec(WebTarget baseResource) { } @Override - public Version exec(VersionCmd command) { + protected Version execute(VersionCmd command) { WebTarget webResource = getBaseResource().path("/version"); LOGGER.trace("GET: {}", webResource); diff --git a/src/main/java/com/github/dockerjava/jaxrs/WaitContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/WaitContainerCmdExec.java index 37f79987..e6f95586 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/WaitContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/WaitContainerCmdExec.java @@ -21,13 +21,13 @@ public WaitContainerCmdExec(WebTarget baseResource) { } @Override - public Integer exec(WaitContainerCmd command) { + protected Integer execute(WaitContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/wait") .resolveTemplate("id", command.getContainerId()); LOGGER.trace("POST: {}", webResource); ObjectNode ObjectNode = webResource.request().accept(MediaType.APPLICATION_JSON) - .post(entity(null, MediaType.APPLICATION_JSON), ObjectNode.class); + .post(entity(null, MediaType.TEXT_PLAIN), ObjectNode.class); return ObjectNode.get("StatusCode").asInt(); } diff --git a/src/main/java/com/github/dockerjava/core/JsonClientFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/JsonClientFilter.java similarity index 95% rename from src/main/java/com/github/dockerjava/core/JsonClientFilter.java rename to src/main/java/com/github/dockerjava/jaxrs/util/JsonClientFilter.java index cb44dacc..e0eaa4a4 100644 --- a/src/main/java/com/github/dockerjava/core/JsonClientFilter.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/JsonClientFilter.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.core; +package com.github.dockerjava.jaxrs.util; import javax.ws.rs.client.ClientRequestContext; diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java new file mode 100644 index 00000000..2ce5dda9 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java @@ -0,0 +1,65 @@ +package com.github.dockerjava.jaxrs.util; + +import java.io.IOException; + +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; + +import org.apache.commons.io.IOUtils; + +import com.github.dockerjava.api.BadRequestException; +import com.github.dockerjava.api.ConflictException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.InternalServerErrorException; +import com.github.dockerjava.api.NotAcceptableException; +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.NotModifiedException; +import com.github.dockerjava.api.UnauthorizedException; + +/** + * This {@link ClientResponseFilter} implementation detects http status codes and throws {@link DockerException}s + * + * @author marcus + * + */ +public class ResponseStatusExceptionFilter implements ClientResponseFilter { + + + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { + int status = responseContext.getStatus(); + switch (status) { + case 200: + case 201: + case 204: + return; + case 304: + throw new NotModifiedException(getBodyAsMessage(responseContext)); + case 400: + throw new BadRequestException(getBodyAsMessage(responseContext)); + case 401: + throw new UnauthorizedException(getBodyAsMessage(responseContext)); + case 404: + throw new NotFoundException(getBodyAsMessage(responseContext)); + case 406: + throw new NotAcceptableException(getBodyAsMessage(responseContext)); + case 409: + throw new ConflictException(getBodyAsMessage(responseContext)); + case 500: { + + throw new InternalServerErrorException(getBodyAsMessage(responseContext)); + } + default: + throw new DockerException(getBodyAsMessage(responseContext), status); + } + } + + public String getBodyAsMessage(ClientResponseContext responseContext) + throws IOException { + byte[] buffer = new byte[1000]; + IOUtils.read(responseContext.getEntityStream(), buffer); + String message = new String(buffer); + return message; + } +} diff --git a/src/main/java/com/github/dockerjava/core/SelectiveLoggingFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java similarity index 96% rename from src/main/java/com/github/dockerjava/core/SelectiveLoggingFilter.java rename to src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java index ca79ea70..7f7e06c7 100644 --- a/src/main/java/com/github/dockerjava/core/SelectiveLoggingFilter.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.core; +package com.github.dockerjava.jaxrs.util; import java.io.IOException; import java.util.Set; diff --git a/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java index 78442b57..f4a603ff 100644 --- a/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java @@ -17,6 +17,7 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -71,5 +72,15 @@ public void commit() throws DockerException { assertThat(inspectImageResponse.getParent(), equalTo(busyboxImg.getId())); } + + + @Test + public void commitNonExistingContainer() throws DockerException { + try { + dockerClient.commitCmd("non-existent").exec(); + fail("expected NotFoundException"); + } catch (NotFoundException e) { + } + } } diff --git a/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java index 6817cc18..60ad22a4 100644 --- a/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java @@ -18,6 +18,7 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.model.ChangeLog; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -45,7 +46,7 @@ public void afterMethod(ITestResult result) { } @Test - public void testDiff() throws DockerException { + public void testContainerDiff() throws DockerException { CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("touch", "/test" ).exec(); LOG.info("Created container: {}", container.toString()); @@ -65,6 +66,15 @@ public void testDiff() throws DockerException { assertThat(testChangeLog, hasField("path", equalTo("/test"))); assertThat(testChangeLog, hasField("kind", equalTo(1))); } + + @Test + public void testContainerDiffWithNonExistingContainer() throws DockerException { + try { + dockerClient.containerDiffCmd("non-existing").exec(); + fail("expected NotFoundException"); + } catch (NotFoundException e) { + } + } } diff --git a/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java index 467d664a..045a1330 100644 --- a/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java @@ -1,5 +1,6 @@ package com.github.dockerjava.core.command; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -50,4 +51,13 @@ public void copyFromContainer() throws Exception { InputStream response = dockerClient.copyFileFromContainerCmd(container.getId(), "/test").exec(); assertTrue(response.available() > 0, "The file was not copied from the container."); } + + @Test + public void copyFromNonExistingContainer() throws Exception { + try { + dockerClient.copyFileFromContainerCmd("non-existing", "/test").exec(); + fail("expected NotFoundException"); + } catch (NotFoundException e) { + } + } } diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index b0647e4b..84c9b35a 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -4,6 +4,7 @@ import static org.hamcrest.Matchers.*; import java.lang.reflect.Method; +import java.security.SecureRandom; import java.util.Arrays; import org.testng.ITestResult; @@ -34,7 +35,7 @@ public void afterTest() { @BeforeMethod public void beforeMethod(Method method) { - super.beforeMethod(method); + super.beforeMethod(method); } @AfterMethod @@ -42,83 +43,119 @@ public void afterMethod(ITestResult result) { super.afterMethod(result); } + @Test + public void createContainerWithExistingName() throws DockerException { + + String containerName = "generated_" + new SecureRandom().nextInt(); + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("env") + .withName(containerName).exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + try { + dockerClient.createContainerCmd("busybox").withCmd("env") + .withName(containerName).exec(); + fail("expected ConflictException"); + } catch (ConflictException e) { + } + } + @Test public void createContainerWithVolume() throws DockerException { CreateContainerResponse container = dockerClient - .createContainerCmd("busybox").withVolumes(new Volume("/var/log")).withCmd("true").exec(); + .createContainerCmd("busybox") + .withVolumes(new Volume("/var/log")).withCmd("true").exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); - InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); - LOG.info("Inspect container {}", inspectContainerResponse.getConfig().getVolumes()); + LOG.info("Inspect container {}", inspectContainerResponse.getConfig() + .getVolumes()); - assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), contains("/var/log")); + assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), + contains("/var/log")); } @Test public void createContainerWithEnv() throws DockerException { CreateContainerResponse container = dockerClient - .createContainerCmd("busybox").withEnv("VARIABLE=success").withCmd("env").exec(); + .createContainerCmd("busybox").withEnv("VARIABLE=success") + .withCmd("env").exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); - InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); - assertThat(Arrays.asList(inspectContainerResponse.getConfig().getEnv()), contains("VARIABLE=success","HOME=/","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")); + assertThat( + Arrays.asList(inspectContainerResponse.getConfig().getEnv()), + contains("VARIABLE=success", "HOME=/", + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")); dockerClient.startContainerCmd(container.getId()).exec(); - assertThat(asString(dockerClient.logContainerCmd(container.getId()).withStdOut().exec()), containsString("VARIABLE=success")); + assertThat(asString(dockerClient.logContainerCmd(container.getId()) + .withStdOut().exec()), containsString("VARIABLE=success")); } @Test public void createContainerWithHostname() throws DockerException { CreateContainerResponse container = dockerClient - .createContainerCmd("busybox").withHostName("docker-java").withCmd("env").exec(); + .createContainerCmd("busybox").withHostName("docker-java") + .withCmd("env").exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); - InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); - assertThat(inspectContainerResponse.getConfig().getHostName(), equalTo("docker-java")); + assertThat(inspectContainerResponse.getConfig().getHostName(), + equalTo("docker-java")); dockerClient.startContainerCmd(container.getId()).exec(); - assertThat(asString(dockerClient.logContainerCmd(container.getId()).withStdOut().exec()), containsString("HOSTNAME=docker-java")); + assertThat(asString(dockerClient.logContainerCmd(container.getId()) + .withStdOut().exec()), containsString("HOSTNAME=docker-java")); } - + @Test public void createContainerWithName() throws DockerException { CreateContainerResponse container = dockerClient - .createContainerCmd("busybox").withName("container").withCmd("env").exec(); + .createContainerCmd("busybox").withName("container") + .withCmd("env").exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); - InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); assertThat(inspectContainerResponse.getName(), equalTo("/container")); - - + try { - dockerClient.createContainerCmd("busybox").withName("container").withCmd("env").exec(); + dockerClient.createContainerCmd("busybox").withName("container") + .withCmd("env").exec(); fail("Expected ConflictException"); } catch (ConflictException e) { } } - } diff --git a/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java index e6507c6f..5203bd3a 100644 --- a/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java @@ -18,6 +18,7 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -48,7 +49,7 @@ public void afterMethod(ITestResult result) { } @Test - public void testKillContainer() throws DockerException { + public void killContainer() throws DockerException { CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); @@ -69,5 +70,15 @@ public void testKillContainer() throws DockerException { not(equalTo(0))); } + + @Test + public void killNonExistingContainer() throws DockerException { + + try { + dockerClient.killContainerCmd("non-existing").exec(); + fail("expected NotFoundException"); + } catch (NotFoundException e) { + } + } } diff --git a/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java index 84b2a5ff..08103703 100644 --- a/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java @@ -6,7 +6,6 @@ import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; -import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; @@ -18,6 +17,7 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -68,6 +68,16 @@ public void logContainer() throws Exception { assertThat(log, endsWith(snippet)); } + + @Test + public void logNonExistingContainer() throws Exception { + + try { + dockerClient.logContainerCmd("non-existing").withStdErr().withStdOut().exec(); + fail("expected NotFoundException"); + } catch (NotFoundException e) { + } + } } diff --git a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java index a3dbd64c..0ae36058 100644 --- a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java @@ -17,6 +17,8 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.InternalServerErrorException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.api.model.Info; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -67,13 +69,11 @@ public void testPullImage() throws DockerException, IOException { imgCount = info.getImages(); LOG.info("imgCount2: {}", imgCount); - LOG.info("Pulling image: {}", testImage); InputStream response = dockerClient.pullImageCmd(testImage).exec(); - assertThat(asString(response), - containsString("Download complete")); + assertThat(asString(response), containsString("Download complete")); info = dockerClient.infoCmd().exec(); LOG.info("Client info after pull, {}", info.toString()); @@ -86,4 +86,18 @@ public void testPullImage() throws DockerException, IOException { assertThat(inspectImageResponse, notNullValue()); } + @Test + public void testPullNonExistingImage() throws DockerException, IOException { + + // does not throw an exception + dockerClient.pullImageCmd("nonexisting/foo").exec(); + + try { + dockerClient.pullImageCmd("non-existing/foo").exec(); + fail("expected InternalServerErrorException"); + } catch (InternalServerErrorException e) { + } + + } + } diff --git a/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java index b3d890ba..bef220c4 100644 --- a/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java @@ -48,7 +48,7 @@ public void afterMethod(ITestResult result) { } @Test - public void testPushLatest() throws Exception { + public void pushLatest() throws Exception { CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("true").exec(); @@ -71,7 +71,7 @@ public void testPushLatest() throws Exception { } @Test - public void testNotExistentImage() throws Exception { + public void pushExistentImage() throws Exception { assertThat(asString(dockerClient.pushImageCmd(username + "/xxx").exec()), containsString("error")); } diff --git a/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java index b4ab9d93..ba850d35 100644 --- a/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java @@ -20,6 +20,7 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -67,6 +68,15 @@ public void removeContainer() throws DockerException { assertThat(containers2, matcher); } + + @Test + public void removeNonExistingContainer() throws DockerException { + try { + dockerClient.removeContainerCmd("non-existing").exec(); + fail("expected NotFoundException"); + } catch (NotFoundException e) { + } + } } diff --git a/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java index c44a786c..1b6d5cc7 100644 --- a/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java @@ -21,6 +21,7 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -50,7 +51,7 @@ public void afterMethod(ITestResult result) { } @Test - public void testRemoveImage() throws DockerException, InterruptedException { + public void removeImage() throws DockerException, InterruptedException { CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); @@ -75,6 +76,16 @@ public void testRemoveImage() throws DockerException, InterruptedException { assertThat(containers, matcher); } + @Test + public void removeNonExistingImage() throws DockerException, InterruptedException { + try { + dockerClient.removeImageCmd("non-existing").exec(); + fail("expected NotFoundException"); + } catch (NotFoundException e) { + } + + } + } diff --git a/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java index ab947e81..c63d1175 100644 --- a/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java @@ -16,6 +16,7 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -73,6 +74,16 @@ public void restartContainer() throws DockerException { dockerClient.killContainerCmd(container.getId()).exec(); } + + @Test + public void restartNonExistingContainer() throws DockerException, InterruptedException { + try { + dockerClient.restartContainerCmd("non-existing").exec(); + fail("expected NotFoundException"); + } catch (NotFoundException e) { + } + + } } diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index f87cc326..a4533332 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -13,6 +13,7 @@ import java.util.*; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.model.*; @@ -262,9 +263,16 @@ public void startContainer() throws DockerException { assertThat(inspectContainerResponse.getState().getExitCode(), is(equalTo(0))); } - } - + + @Test + public void testStartNonExistingContainer() throws DockerException { + try { + dockerClient.startContainerCmd("non-existing").exec(); + fail("expected NotFoundException"); + } catch (NotFoundException e) { + } + } /** * This tests support for --net option for the docker run command: @@ -296,7 +304,6 @@ public void startContainerWithNetworkMode() throws DockerException { assertThat(inspectContainerResponse.getHostConfig().getNetworkMode(), is(equalTo("host"))); - } @Test diff --git a/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java index df0045fa..9824215e 100644 --- a/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java @@ -18,6 +18,7 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -66,5 +67,15 @@ public void testStopContainer() throws DockerException { assertThat(inspectContainerResponse.getState().isRunning(), is(equalTo(false))); assertThat(inspectContainerResponse.getState().getExitCode(), not(equalTo(0))); } + + @Test + public void testStopNonExistingContainer() throws DockerException { + try { + dockerClient.stopContainerCmd("non-existing").withTimeout(2).exec(); + fail("expected NotFoundException"); + } catch (NotFoundException e) { + + } + } } diff --git a/src/test/java/com/github/dockerjava/core/command/TagImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/TagImageCmdImplTest.java index 706dc1b7..68081ac3 100644 --- a/src/test/java/com/github/dockerjava/core/command/TagImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/TagImageCmdImplTest.java @@ -13,6 +13,7 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.client.AbstractDockerClientTest; public class TagImageCmdImplTest extends AbstractDockerClientTest { @@ -40,13 +41,24 @@ public void afterMethod(ITestResult result) { } @Test - public void testTagImage() throws Exception { - String tag = String.valueOf(RandomUtils.nextInt(Integer.MAX_VALUE)); + public void tagImage() throws Exception { + String tag = "" + RandomUtils.nextInt(Integer.MAX_VALUE); dockerClient.tagImageCmd("busybox:latest", "docker-java/busybox", tag).exec(); dockerClient.removeImageCmd("docker-java/busybox:" + tag).exec(); } + + @Test + public void tagNonExistingImage() throws Exception { + String tag = "" + RandomUtils.nextInt(Integer.MAX_VALUE); + + try { + dockerClient.tagImageCmd("non-existing", "docker-java/busybox", tag).exec(); + fail("expected NotFoundException"); + } catch (NotFoundException e) { + } + } } diff --git a/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java index e8693de5..4885b89e 100644 --- a/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java @@ -16,6 +16,8 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.InternalServerErrorException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -64,9 +66,16 @@ public void testWaitContainer() throws DockerException { assertThat(inspectContainerResponse.getState().isRunning(), is(equalTo(false))); assertThat(inspectContainerResponse.getState().getExitCode(), is(equalTo(exitCode))); - } - - - + + @Test + public void testWaitNonExistingContainer() throws DockerException { + // docker returns InternalServerError instead of NotFound + // see https://github.com/docker/docker/issues/8107 + try { + dockerClient.waitContainerCmd("non-existing").exec(); + fail("expected InternalServerErrorException"); + } catch (InternalServerErrorException e) { + } + } } From 9e6bfdc28edc4d9e96edfa9d6f13e35d84e36693 Mon Sep 17 00:00:00 2001 From: yuxuanchi Date: Fri, 19 Sep 2014 10:27:38 +0800 Subject: [PATCH 127/452] Remove unused code --- .../dockerjava/core/DockerClientImpl.java | 1 - .../dockerjava/core/command/AbstrDockerCmd.java | 17 ++--------------- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 1f4590b9..baa5b5da 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -11,7 +11,6 @@ import com.github.dockerjava.api.command.*; import com.github.dockerjava.api.model.AuthConfig; import com.github.dockerjava.core.command.*; -import com.github.dockerjava.jaxrs.DockerCmdExecFactoryImpl; import com.google.common.base.Preconditions; /** diff --git a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java index f4d5f8cc..00c89159 100644 --- a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java @@ -3,20 +3,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.dockerjava.api.BadRequestException; -import com.github.dockerjava.api.ConflictException; import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.api.InternalServerErrorException; -import com.github.dockerjava.api.NotAcceptableException; -import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.NotModifiedException; import com.github.dockerjava.api.command.DockerCmd; import com.github.dockerjava.api.command.DockerCmdExec; - import com.google.common.base.Preconditions; -import javax.ws.rs.ClientErrorException; - public abstract class AbstrDockerCmd, RES_T> implements DockerCmd { private final static Logger LOGGER = LoggerFactory.getLogger(AbstrDockerCmd.class); @@ -28,14 +19,10 @@ public AbstrDockerCmd(DockerCmdExec execution) { this.execution = execution; } - @Override + @Override + @SuppressWarnings("unchecked") public RES_T exec() throws DockerException { LOGGER.debug("Cmd: {}", this); return execution.exec((CMD_T)this); } - - protected DockerException toDockerException(ClientErrorException exception) { - LOGGER.info("toDockerException"); - return new DockerException(exception.getMessage(), exception.getResponse().getStatus(), exception); - } } \ No newline at end of file From 833dc2f47d772c3917d1ede575e5718dfa44f13d Mon Sep 17 00:00:00 2001 From: yuxuanchi Date: Fri, 19 Sep 2014 10:37:06 +0800 Subject: [PATCH 128/452] Clear code style --- .../com/github/dockerjava/jaxrs/InspectContainerCmdExec.java | 2 +- .../dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/InspectContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/InspectContainerCmdExec.java index 1cacd1e8..664a67c5 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/InspectContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/InspectContainerCmdExec.java @@ -21,7 +21,7 @@ public InspectContainerCmdExec(WebTarget baseResource) { @Override protected InspectContainerResponse execute(InspectContainerCmd command) { - WebTarget webResource = getBaseResource().path(String.format("/containers/%s/json", command.getContainerId())); + WebTarget webResource = getBaseResource().path("/containers/{id}/json").resolveTemplate("id", command.getContainerId()); LOGGER.debug("GET: {}", webResource); return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectContainerResponse.class); diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java index 2ce5dda9..4ce67f9d 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java @@ -46,10 +46,8 @@ public void filter(ClientRequestContext requestContext, ClientResponseContext re throw new NotAcceptableException(getBodyAsMessage(responseContext)); case 409: throw new ConflictException(getBodyAsMessage(responseContext)); - case 500: { - + case 500: throw new InternalServerErrorException(getBodyAsMessage(responseContext)); - } default: throw new DockerException(getBodyAsMessage(responseContext), status); } From 04c528eed90317f7db29f6964f2b176e1e8ea07c Mon Sep 17 00:00:00 2001 From: yuxuanchi Date: Fri, 19 Sep 2014 11:02:20 +0800 Subject: [PATCH 129/452] Fixed ResponseStatusExceptionFilter.getBodyAsMessage() incorrect reading entity --- .../util/ResponseStatusExceptionFilter.java | 38 +++++++++++++++++-- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java index 4ce67f9d..61d97f93 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java @@ -1,10 +1,13 @@ package com.github.dockerjava.jaxrs.util; +import java.io.EOFException; import java.io.IOException; +import java.nio.charset.Charset; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientResponseContext; import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.core.MediaType; import org.apache.commons.io.IOUtils; @@ -55,9 +58,36 @@ public void filter(ClientRequestContext requestContext, ClientResponseContext re public String getBodyAsMessage(ClientResponseContext responseContext) throws IOException { - byte[] buffer = new byte[1000]; - IOUtils.read(responseContext.getEntityStream(), buffer); - String message = new String(buffer); - return message; + if (responseContext.hasEntity()) { + int contentLength = responseContext.getLength(); + if (contentLength != -1) { + byte[] buffer = new byte[contentLength]; + try { + IOUtils.readFully(responseContext.getEntityStream(), buffer); + } + catch (EOFException e) { + return null; + } + Charset charset = null; + MediaType mediaType = responseContext.getMediaType(); + if (mediaType != null) { + String charsetName = mediaType.getParameters().get("charset"); + if (charsetName != null) { + try { + charset = Charset.forName(charsetName); + } + catch (Exception e) { + //Do noting... + } + } + } + if (charset == null) { + charset = Charset.defaultCharset(); + } + String message = new String(buffer, charset); + return message; + } + } + return null; } } From d3fe99f694c12b174a7f663af0165cfb49887c27 Mon Sep 17 00:00:00 2001 From: Brendan Almonte Date: Wed, 17 Sep 2014 18:12:12 -0700 Subject: [PATCH 130/452] Add streaming events API --- pom.xml | 2 +- .../github/dockerjava/api/DockerClient.java | 3 + .../api/command/DockerCmdExecFactory.java | 2 + .../dockerjava/api/command/EventsCmd.java | 22 ++++ .../github/dockerjava/api/model/Event.java | 37 +++++++ .../dockerjava/api/model/EventStream.java | 85 +++++++++++++++ .../com/github/dockerjava/api/model/Info.java | 2 +- .../dockerjava/core/DockerClientImpl.java | 5 + .../core/command/EventsCmdImpl.java | 52 +++++++++ .../jaxrs/DockerCmdExecFactoryImpl.java | 8 +- .../dockerjava/jaxrs/EventsCmdExec.java | 29 +++++ .../core/command/EventsCmdImplTest.java | 101 ++++++++++++++++++ 12 files changed, 345 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/command/EventsCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/model/Event.java create mode 100644 src/main/java/com/github/dockerjava/api/model/EventStream.java create mode 100644 src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java create mode 100644 src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java diff --git a/pom.xml b/pom.xml index 99a6c603..d8f1fbac 100644 --- a/pom.xml +++ b/pom.xml @@ -63,7 +63,7 @@ 1.7.5 1.3.9 0.3 - 11.0.1 + 18.0 1.0.1 diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index 15e66bef..ea2fcefe 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -10,6 +10,7 @@ import com.github.dockerjava.api.command.CopyFileFromContainerCmd; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateImageCmd; +import com.github.dockerjava.api.command.EventsCmd; import com.github.dockerjava.api.command.InfoCmd; import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectImageCmd; @@ -114,6 +115,8 @@ public CopyFileFromContainerCmd copyFileFromContainerCmd( public UnpauseContainerCmd unpauseContainerCmd(String containerId); + public EventsCmd eventsCmd(); + public void close() throws IOException; } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java index 6534bb54..24c0a465 100644 --- a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java +++ b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java @@ -69,6 +69,8 @@ public interface DockerCmdExecFactory extends Closeable { public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec(); + public EventsCmd.Exec createEventsCmdExec(); + public void close() throws IOException; } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/EventsCmd.java b/src/main/java/com/github/dockerjava/api/command/EventsCmd.java new file mode 100644 index 00000000..71590c84 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/EventsCmd.java @@ -0,0 +1,22 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.model.EventStream; + +/** + * Get events + * + * @param since - Show all events created since timestamp + * @param until - Stream events until this timestamp + */ +public interface EventsCmd extends DockerCmd { + public EventsCmd withSince(String since); + + public EventsCmd withUntil(String until); + + public String getSince(); + + public String getUntil(); + + public static interface Exec extends DockerCmdExec { + } +} diff --git a/src/main/java/com/github/dockerjava/api/model/Event.java b/src/main/java/com/github/dockerjava/api/model/Event.java new file mode 100644 index 00000000..674cb66d --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/Event.java @@ -0,0 +1,37 @@ +package com.github.dockerjava.api.model; + +import org.apache.commons.lang.builder.ToStringBuilder; + +/** + * Representation of a Docker event. + */ +public class Event { + private String status; + + private String id; + + private String from; + + private long time; + + public String getStatus() { + return status; + } + + public String getId() { + return id; + } + + public String getFrom() { + return from; + } + + public long getTime() { + return time; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/src/main/java/com/github/dockerjava/api/model/EventStream.java b/src/main/java/com/github/dockerjava/api/model/EventStream.java new file mode 100644 index 00000000..0f47c25f --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/EventStream.java @@ -0,0 +1,85 @@ +package com.github.dockerjava.api.model; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.Queues; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.util.Queue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * EventStream API + *

+ * Spawns a thread to poll for events to fill a BlockingQueue + */ +public class EventStream implements Closeable { + private final ExecutorService executor = Executors.newSingleThreadExecutor(); + private final BlockingQueue queue; + private final EventRunner eventRunner; + + private EventStream(InputStream inputStream) { + queue = Queues.newLinkedBlockingQueue(); + eventRunner = new EventRunner(queue, inputStream); + } + + public static EventStream create(InputStream inputStream) { + return new EventStream(inputStream).startRunner(); + } + + public Event pollEvent() { + return queue.poll(); + } + + public Event pollEvent(long timeout, TimeUnit unit) throws InterruptedException { + return queue.poll(timeout, unit); + } + + @Override + public void close() throws IOException { + eventRunner.initiateStop(); + executor.shutdown(); + } + + private EventStream startRunner() { + executor.execute(eventRunner); + return this; + } + + private static class EventRunner implements Runnable { + private static final JsonFactory JSON_FACTORY = new JsonFactory(); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private final Queue queue; + private final InputStream inputStream; + + public EventRunner(Queue queue, InputStream inputStream) { + this.queue = queue; + this.inputStream = inputStream; + } + + public void initiateStop() throws IOException { + inputStream.close(); + } + + @Override + public void run() { + try { + JsonParser jp = JSON_FACTORY.createParser(inputStream); + while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed()) { + queue.add(OBJECT_MAPPER.readValue(jp, Event.class)); + } + inputStream.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } +} diff --git a/src/main/java/com/github/dockerjava/api/model/Info.java b/src/main/java/com/github/dockerjava/api/model/Info.java index f71b75c9..7fe6ae79 100644 --- a/src/main/java/com/github/dockerjava/api/model/Info.java +++ b/src/main/java/com/github/dockerjava/api/model/Info.java @@ -10,7 +10,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -/**Ø +/** * * @author Konstantin Pelykh (kpelykh@gmail.com) * diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index baa5b5da..81047636 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -252,6 +252,11 @@ public UnpauseContainerCmd unpauseContainerCmd(String containerId) { return new UnpauseContainerCmdImpl(getDockerCmdExecFactory().createUnpauseContainerCmdExec(), containerId); } + @Override + public EventsCmd eventsCmd() { + return new EventsCmdImpl(getDockerCmdExecFactory().createEventsCmdExec()); + } + @Override public void close() throws IOException { getDockerCmdExecFactory().close(); diff --git a/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java new file mode 100644 index 00000000..0b045838 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java @@ -0,0 +1,52 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.command.EventsCmd; +import com.github.dockerjava.api.model.EventStream; + +import java.io.InputStream; + +/** + * Stream docker events + */ +public class EventsCmdImpl extends AbstrDockerCmd implements EventsCmd { + + private String since; + private String until; + + public EventsCmdImpl(EventsCmd.Exec exec) { + super(exec); + } + + @Override + public EventsCmd withSince(String since) { + this.since = since; + return this; + } + + @Override + public EventsCmd withUntil(String until) { + this.until = until; + return this; + } + + public String getSince() { + return since; + } + + public String getUntil() { + return until; + } + + @Override + public EventStream exec() { + return super.exec(); + } + + @Override + public String toString() { + return new StringBuilder("events") + .append(since != null ? " --since=" + since : "") + .append(until != null ? " --until=" + until : "") + .toString(); + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 8ba7edd5..cb59f200 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -7,6 +7,7 @@ import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; +import com.github.dockerjava.api.command.EventsCmd; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; @@ -241,7 +242,12 @@ public PauseContainerCmd.Exec createPauseContainerCmdExec() { public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { return new UnpauseContainerCmdExec(baseResource); } - + + @Override + public EventsCmd.Exec createEventsCmdExec() { + return new EventsCmdExec(getBaseResource()); + } + @Override public void close() throws IOException { Preconditions.checkNotNull(client, "Factory not initialized. You probably forgot to call init()!"); diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java new file mode 100644 index 00000000..60739fc6 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -0,0 +1,29 @@ +package com.github.dockerjava.jaxrs; + +import com.github.dockerjava.api.command.EventsCmd; +import com.github.dockerjava.api.model.EventStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; +import java.io.InputStream; + +public class EventsCmdExec extends AbstrDockerCmdExec implements EventsCmd.Exec { + private static final Logger LOGGER = LoggerFactory.getLogger(EventsCmdExec.class); + + public EventsCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + public EventStream exec(EventsCmd command) { + WebTarget webResource = getBaseResource().path("/events") + .queryParam("since", command.getSince()) + .queryParam("until", command.getUntil()); + + LOGGER.trace("GET: {}", webResource); + InputStream inputStream = webResource.request().get(Response.class).readEntity(InputStream.class); + return EventStream.create(inputStream); + } +} diff --git a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java new file mode 100644 index 00000000..33c43ea1 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java @@ -0,0 +1,101 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.model.Event; +import com.github.dockerjava.api.model.EventStream; +import com.github.dockerjava.client.AbstractDockerClientTest; +import com.google.common.collect.Lists; +import org.testng.ITestResult; +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 java.io.IOException; +import java.lang.reflect.Method; +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class EventsCmdImplTest extends AbstractDockerClientTest { + + private static int KNOWN_NUM_EVENTS = 4; + + private static String getEpochTime() { + return String.valueOf(System.currentTimeMillis() / 1000); + } + + @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 testEventStreamTimeBound() throws InterruptedException, IOException { + // Don't include other tests events + TimeUnit.SECONDS.sleep(1); + String startTime = getEpochTime(); + generateEvents(); + String endTime = getEpochTime(); + + EventStream eventStream = dockerClient.eventsCmd().withSince(startTime).withUntil(endTime).exec(); + List eventList = pollEvents(eventStream); + eventStream.close(); + LOG.info("Events: {}", eventList); + assertEquals(eventList.size(), KNOWN_NUM_EVENTS, "Expected 4 events, [create, start, die, stop]"); + } + + @Test + public void testEventStream() throws InterruptedException, IOException { + // Don't include other tests events + TimeUnit.SECONDS.sleep(1); + String startTime = getEpochTime(); + generateEvents(); + + EventStream eventStream = dockerClient.eventsCmd().withSince(startTime).exec(); + List eventList = pollEvents(eventStream); + eventStream.close(); + LOG.info("Events: {}", eventList); + assertEquals(eventList.size(), KNOWN_NUM_EVENTS, "Expected 4 events, [create, start, die, stop]"); + } + + /** + * This method generates {#link KNOWN_NUM_EVENTS} events + */ + private void generateEvents() { + String testImage = "busybox"; + asString(dockerClient.pullImageCmd(testImage).exec()); + CreateContainerResponse container1 = dockerClient + .createContainerCmd(testImage).withCmd("echo").exec(); + dockerClient.startContainerCmd(container1.getId()).exec(); + dockerClient.stopContainerCmd(container1.getId()).exec(); + } + + private List pollEvents(EventStream eventStream) throws InterruptedException { + List eventList = Lists.newArrayList(); + Event event = null; + do { + event = eventStream.pollEvent(1, TimeUnit.SECONDS); + if (event != null) { + eventList.add(event); + } + } while (event != null); + return eventList; + } +} From 3d2a3f017f976e8b740ccd653c75b9755706dc98 Mon Sep 17 00:00:00 2001 From: Brendan Almonte Date: Wed, 17 Sep 2014 18:12:12 -0700 Subject: [PATCH 131/452] Events API: Switch to a callback approach rather than a BlockingQueue --- .../github/dockerjava/api/DockerClient.java | 3 +- .../dockerjava/api/command/EventCallback.java | 10 +++ .../dockerjava/api/command/EventsCmd.java | 8 +- .../dockerjava/api/model/EventNotifier.java | 51 +++++++++++ .../dockerjava/api/model/EventStream.java | 85 ------------------- .../dockerjava/core/DockerClientImpl.java | 4 +- .../core/command/EventsCmdImpl.java | 21 +++-- .../dockerjava/jaxrs/EventsCmdExec.java | 8 +- .../core/command/EventsCmdImplTest.java | 69 ++++++++------- 9 files changed, 128 insertions(+), 131 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/command/EventCallback.java create mode 100644 src/main/java/com/github/dockerjava/api/model/EventNotifier.java delete mode 100644 src/main/java/com/github/dockerjava/api/model/EventStream.java diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index ea2fcefe..52323942 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -10,6 +10,7 @@ import com.github.dockerjava.api.command.CopyFileFromContainerCmd; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateImageCmd; +import com.github.dockerjava.api.command.EventCallback; import com.github.dockerjava.api.command.EventsCmd; import com.github.dockerjava.api.command.InfoCmd; import com.github.dockerjava.api.command.InspectContainerCmd; @@ -115,7 +116,7 @@ public CopyFileFromContainerCmd copyFileFromContainerCmd( public UnpauseContainerCmd unpauseContainerCmd(String containerId); - public EventsCmd eventsCmd(); + public EventsCmd eventsCmd(EventCallback eventCallback); public void close() throws IOException; diff --git a/src/main/java/com/github/dockerjava/api/command/EventCallback.java b/src/main/java/com/github/dockerjava/api/command/EventCallback.java new file mode 100644 index 00000000..009cc599 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/EventCallback.java @@ -0,0 +1,10 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.model.Event; + +/** + * Event callback + */ +public interface EventCallback { + public void onEvent(Event event); +} diff --git a/src/main/java/com/github/dockerjava/api/command/EventsCmd.java b/src/main/java/com/github/dockerjava/api/command/EventsCmd.java index 71590c84..28b5f509 100644 --- a/src/main/java/com/github/dockerjava/api/command/EventsCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/EventsCmd.java @@ -1,6 +1,6 @@ package com.github.dockerjava.api.command; -import com.github.dockerjava.api.model.EventStream; +import com.github.dockerjava.api.model.EventNotifier; /** * Get events @@ -8,7 +8,7 @@ * @param since - Show all events created since timestamp * @param until - Stream events until this timestamp */ -public interface EventsCmd extends DockerCmd { +public interface EventsCmd extends DockerCmd { public EventsCmd withSince(String since); public EventsCmd withUntil(String until); @@ -17,6 +17,8 @@ public interface EventsCmd extends DockerCmd { public String getUntil(); - public static interface Exec extends DockerCmdExec { + public EventCallback getEventCallback(); + + public static interface Exec extends DockerCmdExec { } } diff --git a/src/main/java/com/github/dockerjava/api/model/EventNotifier.java b/src/main/java/com/github/dockerjava/api/model/EventNotifier.java new file mode 100644 index 00000000..f0522576 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/EventNotifier.java @@ -0,0 +1,51 @@ +package com.github.dockerjava.api.model; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.command.EventCallback; +import com.google.common.base.Preconditions; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.util.concurrent.Callable; + +/** + * EventStream API + *

+ * Spawns a thread to poll for events to fill a BlockingQueue + */ +public class EventNotifier implements Closeable, Callable { + private static final JsonFactory JSON_FACTORY = new JsonFactory(); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private final EventCallback eventCallback; + private final InputStream inputStream; + + private EventNotifier(EventCallback eventCallback, InputStream inputStream) { + this.eventCallback = eventCallback; + this.inputStream = inputStream; + } + + public static EventNotifier create(EventCallback eventCallback, InputStream inputStream) { + Preconditions.checkNotNull(eventCallback, "An EventCallback must be provided"); + Preconditions.checkNotNull(inputStream, "An InputStream must be provided"); + return new EventNotifier(eventCallback, inputStream); + } + + @Override + public void close() throws IOException { + inputStream.close(); + } + + @Override + public Void call() throws Exception { + JsonParser jp = JSON_FACTORY.createParser(inputStream); + while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed()) { + eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); + } + return null; + } +} diff --git a/src/main/java/com/github/dockerjava/api/model/EventStream.java b/src/main/java/com/github/dockerjava/api/model/EventStream.java deleted file mode 100644 index 0f47c25f..00000000 --- a/src/main/java/com/github/dockerjava/api/model/EventStream.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.github.dockerjava.api.model; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.Queues; - -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.util.Queue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -/** - * EventStream API - *

- * Spawns a thread to poll for events to fill a BlockingQueue - */ -public class EventStream implements Closeable { - private final ExecutorService executor = Executors.newSingleThreadExecutor(); - private final BlockingQueue queue; - private final EventRunner eventRunner; - - private EventStream(InputStream inputStream) { - queue = Queues.newLinkedBlockingQueue(); - eventRunner = new EventRunner(queue, inputStream); - } - - public static EventStream create(InputStream inputStream) { - return new EventStream(inputStream).startRunner(); - } - - public Event pollEvent() { - return queue.poll(); - } - - public Event pollEvent(long timeout, TimeUnit unit) throws InterruptedException { - return queue.poll(timeout, unit); - } - - @Override - public void close() throws IOException { - eventRunner.initiateStop(); - executor.shutdown(); - } - - private EventStream startRunner() { - executor.execute(eventRunner); - return this; - } - - private static class EventRunner implements Runnable { - private static final JsonFactory JSON_FACTORY = new JsonFactory(); - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - private final Queue queue; - private final InputStream inputStream; - - public EventRunner(Queue queue, InputStream inputStream) { - this.queue = queue; - this.inputStream = inputStream; - } - - public void initiateStop() throws IOException { - inputStream.close(); - } - - @Override - public void run() { - try { - JsonParser jp = JSON_FACTORY.createParser(inputStream); - while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed()) { - queue.add(OBJECT_MAPPER.readValue(jp, Event.class)); - } - inputStream.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } -} diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 81047636..5dfb4c13 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -253,8 +253,8 @@ public UnpauseContainerCmd unpauseContainerCmd(String containerId) { } @Override - public EventsCmd eventsCmd() { - return new EventsCmdImpl(getDockerCmdExecFactory().createEventsCmdExec()); + public EventsCmd eventsCmd(EventCallback eventCallback) { + return new EventsCmdImpl(getDockerCmdExecFactory().createEventsCmdExec(), eventCallback); } @Override diff --git a/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java index 0b045838..6129aa23 100644 --- a/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java @@ -1,20 +1,22 @@ package com.github.dockerjava.core.command; +import com.github.dockerjava.api.command.EventCallback; import com.github.dockerjava.api.command.EventsCmd; -import com.github.dockerjava.api.model.EventStream; - -import java.io.InputStream; +import com.github.dockerjava.api.model.EventNotifier; /** * Stream docker events */ -public class EventsCmdImpl extends AbstrDockerCmd implements EventsCmd { +public class EventsCmdImpl extends AbstrDockerCmd implements EventsCmd { + + private final EventCallback eventCallback; private String since; private String until; - public EventsCmdImpl(EventsCmd.Exec exec) { + public EventsCmdImpl(EventsCmd.Exec exec, EventCallback eventCallback) { super(exec); + this.eventCallback = eventCallback; } @Override @@ -29,16 +31,23 @@ public EventsCmd withUntil(String until) { return this; } + @Override public String getSince() { return since; } + @Override public String getUntil() { return until; } @Override - public EventStream exec() { + public EventCallback getEventCallback() { + return eventCallback; + } + + @Override + public EventNotifier exec() { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java index 60739fc6..8f8a1c83 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -1,7 +1,7 @@ package com.github.dockerjava.jaxrs; import com.github.dockerjava.api.command.EventsCmd; -import com.github.dockerjava.api.model.EventStream; +import com.github.dockerjava.api.model.EventNotifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -9,7 +9,7 @@ import javax.ws.rs.core.Response; import java.io.InputStream; -public class EventsCmdExec extends AbstrDockerCmdExec implements EventsCmd.Exec { +public class EventsCmdExec extends AbstrDockerCmdExec implements EventsCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(EventsCmdExec.class); public EventsCmdExec(WebTarget baseResource) { @@ -17,13 +17,13 @@ public EventsCmdExec(WebTarget baseResource) { } @Override - public EventStream exec(EventsCmd command) { + protected EventNotifier execute(EventsCmd command) { WebTarget webResource = getBaseResource().path("/events") .queryParam("since", command.getSince()) .queryParam("until", command.getUntil()); LOGGER.trace("GET: {}", webResource); InputStream inputStream = webResource.request().get(Response.class).readEntity(InputStream.class); - return EventStream.create(inputStream); + return EventNotifier.create(command.getEventCallback(), inputStream); } } diff --git a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java index 33c43ea1..350c840e 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java @@ -2,10 +2,10 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.EventCallback; import com.github.dockerjava.api.model.Event; -import com.github.dockerjava.api.model.EventStream; +import com.github.dockerjava.api.model.EventNotifier; import com.github.dockerjava.client.AbstractDockerClientTest; -import com.google.common.collect.Lists; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -15,7 +15,8 @@ import java.io.IOException; import java.lang.reflect.Method; -import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class EventsCmdImplTest extends AbstractDockerClientTest { @@ -50,52 +51,60 @@ public void afterMethod(ITestResult result) { public void testEventStreamTimeBound() throws InterruptedException, IOException { // Don't include other tests events TimeUnit.SECONDS.sleep(1); + String startTime = getEpochTime(); - generateEvents(); + int expectedEvents = generateEvents(); String endTime = getEpochTime(); - EventStream eventStream = dockerClient.eventsCmd().withSince(startTime).withUntil(endTime).exec(); - List eventList = pollEvents(eventStream); - eventStream.close(); - LOG.info("Events: {}", eventList); - assertEquals(eventList.size(), KNOWN_NUM_EVENTS, "Expected 4 events, [create, start, die, stop]"); + CountDownLatch countDownLatch = new CountDownLatch(expectedEvents); + EventCallback eventCallback = new EventCallbackTest(countDownLatch); + + EventNotifier eventNotifier = dockerClient.eventsCmd(eventCallback).withSince(startTime).withUntil(endTime).exec(); + boolean zeroCount = countDownLatch.await(30, TimeUnit.SECONDS); + eventNotifier.close(); + assertTrue(zeroCount, "Expected 4 events, [create, start, die, stop]"); } @Test - public void testEventStream() throws InterruptedException, IOException { + public void testEventStreaming() throws InterruptedException, IOException { // Don't include other tests events TimeUnit.SECONDS.sleep(1); - String startTime = getEpochTime(); + + CountDownLatch countDownLatch = new CountDownLatch(KNOWN_NUM_EVENTS); + EventCallback eventCallback = new EventCallbackTest(countDownLatch); + EventNotifier eventNotifier = dockerClient.eventsCmd(eventCallback).withSince(getEpochTime()).exec(); + generateEvents(); - EventStream eventStream = dockerClient.eventsCmd().withSince(startTime).exec(); - List eventList = pollEvents(eventStream); - eventStream.close(); - LOG.info("Events: {}", eventList); - assertEquals(eventList.size(), KNOWN_NUM_EVENTS, "Expected 4 events, [create, start, die, stop]"); + boolean zeroCount = countDownLatch.await(30, TimeUnit.SECONDS); + eventNotifier.close(); + assertTrue(zeroCount, "Expected 4 events, [create, start, die, stop]"); } /** * This method generates {#link KNOWN_NUM_EVENTS} events */ - private void generateEvents() { + private int generateEvents() { String testImage = "busybox"; asString(dockerClient.pullImageCmd(testImage).exec()); - CreateContainerResponse container1 = dockerClient + CreateContainerResponse container = dockerClient .createContainerCmd(testImage).withCmd("echo").exec(); - dockerClient.startContainerCmd(container1.getId()).exec(); - dockerClient.stopContainerCmd(container1.getId()).exec(); + dockerClient.startContainerCmd(container.getId()).exec(); + dockerClient.stopContainerCmd(container.getId()).exec(); + return KNOWN_NUM_EVENTS; } - private List pollEvents(EventStream eventStream) throws InterruptedException { - List eventList = Lists.newArrayList(); - Event event = null; - do { - event = eventStream.pollEvent(1, TimeUnit.SECONDS); - if (event != null) { - eventList.add(event); - } - } while (event != null); - return eventList; + private class EventCallbackTest implements EventCallback { + private final CountDownLatch countDownLatch; + + public EventCallbackTest(CountDownLatch countDownLatch) { + this.countDownLatch = countDownLatch; + } + + @Override + public void onEvent(Event event) { + LOG.info("Received event #{}: {}", countDownLatch.getCount(), event); + countDownLatch.countDown(); + } } } From 5ad41ae313093d91e65e31f797310d63d0c9baed Mon Sep 17 00:00:00 2001 From: Brendan Almonte Date: Sat, 20 Sep 2014 23:15:20 -0700 Subject: [PATCH 132/452] EventsAPI: Complete callback based EventNotifier --- .../dockerjava/api/command/EventsCmd.java | 10 +++-- .../dockerjava/api/model/EventNotifier.java | 41 ++++++++++--------- .../core/command/EventsCmdImpl.java | 19 +++++++-- .../dockerjava/jaxrs/EventsCmdExec.java | 11 +++-- .../core/command/EventsCmdImplTest.java | 20 +++++---- 5 files changed, 61 insertions(+), 40 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/EventsCmd.java b/src/main/java/com/github/dockerjava/api/command/EventsCmd.java index 28b5f509..0386c86a 100644 --- a/src/main/java/com/github/dockerjava/api/command/EventsCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/EventsCmd.java @@ -1,6 +1,6 @@ package com.github.dockerjava.api.command; -import com.github.dockerjava.api.model.EventNotifier; +import java.util.concurrent.ExecutorService; /** * Get events @@ -8,7 +8,7 @@ * @param since - Show all events created since timestamp * @param until - Stream events until this timestamp */ -public interface EventsCmd extends DockerCmd { +public interface EventsCmd extends DockerCmd { public EventsCmd withSince(String since); public EventsCmd withUntil(String until); @@ -19,6 +19,10 @@ public interface EventsCmd extends DockerCmd { public EventCallback getEventCallback(); - public static interface Exec extends DockerCmdExec { + public ExecutorService getExecutorService(); + + public void stop(); + + public static interface Exec extends DockerCmdExec { } } diff --git a/src/main/java/com/github/dockerjava/api/model/EventNotifier.java b/src/main/java/com/github/dockerjava/api/model/EventNotifier.java index f0522576..39d42931 100644 --- a/src/main/java/com/github/dockerjava/api/model/EventNotifier.java +++ b/src/main/java/com/github/dockerjava/api/model/EventNotifier.java @@ -7,44 +7,45 @@ import com.github.dockerjava.api.command.EventCallback; import com.google.common.base.Preconditions; -import java.io.Closeable; -import java.io.IOException; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; import java.io.InputStream; import java.util.concurrent.Callable; /** - * EventStream API - *

- * Spawns a thread to poll for events to fill a BlockingQueue + * EventNotifier API */ -public class EventNotifier implements Closeable, Callable { +public class EventNotifier implements Callable { private static final JsonFactory JSON_FACTORY = new JsonFactory(); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private final EventCallback eventCallback; - private final InputStream inputStream; + private final WebTarget webTarget; - private EventNotifier(EventCallback eventCallback, InputStream inputStream) { + private EventNotifier(EventCallback eventCallback, WebTarget webTarget) { this.eventCallback = eventCallback; - this.inputStream = inputStream; + this.webTarget = webTarget; } - public static EventNotifier create(EventCallback eventCallback, InputStream inputStream) { + public static EventNotifier create(EventCallback eventCallback, WebTarget webTarget) { Preconditions.checkNotNull(eventCallback, "An EventCallback must be provided"); - Preconditions.checkNotNull(inputStream, "An InputStream must be provided"); - return new EventNotifier(eventCallback, inputStream); - } - - @Override - public void close() throws IOException { - inputStream.close(); + Preconditions.checkNotNull(webTarget, "An WebTarget must be provided"); + return new EventNotifier(eventCallback, webTarget); } @Override public Void call() throws Exception { - JsonParser jp = JSON_FACTORY.createParser(inputStream); - while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed()) { - eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); + Response response = webTarget.request().get(Response.class); + InputStream inputStream = response.readEntity(InputStream.class); + try { + JsonParser jp = JSON_FACTORY.createParser(inputStream); + while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed()) { + eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); + } + } finally { + if (response != null) { + response.close(); + } } return null; } diff --git a/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java index 6129aa23..5f053ed9 100644 --- a/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java @@ -2,15 +2,18 @@ import com.github.dockerjava.api.command.EventCallback; import com.github.dockerjava.api.command.EventsCmd; -import com.github.dockerjava.api.model.EventNotifier; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; /** * Stream docker events */ -public class EventsCmdImpl extends AbstrDockerCmd implements EventsCmd { +public class EventsCmdImpl extends AbstrDockerCmd implements EventsCmd { private final EventCallback eventCallback; + private ExecutorService executorService = Executors.newSingleThreadExecutor(); private String since; private String until; @@ -47,7 +50,17 @@ public EventCallback getEventCallback() { } @Override - public EventNotifier exec() { + public ExecutorService getExecutorService() { + return executorService; + } + + @Override + public void stop() { + executorService.shutdown(); + } + + @Override + public Void exec() { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java index 8f8a1c83..8511c048 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -6,10 +6,8 @@ import org.slf4j.LoggerFactory; import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; -import java.io.InputStream; -public class EventsCmdExec extends AbstrDockerCmdExec implements EventsCmd.Exec { +public class EventsCmdExec extends AbstrDockerCmdExec implements EventsCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(EventsCmdExec.class); public EventsCmdExec(WebTarget baseResource) { @@ -17,13 +15,14 @@ public EventsCmdExec(WebTarget baseResource) { } @Override - protected EventNotifier execute(EventsCmd command) { + protected Void execute(EventsCmd command) { WebTarget webResource = getBaseResource().path("/events") .queryParam("since", command.getSince()) .queryParam("until", command.getUntil()); LOGGER.trace("GET: {}", webResource); - InputStream inputStream = webResource.request().get(Response.class).readEntity(InputStream.class); - return EventNotifier.create(command.getEventCallback(), inputStream); + EventNotifier eventNotifier = EventNotifier.create(command.getEventCallback(), webResource); + command.getExecutorService().submit(eventNotifier); + return null; } } diff --git a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java index 350c840e..82bc7ffe 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java @@ -3,8 +3,8 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.EventCallback; +import com.github.dockerjava.api.command.EventsCmd; import com.github.dockerjava.api.model.Event; -import com.github.dockerjava.api.model.EventNotifier; import com.github.dockerjava.client.AbstractDockerClientTest; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; @@ -15,7 +15,6 @@ import java.io.IOException; import java.lang.reflect.Method; -import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -59,9 +58,12 @@ public void testEventStreamTimeBound() throws InterruptedException, IOException CountDownLatch countDownLatch = new CountDownLatch(expectedEvents); EventCallback eventCallback = new EventCallbackTest(countDownLatch); - EventNotifier eventNotifier = dockerClient.eventsCmd(eventCallback).withSince(startTime).withUntil(endTime).exec(); - boolean zeroCount = countDownLatch.await(30, TimeUnit.SECONDS); - eventNotifier.close(); + EventsCmd eventsCmd = dockerClient.eventsCmd(eventCallback).withSince(startTime).withUntil(endTime); + eventsCmd.exec(); + + boolean zeroCount = countDownLatch.await(5, TimeUnit.SECONDS); + + eventsCmd.stop(); assertTrue(zeroCount, "Expected 4 events, [create, start, die, stop]"); } @@ -72,12 +74,14 @@ public void testEventStreaming() throws InterruptedException, IOException { CountDownLatch countDownLatch = new CountDownLatch(KNOWN_NUM_EVENTS); EventCallback eventCallback = new EventCallbackTest(countDownLatch); - EventNotifier eventNotifier = dockerClient.eventsCmd(eventCallback).withSince(getEpochTime()).exec(); + + EventsCmd eventsCmd = dockerClient.eventsCmd(eventCallback).withSince(getEpochTime()); + eventsCmd.exec(); generateEvents(); - boolean zeroCount = countDownLatch.await(30, TimeUnit.SECONDS); - eventNotifier.close(); + boolean zeroCount = countDownLatch.await(5, TimeUnit.SECONDS); + eventsCmd.stop(); assertTrue(zeroCount, "Expected 4 events, [create, start, die, stop]"); } From cdbd58ca0daea9d7a45832afdb70fc0497609564 Mon Sep 17 00:00:00 2001 From: Andrew Block Date: Sun, 21 Sep 2014 19:41:19 -0500 Subject: [PATCH 133/452] Added additional callback methods to EventCallback --- .../dockerjava/api/command/EventCallback.java | 2 ++ .../github/dockerjava/api/model/EventNotifier.java | 14 +++++++++++--- .../dockerjava/core/command/EventsCmdImplTest.java | 10 ++++++++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/EventCallback.java b/src/main/java/com/github/dockerjava/api/command/EventCallback.java index 009cc599..45ac34dc 100644 --- a/src/main/java/com/github/dockerjava/api/command/EventCallback.java +++ b/src/main/java/com/github/dockerjava/api/command/EventCallback.java @@ -7,4 +7,6 @@ */ public interface EventCallback { public void onEvent(Event event); + public void onException(Throwable throwable); + public void onCompletion(int numEvents); } diff --git a/src/main/java/com/github/dockerjava/api/model/EventNotifier.java b/src/main/java/com/github/dockerjava/api/model/EventNotifier.java index 39d42931..18363617 100644 --- a/src/main/java/com/github/dockerjava/api/model/EventNotifier.java +++ b/src/main/java/com/github/dockerjava/api/model/EventNotifier.java @@ -35,18 +35,26 @@ public static EventNotifier create(EventCallback eventCallback, WebTarget webTar @Override public Void call() throws Exception { - Response response = webTarget.request().get(Response.class); - InputStream inputStream = response.readEntity(InputStream.class); + int numEvents=0; + Response response = null; try { + response = webTarget.request().get(Response.class); + InputStream inputStream = response.readEntity(InputStream.class); JsonParser jp = JSON_FACTORY.createParser(inputStream); while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed()) { eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); + numEvents++; } - } finally { + } + catch(Exception e) { + eventCallback.onException(e); + } + finally { if (response != null) { response.close(); } } + eventCallback.onCompletion(numEvents); return null; } } diff --git a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java index 82bc7ffe..f75f7ed7 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java @@ -110,5 +110,15 @@ public void onEvent(Event event) { LOG.info("Received event #{}: {}", countDownLatch.getCount(), event); countDownLatch.countDown(); } + + @Override + public void onException(Throwable throwable) { + LOG.error("Error occurred: {}", throwable.getMessage()); + } + + @Override + public void onCompletion(int numEvents) { + LOG.info("Number of events received: {}", numEvents); + } } } From 8ee8d327b5dd430f6587d173ca27f530b61a889a Mon Sep 17 00:00:00 2001 From: Vincent Zurczak Date: Mon, 22 Sep 2014 14:16:18 +0200 Subject: [PATCH 134/452] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6dcb096e..e7bdf96f 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ In your application, e.g. config.withVersion("1.14"); config.withUsername("dockeruser"); config.withPassword("ilovedocker"); - config.withEmail("dockeruser@github.com); + config.withEmail("dockeruser@github.com"); DockerClient docker = DockerClientBuilder.getInstance( config ).build(); ##### System Properties: From f79e5112452f8ea03f4c73c95d8456e811e4b26c Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 22 Sep 2014 21:59:28 +0200 Subject: [PATCH 135/452] Modified Event Steam API --- .../dockerjava/api/command/EventsCmd.java | 11 ++-- .../core/command/EventsCmdImpl.java | 31 ++++------ .../dockerjava/jaxrs/EventsCmdExec.java | 62 +++++++++++++++++-- .../core/command/EventsCmdImplTest.java | 10 +-- 4 files changed, 80 insertions(+), 34 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/EventsCmd.java b/src/main/java/com/github/dockerjava/api/command/EventsCmd.java index 0386c86a..cfdb23a6 100644 --- a/src/main/java/com/github/dockerjava/api/command/EventsCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/EventsCmd.java @@ -2,13 +2,14 @@ import java.util.concurrent.ExecutorService; + /** * Get events * * @param since - Show all events created since timestamp * @param until - Stream events until this timestamp */ -public interface EventsCmd extends DockerCmd { +public interface EventsCmd extends DockerCmd { public EventsCmd withSince(String since); public EventsCmd withUntil(String until); @@ -18,11 +19,9 @@ public interface EventsCmd extends DockerCmd { public String getUntil(); public EventCallback getEventCallback(); + + public EventsCmd withEventCallback(EventCallback eventCallback); - public ExecutorService getExecutorService(); - - public void stop(); - - public static interface Exec extends DockerCmdExec { + public static interface Exec extends DockerCmdExec { } } diff --git a/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java index 5f053ed9..ac55de71 100644 --- a/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/EventsCmdImpl.java @@ -1,25 +1,22 @@ package com.github.dockerjava.core.command; +import java.util.concurrent.ExecutorService; + import com.github.dockerjava.api.command.EventCallback; import com.github.dockerjava.api.command.EventsCmd; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - /** * Stream docker events */ -public class EventsCmdImpl extends AbstrDockerCmd implements EventsCmd { +public class EventsCmdImpl extends AbstrDockerCmd implements EventsCmd { - private final EventCallback eventCallback; - - private ExecutorService executorService = Executors.newSingleThreadExecutor(); private String since; private String until; + private EventCallback eventCallback; public EventsCmdImpl(EventsCmd.Exec exec, EventCallback eventCallback) { super(exec); - this.eventCallback = eventCallback; + withEventCallback(eventCallback); } @Override @@ -33,6 +30,12 @@ public EventsCmd withUntil(String until) { this.until = until; return this; } + + @Override + public EventsCmd withEventCallback(EventCallback eventCallback) { + this.eventCallback = eventCallback; + return this; + } @Override public String getSince() { @@ -50,17 +53,7 @@ public EventCallback getEventCallback() { } @Override - public ExecutorService getExecutorService() { - return executorService; - } - - @Override - public void stop() { - executorService.shutdown(); - } - - @Override - public Void exec() { + public ExecutorService exec() { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java index 8511c048..63db6772 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -1,28 +1,80 @@ package com.github.dockerjava.jaxrs; +import java.io.InputStream; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.command.EventCallback; import com.github.dockerjava.api.command.EventsCmd; +import com.github.dockerjava.api.model.Event; import com.github.dockerjava.api.model.EventNotifier; +import com.google.common.base.Preconditions; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; -public class EventsCmdExec extends AbstrDockerCmdExec implements EventsCmd.Exec { +public class EventsCmdExec extends AbstrDockerCmdExec implements EventsCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(EventsCmdExec.class); - + public EventsCmdExec(WebTarget baseResource) { super(baseResource); } @Override - protected Void execute(EventsCmd command) { + protected ExecutorService execute(EventsCmd command) { + ExecutorService executorService = Executors.newSingleThreadExecutor(); + WebTarget webResource = getBaseResource().path("/events") .queryParam("since", command.getSince()) .queryParam("until", command.getUntil()); LOGGER.trace("GET: {}", webResource); EventNotifier eventNotifier = EventNotifier.create(command.getEventCallback(), webResource); - command.getExecutorService().submit(eventNotifier); - return null; + executorService.submit(eventNotifier); + return executorService; + } + + private static class EventNotifier implements Callable { + private static final JsonFactory JSON_FACTORY = new JsonFactory(); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private final EventCallback eventCallback; + private final WebTarget webTarget; + + private EventNotifier(EventCallback eventCallback, WebTarget webTarget) { + this.eventCallback = eventCallback; + this.webTarget = webTarget; + } + + public static EventNotifier create(EventCallback eventCallback, WebTarget webTarget) { + Preconditions.checkNotNull(eventCallback, "An EventCallback must be provided"); + Preconditions.checkNotNull(webTarget, "An WebTarget must be provided"); + return new EventNotifier(eventCallback, webTarget); + } + + @Override + public Void call() throws Exception { + Response response = webTarget.request().get(Response.class); + InputStream inputStream = response.readEntity(InputStream.class); + try { + JsonParser jp = JSON_FACTORY.createParser(inputStream); + while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed()) { + eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); + } + } finally { + if (response != null) { + response.close(); + } + } + return null; + } } } diff --git a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java index 82bc7ffe..6d3651c0 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java @@ -6,6 +6,7 @@ import com.github.dockerjava.api.command.EventsCmd; import com.github.dockerjava.api.model.Event; import com.github.dockerjava.client.AbstractDockerClientTest; + import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -16,6 +17,7 @@ import java.io.IOException; import java.lang.reflect.Method; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; public class EventsCmdImplTest extends AbstractDockerClientTest { @@ -59,11 +61,11 @@ public void testEventStreamTimeBound() throws InterruptedException, IOException EventCallback eventCallback = new EventCallbackTest(countDownLatch); EventsCmd eventsCmd = dockerClient.eventsCmd(eventCallback).withSince(startTime).withUntil(endTime); - eventsCmd.exec(); + ExecutorService executorService = eventsCmd.exec(); boolean zeroCount = countDownLatch.await(5, TimeUnit.SECONDS); - eventsCmd.stop(); + executorService.shutdown(); assertTrue(zeroCount, "Expected 4 events, [create, start, die, stop]"); } @@ -76,12 +78,12 @@ public void testEventStreaming() throws InterruptedException, IOException { EventCallback eventCallback = new EventCallbackTest(countDownLatch); EventsCmd eventsCmd = dockerClient.eventsCmd(eventCallback).withSince(getEpochTime()); - eventsCmd.exec(); + ExecutorService executorService = eventsCmd.exec(); generateEvents(); boolean zeroCount = countDownLatch.await(5, TimeUnit.SECONDS); - eventsCmd.stop(); + executorService.shutdown(); assertTrue(zeroCount, "Expected 4 events, [create, start, die, stop]"); } From ddaf529e15b5b2adf63d8e1a8bae2e6d6ce4f6b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20Sch=C3=BCth?= Date: Mon, 22 Sep 2014 22:24:14 +0200 Subject: [PATCH 136/452] Update readme to include corrected api example --- README.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index e7bdf96f..1728708b 100644 --- a/README.md +++ b/README.md @@ -80,12 +80,14 @@ There are three ways to configure, in descending order of precedence: ##### Programatic: In your application, e.g. - DockerClientConfig config = DockerClientConfig.createDefaultConfigBuilder(); - config.withVersion("1.14"); - config.withUsername("dockeruser"); - config.withPassword("ilovedocker"); - config.withEmail("dockeruser@github.com"); - DockerClient docker = DockerClientBuilder.getInstance( config ).build(); + DockerClientConfigBuilder configBuilder = DockerClientConfig.createDefaultConfigBuilder(); + configBuilder.withVersion("1.14"); + configBuilder.withUri("http://my-docker-host.tld:2375"); + configBuilder.withUsername("dockeruser"); + configBuilder.withPassword("ilovedocker"); + configBuilder.withEmail("dockeruser@github.com"); + DockerClientConfig config = configBuilder.build(); + DockerClient docker = DockerClientBuilder.getInstance(config).build(); ##### System Properties: E.g. From ce770cf1f1b4258ef27031b5831ff4ac1a160683 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 23 Sep 2014 07:20:42 +0200 Subject: [PATCH 137/452] Removed public EventNotifier model class --- .../dockerjava/api/model/EventNotifier.java | 52 ------------------- .../dockerjava/jaxrs/EventsCmdExec.java | 1 - 2 files changed, 53 deletions(-) delete mode 100644 src/main/java/com/github/dockerjava/api/model/EventNotifier.java diff --git a/src/main/java/com/github/dockerjava/api/model/EventNotifier.java b/src/main/java/com/github/dockerjava/api/model/EventNotifier.java deleted file mode 100644 index 39d42931..00000000 --- a/src/main/java/com/github/dockerjava/api/model/EventNotifier.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.github.dockerjava.api.model; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.dockerjava.api.command.EventCallback; -import com.google.common.base.Preconditions; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; -import java.io.InputStream; -import java.util.concurrent.Callable; - -/** - * EventNotifier API - */ -public class EventNotifier implements Callable { - private static final JsonFactory JSON_FACTORY = new JsonFactory(); - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - private final EventCallback eventCallback; - private final WebTarget webTarget; - - private EventNotifier(EventCallback eventCallback, WebTarget webTarget) { - this.eventCallback = eventCallback; - this.webTarget = webTarget; - } - - public static EventNotifier create(EventCallback eventCallback, WebTarget webTarget) { - Preconditions.checkNotNull(eventCallback, "An EventCallback must be provided"); - Preconditions.checkNotNull(webTarget, "An WebTarget must be provided"); - return new EventNotifier(eventCallback, webTarget); - } - - @Override - public Void call() throws Exception { - Response response = webTarget.request().get(Response.class); - InputStream inputStream = response.readEntity(InputStream.class); - try { - JsonParser jp = JSON_FACTORY.createParser(inputStream); - while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed()) { - eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); - } - } finally { - if (response != null) { - response.close(); - } - } - return null; - } -} diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java index 63db6772..7840d0af 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -12,7 +12,6 @@ import com.github.dockerjava.api.command.EventCallback; import com.github.dockerjava.api.command.EventsCmd; import com.github.dockerjava.api.model.Event; -import com.github.dockerjava.api.model.EventNotifier; import com.google.common.base.Preconditions; import org.slf4j.Logger; From 6d7d8bd3464036606f9c23ff159e52c06dbf21f1 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 24 Sep 2014 21:18:45 +0200 Subject: [PATCH 138/452] Isse #62 Allow to configure versionless requests --- .../github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index cb59f200..8b9f12eb 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -80,10 +80,10 @@ public void init(DockerClientConfig dockerClientConfig) { WebTarget webResource = client.target(dockerClientConfig.getUri()); - if (dockerClientConfig.getVersion() != null) { - baseResource = webResource.path("v" + dockerClientConfig.getVersion()); + if (dockerClientConfig.getVersion() == null || dockerClientConfig.getVersion().isEmpty()) { + baseResource = webResource; } else { - baseResource = webResource; + baseResource = webResource.path("v" + dockerClientConfig.getVersion()); } } From f5eaf1b0b02efea9b67379e1d1a8b885de39ce38 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Sat, 27 Sep 2014 18:54:07 +0200 Subject: [PATCH 139/452] Parsing serialized Bind with given access mode fails readWrite() and readOnly() both fail due to implementation errors in Bind.parse() --- .../github/dockerjava/api/model/BindTest.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/test/java/com/github/dockerjava/api/model/BindTest.java diff --git a/src/test/java/com/github/dockerjava/api/model/BindTest.java b/src/test/java/com/github/dockerjava/api/model/BindTest.java new file mode 100644 index 00000000..b7774452 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/BindTest.java @@ -0,0 +1,38 @@ +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +public class BindTest { + + @Test + public void parseUsingDefaultAccessMode() { + Bind bind = Bind.parse("/host:/container"); + assertEquals(bind.getPath(), "/host"); + assertEquals(bind.getVolume().getPath(), "/container"); + assertEquals(bind.isReadOnly(), false); + } + + @Test + public void parseReadWrite() { + Bind bind = Bind.parse("/host:/container:rw"); + assertEquals(bind.getPath(), "/host"); + assertEquals(bind.getVolume().getPath(), "/container"); + assertEquals(bind.isReadOnly(), false); + } + + @Test + public void parseReadOnly() { + Bind bind = Bind.parse("/host:/container:ro"); + assertEquals(bind.getPath(), "/host"); + assertEquals(bind.getVolume().getPath(), "/container"); + assertEquals(bind.isReadOnly(), true); + } + + @Test(expectedExceptions = RuntimeException.class) + public void parseInvalidAccessMode() { + Bind.parse("/host:/container:xx"); + } + +} From 1b74f6cca3ffab7b525a315aa74233388bc9def8 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Sat, 27 Sep 2014 19:14:25 +0200 Subject: [PATCH 140/452] Fix and improve parsing of serialized Bind --- .../java/com/github/dockerjava/api/model/Bind.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/api/model/Bind.java b/src/main/java/com/github/dockerjava/api/model/Bind.java index 6779e258..e654c7d5 100644 --- a/src/main/java/com/github/dockerjava/api/model/Bind.java +++ b/src/main/java/com/github/dockerjava/api/model/Bind.java @@ -33,6 +33,12 @@ public boolean isReadOnly() { return readOnly; } + /** + * Parses a bind mount specification to a {@link Bind}. + * + * @param serialized the specification, e.g. /host:/container:ro + * @return a {@link Bind} matching the specification + */ public static Bind parse(String serialized) { try { String[] parts = serialized.split(":"); @@ -41,7 +47,9 @@ public static Bind parse(String serialized) { return new Bind(parts[0], Volume.parse(parts[1])); } case 3: { - if ("rw".equals(parts[3].toLowerCase())) + if ("rw".equals(parts[2].toLowerCase())) + return new Bind(parts[0], Volume.parse(parts[1]), false); + else if ("ro".equals(parts[2].toLowerCase())) return new Bind(parts[0], Volume.parse(parts[1]), true); else throw new RuntimeException("Error parsing Bind '" From ed92136784dfa31477392e4f4f61d63d072e4b23 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Sun, 28 Sep 2014 13:58:38 +0200 Subject: [PATCH 141/452] Parsing invalid serialized Bind throws IllegalArgumentException --- .../com/github/dockerjava/api/model/Bind.java | 9 ++++----- .../github/dockerjava/api/model/BindTest.java | 17 +++++++++++++++-- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/model/Bind.java b/src/main/java/com/github/dockerjava/api/model/Bind.java index e654c7d5..0c4dd315 100644 --- a/src/main/java/com/github/dockerjava/api/model/Bind.java +++ b/src/main/java/com/github/dockerjava/api/model/Bind.java @@ -38,6 +38,7 @@ public boolean isReadOnly() { * * @param serialized the specification, e.g. /host:/container:ro * @return a {@link Bind} matching the specification + * @throws IllegalArgumentException if the specification cannot be parsed */ public static Bind parse(String serialized) { try { @@ -52,16 +53,14 @@ public static Bind parse(String serialized) { else if ("ro".equals(parts[2].toLowerCase())) return new Bind(parts[0], Volume.parse(parts[1]), true); else - throw new RuntimeException("Error parsing Bind '" - + serialized + "'"); + throw new IllegalArgumentException(); } default: { - throw new RuntimeException("Error parsing Bind '" + serialized - + "'"); + throw new IllegalArgumentException(); } } } catch (Exception e) { - throw new RuntimeException("Error parsing Bind '" + serialized + throw new IllegalArgumentException("Error parsing Bind '" + serialized + "'"); } } diff --git a/src/test/java/com/github/dockerjava/api/model/BindTest.java b/src/test/java/com/github/dockerjava/api/model/BindTest.java index b7774452..412c537f 100644 --- a/src/test/java/com/github/dockerjava/api/model/BindTest.java +++ b/src/test/java/com/github/dockerjava/api/model/BindTest.java @@ -30,9 +30,22 @@ public void parseReadOnly() { assertEquals(bind.isReadOnly(), true); } - @Test(expectedExceptions = RuntimeException.class) + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Bind.*") public void parseInvalidAccessMode() { Bind.parse("/host:/container:xx"); } - + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Bind 'nonsense'") + public void parseInvalidInput() { + Bind.parse("nonsense"); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Bind 'null'") + public void parseNull() { + Bind.parse(null); + } + } From c7bf107426879e7f57a8890514ab6cdf4466c3ed Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Tue, 30 Sep 2014 08:37:46 +0200 Subject: [PATCH 142/452] documented Jersey 1.x incompatibility --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 1728708b..78362d9f 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ Java API client for [Docker](http://docs.docker.io/ "Docker") Supports a subset of the Docker Client API v1.14, Docker Server version 1.2.0 +The current implementation is based on Jersey 2.x and therefore classpath incompatible with older Jersey 1.x dependent libraries! + Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/docker-java-dev "docker-java") ## Build with Maven From 2822e6b0d45c66d062ec2cdc33d3de212d33e4d4 Mon Sep 17 00:00:00 2001 From: Fredrik Vihlborg Date: Tue, 30 Sep 2014 20:11:04 +0200 Subject: [PATCH 143/452] Added static method udp in ExposedPort Analogue with tcp, nice to have. --- .../java/com/github/dockerjava/api/model/ExposedPort.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/com/github/dockerjava/api/model/ExposedPort.java b/src/main/java/com/github/dockerjava/api/model/ExposedPort.java index e5d4c02d..875a571a 100644 --- a/src/main/java/com/github/dockerjava/api/model/ExposedPort.java +++ b/src/main/java/com/github/dockerjava/api/model/ExposedPort.java @@ -44,6 +44,10 @@ public static ExposedPort tcp(int port) { return new ExposedPort("tcp", port); } + public static ExposedPort udp(int port) { + return new ExposedPort("udp", port); + } + public static ExposedPort parse(String serialized) { try { String[] parts = serialized.split("/"); From eeec33099ae839d1712c1f7fc01c6426f853c551 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Wed, 1 Oct 2014 17:50:58 +0200 Subject: [PATCH 144/452] typo in README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 78362d9f..f4ce58f8 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ listening on TCP port. To allow Docker server to use TCP add the following line DOCKER_OPTS="-H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock" -More details setting up docket server can be found in official documentation: http://docs.docker.io/en/latest/use/basics/ +More details setting up Docker server can be found in official documentation: http://docs.docker.io/en/latest/use/basics/ Now make sure that docker is up: From 57a625f4595c7ee7d0e7048e8ed86c1c9a178f1b Mon Sep 17 00:00:00 2001 From: Dan Griffin Date: Wed, 1 Oct 2014 17:01:38 +0100 Subject: [PATCH 145/452] Set Jersey client CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE This prevents Jersey SPI autodiscovery of other XML mapping libraries on your classpath --- .../com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 8b9f12eb..74d3073f 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -10,6 +10,7 @@ import com.github.dockerjava.api.command.EventsCmd; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.CommonProperties; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.github.dockerjava.api.command.AttachContainerCmd; @@ -63,6 +64,7 @@ public void init(DockerClientConfig dockerClientConfig) { Preconditions.checkNotNull(dockerClientConfig, "config was not specified"); ClientConfig clientConfig = new ClientConfig(); + clientConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); clientConfig.register(ResponseStatusExceptionFilter.class); clientConfig.register(JsonClientFilter.class); From 50577d2cedbccc781a871b9e05e7153d03d6aa1e Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 1 Oct 2014 20:36:37 +0200 Subject: [PATCH 146/452] fixed imports --- .../dockerjava/core/command/CreateContainerCmdImplTest.java | 2 +- .../github/dockerjava/core/command/PullImageCmdImplTest.java | 1 - .../dockerjava/core/command/WaitContainerCmdImplTest.java | 1 - 3 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index 84c9b35a..1320784c 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -101,7 +101,7 @@ public void createContainerWithEnv() throws DockerException { assertThat( Arrays.asList(inspectContainerResponse.getConfig().getEnv()), - contains("VARIABLE=success", "HOME=/", + containsInAnyOrder("VARIABLE=success", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")); dockerClient.startContainerCmd(container.getId()).exec(); diff --git a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java index 0ae36058..d44638f4 100644 --- a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java @@ -18,7 +18,6 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.InternalServerErrorException; -import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.api.model.Info; import com.github.dockerjava.client.AbstractDockerClientTest; diff --git a/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java index 4885b89e..64311803 100644 --- a/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java @@ -17,7 +17,6 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.InternalServerErrorException; -import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; From b84e5574ffd3b9704436028e38603c313799de6e Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 1 Oct 2014 22:12:51 +0200 Subject: [PATCH 147/452] make TestDockerCmdExecFactory a wrapper --- .../client/AbstractDockerClientTest.java | 5 +- .../core/TestDockerCmdExecFactory.java | 282 ++++++++++++++++++ .../jaxrs/TestDockerCmdExecFactory.java | 106 ------- 3 files changed, 285 insertions(+), 108 deletions(-) create mode 100644 src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java delete mode 100644 src/test/java/com/github/dockerjava/jaxrs/TestDockerCmdExecFactory.java diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index f8e67478..ddf5a903 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -16,8 +16,9 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.core.TestDockerCmdExecFactory; import com.github.dockerjava.jaxrs.DockerClientBuilder; -import com.github.dockerjava.jaxrs.TestDockerCmdExecFactory; +import com.github.dockerjava.jaxrs.DockerCmdExecFactoryImpl; public abstract class AbstractDockerClientTest extends Assert { @@ -26,7 +27,7 @@ public abstract class AbstractDockerClientTest extends Assert { protected DockerClient dockerClient; - protected TestDockerCmdExecFactory dockerCmdExecFactory = new TestDockerCmdExecFactory(); + protected TestDockerCmdExecFactory dockerCmdExecFactory = new TestDockerCmdExecFactory(new DockerCmdExecFactoryImpl()); public void beforeTest() { LOG.info("======================= BEFORETEST ======================="); diff --git a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java new file mode 100644 index 00000000..3a5857c9 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java @@ -0,0 +1,282 @@ +package com.github.dockerjava.core; + +import java.io.IOException; +import java.io.InputStream; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.List; + +import com.github.dockerjava.api.command.AttachContainerCmd; +import com.github.dockerjava.api.command.AuthCmd.Exec; +import com.github.dockerjava.api.command.BuildImageCmd; +import com.github.dockerjava.api.command.CommitCmd; +import com.github.dockerjava.api.command.ContainerDiffCmd; +import com.github.dockerjava.api.command.CopyFileFromContainerCmd; +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.CreateImageCmd; +import com.github.dockerjava.api.command.CreateImageResponse; +import com.github.dockerjava.api.command.DockerCmdExecFactory; +import com.github.dockerjava.api.command.EventsCmd; +import com.github.dockerjava.api.command.InfoCmd; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectImageCmd; +import com.github.dockerjava.api.command.KillContainerCmd; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.command.ListImagesCmd; +import com.github.dockerjava.api.command.LogContainerCmd; +import com.github.dockerjava.api.command.PauseContainerCmd; +import com.github.dockerjava.api.command.PingCmd; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.command.PushImageCmd; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.command.RemoveImageCmd; +import com.github.dockerjava.api.command.RestartContainerCmd; +import com.github.dockerjava.api.command.SearchImagesCmd; +import com.github.dockerjava.api.command.StartContainerCmd; +import com.github.dockerjava.api.command.StopContainerCmd; +import com.github.dockerjava.api.command.TagImageCmd; +import com.github.dockerjava.api.command.TopContainerCmd; +import com.github.dockerjava.api.command.UnpauseContainerCmd; +import com.github.dockerjava.api.command.VersionCmd; +import com.github.dockerjava.api.command.WaitContainerCmd; +import com.github.dockerjava.core.DockerClientConfig; + +/** + * Special {@link DockerCmdExecFactory} implementation that collects container and image creations + * while test execution for the purpose of automatically cleanup. + * + * @author marcus + * + */ +public class TestDockerCmdExecFactory implements DockerCmdExecFactory { + + private List containerNames = new ArrayList(); + + private List imageNames = new ArrayList(); + + private DockerCmdExecFactory delegate; + + public TestDockerCmdExecFactory(DockerCmdExecFactory delegate) { + this.delegate = delegate; + } + + @Override + public void init(DockerClientConfig dockerClientConfig) { + delegate.init(dockerClientConfig); + } + + @Override + public void close() throws IOException { + delegate.close(); + } + + @Override + public CreateContainerCmd.Exec createCreateContainerCmdExec() { + return new CreateContainerCmd.Exec() { + @Override + public CreateContainerResponse exec(CreateContainerCmd command) { + CreateContainerResponse createContainerResponse = delegate.createCreateContainerCmdExec().exec(command); + containerNames.add(createContainerResponse.getId()); + return createContainerResponse; + } + }; + } + + @Override + public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { + return new RemoveContainerCmd.Exec() { + @Override + public Void exec(RemoveContainerCmd command) { + delegate.createRemoveContainerCmdExec().exec(command); + containerNames.remove(command.getContainerId()); + return null; + } + }; + } + + @Override + public CreateImageCmd.Exec createCreateImageCmdExec() { + return new CreateImageCmd.Exec() { + @Override + public CreateImageResponse exec(CreateImageCmd command) { + CreateImageResponse createImageResponse = delegate.createCreateImageCmdExec().exec(command); + imageNames.add(createImageResponse.getId()); + return createImageResponse; + } + }; + } + + + + @Override + public RemoveImageCmd.Exec createRemoveImageCmdExec() { + return new RemoveImageCmd.Exec() { + @Override + public Void exec(RemoveImageCmd command) { + delegate.createRemoveImageCmdExec().exec(command); + imageNames.remove(command.getImageId()); + return null; + } + }; + } + + @Override + public BuildImageCmd.Exec createBuildImageCmdExec() { + return new BuildImageCmd.Exec() { + @Override + public InputStream exec(BuildImageCmd command) { + // can't detect image id here so tagging it + String tag = command.getTag(); + if(tag == null || "".equals(tag.trim())) { + tag = "" + new SecureRandom().nextInt(Integer.MAX_VALUE); + command.withTag(tag); + } + InputStream inputStream = delegate.createBuildImageCmdExec().exec(command); + imageNames.add(tag); + return inputStream; + } + }; + } + + @Override + public Exec createAuthCmdExec() { + return delegate.createAuthCmdExec(); + } + + @Override + public InfoCmd.Exec createInfoCmdExec() { + return delegate.createInfoCmdExec(); + } + + @Override + public PingCmd.Exec createPingCmdExec() { + return delegate.createPingCmdExec(); + } + + @Override + public VersionCmd.Exec createVersionCmdExec() { + return delegate.createVersionCmdExec(); + } + + @Override + public PullImageCmd.Exec createPullImageCmdExec() { + return delegate.createPullImageCmdExec(); + } + + @Override + public PushImageCmd.Exec createPushImageCmdExec() { + return delegate.createPushImageCmdExec(); + } + + @Override + public SearchImagesCmd.Exec createSearchImagesCmdExec() { + return delegate.createSearchImagesCmdExec(); + } + + @Override + public ListImagesCmd.Exec createListImagesCmdExec() { + return delegate.createListImagesCmdExec(); + } + + @Override + public InspectImageCmd.Exec createInspectImageCmdExec() { + return delegate.createInspectImageCmdExec(); + } + + @Override + public ListContainersCmd.Exec createListContainersCmdExec() { + return delegate.createListContainersCmdExec(); + } + + @Override + public StartContainerCmd.Exec createStartContainerCmdExec() { + return delegate.createStartContainerCmdExec(); + } + + @Override + public InspectContainerCmd.Exec createInspectContainerCmdExec() { + return delegate.createInspectContainerCmdExec(); + } + + @Override + public WaitContainerCmd.Exec createWaitContainerCmdExec() { + return delegate.createWaitContainerCmdExec(); + } + + @Override + public AttachContainerCmd.Exec createAttachContainerCmdExec() { + return delegate.createAttachContainerCmdExec(); + } + + @Override + public LogContainerCmd.Exec createLogContainerCmdExec() { + return delegate.createLogContainerCmdExec(); + } + + @Override + public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() { + return delegate.createCopyFileFromContainerCmdExec(); + } + + @Override + public StopContainerCmd.Exec createStopContainerCmdExec() { + return delegate.createStopContainerCmdExec(); + } + + @Override + public ContainerDiffCmd.Exec createContainerDiffCmdExec() { + return delegate.createContainerDiffCmdExec(); + } + + @Override + public KillContainerCmd.Exec createKillContainerCmdExec() { + return delegate.createKillContainerCmdExec(); + } + + @Override + public RestartContainerCmd.Exec createRestartContainerCmdExec() { + return delegate.createRestartContainerCmdExec(); + } + + @Override + public CommitCmd.Exec createCommitCmdExec() { + return delegate.createCommitCmdExec(); + } + + @Override + public TopContainerCmd.Exec createTopContainerCmdExec() { + return delegate.createTopContainerCmdExec(); + } + + @Override + public TagImageCmd.Exec createTagImageCmdExec() { + return delegate.createTagImageCmdExec(); + } + + @Override + public PauseContainerCmd.Exec createPauseContainerCmdExec() { + return delegate.createPauseContainerCmdExec(); + } + + @Override + public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { + return delegate.createUnpauseContainerCmdExec(); + } + + @Override + public EventsCmd.Exec createEventsCmdExec() { + return delegate.createEventsCmdExec(); + } + + public List getContainerNames() { + return new ArrayList(containerNames); + } + + public List getImageNames() { + return new ArrayList(imageNames); + } + + + +} diff --git a/src/test/java/com/github/dockerjava/jaxrs/TestDockerCmdExecFactory.java b/src/test/java/com/github/dockerjava/jaxrs/TestDockerCmdExecFactory.java deleted file mode 100644 index 8ff44a9a..00000000 --- a/src/test/java/com/github/dockerjava/jaxrs/TestDockerCmdExecFactory.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.github.dockerjava.jaxrs; - -import java.io.InputStream; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.List; - -import com.github.dockerjava.api.command.BuildImageCmd; -import com.github.dockerjava.api.command.CreateContainerCmd; -import com.github.dockerjava.api.command.CreateContainerResponse; -import com.github.dockerjava.api.command.CreateImageCmd; -import com.github.dockerjava.api.command.CreateImageResponse; -import com.github.dockerjava.api.command.DockerCmdExecFactory; -import com.github.dockerjava.api.command.RemoveContainerCmd; -import com.github.dockerjava.api.command.RemoveImageCmd; - -/** - * Special {@link DockerCmdExecFactory} implementation that collects container and image creations - * while test execution for the purpose of automatically cleanup. - * - * @author marcus - * - */ -public class TestDockerCmdExecFactory extends DockerCmdExecFactoryImpl { - - private List containerNames = new ArrayList(); - - private List imageNames = new ArrayList(); - - @Override - public CreateContainerCmd.Exec createCreateContainerCmdExec() { - return new CreateContainerCmdExec(getBaseResource()) { - @Override - public CreateContainerResponse exec(CreateContainerCmd command) { - CreateContainerResponse createContainerResponse = super.exec(command); - containerNames.add(createContainerResponse.getId()); - return createContainerResponse; - } - }; - } - - @Override - public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { - return new RemoveContainerCmdExec(getBaseResource()) { - @Override - public Void exec(RemoveContainerCmd command) { - super.exec(command); - containerNames.remove(command.getContainerId()); - return null; - } - }; - } - - @Override - public CreateImageCmd.Exec createCreateImageCmdExec() { - return new CreateImageCmdExec(getBaseResource()) { - @Override - public CreateImageResponse exec(CreateImageCmd command) { - CreateImageResponse createImageResponse = super.exec(command); - imageNames.add(createImageResponse.getId()); - return createImageResponse; - } - }; - } - - - - @Override - public RemoveImageCmd.Exec createRemoveImageCmdExec() { - return new RemoveImageCmdExec(getBaseResource()) { - @Override - public Void exec(RemoveImageCmd command) { - super.exec(command); - imageNames.remove(command.getImageId()); - return null; - } - }; - } - - @Override - public BuildImageCmd.Exec createBuildImageCmdExec() { - return new BuildImageCmdExec(getBaseResource()) { - @Override - public InputStream exec(BuildImageCmd command) { - // can't detect image id here so tagging it - String tag = command.getTag(); - if(tag == null || "".equals(tag.trim())) { - tag = "" + new SecureRandom().nextInt(Integer.MAX_VALUE); - command.withTag(tag); - } - InputStream inputStream = super.exec(command); - imageNames.add(tag); - return inputStream; - } - }; - } - - public List getContainerNames() { - return new ArrayList(containerNames); - } - - public List getImageNames() { - return new ArrayList(imageNames); - } - -} From 48ef8e364d725044862328fd6db0e3280c64ef51 Mon Sep 17 00:00:00 2001 From: Christian Heinemann Date: Thu, 2 Oct 2014 07:52:50 +0200 Subject: [PATCH 148/452] Use canonical form of Docker folder when building TAR files In BuildImageCmdImpl#buildDockerFolderTar a canonical form of the source files referenced in the Dockerfile is used. But the Docker folder is passed in the given form to the CompressArchiveUtil. CompressArchiveUtil#relativize creates absolute TAR archive entries if the canonical form of the source files differs from the given form of the Docker folder. As a result, the Docker deamon can not find the files during the build. This can happen in case-insensitive file systems such as Windows, for example. As a solution, the canonical form of the Docker folder must be used. --- .../java/com/github/dockerjava/core/CompressArchiveUtil.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java b/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java index 2cf341bd..a9a97238 100644 --- a/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java +++ b/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java @@ -15,7 +15,7 @@ public static File archiveTARFiles(File base, Iterable files, String archi tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); for (File file : files) { TarArchiveEntry tarEntry = new TarArchiveEntry(file); - tarEntry.setName(relativize(base, file)); + tarEntry.setName(relativize(base.getCanonicalFile(), file.getCanonicalFile())); if (!file.isDirectory()) { if (file.canExecute()) { From 7a5df6386561b5569ed91509549fe656c0adff27 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 2 Oct 2014 21:04:54 +0200 Subject: [PATCH 149/452] Move DockerClientBuilder to core --- .../{jaxrs => core}/DockerClientBuilder.java | 21 +++++++++++++++---- ...ockerjava.api.command.DockerCmdExecFactory | 1 + .../client/AbstractDockerClientTest.java | 5 ++--- .../core/command/AuthCmdImplTest.java | 6 ++---- 4 files changed, 22 insertions(+), 11 deletions(-) rename src/main/java/com/github/dockerjava/{jaxrs => core}/DockerClientBuilder.java (65%) create mode 100644 src/main/resources/META-INF/services/com.github.dockerjava.api.command.DockerCmdExecFactory diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerClientBuilder.java b/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java similarity index 65% rename from src/main/java/com/github/dockerjava/jaxrs/DockerClientBuilder.java rename to src/main/java/com/github/dockerjava/core/DockerClientBuilder.java index 96065b20..42d29bbc 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerClientBuilder.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java @@ -1,11 +1,13 @@ -package com.github.dockerjava.jaxrs; +package com.github.dockerjava.core; + +import java.util.ServiceLoader; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.DockerCmdExecFactory; -import com.github.dockerjava.core.DockerClientConfig; -import com.github.dockerjava.core.DockerClientImpl; public class DockerClientBuilder { + + private static ServiceLoader serviceLoader = ServiceLoader.load(DockerCmdExecFactory.class); private DockerClientImpl dockerClient = null; @@ -29,8 +31,19 @@ public static DockerClientBuilder getInstance(String serverUrl) { private static DockerClientImpl withDefaultDockerCmdExecFactory( DockerClientImpl dockerClient) { + + DockerCmdExecFactory dockerCmdExecFactory = getDefaultDockerCmdExecFactory(); + return dockerClient - .withDockerCmdExecFactory(new DockerCmdExecFactoryImpl()); + .withDockerCmdExecFactory(dockerCmdExecFactory); + } + + public static DockerCmdExecFactory getDefaultDockerCmdExecFactory() { + if(!serviceLoader.iterator().hasNext()) { + throw new RuntimeException("Fatal: Can't find any implementation of '" + DockerCmdExecFactory.class.getName() + "' in the current classpath."); + } + + return serviceLoader.iterator().next(); } public DockerClientBuilder withDockerCmdExecFactory( diff --git a/src/main/resources/META-INF/services/com.github.dockerjava.api.command.DockerCmdExecFactory b/src/main/resources/META-INF/services/com.github.dockerjava.api.command.DockerCmdExecFactory new file mode 100644 index 00000000..f0686bc9 --- /dev/null +++ b/src/main/resources/META-INF/services/com.github.dockerjava.api.command.DockerCmdExecFactory @@ -0,0 +1 @@ +com.github.dockerjava.jaxrs.DockerCmdExecFactoryImpl \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index ddf5a903..385508b6 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -16,9 +16,8 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.core.DockerClientBuilder; import com.github.dockerjava.core.TestDockerCmdExecFactory; -import com.github.dockerjava.jaxrs.DockerClientBuilder; -import com.github.dockerjava.jaxrs.DockerCmdExecFactoryImpl; public abstract class AbstractDockerClientTest extends Assert { @@ -27,7 +26,7 @@ public abstract class AbstractDockerClientTest extends Assert { protected DockerClient dockerClient; - protected TestDockerCmdExecFactory dockerCmdExecFactory = new TestDockerCmdExecFactory(new DockerCmdExecFactoryImpl()); + protected TestDockerCmdExecFactory dockerCmdExecFactory = new TestDockerCmdExecFactory(DockerClientBuilder.getDefaultDockerCmdExecFactory()); public void beforeTest() { LOG.info("======================= BEFORETEST ======================="); diff --git a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java index babe6b59..5645ccc0 100644 --- a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java @@ -13,8 +13,8 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.UnauthorizedException; import com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.core.DockerClientBuilder; import com.github.dockerjava.core.DockerClientConfig; -import com.github.dockerjava.jaxrs.DockerClientBuilder; public class AuthCmdImplTest extends AbstractDockerClientTest { @@ -53,8 +53,6 @@ public void testAuthInvalid() throws Exception { fail("Expected a UnauthorizedException caused by a bad password."); } catch (UnauthorizedException e) { - } finally { - client.close(); - } + } } } From 12237c2f0e28f3bf7bad4a5351aff5bd29dadf8c Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 2 Oct 2014 21:16:16 +0200 Subject: [PATCH 150/452] [maven-release-plugin] prepare release docker-java-0.10.2 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index d8f1fbac..d34d1ea4 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.2-SNAPSHOT + 0.10.2 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-0.10.2 From 50303882d8b2fd0276c386a09b91998b5c4ba726 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 2 Oct 2014 21:16:24 +0200 Subject: [PATCH 151/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index d34d1ea4..3934beea 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.2 + 0.10.3-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.10.2 + HEAD From 1c91db0dd95a68c861edd6d1abf53030095ee18e Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Tue, 7 Oct 2014 12:16:32 +0200 Subject: [PATCH 152/452] Use Bind.toString() in serialization This also changes the serialization in Binds.Serializer to always include the access mode. This is no problem in Docker API. --- .../com/github/dockerjava/api/model/Bind.java | 19 +++++++++++++++++++ .../github/dockerjava/api/model/Binds.java | 5 +---- .../github/dockerjava/api/model/Volume.java | 12 ++++++++++++ .../github/dockerjava/api/model/BindTest.java | 15 +++++++++++++++ .../dockerjava/api/model/VolumeTest.java | 12 ++++++++++++ 5 files changed, 59 insertions(+), 4 deletions(-) create mode 100644 src/test/java/com/github/dockerjava/api/model/VolumeTest.java diff --git a/src/main/java/com/github/dockerjava/api/model/Bind.java b/src/main/java/com/github/dockerjava/api/model/Bind.java index 0c4dd315..ffae75f6 100644 --- a/src/main/java/com/github/dockerjava/api/model/Bind.java +++ b/src/main/java/com/github/dockerjava/api/model/Bind.java @@ -3,6 +3,11 @@ import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; +/** + * Represents a host path being bind mounted as a {@link Volume} + * in a Docker container. + * The Bind can be in read only or read write access mode. + */ public class Bind { private String path; @@ -81,4 +86,18 @@ public int hashCode() { return new HashCodeBuilder().append(path).append(volume) .append(readOnly).toHashCode(); } + + /** + * Returns a string representation of this {@link Bind} suitable + * for inclusion in a JSON message. + * The format is <host path>:<container path>:<access mode>, + * like the argument in {@link #parse(String)}. + * + * @return a string representation of this {@link Bind} + */ + @Override + public String toString() { + return path + ":" + volume.toString() + (readOnly ? ":ro" : ":rw"); + } + } diff --git a/src/main/java/com/github/dockerjava/api/model/Binds.java b/src/main/java/com/github/dockerjava/api/model/Binds.java index 5b69edab..bfc8dbf2 100644 --- a/src/main/java/com/github/dockerjava/api/model/Binds.java +++ b/src/main/java/com/github/dockerjava/api/model/Binds.java @@ -44,10 +44,7 @@ public void serialize(Binds binds, JsonGenerator jsonGen, // jsonGen.writeStartArray(); for (Bind bind : binds.getBinds()) { - String s = bind.getPath() + ":" + bind.getVolume().toString(); - if(bind.isReadOnly()) s += ":ro"; - jsonGen.writeString(s); - + jsonGen.writeString(bind.toString()); } jsonGen.writeEndArray(); // diff --git a/src/main/java/com/github/dockerjava/api/model/Volume.java b/src/main/java/com/github/dockerjava/api/model/Volume.java index 50f62a27..1a189014 100644 --- a/src/main/java/com/github/dockerjava/api/model/Volume.java +++ b/src/main/java/com/github/dockerjava/api/model/Volume.java @@ -19,6 +19,11 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.node.NullNode; +/** + * Represents a bind mounted volume in a Docker container. + * + * @see Bind + */ @JsonDeserialize(using = Volume.Deserializer.class) @JsonSerialize(using = Volume.Serializer.class) public class Volume { @@ -43,6 +48,13 @@ public static Volume parse(String serialized) { return new Volume(serialized); } + /** + * Returns a string representation of this {@link Volume} suitable + * for inclusion in a JSON message. + * The returned String is simply the container path, {@link #getPath()}. + * + * @return a string representation of this {@link Volume} + */ @Override public String toString() { return getPath(); diff --git a/src/test/java/com/github/dockerjava/api/model/BindTest.java b/src/test/java/com/github/dockerjava/api/model/BindTest.java index 412c537f..bf96987e 100644 --- a/src/test/java/com/github/dockerjava/api/model/BindTest.java +++ b/src/test/java/com/github/dockerjava/api/model/BindTest.java @@ -48,4 +48,19 @@ public void parseNull() { Bind.parse(null); } + @Test + public void toStringReadOnly() { + assertEquals(Bind.parse("/host:/container:ro").toString(), "/host:/container:ro"); + } + + @Test + public void toStringReadWrite() { + assertEquals(Bind.parse("/host:/container:rw").toString(), "/host:/container:rw"); + } + + @Test + public void toStringDefaultAccessMode() { + assertEquals(Bind.parse("/host:/container").toString(), "/host:/container:rw"); + } + } diff --git a/src/test/java/com/github/dockerjava/api/model/VolumeTest.java b/src/test/java/com/github/dockerjava/api/model/VolumeTest.java new file mode 100644 index 00000000..8fdf1997 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/VolumeTest.java @@ -0,0 +1,12 @@ +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +public class VolumeTest { + @Test + public void stringify() { + assertEquals(Volume.parse("/path").toString(), "/path"); + } +} From 74ea00bc856b6b5d9d598397d2707c834240abf4 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Tue, 7 Oct 2014 13:29:37 +0200 Subject: [PATCH 153/452] New enum AccessMode improves instantiation and parsing of Bind --- .../dockerjava/api/model/AccessMode.java | 19 ++++++++ .../com/github/dockerjava/api/model/Bind.java | 43 +++++++++++++------ .../dockerjava/api/model/AccessModeTest.java | 31 +++++++++++++ .../github/dockerjava/api/model/BindTest.java | 8 ++-- .../command/StartContainerCmdImplTest.java | 3 +- 5 files changed, 86 insertions(+), 18 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/AccessMode.java create mode 100644 src/test/java/com/github/dockerjava/api/model/AccessModeTest.java diff --git a/src/main/java/com/github/dockerjava/api/model/AccessMode.java b/src/main/java/com/github/dockerjava/api/model/AccessMode.java new file mode 100644 index 00000000..e0106536 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/AccessMode.java @@ -0,0 +1,19 @@ +package com.github.dockerjava.api.model; + +/** + * The access mode of a file system or file: read-write + * or read-only. + */ +public enum AccessMode { + /** read-write */ + rw, + + /** read-only */ + ro; + + /** + * The default {@link AccessMode}: {@link #rw} + */ + public static final AccessMode DEFAULT = rw; + +} diff --git a/src/main/java/com/github/dockerjava/api/model/Bind.java b/src/main/java/com/github/dockerjava/api/model/Bind.java index ffae75f6..2a838c27 100644 --- a/src/main/java/com/github/dockerjava/api/model/Bind.java +++ b/src/main/java/com/github/dockerjava/api/model/Bind.java @@ -1,5 +1,8 @@ package com.github.dockerjava.api.model; +import static com.github.dockerjava.api.model.AccessMode.ro; +import static com.github.dockerjava.api.model.AccessMode.rw; + import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; @@ -14,16 +17,24 @@ public class Bind { private Volume volume; - private boolean readOnly = false; + private AccessMode accessMode; public Bind(String path, Volume volume) { - this(path, volume, false); + this(path, volume, AccessMode.DEFAULT); } - public Bind(String path, Volume volume, boolean readOnly) { + public Bind(String path, Volume volume, AccessMode accessMode) { this.path = path; this.volume = volume; - this.readOnly = readOnly; + this.accessMode = accessMode; + } + + /** + * @deprecated use {@link #Bind(String, Volume, AccessMode)} + */ + @Deprecated + public Bind(String path, Volume volume, boolean readOnly) { + this(path, volume, readOnly ? ro : rw); } public String getPath() { @@ -33,9 +44,17 @@ public String getPath() { public Volume getVolume() { return volume; } + + public AccessMode getAccessMode() { + return accessMode; + } + /** + * @deprecated use {@link #getAccessMode()} + */ + @Deprecated public boolean isReadOnly() { - return readOnly; + return ro.equals(accessMode); } /** @@ -53,12 +72,8 @@ public static Bind parse(String serialized) { return new Bind(parts[0], Volume.parse(parts[1])); } case 3: { - if ("rw".equals(parts[2].toLowerCase())) - return new Bind(parts[0], Volume.parse(parts[1]), false); - else if ("ro".equals(parts[2].toLowerCase())) - return new Bind(parts[0], Volume.parse(parts[1]), true); - else - throw new IllegalArgumentException(); + AccessMode accessMode = AccessMode.valueOf(parts[2].toLowerCase()); + return new Bind(parts[0], Volume.parse(parts[1]), accessMode); } default: { throw new IllegalArgumentException(); @@ -76,7 +91,7 @@ public boolean equals(Object obj) { Bind other = (Bind) obj; return new EqualsBuilder().append(path, other.getPath()) .append(volume, other.getVolume()) - .append(readOnly, other.isReadOnly()).isEquals(); + .append(accessMode, other.getAccessMode()).isEquals(); } else return super.equals(obj); } @@ -84,7 +99,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { return new HashCodeBuilder().append(path).append(volume) - .append(readOnly).toHashCode(); + .append(accessMode).toHashCode(); } /** @@ -97,7 +112,7 @@ public int hashCode() { */ @Override public String toString() { - return path + ":" + volume.toString() + (readOnly ? ":ro" : ":rw"); + return path + ":" + volume.toString() + ":" + accessMode.toString(); } } diff --git a/src/test/java/com/github/dockerjava/api/model/AccessModeTest.java b/src/test/java/com/github/dockerjava/api/model/AccessModeTest.java new file mode 100644 index 00000000..d9328958 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/AccessModeTest.java @@ -0,0 +1,31 @@ +package com.github.dockerjava.api.model; + +import static com.github.dockerjava.api.model.AccessMode.rw; +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +public class AccessModeTest { + + @Test + public void defaultAccessMode() { + assertEquals(AccessMode.DEFAULT, rw); + } + + @Test + public void stringify() { + assertEquals(AccessMode.rw.toString(), "rw"); + } + + @Test + public void fromString() { + assertEquals(AccessMode.valueOf("rw"), rw); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "No enum constant.*") + public void fromIllegalString() { + AccessMode.valueOf("xx"); + } + +} diff --git a/src/test/java/com/github/dockerjava/api/model/BindTest.java b/src/test/java/com/github/dockerjava/api/model/BindTest.java index bf96987e..50a41fc3 100644 --- a/src/test/java/com/github/dockerjava/api/model/BindTest.java +++ b/src/test/java/com/github/dockerjava/api/model/BindTest.java @@ -1,5 +1,7 @@ package com.github.dockerjava.api.model; +import static com.github.dockerjava.api.model.AccessMode.ro; +import static com.github.dockerjava.api.model.AccessMode.rw; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; @@ -11,7 +13,7 @@ public void parseUsingDefaultAccessMode() { Bind bind = Bind.parse("/host:/container"); assertEquals(bind.getPath(), "/host"); assertEquals(bind.getVolume().getPath(), "/container"); - assertEquals(bind.isReadOnly(), false); + assertEquals(bind.getAccessMode(), AccessMode.DEFAULT); } @Test @@ -19,7 +21,7 @@ public void parseReadWrite() { Bind bind = Bind.parse("/host:/container:rw"); assertEquals(bind.getPath(), "/host"); assertEquals(bind.getVolume().getPath(), "/container"); - assertEquals(bind.isReadOnly(), false); + assertEquals(bind.getAccessMode(), rw); } @Test @@ -27,7 +29,7 @@ public void parseReadOnly() { Bind bind = Bind.parse("/host:/container:ro"); assertEquals(bind.getPath(), "/host"); assertEquals(bind.getVolume().getPath(), "/container"); - assertEquals(bind.isReadOnly(), true); + assertEquals(bind.getAccessMode(), ro); } @Test(expectedExceptions = IllegalArgumentException.class, diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index a4533332..2c72c444 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -1,5 +1,6 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.api.model.AccessMode.ro; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; @@ -72,7 +73,7 @@ public void startContainerWithVolumes() throws DockerException { assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), contains("/opt/webapp1", "/opt/webapp2")); - dockerClient.startContainerCmd(container.getId()).withBinds(new Bind("/src/webapp1", volume1, true), new Bind("/src/webapp2", volume2)).exec(); + dockerClient.startContainerCmd(container.getId()).withBinds(new Bind("/src/webapp1", volume1, ro), new Bind("/src/webapp2", volume2)).exec(); dockerClient.waitContainerCmd(container.getId()).exec(); From e6d1c2f949eeec526692259a88c63349bd33c36a Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Tue, 14 Oct 2014 18:51:48 +0200 Subject: [PATCH 154/452] Throw IllegalArgumentException on Link.parse() parsing errors, javadoc --- .../com/github/dockerjava/api/model/Link.java | 38 +++++++++++++++++-- .../github/dockerjava/api/model/LinkTest.java | 28 ++++++++++++++ 2 files changed, 62 insertions(+), 4 deletions(-) create mode 100644 src/test/java/com/github/dockerjava/api/model/LinkTest.java diff --git a/src/main/java/com/github/dockerjava/api/model/Link.java b/src/main/java/com/github/dockerjava/api/model/Link.java index 9aa762a8..ced31322 100644 --- a/src/main/java/com/github/dockerjava/api/model/Link.java +++ b/src/main/java/com/github/dockerjava/api/model/Link.java @@ -1,9 +1,16 @@ - package com.github.dockerjava.api.model; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; +/** + * Represents a network link between two Docker containers. + * The container with the name {@link #getName()} is made available in the + * target container with the aliased name {@link #getAlias()}. + * This involves creating an entry in /etc/hosts and some environment + * variables in the target container as well as creating a network bridge between + * both containers. + */ public class Link { @@ -11,23 +18,46 @@ public class Link private final String alias; + /** + * Creates a {@link Link} for the container with the given name and an aliased + * name for use in the target container. + * + * @param name the name of the container that you want to link into the target + * container + * @param alias the aliased name under which the linked container will be available + * in the target container + */ public Link(final String name, final String alias) { this.name = name; this.alias = alias; } + /** + * @return the name of the container that is linked into the target container + */ public String getName() { return name; } + /** + * @return the aliased name under which the linked container will be available + * in the target container + */ public String getAlias() { return alias; } - public static Link parse(final String serialized) + /** + * Parses a textual link specification (as used by the Docker CLI) to a {@link Link}. + * + * @param serialized the specification, e.g. name:alias + * @return a {@link Link} matching the specification + * @throws IllegalArgumentException if the specification cannot be parsed + */ + public static Link parse(final String serialized) throws IllegalArgumentException { try { final String[] parts = serialized.split(":"); @@ -36,11 +66,11 @@ public static Link parse(final String serialized) return new Link(parts[0], parts[1]); } default: { - throw new RuntimeException("Error parsing Link '" + serialized + "'"); + throw new IllegalArgumentException(); } } } catch (final Exception e) { - throw new RuntimeException("Error parsing Link '" + serialized + "'"); + throw new IllegalArgumentException("Error parsing Link '" + serialized + "'"); } } diff --git a/src/test/java/com/github/dockerjava/api/model/LinkTest.java b/src/test/java/com/github/dockerjava/api/model/LinkTest.java new file mode 100644 index 00000000..c19f395b --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/LinkTest.java @@ -0,0 +1,28 @@ +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +public class LinkTest { + + @Test + public void parse() { + Link link = Link.parse("name:alias"); + assertEquals(link.getName(), "name"); + assertEquals(link.getAlias(), "alias"); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Link 'nonsense'") + public void parseInvalidInput() { + Link.parse("nonsense"); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Link 'null'") + public void parseNull() { + Link.parse(null); + } + +} From 4039ddbaa85e23fab71a461e876463e771b9aa27 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Tue, 14 Oct 2014 19:54:46 +0200 Subject: [PATCH 155/452] Use Link.toString() in serialization --- .../java/com/github/dockerjava/api/model/Link.java | 12 ++++++++++++ .../java/com/github/dockerjava/api/model/Links.java | 3 +-- .../com/github/dockerjava/api/model/LinkTest.java | 5 +++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/model/Link.java b/src/main/java/com/github/dockerjava/api/model/Link.java index ced31322..4416dca0 100644 --- a/src/main/java/com/github/dockerjava/api/model/Link.java +++ b/src/main/java/com/github/dockerjava/api/model/Link.java @@ -90,4 +90,16 @@ public int hashCode() return new HashCodeBuilder().append(name).append(alias).toHashCode(); } + /** + * Returns a string representation of this {@link Link} suitable + * for inclusion in a JSON message. + * The format is name:alias, like the argument in {@link #parse(String)}. + * + * @return a string representation of this {@link Link} + */ + @Override + public String toString() { + return name + ":" + alias; + } + } diff --git a/src/main/java/com/github/dockerjava/api/model/Links.java b/src/main/java/com/github/dockerjava/api/model/Links.java index 499e8440..b0d0cc8d 100644 --- a/src/main/java/com/github/dockerjava/api/model/Links.java +++ b/src/main/java/com/github/dockerjava/api/model/Links.java @@ -45,8 +45,7 @@ public void serialize(final Links links, final JsonGenerator jsonGen, final Seri { jsonGen.writeStartArray(); for (final Link link : links.getLinks()) { - final String s = link.getName() + ":" + link.getAlias(); - jsonGen.writeString(s); + jsonGen.writeString(link.toString()); } jsonGen.writeEndArray(); } diff --git a/src/test/java/com/github/dockerjava/api/model/LinkTest.java b/src/test/java/com/github/dockerjava/api/model/LinkTest.java index c19f395b..c42af9da 100644 --- a/src/test/java/com/github/dockerjava/api/model/LinkTest.java +++ b/src/test/java/com/github/dockerjava/api/model/LinkTest.java @@ -25,4 +25,9 @@ public void parseNull() { Link.parse(null); } + @Test + public void stringify() { + assertEquals(Link.parse("name:alias").toString(), "name:alias"); + } + } From 04cd1e645aa6107267c94912b0f9c70ffec5c23a Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Wed, 15 Oct 2014 18:32:30 +0200 Subject: [PATCH 156/452] Use project.build.sourceEncoding in compiler Defining a default encoding of UTF-8 in project.build.sourceEncoding and then overriding it in the compiler args with another (presumably wrong) encoding does not make sense. By default, will use project.build.sourceEncoding. --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3934beea..13c71b63 100644 --- a/pom.xml +++ b/pom.xml @@ -237,7 +237,6 @@ ${jdk.source} ${jdk.target} - ISO-8859-1 ${jdk.debug} ${jdk.optimize} From 8e31899b8543a051ef938cce5b500aacb043fe4b Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Wed, 15 Oct 2014 19:05:19 +0200 Subject: [PATCH 157/452] Use ExposedPort.toString() in serialization Changed type of parsing exception, added test and javadoc. --- .../dockerjava/api/model/ExposedPort.java | 53 ++++++++++++++++--- .../dockerjava/api/model/ExposedPorts.java | 3 +- .../github/dockerjava/api/model/Ports.java | 30 ++++++++++- .../dockerjava/api/model/ExposedPortTest.java | 32 +++++++++++ 4 files changed, 108 insertions(+), 10 deletions(-) create mode 100644 src/test/java/com/github/dockerjava/api/model/ExposedPortTest.java diff --git a/src/main/java/com/github/dockerjava/api/model/ExposedPort.java b/src/main/java/com/github/dockerjava/api/model/ExposedPort.java index 875a571a..d085f6c4 100644 --- a/src/main/java/com/github/dockerjava/api/model/ExposedPort.java +++ b/src/main/java/com/github/dockerjava/api/model/ExposedPort.java @@ -18,20 +18,38 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.node.NullNode; - +import com.github.dockerjava.api.model.Ports.Binding; + +/** + * Represents a container port that Docker exposes to external clients. + * The port is defined by its {@link #getPort() port number} and a + * {@link #getScheme() scheme}, e.g. tcp. + * It can be published by Docker by {@link Ports#bind(ExposedPort, Binding) binding} + * it to a host port, represented by a {@link Binding}. + */ @JsonDeserialize(using = ExposedPort.Deserializer.class) @JsonSerialize(using = ExposedPort.Serializer.class) public class ExposedPort { - private String scheme; + private final String scheme; - private int port; + private final int port; + /** + * Creates an {@link ExposedPort} for the given parameters. + * + * @param scheme the {@link #getScheme() scheme}, tcp or + * udp + * @param port the {@link #getPort() port number} + */ public ExposedPort(String scheme, int port) { this.scheme = scheme; this.port = port; } + /** + * @return the scheme (IP protocol), tcp or udp + */ public String getScheme() { return scheme; } @@ -40,27 +58,50 @@ public int getPort() { return port; } + /** + * Creates an {@link ExposedPort} for the TCP scheme. + * This is a shortcut for new ExposedPort("tcp", port) + */ public static ExposedPort tcp(int port) { return new ExposedPort("tcp", port); } + /** + * Creates an {@link ExposedPort} for the UDP scheme. + * This is a shortcut for new ExposedPort("udp", port) + */ public static ExposedPort udp(int port) { return new ExposedPort("udp", port); } - public static ExposedPort parse(String serialized) { + /** + * Parses a textual port specification (as used by the Docker CLI) to an + * {@link ExposedPort}. + * + * @param serialized the specification, e.g. 80/tcp + * @return an {@link ExposedPort} matching the specification + * @throws IllegalArgumentException if the specification cannot be parsed + */ + public static ExposedPort parse(String serialized) throws IllegalArgumentException { try { String[] parts = serialized.split("/"); ExposedPort out = new ExposedPort(parts[1], Integer.valueOf(parts[0])); return out; } catch (Exception e) { - throw new RuntimeException("Error parsing ExposedPort '" + serialized + "'"); + throw new IllegalArgumentException("Error parsing ExposedPort '" + serialized + "'"); } } + /** + * Returns a string representation of this {@link ExposedPort} suitable + * for inclusion in a JSON message. + * The format is port/scheme, like the argument in {@link #parse(String)}. + * + * @return a string representation of this {@link ExposedPort} + */ @Override public String toString() { - return getPort() + "/" + getScheme(); + return port + "/" + scheme; } @Override diff --git a/src/main/java/com/github/dockerjava/api/model/ExposedPorts.java b/src/main/java/com/github/dockerjava/api/model/ExposedPorts.java index c9e15758..924d1300 100644 --- a/src/main/java/com/github/dockerjava/api/model/ExposedPorts.java +++ b/src/main/java/com/github/dockerjava/api/model/ExposedPorts.java @@ -43,8 +43,7 @@ public void serialize(ExposedPorts exposedPorts, JsonGenerator jsonGen, jsonGen.writeStartObject(); for (ExposedPort exposedPort : exposedPorts.getExposedPorts()) { - jsonGen.writeFieldName(exposedPort.getPort() + "/" - + exposedPort.getScheme()); + jsonGen.writeFieldName(exposedPort.toString()); jsonGen.writeStartObject(); jsonGen.writeEndObject(); } diff --git a/src/main/java/com/github/dockerjava/api/model/Ports.java b/src/main/java/com/github/dockerjava/api/model/Ports.java index 5a182c04..fe790468 100644 --- a/src/main/java/com/github/dockerjava/api/model/Ports.java +++ b/src/main/java/com/github/dockerjava/api/model/Ports.java @@ -20,8 +20,18 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.node.NullNode; +import com.github.dockerjava.api.command.InspectContainerResponse.HostConfig; +import com.github.dockerjava.api.command.InspectContainerResponse.NetworkSettings; + import org.apache.commons.lang.builder.ToStringBuilder; +/** + * A container for port bindings, made available as a {@link Map} via its + * {@link #getBindings()} method. + * + * @see HostConfig#getPortBindings() + * @see NetworkSettings#getPorts() + */ @JsonDeserialize(using = Ports.Deserializer.class) @JsonSerialize(using = Ports.Serializer.class) public class Ports { @@ -43,6 +53,10 @@ public String toString(){ return ports.toString(); } + /** + * @return the port bindings as a {@link Map} that contains one + * {@link Binding} per {@link ExposedPort}. + */ public Map getBindings(){ return ports; } @@ -55,13 +69,25 @@ public static Binding Binding(int hostPort) { } + /** + * The host part of a port binding. + * In a port binding a container port, expressed as an {@link ExposedPort}, + * is published as a port of the Docker host. + * + * @see ExposedPort + */ public static class Binding { - private final String hostIp; private final int hostPort; + /** + * Creates the host part of a port binding. + * + * @see Ports#bind(ExposedPort, Binding) + * @see ExposedPort + */ public Binding(String hostIp, int hostPort) { this.hostIp = hostIp; this.hostPort = hostPort; @@ -125,7 +151,7 @@ public void serialize(Ports portBindings, JsonGenerator jsonGen, jsonGen.writeStartObject(); for(Entry entry : portBindings.getBindings().entrySet()){ - jsonGen.writeFieldName(entry.getKey().getPort() + "/" + entry.getKey().getScheme()); + jsonGen.writeFieldName(entry.getKey().toString()); jsonGen.writeStartArray(); jsonGen.writeStartObject(); jsonGen.writeStringField("HostIp", entry.getValue().getHostIp()); diff --git a/src/test/java/com/github/dockerjava/api/model/ExposedPortTest.java b/src/test/java/com/github/dockerjava/api/model/ExposedPortTest.java new file mode 100644 index 00000000..052e44ff --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/ExposedPortTest.java @@ -0,0 +1,32 @@ +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +public class ExposedPortTest { + + @Test + public void parse() { + ExposedPort exposedPort = ExposedPort.parse("80/tcp"); + assertEquals(exposedPort.getPort(), 80); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing ExposedPort 'nonsense'") + public void parseInvalidInput() { + ExposedPort.parse("nonsense"); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing ExposedPort 'null'") + public void parseNull() { + ExposedPort.parse(null); + } + + @Test + public void stringify() { + assertEquals(ExposedPort.parse("80/tcp").toString(), "80/tcp"); + } + +} From 68c7fc03aec4118318ece3192f8ad480fd682125 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Thu, 16 Oct 2014 10:38:05 +0200 Subject: [PATCH 158/452] New enum "InternetProtocol" for supported IP protocols replaces scheme The enum provides a home for parsing, stringification and the default value of the supported protocols. It also enforces the use of the more correct term "internet protocol" instead of "scheme". --- .../dockerjava/api/model/ExposedPort.java | 61 +++++++++++++------ .../api/model/InternetProtocol.java | 49 +++++++++++++++ .../api/model/InternetProtocolTest.java | 42 +++++++++++++ 3 files changed, 132 insertions(+), 20 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/InternetProtocol.java create mode 100644 src/test/java/com/github/dockerjava/api/model/InternetProtocolTest.java diff --git a/src/main/java/com/github/dockerjava/api/model/ExposedPort.java b/src/main/java/com/github/dockerjava/api/model/ExposedPort.java index d085f6c4..d19bfbf0 100644 --- a/src/main/java/com/github/dockerjava/api/model/ExposedPort.java +++ b/src/main/java/com/github/dockerjava/api/model/ExposedPort.java @@ -1,5 +1,8 @@ package com.github.dockerjava.api.model; +import static com.github.dockerjava.api.model.InternetProtocol.TCP; +import static com.github.dockerjava.api.model.InternetProtocol.UDP; + import java.io.IOException; import java.util.Map.Entry; @@ -22,8 +25,8 @@ /** * Represents a container port that Docker exposes to external clients. - * The port is defined by its {@link #getPort() port number} and a - * {@link #getScheme() scheme}, e.g. tcp. + * The port is defined by its {@link #getPort() port number} and an + * {@link InternetProtocol}. * It can be published by Docker by {@link Ports#bind(ExposedPort, Binding) binding} * it to a host port, represented by a {@link Binding}. */ @@ -31,47 +34,66 @@ @JsonSerialize(using = ExposedPort.Serializer.class) public class ExposedPort { - private final String scheme; - + private final InternetProtocol protocol; private final int port; + /** + * Creates an {@link ExposedPort} for the given parameters. + * + * @param port the {@link #getPort() port number} + * @param protocol the {@link InternetProtocol} + */ + public ExposedPort(int port, InternetProtocol protocol) { + this.port = port; + this.protocol = protocol; + } + /** * Creates an {@link ExposedPort} for the given parameters. * * @param scheme the {@link #getScheme() scheme}, tcp or * udp * @param port the {@link #getPort() port number} + * @deprecated use {@link #ExposedPort(int, InternetProtocol)} */ + @Deprecated public ExposedPort(String scheme, int port) { - this.scheme = scheme; - this.port = port; + this(port, InternetProtocol.valueOf(scheme)); } + /** @return the {@link InternetProtocol} */ + public InternetProtocol getProtocol() { + return protocol; + } + /** - * @return the scheme (IP protocol), tcp or udp + * @return the scheme (internet protocol), tcp or udp + * @deprecated use {@link #getProtocol()} */ + @Deprecated public String getScheme() { - return scheme; + return protocol.toString(); } + /** @return the port number */ public int getPort() { return port; } /** - * Creates an {@link ExposedPort} for the TCP scheme. - * This is a shortcut for new ExposedPort("tcp", port) + * Creates an {@link ExposedPort} for {@link InternetProtocol#TCP}. + * This is a shortcut for new ExposedPort(port, {@link InternetProtocol#TCP}) */ public static ExposedPort tcp(int port) { - return new ExposedPort("tcp", port); + return new ExposedPort(port, TCP); } /** - * Creates an {@link ExposedPort} for the UDP scheme. - * This is a shortcut for new ExposedPort("udp", port) + * Creates an {@link ExposedPort} for {@link InternetProtocol#UDP}. + * This is a shortcut for new ExposedPort(port, {@link InternetProtocol#UDP}) */ public static ExposedPort udp(int port) { - return new ExposedPort("udp", port); + return new ExposedPort(port, UDP); } /** @@ -85,8 +107,7 @@ public static ExposedPort udp(int port) { public static ExposedPort parse(String serialized) throws IllegalArgumentException { try { String[] parts = serialized.split("/"); - ExposedPort out = new ExposedPort(parts[1], Integer.valueOf(parts[0])); - return out; + return new ExposedPort(Integer.valueOf(parts[0]), InternetProtocol.parse(parts[1])); } catch (Exception e) { throw new IllegalArgumentException("Error parsing ExposedPort '" + serialized + "'"); } @@ -95,20 +116,20 @@ public static ExposedPort parse(String serialized) throws IllegalArgumentExcepti /** * Returns a string representation of this {@link ExposedPort} suitable * for inclusion in a JSON message. - * The format is port/scheme, like the argument in {@link #parse(String)}. + * The format is port/protocol, like the argument in {@link #parse(String)}. * * @return a string representation of this {@link ExposedPort} */ @Override public String toString() { - return port + "/" + scheme; + return port + "/" + protocol.toString(); } @Override public boolean equals(Object obj) { if (obj instanceof ExposedPort) { ExposedPort other = (ExposedPort) obj; - return new EqualsBuilder().append(scheme, other.getScheme()) + return new EqualsBuilder().append(protocol, other.getProtocol()) .append(port, other.getPort()).isEquals(); } else return super.equals(obj); @@ -116,7 +137,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return new HashCodeBuilder().append(scheme).append(port).toHashCode(); + return new HashCodeBuilder().append(protocol).append(port).toHashCode(); } public static class Deserializer extends JsonDeserializer { diff --git a/src/main/java/com/github/dockerjava/api/model/InternetProtocol.java b/src/main/java/com/github/dockerjava/api/model/InternetProtocol.java new file mode 100644 index 00000000..96c21524 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/InternetProtocol.java @@ -0,0 +1,49 @@ +package com.github.dockerjava.api.model; + + +/** + * The IP protocols supported by Docker. + * + * @see #TCP + * @see #UDP + */ +public enum InternetProtocol { + /** The Transmission Control Protocol */ + TCP, + + /** The User Datagram Protocol */ + UDP; + + /** + * The default {@link InternetProtocol}: {@link #TCP} + */ + public static final InternetProtocol DEFAULT = TCP; + + /** + * Returns a string representation of this {@link InternetProtocol} suitable + * for inclusion in a JSON message. + * The output is the lowercased name of the Protocol, e.g. tcp. + * + * @return a string representation of this {@link InternetProtocol} + */ + @Override + public String toString() { + return super.toString().toLowerCase(); + } + + /** + * Parses a string to an {@link InternetProtocol}. + * + * @param serialized the protocol, e.g. tcp or TCP + * @return an {@link InternetProtocol} described by the string + * @throws IllegalArgumentException if the argument cannot be parsed + */ + public static InternetProtocol parse(String serialized) throws IllegalArgumentException { + try { + return valueOf(serialized.toUpperCase()); + } catch (Exception e) { + throw new IllegalArgumentException("Error parsing Protocol '" + serialized + "'"); + } + } + +} diff --git a/src/test/java/com/github/dockerjava/api/model/InternetProtocolTest.java b/src/test/java/com/github/dockerjava/api/model/InternetProtocolTest.java new file mode 100644 index 00000000..ea0b20d7 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/InternetProtocolTest.java @@ -0,0 +1,42 @@ +package com.github.dockerjava.api.model; + +import static com.github.dockerjava.api.model.InternetProtocol.*; +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +public class InternetProtocolTest { + + @Test + public void defaultProtocol() { + assertEquals(InternetProtocol.DEFAULT, TCP); + } + + @Test + public void stringify() { + assertEquals(TCP.toString(), "tcp"); + } + + @Test + public void parseUpperCase() { + assertEquals(InternetProtocol.parse("TCP"), TCP); + } + + @Test + public void parseLowerCase() { + assertEquals(InternetProtocol.parse("tcp"), TCP); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Protocol.*") + public void parseInvalidInput() { + InternetProtocol.parse("xx"); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Protocol 'null'") + public void parseNull() { + InternetProtocol.parse(null); + } + +} From 8a9b9e4107e69d818dd3544879db404245cc0867 Mon Sep 17 00:00:00 2001 From: Andrew Block Date: Sun, 19 Oct 2014 08:19:25 -0400 Subject: [PATCH 159/452] Added SSL support --- .../dockerjava/core/DockerClientConfig.java | 48 ++++++++++++++++-- .../jaxrs/DockerCmdExecFactoryImpl.java | 49 ++++++++++++++----- 2 files changed, 80 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index b2adea7f..9c2b5867 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -10,7 +10,7 @@ public class DockerClientConfig { private final URI uri; - private final String version, username, password, email; + private final String version, username, password, email, keystore, keystorePassword, truststore, truststorePassword; private final Integer readTimeout; private final boolean loggingFilterEnabled; @@ -22,6 +22,10 @@ private DockerClientConfig(DockerClientConfigBuilder builder) { this.email = builder.email; this.readTimeout = builder.readTimeout; this.loggingFilterEnabled = builder.loggingFilterEnabled; + this.keystore = builder.keystore; + this.keystorePassword = builder.keystorePassword; + this.truststore = builder.truststore; + this.truststorePassword = builder.truststorePassword; } public URI getUri() { @@ -51,6 +55,22 @@ public Integer getReadTimeout() { public boolean isLoggingFilterEnabled() { return loggingFilterEnabled; } + + public String getKeystore() { + return keystore; + } + + public String getKeystorePassword() { + return keystorePassword; + } + + public String getTruststore() { + return truststore; + } + + public String getTruststorePassword() { + return truststorePassword; + } public static Properties loadIncludedDockerProperties() { try { @@ -97,7 +117,7 @@ public static Properties overrideDockerPropertiesWithSystemProperties(Properties overriddenProperties.putAll(p); // TODO Add all values from system properties that begin with docker.io.* - for (String s : new String[]{ "url", "version", "username", "password", "email", "readTimeout", "enableLoggingFilter"}) { + for (String s : new String[]{ "url", "version", "username", "password", "email", "readTimeout", "enableLoggingFilter", "keystore", "keystorePassword", "truststore", "truststorePassword"}) { final String key = "docker.io." + s; if (System.getProperties().containsKey(key)) { overriddenProperties.setProperty(key, System.getProperty(key)); @@ -115,7 +135,7 @@ public static DockerClientConfigBuilder createDefaultConfigBuilder() { public static class DockerClientConfigBuilder { private URI uri; - private String version, username, password, email; + private String version, username, password, email, keystore, keystorePassword, truststore, truststorePassword; private Integer readTimeout; private boolean loggingFilterEnabled; @@ -138,7 +158,11 @@ public DockerClientConfigBuilder withProperties(Properties p) { .withPassword(p.getProperty("docker.io.password")) .withEmail(p.getProperty("docker.io.email")) .withReadTimeout(Integer.valueOf(p.getProperty("docker.io.readTimeout", "0"))) - .withLoggingFilter(Boolean.valueOf(p.getProperty("docker.io.enableLoggingFilter", "true"))); + .withLoggingFilter(Boolean.valueOf(p.getProperty("docker.io.enableLoggingFilter", "true"))) + .withKeystore(p.getProperty("docker.io.keystore")) + .withKeystorePassword(p.getProperty("docker.io.keystorePassword")) + .withTruststore(p.getProperty("docker.io.truststore")) + .withTruststorePassword(p.getProperty("docker.io.truststorePassword")); } public final DockerClientConfigBuilder withUri(String uri) { @@ -170,6 +194,22 @@ public final DockerClientConfigBuilder withLoggingFilter(boolean loggingFilterEn this.loggingFilterEnabled = loggingFilterEnabled; return this; } + public final DockerClientConfigBuilder withKeystore(String keystore) { + this.keystore = keystore; + return this; + } + public final DockerClientConfigBuilder withKeystorePassword(String keystorePassword) { + this.keystorePassword = keystorePassword; + return this; + } + public final DockerClientConfigBuilder withTruststore(String truststore) { + this.truststore = truststore; + return this; + } + public final DockerClientConfigBuilder withTruststorePassword(String truststorePassword) { + this.truststorePassword = truststorePassword; + return this; + } public DockerClientConfig build() { return new DockerClientConfig(this); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 74d3073f..1a70ccbe 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -1,17 +1,5 @@ package com.github.dockerjava.jaxrs; -import java.io.IOException; -import java.util.logging.Logger; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; - -import com.github.dockerjava.api.command.EventsCmd; -import org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.client.ClientProperties; -import org.glassfish.jersey.CommonProperties; - import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.github.dockerjava.api.command.AttachContainerCmd; import com.github.dockerjava.api.command.AuthCmd; @@ -22,6 +10,7 @@ import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateImageCmd; import com.github.dockerjava.api.command.DockerCmdExecFactory; +import com.github.dockerjava.api.command.EventsCmd; import com.github.dockerjava.api.command.InfoCmd; import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectImageCmd; @@ -50,6 +39,19 @@ import com.github.dockerjava.jaxrs.util.SelectiveLoggingFilter; import com.google.common.base.Preconditions; +import java.io.IOException; +import java.util.logging.Logger; + +import javax.net.ssl.SSLContext; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; + +import org.glassfish.jersey.CommonProperties; +import org.glassfish.jersey.SslConfigurator; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; + public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { private Client client; @@ -78,7 +80,28 @@ public void init(DockerClientConfig dockerClientConfig) { int readTimeout = dockerClientConfig.getReadTimeout(); clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); } - client = ClientBuilder.newClient(clientConfig); + + ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig); + + + if((dockerClientConfig.getKeystore() != null && dockerClientConfig.getKeystorePassword() != null) || (dockerClientConfig.getTruststore() != null && dockerClientConfig.getTruststorePassword() != null)) { + SslConfigurator sslConfig = SslConfigurator.newInstance(); + + if(dockerClientConfig.getKeystore() != null && dockerClientConfig.getKeystorePassword() != null) { + sslConfig.keyStoreFile(dockerClientConfig.getKeystore()); + sslConfig.keyStorePassword(dockerClientConfig.getKeystorePassword()); + } + + if(dockerClientConfig.getTruststore() != null && dockerClientConfig.getTruststorePassword() != null) { + sslConfig.trustStoreFile(dockerClientConfig.getTruststore()); + sslConfig.trustStorePassword(dockerClientConfig.getTruststorePassword()); + } + + SSLContext sslContext = sslConfig.createSSLContext(); + clientBuilder.sslContext(sslContext); + } + + client = clientBuilder.build(); WebTarget webResource = client.target(dockerClientConfig.getUri()); From ea72d6b2966d6fd600403ae15cfd79813c13cc73 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Mon, 20 Oct 2014 10:53:51 +0200 Subject: [PATCH 160/452] Allow fast tests to execute during standard build Use TestNG's test groups feature to distinguish between fast, self contained unit tests and slow integration tests that access external services. Move the latter ones to the integration test phase and disable them by default. --- README.md | 9 +++- pom.xml | 46 ++++++++++++++----- .../dockerjava/client/DockerClientTest.java | 1 + .../core/command/AuthCmdImplTest.java | 1 + .../core/command/BuildImageCmdImplTest.java | 1 + .../core/command/CommitCmdImplTest.java | 1 + .../command/ContainerDiffCmdImplTest.java | 1 + .../CopyFileFromContainerCmdImplTest.java | 1 + .../command/CreateContainerCmdImplTest.java | 1 + .../core/command/EventsCmdImplTest.java | 1 + .../core/command/InfoCmdImplTest.java | 1 + .../command/KillContainerCmdImplTest.java | 1 + .../command/ListContainersCmdImplTest.java | 1 + .../core/command/ListImagesCmdImplTest.java | 1 + .../core/command/LogContainerCmdImplTest.java | 1 + .../core/command/PullImageCmdImplTest.java | 1 + .../core/command/PushImageCmdImplTest.java | 1 + .../command/RemoveContainerCmdImplTest.java | 1 + .../core/command/RemoveImageCmdImplTest.java | 1 + .../command/RestartContainerCmdImplTest.java | 1 + .../core/command/SearchImagesCmdImplTest.java | 1 + .../command/StartContainerCmdImplTest.java | 2 +- .../command/StopContainerCmdImplTest.java | 1 + .../core/command/TagImageCmdImplTest.java | 1 + .../core/command/VersionCmdImplTest.java | 1 + .../command/WaitContainerCmdImplTest.java | 1 + 26 files changed, 65 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index f4ce58f8..3e9a6649 100644 --- a/README.md +++ b/README.md @@ -16,9 +16,14 @@ Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/ * Maven 3.0.5 * Docker daemon running -Maven may run tests during build process but tests are disabled by default. The tests are using a localhost instance of Docker, make sure that you have Docker running for tests to work. To run the tests you have to provide your https://www.docker.io/account/login/ information: +Some of the tests are using a localhost instance of Docker and require manual setup. +In order to enable an easy standard build, these integration tests are disabled by default. - $ mvn clean install -DskipTests=false -Ddocker.io.username=... -Ddocker.io.password=... -Ddocker.io.email=... +To run the full set of tests, make sure you have a local Docker daemon running and hten provide your https://registry.hub.docker.com/account/login/ information via system properties: + + $ mvn clean install -DskipITs=false -Ddocker.io.username=... -Ddocker.io.password=... -Ddocker.io.email=... + +If you are using a remote Docker server, add its URL like this: `-Ddocker.io.url=http://...:2375`. By default Docker server is using UNIX sockets for communication with the Docker client, however docker-java client uses TCP/IP to connect to the Docker server, so you will need to make sure that your Docker server is diff --git a/pom.xml b/pom.xml index 13c71b63..3e4c9f9a 100644 --- a/pom.xml +++ b/pom.xml @@ -40,9 +40,10 @@ - true + true UTF-8 + UTF-8 true false 1.6 @@ -76,7 +77,8 @@ 2.2 2.3.1 2.3.1 - 2.8.1 + 2.17 + 2.17 2.5.1 1.7 @@ -255,16 +257,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - ${skipTests} - - - - org.codehaus.mojo cobertura-maven-plugin @@ -329,6 +321,36 @@ deploy nexus-staging:release + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + integration + + + + + org.apache.maven.plugins + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + + + + integration-test + verify + + + ${skipITs} + integration + + **/*Test.java + + + + + diff --git a/src/test/java/com/github/dockerjava/client/DockerClientTest.java b/src/test/java/com/github/dockerjava/client/DockerClientTest.java index b06ded00..e5bef57d 100644 --- a/src/test/java/com/github/dockerjava/client/DockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/DockerClientTest.java @@ -22,6 +22,7 @@ * * @author Konstantin Pelykh (kpelykh@gmail.com) */ +@Test(groups = "integration") public class DockerClientTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory .getLogger(DockerClientTest.class); diff --git a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java index 5645ccc0..3c03b1b4 100644 --- a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java @@ -16,6 +16,7 @@ import com.github.dockerjava.core.DockerClientBuilder; import com.github.dockerjava.core.DockerClientConfig; +@Test(groups = "integration") public class AuthCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index 353fea12..62603706 100644 --- a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -28,6 +28,7 @@ import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class BuildImageCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java index f4a603ff..ea5f6128 100644 --- a/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CommitCmdImplTest.java @@ -22,6 +22,7 @@ import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class CommitCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java index 60ad22a4..8d6f9254 100644 --- a/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java @@ -23,6 +23,7 @@ import com.github.dockerjava.api.model.ChangeLog; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class ContainerDiffCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java index 045a1330..945b6198 100644 --- a/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java @@ -13,6 +13,7 @@ import static org.hamcrest.Matchers.*; import static org.hamcrest.MatcherAssert.assertThat; +@Test(groups = "integration") public class CopyFileFromContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index 1320784c..284fd772 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -21,6 +21,7 @@ import com.github.dockerjava.api.model.Volume; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class CreateContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java index fc66daa5..5c33a30f 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java @@ -20,6 +20,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; +@Test(groups = "integration") public class EventsCmdImplTest extends AbstractDockerClientTest { private static int KNOWN_NUM_EVENTS = 4; diff --git a/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java index cbd55697..37214418 100644 --- a/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java @@ -18,6 +18,7 @@ import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.hamcrest.Matchers.not; +@Test(groups = "integration") public class InfoCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java index 5203bd3a..419d6e02 100644 --- a/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java @@ -23,6 +23,7 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class KillContainerCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory diff --git a/src/test/java/com/github/dockerjava/core/command/ListContainersCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ListContainersCmdImplTest.java index 49b61aab..f73ac5e4 100644 --- a/src/test/java/com/github/dockerjava/core/command/ListContainersCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ListContainersCmdImplTest.java @@ -28,6 +28,7 @@ import com.github.dockerjava.api.model.Container; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class ListContainersCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java index 3d892b0f..b2f3b88e 100644 --- a/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java @@ -18,6 +18,7 @@ import com.github.dockerjava.api.model.Info; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class ListImagesCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java index 08103703..84299219 100644 --- a/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java @@ -21,6 +21,7 @@ import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class LogContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java index d44638f4..404abd4e 100644 --- a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java @@ -22,6 +22,7 @@ import com.github.dockerjava.api.model.Info; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class PullImageCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java index bef220c4..b12ac4ec 100644 --- a/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java @@ -20,6 +20,7 @@ import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class PushImageCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory diff --git a/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java index ba850d35..9c23d70e 100644 --- a/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java @@ -25,6 +25,7 @@ import com.github.dockerjava.api.model.Container; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class RemoveContainerCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory diff --git a/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java index 1b6d5cc7..ec6b6ec3 100644 --- a/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java @@ -26,6 +26,7 @@ import com.github.dockerjava.api.model.Container; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class RemoveImageCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory diff --git a/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java index c63d1175..b6040a0f 100644 --- a/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RestartContainerCmdImplTest.java @@ -21,6 +21,7 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class RestartContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/SearchImagesCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/SearchImagesCmdImplTest.java index 5d9f60f0..5c239353 100644 --- a/src/test/java/com/github/dockerjava/core/command/SearchImagesCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/SearchImagesCmdImplTest.java @@ -22,6 +22,7 @@ import com.github.dockerjava.api.model.SearchItem; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class SearchImagesCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index 2c72c444..e5ceff82 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -28,7 +28,7 @@ import com.github.dockerjava.client.AbstractDockerClientTest; - +@Test(groups = "integration") public class StartContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java index 9824215e..d4681428 100644 --- a/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java @@ -23,6 +23,7 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class StopContainerCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory diff --git a/src/test/java/com/github/dockerjava/core/command/TagImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/TagImageCmdImplTest.java index 68081ac3..97f422f2 100644 --- a/src/test/java/com/github/dockerjava/core/command/TagImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/TagImageCmdImplTest.java @@ -16,6 +16,7 @@ import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class TagImageCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory diff --git a/src/test/java/com/github/dockerjava/core/command/VersionCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/VersionCmdImplTest.java index 0f9883ee..8c906434 100644 --- a/src/test/java/com/github/dockerjava/core/command/VersionCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/VersionCmdImplTest.java @@ -14,6 +14,7 @@ import com.github.dockerjava.api.model.Version; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class VersionCmdImplTest extends AbstractDockerClientTest { @BeforeTest diff --git a/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java index 64311803..25bc5a42 100644 --- a/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java @@ -21,6 +21,7 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; +@Test(groups = "integration") public class WaitContainerCmdImplTest extends AbstractDockerClientTest { @BeforeTest From 843600dd4ce5ed2fd33de14bd8dd9f618918164e Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Mon, 20 Oct 2014 12:35:02 +0200 Subject: [PATCH 161/452] Run all tests by default, integration tests can be disabled. This changes the build to a more standard Maven way. --- README.md | 11 ++++++----- pom.xml | 3 --- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 3e9a6649..471c8132 100644 --- a/README.md +++ b/README.md @@ -16,14 +16,15 @@ Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/ * Maven 3.0.5 * Docker daemon running -Some of the tests are using a localhost instance of Docker and require manual setup. -In order to enable an easy standard build, these integration tests are disabled by default. +The Maven build includes integration tests which are using a localhost instance of Docker and require manual setup. Make sure you have a local Docker daemon running and then provide your https://registry.hub.docker.com/account/login/ information via system properties: -To run the full set of tests, make sure you have a local Docker daemon running and hten provide your https://registry.hub.docker.com/account/login/ information via system properties: + $ mvn clean install -Ddocker.io.username=... -Ddocker.io.password=... -Ddocker.io.email=... - $ mvn clean install -DskipITs=false -Ddocker.io.username=... -Ddocker.io.password=... -Ddocker.io.email=... +_If your Docker server is remote, add its URL like this: `-Ddocker.io.url=http://...:2375`._ -If you are using a remote Docker server, add its URL like this: `-Ddocker.io.url=http://...:2375`. +If you do not have access to a Docker server or just want to execute the build quickly, you can run the build without the integration tests: + + $ mvn clean install -DskipITs By default Docker server is using UNIX sockets for communication with the Docker client, however docker-java client uses TCP/IP to connect to the Docker server, so you will need to make sure that your Docker server is diff --git a/pom.xml b/pom.xml index 3e4c9f9a..bac57699 100644 --- a/pom.xml +++ b/pom.xml @@ -40,8 +40,6 @@ - true - UTF-8 UTF-8 true @@ -342,7 +340,6 @@ verify - ${skipITs} integration **/*Test.java From 2ce62f4ab93de79e74b5db8dbba70552bc46f005 Mon Sep 17 00:00:00 2001 From: Andrew Block Date: Tue, 21 Oct 2014 21:04:23 -0500 Subject: [PATCH 162/452] Removed options to specify keystore and truststore files. Added ability to leverage environment variable or explicitly specify location of default certificates --- pom.xml | 7 + .../dockerjava/core/CertificateUtils.java | 142 ++++++++++++++++++ .../dockerjava/core/DockerClientConfig.java | 48 ++---- .../jaxrs/DockerCmdExecFactoryImpl.java | 59 ++++++-- 4 files changed, 204 insertions(+), 52 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/core/CertificateUtils.java diff --git a/pom.xml b/pom.xml index 13c71b63..4b3d7cc0 100644 --- a/pom.xml +++ b/pom.xml @@ -64,6 +64,7 @@ 1.3.9 0.3 18.0 + 1.51 1.0.1 @@ -142,6 +143,12 @@ guava ${guava.version} + + + org.bouncycastle + bcpkix-jdk15on + ${bouncycastle.version} + diff --git a/src/main/java/com/github/dockerjava/core/CertificateUtils.java b/src/main/java/com/github/dockerjava/core/CertificateUtils.java new file mode 100644 index 00000000..89722a94 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/CertificateUtils.java @@ -0,0 +1,142 @@ +package com.github.dockerjava.core; + +import java.io.BufferedReader; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +import org.apache.commons.io.IOUtils; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.openssl.PEMKeyPair; +import org.bouncycastle.openssl.PEMParser; + +public class CertificateUtils { + + public static boolean verifyCertificatesExist(String dockerCertPath) { + String[] files = {"ca.pem", "cert.pem", "key.pem"}; + for (String file : files) { + Path path = Paths.get(dockerCertPath, file); + boolean exists = Files.exists(path); + if(!exists) { + return false; + } + } + + return true; + } + + public static KeyStore createKeyStore(final String dockerCertPath) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, CertificateException, KeyStoreException { + KeyPair keyPair = loadPrivateKey(dockerCertPath); + Certificate privateCertificate = loadCertificate(dockerCertPath); + + KeyStore keyStore = KeyStore.getInstance("JKS"); + keyStore.load(null); + + keyStore.setKeyEntry("docker", keyPair.getPrivate(), "docker".toCharArray(), new Certificate[]{privateCertificate}); + return keyStore; + } + + public static KeyStore createTrustStore(final String dockerCertPath) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException { + Path caPath = Paths.get(dockerCertPath, "ca.pem"); + BufferedReader reader = Files.newBufferedReader(caPath, Charset.defaultCharset()); + PEMParser pemParser = null; + + try { + pemParser = new PEMParser(reader); + X509CertificateHolder certificateHolder = (X509CertificateHolder) pemParser.readObject(); + Certificate caCertificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder); + + KeyStore trustStore = KeyStore.getInstance("JKS"); + trustStore.load(null); + trustStore.setCertificateEntry("ca", caCertificate); + return trustStore; + + } + finally { + if(pemParser != null) { + IOUtils.closeQuietly(pemParser); + } + + if(reader != null) { + IOUtils.closeQuietly(reader); + } + } + + } + + private static Certificate loadCertificate(final String dockerCertPath) throws IOException, CertificateException { + Path certificate = Paths.get(dockerCertPath, "cert.pem"); + BufferedReader reader = Files.newBufferedReader(certificate, Charset.defaultCharset()); + PEMParser pemParser = null; + + try { + pemParser = new PEMParser(reader); + X509CertificateHolder certificateHolder = (X509CertificateHolder) pemParser.readObject(); + return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder); + } + finally { + if(pemParser != null) { + IOUtils.closeQuietly(pemParser); + } + + if(reader != null) { + IOUtils.closeQuietly(reader); + } + } + + } + + private static KeyPair loadPrivateKey(final String dockerCertPath) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { + Path certificate = Paths.get(dockerCertPath, "key.pem"); + BufferedReader reader = Files.newBufferedReader(certificate, Charset.defaultCharset()); + + PEMParser pemParser = null; + + try { + pemParser = new PEMParser(reader); + + PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject(); + + byte[] pemPrivateKeyEncoded = pemKeyPair.getPrivateKeyInfo().getEncoded(); + byte[] pemPublicKeyEncoded = pemKeyPair.getPublicKeyInfo().getEncoded(); + + KeyFactory factory = KeyFactory.getInstance("RSA"); + + X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pemPublicKeyEncoded); + PublicKey publicKey = factory.generatePublic(publicKeySpec); + + PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pemPrivateKeyEncoded); + PrivateKey privateKey = factory.generatePrivate(privateKeySpec); + + return new KeyPair(publicKey, privateKey); + + } + finally { + if(pemParser != null) { + IOUtils.closeQuietly(pemParser); + } + + if(reader != null) { + IOUtils.closeQuietly(reader); + } + } + + + } + +} diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 9c2b5867..4308f4be 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -10,7 +10,7 @@ public class DockerClientConfig { private final URI uri; - private final String version, username, password, email, keystore, keystorePassword, truststore, truststorePassword; + private final String version, username, password, email, dockerCertPath; private final Integer readTimeout; private final boolean loggingFilterEnabled; @@ -22,10 +22,7 @@ private DockerClientConfig(DockerClientConfigBuilder builder) { this.email = builder.email; this.readTimeout = builder.readTimeout; this.loggingFilterEnabled = builder.loggingFilterEnabled; - this.keystore = builder.keystore; - this.keystorePassword = builder.keystorePassword; - this.truststore = builder.truststore; - this.truststorePassword = builder.truststorePassword; + this.dockerCertPath = builder.dockerCertPath; } public URI getUri() { @@ -56,20 +53,8 @@ public boolean isLoggingFilterEnabled() { return loggingFilterEnabled; } - public String getKeystore() { - return keystore; - } - - public String getKeystorePassword() { - return keystorePassword; - } - - public String getTruststore() { - return truststore; - } - - public String getTruststorePassword() { - return truststorePassword; + public String getDockerCertPath() { + return dockerCertPath; } public static Properties loadIncludedDockerProperties() { @@ -117,7 +102,7 @@ public static Properties overrideDockerPropertiesWithSystemProperties(Properties overriddenProperties.putAll(p); // TODO Add all values from system properties that begin with docker.io.* - for (String s : new String[]{ "url", "version", "username", "password", "email", "readTimeout", "enableLoggingFilter", "keystore", "keystorePassword", "truststore", "truststorePassword"}) { + for (String s : new String[]{ "url", "version", "username", "password", "email", "readTimeout", "enableLoggingFilter", "dockerCertPath"}) { final String key = "docker.io." + s; if (System.getProperties().containsKey(key)) { overriddenProperties.setProperty(key, System.getProperty(key)); @@ -135,7 +120,7 @@ public static DockerClientConfigBuilder createDefaultConfigBuilder() { public static class DockerClientConfigBuilder { private URI uri; - private String version, username, password, email, keystore, keystorePassword, truststore, truststorePassword; + private String version, username, password, email, dockerCertPath; private Integer readTimeout; private boolean loggingFilterEnabled; @@ -159,10 +144,7 @@ public DockerClientConfigBuilder withProperties(Properties p) { .withEmail(p.getProperty("docker.io.email")) .withReadTimeout(Integer.valueOf(p.getProperty("docker.io.readTimeout", "0"))) .withLoggingFilter(Boolean.valueOf(p.getProperty("docker.io.enableLoggingFilter", "true"))) - .withKeystore(p.getProperty("docker.io.keystore")) - .withKeystorePassword(p.getProperty("docker.io.keystorePassword")) - .withTruststore(p.getProperty("docker.io.truststore")) - .withTruststorePassword(p.getProperty("docker.io.truststorePassword")); + .withDockerCertPath(p.getProperty("docker.io.dockerCertPath")); } public final DockerClientConfigBuilder withUri(String uri) { @@ -194,20 +176,8 @@ public final DockerClientConfigBuilder withLoggingFilter(boolean loggingFilterEn this.loggingFilterEnabled = loggingFilterEnabled; return this; } - public final DockerClientConfigBuilder withKeystore(String keystore) { - this.keystore = keystore; - return this; - } - public final DockerClientConfigBuilder withKeystorePassword(String keystorePassword) { - this.keystorePassword = keystorePassword; - return this; - } - public final DockerClientConfigBuilder withTruststore(String truststore) { - this.truststore = truststore; - return this; - } - public final DockerClientConfigBuilder withTruststorePassword(String truststorePassword) { - this.truststorePassword = truststorePassword; + public final DockerClientConfigBuilder withDockerCertPath(String dockerCertPath) { + this.dockerCertPath = dockerCertPath; return this; } public DockerClientConfig build() { diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 1a70ccbe..58450c8a 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -1,6 +1,7 @@ package com.github.dockerjava.jaxrs; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import com.github.dockerjava.api.DockerClientException; import com.github.dockerjava.api.command.AttachContainerCmd; import com.github.dockerjava.api.command.AuthCmd; import com.github.dockerjava.api.command.BuildImageCmd; @@ -33,13 +34,17 @@ import com.github.dockerjava.api.command.UnpauseContainerCmd; import com.github.dockerjava.api.command.VersionCmd; import com.github.dockerjava.api.command.WaitContainerCmd; +import com.github.dockerjava.core.CertificateUtils; import com.github.dockerjava.core.DockerClientConfig; import com.github.dockerjava.jaxrs.util.JsonClientFilter; import com.github.dockerjava.jaxrs.util.ResponseStatusExceptionFilter; import com.github.dockerjava.jaxrs.util.SelectiveLoggingFilter; import com.google.common.base.Preconditions; +import java.io.File; import java.io.IOException; +import java.security.KeyStore; +import java.security.Security; import java.util.logging.Logger; import javax.net.ssl.SSLContext; @@ -47,6 +52,7 @@ import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; +import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.glassfish.jersey.CommonProperties; import org.glassfish.jersey.SslConfigurator; import org.glassfish.jersey.client.ClientConfig; @@ -83,22 +89,49 @@ public void init(DockerClientConfig dockerClientConfig) { ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig); - - if((dockerClientConfig.getKeystore() != null && dockerClientConfig.getKeystorePassword() != null) || (dockerClientConfig.getTruststore() != null && dockerClientConfig.getTruststorePassword() != null)) { - SslConfigurator sslConfig = SslConfigurator.newInstance(); + // Attempt to load Docker SSL certificates from location in following order: + // 1. User Defined + // 2. Environment Variable + // 3. User Home Directory + String dockerCertPath = dockerClientConfig.getDockerCertPath(); - if(dockerClientConfig.getKeystore() != null && dockerClientConfig.getKeystorePassword() != null) { - sslConfig.keyStoreFile(dockerClientConfig.getKeystore()); - sslConfig.keyStorePassword(dockerClientConfig.getKeystorePassword()); - } + if(dockerCertPath == null) { + dockerCertPath = System.getenv("DOCKER_CERT_PATH"); + } - if(dockerClientConfig.getTruststore() != null && dockerClientConfig.getTruststorePassword() != null) { - sslConfig.trustStoreFile(dockerClientConfig.getTruststore()); - sslConfig.trustStorePassword(dockerClientConfig.getTruststorePassword()); - } + if(dockerCertPath == null) { + dockerCertPath = System.getProperty("USER_HOME") + File.separator + ".docker"; + } + + if(dockerCertPath != null) { + boolean certificatesExist = CertificateUtils.verifyCertificatesExist(dockerCertPath); - SSLContext sslContext = sslConfig.createSSLContext(); - clientBuilder.sslContext(sslContext); + if(certificatesExist) { + + try { + + Security.addProvider(new BouncyCastleProvider()); + + SslConfigurator sslConfig = SslConfigurator.newInstance(); + + KeyStore keyStore = CertificateUtils.createKeyStore(dockerCertPath); + KeyStore trustStore = CertificateUtils.createTrustStore(dockerCertPath); + + sslConfig.keyStore(keyStore); + sslConfig.keyStorePassword("docker"); + + sslConfig.trustStore(trustStore); + + SSLContext sslContext = sslConfig.createSSLContext(); + clientBuilder.sslContext(sslContext); + + } + catch(Exception e) { + throw new DockerClientException(e.getMessage(), e); + } + + } + } client = clientBuilder.build(); From 077df9fad765e8b14c0decca302a1952e79a3e40 Mon Sep 17 00:00:00 2001 From: Andrew Block Date: Tue, 21 Oct 2014 21:38:28 -0500 Subject: [PATCH 163/452] Minor javadoc addition --- .../java/com/github/dockerjava/core/DockerClientConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 4308f4be..6e3795e9 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -129,7 +129,7 @@ public DockerClientConfigBuilder() { /** * This will set all fields in the builder to those contained in the Properties object. The Properties object - * should contain the following docker.io.* keys: url, version, username, password, and email. If + * should contain the following docker.io.* keys: url, version, username, password, email, and dockerCertPath. If * docker.io.readTimeout or docker.io.enableLoggingFilter are not contained, they will be set to 1000 and true, * respectively. * From ef4e1978a1cd6d75a27649ff7c2a7aaa7a137bce Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 24 Oct 2014 23:37:00 +0200 Subject: [PATCH 164/452] Fixed ssl configuration for java 1.6 --- .../dockerjava/core/CertificateUtils.java | 23 +++++++++---------- .../jaxrs/DockerCmdExecFactoryImpl.java | 13 +++++++---- .../dockerjava/api/model/AccessModeTest.java | 2 +- .../core/command/EventsCmdImplTest.java | 2 ++ .../core/command/PullImageCmdImplTest.java | 9 +++++++- .../command/WaitContainerCmdImplTest.java | 7 +++--- 6 files changed, 34 insertions(+), 22 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/CertificateUtils.java b/src/main/java/com/github/dockerjava/core/CertificateUtils.java index 89722a94..6b19a201 100644 --- a/src/main/java/com/github/dockerjava/core/CertificateUtils.java +++ b/src/main/java/com/github/dockerjava/core/CertificateUtils.java @@ -1,11 +1,10 @@ package com.github.dockerjava.core; import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; + import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyStore; @@ -30,8 +29,8 @@ public class CertificateUtils { public static boolean verifyCertificatesExist(String dockerCertPath) { String[] files = {"ca.pem", "cert.pem", "key.pem"}; for (String file : files) { - Path path = Paths.get(dockerCertPath, file); - boolean exists = Files.exists(path); + File path = new File(dockerCertPath, file); + boolean exists = path.exists(); if(!exists) { return false; } @@ -52,8 +51,8 @@ public static KeyStore createKeyStore(final String dockerCertPath) throws NoSuch } public static KeyStore createTrustStore(final String dockerCertPath) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException { - Path caPath = Paths.get(dockerCertPath, "ca.pem"); - BufferedReader reader = Files.newBufferedReader(caPath, Charset.defaultCharset()); + File caPath = new File(dockerCertPath, "ca.pem"); + BufferedReader reader = new BufferedReader(new FileReader(caPath)); PEMParser pemParser = null; try { @@ -80,8 +79,8 @@ public static KeyStore createTrustStore(final String dockerCertPath) throws IOEx } private static Certificate loadCertificate(final String dockerCertPath) throws IOException, CertificateException { - Path certificate = Paths.get(dockerCertPath, "cert.pem"); - BufferedReader reader = Files.newBufferedReader(certificate, Charset.defaultCharset()); + File certificate = new File(dockerCertPath, "cert.pem"); + BufferedReader reader = new BufferedReader(new FileReader(certificate)); PEMParser pemParser = null; try { @@ -102,8 +101,8 @@ private static Certificate loadCertificate(final String dockerCertPath) throws I } private static KeyPair loadPrivateKey(final String dockerCertPath) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { - Path certificate = Paths.get(dockerCertPath, "key.pem"); - BufferedReader reader = Files.newBufferedReader(certificate, Charset.defaultCharset()); + File certificate = new File(dockerCertPath, "key.pem"); + BufferedReader reader = new BufferedReader(new FileReader(certificate)); PEMParser pemParser = null; diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 58450c8a..cb912873 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -112,17 +112,22 @@ public void init(DockerClientConfig dockerClientConfig) { Security.addProvider(new BouncyCastleProvider()); - SslConfigurator sslConfig = SslConfigurator.newInstance(); - KeyStore keyStore = CertificateUtils.createKeyStore(dockerCertPath); KeyStore trustStore = CertificateUtils.createTrustStore(dockerCertPath); - + + // properties acrobatics not needed for java > 1.6 + String httpProtocols = System.getProperty("https.protocols"); + System.setProperty("https.protocols", "TLSv1"); + SslConfigurator sslConfig = SslConfigurator.newInstance(true); + if(httpProtocols != null ) System.setProperty("https.protocols", httpProtocols); + sslConfig.keyStore(keyStore); sslConfig.keyStorePassword("docker"); - sslConfig.trustStore(trustStore); SSLContext sslContext = sslConfig.createSSLContext(); + + clientBuilder.sslContext(sslContext); } diff --git a/src/test/java/com/github/dockerjava/api/model/AccessModeTest.java b/src/test/java/com/github/dockerjava/api/model/AccessModeTest.java index d9328958..432f7b00 100644 --- a/src/test/java/com/github/dockerjava/api/model/AccessModeTest.java +++ b/src/test/java/com/github/dockerjava/api/model/AccessModeTest.java @@ -23,7 +23,7 @@ public void fromString() { } @Test(expectedExceptions = IllegalArgumentException.class, - expectedExceptionsMessageRegExp = "No enum constant.*") + expectedExceptionsMessageRegExp = "No enum const.*") public void fromIllegalString() { AccessMode.valueOf("xx"); } diff --git a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java index 5c33a30f..6935227b 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java @@ -67,6 +67,8 @@ public void testEventStreamTimeBound() throws InterruptedException, IOException boolean zeroCount = countDownLatch.await(5, TimeUnit.SECONDS); executorService.shutdown(); + + assertTrue(zeroCount, "Expected 4 events, [create, start, die, stop]"); } diff --git a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java index 404abd4e..84af9e72 100644 --- a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java @@ -18,6 +18,7 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.InternalServerErrorException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.api.model.Info; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -61,7 +62,13 @@ public void testPullImage() throws DockerException, IOException { String testImage = "hackmann/empty"; LOG.info("Removing image: {}", testImage); - dockerClient.removeImageCmd(testImage).exec(); + + try { + dockerClient.removeImageCmd(testImage).exec(); + } catch (NotFoundException e) { + // just ignore if not exist + } + info = dockerClient.infoCmd().exec(); LOG.info("Client info: {}", info.toString()); diff --git a/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java index 25bc5a42..32434eea 100644 --- a/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java @@ -17,6 +17,7 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.InternalServerErrorException; +import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -70,12 +71,10 @@ public void testWaitContainer() throws DockerException { @Test public void testWaitNonExistingContainer() throws DockerException { - // docker returns InternalServerError instead of NotFound - // see https://github.com/docker/docker/issues/8107 try { dockerClient.waitContainerCmd("non-existing").exec(); - fail("expected InternalServerErrorException"); - } catch (InternalServerErrorException e) { + fail("expected NotFoundException"); + } catch (NotFoundException e) { } } } From 71d353b7330381d304d27f42a1e74ec12b6664ff Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Fri, 24 Oct 2014 23:45:07 +0200 Subject: [PATCH 165/452] Bumped versions and fix Java version --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 471c8132..c70eba92 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/ ###### Prerequisites: -* Java 1.6+ +* Java 1.6 * Maven 3.0.5 * Docker daemon running @@ -56,7 +56,7 @@ Run build with tests: com.github.docker-java docker-java - 0.10.1 + 0.10.2 ### Latest SNAPSHOT version @@ -64,7 +64,7 @@ Run build with tests: com.github.docker-java docker-java - 0.10.2-SNAPSHOT + 0.10.3-SNAPSHOT Latest SNAPSHOT is published to maven repo: https://oss.sonatype.org/content/groups/public via ![Build on CloudBees](http://cloudbees.prod.acquia-sites.com/sites/default/files/styles/large/public/Button-Powered-by-CB.png?itok=uMDWINfY) From 2b241fea6eff446f2d4416147a0c2b060001fd0d Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sat, 25 Oct 2014 00:15:15 +0200 Subject: [PATCH 166/452] Improved configuration documentation --- README.md | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index c70eba92..9a550e31 100644 --- a/README.md +++ b/README.md @@ -77,38 +77,47 @@ For code examples, please look at the [Wiki](https://github.com/docker-java/dock There are a couple of configuration items, all of which have sensible defaults: -* `url` The Docker URL, e.g. `http://localhost:2375`. +* `url` The Docker URL, e.g. `https://localhost:2376`. * `version` The API version, e.g. `1.14`. * `username` Your repository username (required to push containers). * `password` Your repository password. * `email` Your repository email. +* `dockerCertPath` Path to the docker certs. There are three ways to configure, in descending order of precedence: -##### Programatic: +#### Programatic: In your application, e.g. DockerClientConfigBuilder configBuilder = DockerClientConfig.createDefaultConfigBuilder(); - configBuilder.withVersion("1.14"); - configBuilder.withUri("http://my-docker-host.tld:2375"); + configBuilder.withVersion("1.15"); + configBuilder.withUri("https://my-docker-host.tld:2376"); configBuilder.withUsername("dockeruser"); configBuilder.withPassword("ilovedocker"); configBuilder.withEmail("dockeruser@github.com"); + configBuilder.withDockerCertPath("/home/user/.docker"); DockerClientConfig config = configBuilder.build(); DockerClient docker = DockerClientBuilder.getInstance(config).build(); +#### Properties + + docker.io.url=https://localhost:2376 + docker.io.version=1.15 + docker.io.username=dockeruser + docker.io.password=ilovedocker + docker.io.email=dockeruser@github.com + docker.io.dockerCertPath=/home/user/.docker + + ##### System Properties: -E.g. - java -Ddocker.io.username=kpelykh pkg.Main + java -Ddocker.io.username=dockeruser pkg.Main ##### File System -In `$HOME/.docker.io.properties`, e.g.: - docker.io.username=dockeruser +In `$HOME/.docker.io.properties` ##### Class Path -In the class path at `/docker.io.properties`, e.g.: - docker.io.url=http://localhost:2375 - docker.io.version=1.13 +In the class path at `/docker.io.properties` + From 209c246185685982c66bd87fa0e1d7e3fa2e68b9 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sat, 25 Oct 2014 00:17:37 +0200 Subject: [PATCH 167/452] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9a550e31..d0456aed 100644 --- a/README.md +++ b/README.md @@ -45,9 +45,9 @@ Now make sure that docker is up: Git commit (server): fa7b24f Go version (server): go1.3.1 -Run build with tests: +Run build without integration tests: - $ mvn clean install -DskipTests=false + $ mvn clean install -DskipITs ## Docker-Java maven dependencies @@ -78,7 +78,7 @@ For code examples, please look at the [Wiki](https://github.com/docker-java/dock There are a couple of configuration items, all of which have sensible defaults: * `url` The Docker URL, e.g. `https://localhost:2376`. -* `version` The API version, e.g. `1.14`. +* `version` The API version, e.g. `1.15`. * `username` Your repository username (required to push containers). * `password` Your repository password. * `email` Your repository email. From a37e09b1458e17db375d62f566d9403f9b6c53c3 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sat, 25 Oct 2014 00:18:13 +0200 Subject: [PATCH 168/452] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d0456aed..a31cfb4d 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Java API client for [Docker](http://docs.docker.io/ "Docker") -Supports a subset of the Docker Client API v1.14, Docker Server version 1.2.0 +Supports a subset of the Docker Client API v1.15, Docker Server version 1.3.0 The current implementation is based on Jersey 2.x and therefore classpath incompatible with older Jersey 1.x dependent libraries! From f52f84364bf49b20b5725f0051888be8d2ed7eca Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 25 Oct 2014 12:28:07 +0200 Subject: [PATCH 169/452] Fixed fallback/default configuration --- src/main/resources/docker.io.properties | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/resources/docker.io.properties b/src/main/resources/docker.io.properties index da6fb677..ea8ce7ed 100644 --- a/src/main/resources/docker.io.properties +++ b/src/main/resources/docker.io.properties @@ -1,3 +1,4 @@ -docker.io.url=http://localhost:2375 -docker.io.version=1.14 -docker.io.enableLoggingFilter=true \ No newline at end of file +docker.io.url=https://localhost:2376 +docker.io.version=1.15 +docker.io.enableLoggingFilter=true +#docker.io.dockerCertPath= \ No newline at end of file From c35f0255d5b4bbd7d8b8d55ce777e85b10941b7a Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sat, 25 Oct 2014 12:31:03 +0200 Subject: [PATCH 170/452] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a31cfb4d..f97ce15b 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ The Maven build includes integration tests which are using a localhost instance $ mvn clean install -Ddocker.io.username=... -Ddocker.io.password=... -Ddocker.io.email=... -_If your Docker server is remote, add its URL like this: `-Ddocker.io.url=http://...:2375`._ +_If your Docker server is remote, add its URL like this: `-Ddocker.io.url=https://...:2376`._ If you do not have access to a Docker server or just want to execute the build quickly, you can run the build without the integration tests: From 96400c22e81cadb7d84fd67aabb8ad5ec15844e5 Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Sat, 25 Oct 2014 23:33:33 +0200 Subject: [PATCH 171/452] explicitly use the latest image version --- src/test/resources/netcat/Dockerfile | 2 +- src/test/resources/nginx/Dockerfile | 2 +- src/test/resources/testAddFile/Dockerfile | 2 +- src/test/resources/testAddFileInSubfolder/Dockerfile | 2 +- src/test/resources/testAddFolder/Dockerfile | 2 +- src/test/resources/testAddUrl/Dockerfile | 2 +- src/test/resources/testENVSubstitution/Dockerfile | 2 +- src/test/resources/testReadFile/Dockerfile | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/test/resources/netcat/Dockerfile b/src/test/resources/netcat/Dockerfile index 1ea35547..1974f106 100644 --- a/src/test/resources/netcat/Dockerfile +++ b/src/test/resources/netcat/Dockerfile @@ -2,7 +2,7 @@ # # VERSION 0.3 -FROM ubuntu +FROM ubuntu:latest #install netcat RUN apt-get install -y netcat diff --git a/src/test/resources/nginx/Dockerfile b/src/test/resources/nginx/Dockerfile index b0abcd67..2d0fa24c 100644 --- a/src/test/resources/nginx/Dockerfile +++ b/src/test/resources/nginx/Dockerfile @@ -2,7 +2,7 @@ # # VERSION 0.0.1 -FROM ubuntu +FROM ubuntu:latest MAINTAINER Guillaume J. Charmes "guillaume@dotcloud.com" # make sure the package repository is up to date diff --git a/src/test/resources/testAddFile/Dockerfile b/src/test/resources/testAddFile/Dockerfile index 2900a5e7..8a4a6776 100644 --- a/src/test/resources/testAddFile/Dockerfile +++ b/src/test/resources/testAddFile/Dockerfile @@ -1,4 +1,4 @@ -FROM ubuntu +FROM ubuntu:latest # Copy testrun.sh files into the container diff --git a/src/test/resources/testAddFileInSubfolder/Dockerfile b/src/test/resources/testAddFileInSubfolder/Dockerfile index 41d8f437..eac6b0e9 100644 --- a/src/test/resources/testAddFileInSubfolder/Dockerfile +++ b/src/test/resources/testAddFileInSubfolder/Dockerfile @@ -1,4 +1,4 @@ -FROM ubuntu +FROM ubuntu:latest # Copy testrun.sh files into the container diff --git a/src/test/resources/testAddFolder/Dockerfile b/src/test/resources/testAddFolder/Dockerfile index b2a8e2a1..183e831c 100644 --- a/src/test/resources/testAddFolder/Dockerfile +++ b/src/test/resources/testAddFolder/Dockerfile @@ -1,4 +1,4 @@ -FROM ubuntu +FROM ubuntu:latest # Copy testrun.sh files into the container diff --git a/src/test/resources/testAddUrl/Dockerfile b/src/test/resources/testAddUrl/Dockerfile index 1d76926c..ba0b91a0 100644 --- a/src/test/resources/testAddUrl/Dockerfile +++ b/src/test/resources/testAddUrl/Dockerfile @@ -1,4 +1,4 @@ -FROM ubuntu +FROM ubuntu:latest # Copy testrun.sh files into the container diff --git a/src/test/resources/testENVSubstitution/Dockerfile b/src/test/resources/testENVSubstitution/Dockerfile index de06ddbb..134f7a60 100644 --- a/src/test/resources/testENVSubstitution/Dockerfile +++ b/src/test/resources/testENVSubstitution/Dockerfile @@ -1,4 +1,4 @@ -FROM ubuntu +FROM ubuntu:latest # Copy testrun.sh files into the container diff --git a/src/test/resources/testReadFile/Dockerfile b/src/test/resources/testReadFile/Dockerfile index 3dfe89f9..0f73b8ea 100644 --- a/src/test/resources/testReadFile/Dockerfile +++ b/src/test/resources/testReadFile/Dockerfile @@ -1,4 +1,4 @@ -FROM ubuntu +FROM ubuntu:latest # Copy testrun.sh files into the container From 2114d0e368cfe457d55dfa6e5c7dc9f116743fbe Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 26 Oct 2014 11:28:39 +0000 Subject: [PATCH 172/452] Updated DockerClientConfig so that environment properties can be used to configure Docker. Made a couple of public methods private. --- README.md | 24 +- .../dockerjava/core/DockerClientConfig.java | 289 ++++++++--- .../jaxrs/DockerCmdExecFactoryImpl.java | 470 ++++++++---------- src/main/resources/docker.io.properties | 2 +- .../core/DockerClientConfigTest.java | 125 +++++ 5 files changed, 565 insertions(+), 345 deletions(-) create mode 100644 src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java diff --git a/README.md b/README.md index f97ce15b..8eff82a2 100644 --- a/README.md +++ b/README.md @@ -86,17 +86,17 @@ There are a couple of configuration items, all of which have sensible defaults: There are three ways to configure, in descending order of precedence: -#### Programatic: +#### Programmatic: In your application, e.g. - DockerClientConfigBuilder configBuilder = DockerClientConfig.createDefaultConfigBuilder(); - configBuilder.withVersion("1.15"); - configBuilder.withUri("https://my-docker-host.tld:2376"); - configBuilder.withUsername("dockeruser"); - configBuilder.withPassword("ilovedocker"); - configBuilder.withEmail("dockeruser@github.com"); - configBuilder.withDockerCertPath("/home/user/.docker"); - DockerClientConfig config = configBuilder.build(); + DockerClientConfig config = DockerClientConfig.createDefaultConfigBuilder() + .withVersion("1.15") + .withUri("https://my-docker-host.tld:2376") + .withUsername("dockeruser") + .withPassword("ilovedocker") + .withEmail("dockeruser@github.com") + .withDockerCertPath("/home/user/.docker") + .build(); DockerClient docker = DockerClientBuilder.getInstance(config).build(); #### Properties @@ -113,6 +113,12 @@ In your application, e.g. java -Ddocker.io.username=dockeruser pkg.Main +##### System Environment + + export DOCKER_URL=http://localhost:2376 + +Note: we also auto-detect defaults. If you use `DOCKER_HOST` we use that value, and if `DOCKER_CERT_PATH` is set, we switch to SSL. + ##### File System In `$HOME/.docker.io.properties` diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 6e3795e9..8ed9a3fa 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -1,82 +1,96 @@ package com.github.dockerjava.core; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URI; -import java.util.Properties; + import com.google.common.base.Preconditions; + import com.google.common.collect.ImmutableMap; -import com.google.common.base.Preconditions; + import java.io.File; + import java.io.FileInputStream; + import java.io.IOException; + import java.net.URI; + import java.util.Map; + import java.util.Properties; public class DockerClientConfig { + private static final String DOCKER_HOST_PROPERTY = "DOCKER_HOST"; + private static final String DOCKER_CERT_PATH_PROPERTY = "DOCKER_CERT_PATH"; + private static final String DOCKER_IO_URL_PROPERTY = "docker.io.url"; + private static final String DOCKER_IO_VERSION_PROPERTY = "docker.io.version"; + private static final String DOCKER_IO_USERNAME_PROPERTY = "docker.io.username"; + private static final String DOCKER_IO_PASSWORD_PROPERTY = "docker.io.password"; + private static final String DOCKER_IO_EMAIL_PROPERTY = "docker.io.email"; + private static final String DOCKER_IO_READ_TIMEOUT_PROPERTY = "docker.io.readTimeout"; + // this is really confusing, as there are two ways to spell it + private static final String DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY = "docker.io.enableLoggingFilter"; + private static final String DOCKER_IO_DOCKER_CERT_PATH_PROPERTY = "docker.io.dockerCertPath"; + /** + * A map from the environment name to the interval name. + */ + private static final Map ENV_NAME_TO_IO_NAME = ImmutableMap.builder() + .put("DOCKER_URL", DOCKER_IO_URL_PROPERTY) + .put("DOCKER_VERSION", DOCKER_IO_VERSION_PROPERTY) + .put("DOCKER_USERNAME", DOCKER_IO_USERNAME_PROPERTY) + .put("DOCKER_PASSWORD", DOCKER_IO_PASSWORD_PROPERTY) + .put("DOCKER_EMAIL", DOCKER_IO_EMAIL_PROPERTY) + .put("DOCKER_READ_TIMEOUT", DOCKER_IO_READ_TIMEOUT_PROPERTY) + .put("DOCKER_LOGGING_FILTER_ENABLED", DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY) + .put(DOCKER_CERT_PATH_PROPERTY, DOCKER_IO_DOCKER_CERT_PATH_PROPERTY) + .build(); + private static final String DOCKER_IO_PROPERTIES_PROPERTY = "docker.io.properties"; private final URI uri; private final String version, username, password, email, dockerCertPath; private final Integer readTimeout; private final boolean loggingFilterEnabled; - private DockerClientConfig(DockerClientConfigBuilder builder) { - this.uri = builder.uri; - this.version = builder.version; - this.username = builder.username; - this.password = builder.password; - this.email = builder.email; - this.readTimeout = builder.readTimeout; - this.loggingFilterEnabled = builder.loggingFilterEnabled; - this.dockerCertPath = builder.dockerCertPath; - } - - public URI getUri() { - return uri; - } - - public String getVersion() { - return version; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public String getEmail() { - return email; - } - - public Integer getReadTimeout() { - return readTimeout; - } - - public boolean isLoggingFilterEnabled() { - return loggingFilterEnabled; - } - - public String getDockerCertPath() { - return dockerCertPath; + DockerClientConfig(URI uri, String version, String username, String password, String email, String dockerCertPath, Integer readTimeout, boolean loggingFilterEnabled) { + this.uri = uri; + this.version = version; + this.username = username; + this.password = password; + this.email = email; + this.dockerCertPath = dockerCertPath; + this.readTimeout = readTimeout; + this.loggingFilterEnabled = loggingFilterEnabled; } - public static Properties loadIncludedDockerProperties() { + private static Properties loadIncludedDockerProperties(Properties systemProperties) { try { Properties p = new Properties(); - p.load(DockerClientConfig.class.getResourceAsStream("/docker.io.properties")); + p.load(DockerClientConfig.class.getResourceAsStream("/" + DOCKER_IO_PROPERTIES_PROPERTY)); + replaceProperties(p, systemProperties); return p; } catch (IOException e) { throw new RuntimeException(e); } } + private static void replaceProperties(Properties properties, Properties replacements) { + for (Object objectKey : properties.keySet()) { + String key = objectKey.toString(); + properties.setProperty(key, replaceProperties(properties.getProperty(key), replacements)); + } + } + + private static String replaceProperties(String s, Properties replacements) { + for (Map.Entry entry : replacements.entrySet()) { + String key = "${" + entry.getKey() + "}"; + while (s.contains(key)) { + s = s.replace(key, String.valueOf(entry.getValue())); + } + } + return s; + } + /** * Creates a new Properties object containing values overridden from ${user.home}/.docker.io.properties + * * @param p The original set of properties to override * @return A copy of the original Properties with overridden values */ - public static Properties overrideDockerPropertiesWithSettingsFromUserHome(Properties p) { + private static Properties overrideDockerPropertiesWithSettingsFromUserHome(Properties p, Properties systemProperties) { Properties overriddenProperties = new Properties(); overriddenProperties.putAll(p); - final File usersDockerPropertiesFile = new File(System.getProperty("user.home"), ".docker.io.properties"); + final File usersDockerPropertiesFile = new File(systemProperties.getProperty("user.home"), "." + DOCKER_IO_PROPERTIES_PROPERTY); if (usersDockerPropertiesFile.isFile()) { try { final FileInputStream in = new FileInputStream(usersDockerPropertiesFile); @@ -92,39 +106,158 @@ public static Properties overrideDockerPropertiesWithSettingsFromUserHome(Proper return overriddenProperties; } + private static Properties overrideDockerPropertiesWithEnv(Properties properties, Map env) { + Properties overriddenProperties = new Properties(); + overriddenProperties.putAll(properties); + + // special case which is a sensible default + if (env.containsKey(DOCKER_HOST_PROPERTY)) { + overriddenProperties.setProperty(DOCKER_IO_URL_PROPERTY, env.get(DOCKER_HOST_PROPERTY).replace("tcp", protocol(env))); + } + + for (Map.Entry envEntry : env.entrySet()) { + String envKey = envEntry.getKey(); + if (ENV_NAME_TO_IO_NAME.containsKey(envKey)) { + overriddenProperties.setProperty(ENV_NAME_TO_IO_NAME.get(envKey), envEntry.getValue()); + } + } + + return overriddenProperties; + } + + private static String protocol(Map env) { + // if this is set, we assume we need SSL + return env.containsKey(DOCKER_CERT_PATH_PROPERTY) ? "https" : "http"; + } + /** * Creates a new Properties object containing values overridden from the System properties + * * @param p The original set of properties to override * @return A copy of the original Properties with overridden values */ - public static Properties overrideDockerPropertiesWithSystemProperties(Properties p) { + private static Properties overrideDockerPropertiesWithSystemProperties(Properties p, Properties systemProperties) { Properties overriddenProperties = new Properties(); overriddenProperties.putAll(p); - // TODO Add all values from system properties that begin with docker.io.* - for (String s : new String[]{ "url", "version", "username", "password", "email", "readTimeout", "enableLoggingFilter", "dockerCertPath"}) { - final String key = "docker.io." + s; - if (System.getProperties().containsKey(key)) { - overriddenProperties.setProperty(key, System.getProperty(key)); - } - } + for (String key : new String[]{ + DOCKER_IO_URL_PROPERTY, + DOCKER_IO_VERSION_PROPERTY, + DOCKER_IO_USERNAME_PROPERTY, + DOCKER_IO_PASSWORD_PROPERTY, + DOCKER_IO_EMAIL_PROPERTY, + DOCKER_IO_READ_TIMEOUT_PROPERTY, + DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY, + DOCKER_IO_DOCKER_CERT_PATH_PROPERTY, + }) { + if (systemProperties.containsKey(key)) { + overriddenProperties.setProperty(key, systemProperties.getProperty(key)); + } + } return overriddenProperties; } public static DockerClientConfigBuilder createDefaultConfigBuilder() { - Properties properties = loadIncludedDockerProperties(); - properties = overrideDockerPropertiesWithSettingsFromUserHome(properties); - properties = overrideDockerPropertiesWithSystemProperties(properties); + return createDefaultConfigBuilder(System.getenv(), System.getProperties()); + } + + /** + * Allows you to build the config without system environment interfering for more robust testing + */ + static DockerClientConfigBuilder createDefaultConfigBuilder(Map env, Properties systemProperties) { + Properties properties = loadIncludedDockerProperties(systemProperties); + properties = overrideDockerPropertiesWithSettingsFromUserHome(properties, systemProperties); + properties = overrideDockerPropertiesWithEnv(properties, env); + properties = overrideDockerPropertiesWithSystemProperties(properties, systemProperties); return new DockerClientConfigBuilder().withProperties(properties); } + public URI getUri() { + return uri; + } + + public String getVersion() { + return version; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + public String getEmail() { + return email; + } + + public Integer getReadTimeout() { + return readTimeout; + } + + public boolean isLoggingFilterEnabled() { + return loggingFilterEnabled; + } + + public String getDockerCertPath() { + return dockerCertPath; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + DockerClientConfig that = (DockerClientConfig) o; + + if (loggingFilterEnabled != that.loggingFilterEnabled) return false; + if (dockerCertPath != null ? !dockerCertPath.equals(that.dockerCertPath) : that.dockerCertPath != null) + return false; + if (email != null ? !email.equals(that.email) : that.email != null) return false; + if (password != null ? !password.equals(that.password) : that.password != null) return false; + if (readTimeout != null ? !readTimeout.equals(that.readTimeout) : that.readTimeout != null) return false; + if (uri != null ? !uri.equals(that.uri) : that.uri != null) return false; + if (username != null ? !username.equals(that.username) : that.username != null) return false; + if (version != null ? !version.equals(that.version) : that.version != null) return false; + + return true; + } + + @Override + public int hashCode() { + int result = uri != null ? uri.hashCode() : 0; + result = 31 * result + (version != null ? version.hashCode() : 0); + result = 31 * result + (username != null ? username.hashCode() : 0); + result = 31 * result + (password != null ? password.hashCode() : 0); + result = 31 * result + (email != null ? email.hashCode() : 0); + result = 31 * result + (dockerCertPath != null ? dockerCertPath.hashCode() : 0); + result = 31 * result + (readTimeout != null ? readTimeout.hashCode() : 0); + result = 31 * result + (loggingFilterEnabled ? 1 : 0); + return result; + } + + @Override + public String toString() { + return "DockerClientConfig{" + + "uri=" + uri + + ", version='" + version + '\'' + + ", username='" + username + '\'' + + ", password='" + password + '\'' + + ", email='" + email + '\'' + + ", dockerCertPath='" + dockerCertPath + '\'' + + ", readTimeout=" + readTimeout + + ", loggingFilterEnabled=" + loggingFilterEnabled + + '}'; + } + public static class DockerClientConfigBuilder { private URI uri; private String version, username, password, email, dockerCertPath; private Integer readTimeout; private boolean loggingFilterEnabled; - public DockerClientConfigBuilder() { + private DockerClientConfigBuilder() { } /** @@ -132,19 +265,16 @@ public DockerClientConfigBuilder() { * should contain the following docker.io.* keys: url, version, username, password, email, and dockerCertPath. If * docker.io.readTimeout or docker.io.enableLoggingFilter are not contained, they will be set to 1000 and true, * respectively. - * - * @param p - * @return */ public DockerClientConfigBuilder withProperties(Properties p) { - return withUri(p.getProperty("docker.io.url")) - .withVersion(p.getProperty("docker.io.version")) - .withUsername(p.getProperty("docker.io.username")) - .withPassword(p.getProperty("docker.io.password")) - .withEmail(p.getProperty("docker.io.email")) - .withReadTimeout(Integer.valueOf(p.getProperty("docker.io.readTimeout", "0"))) - .withLoggingFilter(Boolean.valueOf(p.getProperty("docker.io.enableLoggingFilter", "true"))) - .withDockerCertPath(p.getProperty("docker.io.dockerCertPath")); + return withUri(p.getProperty(DOCKER_IO_URL_PROPERTY)) + .withVersion(p.getProperty(DOCKER_IO_VERSION_PROPERTY)) + .withUsername(p.getProperty(DOCKER_IO_USERNAME_PROPERTY)) + .withPassword(p.getProperty(DOCKER_IO_PASSWORD_PROPERTY)) + .withEmail(p.getProperty(DOCKER_IO_EMAIL_PROPERTY)) + .withReadTimeout(Integer.valueOf(p.getProperty(DOCKER_IO_READ_TIMEOUT_PROPERTY, "0"))) + .withLoggingFilter(Boolean.valueOf(p.getProperty(DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY, "true"))) + .withDockerCertPath(p.getProperty(DOCKER_IO_DOCKER_CERT_PATH_PROPERTY)); } public final DockerClientConfigBuilder withUri(String uri) { @@ -181,7 +311,16 @@ public final DockerClientConfigBuilder withDockerCertPath(String dockerCertPath) return this; } public DockerClientConfig build() { - return new DockerClientConfig(this); + return new DockerClientConfig( + uri, + version, + username, + password, + email, + dockerCertPath, + readTimeout, + loggingFilterEnabled + ); } } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index cb912873..862824fc 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -2,74 +2,37 @@ import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.github.dockerjava.api.DockerClientException; -import com.github.dockerjava.api.command.AttachContainerCmd; -import com.github.dockerjava.api.command.AuthCmd; -import com.github.dockerjava.api.command.BuildImageCmd; -import com.github.dockerjava.api.command.CommitCmd; -import com.github.dockerjava.api.command.ContainerDiffCmd; -import com.github.dockerjava.api.command.CopyFileFromContainerCmd; -import com.github.dockerjava.api.command.CreateContainerCmd; -import com.github.dockerjava.api.command.CreateImageCmd; -import com.github.dockerjava.api.command.DockerCmdExecFactory; -import com.github.dockerjava.api.command.EventsCmd; -import com.github.dockerjava.api.command.InfoCmd; -import com.github.dockerjava.api.command.InspectContainerCmd; -import com.github.dockerjava.api.command.InspectImageCmd; -import com.github.dockerjava.api.command.KillContainerCmd; -import com.github.dockerjava.api.command.ListContainersCmd; -import com.github.dockerjava.api.command.ListImagesCmd; -import com.github.dockerjava.api.command.LogContainerCmd; -import com.github.dockerjava.api.command.PauseContainerCmd; -import com.github.dockerjava.api.command.PingCmd; -import com.github.dockerjava.api.command.PullImageCmd; -import com.github.dockerjava.api.command.PushImageCmd; -import com.github.dockerjava.api.command.RemoveContainerCmd; -import com.github.dockerjava.api.command.RemoveImageCmd; -import com.github.dockerjava.api.command.RestartContainerCmd; -import com.github.dockerjava.api.command.SearchImagesCmd; -import com.github.dockerjava.api.command.StartContainerCmd; -import com.github.dockerjava.api.command.StopContainerCmd; -import com.github.dockerjava.api.command.TagImageCmd; -import com.github.dockerjava.api.command.TopContainerCmd; -import com.github.dockerjava.api.command.UnpauseContainerCmd; -import com.github.dockerjava.api.command.VersionCmd; -import com.github.dockerjava.api.command.WaitContainerCmd; +import com.github.dockerjava.api.command.*; import com.github.dockerjava.core.CertificateUtils; import com.github.dockerjava.core.DockerClientConfig; import com.github.dockerjava.jaxrs.util.JsonClientFilter; import com.github.dockerjava.jaxrs.util.ResponseStatusExceptionFilter; import com.github.dockerjava.jaxrs.util.SelectiveLoggingFilter; import com.google.common.base.Preconditions; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.glassfish.jersey.CommonProperties; +import org.glassfish.jersey.SslConfigurator; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; -import java.io.File; +import javax.net.ssl.SSLContext; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; import java.io.IOException; import java.security.KeyStore; import java.security.Security; import java.util.logging.Logger; -import javax.net.ssl.SSLContext; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; +public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.glassfish.jersey.CommonProperties; -import org.glassfish.jersey.SslConfigurator; -import org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.client.ClientProperties; + private static final Logger LOGGER = Logger.getLogger(DockerCmdExecFactoryImpl.class.getName()); + private Client client; + private WebTarget baseResource; -public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { - - private Client client; - - private WebTarget baseResource; - - private static final Logger LOGGER = Logger.getLogger(DockerCmdExecFactoryImpl.class.getName()); - - - @Override - public void init(DockerClientConfig dockerClientConfig) { - Preconditions.checkNotNull(dockerClientConfig, "config was not specified"); + @Override + public void init(DockerClientConfig dockerClientConfig) { + Preconditions.checkNotNull(dockerClientConfig, "config was not specified"); ClientConfig clientConfig = new ClientConfig(); clientConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); @@ -81,240 +44,227 @@ public void init(DockerClientConfig dockerClientConfig) { if (dockerClientConfig.isLoggingFilterEnabled()) { clientConfig.register(new SelectiveLoggingFilter(LOGGER, true)); } - + if (dockerClientConfig.getReadTimeout() != null) { - int readTimeout = dockerClientConfig.getReadTimeout(); - clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); + int readTimeout = dockerClientConfig.getReadTimeout(); + clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); } - + ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig); - - // Attempt to load Docker SSL certificates from location in following order: - // 1. User Defined - // 2. Environment Variable - // 3. User Home Directory + String dockerCertPath = dockerClientConfig.getDockerCertPath(); - - if(dockerCertPath == null) { - dockerCertPath = System.getenv("DOCKER_CERT_PATH"); - } - - if(dockerCertPath == null) { - dockerCertPath = System.getProperty("USER_HOME") + File.separator + ".docker"; - } - - if(dockerCertPath != null) { + + if (dockerCertPath != null) { boolean certificatesExist = CertificateUtils.verifyCertificatesExist(dockerCertPath); - - if(certificatesExist) { - + + if (certificatesExist) { + try { - + Security.addProvider(new BouncyCastleProvider()); - + KeyStore keyStore = CertificateUtils.createKeyStore(dockerCertPath); KeyStore trustStore = CertificateUtils.createTrustStore(dockerCertPath); - + // properties acrobatics not needed for java > 1.6 String httpProtocols = System.getProperty("https.protocols"); System.setProperty("https.protocols", "TLSv1"); SslConfigurator sslConfig = SslConfigurator.newInstance(true); - if(httpProtocols != null ) System.setProperty("https.protocols", httpProtocols); - + if (httpProtocols != null) System.setProperty("https.protocols", httpProtocols); + sslConfig.keyStore(keyStore); sslConfig.keyStorePassword("docker"); sslConfig.trustStore(trustStore); - + SSLContext sslContext = sslConfig.createSSLContext(); - - - clientBuilder.sslContext(sslContext); - } - catch(Exception e) { + + clientBuilder.sslContext(sslContext); + + } catch (Exception e) { throw new DockerClientException(e.getMessage(), e); } - + } } - + client = clientBuilder.build(); - + WebTarget webResource = client.target(dockerClientConfig.getUri()); if (dockerClientConfig.getVersion() == null || dockerClientConfig.getVersion().isEmpty()) { - baseResource = webResource; + baseResource = webResource; } else { - baseResource = webResource.path("v" + dockerClientConfig.getVersion()); + baseResource = webResource.path("v" + dockerClientConfig.getVersion()); } - - } - - protected WebTarget getBaseResource() { - Preconditions.checkNotNull(baseResource, "Factory not initialized. You probably forgot to call init()!"); - return baseResource; - } - - @Override - public AuthCmd.Exec createAuthCmdExec() { - return new AuthCmdExec(getBaseResource()); - } - - @Override - public InfoCmd.Exec createInfoCmdExec() { - return new InfoCmdExec(getBaseResource()); - } - - @Override - public PingCmd.Exec createPingCmdExec() { - return new PingCmdExec(getBaseResource()); - } - - @Override - public VersionCmd.Exec createVersionCmdExec() { - return new VersionCmdExec(getBaseResource()); - } - - @Override - public PullImageCmd.Exec createPullImageCmdExec() { - return new PullImageCmdExec(getBaseResource()); - } - - @Override - public PushImageCmd.Exec createPushImageCmdExec() { - return new PushImageCmdExec(getBaseResource()); - } - - @Override - public CreateImageCmd.Exec createCreateImageCmdExec() { - return new CreateImageCmdExec(getBaseResource()); - } - - @Override - public SearchImagesCmd.Exec createSearchImagesCmdExec() { - return new SearchImagesCmdExec(getBaseResource()); - } - - @Override - public RemoveImageCmd.Exec createRemoveImageCmdExec() { - return new RemoveImageCmdExec(getBaseResource()); - } - - @Override - public ListImagesCmd.Exec createListImagesCmdExec() { - return new ListImagesCmdExec(getBaseResource()); - } - - @Override - public InspectImageCmd.Exec createInspectImageCmdExec() { - return new InspectImageCmdExec(getBaseResource()); - } - - @Override - public ListContainersCmd.Exec createListContainersCmdExec() { - return new ListContainersCmdExec(getBaseResource()); - } - - @Override - public CreateContainerCmd.Exec createCreateContainerCmdExec() { - return new CreateContainerCmdExec(getBaseResource()); - } - - @Override - public StartContainerCmd.Exec createStartContainerCmdExec() { - return new StartContainerCmdExec(getBaseResource()); - } - - @Override - public InspectContainerCmd.Exec createInspectContainerCmdExec() { - return new InspectContainerCmdExec(getBaseResource()); - } - - @Override - public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { - return new RemoveContainerCmdExec(getBaseResource()); - } - - @Override - public WaitContainerCmd.Exec createWaitContainerCmdExec() { - return new WaitContainerCmdExec(getBaseResource()); - } - - @Override - public AttachContainerCmd.Exec createAttachContainerCmdExec() { - return new AttachContainerCmdExec(getBaseResource()); - } - - @Override - public LogContainerCmd.Exec createLogContainerCmdExec() { - return new LogContainerCmdExec(getBaseResource()); - } - - @Override - public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() { - return new CopyFileFromContainerCmdExec(getBaseResource()); - } - - @Override - public StopContainerCmd.Exec createStopContainerCmdExec() { - return new StopContainerCmdExec(getBaseResource()); - } - - @Override - public ContainerDiffCmd.Exec createContainerDiffCmdExec() { - return new ContainerDiffCmdExec(getBaseResource()); - } - - @Override - public KillContainerCmd.Exec createKillContainerCmdExec() { - return new KillContainerCmdExec(getBaseResource()); - } - - @Override - public RestartContainerCmd.Exec createRestartContainerCmdExec() { - return new RestartContainerCmdExec(getBaseResource()); - } - - @Override - public CommitCmd.Exec createCommitCmdExec() { - return new CommitCmdExec(getBaseResource()); - } - - @Override - public BuildImageCmd.Exec createBuildImageCmdExec() { - return new BuildImageCmdExec(getBaseResource()); - } - - @Override - public TopContainerCmd.Exec createTopContainerCmdExec() { - return new TopContainerCmdExec(getBaseResource()); - } - - @Override - public TagImageCmd.Exec createTagImageCmdExec() { - return new TagImageCmdExec(getBaseResource()); - } - - @Override - public PauseContainerCmd.Exec createPauseContainerCmdExec() { - return new PauseContainerCmdExec(getBaseResource()); - } - - @Override - public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { - return new UnpauseContainerCmdExec(baseResource); - } - - @Override - public EventsCmd.Exec createEventsCmdExec() { - return new EventsCmdExec(getBaseResource()); - } - - @Override - public void close() throws IOException { - Preconditions.checkNotNull(client, "Factory not initialized. You probably forgot to call init()!"); - client.close(); - } + + } + + protected WebTarget getBaseResource() { + Preconditions.checkNotNull(baseResource, "Factory not initialized. You probably forgot to call init()!"); + return baseResource; + } + + @Override + public AuthCmd.Exec createAuthCmdExec() { + return new AuthCmdExec(getBaseResource()); + } + + @Override + public InfoCmd.Exec createInfoCmdExec() { + return new InfoCmdExec(getBaseResource()); + } + + @Override + public PingCmd.Exec createPingCmdExec() { + return new PingCmdExec(getBaseResource()); + } + + @Override + public VersionCmd.Exec createVersionCmdExec() { + return new VersionCmdExec(getBaseResource()); + } + + @Override + public PullImageCmd.Exec createPullImageCmdExec() { + return new PullImageCmdExec(getBaseResource()); + } + + @Override + public PushImageCmd.Exec createPushImageCmdExec() { + return new PushImageCmdExec(getBaseResource()); + } + + @Override + public CreateImageCmd.Exec createCreateImageCmdExec() { + return new CreateImageCmdExec(getBaseResource()); + } + + @Override + public SearchImagesCmd.Exec createSearchImagesCmdExec() { + return new SearchImagesCmdExec(getBaseResource()); + } + + @Override + public RemoveImageCmd.Exec createRemoveImageCmdExec() { + return new RemoveImageCmdExec(getBaseResource()); + } + + @Override + public ListImagesCmd.Exec createListImagesCmdExec() { + return new ListImagesCmdExec(getBaseResource()); + } + + @Override + public InspectImageCmd.Exec createInspectImageCmdExec() { + return new InspectImageCmdExec(getBaseResource()); + } + + @Override + public ListContainersCmd.Exec createListContainersCmdExec() { + return new ListContainersCmdExec(getBaseResource()); + } + + @Override + public CreateContainerCmd.Exec createCreateContainerCmdExec() { + return new CreateContainerCmdExec(getBaseResource()); + } + + @Override + public StartContainerCmd.Exec createStartContainerCmdExec() { + return new StartContainerCmdExec(getBaseResource()); + } + + @Override + public InspectContainerCmd.Exec createInspectContainerCmdExec() { + return new InspectContainerCmdExec(getBaseResource()); + } + + @Override + public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { + return new RemoveContainerCmdExec(getBaseResource()); + } + + @Override + public WaitContainerCmd.Exec createWaitContainerCmdExec() { + return new WaitContainerCmdExec(getBaseResource()); + } + + @Override + public AttachContainerCmd.Exec createAttachContainerCmdExec() { + return new AttachContainerCmdExec(getBaseResource()); + } + + @Override + public LogContainerCmd.Exec createLogContainerCmdExec() { + return new LogContainerCmdExec(getBaseResource()); + } + + @Override + public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() { + return new CopyFileFromContainerCmdExec(getBaseResource()); + } + + @Override + public StopContainerCmd.Exec createStopContainerCmdExec() { + return new StopContainerCmdExec(getBaseResource()); + } + + @Override + public ContainerDiffCmd.Exec createContainerDiffCmdExec() { + return new ContainerDiffCmdExec(getBaseResource()); + } + + @Override + public KillContainerCmd.Exec createKillContainerCmdExec() { + return new KillContainerCmdExec(getBaseResource()); + } + + @Override + public RestartContainerCmd.Exec createRestartContainerCmdExec() { + return new RestartContainerCmdExec(getBaseResource()); + } + + @Override + public CommitCmd.Exec createCommitCmdExec() { + return new CommitCmdExec(getBaseResource()); + } + + @Override + public BuildImageCmd.Exec createBuildImageCmdExec() { + return new BuildImageCmdExec(getBaseResource()); + } + + @Override + public TopContainerCmd.Exec createTopContainerCmdExec() { + return new TopContainerCmdExec(getBaseResource()); + } + + @Override + public TagImageCmd.Exec createTagImageCmdExec() { + return new TagImageCmdExec(getBaseResource()); + } + + @Override + public PauseContainerCmd.Exec createPauseContainerCmdExec() { + return new PauseContainerCmdExec(getBaseResource()); + } + + @Override + public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { + return new UnpauseContainerCmdExec(baseResource); + } + + @Override + public EventsCmd.Exec createEventsCmdExec() { + return new EventsCmdExec(getBaseResource()); + } + + @Override + public void close() throws IOException { + Preconditions.checkNotNull(client, "Factory not initialized. You probably forgot to call init()!"); + client.close(); + } } diff --git a/src/main/resources/docker.io.properties b/src/main/resources/docker.io.properties index ea8ce7ed..f4d69953 100644 --- a/src/main/resources/docker.io.properties +++ b/src/main/resources/docker.io.properties @@ -1,4 +1,4 @@ docker.io.url=https://localhost:2376 docker.io.version=1.15 docker.io.enableLoggingFilter=true -#docker.io.dockerCertPath= \ No newline at end of file +docker.io.dockerCertPath=${user.home}/.docker \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java new file mode 100644 index 00000000..b0747e68 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java @@ -0,0 +1,125 @@ +package com.github.dockerjava.core; + +import org.testng.annotations.Test; + +import java.net.URI; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import static org.testng.Assert.assertEquals; + +public class DockerClientConfigTest { + + public static final DockerClientConfig EXAMPLE_CONFIG = newExampleConfig(); + + private static DockerClientConfig newExampleConfig() { + return new DockerClientConfig(URI.create("http://foo"), "bar", "baz", "qux", "blam", "flim", 877, false); + } + + @Test + public void string() throws Exception { + assertEquals("DockerClientConfig{uri=http://foo, version='bar', username='baz', password='qux', email='blam', dockerCertPath='flim', readTimeout=877, loggingFilterEnabled=false}", + EXAMPLE_CONFIG.toString()); + } + + @Test + public void equals() throws Exception { + assertEquals(EXAMPLE_CONFIG, newExampleConfig()); + } + + @Test + public void environmentDockerHost() throws Exception { + + // given docker host in env + Map env = new HashMap(System.getenv()); + env.put("DOCKER_HOST", "tcp://baz:8768"); + + // when you build a config + DockerClientConfig config = buildConfig(env, new Properties()); + + // then the URL is that value with "http" instead of "tcp" + assertEquals(config.getUri(), URI.create("http://baz:8768")); + } + + @Test + public void environmentDockerHostHttpsAutoDetect() throws Exception { + + // given docker host in env + Map env = new HashMap(System.getenv()); + env.put("DOCKER_HOST", "tcp://bar:8768"); + // and it looks to be SSL enabled + env.put("DOCKER_CERT_PATH", "any value"); + + // when you build a config + DockerClientConfig config = buildConfig(env, new Properties()); + + // then the URL is that value with "tcp" changed to "https" + assertEquals(config.getUri(), URI.create("https://bar:8768")); + } + + @Test + public void environment() throws Exception { + + // given a default config in env properties + Map env = new HashMap(); + env.put("DOCKER_URL", "http://foo"); + env.put("DOCKER_VERSION", "bar"); + env.put("DOCKER_USERNAME", "baz"); + env.put("DOCKER_PASSWORD", "qux"); + env.put("DOCKER_EMAIL", "blam"); + env.put("DOCKER_CERT_PATH", "flim"); + env.put("DOCKER_READ_TIMEOUT", "877"); + env.put("DOCKER_LOGGING_FILTER_ENABLED", "false"); + + // when you build a config + DockerClientConfig config = buildConfig(env, new Properties()); + + // then we get the example object + assertEquals(config, EXAMPLE_CONFIG); + } + + private DockerClientConfig buildConfig(Map env, Properties systemProperties) { + return DockerClientConfig.createDefaultConfigBuilder(env, systemProperties).build(); + } + + @Test + public void defaults() throws Exception { + + // given default cert path + Properties systemProperties = new Properties(); + systemProperties.setProperty("user.home", "someHomeDir"); + + // when you build config + DockerClientConfig config = buildConfig(Collections.emptyMap(), systemProperties); + + // then the cert path is as expected + assertEquals(config.getUri(), URI.create("https://localhost:2376")); + assertEquals(config.getVersion(), "1.15"); + assertEquals(config.isLoggingFilterEnabled(), true); + assertEquals(config.getDockerCertPath(), "someHomeDir/.docker"); + } + + @Test + public void systemProperties() throws Exception { + + // given system properties based on the example + Properties systemProperties = new Properties(); + systemProperties.setProperty("docker.io.url", "http://foo"); + systemProperties.setProperty("docker.io.version", "bar"); + systemProperties.setProperty("docker.io.username", "baz"); + systemProperties.setProperty("docker.io.password", "qux"); + systemProperties.setProperty("docker.io.email", "blam"); + systemProperties.setProperty("docker.io.dockerCertPath", "flim"); + systemProperties.setProperty("docker.io.readTimeout", "877"); + systemProperties.setProperty("docker.io.enableLoggingFilter", "false"); + + // when you build new config + DockerClientConfig config = buildConfig(Collections.emptyMap(), systemProperties); + + // then it is the same as the example + assertEquals(config, EXAMPLE_CONFIG); + + } +} \ No newline at end of file From 80d1a3d3d8b84b69cd7aa62aee1811a2da9c0bb3 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 26 Oct 2014 13:38:54 +0000 Subject: [PATCH 173/452] made method public --- .../dockerjava/core/DockerClientConfig.java | 41 +++++++++++-------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 8ed9a3fa..c12585a5 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -1,14 +1,14 @@ - package com.github.dockerjava.core; +package com.github.dockerjava.core; - import com.google.common.base.Preconditions; - import com.google.common.collect.ImmutableMap; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; - import java.io.File; - import java.io.FileInputStream; - import java.io.IOException; - import java.net.URI; - import java.util.Map; - import java.util.Properties; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URI; +import java.util.Map; +import java.util.Properties; public class DockerClientConfig { private static final String DOCKER_HOST_PROPERTY = "DOCKER_HOST"; @@ -257,9 +257,6 @@ public static class DockerClientConfigBuilder { private Integer readTimeout; private boolean loggingFilterEnabled; - private DockerClientConfigBuilder() { - } - /** * This will set all fields in the builder to those contained in the Properties object. The Properties object * should contain the following docker.io.* keys: url, version, username, password, email, and dockerCertPath. If @@ -278,38 +275,46 @@ public DockerClientConfigBuilder withProperties(Properties p) { } public final DockerClientConfigBuilder withUri(String uri) { - Preconditions.checkNotNull(uri, "uri was not specified"); + Preconditions.checkNotNull(uri, "uri was not specified"); this.uri = URI.create(uri); return this; } + public final DockerClientConfigBuilder withVersion(String version) { - this.version = version; + this.version = version; return this; } + public final DockerClientConfigBuilder withUsername(String username) { - this.username = username; + this.username = username; return this; } + public final DockerClientConfigBuilder withPassword(String password) { - this.password = password; + this.password = password; return this; } + public final DockerClientConfigBuilder withEmail(String email) { - this.email = email; + this.email = email; return this; } + public final DockerClientConfigBuilder withReadTimeout(Integer readTimeout) { - this.readTimeout = readTimeout; + this.readTimeout = readTimeout; return this; } + public final DockerClientConfigBuilder withLoggingFilter(boolean loggingFilterEnabled) { this.loggingFilterEnabled = loggingFilterEnabled; return this; } + public final DockerClientConfigBuilder withDockerCertPath(String dockerCertPath) { this.dockerCertPath = dockerCertPath; return this; } + public DockerClientConfig build() { return new DockerClientConfig( uri, From d1f31cdfb0716c976eff6051f00fc8896cfc75c8 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Mon, 20 Oct 2014 20:49:49 +0200 Subject: [PATCH 174/452] Document current deserialization of Ports with a test --- .../dockerjava/api/model/PortsTest.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/test/java/com/github/dockerjava/api/model/PortsTest.java diff --git a/src/test/java/com/github/dockerjava/api/model/PortsTest.java b/src/test/java/com/github/dockerjava/api/model/PortsTest.java new file mode 100644 index 00000000..9cd5ef72 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/PortsTest.java @@ -0,0 +1,33 @@ +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import java.util.Map; + +import org.testng.annotations.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.model.Ports.Binding; + +public class PortsTest { + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Test + public void deserializingPortWithMultipleBindingsReturnsFirstBinding() throws Exception { + String json = "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"},{\"HostIp\":\"10.0.0.2\",\"HostPort\":\"80\"}]}"; + Ports ports = objectMapper.readValue(json, Ports.class); + Map bindings = ports.getBindings(); + assertEquals(bindings.size(), 1); + + Binding binding = bindings.get(ExposedPort.tcp(80)); + assertEquals(binding, new Binding("10.0.0.1", 80)); + } + + @Test + public void serializePort() throws Exception { + Ports ports = new Ports(ExposedPort.tcp(80), new Binding("10.0.0.1", 80)); + String expectedJson = "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"}]}"; + assertEquals(objectMapper.writeValueAsString(ports), expectedJson); + } + +} From 4571e99c6d9ceb1401d1ed7927723b8f840fd0e4 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Mon, 20 Oct 2014 21:55:37 +0200 Subject: [PATCH 175/452] Allow multiple port bindings per exposed port --- .../github/dockerjava/api/model/Ports.java | 45 +++++++----- .../dockerjava/api/model/PortsTest.java | 70 ++++++++++--------- .../command/StartContainerCmdImplTest.java | 8 ++- 3 files changed, 71 insertions(+), 52 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/model/Ports.java b/src/main/java/com/github/dockerjava/api/model/Ports.java index fe790468..a14b3103 100644 --- a/src/main/java/com/github/dockerjava/api/model/Ports.java +++ b/src/main/java/com/github/dockerjava/api/model/Ports.java @@ -6,7 +6,9 @@ import java.util.Map; import java.util.Map.Entry; +import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; @@ -23,8 +25,6 @@ import com.github.dockerjava.api.command.InspectContainerResponse.HostConfig; import com.github.dockerjava.api.command.InspectContainerResponse.NetworkSettings; -import org.apache.commons.lang.builder.ToStringBuilder; - /** * A container for port bindings, made available as a {@link Map} via its * {@link #getBindings()} method. @@ -36,7 +36,7 @@ @JsonSerialize(using = Ports.Serializer.class) public class Ports { - private final Map ports = new HashMap(); + private final Map ports = new HashMap(); public Ports() { } @@ -45,7 +45,12 @@ public Ports(ExposedPort exposedPort, Binding host) { } public void bind(ExposedPort exposedPort, Binding host) { - ports.put(exposedPort, host); + if (ports.containsKey(exposedPort)) { + Binding[] bindings = ports.get(exposedPort); + ports.put(exposedPort, (Binding[]) ArrayUtils.add(bindings, host)); + } else { + ports.put(exposedPort, new Binding[]{host}); + } } @Override @@ -54,10 +59,10 @@ public String toString(){ } /** - * @return the port bindings as a {@link Map} that contains one - * {@link Binding} per {@link ExposedPort}. + * @return the port bindings as a {@link Map} that contains one or more + * {@link Binding}s per {@link ExposedPort}. */ - public Map getBindings(){ + public Map getBindings(){ return ports; } @@ -132,11 +137,15 @@ public Ports deserialize(JsonParser jsonParser, DeserializationContext deseriali 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(); - int hostPort = field.getValue().get(0).get("HostPort").asInt(); - out.bind(ExposedPort.parse(field.getKey()), new Binding(hostIp, hostPort)); + Map.Entry portNode = it.next(); + JsonNode bindingsArray = portNode.getValue(); + for (int i = 0; i < bindingsArray.size(); i++) { + JsonNode bindingNode = bindingsArray.get(i); + if (!bindingNode.equals(NullNode.getInstance())) { + String hostIp = bindingNode.get("HostIp").textValue(); + int hostPort = bindingNode.get("HostPort").asInt(); + out.bind(ExposedPort.parse(portNode.getKey()), new Binding(hostIp, hostPort)); + } } } return out; @@ -150,13 +159,15 @@ public void serialize(Ports portBindings, JsonGenerator jsonGen, SerializerProvider serProvider) throws IOException, JsonProcessingException { jsonGen.writeStartObject(); - for(Entry entry : portBindings.getBindings().entrySet()){ + for(Entry entry : portBindings.getBindings().entrySet()){ jsonGen.writeFieldName(entry.getKey().toString()); jsonGen.writeStartArray(); - jsonGen.writeStartObject(); - jsonGen.writeStringField("HostIp", entry.getValue().getHostIp()); - jsonGen.writeStringField("HostPort", "" + entry.getValue().getHostPort()); - jsonGen.writeEndObject(); + for (Binding binding : entry.getValue()) { + jsonGen.writeStartObject(); + jsonGen.writeStringField("HostIp", binding.getHostIp()); + jsonGen.writeStringField("HostPort", "" + binding.getHostPort()); + jsonGen.writeEndObject(); + } jsonGen.writeEndArray(); } jsonGen.writeEndObject(); diff --git a/src/test/java/com/github/dockerjava/api/model/PortsTest.java b/src/test/java/com/github/dockerjava/api/model/PortsTest.java index 9cd5ef72..6a6c5e44 100644 --- a/src/test/java/com/github/dockerjava/api/model/PortsTest.java +++ b/src/test/java/com/github/dockerjava/api/model/PortsTest.java @@ -1,33 +1,37 @@ -package com.github.dockerjava.api.model; - -import static org.testng.Assert.assertEquals; - -import java.util.Map; - -import org.testng.annotations.Test; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.dockerjava.api.model.Ports.Binding; - -public class PortsTest { - private final ObjectMapper objectMapper = new ObjectMapper(); - - @Test - public void deserializingPortWithMultipleBindingsReturnsFirstBinding() throws Exception { - String json = "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"},{\"HostIp\":\"10.0.0.2\",\"HostPort\":\"80\"}]}"; - Ports ports = objectMapper.readValue(json, Ports.class); - Map bindings = ports.getBindings(); - assertEquals(bindings.size(), 1); - - Binding binding = bindings.get(ExposedPort.tcp(80)); - assertEquals(binding, new Binding("10.0.0.1", 80)); - } - - @Test - public void serializePort() throws Exception { - Ports ports = new Ports(ExposedPort.tcp(80), new Binding("10.0.0.1", 80)); - String expectedJson = "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"}]}"; - assertEquals(objectMapper.writeValueAsString(ports), expectedJson); - } - -} +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import java.util.Map; + +import org.testng.annotations.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.model.Ports.Binding; + +public class PortsTest { + private final ObjectMapper objectMapper = new ObjectMapper(); + private final String jsonWithDoubleBindingForOnePort = + "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"},{\"HostIp\":\"10.0.0.2\",\"HostPort\":\"80\"}]}"; + + @Test + public void deserializingPortWithMultipleBindings() throws Exception { + Ports ports = objectMapper.readValue(jsonWithDoubleBindingForOnePort, Ports.class); + Map map = ports.getBindings(); + assertEquals(map.size(), 1); + + Binding[] bindings = map.get(ExposedPort.tcp(80)); + assertEquals(bindings.length, 2); + assertEquals(bindings[0], new Binding("10.0.0.1", 80)); + assertEquals(bindings[1], new Binding("10.0.0.2", 80)); + } + + @Test + public void serializingPortWithMultipleBindings() throws Exception { + Ports ports = new Ports(); + ports.bind(ExposedPort.tcp(80), new Binding("10.0.0.1", 80)); + ports.bind(ExposedPort.tcp(80), new Binding("10.0.0.2", 80)); + assertEquals(objectMapper.writeValueAsString(ports), jsonWithDoubleBindingForOnePort); + } + +} diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index e5ceff82..469259ee 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -163,6 +163,7 @@ public void startContainerWithPortBindings() throws DockerException { Ports portBindings = new Ports(); portBindings.bind(tcp22, Ports.Binding(11022)); portBindings.bind(tcp23, Ports.Binding(11023)); + portBindings.bind(tcp23, Ports.Binding(11024)); dockerClient.startContainerCmd(container.getId()).withPortBindings(portBindings).exec(); @@ -172,12 +173,15 @@ public void startContainerWithPortBindings() throws DockerException { assertThat(Arrays.asList(inspectContainerResponse.getConfig().getExposedPorts()), contains(tcp22, tcp23)); - assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp22), + assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp22)[0], is(equalTo(Ports.Binding(11022)))); - assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23), + assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23)[0], is(equalTo(Ports.Binding(11023)))); + assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23)[1], + is(equalTo(Ports.Binding(11024)))); + } @Test From c656b26fa7baa1d9cb1d7319b81fabd66b59c59b Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 26 Oct 2014 20:02:25 +0100 Subject: [PATCH 176/452] Fix issue #71 --- .../java/com/github/dockerjava/core/DockerClientBuilder.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java b/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java index 42d29bbc..80028a10 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java @@ -4,6 +4,7 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.DockerCmdExecFactory; +import com.github.dockerjava.core.DockerClientConfig.DockerClientConfigBuilder; public class DockerClientBuilder { @@ -18,6 +19,10 @@ private DockerClientBuilder(DockerClientImpl dockerClient) { public static DockerClientBuilder getInstance() { return new DockerClientBuilder(withDefaultDockerCmdExecFactory(DockerClientImpl.getInstance())); } + + public static DockerClientBuilder getInstance(DockerClientConfigBuilder dockerClientConfigBuilder) { + return getInstance(dockerClientConfigBuilder.build()); + } public static DockerClientBuilder getInstance(DockerClientConfig dockerClientConfig) { return new DockerClientBuilder(withDefaultDockerCmdExecFactory(DockerClientImpl From fc706edc6e10c97cdf20215477f443af75080f6d Mon Sep 17 00:00:00 2001 From: Andrew Block Date: Mon, 27 Oct 2014 17:03:16 -0500 Subject: [PATCH 177/452] Allow for custom implementations of DockerCmdExecFactory to be specified without attempting to load default --- .../dockerjava/core/DockerClientBuilder.java | 30 +++++++++---------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java b/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java index 80028a10..fb7783ce 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java @@ -11,13 +11,14 @@ public class DockerClientBuilder { private static ServiceLoader serviceLoader = ServiceLoader.load(DockerCmdExecFactory.class); private DockerClientImpl dockerClient = null; + private DockerCmdExecFactory dockerCmdExecFactory = null; private DockerClientBuilder(DockerClientImpl dockerClient) { this.dockerClient = dockerClient; } public static DockerClientBuilder getInstance() { - return new DockerClientBuilder(withDefaultDockerCmdExecFactory(DockerClientImpl.getInstance())); + return new DockerClientBuilder(DockerClientImpl.getInstance()); } public static DockerClientBuilder getInstance(DockerClientConfigBuilder dockerClientConfigBuilder) { @@ -25,22 +26,13 @@ public static DockerClientBuilder getInstance(DockerClientConfigBuilder dockerCl } public static DockerClientBuilder getInstance(DockerClientConfig dockerClientConfig) { - return new DockerClientBuilder(withDefaultDockerCmdExecFactory(DockerClientImpl - .getInstance(dockerClientConfig))); + return new DockerClientBuilder(DockerClientImpl + .getInstance(dockerClientConfig)); } public static DockerClientBuilder getInstance(String serverUrl) { - return new DockerClientBuilder(withDefaultDockerCmdExecFactory(DockerClientImpl - .getInstance(serverUrl))); - } - - private static DockerClientImpl withDefaultDockerCmdExecFactory( - DockerClientImpl dockerClient) { - - DockerCmdExecFactory dockerCmdExecFactory = getDefaultDockerCmdExecFactory(); - - return dockerClient - .withDockerCmdExecFactory(dockerCmdExecFactory); + return new DockerClientBuilder(DockerClientImpl + .getInstance(serverUrl)); } public static DockerCmdExecFactory getDefaultDockerCmdExecFactory() { @@ -53,12 +45,18 @@ public static DockerCmdExecFactory getDefaultDockerCmdExecFactory() { public DockerClientBuilder withDockerCmdExecFactory( DockerCmdExecFactory dockerCmdExecFactory) { - dockerClient = dockerClient - .withDockerCmdExecFactory(dockerCmdExecFactory); + this.dockerCmdExecFactory = dockerCmdExecFactory; return this; } public DockerClient build() { + if(dockerCmdExecFactory != null) { + dockerClient.withDockerCmdExecFactory(dockerCmdExecFactory); + } + else { + dockerClient.withDockerCmdExecFactory(getDefaultDockerCmdExecFactory()); + } + return dockerClient; } } From 97bf5ef4aebb0c04b67238e034477b14e8cc2d95 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Mon, 27 Oct 2014 19:04:40 +0100 Subject: [PATCH 178/452] More intuitive way to add port bindings: new abstraction "PortBinding" The use of Ports for adding port bindings requires knowledge of the internal data structure used for storing port bindings in Docker API. This commit adds a more intuitive alternative that works like the --publish option of the Docker CLI and some builder methods like withBinds(Bind...) and withLinks(Link...). --- .../api/command/StartContainerCmd.java | 14 +++++ .../dockerjava/api/model/PortBinding.java | 36 ++++++++++++ .../github/dockerjava/api/model/Ports.java | 56 +++++++++++++++--- .../core/command/StartContainerCmdImpl.java | 11 ++++ ...tsTest.java => Ports_SerializingTest.java} | 2 +- .../api/model/Ports_addBindingsTest.java | 57 +++++++++++++++++++ 6 files changed, 168 insertions(+), 8 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/PortBinding.java rename src/test/java/com/github/dockerjava/api/model/{PortsTest.java => Ports_SerializingTest.java} (94%) create mode 100644 src/test/java/com/github/dockerjava/api/model/Ports_addBindingsTest.java diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index ed16a727..8535c8ed 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -6,6 +6,7 @@ import com.github.dockerjava.api.model.Device; import com.github.dockerjava.api.model.Link; import com.github.dockerjava.api.model.LxcConf; +import com.github.dockerjava.api.model.PortBinding; import com.github.dockerjava.api.model.Ports; import com.github.dockerjava.api.model.RestartPolicy; @@ -53,8 +54,21 @@ public interface StartContainerCmd extends DockerCmd { public StartContainerCmd withLxcConf(LxcConf... lxcConf); + /** + * Add the port bindings that are contained in the given {@link Ports} + * object. + * + * @see #withPortBindings(PortBinding...) + */ public StartContainerCmd withPortBindings(Ports portBindings); + /** + * Add one or more {@link PortBinding}s. + * This corresponds to the --publish (-p) + * option of the docker run CLI command. + */ + public StartContainerCmd withPortBindings(PortBinding... portBindings); + public StartContainerCmd withPrivileged(boolean privileged); public StartContainerCmd withPublishAllPorts(boolean publishAllPorts); diff --git a/src/main/java/com/github/dockerjava/api/model/PortBinding.java b/src/main/java/com/github/dockerjava/api/model/PortBinding.java new file mode 100644 index 00000000..be4f5a29 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/PortBinding.java @@ -0,0 +1,36 @@ +package com.github.dockerjava.api.model; + +import com.github.dockerjava.api.command.InspectContainerResponse.HostConfig; +import com.github.dockerjava.api.command.InspectContainerResponse.NetworkSettings; +import com.github.dockerjava.api.model.Ports.Binding; + +/** + * In a {@link PortBinding}, a network socket on the Docker host, expressed + * as a {@link Binding}, is bound to an {@link ExposedPort} of a container. + * A {@link PortBinding} corresponds to the --publish + * (-p) option of the docker run (and similar) + * CLI command for adding port bindings to a container. + *

+ * Note: This is an abstraction used for creating new port bindings. + * It is not to be confused with the abstraction used for querying existing + * port bindings from a container configuration in + * {@link NetworkSettings#getPorts()} and {@link HostConfig#getPortBindings()}. + * In that context, a Map<ExposedPort, Binding[]> is used. + */ +public class PortBinding { + private final Binding binding; + private final ExposedPort exposedPort; + + public PortBinding(Binding binding, ExposedPort exposedPort) { + this.binding = binding; + this.exposedPort = exposedPort; + } + + public Binding getBinding() { + return binding; + } + + public ExposedPort getExposedPort() { + return exposedPort; + } +} diff --git a/src/main/java/com/github/dockerjava/api/model/Ports.java b/src/main/java/com/github/dockerjava/api/model/Ports.java index a14b3103..0aaf3b44 100644 --- a/src/main/java/com/github/dockerjava/api/model/Ports.java +++ b/src/main/java/com/github/dockerjava/api/model/Ports.java @@ -28,6 +28,11 @@ /** * A container for port bindings, made available as a {@link Map} via its * {@link #getBindings()} method. + *

+ * Note: This is an abstraction used for querying existing port bindings from + * a container configuration. + * It is not to be confused with the {@link PortBinding} abstraction used for + * adding new port bindings to a container. * * @see HostConfig#getPortBindings() * @see NetworkSettings#getPorts() @@ -38,18 +43,42 @@ public class Ports { private final Map ports = new HashMap(); + /** + * Creates a {@link Ports} object with no {@link PortBinding}s. + * Use {@link #bind(ExposedPort, Binding)} or {@link #add(PortBinding...)} + * to add {@link PortBinding}s. + */ public Ports() { } + /** + * Creates a {@link Ports} object with an initial {@link PortBinding} for + * the specified {@link ExposedPort} and {@link Binding}. + * Use {@link #bind(ExposedPort, Binding)} or {@link #add(PortBinding...)} + * to add more {@link PortBinding}s. + */ public Ports(ExposedPort exposedPort, Binding host) { bind(exposedPort, host); } - public void bind(ExposedPort exposedPort, Binding host) { + /** + * Adds a new {@link PortBinding} for the specified {@link ExposedPort} and + * {@link Binding} to the current bindings. + */ + public void bind(ExposedPort exposedPort, Binding binding) { if (ports.containsKey(exposedPort)) { Binding[] bindings = ports.get(exposedPort); - ports.put(exposedPort, (Binding[]) ArrayUtils.add(bindings, host)); + ports.put(exposedPort, (Binding[]) ArrayUtils.add(bindings, binding)); } else { - ports.put(exposedPort, new Binding[]{host}); + ports.put(exposedPort, new Binding[]{binding}); + } + } + + /** + * Adds the specified {@link PortBinding}(s) to the list of {@link PortBinding}s. + */ + public void add(PortBinding... portBindings) { + for (PortBinding binding : portBindings) { + bind(binding.getExposedPort(), binding.getBinding()); } } @@ -59,6 +88,9 @@ public String toString(){ } /** + * Returns the port bindings in the format used by the Docker remote API, + * i.e. the {@link Binding}s grouped by {@link ExposedPort}. + * * @return the port bindings as a {@link Map} that contains one or more * {@link Binding}s per {@link ExposedPort}. */ @@ -75,10 +107,12 @@ public static Binding Binding(int hostPort) { /** - * The host part of a port binding. - * In a port binding a container port, expressed as an {@link ExposedPort}, - * is published as a port of the Docker host. + * A {@link Binding} represents a socket on the Docker host that is + * used in a {@link PortBinding}. + * It is characterized by an {@link #getHostIp() IP address} and a + * {@link #getHostPort() port number}. * + * @see Ports#bind(ExposedPort, Binding) * @see ExposedPort */ public static class Binding { @@ -88,7 +122,8 @@ public static class Binding { private final int hostPort; /** - * Creates the host part of a port binding. + * Creates a {@link Binding} for the given {@link #getHostIp() IP address} + * and {@link #getHostPort() port number}. * * @see Ports#bind(ExposedPort, Binding) * @see ExposedPort @@ -98,6 +133,13 @@ public Binding(String hostIp, int hostPort) { this.hostPort = hostPort; } + /** + * Creates a {@link Binding} for the given {@link #getHostPort() port number}, + * leaving the {@link #getHostIp() IP address} undefined. + * + * @see Ports#bind(ExposedPort, Binding) + * @see ExposedPort + */ public Binding(int hostPort) { this("", hostPort); } diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index 9cf83083..74fbd679 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -13,6 +13,7 @@ import com.github.dockerjava.api.model.Link; import com.github.dockerjava.api.model.Links; import com.github.dockerjava.api.model.LxcConf; +import com.github.dockerjava.api.model.PortBinding; import com.github.dockerjava.api.model.Ports; import com.github.dockerjava.api.model.RestartPolicy; import com.google.common.base.Preconditions; @@ -179,6 +180,16 @@ public StartContainerCmd withPortBindings(Ports portBindings) { return this; } + @Override + public StartContainerCmd withPortBindings(PortBinding... portBindings) { + Preconditions.checkNotNull(portBindings, "portBindings was not specified"); + if (this.portBindings == null) { + this.portBindings = new Ports(); + } + this.portBindings.add(portBindings); + return this; + } + @Override public StartContainerCmd withPrivileged(boolean privileged) { this.privileged = privileged; diff --git a/src/test/java/com/github/dockerjava/api/model/PortsTest.java b/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java similarity index 94% rename from src/test/java/com/github/dockerjava/api/model/PortsTest.java rename to src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java index 6a6c5e44..d7ab23d2 100644 --- a/src/test/java/com/github/dockerjava/api/model/PortsTest.java +++ b/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.github.dockerjava.api.model.Ports.Binding; -public class PortsTest { +public class Ports_SerializingTest { private final ObjectMapper objectMapper = new ObjectMapper(); private final String jsonWithDoubleBindingForOnePort = "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"},{\"HostIp\":\"10.0.0.2\",\"HostPort\":\"80\"}]}"; diff --git a/src/test/java/com/github/dockerjava/api/model/Ports_addBindingsTest.java b/src/test/java/com/github/dockerjava/api/model/Ports_addBindingsTest.java new file mode 100644 index 00000000..23abbdd2 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/Ports_addBindingsTest.java @@ -0,0 +1,57 @@ +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import java.util.Map; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.github.dockerjava.api.model.Ports.Binding; + +/** + * As there may be several {@link Binding}s per {@link ExposedPort}, + * it makes a difference if you add {@link PortBinding}s for the + * same or different {@link ExposedPort}s to {@link Ports}. + * This test verifies that the Map in {@link Ports} is populated + * correctly in both cases. + */ +public class Ports_addBindingsTest { + private static final ExposedPort TCP_80 = ExposedPort.tcp(80); + private static final ExposedPort TCP_90 = ExposedPort.tcp(90); + private static final Binding BINDING_8080 = Ports.Binding(8080); + private static final Binding BINDING_9090 = Ports.Binding(9090); + + private Ports ports; + + @BeforeMethod + public void setup() { + ports = new Ports(); + } + + @Test + public void addTwoBindingsForDifferentExposedPorts() { + ports.add( + new PortBinding(BINDING_8080, TCP_80), + new PortBinding(BINDING_9090, TCP_90)); + + Map bindings = ports.getBindings(); + // two keys with one value each + assertEquals(bindings.size(), 2); + assertEquals(bindings.get(TCP_80), new Binding[] { BINDING_8080 }); + assertEquals(bindings.get(TCP_90), new Binding[] { BINDING_9090 }); + } + + @Test + public void addTwoBindingsForSameExposedPort() { + ports.add( + new PortBinding(BINDING_8080, TCP_80), + new PortBinding(BINDING_9090, TCP_80)); + + Map bindings = ports.getBindings(); + // one key with two values + assertEquals(bindings.size(), 1); + assertEquals(bindings.get(TCP_80), new Binding[] { BINDING_8080, BINDING_9090 }); + } + +} From 3b14b1fa5cf35a72c150676c43ecceb196330875 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Fri, 31 Oct 2014 14:47:21 +0100 Subject: [PATCH 179/452] Allow port-only as a legal syntax for ExposedPort.parse(String) --- .../dockerjava/api/model/ExposedPort.java | 24 ++++++++++++++++--- .../dockerjava/api/model/ExposedPortTest.java | 12 ++++++++-- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/model/ExposedPort.java b/src/main/java/com/github/dockerjava/api/model/ExposedPort.java index d19bfbf0..30f7ce38 100644 --- a/src/main/java/com/github/dockerjava/api/model/ExposedPort.java +++ b/src/main/java/com/github/dockerjava/api/model/ExposedPort.java @@ -48,6 +48,16 @@ public ExposedPort(int port, InternetProtocol protocol) { this.protocol = protocol; } + /** + * Creates an {@link ExposedPort} for the given + * {@link #getPort() port number} and {@link InternetProtocol#DEFAULT}. + * + * @param port the {@link #getPort() port number} + */ + public ExposedPort(int port) { + this(port, InternetProtocol.DEFAULT); + } + /** * Creates an {@link ExposedPort} for the given parameters. * @@ -61,7 +71,8 @@ public ExposedPort(String scheme, int port) { this(port, InternetProtocol.valueOf(scheme)); } - /** @return the {@link InternetProtocol} */ + /** @return the {@link InternetProtocol} of the {@link #getPort() port} + * that the container exposes */ public InternetProtocol getProtocol() { return protocol; } @@ -75,7 +86,7 @@ public String getScheme() { return protocol.toString(); } - /** @return the port number */ + /** @return the port number that the container exposes */ public int getPort() { return port; } @@ -107,7 +118,14 @@ public static ExposedPort udp(int port) { public static ExposedPort parse(String serialized) throws IllegalArgumentException { try { String[] parts = serialized.split("/"); - return new ExposedPort(Integer.valueOf(parts[0]), InternetProtocol.parse(parts[1])); + switch (parts.length) { + case 1: + return new ExposedPort(Integer.valueOf(parts[0])); + case 2: + return new ExposedPort(Integer.valueOf(parts[0]), InternetProtocol.parse(parts[1])); + default: + throw new IllegalArgumentException(); + } } catch (Exception e) { throw new IllegalArgumentException("Error parsing ExposedPort '" + serialized + "'"); } diff --git a/src/test/java/com/github/dockerjava/api/model/ExposedPortTest.java b/src/test/java/com/github/dockerjava/api/model/ExposedPortTest.java index 052e44ff..de1d23c2 100644 --- a/src/test/java/com/github/dockerjava/api/model/ExposedPortTest.java +++ b/src/test/java/com/github/dockerjava/api/model/ExposedPortTest.java @@ -1,5 +1,7 @@ package com.github.dockerjava.api.model; +import static com.github.dockerjava.api.model.InternetProtocol.DEFAULT; +import static com.github.dockerjava.api.model.InternetProtocol.TCP; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; @@ -7,9 +9,15 @@ public class ExposedPortTest { @Test - public void parse() { + public void parsePortAndProtocol() { ExposedPort exposedPort = ExposedPort.parse("80/tcp"); - assertEquals(exposedPort.getPort(), 80); + assertEquals(exposedPort, new ExposedPort(80, TCP)); + } + + @Test + public void parsePortOnly() { + ExposedPort exposedPort = ExposedPort.parse("80"); + assertEquals(exposedPort, new ExposedPort(80, DEFAULT)); } @Test(expectedExceptions = IllegalArgumentException.class, From 0ee67be7ac04bc50ce858e9525462e4a9bc5aa34 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Fri, 31 Oct 2014 14:44:52 +0100 Subject: [PATCH 180/452] Parser for PortBinding and Binding This allows you to use textual port binding specifications in the format used by the Docker CLI in docker-java: StartContainerCmd.withPortBindings(PortBinding.parse("80:8080/tcp")); --- .../dockerjava/api/model/PortBinding.java | 47 ++++++++++++++++++ .../github/dockerjava/api/model/Ports.java | 47 +++++++++++++++++- .../dockerjava/api/model/BindingTest.java | 43 ++++++++++++++++ .../dockerjava/api/model/PortBindingTest.java | 49 +++++++++++++++++++ 4 files changed, 184 insertions(+), 2 deletions(-) create mode 100644 src/test/java/com/github/dockerjava/api/model/BindingTest.java create mode 100644 src/test/java/com/github/dockerjava/api/model/PortBindingTest.java diff --git a/src/main/java/com/github/dockerjava/api/model/PortBinding.java b/src/main/java/com/github/dockerjava/api/model/PortBinding.java index be4f5a29..df908559 100644 --- a/src/main/java/com/github/dockerjava/api/model/PortBinding.java +++ b/src/main/java/com/github/dockerjava/api/model/PortBinding.java @@ -1,5 +1,9 @@ package com.github.dockerjava.api.model; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + import com.github.dockerjava.api.command.InspectContainerResponse.HostConfig; import com.github.dockerjava.api.command.InspectContainerResponse.NetworkSettings; import com.github.dockerjava.api.model.Ports.Binding; @@ -33,4 +37,47 @@ public Binding getBinding() { public ExposedPort getExposedPort() { return exposedPort; } + + public static PortBinding parse(String serialized) throws IllegalArgumentException { + try { + String[] parts = StringUtils.splitByWholeSeparator(serialized, ":"); + switch (parts.length) { + case 3: + // 127.0.0.1:80:8080/tcp + return createFromSubstrings(parts[0] + ":" + parts[1], parts[2]); + case 2: + // 80:8080 // 127.0.0.1::8080 + return createFromSubstrings(parts[0], parts[1]); + case 1: + // 8080 + return createFromSubstrings("", parts[0]); + default: + throw new IllegalArgumentException(); + } + } catch (Exception e) { + throw new IllegalArgumentException("Error parsing PortBinding '" + + serialized + "'", e); + } + } + + private static PortBinding createFromSubstrings(String binding, String exposedPort) + throws IllegalArgumentException { + return new PortBinding(Binding.parse(binding), ExposedPort.parse(exposedPort)); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof PortBinding) { + PortBinding other = (PortBinding) obj; + return new EqualsBuilder().append(binding, other.getBinding()) + .append(exposedPort, other.getExposedPort()).isEquals(); + } else + return super.equals(obj); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(binding).append(exposedPort).toHashCode(); + } + } diff --git a/src/main/java/com/github/dockerjava/api/model/Ports.java b/src/main/java/com/github/dockerjava/api/model/Ports.java index 0aaf3b44..f483ba9d 100644 --- a/src/main/java/com/github/dockerjava/api/model/Ports.java +++ b/src/main/java/com/github/dockerjava/api/model/Ports.java @@ -1,5 +1,7 @@ package com.github.dockerjava.api.model; +import static org.apache.commons.lang.StringUtils.isEmpty; + import java.io.IOException; import java.util.HashMap; import java.util.Iterator; @@ -8,7 +10,6 @@ import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; @@ -152,9 +153,51 @@ public int getHostPort() { return hostPort; } + /** + * Parses a textual host and port specification (as used by the Docker CLI) + * to a {@link Binding}. + *

+ * Legal syntax: [IP:]Port + * + * @param serialized serialized the specification, e.g. + * 127.0.0.1:80 + * @return a {@link Binding} matching the specification + * @throws IllegalArgumentException if the specification cannot be parsed + */ + public static Binding parse(String serialized) throws IllegalArgumentException { + try { + String[] parts = serialized.split(":"); + switch (parts.length) { + case 2: { + return new Binding(parts[0], Integer.valueOf(parts[1])); + } + case 1: { + return new Binding(Integer.valueOf(parts[0])); + } + default: { + throw new IllegalArgumentException(); + } + } + } catch (Exception e) { + throw new IllegalArgumentException("Error parsing Binding '" + + serialized + "'"); + } + } + + /** + * Returns a string representation of this {@link Binding} suitable + * for inclusion in a JSON message. + * The format is [IP:]Port, like the argument in {@link #parse(String)}. + * + * @return a string representation of this {@link Binding} + */ @Override public String toString() { - return ToStringBuilder.reflectionToString(this); + if (isEmpty(hostIp)) { + return Integer.toString(hostPort); + } else { + return hostIp + ":" + hostPort; + } } @Override diff --git a/src/test/java/com/github/dockerjava/api/model/BindingTest.java b/src/test/java/com/github/dockerjava/api/model/BindingTest.java new file mode 100644 index 00000000..bfe58153 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/BindingTest.java @@ -0,0 +1,43 @@ +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.github.dockerjava.api.model.Ports.Binding; + +public class BindingTest { + + @Test + public void parseIpAndPort() { + assertEquals(Binding.parse("127.0.0.1:80"), Ports.Binding("127.0.0.1", 80)); + } + + @Test + public void parsePortOnly() { + assertEquals(Binding.parse("80"), Ports.Binding("", 80)); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Binding 'nonsense'") + public void parseInvalidInput() { + Binding.parse("nonsense"); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Binding 'null'") + public void parseNull() { + Binding.parse(null); + } + + @Test + public void toStringIpAndHost() { + assertEquals(Binding.parse("127.0.0.1:80").toString(), "127.0.0.1:80"); + } + + @Test + public void toStringPortOnly() { + assertEquals(Binding.parse("80").toString(), "80"); + } + +} diff --git a/src/test/java/com/github/dockerjava/api/model/PortBindingTest.java b/src/test/java/com/github/dockerjava/api/model/PortBindingTest.java new file mode 100644 index 00000000..21644b2c --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/PortBindingTest.java @@ -0,0 +1,49 @@ +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.github.dockerjava.api.model.Ports.Binding; + +public class PortBindingTest { + + private static final ExposedPort TCP_8080 = ExposedPort.tcp(8080); + + @Test + public void fullDefinition() { + assertEquals(PortBinding.parse("127.0.0.1:80:8080/tcp"), + new PortBinding(new Binding("127.0.0.1", 80), TCP_8080)); + } + + @Test + public void noProtocol() { + assertEquals(PortBinding.parse("127.0.0.1:80:8080"), + new PortBinding(new Binding("127.0.0.1", 80), TCP_8080)); + } + + @Test + public void noHostIp() { + assertEquals(PortBinding.parse("80:8080/tcp"), + new PortBinding(new Binding(80), TCP_8080)); + } + + @Test + public void portsOnly() { + assertEquals(PortBinding.parse("80:8080"), + new PortBinding(new Binding(80), TCP_8080)); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing PortBinding 'nonsense'") + public void parseInvalidInput() { + PortBinding.parse("nonsense"); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing PortBinding 'null'") + public void parseNull() { + PortBinding.parse(null); + } + +} From 29643a46305a4f9308c469419fda39a516dc062d Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Fri, 31 Oct 2014 13:29:36 +0100 Subject: [PATCH 181/452] Binding: Port and IP may be null In Docker API, an undefined IP address is expressed as "". This is not intuitive and should be hidden from the user. Likewise, docker-java uses 0 for an unspecified port number. This also is not intuitive, especially if you consider that 0 is a legal port number. This change makes the undefinedness explicit by using null in both cases. When serializing, "" is used instead of null. This implies changing the type of hostPort from int to Integer. --- .../github/dockerjava/api/model/Ports.java | 67 +++++++++--- .../dockerjava/api/model/BindingTest.java | 101 ++++++++++-------- .../dockerjava/api/model/PortBindingTest.java | 12 +++ .../api/model/Ports_SerializingTest.java | 5 + 4 files changed, 130 insertions(+), 55 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/model/Ports.java b/src/main/java/com/github/dockerjava/api/model/Ports.java index f483ba9d..d68175a5 100644 --- a/src/main/java/com/github/dockerjava/api/model/Ports.java +++ b/src/main/java/com/github/dockerjava/api/model/Ports.java @@ -99,10 +99,18 @@ public Map getBindings(){ return ports; } - public static Binding Binding(String hostIp, int hostPort) { + /** + * Creates a {@link Binding} for the given IP address and port number. + */ + public static Binding Binding(String hostIp, Integer hostPort) { return new Binding(hostIp, hostPort); } - public static Binding Binding(int hostPort) { + + /** + * Creates a {@link Binding} for the given port number, leaving the + * IP address undefined. + */ + public static Binding Binding(Integer hostPort) { return new Binding(hostPort); } @@ -112,6 +120,8 @@ public static Binding Binding(int hostPort) { * used in a {@link PortBinding}. * It is characterized by an {@link #getHostIp() IP address} and a * {@link #getHostPort() port number}. + * Both properties may be null in order to let Docker assign + * them dynamically/using defaults. * * @see Ports#bind(ExposedPort, Binding) * @see ExposedPort @@ -120,7 +130,7 @@ public static class Binding { private final String hostIp; - private final int hostPort; + private final Integer hostPort; /** * Creates a {@link Binding} for the given {@link #getHostIp() IP address} @@ -129,8 +139,8 @@ public static class Binding { * @see Ports#bind(ExposedPort, Binding) * @see ExposedPort */ - public Binding(String hostIp, int hostPort) { - this.hostIp = hostIp; + public Binding(String hostIp, Integer hostPort) { + this.hostIp = isEmpty(hostIp) ? null : hostIp; this.hostPort = hostPort; } @@ -141,15 +151,41 @@ public Binding(String hostIp, int hostPort) { * @see Ports#bind(ExposedPort, Binding) * @see ExposedPort */ - public Binding(int hostPort) { - this("", hostPort); + public Binding(Integer hostPort) { + this(null, hostPort); } + /** + * Creates a {@link Binding} for the given {@link #getHostIp() IP address}, + * leaving the {@link #getHostPort() port number} undefined. + */ + public Binding(String hostIp) { + this(hostIp, null); + } + + /** + * Creates a {@link Binding} with both {@link #getHostIp() IP address} and + * {@link #getHostPort() port number} undefined. + */ + public Binding() { + this(null, null); + } + + /** + * @return the IP address on the Docker host. + * May be null, in which case Docker will bind the + * port to all interfaces (0.0.0.0). + */ public String getHostIp() { return hostIp; } - public int getHostPort() { + /** + * @return the port number on the Docker host. + * May be null, in which case Docker will dynamically + * assign a port. + */ + public Integer getHostPort() { return hostPort; } @@ -157,7 +193,7 @@ public int getHostPort() { * Parses a textual host and port specification (as used by the Docker CLI) * to a {@link Binding}. *

- * Legal syntax: [IP:]Port + * Legal syntax: IP|IP:port|port * * @param serialized serialized the specification, e.g. * 127.0.0.1:80 @@ -166,13 +202,18 @@ public int getHostPort() { */ public static Binding parse(String serialized) throws IllegalArgumentException { try { + if (serialized.isEmpty()) { + return new Binding(); + } + String[] parts = serialized.split(":"); switch (parts.length) { case 2: { return new Binding(parts[0], Integer.valueOf(parts[1])); } case 1: { - return new Binding(Integer.valueOf(parts[0])); + return parts[0].contains(".") ? new Binding(parts[0]) + : new Binding(Integer.valueOf(parts[0])); } default: { throw new IllegalArgumentException(); @@ -195,6 +236,8 @@ public static Binding parse(String serialized) throws IllegalArgumentException { public String toString() { if (isEmpty(hostIp)) { return Integer.toString(hostPort); + } else if (hostPort == null) { + return hostIp; } else { return hostIp + ":" + hostPort; } @@ -249,8 +292,8 @@ public void serialize(Ports portBindings, JsonGenerator jsonGen, jsonGen.writeStartArray(); for (Binding binding : entry.getValue()) { jsonGen.writeStartObject(); - jsonGen.writeStringField("HostIp", binding.getHostIp()); - jsonGen.writeStringField("HostPort", "" + binding.getHostPort()); + jsonGen.writeStringField("HostIp", binding.getHostIp() == null ? "" : binding.getHostIp()); + jsonGen.writeStringField("HostPort", binding.getHostPort() == null ? "" : binding.getHostPort().toString()); jsonGen.writeEndObject(); } jsonGen.writeEndArray(); diff --git a/src/test/java/com/github/dockerjava/api/model/BindingTest.java b/src/test/java/com/github/dockerjava/api/model/BindingTest.java index bfe58153..bd848866 100644 --- a/src/test/java/com/github/dockerjava/api/model/BindingTest.java +++ b/src/test/java/com/github/dockerjava/api/model/BindingTest.java @@ -1,43 +1,58 @@ -package com.github.dockerjava.api.model; - -import static org.testng.Assert.assertEquals; - -import org.testng.annotations.Test; - -import com.github.dockerjava.api.model.Ports.Binding; - -public class BindingTest { - - @Test - public void parseIpAndPort() { - assertEquals(Binding.parse("127.0.0.1:80"), Ports.Binding("127.0.0.1", 80)); - } - - @Test - public void parsePortOnly() { - assertEquals(Binding.parse("80"), Ports.Binding("", 80)); - } - - @Test(expectedExceptions = IllegalArgumentException.class, - expectedExceptionsMessageRegExp = "Error parsing Binding 'nonsense'") - public void parseInvalidInput() { - Binding.parse("nonsense"); - } - - @Test(expectedExceptions = IllegalArgumentException.class, - expectedExceptionsMessageRegExp = "Error parsing Binding 'null'") - public void parseNull() { - Binding.parse(null); - } - - @Test - public void toStringIpAndHost() { - assertEquals(Binding.parse("127.0.0.1:80").toString(), "127.0.0.1:80"); - } - - @Test - public void toStringPortOnly() { - assertEquals(Binding.parse("80").toString(), "80"); - } - -} +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.github.dockerjava.api.model.Ports.Binding; + +public class BindingTest { + + @Test + public void parseIpAndPort() { + assertEquals(Binding.parse("127.0.0.1:80"), Ports.Binding("127.0.0.1", 80)); + } + + @Test + public void parsePortOnly() { + assertEquals(Binding.parse("80"), Ports.Binding(null, 80)); + } + + @Test + public void parseIPOnly() { + assertEquals(Binding.parse("127.0.0.1"), Ports.Binding("127.0.0.1", null)); + } + + @Test + public void parseEmptyString() { + assertEquals(Binding.parse(""), Ports.Binding(null, null)); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Binding 'nonsense'") + public void parseInvalidInput() { + Binding.parse("nonsense"); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Binding 'null'") + public void parseNull() { + Binding.parse(null); + } + + @Test + public void toStringIpAndHost() { + assertEquals(Binding.parse("127.0.0.1:80").toString(), "127.0.0.1:80"); + } + + @Test + public void toStringPortOnly() { + assertEquals(Binding.parse("80").toString(), "80"); + } + + @Test + public void toStringIpOnly() { + assertEquals(Binding.parse("127.0.0.1").toString(), "127.0.0.1"); + } + +} diff --git a/src/test/java/com/github/dockerjava/api/model/PortBindingTest.java b/src/test/java/com/github/dockerjava/api/model/PortBindingTest.java index 21644b2c..2aeb768f 100644 --- a/src/test/java/com/github/dockerjava/api/model/PortBindingTest.java +++ b/src/test/java/com/github/dockerjava/api/model/PortBindingTest.java @@ -34,6 +34,18 @@ public void portsOnly() { new PortBinding(new Binding(80), TCP_8080)); } + @Test + public void exposedPortOnly() { + assertEquals(PortBinding.parse("8080"), + new PortBinding(new Binding(), TCP_8080)); + } + + @Test + public void dynamicHostPort() { + assertEquals(PortBinding.parse("127.0.0.1::8080"), + new PortBinding(new Binding("127.0.0.1"), TCP_8080)); + } + @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Error parsing PortBinding 'nonsense'") public void parseInvalidInput() { diff --git a/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java b/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java index d7ab23d2..d295c881 100644 --- a/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java +++ b/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java @@ -34,4 +34,9 @@ public void serializingPortWithMultipleBindings() throws Exception { assertEquals(objectMapper.writeValueAsString(ports), jsonWithDoubleBindingForOnePort); } + @Test + public void serializingEmptyBinding() throws Exception { + Ports ports = new Ports(ExposedPort.tcp(80), new Binding(null, null)); + assertEquals(objectMapper.writeValueAsString(ports), "{\"80/tcp\":[{\"HostIp\":\"\",\"HostPort\":\"\"}]}"); + } } From 1543b0b4d807273938746dbf23a9e6533bd50dc9 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 2 Nov 2014 17:16:03 +0000 Subject: [PATCH 182/452] first draft of support for pulling and pushing from a private, authenticate repository --- README.md | 12 ++- .../dockerjava/api/command/PullImageCmd.java | 12 ++- .../dockerjava/api/model/AuthConfig.java | 13 +++- .../dockerjava/core/DockerClientConfig.java | 25 ++++++- .../dockerjava/core/DockerClientImpl.java | 4 +- .../core/command/PullImageCmdImpl.java | 20 ++++- .../dockerjava/jaxrs/PullImageCmdExec.java | 26 ++++--- src/main/resources/docker.io.properties | 4 +- .../dockerjava/api/model/AuthConfigTest.java | 31 ++++++++ .../dockerjava/api/model/PortsTest.java | 73 +++++++++---------- .../core/DockerClientConfigTest.java | 10 ++- .../dockerjava/core/DockerClientImplTest.java | 36 +++++++++ .../core/command/PullImageCmdImplTest.java | 48 +++++++----- .../core/command/PushImageCmdImplTest.java | 23 ++---- 14 files changed, 239 insertions(+), 98 deletions(-) create mode 100644 src/test/java/com/github/dockerjava/api/model/AuthConfigTest.java create mode 100644 src/test/java/com/github/dockerjava/core/DockerClientImplTest.java diff --git a/README.md b/README.md index 8eff82a2..3b04aa02 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,11 @@ Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/ * Java 1.6 * Maven 3.0.5 * Docker daemon running +* Docker private repository running (see below). + +You'll need to be running a local private registry, as per [the quick start instructions](https://github.com/docker/docker-registry): + + docker run -p 5000:5000 registry The Maven build includes integration tests which are using a localhost instance of Docker and require manual setup. Make sure you have a local Docker daemon running and then provide your https://registry.hub.docker.com/account/login/ information via system properties: @@ -56,7 +61,7 @@ Run build without integration tests: com.github.docker-java docker-java - 0.10.2 + RELEASE ### Latest SNAPSHOT version @@ -64,7 +69,7 @@ Run build without integration tests: com.github.docker-java docker-java - 0.10.3-SNAPSHOT + LATEST Latest SNAPSHOT is published to maven repo: https://oss.sonatype.org/content/groups/public via ![Build on CloudBees](http://cloudbees.prod.acquia-sites.com/sites/default/files/styles/large/public/Button-Powered-by-CB.png?itok=uMDWINfY) @@ -82,6 +87,7 @@ There are a couple of configuration items, all of which have sensible defaults: * `username` Your repository username (required to push containers). * `password` Your repository password. * `email` Your repository email. +* `serverAddress` Your repository's address. * `dockerCertPath` Path to the docker certs. There are three ways to configure, in descending order of precedence: @@ -95,6 +101,7 @@ In your application, e.g. .withUsername("dockeruser") .withPassword("ilovedocker") .withEmail("dockeruser@github.com") + .withServerAddress("https://index.docker.io/v1/") .withDockerCertPath("/home/user/.docker") .build(); DockerClient docker = DockerClientBuilder.getInstance(config).build(); @@ -106,6 +113,7 @@ In your application, e.g. docker.io.username=dockeruser docker.io.password=ilovedocker docker.io.email=dockeruser@github.com + docker.io.serverAddress=https://index.docker.io/v1/ docker.io.dockerCertPath=/home/user/.docker diff --git a/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java b/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java index f938542d..27d5b978 100644 --- a/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java @@ -1,5 +1,7 @@ package com.github.dockerjava.api.command; +import com.github.dockerjava.api.model.AuthConfig; + import java.io.InputStream; /** @@ -15,13 +17,17 @@ public interface PullImageCmd extends DockerCmd{ public String getRegistry(); - public PullImageCmd withRepository(String repository); + public AuthConfig getAuthConfig(); + + public PullImageCmd withRepository(String repository); public PullImageCmd withTag(String tag); public PullImageCmd withRegistry(String registry); - - public static interface Exec extends DockerCmdExec { + + public PullImageCmd withAuthConfig(AuthConfig authConfig); + + public static interface Exec extends DockerCmdExec { } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/model/AuthConfig.java b/src/main/java/com/github/dockerjava/api/model/AuthConfig.java index 7212d823..d7f0deab 100644 --- a/src/main/java/com/github/dockerjava/api/model/AuthConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/AuthConfig.java @@ -3,8 +3,15 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class AuthConfig { - - @JsonProperty + + /** + * For backwards compatibility. Make sure you update the properties if you change this. + * + * @see /docker.io.properties + */ + public static final String DEFAULT_SERVER_ADDRESS = "https://index.docker.io/v1/"; + + @JsonProperty private String username; @JsonProperty @@ -14,7 +21,7 @@ public class AuthConfig { private String email; @JsonProperty("serveraddress") - private String serverAddress = "https://index.docker.io/v1/"; + private String serverAddress = DEFAULT_SERVER_ADDRESS; public String getUsername() { return username; diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index c12585a5..9f1694b5 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -18,6 +18,7 @@ public class DockerClientConfig { private static final String DOCKER_IO_USERNAME_PROPERTY = "docker.io.username"; private static final String DOCKER_IO_PASSWORD_PROPERTY = "docker.io.password"; private static final String DOCKER_IO_EMAIL_PROPERTY = "docker.io.email"; + private static final String DOCKER_IO_SERVER_ADDRESS_PROPERTY = "docker.io.serverAddress"; private static final String DOCKER_IO_READ_TIMEOUT_PROPERTY = "docker.io.readTimeout"; // this is really confusing, as there are two ways to spell it private static final String DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY = "docker.io.enableLoggingFilter"; @@ -31,22 +32,24 @@ public class DockerClientConfig { .put("DOCKER_USERNAME", DOCKER_IO_USERNAME_PROPERTY) .put("DOCKER_PASSWORD", DOCKER_IO_PASSWORD_PROPERTY) .put("DOCKER_EMAIL", DOCKER_IO_EMAIL_PROPERTY) + .put("DOCKER_SERVER_ADDRESS", DOCKER_IO_SERVER_ADDRESS_PROPERTY) .put("DOCKER_READ_TIMEOUT", DOCKER_IO_READ_TIMEOUT_PROPERTY) .put("DOCKER_LOGGING_FILTER_ENABLED", DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY) .put(DOCKER_CERT_PATH_PROPERTY, DOCKER_IO_DOCKER_CERT_PATH_PROPERTY) .build(); private static final String DOCKER_IO_PROPERTIES_PROPERTY = "docker.io.properties"; private final URI uri; - private final String version, username, password, email, dockerCertPath; + private final String version, username, password, email, serverAddress, dockerCertPath; private final Integer readTimeout; private final boolean loggingFilterEnabled; - DockerClientConfig(URI uri, String version, String username, String password, String email, String dockerCertPath, Integer readTimeout, boolean loggingFilterEnabled) { + DockerClientConfig(URI uri, String version, String username, String password, String email, String serverAddress, String dockerCertPath, Integer readTimeout, boolean loggingFilterEnabled) { this.uri = uri; this.version = version; this.username = username; this.password = password; this.email = email; + this.serverAddress = serverAddress; this.dockerCertPath = dockerCertPath; this.readTimeout = readTimeout; this.loggingFilterEnabled = loggingFilterEnabled; @@ -146,6 +149,7 @@ private static Properties overrideDockerPropertiesWithSystemProperties(Propertie DOCKER_IO_USERNAME_PROPERTY, DOCKER_IO_PASSWORD_PROPERTY, DOCKER_IO_EMAIL_PROPERTY, + DOCKER_IO_SERVER_ADDRESS_PROPERTY, DOCKER_IO_READ_TIMEOUT_PROPERTY, DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY, DOCKER_IO_DOCKER_CERT_PATH_PROPERTY, @@ -192,6 +196,10 @@ public String getEmail() { return email; } + public String getServerAddress() { + return serverAddress; + } + public Integer getReadTimeout() { return readTimeout; } @@ -217,6 +225,8 @@ public boolean equals(Object o) { if (email != null ? !email.equals(that.email) : that.email != null) return false; if (password != null ? !password.equals(that.password) : that.password != null) return false; if (readTimeout != null ? !readTimeout.equals(that.readTimeout) : that.readTimeout != null) return false; + if (serverAddress != null ? !serverAddress.equals(that.serverAddress) : that.serverAddress != null) + return false; if (uri != null ? !uri.equals(that.uri) : that.uri != null) return false; if (username != null ? !username.equals(that.username) : that.username != null) return false; if (version != null ? !version.equals(that.version) : that.version != null) return false; @@ -231,6 +241,7 @@ public int hashCode() { result = 31 * result + (username != null ? username.hashCode() : 0); result = 31 * result + (password != null ? password.hashCode() : 0); result = 31 * result + (email != null ? email.hashCode() : 0); + result = 31 * result + (serverAddress != null ? serverAddress.hashCode() : 0); result = 31 * result + (dockerCertPath != null ? dockerCertPath.hashCode() : 0); result = 31 * result + (readTimeout != null ? readTimeout.hashCode() : 0); result = 31 * result + (loggingFilterEnabled ? 1 : 0); @@ -245,6 +256,7 @@ public String toString() { ", username='" + username + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + + ", serverAddress='" + serverAddress + '\'' + ", dockerCertPath='" + dockerCertPath + '\'' + ", readTimeout=" + readTimeout + ", loggingFilterEnabled=" + loggingFilterEnabled + @@ -253,7 +265,7 @@ public String toString() { public static class DockerClientConfigBuilder { private URI uri; - private String version, username, password, email, dockerCertPath; + private String version, username, password, email, serverAddress, dockerCertPath; private Integer readTimeout; private boolean loggingFilterEnabled; @@ -269,6 +281,7 @@ public DockerClientConfigBuilder withProperties(Properties p) { .withUsername(p.getProperty(DOCKER_IO_USERNAME_PROPERTY)) .withPassword(p.getProperty(DOCKER_IO_PASSWORD_PROPERTY)) .withEmail(p.getProperty(DOCKER_IO_EMAIL_PROPERTY)) + .withServerAddress(p.getProperty(DOCKER_IO_SERVER_ADDRESS_PROPERTY)) .withReadTimeout(Integer.valueOf(p.getProperty(DOCKER_IO_READ_TIMEOUT_PROPERTY, "0"))) .withLoggingFilter(Boolean.valueOf(p.getProperty(DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY, "true"))) .withDockerCertPath(p.getProperty(DOCKER_IO_DOCKER_CERT_PATH_PROPERTY)); @@ -300,6 +313,11 @@ public final DockerClientConfigBuilder withEmail(String email) { return this; } + public DockerClientConfigBuilder withServerAddress(String serverAddress) { + this.serverAddress = serverAddress; + return this; + } + public final DockerClientConfigBuilder withReadTimeout(Integer readTimeout) { this.readTimeout = readTimeout; return this; @@ -322,6 +340,7 @@ public DockerClientConfig build() { username, password, email, + serverAddress, dockerCertPath, readTimeout, loggingFilterEnabled diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 5dfb4c13..4d88651e 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -73,12 +73,14 @@ public AuthConfig authConfig() { checkNotNull(dockerClientConfig.getUsername(), "Configured username is null."); checkNotNull(dockerClientConfig.getPassword(), "Configured password is null."); checkNotNull(dockerClientConfig.getEmail(), "Configured email is null."); + checkNotNull(dockerClientConfig.getServerAddress(), "Configured serverAddress is null."); AuthConfig authConfig = new AuthConfig(); authConfig.setUsername(dockerClientConfig.getUsername()); authConfig.setPassword(dockerClientConfig.getPassword()); authConfig.setEmail(dockerClientConfig.getEmail()); - // TODO Make the registry address configurable + authConfig.setServerAddress(dockerClientConfig.getServerAddress()); + return authConfig; } diff --git a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java index b0ec0251..ed045878 100644 --- a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java @@ -1,11 +1,11 @@ package com.github.dockerjava.core.command; -import java.io.InputStream; - import com.github.dockerjava.api.command.PullImageCmd; - +import com.github.dockerjava.api.model.AuthConfig; import com.google.common.base.Preconditions; +import java.io.InputStream; + /** * * Pull image from repository. @@ -13,7 +13,8 @@ */ public class PullImageCmdImpl extends AbstrDockerCmd implements PullImageCmd { - private String repository, tag, registry; + private String repository, tag, registry; + private AuthConfig authConfig; public PullImageCmdImpl(PullImageCmd.Exec exec, String repository) { super(exec); @@ -35,6 +36,10 @@ public String getRegistry() { return registry; } + public AuthConfig getAuthConfig() { + return authConfig; + } + @Override public PullImageCmd withRepository(String repository) { Preconditions.checkNotNull(repository, "repository was not specified"); @@ -56,6 +61,13 @@ public PullImageCmd withRegistry(String registry) { return this; } + @Override + public PullImageCmd withAuthConfig(AuthConfig authConfig) { + Preconditions.checkNotNull(authConfig, "authConfig was not specified"); + this.authConfig = authConfig; + return this; + } + @Override public String toString() { return new StringBuilder("pull ") diff --git a/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java index 4ac190be..dea72f42 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java @@ -1,17 +1,17 @@ package com.github.dockerjava.jaxrs; -import static javax.ws.rs.client.Entity.entity; - -import java.io.InputStream; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.model.AuthConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import java.io.InputStream; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.command.PullImageCmd; +import static javax.ws.rs.client.Entity.entity; public class PullImageCmdExec extends AbstrDockerCmdExec implements PullImageCmd.Exec { @@ -27,11 +27,19 @@ protected InputStream execute(PullImageCmd command) { .queryParam("tag", command.getTag()) .queryParam("fromImage", command.getRepository()) .queryParam("registry", command.getRegistry()); - + LOGGER.trace("POST: {}", webResource); - return webResource.request() + return resourceWithOptionalAuthConfig(command, webResource.request()) .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) .post(entity(Response.class, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); } + private Invocation.Builder resourceWithOptionalAuthConfig(PullImageCmd command, Invocation.Builder request) { + AuthConfig authConfig = command.getAuthConfig(); + if (authConfig != null) { + request = request.header("X-Registry-Auth", registryAuth(authConfig)); + } + return request; + } + } diff --git a/src/main/resources/docker.io.properties b/src/main/resources/docker.io.properties index f4d69953..3d9c7149 100644 --- a/src/main/resources/docker.io.properties +++ b/src/main/resources/docker.io.properties @@ -1,4 +1,6 @@ docker.io.url=https://localhost:2376 docker.io.version=1.15 docker.io.enableLoggingFilter=true -docker.io.dockerCertPath=${user.home}/.docker \ No newline at end of file +docker.io.dockerCertPath=${user.home}/.docker +docker.io.username=${user.name} +docker.io.serverAddress=https://index.docker.io/v1/ \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/api/model/AuthConfigTest.java b/src/test/java/com/github/dockerjava/api/model/AuthConfigTest.java new file mode 100644 index 00000000..1ed618ed --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/AuthConfigTest.java @@ -0,0 +1,31 @@ +package com.github.dockerjava.api.model; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertEquals; + +public class AuthConfigTest { + + private AuthConfig authConfig; + + @BeforeMethod + public void setUp() throws Exception { + authConfig = new AuthConfig(); + authConfig.setEmail("foo"); + authConfig.setPassword("bar"); + authConfig.setServerAddress("baz"); + authConfig.setUsername("qux"); + } + + @Test + public void string() throws Exception { + assertEquals(authConfig.toString(), + "AuthConfig{username='qux', password='bar', email='foo', serverAddress='baz'}"); + } + + @Test + public void defaultServerAddress() throws Exception { + assertEquals(new AuthConfig().getServerAddress(), "https://index.docker.io/v1/"); + } +} \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/api/model/PortsTest.java b/src/test/java/com/github/dockerjava/api/model/PortsTest.java index 6a6c5e44..dea43aa7 100644 --- a/src/test/java/com/github/dockerjava/api/model/PortsTest.java +++ b/src/test/java/com/github/dockerjava/api/model/PortsTest.java @@ -1,37 +1,36 @@ -package com.github.dockerjava.api.model; - -import static org.testng.Assert.assertEquals; - -import java.util.Map; - -import org.testng.annotations.Test; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.dockerjava.api.model.Ports.Binding; - -public class PortsTest { - private final ObjectMapper objectMapper = new ObjectMapper(); - private final String jsonWithDoubleBindingForOnePort = - "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"},{\"HostIp\":\"10.0.0.2\",\"HostPort\":\"80\"}]}"; - - @Test - public void deserializingPortWithMultipleBindings() throws Exception { - Ports ports = objectMapper.readValue(jsonWithDoubleBindingForOnePort, Ports.class); - Map map = ports.getBindings(); - assertEquals(map.size(), 1); - - Binding[] bindings = map.get(ExposedPort.tcp(80)); - assertEquals(bindings.length, 2); - assertEquals(bindings[0], new Binding("10.0.0.1", 80)); - assertEquals(bindings[1], new Binding("10.0.0.2", 80)); - } - - @Test - public void serializingPortWithMultipleBindings() throws Exception { - Ports ports = new Ports(); - ports.bind(ExposedPort.tcp(80), new Binding("10.0.0.1", 80)); - ports.bind(ExposedPort.tcp(80), new Binding("10.0.0.2", 80)); - assertEquals(objectMapper.writeValueAsString(ports), jsonWithDoubleBindingForOnePort); - } - -} +package com.github.dockerjava.api.model; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.model.Ports.Binding; +import org.testng.annotations.Test; + +import java.util.Map; + +import static org.testng.Assert.assertEquals; + +public class PortsTest { + private final ObjectMapper objectMapper = new ObjectMapper(); + private final String jsonWithDoubleBindingForOnePort = + "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"},{\"HostIp\":\"10.0.0.2\",\"HostPort\":\"80\"}]}"; + + @Test + public void deserializingPortWithMultipleBindings() throws Exception { + Ports ports = objectMapper.readValue(jsonWithDoubleBindingForOnePort, Ports.class); + Map map = ports.getBindings(); + assertEquals(map.size(), 1); + + Binding[] bindings = map.get(ExposedPort.tcp(80)); + assertEquals(bindings.length, 2); + assertEquals(bindings[0], new Binding("10.0.0.1", 80)); + assertEquals(bindings[1], new Binding("10.0.0.2", 80)); + } + + @Test + public void serializingPortWithMultipleBindings() throws Exception { + Ports ports = new Ports(); + ports.bind(ExposedPort.tcp(80), new Binding("10.0.0.1", 80)); + ports.bind(ExposedPort.tcp(80), new Binding("10.0.0.2", 80)); + assertEquals(objectMapper.writeValueAsString(ports), jsonWithDoubleBindingForOnePort); + } + +} diff --git a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java index b0747e68..b05d8c6b 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java @@ -1,5 +1,6 @@ package com.github.dockerjava.core; +import com.github.dockerjava.api.model.AuthConfig; import org.testng.annotations.Test; import java.net.URI; @@ -15,12 +16,12 @@ public class DockerClientConfigTest { public static final DockerClientConfig EXAMPLE_CONFIG = newExampleConfig(); private static DockerClientConfig newExampleConfig() { - return new DockerClientConfig(URI.create("http://foo"), "bar", "baz", "qux", "blam", "flim", 877, false); + return new DockerClientConfig(URI.create("http://foo"), "bar", "baz", "qux", "blam", "wham", "flim", 877, false); } @Test public void string() throws Exception { - assertEquals("DockerClientConfig{uri=http://foo, version='bar', username='baz', password='qux', email='blam', dockerCertPath='flim', readTimeout=877, loggingFilterEnabled=false}", + assertEquals("DockerClientConfig{uri=http://foo, version='bar', username='baz', password='qux', email='blam', serverAddress='wham', dockerCertPath='flim', readTimeout=877, loggingFilterEnabled=false}", EXAMPLE_CONFIG.toString()); } @@ -69,6 +70,7 @@ public void environment() throws Exception { env.put("DOCKER_USERNAME", "baz"); env.put("DOCKER_PASSWORD", "qux"); env.put("DOCKER_EMAIL", "blam"); + env.put("DOCKER_SERVER_ADDRESS", "wham"); env.put("DOCKER_CERT_PATH", "flim"); env.put("DOCKER_READ_TIMEOUT", "877"); env.put("DOCKER_LOGGING_FILTER_ENABLED", "false"); @@ -89,6 +91,7 @@ public void defaults() throws Exception { // given default cert path Properties systemProperties = new Properties(); + systemProperties.setProperty("user.name", "someUserName"); systemProperties.setProperty("user.home", "someHomeDir"); // when you build config @@ -96,6 +99,8 @@ public void defaults() throws Exception { // then the cert path is as expected assertEquals(config.getUri(), URI.create("https://localhost:2376")); + assertEquals(config.getUsername(), "someUserName"); + assertEquals(config.getServerAddress(), AuthConfig.DEFAULT_SERVER_ADDRESS); assertEquals(config.getVersion(), "1.15"); assertEquals(config.isLoggingFilterEnabled(), true); assertEquals(config.getDockerCertPath(), "someHomeDir/.docker"); @@ -111,6 +116,7 @@ public void systemProperties() throws Exception { systemProperties.setProperty("docker.io.username", "baz"); systemProperties.setProperty("docker.io.password", "qux"); systemProperties.setProperty("docker.io.email", "blam"); + systemProperties.setProperty("docker.io.serverAddress", "wham"); systemProperties.setProperty("docker.io.dockerCertPath", "flim"); systemProperties.setProperty("docker.io.readTimeout", "877"); systemProperties.setProperty("docker.io.enableLoggingFilter", "false"); diff --git a/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java b/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java new file mode 100644 index 00000000..da1d7f8e --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java @@ -0,0 +1,36 @@ +package com.github.dockerjava.core; + +import org.testng.annotations.Test; + +import static org.testng.Assert.assertEquals; +import static org.testng.AssertJUnit.fail; + +public class DockerClientImplTest { + + @Test + public void configuredInstanceAuthConfig() throws Exception { + // given a config with null serverAddress + DockerClientConfig dockerClientConfig = new DockerClientConfig(null, null, "", "", "", null, null, 0, false); + DockerClientImpl dockerClient = DockerClientImpl.getInstance(dockerClientConfig); + + // when we get the auth config + try { + dockerClient.authConfig(); + fail(); + } catch (NullPointerException e) { + // then we get a NPE with expected message + assertEquals(e.getMessage(), "Configured serverAddress is null."); + } + } + + @Test + public void defaultInstanceAuthConfig() throws Exception { + // given a default client + DockerClientImpl dockerClient = DockerClientImpl.getInstance(); + + // when we get the auth config + dockerClient.authConfig(); + + // then we do not get an exception + } +} \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java index 84af9e72..461bf694 100644 --- a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java @@ -1,32 +1,33 @@ package com.github.dockerjava.core.command; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.hamcrest.Matchers.notNullValue; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Method; - -import org.testng.ITestResult; -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 com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.InternalServerErrorException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.InspectImageResponse; +import com.github.dockerjava.api.command.PullImageCmd; import com.github.dockerjava.api.model.Info; import com.github.dockerjava.client.AbstractDockerClientTest; +import org.testng.ITestResult; +import org.testng.annotations.*; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; @Test(groups = "integration") public class PullImageCmdImplTest extends AbstractDockerClientTest { - @BeforeTest + private static final PullImageCmd.Exec NOP_EXEC = new PullImageCmd.Exec() { + @Override + public InputStream exec(PullImageCmd command) { + return null; + } + }; + + @BeforeTest public void beforeTest() throws DockerException { super.beforeTest(); } @@ -46,7 +47,18 @@ public void afterMethod(ITestResult result) { super.afterMethod(result); } - @Test + @Test + public void nullAuthConfig() throws Exception { + PullImageCmdImpl pullImageCmd = new PullImageCmdImpl(NOP_EXEC, ""); + try { + pullImageCmd.withAuthConfig(null); + fail(); + } catch (Exception e) { + assertEquals(e.getMessage(), "authConfig was not specified"); + } + } + + @Test public void testPullImage() throws DockerException, IOException { Info info = dockerClient.infoCmd().exec(); LOG.info("Client info: {}", info.toString()); diff --git a/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java index b12ac4ec..e64aaa7b 100644 --- a/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java @@ -1,24 +1,17 @@ package com.github.dockerjava.core.command; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.isEmptyString; -import static org.hamcrest.Matchers.not; - -import java.lang.reflect.Method; - +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.client.AbstractDockerClientTest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; -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 org.testng.annotations.*; -import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.api.command.CreateContainerResponse; -import com.github.dockerjava.client.AbstractDockerClientTest; +import java.lang.reflect.Method; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; @Test(groups = "integration") public class PushImageCmdImplTest extends AbstractDockerClientTest { From 60dee43ad1f03baaf846048e7b14dccac204092d Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 2 Nov 2014 19:39:40 +0000 Subject: [PATCH 183/452] AuthCmd now returns AuthResponse so you can tell if you need to authorise you newly registered account --- README.md | 14 ++++++--- .../dockerjava/api/command/AuthCmd.java | 14 ++++++--- .../dockerjava/api/model/AuthResponse.java | 12 +++++++ .../dockerjava/core/command/AuthCmdImpl.java | 9 +++--- .../github/dockerjava/jaxrs/AuthCmdExec.java | 26 +++++++++------- .../client/AbstractDockerClientTest.java | 31 ++++++++++++------- .../core/command/AuthCmdImplTest.java | 24 +++++++------- 7 files changed, 83 insertions(+), 47 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/AuthResponse.java diff --git a/README.md b/README.md index 3b04aa02..38cd47fb 100644 --- a/README.md +++ b/README.md @@ -19,13 +19,19 @@ Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/ You'll need to be running a local private registry, as per [the quick start instructions](https://github.com/docker/docker-registry): - docker run -p 5000:5000 registry + $ docker run -p 5000:5000 registry + + If you're using boot2docker, set-up a port forward: + + $ VBoxManage controlvm boot2docker-vm natpf1 "5000,tcp,127.0.0.1,5000,,5000" + +You can remove this forward later using: + + $ VBoxManage controlvm boot2docker-vm natpf1 delete 5000 The Maven build includes integration tests which are using a localhost instance of Docker and require manual setup. Make sure you have a local Docker daemon running and then provide your https://registry.hub.docker.com/account/login/ information via system properties: - $ mvn clean install -Ddocker.io.username=... -Ddocker.io.password=... -Ddocker.io.email=... - -_If your Docker server is remote, add its URL like this: `-Ddocker.io.url=https://...:2376`._ + $ mvn clean install If you do not have access to a Docker server or just want to execute the build quickly, you can run the build without the integration tests: diff --git a/src/main/java/com/github/dockerjava/api/command/AuthCmd.java b/src/main/java/com/github/dockerjava/api/command/AuthCmd.java index f71a132b..3c592258 100644 --- a/src/main/java/com/github/dockerjava/api/command/AuthCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/AuthCmd.java @@ -2,22 +2,28 @@ import com.github.dockerjava.api.UnauthorizedException; import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.AuthResponse; /** * * Authenticate with the server, useful for checking authentication. * */ -public interface AuthCmd extends DockerCmd { +public interface AuthCmd extends DockerCmd { public AuthConfig getAuthConfig(); public AuthCmd withAuthConfig(AuthConfig authConfig); - + + /** + * @return The status. Based on it's value you may mean you need to authorise your account, e.g.: + * "Account created. Please see the documentation of the registry http://localhost:5000/v1/ for instructions how to activate it." + * @throws UnauthorizedException If you're not authorised (e.g. bad password). + */ @Override - public Void exec() throws UnauthorizedException; + public AuthResponse exec() throws UnauthorizedException; - public static interface Exec extends DockerCmdExec { + public static interface Exec extends DockerCmdExec { } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/model/AuthResponse.java b/src/main/java/com/github/dockerjava/api/model/AuthResponse.java new file mode 100644 index 00000000..cb5d9df8 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/AuthResponse.java @@ -0,0 +1,12 @@ +package com.github.dockerjava.api.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class AuthResponse { + @JsonProperty("Status") + private String status; + + public String getStatus() { + return status; + } +} diff --git a/src/main/java/com/github/dockerjava/core/command/AuthCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/AuthCmdImpl.java index 259333e5..0da0da3c 100644 --- a/src/main/java/com/github/dockerjava/core/command/AuthCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/AuthCmdImpl.java @@ -3,24 +3,25 @@ import com.github.dockerjava.api.UnauthorizedException; import com.github.dockerjava.api.command.AuthCmd; import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.AuthResponse; /** * * Authenticate with the server, useful for checking authentication. * */ -public class AuthCmdImpl extends AbstrAuthCfgDockerCmd implements AuthCmd { +public class AuthCmdImpl extends AbstrAuthCfgDockerCmd implements AuthCmd { public AuthCmdImpl(AuthCmd.Exec exec, AuthConfig authConfig) { super(exec); withAuthConfig(authConfig); } - + @Override - public Void exec() throws UnauthorizedException { + public AuthResponse exec() throws UnauthorizedException { return super.exec(); } - + @Override public String toString() { return "authenticate using " + this.getAuthConfig(); diff --git a/src/main/java/com/github/dockerjava/jaxrs/AuthCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AuthCmdExec.java index d73487bb..3552d974 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/AuthCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/AuthCmdExec.java @@ -1,18 +1,18 @@ package com.github.dockerjava.jaxrs; -import static javax.ws.rs.client.Entity.entity; +import com.github.dockerjava.api.UnauthorizedException; +import com.github.dockerjava.api.command.AuthCmd; +import com.github.dockerjava.api.model.AuthResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.github.dockerjava.api.UnauthorizedException; -import com.github.dockerjava.api.command.AuthCmd; +import static javax.ws.rs.client.Entity.entity; -public class AuthCmdExec extends AbstrDockerCmdExec implements AuthCmd.Exec { +public class AuthCmdExec extends AbstrDockerCmdExec implements AuthCmd.Exec { private static final Logger LOGGER = LoggerFactory .getLogger(AuthCmdExec.class); @@ -22,16 +22,18 @@ public AuthCmdExec(WebTarget baseResource) { } @Override - protected Void execute(AuthCmd command) { + protected AuthResponse execute(AuthCmd command) { WebTarget webResource = getBaseResource().path("/auth"); LOGGER.trace("POST: {}", webResource); - Response response = webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command.getAuthConfig(), MediaType.APPLICATION_JSON)); + Response response = webResource + .request() + .accept(MediaType.APPLICATION_JSON).post(entity(command.getAuthConfig(), MediaType.APPLICATION_JSON)); if(response.getStatus() == 401) { throw new UnauthorizedException("Unauthorized"); - }; - - return null; + } + + return response.readEntity(AuthResponse.class); } } diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 385508b6..91d0c907 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -1,12 +1,10 @@ package com.github.dockerjava.client; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.net.DatagramSocket; -import java.net.ServerSocket; - +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.core.DockerClientBuilder; +import com.github.dockerjava.core.DockerClientConfig; +import com.github.dockerjava.core.TestDockerCmdExecFactory; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.slf4j.Logger; @@ -14,10 +12,12 @@ import org.testng.Assert; import org.testng.ITestResult; -import com.github.dockerjava.api.DockerClient; -import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.core.DockerClientBuilder; -import com.github.dockerjava.core.TestDockerCmdExecFactory; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.net.DatagramSocket; +import java.net.ServerSocket; public abstract class AbstractDockerClientTest extends Assert { @@ -31,7 +31,14 @@ public abstract class AbstractDockerClientTest extends Assert { public void beforeTest() { LOG.info("======================= BEFORETEST ======================="); LOG.info("Connecting to Docker server"); - dockerClient = DockerClientBuilder.getInstance() + dockerClient = DockerClientBuilder.getInstance( + DockerClientConfig.createDefaultConfigBuilder() + .withServerAddress("http://localhost:5000") + .withUsername("docker-java") + .withPassword("docker-java") + .withEmail("docker-java@github.com") + .build() + ) .withDockerCmdExecFactory(dockerCmdExecFactory) .build(); diff --git a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java index 3c03b1b4..79834281 100644 --- a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java @@ -1,20 +1,20 @@ package com.github.dockerjava.core.command; -import java.lang.reflect.Method; - -import org.testng.ITestResult; -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 com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.UnauthorizedException; +import com.github.dockerjava.api.model.AuthResponse; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.core.DockerClientBuilder; import com.github.dockerjava.core.DockerClientConfig; +import org.testng.ITestResult; +import org.testng.annotations.*; + +import java.lang.reflect.Method; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.StringContains.containsString; @Test(groups = "integration") public class AuthCmdImplTest extends AbstractDockerClientTest { @@ -41,8 +41,10 @@ public void afterMethod(ITestResult result) { @Test public void testAuth() throws Exception { - dockerClient.authCmd().exec(); - } + AuthResponse response = dockerClient.authCmd().exec(); + + assertThat(response.getStatus(), not(containsString("Account created"))); + } @Test public void testAuthInvalid() throws Exception { From f4d347600f0570d0cd780686c567f1c6cbc35018 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 2 Nov 2014 23:04:54 +0000 Subject: [PATCH 184/452] create a private authenticated local repository --- README.md | 12 +---- build-docker-registry.sh | 5 +++ docker-auth-registry/Dockerfile | 17 +++++++ docker-auth-registry/README.md | 8 ++++ docker-auth-registry/build.sh | 8 ++++ docker-auth-registry/docker-registry.conf | 5 +++ docker-auth-registry/docker-registry.htpasswd | 1 + docker-auth-registry/nginx.conf | 44 +++++++++++++++++++ docker-auth-registry/run.sh | 6 +++ docker-auth-registry/start.sh | 8 ++++ docker-auth-registry/test.sh | 6 +++ .../client/AbstractDockerClientTest.java | 24 ++++++---- .../core/command/AuthCmdImplTest.java | 18 +++----- 13 files changed, 129 insertions(+), 33 deletions(-) create mode 100644 build-docker-registry.sh create mode 100644 docker-auth-registry/Dockerfile create mode 100644 docker-auth-registry/README.md create mode 100755 docker-auth-registry/build.sh create mode 100644 docker-auth-registry/docker-registry.conf create mode 100644 docker-auth-registry/docker-registry.htpasswd create mode 100644 docker-auth-registry/nginx.conf create mode 100755 docker-auth-registry/run.sh create mode 100755 docker-auth-registry/start.sh create mode 100755 docker-auth-registry/test.sh diff --git a/README.md b/README.md index 38cd47fb..26c148c8 100644 --- a/README.md +++ b/README.md @@ -17,17 +17,7 @@ Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/ * Docker daemon running * Docker private repository running (see below). -You'll need to be running a local private registry, as per [the quick start instructions](https://github.com/docker/docker-registry): - - $ docker run -p 5000:5000 registry - - If you're using boot2docker, set-up a port forward: - - $ VBoxManage controlvm boot2docker-vm natpf1 "5000,tcp,127.0.0.1,5000,,5000" - -You can remove this forward later using: - - $ VBoxManage controlvm boot2docker-vm natpf1 delete 5000 +You'll need to be running a local private registry, as per [these instructions](docker-auth-registry/README.md): The Maven build includes integration tests which are using a localhost instance of Docker and require manual setup. Make sure you have a local Docker daemon running and then provide your https://registry.hub.docker.com/account/login/ information via system properties: diff --git a/build-docker-registry.sh b/build-docker-registry.sh new file mode 100644 index 00000000..56884517 --- /dev/null +++ b/build-docker-registry.sh @@ -0,0 +1,5 @@ +#! /bin/sh +set -eux + +git clone https://github.com/docker/docker-registry +cp docker-registry/contrib/nginx/nginx_1–3–9.conf /etc/nginx/conf.d/ \ No newline at end of file diff --git a/docker-auth-registry/Dockerfile b/docker-auth-registry/Dockerfile new file mode 100644 index 00000000..4a663bc0 --- /dev/null +++ b/docker-auth-registry/Dockerfile @@ -0,0 +1,17 @@ +# https://medium.com/@deeeet/building-private-docker-registry-with-basic-authentication-with-self-signed-certificate-using-it-e6329085e612 + +FROM registry + +RUN apt-get update +RUN apt-get install -y nginx + +ADD nginx.conf /etc/nginx/ +ADD docker-registry.conf /etc/nginx/ + +ADD docker-registry.htpasswd /etc/nginx/ + +EXPOSE 5001 + +ADD start.sh . + +CMD ./start.sh diff --git a/docker-auth-registry/README.md b/docker-auth-registry/README.md new file mode 100644 index 00000000..86a6bca0 --- /dev/null +++ b/docker-auth-registry/README.md @@ -0,0 +1,8 @@ +Set-up a Docker Registry with Plain Text Authentication +-- + +This creates a registry that runs locally with plain text authentication set-up. + + ./build.sh + ./run.sh + ./test.sh diff --git a/docker-auth-registry/build.sh b/docker-auth-registry/build.sh new file mode 100755 index 00000000..6cccf6d5 --- /dev/null +++ b/docker-auth-registry/build.sh @@ -0,0 +1,8 @@ +#! /bin/sh +set -eux + +docker build -t auth-registry . + +if [ "$(which boot2docker)" != "" ]; then + VBoxManage controlvm boot2docker-vm natpf1 "5001,tcp,127.0.0.1,5001,,5001" || true +fi diff --git a/docker-auth-registry/docker-registry.conf b/docker-auth-registry/docker-registry.conf new file mode 100644 index 00000000..6173e5ca --- /dev/null +++ b/docker-auth-registry/docker-registry.conf @@ -0,0 +1,5 @@ +proxy_pass http://docker-registry; +proxy_set_header Host $http_host; # required for docker client's sake +proxy_set_header X-Real-IP $remote_addr; # pass on real client's IP +proxy_set_header Authorization ""; # see https://github.com/dotcloud/docker-registry/issues/170 +proxy_read_timeout 900; diff --git a/docker-auth-registry/docker-registry.htpasswd b/docker-auth-registry/docker-registry.htpasswd new file mode 100644 index 00000000..ccd2a76f --- /dev/null +++ b/docker-auth-registry/docker-registry.htpasswd @@ -0,0 +1 @@ +docker-java:$apr1$nhxYQXIn$s93lYeFNs66YAXwQerlHL0 diff --git a/docker-auth-registry/nginx.conf b/docker-auth-registry/nginx.conf new file mode 100644 index 00000000..8a11c229 --- /dev/null +++ b/docker-auth-registry/nginx.conf @@ -0,0 +1,44 @@ +http { +# FYI: Chunking requires nginx-extras package on Debian Wheezy and some Ubuntu versions +# See chunking http://wiki.nginx.org/HttpChunkinModule +# Replace with appropriate values where necessary + +upstream docker-registry { + server localhost:5000; +} + +# uncomment if you want a 301 redirect for users attempting to connect +# on port 80 +# NOTE: docker client will still fail. This is just for convenience +# server { +# listen *:80; +# server_name my.docker.registry.com; +# return 301 https://$server_name$request_uri; +# } + +server { + listen 5001; + server_name my.docker.registry.com; + + client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image uploads + + location / { + auth_basic "Restricted"; + auth_basic_user_file docker-registry.htpasswd; + include docker-registry.conf; + } + + location /_ping { + auth_basic off; + include docker-registry.conf; + } + + location /v1/_ping { + auth_basic off; + include docker-registry.conf; + } +} +} +events { + worker_connections 1024; +} \ No newline at end of file diff --git a/docker-auth-registry/run.sh b/docker-auth-registry/run.sh new file mode 100755 index 00000000..5a338dde --- /dev/null +++ b/docker-auth-registry/run.sh @@ -0,0 +1,6 @@ +#! /bin/sh +set -eux + +docker kill $(docker ps -q) || true + +docker run -p 5001:5001 auth-registry \ No newline at end of file diff --git a/docker-auth-registry/start.sh b/docker-auth-registry/start.sh new file mode 100755 index 00000000..c12ea4ed --- /dev/null +++ b/docker-auth-registry/start.sh @@ -0,0 +1,8 @@ +#! /bin/sh +set -eux + +docker-registry & +nginx + +wait + diff --git a/docker-auth-registry/test.sh b/docker-auth-registry/test.sh new file mode 100755 index 00000000..7d78b36d --- /dev/null +++ b/docker-auth-registry/test.sh @@ -0,0 +1,6 @@ +#! /bin/sh +set -eux + +curl http://localhost:5001/v1/_ping +curl http://localhost:5001/v1/users/ --basic --user docker-java:docker-java + diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 91d0c907..36962434 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -31,14 +31,7 @@ public abstract class AbstractDockerClientTest extends Assert { public void beforeTest() { LOG.info("======================= BEFORETEST ======================="); LOG.info("Connecting to Docker server"); - dockerClient = DockerClientBuilder.getInstance( - DockerClientConfig.createDefaultConfigBuilder() - .withServerAddress("http://localhost:5000") - .withUsername("docker-java") - .withPassword("docker-java") - .withEmail("docker-java@github.com") - .build() - ) + dockerClient = DockerClientBuilder.getInstance(config()) .withDockerCmdExecFactory(dockerCmdExecFactory) .build(); @@ -52,7 +45,20 @@ public void beforeTest() { LOG.info("======================= END OF BEFORETEST =======================\n\n"); } - public void afterTest() { + private DockerClientConfig config() { + return config("docker-java"); + } + + protected DockerClientConfig config(String password) { + return DockerClientConfig.createDefaultConfigBuilder() + .withServerAddress("http://localhost:5001") + .withUsername("docker-java") + .withPassword(password) + .withEmail("docker-java@github.com") + .build(); + } + + public void afterTest() { LOG.info("======================= END OF AFTERTEST ======================="); } diff --git a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java index 79834281..95011149 100644 --- a/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/AuthCmdImplTest.java @@ -1,21 +1,15 @@ package com.github.dockerjava.core.command; -import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.UnauthorizedException; import com.github.dockerjava.api.model.AuthResponse; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.core.DockerClientBuilder; -import com.github.dockerjava.core.DockerClientConfig; import org.testng.ITestResult; import org.testng.annotations.*; import java.lang.reflect.Method; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsNot.not; -import static org.hamcrest.core.StringContains.containsString; - @Test(groups = "integration") public class AuthCmdImplTest extends AbstractDockerClientTest { @@ -43,19 +37,17 @@ public void afterMethod(ITestResult result) { public void testAuth() throws Exception { AuthResponse response = dockerClient.authCmd().exec(); - assertThat(response.getStatus(), not(containsString("Account created"))); + assertEquals(response.getStatus(), "Login Succeeded"); } @Test public void testAuthInvalid() throws Exception { - DockerClientConfig config = DockerClientConfig.createDefaultConfigBuilder().withPassword("garbage").build(); - DockerClient client = DockerClientBuilder.getInstance(config).withDockerCmdExecFactory(dockerCmdExecFactory).build(); - - try { - client.authCmd().exec(); + + try { + DockerClientBuilder.getInstance(config("garbage")).build().authCmd().exec(); fail("Expected a UnauthorizedException caused by a bad password."); } catch (UnauthorizedException e) { - + assertEquals(e.getMessage(), "Wrong login/password, please try again\n"); } } } From 402fa2b1e3d146083ae71128d3209ab4a5a30bd2 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 2 Nov 2014 23:19:08 +0000 Subject: [PATCH 185/452] updated default username/password to be just "dockerjava" as hyphen is not allowed in usernames by Docker --- docker-auth-registry/Dockerfile | 2 -- docker-auth-registry/README.md | 2 ++ docker-auth-registry/docker-registry.htpasswd | 2 +- docker-auth-registry/test.sh | 2 +- .../dockerjava/client/AbstractDockerClientTest.java | 11 ++++++----- 5 files changed, 10 insertions(+), 9 deletions(-) diff --git a/docker-auth-registry/Dockerfile b/docker-auth-registry/Dockerfile index 4a663bc0..a1ff436a 100644 --- a/docker-auth-registry/Dockerfile +++ b/docker-auth-registry/Dockerfile @@ -1,5 +1,3 @@ -# https://medium.com/@deeeet/building-private-docker-registry-with-basic-authentication-with-self-signed-certificate-using-it-e6329085e612 - FROM registry RUN apt-get update diff --git a/docker-auth-registry/README.md b/docker-auth-registry/README.md index 86a6bca0..93a703fd 100644 --- a/docker-auth-registry/README.md +++ b/docker-auth-registry/README.md @@ -6,3 +6,5 @@ This creates a registry that runs locally with plain text authentication set-up. ./build.sh ./run.sh ./test.sh + +Based on . \ No newline at end of file diff --git a/docker-auth-registry/docker-registry.htpasswd b/docker-auth-registry/docker-registry.htpasswd index ccd2a76f..8288b160 100644 --- a/docker-auth-registry/docker-registry.htpasswd +++ b/docker-auth-registry/docker-registry.htpasswd @@ -1 +1 @@ -docker-java:$apr1$nhxYQXIn$s93lYeFNs66YAXwQerlHL0 +dockerjava:$apr1$9s.aEJml$nivZMa6GEWnJA/FhpTPbj0 diff --git a/docker-auth-registry/test.sh b/docker-auth-registry/test.sh index 7d78b36d..a71409a8 100755 --- a/docker-auth-registry/test.sh +++ b/docker-auth-registry/test.sh @@ -2,5 +2,5 @@ set -eux curl http://localhost:5001/v1/_ping -curl http://localhost:5001/v1/users/ --basic --user docker-java:docker-java +curl http://localhost:5001/v1/users/ --basic --user dockerjava:dockerjava diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 36962434..e0d198b8 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -23,8 +23,9 @@ public abstract class AbstractDockerClientTest extends Assert { public static final Logger LOG = LoggerFactory .getLogger(AbstractDockerClientTest.class); - - protected DockerClient dockerClient; + public static final String DOCKER_JAVA = "dockerjava"; + + protected DockerClient dockerClient; protected TestDockerCmdExecFactory dockerCmdExecFactory = new TestDockerCmdExecFactory(DockerClientBuilder.getDefaultDockerCmdExecFactory()); @@ -46,15 +47,15 @@ public void beforeTest() { } private DockerClientConfig config() { - return config("docker-java"); + return config(DOCKER_JAVA); } protected DockerClientConfig config(String password) { return DockerClientConfig.createDefaultConfigBuilder() .withServerAddress("http://localhost:5001") - .withUsername("docker-java") + .withUsername(DOCKER_JAVA) .withPassword(password) - .withEmail("docker-java@github.com") + .withEmail(DOCKER_JAVA + "@github.com") .build(); } From e5af72c5e6045996fea22c7974de80cc62a61388 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 2 Nov 2014 23:19:27 +0000 Subject: [PATCH 186/452] added debugging to PushImageCmdImplTest as it is failing --- .../github/dockerjava/core/command/PushImageCmdImplTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java index e64aaa7b..2e2c9134 100644 --- a/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java @@ -51,12 +51,13 @@ public void pushLatest() throws Exception { assertThat(container.getId(), not(isEmptyString())); - LOG.info("Commiting container: {}", container.toString()); + LOG.info("Committing container: {}", container.toString()); String imageId = dockerClient.commitCmd(container.getId()).withRepository(username + "/busybox").exec(); // we have to block until image is pushed asString(dockerClient.pushImageCmd(username + "/busybox").exec()); + LOG.info("Removing image: {}", imageId); dockerClient.removeImageCmd(imageId).exec(); String response = asString(dockerClient.pullImageCmd(username + "/busybox").exec()); From 6c84ba30cb273f037c1f9dcc9a4494381d5434d5 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 2 Nov 2014 23:21:25 +0000 Subject: [PATCH 187/452] removed file accidentally committed --- build-docker-registry.sh | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 build-docker-registry.sh diff --git a/build-docker-registry.sh b/build-docker-registry.sh deleted file mode 100644 index 56884517..00000000 --- a/build-docker-registry.sh +++ /dev/null @@ -1,5 +0,0 @@ -#! /bin/sh -set -eux - -git clone https://github.com/docker/docker-registry -cp docker-registry/contrib/nginx/nginx_1–3–9.conf /etc/nginx/conf.d/ \ No newline at end of file From f0f232fc3996381c4003dc2a31084a806edab723 Mon Sep 17 00:00:00 2001 From: "alex.collins" Date: Mon, 3 Nov 2014 17:15:30 +0000 Subject: [PATCH 188/452] fixed twitch tests in DockerClientImpl --- src/main/java/com/github/dockerjava/core/DockerClientImpl.java | 2 -- .../java/com/github/dockerjava/core/DockerClientConfigTest.java | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 4d88651e..2630d26d 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -71,8 +71,6 @@ private DockerCmdExecFactory getDockerCmdExecFactory() { public AuthConfig authConfig() { checkNotNull(dockerClientConfig.getUsername(), "Configured username is null."); - checkNotNull(dockerClientConfig.getPassword(), "Configured password is null."); - checkNotNull(dockerClientConfig.getEmail(), "Configured email is null."); checkNotNull(dockerClientConfig.getServerAddress(), "Configured serverAddress is null."); AuthConfig authConfig = new AuthConfig(); diff --git a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java index b05d8c6b..ac7024f5 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java @@ -34,7 +34,7 @@ public void equals() throws Exception { public void environmentDockerHost() throws Exception { // given docker host in env - Map env = new HashMap(System.getenv()); + Map env = new HashMap(); env.put("DOCKER_HOST", "tcp://baz:8768"); // when you build a config From bbeb6dc617161ba27ff4f409a50d6fea67d04454 Mon Sep 17 00:00:00 2001 From: "alex.collins" Date: Tue, 4 Nov 2014 19:06:30 +0000 Subject: [PATCH 189/452] make version default to null (i.e. absent and autodetect) --- src/main/resources/docker.io.properties | 1 - .../java/com/github/dockerjava/core/DockerClientConfigTest.java | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/resources/docker.io.properties b/src/main/resources/docker.io.properties index 3d9c7149..2188cff3 100644 --- a/src/main/resources/docker.io.properties +++ b/src/main/resources/docker.io.properties @@ -1,5 +1,4 @@ docker.io.url=https://localhost:2376 -docker.io.version=1.15 docker.io.enableLoggingFilter=true docker.io.dockerCertPath=${user.home}/.docker docker.io.username=${user.name} diff --git a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java index ac7024f5..f14640b0 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java @@ -101,7 +101,7 @@ public void defaults() throws Exception { assertEquals(config.getUri(), URI.create("https://localhost:2376")); assertEquals(config.getUsername(), "someUserName"); assertEquals(config.getServerAddress(), AuthConfig.DEFAULT_SERVER_ADDRESS); - assertEquals(config.getVersion(), "1.15"); + assertEquals(config.getVersion(), null); assertEquals(config.isLoggingFilterEnabled(), true); assertEquals(config.getDockerCertPath(), "someHomeDir/.docker"); } From 338851901dc2bf71595db00e99c00adcf72f5ffd Mon Sep 17 00:00:00 2001 From: "alex.collins" Date: Tue, 4 Nov 2014 19:40:44 +0000 Subject: [PATCH 190/452] pem files for SSL --- docker-auth-registry/Dockerfile | 3 +++ docker-auth-registry/build.sh | 20 +++++++++++++++++++ docker-auth-registry/ca-key.pem | 30 ++++++++++++++++++++++++++++ docker-auth-registry/ca.pem | 22 ++++++++++++++++++++ docker-auth-registry/ca.srl | 1 + docker-auth-registry/server-cert.pem | 18 +++++++++++++++++ docker-auth-registry/server-key.pem | 27 +++++++++++++++++++++++++ docker-auth-registry/server.csr | 15 ++++++++++++++ 8 files changed, 136 insertions(+) create mode 100644 docker-auth-registry/ca-key.pem create mode 100644 docker-auth-registry/ca.pem create mode 100644 docker-auth-registry/ca.srl create mode 100644 docker-auth-registry/server-cert.pem create mode 100644 docker-auth-registry/server-key.pem create mode 100644 docker-auth-registry/server.csr diff --git a/docker-auth-registry/Dockerfile b/docker-auth-registry/Dockerfile index a1ff436a..7780dc48 100644 --- a/docker-auth-registry/Dockerfile +++ b/docker-auth-registry/Dockerfile @@ -3,6 +3,9 @@ FROM registry RUN apt-get update RUN apt-get install -y nginx +ADD server-cert.pem /etc/ssl/certs/docker-registry +ADD server-key.pem /etc/ssl/private/docker-registry + ADD nginx.conf /etc/nginx/ ADD docker-registry.conf /etc/nginx/ diff --git a/docker-auth-registry/build.sh b/docker-auth-registry/build.sh index 6cccf6d5..784858fe 100755 --- a/docker-auth-registry/build.sh +++ b/docker-auth-registry/build.sh @@ -1,8 +1,28 @@ #! /bin/sh set -eux +if [ ! -e server-key.pem ]; then + echo "enter dockerjava each time you are asked for a pass-phase, press enter for everything else" + + echo 01 > ca.srl + openssl genrsa -des3 -out ca-key.pem 2048 + openssl req -new -x509 -days 365 -key ca-key.pem -out ca.pem + openssl genrsa -des3 -out server-key.pem 2048 + openssl req -subj '/CN=localhost' -new -key server-key.pem -out server.csr + openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem -out server-cert.pem + openssl rsa -in server-key.pem -out server-key.pem +fi + docker build -t auth-registry . if [ "$(which boot2docker)" != "" ]; then + B=$(echo $DOCKER_HOST|sed 's/.*\/\(.*\):.*/\1/') + + scp -i ~/.ssh/id_boot2docker ca.pem docker@$B: + + echo "sudo su - +chmod +w /etc/ssl/certs/ca-certificates.crt +cat ca.pem >> /etc/ssl/certs/ca-certificates.crt" | boot2docker ssh + VBoxManage controlvm boot2docker-vm natpf1 "5001,tcp,127.0.0.1,5001,,5001" || true fi diff --git a/docker-auth-registry/ca-key.pem b/docker-auth-registry/ca-key.pem new file mode 100644 index 00000000..0db29a49 --- /dev/null +++ b/docker-auth-registry/ca-key.pem @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: DES-EDE3-CBC,73BD3223857CCE6D + +rPSVPVC+qyguEaHhLhNFaqlRRdaCmTm5QH1bBqo3R+GJ7E28u7KmUhVyYXXI7uW9 +CsDnTIYV2Lh+wJ3aWcYpevHnFSdwELYkzVgCAdOI3vwl5sDJbgBHolIMd8lxaeUW +Yjb5t6E+HoOJGt1Os5Si3etS40o9hwc0l/FEASWCK0DQdHanUra2SIfOxOdd0p4Q +q/dr5ISmSVpCHGSwl04WF95PnV7+glkT8MuJqcp1jdb3iZNjZsnIzameBLtRWw1P +G7HxfeKtMJ8Fz9hV17OPFi7DeuPnS7xzcvj6JCGWQxPTi684Q6VReNjrNAqIK2jr +GuYxXUHVeYp4BUwO9o6/sK3cAj6X7khzRZ8Oz/ELl8MPV6ekFI4bWRXzPGHtG3AB +mN1NR4KZrBJiLOx770fhVxn7qbTc/eBd/r0tcfsVnMrOBqTQueyaGhEMiUf/lYY5 +l3llhYb0UBgzteValM4VIaVj0aizpV1xBkPZHkpQAw4nJPrykDNRXKrgZdTQLhif +zKjol+3UKMGrMvZA8DVBI7g93sxC34lk9y8V58LnX6lx3WDIz381Mer6D6+FDQoN +taGC1EpiU2Bb6zyxVzg4thjYwCOLNWWbPAJF9DH/PZf+9dDGxrrhaZZ8nkT/bztB +UAa3nFszgUKL1bbpSundkRJpBxDLWXhP1lnti9+VaP8TwTNOdvLlgwJ7jsleSyTg +WzrTjSk8DY1LD5sT9gyNbyw7m9zlYGh1USgBMQ2BYCRerHUyjBx/Iryl4mws5EWa +3BJZCxzJCRFh+YKHzsn/I7ZWLrOAXlrqOFcepcoYrIXJzmgztCoLuAHQY8DNjkoT +CxEHtFiWEN3GsHHnNQD0uFDcRjMLu7F31XPUSVZWk9/2pQyXfp2/Eacdjb6x9xnK +QCzmK5P3sYY39+1S3RyzB3o3CgnAtX56B2pPg4NSM9RYPRhMwkHFx+MBwuL90i+q +YbJrskngQTMGphmTbGW7kZsxtzGanbM74NvRd43BewtpqY6TihEszrXBx7WHd3PP +QNKPTNkC71goyDNmZUTeQWkKOZE7jHqOKzuwnWyh8FhvfNIyz/NunHKfcwGElsQQ +HzuD3+VYnNatXbMAn63/5ovPqFwhalBIj5ars4UDqAXBpDg4mNKtzOZp4E9Get6J +VeAHynFRZIXOF7qIUTRPiLt2mriHRDtljZfUOlzZDgBo1OFcJwKkj+6mA1zDMcpq +veZyMLPvbUHzFYINP5GlEJtWPH6msFUiyyI0WlS4jfVqZgVXhclgOEu+x40xaTCF +9cjvVsq6tjsZ2IRUVTZlkPgycWHP/iRlkC/mRz/ypKP6dAMOc50kpgaOf6HZkWnH +ACUKEn+2QDVQ2CgPPS4BWeMgFAolXiG1zWvVz7ImVs7LJzLcsVMSypbk2O+ysIqt +57MB1gUwDrE6am0+0x1Ub5eWiA8XJDGZZfI0xTtaChqCcOWxXmyvjSuKng9KXB5y +v3JYtPoNaNqNXSibyIbVdn2vlwH2Jc6wm7se/xhyohMXQDlrC2y4sRXPwPghzAXx +khr0WAeW2CxqAMs/DAc6q6rEfOGfmhxla1JdfH6oKN4YiHZV5pqN8A== +-----END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/ca.pem b/docker-auth-registry/ca.pem new file mode 100644 index 00000000..e9843a0e --- /dev/null +++ b/docker-auth-registry/ca.pem @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDtTCCAp2gAwIBAgIJAMgLvS7V36/7MA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQwHhcNMTQxMTA0MTkzOTU5WhcNMTUxMTA0MTkzOTU5WjBF +MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 +ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEAqMYo+Yegm1tvkR1raYAyjl04RnE5kMYqgf+4qm5SJPnTMoHFujOJRueI +oXbU3NsWwoPTxK2bRbseYsrtiazv6tMTOD6Q5PPPWAJX4Rd+rIsPm8yTS7maY6oj +wWpWOdoAb4VKebsGlXtU6HjgRTTzwt6PLrivveG5XfL8f/MXw24nMIQcxd7TghPP +xrkTqbdhT0kEGmtzuRzhiRUueu6aGsRM47gcjUmlTcanLA2upGv79xYG6ctXFk9v +HvxDzBkI6IZAPdMi868BfTkC7e8FpwaL0xxLimzMNlJq81+ML6b7M9tCE6AkIFGJ +R1hYZlrdb2m5q1VSEp12KXnHt0af8wIDAQABo4GnMIGkMB0GA1UdDgQWBBTXCS2i +qGDSW4mBqZ+93jgNX04AhTB1BgNVHSMEbjBsgBTXCS2iqGDSW4mBqZ+93jgNX04A +haFJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV +BAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAMgLvS7V36/7MAwGA1UdEwQF +MAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAGXe/NpC+fLA9jwN2i8j+5oGILyyaM6t +IDicuLkCCd3Wmf6/esRVycspxdUWr3fT5irR+qIfW0ZQJAoEP7bNQGbdyZwv/k2j +45mLpMe9thr3KXib4VEh9wWBNygZ7JkvBMLUX1hYYKVa7Q35d+BWxysNTj4kemsB +eeRensWQAI84gPbCNTL4QAMCzNm15L1g/HZTcKh3+uoLmkPOOME1FcCmOqyPCoqQ +Q7b9DR8D7gqD6jbXM7j9QlhZXz66eDNU5p50jh9To+4xyvMTwIHGmxRPh8oRxMoz +LvQ0mWR3ktykHT2R7Rc036ExFJ+9M6OEU/UXBzLj0qha61lWFesZgaQ= +-----END CERTIFICATE----- diff --git a/docker-auth-registry/ca.srl b/docker-auth-registry/ca.srl new file mode 100644 index 00000000..9e22bcb8 --- /dev/null +++ b/docker-auth-registry/ca.srl @@ -0,0 +1 @@ +02 diff --git a/docker-auth-registry/server-cert.pem b/docker-auth-registry/server-cert.pem new file mode 100644 index 00000000..17ded5a7 --- /dev/null +++ b/docker-auth-registry/server-cert.pem @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIICzTCCAbUCAQIwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQVUxEzARBgNV +BAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0 +ZDAeFw0xNDExMDQxOTQwMDRaFw0xNTExMDQxOTQwMDRaMBQxEjAQBgNVBAMTCWxv +Y2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKfRxskyD/zB +oaE1kUpfKnU2QHevcXFiEulA88UxsktWV9laekFmoFlEPJCV1Y3rZv52+whhAZM9 +p845qNdEMARohrGimKf+S/fybk6Jo+A+3Q2ZpKAyKZ6k6sAiWoHCkcRoCE8L/Apr +luyiCTbdavaBKEro/nlkeDfaFKjoraX/PEgfXtBjHH4r6xvpWEE7BWJ6jREkFIl0 +PyO4TJBmhL4btmTMKIiszO8ak3oXa72NKpjGR0Dll5utvveSxluQycGRe16ocGBZ +ihoLcHuNrJjbfo0wv+JA8mTNCnx+J3pnXoVCArkHpteTSABiB7lyLCM3DAEGEsOd +oKi57oGEwkECAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAgsynmNIju8Oz23Vn/zvt +L7r0j1M5srFvNXx1lEVooaBhwdZ50jxMAWdp+mw4r6r17Ml7NJ9IEB4xFE3c3RUO +9OEDN2Y7bvxjWG2weGyA8WcCWPwdwikm6rTdT+g+pPVZadSStHqTNcYtGiAcbSXx +L4T6AdogcfLKbJhDDOo51wEmDEru/NHJmmL+f05oKtrANQXMUJcaF2B2pFZ4va8N +MjLs/kNHgG/i7xYAu/PxNFNwQEnXdzEZG0RQFPMfCo30aNhtKCXQz2/lDSx3kg7v +Xbovhg/wgIFk98w4R/26iqT4pa4Abl33SZj38Aho9yi/utJg7xiIoy4YFv+f9W8c +gQ== +-----END CERTIFICATE----- diff --git a/docker-auth-registry/server-key.pem b/docker-auth-registry/server-key.pem new file mode 100644 index 00000000..388ef1d3 --- /dev/null +++ b/docker-auth-registry/server-key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAp9HGyTIP/MGhoTWRSl8qdTZAd69xcWIS6UDzxTGyS1ZX2Vp6 +QWagWUQ8kJXVjetm/nb7CGEBkz2nzjmo10QwBGiGsaKYp/5L9/JuTomj4D7dDZmk +oDIpnqTqwCJagcKRxGgITwv8CmuW7KIJNt1q9oEoSuj+eWR4N9oUqOitpf88SB9e +0GMcfivrG+lYQTsFYnqNESQUiXQ/I7hMkGaEvhu2ZMwoiKzM7xqTehdrvY0qmMZH +QOWXm62+95LGW5DJwZF7XqhwYFmKGgtwe42smNt+jTC/4kDyZM0KfH4nemdehUIC +uQem15NIAGIHuXIsIzcMAQYSw52gqLnugYTCQQIDAQABAoIBAAFWMGkl1u7CdBEe +phubinEIj5bkdNjcWR42gDqP3MWw2F5I1DR1Js3PN1RHfT32JAne1L0KWMLdeNqx +puCgEGnYk0oS63hbFCvTaIGDoySEG6qiEKed/qre0WfaXjIuZI7V7UsD42wJ01fr +KnufY9y2xqViGbTJ0hNPz15RDCEIVhtKvO8Z1zczxZYyKyj4Oq+mh/5VJSWVdoke +dg7QG1smH1QvS0R4rnmb4Z9Hhvf6Ux1StuTxIzMTSqKdP+AeR3H1rAXirHYltKd3 +OOe+H5hJypS43tRsB9qRqlv6cTKoaZPWkoyk11GXy6VO0ZvosqS5QD87HFCDIaO7 +tnXXCAECgYEA0Cr719q5k/HIBUw2C5owLy6ByzF73Yybgsw08flSZb31XLR8uwsy +AxQlN2OfLfEEt6Ym9GCFJBFd5gaSMOrZfV5iTO2DqxqqY9IovJjItTNxcIxDlanT +0ixV3apCaT6O7pWM4XdK2i6F14mD/ISCqjGbV4kB3q+tVpn96kn25GECgYEAzmFi +MLlzboj2oyE6+Lj/PEUHpQFtnpl7fz6A0KW14Jd0lV6YR1oxvfFX0jNUzzTZUsCu +6R0sZbQ/UKaDxsrgtTh1z4RrOJvqloDVxRFYau8IhmU90FRy4CvzSXC8ozYmyg0P +LWlFJ6p3vmQA54oeUS9z/sbMhLElLit/G/oCqeECgYA5FqCsiNJ+DT+ynDzyH535 +QoLb670xfB8l1sTqW1rKhjbk7qaKUT6s83hlYU/FNKT7jHiAanv48T5UGBc9jRqK +NDk3KagDY7O43mjHmArrDqmcmQrr34A00m3V9Zxy6nIeYisZpjKD9WBFRPRKazi+ +Xg5hCjTWEk2yQ1cMSq6H4QKBgEv1acdXKlYfkO8/ls3egQp0ubiQiwEZqmuN3Klu +pD9SXzVuyItSdgZb4p/aBrfw0p/zjSz9cM7KBZewgcXT+9qXOj0zlqcSM8hLCOLs +XGeXLMMSVirsOg+p/XQlSzijAKnTHqfvG+XahxILCo4ttrTYy0+VacbY0D9rAPCS +FxLhAoGBALFasz705seizxNaUbv/CmjYu7Fpy1nmJq1n4yXzhNn/1mPlDD4xU2LE +GFc5PtzdjAGg1pFetPQeui7LJScdZGrotU9OlOyccDZwkhm5F2f7D6RSp5uzoB5H +2hyqGV7fkQ5e0FbBEcYwblsfqrEwA4punAuMCJa7MMpKHBjqt9/7 +-----END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/server.csr b/docker-auth-registry/server.csr new file mode 100644 index 00000000..8d1aa537 --- /dev/null +++ b/docker-auth-registry/server.csr @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICWTCCAUECAQAwFDESMBAGA1UEAxMJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEAp9HGyTIP/MGhoTWRSl8qdTZAd69xcWIS6UDzxTGy +S1ZX2Vp6QWagWUQ8kJXVjetm/nb7CGEBkz2nzjmo10QwBGiGsaKYp/5L9/JuTomj +4D7dDZmkoDIpnqTqwCJagcKRxGgITwv8CmuW7KIJNt1q9oEoSuj+eWR4N9oUqOit +pf88SB9e0GMcfivrG+lYQTsFYnqNESQUiXQ/I7hMkGaEvhu2ZMwoiKzM7xqTehdr +vY0qmMZHQOWXm62+95LGW5DJwZF7XqhwYFmKGgtwe42smNt+jTC/4kDyZM0KfH4n +emdehUICuQem15NIAGIHuXIsIzcMAQYSw52gqLnugYTCQQIDAQABoAAwDQYJKoZI +hvcNAQEFBQADggEBACrZ6CdZET4uqCfBeN2qxPAHopmrIRrZpy+0l41ogYW1ZAht +xQwGmlleTdbBge6bPwOg2tU88IL1+q4jl5dyyvq0YBpCZKlIxhbG0h21+lUbQnNe +3lqcgdgBGeVEO+nyWd7HXSuK43kbRlRAt4dBdlXDa9vCQFj6HXanlwRr9Org6RTn +i4opE7KrgiTqHEHkqRv3OmaCFYBR0YJgU6KrwRTkynukayF6OKY4qKUximcA5TUZ +bzo60MCY01QoM3N+wdebYtrc0YbgKeIz2/LXeJx8CeZHxB5ScUo4I6BQ06fPeor1 +CVsUCx6Jc8hZYGr2VIgOqfcSnNiaZrmhzkInRIs= +-----END CERTIFICATE REQUEST----- From e06b2a42068883a202ce20f0c5d6115bd433a84b Mon Sep 17 00:00:00 2001 From: "alex.collins" Date: Tue, 4 Nov 2014 20:46:18 +0000 Subject: [PATCH 191/452] moved files around --- README.md | 16 ++-- docker-auth-registry/README.md | 2 +- docker-auth-registry/build.sh | 28 ------- docker-auth-registry/ca-key.pem | 30 ------- docker-auth-registry/ca.pem | 22 ----- .../{ => container}/Dockerfile | 2 +- docker-auth-registry/container/ca-key.pem | 30 +++++++ docker-auth-registry/container/ca.pem | 24 ++++++ docker-auth-registry/{ => container}/ca.srl | 0 .../{ => container}/docker-registry.conf | 0 .../{ => container}/docker-registry.htpasswd | 0 .../{ => container}/nginx.conf | 11 ++- .../container/server-cert.pem | 18 ++++ docker-auth-registry/container/server-key.pem | 27 ++++++ docker-auth-registry/container/server.csr | 15 ++++ docker-auth-registry/{ => container}/start.sh | 0 docker-auth-registry/registry.sh | 84 +++++++++++++++++++ docker-auth-registry/run.sh | 6 -- docker-auth-registry/server-cert.pem | 18 ---- docker-auth-registry/server-key.pem | 27 ------ docker-auth-registry/server.csr | 15 ---- docker-auth-registry/test.sh | 6 -- 22 files changed, 219 insertions(+), 162 deletions(-) delete mode 100755 docker-auth-registry/build.sh delete mode 100644 docker-auth-registry/ca-key.pem delete mode 100644 docker-auth-registry/ca.pem rename docker-auth-registry/{ => container}/Dockerfile (96%) create mode 100644 docker-auth-registry/container/ca-key.pem create mode 100644 docker-auth-registry/container/ca.pem rename docker-auth-registry/{ => container}/ca.srl (100%) rename docker-auth-registry/{ => container}/docker-registry.conf (100%) rename docker-auth-registry/{ => container}/docker-registry.htpasswd (100%) rename docker-auth-registry/{ => container}/nginx.conf (78%) create mode 100644 docker-auth-registry/container/server-cert.pem create mode 100644 docker-auth-registry/container/server-key.pem create mode 100644 docker-auth-registry/container/server.csr rename docker-auth-registry/{ => container}/start.sh (100%) create mode 100755 docker-auth-registry/registry.sh delete mode 100755 docker-auth-registry/run.sh delete mode 100644 docker-auth-registry/server-cert.pem delete mode 100644 docker-auth-registry/server-key.pem delete mode 100644 docker-auth-registry/server.csr delete mode 100755 docker-auth-registry/test.sh diff --git a/README.md b/README.md index 26c148c8..46c75531 100644 --- a/README.md +++ b/README.md @@ -17,9 +17,13 @@ Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/ * Docker daemon running * Docker private repository running (see below). -You'll need to be running a local private registry, as per [these instructions](docker-auth-registry/README.md): +You'll need to be running a local private registry, as per [these instructions](docker-auth-registry/README.md): -The Maven build includes integration tests which are using a localhost instance of Docker and require manual setup. Make sure you have a local Docker daemon running and then provide your https://registry.hub.docker.com/account/login/ information via system properties: +If you need SSL, then you'll need to put your `*.pem` file into `~/.docker/`, if you're using boot2docker, do this: + + $ ln -s /Users/alex.collins/.boot2docker/certs/boot2docker-vm .docker + +Build and run integration tests as follows: $ mvn clean install @@ -80,10 +84,10 @@ There are a couple of configuration items, all of which have sensible defaults: * `url` The Docker URL, e.g. `https://localhost:2376`. * `version` The API version, e.g. `1.15`. -* `username` Your repository username (required to push containers). -* `password` Your repository password. -* `email` Your repository email. -* `serverAddress` Your repository's address. +* `username` Your register username (required to push containers). +* `password` Your register password. +* `email` Your register email. +* `serverAddress` Your register's address. * `dockerCertPath` Path to the docker certs. There are three ways to configure, in descending order of precedence: diff --git a/docker-auth-registry/README.md b/docker-auth-registry/README.md index 93a703fd..7bf17f1c 100644 --- a/docker-auth-registry/README.md +++ b/docker-auth-registry/README.md @@ -4,7 +4,7 @@ Set-up a Docker Registry with Plain Text Authentication This creates a registry that runs locally with plain text authentication set-up. ./build.sh - ./run.sh + ./start-registry.sh ./test.sh Based on . \ No newline at end of file diff --git a/docker-auth-registry/build.sh b/docker-auth-registry/build.sh deleted file mode 100755 index 784858fe..00000000 --- a/docker-auth-registry/build.sh +++ /dev/null @@ -1,28 +0,0 @@ -#! /bin/sh -set -eux - -if [ ! -e server-key.pem ]; then - echo "enter dockerjava each time you are asked for a pass-phase, press enter for everything else" - - echo 01 > ca.srl - openssl genrsa -des3 -out ca-key.pem 2048 - openssl req -new -x509 -days 365 -key ca-key.pem -out ca.pem - openssl genrsa -des3 -out server-key.pem 2048 - openssl req -subj '/CN=localhost' -new -key server-key.pem -out server.csr - openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem -out server-cert.pem - openssl rsa -in server-key.pem -out server-key.pem -fi - -docker build -t auth-registry . - -if [ "$(which boot2docker)" != "" ]; then - B=$(echo $DOCKER_HOST|sed 's/.*\/\(.*\):.*/\1/') - - scp -i ~/.ssh/id_boot2docker ca.pem docker@$B: - - echo "sudo su - -chmod +w /etc/ssl/certs/ca-certificates.crt -cat ca.pem >> /etc/ssl/certs/ca-certificates.crt" | boot2docker ssh - - VBoxManage controlvm boot2docker-vm natpf1 "5001,tcp,127.0.0.1,5001,,5001" || true -fi diff --git a/docker-auth-registry/ca-key.pem b/docker-auth-registry/ca-key.pem deleted file mode 100644 index 0db29a49..00000000 --- a/docker-auth-registry/ca-key.pem +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: DES-EDE3-CBC,73BD3223857CCE6D - -rPSVPVC+qyguEaHhLhNFaqlRRdaCmTm5QH1bBqo3R+GJ7E28u7KmUhVyYXXI7uW9 -CsDnTIYV2Lh+wJ3aWcYpevHnFSdwELYkzVgCAdOI3vwl5sDJbgBHolIMd8lxaeUW -Yjb5t6E+HoOJGt1Os5Si3etS40o9hwc0l/FEASWCK0DQdHanUra2SIfOxOdd0p4Q -q/dr5ISmSVpCHGSwl04WF95PnV7+glkT8MuJqcp1jdb3iZNjZsnIzameBLtRWw1P -G7HxfeKtMJ8Fz9hV17OPFi7DeuPnS7xzcvj6JCGWQxPTi684Q6VReNjrNAqIK2jr -GuYxXUHVeYp4BUwO9o6/sK3cAj6X7khzRZ8Oz/ELl8MPV6ekFI4bWRXzPGHtG3AB -mN1NR4KZrBJiLOx770fhVxn7qbTc/eBd/r0tcfsVnMrOBqTQueyaGhEMiUf/lYY5 -l3llhYb0UBgzteValM4VIaVj0aizpV1xBkPZHkpQAw4nJPrykDNRXKrgZdTQLhif -zKjol+3UKMGrMvZA8DVBI7g93sxC34lk9y8V58LnX6lx3WDIz381Mer6D6+FDQoN -taGC1EpiU2Bb6zyxVzg4thjYwCOLNWWbPAJF9DH/PZf+9dDGxrrhaZZ8nkT/bztB -UAa3nFszgUKL1bbpSundkRJpBxDLWXhP1lnti9+VaP8TwTNOdvLlgwJ7jsleSyTg -WzrTjSk8DY1LD5sT9gyNbyw7m9zlYGh1USgBMQ2BYCRerHUyjBx/Iryl4mws5EWa -3BJZCxzJCRFh+YKHzsn/I7ZWLrOAXlrqOFcepcoYrIXJzmgztCoLuAHQY8DNjkoT -CxEHtFiWEN3GsHHnNQD0uFDcRjMLu7F31XPUSVZWk9/2pQyXfp2/Eacdjb6x9xnK -QCzmK5P3sYY39+1S3RyzB3o3CgnAtX56B2pPg4NSM9RYPRhMwkHFx+MBwuL90i+q -YbJrskngQTMGphmTbGW7kZsxtzGanbM74NvRd43BewtpqY6TihEszrXBx7WHd3PP -QNKPTNkC71goyDNmZUTeQWkKOZE7jHqOKzuwnWyh8FhvfNIyz/NunHKfcwGElsQQ -HzuD3+VYnNatXbMAn63/5ovPqFwhalBIj5ars4UDqAXBpDg4mNKtzOZp4E9Get6J -VeAHynFRZIXOF7qIUTRPiLt2mriHRDtljZfUOlzZDgBo1OFcJwKkj+6mA1zDMcpq -veZyMLPvbUHzFYINP5GlEJtWPH6msFUiyyI0WlS4jfVqZgVXhclgOEu+x40xaTCF -9cjvVsq6tjsZ2IRUVTZlkPgycWHP/iRlkC/mRz/ypKP6dAMOc50kpgaOf6HZkWnH -ACUKEn+2QDVQ2CgPPS4BWeMgFAolXiG1zWvVz7ImVs7LJzLcsVMSypbk2O+ysIqt -57MB1gUwDrE6am0+0x1Ub5eWiA8XJDGZZfI0xTtaChqCcOWxXmyvjSuKng9KXB5y -v3JYtPoNaNqNXSibyIbVdn2vlwH2Jc6wm7se/xhyohMXQDlrC2y4sRXPwPghzAXx -khr0WAeW2CxqAMs/DAc6q6rEfOGfmhxla1JdfH6oKN4YiHZV5pqN8A== ------END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/ca.pem b/docker-auth-registry/ca.pem deleted file mode 100644 index e9843a0e..00000000 --- a/docker-auth-registry/ca.pem +++ /dev/null @@ -1,22 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDtTCCAp2gAwIBAgIJAMgLvS7V36/7MA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV -BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX -aWRnaXRzIFB0eSBMdGQwHhcNMTQxMTA0MTkzOTU5WhcNMTUxMTA0MTkzOTU5WjBF -MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 -ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB -CgKCAQEAqMYo+Yegm1tvkR1raYAyjl04RnE5kMYqgf+4qm5SJPnTMoHFujOJRueI -oXbU3NsWwoPTxK2bRbseYsrtiazv6tMTOD6Q5PPPWAJX4Rd+rIsPm8yTS7maY6oj -wWpWOdoAb4VKebsGlXtU6HjgRTTzwt6PLrivveG5XfL8f/MXw24nMIQcxd7TghPP -xrkTqbdhT0kEGmtzuRzhiRUueu6aGsRM47gcjUmlTcanLA2upGv79xYG6ctXFk9v -HvxDzBkI6IZAPdMi868BfTkC7e8FpwaL0xxLimzMNlJq81+ML6b7M9tCE6AkIFGJ -R1hYZlrdb2m5q1VSEp12KXnHt0af8wIDAQABo4GnMIGkMB0GA1UdDgQWBBTXCS2i -qGDSW4mBqZ+93jgNX04AhTB1BgNVHSMEbjBsgBTXCS2iqGDSW4mBqZ+93jgNX04A -haFJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV -BAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAMgLvS7V36/7MAwGA1UdEwQF -MAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAGXe/NpC+fLA9jwN2i8j+5oGILyyaM6t -IDicuLkCCd3Wmf6/esRVycspxdUWr3fT5irR+qIfW0ZQJAoEP7bNQGbdyZwv/k2j -45mLpMe9thr3KXib4VEh9wWBNygZ7JkvBMLUX1hYYKVa7Q35d+BWxysNTj4kemsB -eeRensWQAI84gPbCNTL4QAMCzNm15L1g/HZTcKh3+uoLmkPOOME1FcCmOqyPCoqQ -Q7b9DR8D7gqD6jbXM7j9QlhZXz66eDNU5p50jh9To+4xyvMTwIHGmxRPh8oRxMoz -LvQ0mWR3ktykHT2R7Rc036ExFJ+9M6OEU/UXBzLj0qha61lWFesZgaQ= ------END CERTIFICATE----- diff --git a/docker-auth-registry/Dockerfile b/docker-auth-registry/container/Dockerfile similarity index 96% rename from docker-auth-registry/Dockerfile rename to docker-auth-registry/container/Dockerfile index 7780dc48..11407726 100644 --- a/docker-auth-registry/Dockerfile +++ b/docker-auth-registry/container/Dockerfile @@ -11,7 +11,7 @@ ADD docker-registry.conf /etc/nginx/ ADD docker-registry.htpasswd /etc/nginx/ -EXPOSE 5001 +EXPOSE 5443 ADD start.sh . diff --git a/docker-auth-registry/container/ca-key.pem b/docker-auth-registry/container/ca-key.pem new file mode 100644 index 00000000..1045c4b0 --- /dev/null +++ b/docker-auth-registry/container/ca-key.pem @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: DES-EDE3-CBC,3999A487D02FB784 + +itt2rZJ/o7LNUwOOQ7DBWkw1X6QH0KsPJyhGiz65+mBzs6o5MVNGfoP9n0BWczH9 +JROYfynKpucI7hCFoOf3315M2fdscJ4aJ2gZBSSDsK4vwUL+RWXf7qorY1iL4Xqg +niOg80qLKZTGwF0PxuIOHyfDqBhrmSG9prD7elsVGKB6sAC8Z+HvTrFsZ0+voIEJ +je81yEKO8uD8FP5nGeGE6BgLlNmkzbxL4lZjdrF7tkSkY+GzR937NzjHmNWbF5Vp +knVIv5Y0W9ptThkTwYxbWS/AUHgn7VLsOQGmkRvQbj/JJhVqFyBAyE4kN+foec1W +o8glNBIGGHvR3Fo2w2kWJ7uAWAQ4MfcJnWpN2I+EOQUo0Ojgr543F0XAjtr90480 +U0RatIxzc3eoRcVmh9+iD595zRe8gwJNfi6AEGrFx8aK5pCIdQI2/HNY3AR1v4gC +ZD+/meUM7krMBY4EVTKgS17dxPCQfwxj3hd5kvfde5Lg3JvZRKDEPFmF6T9CDI5d +0oG+w/usXCW8C+zOWtNRvrgJgp7SnNLriMIjPvAqrEEn/6tAFKfrVnEfjxnZt/ai +M7o8OdP9u5NRzQEgAUfhKeR/KNGN26ZFD0a0wVx3MCxEq2k9xs33nActtAb6rZM6 +c20IvGRxL1YWhfcPKDH4OpVk/zfORGLUNS6T9CGZgaMzKz/hd8L0wpJ/MKGbvpCh +dANutqKBWg4DwKDaL33Abo1OhFkCRoFPSs1GiBEcmSxcVa3loxaNpR4KFElbKrXy +I7NlCJG82stThm6NqxMUpRJNvUQaXz7P1x6RGnHMC84TE0gZPPezLToArcE41OTY +czB5PP3efz0r/PexZaFZPT98J4NgSV1mqTOXuBmIHKlnvyyEYq0Ytdi5RqWLECoK +KSAX/SYFFq+NqxcC5ua0hH5C6klv7qtmLJ5KfyHfpTNt2qScN7M9Kmd4v8CBiZOL +9KcKBKqhXRt3laSJyRI59s+pqvhDr1T2CGvFZ/8oGwhjGPIxKnr81AwAT3SwjqXQ +HKDKs+RwxZYRZuTtRCkBMHxxk/c+hrTbomAwfM3DiPZFMSk8n81WCjEoyY3FN2si +QSrJYAzu/Oga1jJPwhxLLbucGnQUGi94DSy+RAD4btGtSK6eN2rPo8Wwh/Vh8GHi +wXS5d+VIsFEAL70dYpkkQSE34ZjEpbcGOpx0YIgrsGG2c0BbmxiYzJhDHpSMWvQ+ +Zbly8Mp7c5YOCHVbnIvDi6LyK+Py3zucIjEa6T6sC9Jy28bfuQUegiBNerLI4Y0E +Txi5lcH1YD3AJIIWyW4Fub2TUBocYciZAs79vD0iRzAKgF9/4PGGTyVc0cdKIr6w +jUtQMQt0vPnqi4pgx1MuNxza5LEJ7O2tRkAs+SYGQu3uuWxtJsGsH72lJFzpj/rs +5Lo8TM/rjdwF0JtdSt+RmVa05BmUxPzP1K1vgu1wdq08iyJ2qme/g6cwBwICxjaX +50Pqh6WpFUUldJMU9jwljNlqumpTHmxlzbwLc5RWTmoBYth068HfnCQLbGnO+6zS +n/lJScYuMAiFmuugOVhwDKc5LzlVnrjVlapxRbas9nprupwzeBJKh6p2Jg/oqFRm +-----END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/container/ca.pem b/docker-auth-registry/container/ca.pem new file mode 100644 index 00000000..7af686f6 --- /dev/null +++ b/docker-auth-registry/container/ca.pem @@ -0,0 +1,24 @@ +-----BEGIN CERTIFICATE----- +MIIEGDCCAwCgAwIBAgIJAJuxT3/GW0piMA0GCSqGSIb3DQEBBQUAMGUxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQxHjAcBgNVBAMTFWdsMDQzMjFtLmdhbWVzeXMuY29ycDAe +Fw0xNDExMDQyMDI4MzBaFw0xNTExMDQyMDI4MzBaMGUxCzAJBgNVBAYTAkFVMRMw +EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0 +eSBMdGQxHjAcBgNVBAMTFWdsMDQzMjFtLmdhbWVzeXMuY29ycDCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAM1VTVMAFSieoaFChrzMArR6la7SpDOXYRNo +PcW/BgpLEoq7SpqY5f5LAzq6ivAP8DwHSrnGIFNrn4Lf7OWhtAT4jLc7ZaTi2NXb +wQoTZUqnSeGjLJqTM5hLAjnxcvL0ZJyMTSbLL4ezbs1GePyTDi6VFiP1lI+mpytc +lVKsAJy8sW7rXRLSH3xliUQXUPR7I9I73pm0z+D/7R+hxN5EDYUPgXmsleUmiEJl +dhdaFeFxYjGox9RjCeXsl/xQ/GcYUxv93DdUwSpVCFE1OOOjuXlpcvoRBAbKBGmB +n5piD542NpandtRg7wJEfSVq9FR+nEcMRSSNfFKUAIqlzbcjcZsCAwEAAaOByjCB +xzAdBgNVHQ4EFgQUpRc8oWOtyJIg/fVn12SfhAvbl1gwgZcGA1UdIwSBjzCBjIAU +pRc8oWOtyJIg/fVn12SfhAvbl1ihaaRnMGUxCzAJBgNVBAYTAkFVMRMwEQYDVQQI +EwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQx +HjAcBgNVBAMTFWdsMDQzMjFtLmdhbWVzeXMuY29ycIIJAJuxT3/GW0piMAwGA1Ud +EwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADckZj0+Fz4Tp/Wv97deSigTIbDs +z8HhgcEo7lzyXCnGVkuMRr6DIpi+cULe7+NZh6+bEdB8Jc/pM8G3fZY9q2QSoTCA +EcNe1ctB0y/YrD66cDCzhWYFzTp+7B7/DlsMdqmeuPgpbhggpun8V7v+QhrvvKQz +CHCD1wOc61aM9jayGAH5uK7N25oiySY4F1okELbsjQ3y3vsfDed1yw1//Td8F2J7 +7geLpgAWrjHQ86Jx+7see1UuSaaIONTtNHD5K0zQQCIvcFi8OiAnEgWQTY4OayG0 +M5sDGFdi3/ba/ffG95Hb802fjQsQlUACKZk6Ni3FlwPWQVPzgU3jj/AFCtw= +-----END CERTIFICATE----- diff --git a/docker-auth-registry/ca.srl b/docker-auth-registry/container/ca.srl similarity index 100% rename from docker-auth-registry/ca.srl rename to docker-auth-registry/container/ca.srl diff --git a/docker-auth-registry/docker-registry.conf b/docker-auth-registry/container/docker-registry.conf similarity index 100% rename from docker-auth-registry/docker-registry.conf rename to docker-auth-registry/container/docker-registry.conf diff --git a/docker-auth-registry/docker-registry.htpasswd b/docker-auth-registry/container/docker-registry.htpasswd similarity index 100% rename from docker-auth-registry/docker-registry.htpasswd rename to docker-auth-registry/container/docker-registry.htpasswd diff --git a/docker-auth-registry/nginx.conf b/docker-auth-registry/container/nginx.conf similarity index 78% rename from docker-auth-registry/nginx.conf rename to docker-auth-registry/container/nginx.conf index 8a11c229..096aa23d 100644 --- a/docker-auth-registry/nginx.conf +++ b/docker-auth-registry/container/nginx.conf @@ -17,11 +17,18 @@ upstream docker-registry { # } server { - listen 5001; - server_name my.docker.registry.com; + listen 5443; + server_name localhost; + + ssl on; + ssl_certificate /etc/ssl/certs/docker-registry; + ssl_certificate_key /etc/ssl/private/docker-registry; client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image uploads + # required to avoid HTTP 411: see Issue #1486 (https://github.com/docker/docker/issues/1486) + chunked_transfer_encoding on; + location / { auth_basic "Restricted"; auth_basic_user_file docker-registry.htpasswd; diff --git a/docker-auth-registry/container/server-cert.pem b/docker-auth-registry/container/server-cert.pem new file mode 100644 index 00000000..5cdcd083 --- /dev/null +++ b/docker-auth-registry/container/server-cert.pem @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC+TCCAeECAQIwDQYJKoZIhvcNAQEFBQAwZTELMAkGA1UEBhMCQVUxEzARBgNV +BAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0 +ZDEeMBwGA1UEAxMVZ2wwNDMyMW0uZ2FtZXN5cy5jb3JwMB4XDTE0MTEwNDIwMjg0 +MFoXDTE1MTEwNDIwMjg0MFowIDEeMBwGA1UEAxMVZ2wwNDMyMW0uZ2FtZXN5cy5j +b3JwMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv/x+4myZH+OQlohG +PQGKWU7txx26LjQ8XAWlpER1HseZphWmPVRdDvpvU8qKR9GxWrX3FBZagwFR7deX +u2spCa1DDwFBy5ysEK2HxKEI1U/1t9QhM4IDlFdWEO2FiT1GDkF8jqr6xVDPVwot +zhLZFBUrNcEtsZAMpg3jpv8Pz89WHzP+M87eqgt8SYBK4yWgDt1qiAshQiF9XKA5 +HjwKSi0N86NjE+UTcGJ82lcCRTr3vnXHwPQicYY2sbawF6ZznzAbmPWrqIcfnkD/ +vvjtnHL29gHL4eb/Dk4OxYdNkADZDMwmZgyalPkTFFRY7reqLojoHCzgdW1UxbaA +LRav7wIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQCYNfq7ANSLfNPs43J/CCJ2SzfJ +elTvnYah9fdN9Bog9oTmk053wbLKJFv8xUlYZvSnnBFRP0CcBfJ/IFVe+/Pjk1cB +KrhbOT4pZKcA1gYFNEz2+DjM6caf7H8bsE2NFF9rlb05ys0P6mtqywxRDFVbyD42 +dNFZteP775sZDK7Bd9hNPnfter9KXDFi1j79jR3ZwalHOdVwOpeXZoieqoEIDbo5 +wgjuXsk0AyrERUWGL4/oQ91BhlK6OBtPNZ0SwjWBKECOZjf8RRZ49W9jZOPzRczj +JO0STwxfKFwEu2YJkdnlH2TdJF1+GsuukkjFeYc61lCp7jwakD9LfY55vhcy +-----END CERTIFICATE----- diff --git a/docker-auth-registry/container/server-key.pem b/docker-auth-registry/container/server-key.pem new file mode 100644 index 00000000..92b3f8ca --- /dev/null +++ b/docker-auth-registry/container/server-key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAv/x+4myZH+OQlohGPQGKWU7txx26LjQ8XAWlpER1HseZphWm +PVRdDvpvU8qKR9GxWrX3FBZagwFR7deXu2spCa1DDwFBy5ysEK2HxKEI1U/1t9Qh +M4IDlFdWEO2FiT1GDkF8jqr6xVDPVwotzhLZFBUrNcEtsZAMpg3jpv8Pz89WHzP+ +M87eqgt8SYBK4yWgDt1qiAshQiF9XKA5HjwKSi0N86NjE+UTcGJ82lcCRTr3vnXH +wPQicYY2sbawF6ZznzAbmPWrqIcfnkD/vvjtnHL29gHL4eb/Dk4OxYdNkADZDMwm +ZgyalPkTFFRY7reqLojoHCzgdW1UxbaALRav7wIDAQABAoIBAQCeBD+XM5Uw1wep +ro5JJhxt93Xj/kbAQsQvZYJ5WtMfO1/ugEEsl2RksKGy0LDR/fjA1aaAhQmIbCy3 +20wKuV+0lEPudLVn1hMVQw7NO1He6Iow/Ms67tbtYJj5I9ZWJ/WiRCo17uqqPyH4 +3Orog0Dis62198MZM5wFjMcEK0kjW3HtovEvxRzCoMr9cgQ2qCN9L+W069lEinZC +LRcQlcxTuIzVRkQN7pxtGW+AGdX4fWzndMLdmJJce++jyIFfoev7KVzDqQFKJA+V +ceKa0/F8Jr0de1dUl06XhhfSibXBeimQIpVo6Bnd4wJs52gdvbqnF4ojOjPMuHmk +Bymx0VZBAoGBAN+IScCZ4FVsYbUsRWaNAB9G+idAZ6m3wiu+1xdYiFjGEjtHtiSc +XUT7Z3t/8mqL+4RgHq3+aBCUI6UaOQ0wmI+1q3JnngW4YG8LLEzqJjQoapsck/Hw +R83advxNraohdFqzti+NS+vmFQjAQozAH0z20pt2aTty4bgKDFzXmM5PAoGBANvf +Nw3liHBwnOKKLXBY/gyqWh2UPWoWte2cplVqC2TQjYA4sMA5bn/e26aeMQ+h9SzP +t53zhxxJXOk2XpQIbRwQygNzXmlQHLI1oGitd6Jm3wLRyABIIKfLZK3v3NOGsktu +qjInecUR27DW8ah33Q8+L0Ro4cMYQH30Dn8nSjxhAoGAC5Khxt/wllubH2cgXLPW +Gshw8RFLjKTf36Xsut+xh28RyJHo4zJZPdYKQIGaSlve9LaJQBbYymrxAX4/D+jB +LUeJjc3Bh6hJDda1P3Ir8i1Zf5hWLIN1JDo4SM24vQMoY/3D4+hb0uXBlwdlKqZT +uIda1gOmZRaIix+yDih3V88CgYAmw0mPd6IAQLpH7hhosCfJz9anVFUneO2GAJIK +iPGNSn9H1bbDjNyASqfqzgTUPrdcuRokDKULRZvNuboe2wVxZzxWM2a3ploIyQ+I +pNxskzpJ4vYhppWrP152k80YtayFQ/NZeEAtkCJtINfl3YvpfgsTQnJa1NG54ucT +X7fkwQKBgQDWhiZvB9YGaWGIwxUXR8eZtsilcMMwLWMr5YrYwfpZlb1Syxa8L32Y +Qyqx10b+0o+GcqhIoFc1YjjG7hgQkyYNtZ/weKAAZfNEdLA630oIva80NnoWTpYe +MuKRa2cQxeUmW1t5OoF63j6nZcTpR/AivBoBfdF4vSfF0tFB46N7qg== +-----END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/container/server.csr b/docker-auth-registry/container/server.csr new file mode 100644 index 00000000..d3ffd9c3 --- /dev/null +++ b/docker-auth-registry/container/server.csr @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICZTCCAU0CAQAwIDEeMBwGA1UEAxMVZ2wwNDMyMW0uZ2FtZXN5cy5jb3JwMIIB +IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv/x+4myZH+OQlohGPQGKWU7t +xx26LjQ8XAWlpER1HseZphWmPVRdDvpvU8qKR9GxWrX3FBZagwFR7deXu2spCa1D +DwFBy5ysEK2HxKEI1U/1t9QhM4IDlFdWEO2FiT1GDkF8jqr6xVDPVwotzhLZFBUr +NcEtsZAMpg3jpv8Pz89WHzP+M87eqgt8SYBK4yWgDt1qiAshQiF9XKA5HjwKSi0N +86NjE+UTcGJ82lcCRTr3vnXHwPQicYY2sbawF6ZznzAbmPWrqIcfnkD/vvjtnHL2 +9gHL4eb/Dk4OxYdNkADZDMwmZgyalPkTFFRY7reqLojoHCzgdW1UxbaALRav7wID +AQABoAAwDQYJKoZIhvcNAQEFBQADggEBAB2R18mbz31Aov765hX3MgXrt9h5lmbs +bGjawK+wT3RffLgKWAIMg6IXfzpYVfMTZGu8j0xBnz388371GNix3zct0fGtdY5c +tcaT67zvCy4ubAnOkd8lKBZM2FNfg2BeyVp3wKCrYEr9aYKesZnFVMgfx30dC1eO +lB97fBSz6hdPIzOKqGpj6cf8g7GmpaL5AHx2NuPbBoHwMhFpvIUK1OvwcGooMTJC +vGBwqZqDQybFPBpxQRUfVGm8ZBwkQvw+ekxgzeknd133lIi+ciL3lrLn3AqIrs/5 +TtnKG5E+YXHPxKXpeP8paPDZl/wVJrqhxZqyNMJnAQmNVMxjTWFjJzY= +-----END CERTIFICATE REQUEST----- diff --git a/docker-auth-registry/start.sh b/docker-auth-registry/container/start.sh similarity index 100% rename from docker-auth-registry/start.sh rename to docker-auth-registry/container/start.sh diff --git a/docker-auth-registry/registry.sh b/docker-auth-registry/registry.sh new file mode 100755 index 00000000..91ea9d53 --- /dev/null +++ b/docker-auth-registry/registry.sh @@ -0,0 +1,84 @@ +#! /bin/sh +set -eu + +function build() { + echo "building..." + if [ ! -e done ]; then + echo "enter dockerjava each time you are asked for a pass-phase" + H=$(hostname) + echo "enter $H when requested for a common name" + echo "press enter for everything else" + + echo 01 > ca.srl + openssl genrsa -des3 -out ca-key.pem 2048 + openssl req -new -x509 -days 365 -key ca-key.pem -out ca.pem + + openssl genrsa -des3 -out server-key.pem 2048 + openssl req -subj "/CN=$H" -new -key server-key.pem -out server.csr + openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem -out server-cert.pem + + openssl rsa -in server-key.pem -out server-key.pem + + if [ "$(which boot2docker)" != "" ]; then + B=$(echo $DOCKER_HOST|sed 's/.*\/\(.*\):.*/\1/') + + scp -i ~/.ssh/id_boot2docker ca.pem docker@$B: + + echo "mkdir /etc/docker/certs.d/localhost:5443/" | boot2docker ssh + echo "cat ca.pem > /etc/docker/certs.d/localhost:5443/ca.crt" | boot2docker ssh + fi + + touch done + fi + + docker build -t auth-registry . + + if [ "$(which boot2docker)" != "" ]; then + VBoxManage controlvm boot2docker-vm natpf1 "5443,tcp,127.0.0.1,5443,,5443" || true + fi +} + +function start() { + echo "starting..." + docker run -P -p 5443:5443 -d auth-registry + sleep 2s +} + +function stop() { + PS=$(docker ps|grep auth-registry|awk '{print $1}') + if [ "" != "$PS" ]; then + echo "stopping..." + docker kill $PS + fi + if [ "$(which boot2docker)" != "" ]; then + VBoxManage controlvm boot2docker-vm natpf1 delete 5443 || true + fi +} + +function testIt() { + echo "testing..." + curl https://localhost:5443/v1/_ping -f -k + echo + curl https://localhost:5443/v1/users/ -k -f --basic --user dockerjava:dockerjava + echo +} + +C=${1:-''} + +cd container + +case $C in + build) build ;; + start) start ;; + stop) stop ;; + test) testIt ;; + '') + stop + build + start + testIt + ;; + *) + echo "$(basename $0) (build|start|stop|test)" +esac + diff --git a/docker-auth-registry/run.sh b/docker-auth-registry/run.sh deleted file mode 100755 index 5a338dde..00000000 --- a/docker-auth-registry/run.sh +++ /dev/null @@ -1,6 +0,0 @@ -#! /bin/sh -set -eux - -docker kill $(docker ps -q) || true - -docker run -p 5001:5001 auth-registry \ No newline at end of file diff --git a/docker-auth-registry/server-cert.pem b/docker-auth-registry/server-cert.pem deleted file mode 100644 index 17ded5a7..00000000 --- a/docker-auth-registry/server-cert.pem +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICzTCCAbUCAQIwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQVUxEzARBgNV -BAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0 -ZDAeFw0xNDExMDQxOTQwMDRaFw0xNTExMDQxOTQwMDRaMBQxEjAQBgNVBAMTCWxv -Y2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKfRxskyD/zB -oaE1kUpfKnU2QHevcXFiEulA88UxsktWV9laekFmoFlEPJCV1Y3rZv52+whhAZM9 -p845qNdEMARohrGimKf+S/fybk6Jo+A+3Q2ZpKAyKZ6k6sAiWoHCkcRoCE8L/Apr -luyiCTbdavaBKEro/nlkeDfaFKjoraX/PEgfXtBjHH4r6xvpWEE7BWJ6jREkFIl0 -PyO4TJBmhL4btmTMKIiszO8ak3oXa72NKpjGR0Dll5utvveSxluQycGRe16ocGBZ -ihoLcHuNrJjbfo0wv+JA8mTNCnx+J3pnXoVCArkHpteTSABiB7lyLCM3DAEGEsOd -oKi57oGEwkECAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAgsynmNIju8Oz23Vn/zvt -L7r0j1M5srFvNXx1lEVooaBhwdZ50jxMAWdp+mw4r6r17Ml7NJ9IEB4xFE3c3RUO -9OEDN2Y7bvxjWG2weGyA8WcCWPwdwikm6rTdT+g+pPVZadSStHqTNcYtGiAcbSXx -L4T6AdogcfLKbJhDDOo51wEmDEru/NHJmmL+f05oKtrANQXMUJcaF2B2pFZ4va8N -MjLs/kNHgG/i7xYAu/PxNFNwQEnXdzEZG0RQFPMfCo30aNhtKCXQz2/lDSx3kg7v -Xbovhg/wgIFk98w4R/26iqT4pa4Abl33SZj38Aho9yi/utJg7xiIoy4YFv+f9W8c -gQ== ------END CERTIFICATE----- diff --git a/docker-auth-registry/server-key.pem b/docker-auth-registry/server-key.pem deleted file mode 100644 index 388ef1d3..00000000 --- a/docker-auth-registry/server-key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAp9HGyTIP/MGhoTWRSl8qdTZAd69xcWIS6UDzxTGyS1ZX2Vp6 -QWagWUQ8kJXVjetm/nb7CGEBkz2nzjmo10QwBGiGsaKYp/5L9/JuTomj4D7dDZmk -oDIpnqTqwCJagcKRxGgITwv8CmuW7KIJNt1q9oEoSuj+eWR4N9oUqOitpf88SB9e -0GMcfivrG+lYQTsFYnqNESQUiXQ/I7hMkGaEvhu2ZMwoiKzM7xqTehdrvY0qmMZH -QOWXm62+95LGW5DJwZF7XqhwYFmKGgtwe42smNt+jTC/4kDyZM0KfH4nemdehUIC -uQem15NIAGIHuXIsIzcMAQYSw52gqLnugYTCQQIDAQABAoIBAAFWMGkl1u7CdBEe -phubinEIj5bkdNjcWR42gDqP3MWw2F5I1DR1Js3PN1RHfT32JAne1L0KWMLdeNqx -puCgEGnYk0oS63hbFCvTaIGDoySEG6qiEKed/qre0WfaXjIuZI7V7UsD42wJ01fr -KnufY9y2xqViGbTJ0hNPz15RDCEIVhtKvO8Z1zczxZYyKyj4Oq+mh/5VJSWVdoke -dg7QG1smH1QvS0R4rnmb4Z9Hhvf6Ux1StuTxIzMTSqKdP+AeR3H1rAXirHYltKd3 -OOe+H5hJypS43tRsB9qRqlv6cTKoaZPWkoyk11GXy6VO0ZvosqS5QD87HFCDIaO7 -tnXXCAECgYEA0Cr719q5k/HIBUw2C5owLy6ByzF73Yybgsw08flSZb31XLR8uwsy -AxQlN2OfLfEEt6Ym9GCFJBFd5gaSMOrZfV5iTO2DqxqqY9IovJjItTNxcIxDlanT -0ixV3apCaT6O7pWM4XdK2i6F14mD/ISCqjGbV4kB3q+tVpn96kn25GECgYEAzmFi -MLlzboj2oyE6+Lj/PEUHpQFtnpl7fz6A0KW14Jd0lV6YR1oxvfFX0jNUzzTZUsCu -6R0sZbQ/UKaDxsrgtTh1z4RrOJvqloDVxRFYau8IhmU90FRy4CvzSXC8ozYmyg0P -LWlFJ6p3vmQA54oeUS9z/sbMhLElLit/G/oCqeECgYA5FqCsiNJ+DT+ynDzyH535 -QoLb670xfB8l1sTqW1rKhjbk7qaKUT6s83hlYU/FNKT7jHiAanv48T5UGBc9jRqK -NDk3KagDY7O43mjHmArrDqmcmQrr34A00m3V9Zxy6nIeYisZpjKD9WBFRPRKazi+ -Xg5hCjTWEk2yQ1cMSq6H4QKBgEv1acdXKlYfkO8/ls3egQp0ubiQiwEZqmuN3Klu -pD9SXzVuyItSdgZb4p/aBrfw0p/zjSz9cM7KBZewgcXT+9qXOj0zlqcSM8hLCOLs -XGeXLMMSVirsOg+p/XQlSzijAKnTHqfvG+XahxILCo4ttrTYy0+VacbY0D9rAPCS -FxLhAoGBALFasz705seizxNaUbv/CmjYu7Fpy1nmJq1n4yXzhNn/1mPlDD4xU2LE -GFc5PtzdjAGg1pFetPQeui7LJScdZGrotU9OlOyccDZwkhm5F2f7D6RSp5uzoB5H -2hyqGV7fkQ5e0FbBEcYwblsfqrEwA4punAuMCJa7MMpKHBjqt9/7 ------END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/server.csr b/docker-auth-registry/server.csr deleted file mode 100644 index 8d1aa537..00000000 --- a/docker-auth-registry/server.csr +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN CERTIFICATE REQUEST----- -MIICWTCCAUECAQAwFDESMBAGA1UEAxMJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0B -AQEFAAOCAQ8AMIIBCgKCAQEAp9HGyTIP/MGhoTWRSl8qdTZAd69xcWIS6UDzxTGy -S1ZX2Vp6QWagWUQ8kJXVjetm/nb7CGEBkz2nzjmo10QwBGiGsaKYp/5L9/JuTomj -4D7dDZmkoDIpnqTqwCJagcKRxGgITwv8CmuW7KIJNt1q9oEoSuj+eWR4N9oUqOit -pf88SB9e0GMcfivrG+lYQTsFYnqNESQUiXQ/I7hMkGaEvhu2ZMwoiKzM7xqTehdr -vY0qmMZHQOWXm62+95LGW5DJwZF7XqhwYFmKGgtwe42smNt+jTC/4kDyZM0KfH4n -emdehUICuQem15NIAGIHuXIsIzcMAQYSw52gqLnugYTCQQIDAQABoAAwDQYJKoZI -hvcNAQEFBQADggEBACrZ6CdZET4uqCfBeN2qxPAHopmrIRrZpy+0l41ogYW1ZAht -xQwGmlleTdbBge6bPwOg2tU88IL1+q4jl5dyyvq0YBpCZKlIxhbG0h21+lUbQnNe -3lqcgdgBGeVEO+nyWd7HXSuK43kbRlRAt4dBdlXDa9vCQFj6HXanlwRr9Org6RTn -i4opE7KrgiTqHEHkqRv3OmaCFYBR0YJgU6KrwRTkynukayF6OKY4qKUximcA5TUZ -bzo60MCY01QoM3N+wdebYtrc0YbgKeIz2/LXeJx8CeZHxB5ScUo4I6BQ06fPeor1 -CVsUCx6Jc8hZYGr2VIgOqfcSnNiaZrmhzkInRIs= ------END CERTIFICATE REQUEST----- diff --git a/docker-auth-registry/test.sh b/docker-auth-registry/test.sh deleted file mode 100755 index a71409a8..00000000 --- a/docker-auth-registry/test.sh +++ /dev/null @@ -1,6 +0,0 @@ -#! /bin/sh -set -eux - -curl http://localhost:5001/v1/_ping -curl http://localhost:5001/v1/users/ --basic --user dockerjava:dockerjava - From 6f28a243f06ab19310774e92e5fac0106a065196 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Tue, 4 Nov 2014 20:47:18 +0000 Subject: [PATCH 192/452] Update README.md --- docker-auth-registry/README.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/docker-auth-registry/README.md b/docker-auth-registry/README.md index 7bf17f1c..be8c7de5 100644 --- a/docker-auth-registry/README.md +++ b/docker-auth-registry/README.md @@ -1,10 +1,8 @@ Set-up a Docker Registry with Plain Text Authentication -- -This creates a registry that runs locally with plain text authentication set-up. +This creates a registry that runs locally with SSL andt authentication set-up. - ./build.sh - ./start-registry.sh - ./test.sh + ./registry.sh -Based on . \ No newline at end of file +Based on . From f1573c0efb2eb83c1314254cfc5732977d1e79f3 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Tue, 4 Nov 2014 20:47:28 +0000 Subject: [PATCH 193/452] Update README.md --- docker-auth-registry/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-auth-registry/README.md b/docker-auth-registry/README.md index be8c7de5..212ab92e 100644 --- a/docker-auth-registry/README.md +++ b/docker-auth-registry/README.md @@ -1,7 +1,7 @@ Set-up a Docker Registry with Plain Text Authentication -- -This creates a registry that runs locally with SSL andt authentication set-up. +This creates a registry that runs locally with SSL and authentication set-up. ./registry.sh From eca6f62ad49ea78db765fc1e398456fc26c37000 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 5 Nov 2014 20:21:11 +0100 Subject: [PATCH 194/452] Commit tests --- .../dockerjava/api/model/BindingTest.java | 116 +++++++++--------- .../api/model/Ports_SerializingTest.java | 84 ++++++------- .../api/model/Ports_addBindingsTest.java | 114 ++++++++--------- 3 files changed, 157 insertions(+), 157 deletions(-) diff --git a/src/test/java/com/github/dockerjava/api/model/BindingTest.java b/src/test/java/com/github/dockerjava/api/model/BindingTest.java index bd848866..0379dcdb 100644 --- a/src/test/java/com/github/dockerjava/api/model/BindingTest.java +++ b/src/test/java/com/github/dockerjava/api/model/BindingTest.java @@ -1,58 +1,58 @@ -package com.github.dockerjava.api.model; - -import static org.testng.Assert.assertEquals; - -import org.testng.annotations.Test; - -import com.github.dockerjava.api.model.Ports.Binding; - -public class BindingTest { - - @Test - public void parseIpAndPort() { - assertEquals(Binding.parse("127.0.0.1:80"), Ports.Binding("127.0.0.1", 80)); - } - - @Test - public void parsePortOnly() { - assertEquals(Binding.parse("80"), Ports.Binding(null, 80)); - } - - @Test - public void parseIPOnly() { - assertEquals(Binding.parse("127.0.0.1"), Ports.Binding("127.0.0.1", null)); - } - - @Test - public void parseEmptyString() { - assertEquals(Binding.parse(""), Ports.Binding(null, null)); - } - - @Test(expectedExceptions = IllegalArgumentException.class, - expectedExceptionsMessageRegExp = "Error parsing Binding 'nonsense'") - public void parseInvalidInput() { - Binding.parse("nonsense"); - } - - @Test(expectedExceptions = IllegalArgumentException.class, - expectedExceptionsMessageRegExp = "Error parsing Binding 'null'") - public void parseNull() { - Binding.parse(null); - } - - @Test - public void toStringIpAndHost() { - assertEquals(Binding.parse("127.0.0.1:80").toString(), "127.0.0.1:80"); - } - - @Test - public void toStringPortOnly() { - assertEquals(Binding.parse("80").toString(), "80"); - } - - @Test - public void toStringIpOnly() { - assertEquals(Binding.parse("127.0.0.1").toString(), "127.0.0.1"); - } - -} +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.github.dockerjava.api.model.Ports.Binding; + +public class BindingTest { + + @Test + public void parseIpAndPort() { + assertEquals(Binding.parse("127.0.0.1:80"), Ports.Binding("127.0.0.1", 80)); + } + + @Test + public void parsePortOnly() { + assertEquals(Binding.parse("80"), Ports.Binding(null, 80)); + } + + @Test + public void parseIPOnly() { + assertEquals(Binding.parse("127.0.0.1"), Ports.Binding("127.0.0.1", null)); + } + + @Test + public void parseEmptyString() { + assertEquals(Binding.parse(""), Ports.Binding(null, null)); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Binding 'nonsense'") + public void parseInvalidInput() { + Binding.parse("nonsense"); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing Binding 'null'") + public void parseNull() { + Binding.parse(null); + } + + @Test + public void toStringIpAndHost() { + assertEquals(Binding.parse("127.0.0.1:80").toString(), "127.0.0.1:80"); + } + + @Test + public void toStringPortOnly() { + assertEquals(Binding.parse("80").toString(), "80"); + } + + @Test + public void toStringIpOnly() { + assertEquals(Binding.parse("127.0.0.1").toString(), "127.0.0.1"); + } + +} diff --git a/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java b/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java index d295c881..25931069 100644 --- a/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java +++ b/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java @@ -1,42 +1,42 @@ -package com.github.dockerjava.api.model; - -import static org.testng.Assert.assertEquals; - -import java.util.Map; - -import org.testng.annotations.Test; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.dockerjava.api.model.Ports.Binding; - -public class Ports_SerializingTest { - private final ObjectMapper objectMapper = new ObjectMapper(); - private final String jsonWithDoubleBindingForOnePort = - "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"},{\"HostIp\":\"10.0.0.2\",\"HostPort\":\"80\"}]}"; - - @Test - public void deserializingPortWithMultipleBindings() throws Exception { - Ports ports = objectMapper.readValue(jsonWithDoubleBindingForOnePort, Ports.class); - Map map = ports.getBindings(); - assertEquals(map.size(), 1); - - Binding[] bindings = map.get(ExposedPort.tcp(80)); - assertEquals(bindings.length, 2); - assertEquals(bindings[0], new Binding("10.0.0.1", 80)); - assertEquals(bindings[1], new Binding("10.0.0.2", 80)); - } - - @Test - public void serializingPortWithMultipleBindings() throws Exception { - Ports ports = new Ports(); - ports.bind(ExposedPort.tcp(80), new Binding("10.0.0.1", 80)); - ports.bind(ExposedPort.tcp(80), new Binding("10.0.0.2", 80)); - assertEquals(objectMapper.writeValueAsString(ports), jsonWithDoubleBindingForOnePort); - } - - @Test - public void serializingEmptyBinding() throws Exception { - Ports ports = new Ports(ExposedPort.tcp(80), new Binding(null, null)); - assertEquals(objectMapper.writeValueAsString(ports), "{\"80/tcp\":[{\"HostIp\":\"\",\"HostPort\":\"\"}]}"); - } -} +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import java.util.Map; + +import org.testng.annotations.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.model.Ports.Binding; + +public class Ports_SerializingTest { + private final ObjectMapper objectMapper = new ObjectMapper(); + private final String jsonWithDoubleBindingForOnePort = + "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"},{\"HostIp\":\"10.0.0.2\",\"HostPort\":\"80\"}]}"; + + @Test + public void deserializingPortWithMultipleBindings() throws Exception { + Ports ports = objectMapper.readValue(jsonWithDoubleBindingForOnePort, Ports.class); + Map map = ports.getBindings(); + assertEquals(map.size(), 1); + + Binding[] bindings = map.get(ExposedPort.tcp(80)); + assertEquals(bindings.length, 2); + assertEquals(bindings[0], new Binding("10.0.0.1", 80)); + assertEquals(bindings[1], new Binding("10.0.0.2", 80)); + } + + @Test + public void serializingPortWithMultipleBindings() throws Exception { + Ports ports = new Ports(); + ports.bind(ExposedPort.tcp(80), new Binding("10.0.0.1", 80)); + ports.bind(ExposedPort.tcp(80), new Binding("10.0.0.2", 80)); + assertEquals(objectMapper.writeValueAsString(ports), jsonWithDoubleBindingForOnePort); + } + + @Test + public void serializingEmptyBinding() throws Exception { + Ports ports = new Ports(ExposedPort.tcp(80), new Binding(null, null)); + assertEquals(objectMapper.writeValueAsString(ports), "{\"80/tcp\":[{\"HostIp\":\"\",\"HostPort\":\"\"}]}"); + } +} diff --git a/src/test/java/com/github/dockerjava/api/model/Ports_addBindingsTest.java b/src/test/java/com/github/dockerjava/api/model/Ports_addBindingsTest.java index 23abbdd2..20e47df9 100644 --- a/src/test/java/com/github/dockerjava/api/model/Ports_addBindingsTest.java +++ b/src/test/java/com/github/dockerjava/api/model/Ports_addBindingsTest.java @@ -1,57 +1,57 @@ -package com.github.dockerjava.api.model; - -import static org.testng.Assert.assertEquals; - -import java.util.Map; - -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import com.github.dockerjava.api.model.Ports.Binding; - -/** - * As there may be several {@link Binding}s per {@link ExposedPort}, - * it makes a difference if you add {@link PortBinding}s for the - * same or different {@link ExposedPort}s to {@link Ports}. - * This test verifies that the Map in {@link Ports} is populated - * correctly in both cases. - */ -public class Ports_addBindingsTest { - private static final ExposedPort TCP_80 = ExposedPort.tcp(80); - private static final ExposedPort TCP_90 = ExposedPort.tcp(90); - private static final Binding BINDING_8080 = Ports.Binding(8080); - private static final Binding BINDING_9090 = Ports.Binding(9090); - - private Ports ports; - - @BeforeMethod - public void setup() { - ports = new Ports(); - } - - @Test - public void addTwoBindingsForDifferentExposedPorts() { - ports.add( - new PortBinding(BINDING_8080, TCP_80), - new PortBinding(BINDING_9090, TCP_90)); - - Map bindings = ports.getBindings(); - // two keys with one value each - assertEquals(bindings.size(), 2); - assertEquals(bindings.get(TCP_80), new Binding[] { BINDING_8080 }); - assertEquals(bindings.get(TCP_90), new Binding[] { BINDING_9090 }); - } - - @Test - public void addTwoBindingsForSameExposedPort() { - ports.add( - new PortBinding(BINDING_8080, TCP_80), - new PortBinding(BINDING_9090, TCP_80)); - - Map bindings = ports.getBindings(); - // one key with two values - assertEquals(bindings.size(), 1); - assertEquals(bindings.get(TCP_80), new Binding[] { BINDING_8080, BINDING_9090 }); - } - -} +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import java.util.Map; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.github.dockerjava.api.model.Ports.Binding; + +/** + * As there may be several {@link Binding}s per {@link ExposedPort}, + * it makes a difference if you add {@link PortBinding}s for the + * same or different {@link ExposedPort}s to {@link Ports}. + * This test verifies that the Map in {@link Ports} is populated + * correctly in both cases. + */ +public class Ports_addBindingsTest { + private static final ExposedPort TCP_80 = ExposedPort.tcp(80); + private static final ExposedPort TCP_90 = ExposedPort.tcp(90); + private static final Binding BINDING_8080 = Ports.Binding(8080); + private static final Binding BINDING_9090 = Ports.Binding(9090); + + private Ports ports; + + @BeforeMethod + public void setup() { + ports = new Ports(); + } + + @Test + public void addTwoBindingsForDifferentExposedPorts() { + ports.add( + new PortBinding(BINDING_8080, TCP_80), + new PortBinding(BINDING_9090, TCP_90)); + + Map bindings = ports.getBindings(); + // two keys with one value each + assertEquals(bindings.size(), 2); + assertEquals(bindings.get(TCP_80), new Binding[] { BINDING_8080 }); + assertEquals(bindings.get(TCP_90), new Binding[] { BINDING_9090 }); + } + + @Test + public void addTwoBindingsForSameExposedPort() { + ports.add( + new PortBinding(BINDING_8080, TCP_80), + new PortBinding(BINDING_9090, TCP_80)); + + Map bindings = ports.getBindings(); + // one key with two values + assertEquals(bindings.size(), 1); + assertEquals(bindings.get(TCP_80), new Binding[] { BINDING_8080, BINDING_9090 }); + } + +} From 9898ac36ca4f373e228129b65a348d5802e94556 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 5 Nov 2014 20:26:44 +0100 Subject: [PATCH 195/452] [maven-release-plugin] prepare release docker-java-0.10.3 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 72e9dfd0..617f1945 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.3-SNAPSHOT + 0.10.3 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-0.10.3 From 41fe15d4cc0be97a14882c1f4651f6700c4e8f2b Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 5 Nov 2014 20:26:49 +0100 Subject: [PATCH 196/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 617f1945..89fb8831 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.3 + 0.10.4-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.10.3 + HEAD From d74799eae1e09c051354ed6914413aa15c0ea05e Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 5 Nov 2014 20:37:42 +0100 Subject: [PATCH 197/452] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8eff82a2..51ac433c 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Run build without integration tests: com.github.docker-java docker-java - 0.10.2 + 0.10.3 ### Latest SNAPSHOT version @@ -64,7 +64,7 @@ Run build without integration tests: com.github.docker-java docker-java - 0.10.3-SNAPSHOT + 0.10.4-SNAPSHOT Latest SNAPSHOT is published to maven repo: https://oss.sonatype.org/content/groups/public via ![Build on CloudBees](http://cloudbees.prod.acquia-sites.com/sites/default/files/styles/large/public/Button-Powered-by-CB.png?itok=uMDWINfY) From b50bb58a14335ffa13fbcb35260de1805a098e4e Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sat, 8 Nov 2014 23:23:42 +0000 Subject: [PATCH 198/452] 1 --- docker-auth-registry/README.md | 14 +++- docker-auth-registry/container/ca-key.pem | 30 ------- docker-auth-registry/container/ca.pem | 24 ------ .../container/server-cert.pem | 18 ---- docker-auth-registry/container/server-key.pem | 27 ------ docker-auth-registry/container/server.csr | 15 ---- docker-auth-registry/container/start.sh | 8 -- docker-auth-registry/fig.yml | 10 +++ .../{container => nginx}/Dockerfile | 11 +-- docker-auth-registry/nginx/build.sh | 27 ++++++ docker-auth-registry/nginx/ca-key.pem | 30 +++++++ docker-auth-registry/nginx/ca.pem | 25 ++++++ .../{container => nginx}/ca.srl | 0 .../{container => nginx}/docker-registry.conf | 2 +- .../docker-registry.htpasswd | 0 .../{container => nginx}/nginx.conf | 0 docker-auth-registry/nginx/server-cert.pem | 19 +++++ docker-auth-registry/nginx/server-key.pem | 27 ++++++ docker-auth-registry/nginx/server.csr | 15 ++++ docker-auth-registry/registry.sh | 84 ------------------- .../dockerjava/api/model/ErrorDetail.java | 4 + .../dockerjava/api/model/ErrorResponse.java | 4 + 22 files changed, 177 insertions(+), 217 deletions(-) delete mode 100644 docker-auth-registry/container/ca-key.pem delete mode 100644 docker-auth-registry/container/ca.pem delete mode 100644 docker-auth-registry/container/server-cert.pem delete mode 100644 docker-auth-registry/container/server-key.pem delete mode 100644 docker-auth-registry/container/server.csr delete mode 100755 docker-auth-registry/container/start.sh create mode 100644 docker-auth-registry/fig.yml rename docker-auth-registry/{container => nginx}/Dockerfile (66%) create mode 100755 docker-auth-registry/nginx/build.sh create mode 100644 docker-auth-registry/nginx/ca-key.pem create mode 100644 docker-auth-registry/nginx/ca.pem rename docker-auth-registry/{container => nginx}/ca.srl (100%) rename docker-auth-registry/{container => nginx}/docker-registry.conf (83%) rename docker-auth-registry/{container => nginx}/docker-registry.htpasswd (100%) rename docker-auth-registry/{container => nginx}/nginx.conf (100%) create mode 100644 docker-auth-registry/nginx/server-cert.pem create mode 100644 docker-auth-registry/nginx/server-key.pem create mode 100644 docker-auth-registry/nginx/server.csr delete mode 100755 docker-auth-registry/registry.sh create mode 100644 src/main/java/com/github/dockerjava/api/model/ErrorDetail.java create mode 100644 src/main/java/com/github/dockerjava/api/model/ErrorResponse.java diff --git a/docker-auth-registry/README.md b/docker-auth-registry/README.md index 212ab92e..8a70b930 100644 --- a/docker-auth-registry/README.md +++ b/docker-auth-registry/README.md @@ -1,8 +1,18 @@ Set-up a Docker Registry with Plain Text Authentication -- - This creates a registry that runs locally with SSL and authentication set-up. - ./registry.sh +Pre-requisites, fig (on OS-X with Homebrew): + + brew install fig + +To build: + + fig up + +Test it works: + + curl https://localhost:5443/v1/users/ -k -f --basic --user registry:registry Based on . + diff --git a/docker-auth-registry/container/ca-key.pem b/docker-auth-registry/container/ca-key.pem deleted file mode 100644 index 1045c4b0..00000000 --- a/docker-auth-registry/container/ca-key.pem +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: DES-EDE3-CBC,3999A487D02FB784 - -itt2rZJ/o7LNUwOOQ7DBWkw1X6QH0KsPJyhGiz65+mBzs6o5MVNGfoP9n0BWczH9 -JROYfynKpucI7hCFoOf3315M2fdscJ4aJ2gZBSSDsK4vwUL+RWXf7qorY1iL4Xqg -niOg80qLKZTGwF0PxuIOHyfDqBhrmSG9prD7elsVGKB6sAC8Z+HvTrFsZ0+voIEJ -je81yEKO8uD8FP5nGeGE6BgLlNmkzbxL4lZjdrF7tkSkY+GzR937NzjHmNWbF5Vp -knVIv5Y0W9ptThkTwYxbWS/AUHgn7VLsOQGmkRvQbj/JJhVqFyBAyE4kN+foec1W -o8glNBIGGHvR3Fo2w2kWJ7uAWAQ4MfcJnWpN2I+EOQUo0Ojgr543F0XAjtr90480 -U0RatIxzc3eoRcVmh9+iD595zRe8gwJNfi6AEGrFx8aK5pCIdQI2/HNY3AR1v4gC -ZD+/meUM7krMBY4EVTKgS17dxPCQfwxj3hd5kvfde5Lg3JvZRKDEPFmF6T9CDI5d -0oG+w/usXCW8C+zOWtNRvrgJgp7SnNLriMIjPvAqrEEn/6tAFKfrVnEfjxnZt/ai -M7o8OdP9u5NRzQEgAUfhKeR/KNGN26ZFD0a0wVx3MCxEq2k9xs33nActtAb6rZM6 -c20IvGRxL1YWhfcPKDH4OpVk/zfORGLUNS6T9CGZgaMzKz/hd8L0wpJ/MKGbvpCh -dANutqKBWg4DwKDaL33Abo1OhFkCRoFPSs1GiBEcmSxcVa3loxaNpR4KFElbKrXy -I7NlCJG82stThm6NqxMUpRJNvUQaXz7P1x6RGnHMC84TE0gZPPezLToArcE41OTY -czB5PP3efz0r/PexZaFZPT98J4NgSV1mqTOXuBmIHKlnvyyEYq0Ytdi5RqWLECoK -KSAX/SYFFq+NqxcC5ua0hH5C6klv7qtmLJ5KfyHfpTNt2qScN7M9Kmd4v8CBiZOL -9KcKBKqhXRt3laSJyRI59s+pqvhDr1T2CGvFZ/8oGwhjGPIxKnr81AwAT3SwjqXQ -HKDKs+RwxZYRZuTtRCkBMHxxk/c+hrTbomAwfM3DiPZFMSk8n81WCjEoyY3FN2si -QSrJYAzu/Oga1jJPwhxLLbucGnQUGi94DSy+RAD4btGtSK6eN2rPo8Wwh/Vh8GHi -wXS5d+VIsFEAL70dYpkkQSE34ZjEpbcGOpx0YIgrsGG2c0BbmxiYzJhDHpSMWvQ+ -Zbly8Mp7c5YOCHVbnIvDi6LyK+Py3zucIjEa6T6sC9Jy28bfuQUegiBNerLI4Y0E -Txi5lcH1YD3AJIIWyW4Fub2TUBocYciZAs79vD0iRzAKgF9/4PGGTyVc0cdKIr6w -jUtQMQt0vPnqi4pgx1MuNxza5LEJ7O2tRkAs+SYGQu3uuWxtJsGsH72lJFzpj/rs -5Lo8TM/rjdwF0JtdSt+RmVa05BmUxPzP1K1vgu1wdq08iyJ2qme/g6cwBwICxjaX -50Pqh6WpFUUldJMU9jwljNlqumpTHmxlzbwLc5RWTmoBYth068HfnCQLbGnO+6zS -n/lJScYuMAiFmuugOVhwDKc5LzlVnrjVlapxRbas9nprupwzeBJKh6p2Jg/oqFRm ------END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/container/ca.pem b/docker-auth-registry/container/ca.pem deleted file mode 100644 index 7af686f6..00000000 --- a/docker-auth-registry/container/ca.pem +++ /dev/null @@ -1,24 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIEGDCCAwCgAwIBAgIJAJuxT3/GW0piMA0GCSqGSIb3DQEBBQUAMGUxCzAJBgNV -BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX -aWRnaXRzIFB0eSBMdGQxHjAcBgNVBAMTFWdsMDQzMjFtLmdhbWVzeXMuY29ycDAe -Fw0xNDExMDQyMDI4MzBaFw0xNTExMDQyMDI4MzBaMGUxCzAJBgNVBAYTAkFVMRMw -EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0 -eSBMdGQxHjAcBgNVBAMTFWdsMDQzMjFtLmdhbWVzeXMuY29ycDCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAM1VTVMAFSieoaFChrzMArR6la7SpDOXYRNo -PcW/BgpLEoq7SpqY5f5LAzq6ivAP8DwHSrnGIFNrn4Lf7OWhtAT4jLc7ZaTi2NXb -wQoTZUqnSeGjLJqTM5hLAjnxcvL0ZJyMTSbLL4ezbs1GePyTDi6VFiP1lI+mpytc -lVKsAJy8sW7rXRLSH3xliUQXUPR7I9I73pm0z+D/7R+hxN5EDYUPgXmsleUmiEJl -dhdaFeFxYjGox9RjCeXsl/xQ/GcYUxv93DdUwSpVCFE1OOOjuXlpcvoRBAbKBGmB -n5piD542NpandtRg7wJEfSVq9FR+nEcMRSSNfFKUAIqlzbcjcZsCAwEAAaOByjCB -xzAdBgNVHQ4EFgQUpRc8oWOtyJIg/fVn12SfhAvbl1gwgZcGA1UdIwSBjzCBjIAU -pRc8oWOtyJIg/fVn12SfhAvbl1ihaaRnMGUxCzAJBgNVBAYTAkFVMRMwEQYDVQQI -EwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQx -HjAcBgNVBAMTFWdsMDQzMjFtLmdhbWVzeXMuY29ycIIJAJuxT3/GW0piMAwGA1Ud -EwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADckZj0+Fz4Tp/Wv97deSigTIbDs -z8HhgcEo7lzyXCnGVkuMRr6DIpi+cULe7+NZh6+bEdB8Jc/pM8G3fZY9q2QSoTCA -EcNe1ctB0y/YrD66cDCzhWYFzTp+7B7/DlsMdqmeuPgpbhggpun8V7v+QhrvvKQz -CHCD1wOc61aM9jayGAH5uK7N25oiySY4F1okELbsjQ3y3vsfDed1yw1//Td8F2J7 -7geLpgAWrjHQ86Jx+7see1UuSaaIONTtNHD5K0zQQCIvcFi8OiAnEgWQTY4OayG0 -M5sDGFdi3/ba/ffG95Hb802fjQsQlUACKZk6Ni3FlwPWQVPzgU3jj/AFCtw= ------END CERTIFICATE----- diff --git a/docker-auth-registry/container/server-cert.pem b/docker-auth-registry/container/server-cert.pem deleted file mode 100644 index 5cdcd083..00000000 --- a/docker-auth-registry/container/server-cert.pem +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC+TCCAeECAQIwDQYJKoZIhvcNAQEFBQAwZTELMAkGA1UEBhMCQVUxEzARBgNV -BAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0 -ZDEeMBwGA1UEAxMVZ2wwNDMyMW0uZ2FtZXN5cy5jb3JwMB4XDTE0MTEwNDIwMjg0 -MFoXDTE1MTEwNDIwMjg0MFowIDEeMBwGA1UEAxMVZ2wwNDMyMW0uZ2FtZXN5cy5j -b3JwMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv/x+4myZH+OQlohG -PQGKWU7txx26LjQ8XAWlpER1HseZphWmPVRdDvpvU8qKR9GxWrX3FBZagwFR7deX -u2spCa1DDwFBy5ysEK2HxKEI1U/1t9QhM4IDlFdWEO2FiT1GDkF8jqr6xVDPVwot -zhLZFBUrNcEtsZAMpg3jpv8Pz89WHzP+M87eqgt8SYBK4yWgDt1qiAshQiF9XKA5 -HjwKSi0N86NjE+UTcGJ82lcCRTr3vnXHwPQicYY2sbawF6ZznzAbmPWrqIcfnkD/ -vvjtnHL29gHL4eb/Dk4OxYdNkADZDMwmZgyalPkTFFRY7reqLojoHCzgdW1UxbaA -LRav7wIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQCYNfq7ANSLfNPs43J/CCJ2SzfJ -elTvnYah9fdN9Bog9oTmk053wbLKJFv8xUlYZvSnnBFRP0CcBfJ/IFVe+/Pjk1cB -KrhbOT4pZKcA1gYFNEz2+DjM6caf7H8bsE2NFF9rlb05ys0P6mtqywxRDFVbyD42 -dNFZteP775sZDK7Bd9hNPnfter9KXDFi1j79jR3ZwalHOdVwOpeXZoieqoEIDbo5 -wgjuXsk0AyrERUWGL4/oQ91BhlK6OBtPNZ0SwjWBKECOZjf8RRZ49W9jZOPzRczj -JO0STwxfKFwEu2YJkdnlH2TdJF1+GsuukkjFeYc61lCp7jwakD9LfY55vhcy ------END CERTIFICATE----- diff --git a/docker-auth-registry/container/server-key.pem b/docker-auth-registry/container/server-key.pem deleted file mode 100644 index 92b3f8ca..00000000 --- a/docker-auth-registry/container/server-key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEAv/x+4myZH+OQlohGPQGKWU7txx26LjQ8XAWlpER1HseZphWm -PVRdDvpvU8qKR9GxWrX3FBZagwFR7deXu2spCa1DDwFBy5ysEK2HxKEI1U/1t9Qh -M4IDlFdWEO2FiT1GDkF8jqr6xVDPVwotzhLZFBUrNcEtsZAMpg3jpv8Pz89WHzP+ -M87eqgt8SYBK4yWgDt1qiAshQiF9XKA5HjwKSi0N86NjE+UTcGJ82lcCRTr3vnXH -wPQicYY2sbawF6ZznzAbmPWrqIcfnkD/vvjtnHL29gHL4eb/Dk4OxYdNkADZDMwm -ZgyalPkTFFRY7reqLojoHCzgdW1UxbaALRav7wIDAQABAoIBAQCeBD+XM5Uw1wep -ro5JJhxt93Xj/kbAQsQvZYJ5WtMfO1/ugEEsl2RksKGy0LDR/fjA1aaAhQmIbCy3 -20wKuV+0lEPudLVn1hMVQw7NO1He6Iow/Ms67tbtYJj5I9ZWJ/WiRCo17uqqPyH4 -3Orog0Dis62198MZM5wFjMcEK0kjW3HtovEvxRzCoMr9cgQ2qCN9L+W069lEinZC -LRcQlcxTuIzVRkQN7pxtGW+AGdX4fWzndMLdmJJce++jyIFfoev7KVzDqQFKJA+V -ceKa0/F8Jr0de1dUl06XhhfSibXBeimQIpVo6Bnd4wJs52gdvbqnF4ojOjPMuHmk -Bymx0VZBAoGBAN+IScCZ4FVsYbUsRWaNAB9G+idAZ6m3wiu+1xdYiFjGEjtHtiSc -XUT7Z3t/8mqL+4RgHq3+aBCUI6UaOQ0wmI+1q3JnngW4YG8LLEzqJjQoapsck/Hw -R83advxNraohdFqzti+NS+vmFQjAQozAH0z20pt2aTty4bgKDFzXmM5PAoGBANvf -Nw3liHBwnOKKLXBY/gyqWh2UPWoWte2cplVqC2TQjYA4sMA5bn/e26aeMQ+h9SzP -t53zhxxJXOk2XpQIbRwQygNzXmlQHLI1oGitd6Jm3wLRyABIIKfLZK3v3NOGsktu -qjInecUR27DW8ah33Q8+L0Ro4cMYQH30Dn8nSjxhAoGAC5Khxt/wllubH2cgXLPW -Gshw8RFLjKTf36Xsut+xh28RyJHo4zJZPdYKQIGaSlve9LaJQBbYymrxAX4/D+jB -LUeJjc3Bh6hJDda1P3Ir8i1Zf5hWLIN1JDo4SM24vQMoY/3D4+hb0uXBlwdlKqZT -uIda1gOmZRaIix+yDih3V88CgYAmw0mPd6IAQLpH7hhosCfJz9anVFUneO2GAJIK -iPGNSn9H1bbDjNyASqfqzgTUPrdcuRokDKULRZvNuboe2wVxZzxWM2a3ploIyQ+I -pNxskzpJ4vYhppWrP152k80YtayFQ/NZeEAtkCJtINfl3YvpfgsTQnJa1NG54ucT -X7fkwQKBgQDWhiZvB9YGaWGIwxUXR8eZtsilcMMwLWMr5YrYwfpZlb1Syxa8L32Y -Qyqx10b+0o+GcqhIoFc1YjjG7hgQkyYNtZ/weKAAZfNEdLA630oIva80NnoWTpYe -MuKRa2cQxeUmW1t5OoF63j6nZcTpR/AivBoBfdF4vSfF0tFB46N7qg== ------END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/container/server.csr b/docker-auth-registry/container/server.csr deleted file mode 100644 index d3ffd9c3..00000000 --- a/docker-auth-registry/container/server.csr +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN CERTIFICATE REQUEST----- -MIICZTCCAU0CAQAwIDEeMBwGA1UEAxMVZ2wwNDMyMW0uZ2FtZXN5cy5jb3JwMIIB -IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv/x+4myZH+OQlohGPQGKWU7t -xx26LjQ8XAWlpER1HseZphWmPVRdDvpvU8qKR9GxWrX3FBZagwFR7deXu2spCa1D -DwFBy5ysEK2HxKEI1U/1t9QhM4IDlFdWEO2FiT1GDkF8jqr6xVDPVwotzhLZFBUr -NcEtsZAMpg3jpv8Pz89WHzP+M87eqgt8SYBK4yWgDt1qiAshQiF9XKA5HjwKSi0N -86NjE+UTcGJ82lcCRTr3vnXHwPQicYY2sbawF6ZznzAbmPWrqIcfnkD/vvjtnHL2 -9gHL4eb/Dk4OxYdNkADZDMwmZgyalPkTFFRY7reqLojoHCzgdW1UxbaALRav7wID -AQABoAAwDQYJKoZIhvcNAQEFBQADggEBAB2R18mbz31Aov765hX3MgXrt9h5lmbs -bGjawK+wT3RffLgKWAIMg6IXfzpYVfMTZGu8j0xBnz388371GNix3zct0fGtdY5c -tcaT67zvCy4ubAnOkd8lKBZM2FNfg2BeyVp3wKCrYEr9aYKesZnFVMgfx30dC1eO -lB97fBSz6hdPIzOKqGpj6cf8g7GmpaL5AHx2NuPbBoHwMhFpvIUK1OvwcGooMTJC -vGBwqZqDQybFPBpxQRUfVGm8ZBwkQvw+ekxgzeknd133lIi+ciL3lrLn3AqIrs/5 -TtnKG5E+YXHPxKXpeP8paPDZl/wVJrqhxZqyNMJnAQmNVMxjTWFjJzY= ------END CERTIFICATE REQUEST----- diff --git a/docker-auth-registry/container/start.sh b/docker-auth-registry/container/start.sh deleted file mode 100755 index c12ea4ed..00000000 --- a/docker-auth-registry/container/start.sh +++ /dev/null @@ -1,8 +0,0 @@ -#! /bin/sh -set -eux - -docker-registry & -nginx - -wait - diff --git a/docker-auth-registry/fig.yml b/docker-auth-registry/fig.yml new file mode 100644 index 00000000..5b833325 --- /dev/null +++ b/docker-auth-registry/fig.yml @@ -0,0 +1,10 @@ +registry: + image: registry + ports: + - "5000:5000" +nginx: + build: nginx + ports: + - "443:8443" + links: + - registry diff --git a/docker-auth-registry/container/Dockerfile b/docker-auth-registry/nginx/Dockerfile similarity index 66% rename from docker-auth-registry/container/Dockerfile rename to docker-auth-registry/nginx/Dockerfile index 11407726..c425f4de 100644 --- a/docker-auth-registry/container/Dockerfile +++ b/docker-auth-registry/nginx/Dockerfile @@ -1,7 +1,4 @@ -FROM registry - -RUN apt-get update -RUN apt-get install -y nginx +FROM dockerfile/nginx ADD server-cert.pem /etc/ssl/certs/docker-registry ADD server-key.pem /etc/ssl/private/docker-registry @@ -11,8 +8,6 @@ ADD docker-registry.conf /etc/nginx/ ADD docker-registry.htpasswd /etc/nginx/ -EXPOSE 5443 - -ADD start.sh . +EXPOSE 443 -CMD ./start.sh +CMD nginx diff --git a/docker-auth-registry/nginx/build.sh b/docker-auth-registry/nginx/build.sh new file mode 100755 index 00000000..621ce740 --- /dev/null +++ b/docker-auth-registry/nginx/build.sh @@ -0,0 +1,27 @@ +#! /bin/sh +set -eu + + +echo "enter "registry" each time you are asked for a pass-phase" +echo "enter "registry" when requested for a common name" +echo "press enter for everything else" + +echo 01 > ca.srl +openssl genrsa -des3 -out ca-key.pem 2048 +openssl req -new -x509 -days 365 -key ca-key.pem -out ca.pem + +openssl genrsa -des3 -out server-key.pem 2048 +openssl req -subj "/CN=registry" -new -key server-key.pem -out server.csr +openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem -out server-cert.pem + +openssl rsa -in server-key.pem -out server-key.pem + +if [ "$(which boot2docker)" != "" ]; then + B=$(echo $DOCKER_HOST|sed 's/.*\/\(.*\):.*/\1/') + + scp -i ~/.ssh/id_boot2docker ca.pem docker@$B: + + echo "mkdir /etc/docker/certs.d/localhost:5443/" | boot2docker ssh + echo "cat ca.pem > /etc/docker/certs.d/localhost:5443/ca.crt" | boot2docker ssh +fi + diff --git a/docker-auth-registry/nginx/ca-key.pem b/docker-auth-registry/nginx/ca-key.pem new file mode 100644 index 00000000..39f7b194 --- /dev/null +++ b/docker-auth-registry/nginx/ca-key.pem @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: DES-EDE3-CBC,B5430D61BC639C5C + +16iWQsb9WQyDENfLqJcdF+KuER+0Bg51ZWBOam34z7iRLB3vDiULO718HVAXE+kL +IxA55utKPEkCT74CcUQ6+wlfEqXnBF3p3DPzBEVhLKdMKeciw4EzjCuV4+l+PKR4 +LEMT1NXUud8lzb2vej/HuXEObq2Pc9GTQBOQ/Y6hku4w+W9No4Dmo8jChAOquI5j +obkdsdMKtIu8SbsErbb8K0cngo6NaO/Jmn0E/VTVbDS7A8cn8NlGk59OfuhPP52d +qSegC/Ja3fCQZxuohrf+6UwlqEI4dlyqme1IKWEIXk3vCRy4zfMVpVzi6e2UXdyb +akU4lFCQbQEm1925m9poLqxkA2YXUr3e5KMJ1B6i40p5dWSgge8xpFQBXVFJo/Rf +rj//A5/ML/8LgZPvPtJqnLu3Z59naeGMwYkYscJGKMMfeOUKCtUwBWG3FbXX6Z8G +rlVeJ1YAU06sueur8BGbLbTtNU5i3ujQ2kb7k68CLGWMulY0a7jTLMHNTx6Mq/yH +xZly6hkfUsNjgAModLe6pt5CcoQbFptL+tWVRBMsvSr2P3NRQIoPRRgbvXw1mZ60 +v3FHukIXVczQ9J98GdIPgqDMFLPKL+AIbNarKnlv9hEyNgZ0D5Qu0+4DA1ITPfVy +nlGyKK46vHF4QqjSQXz7482FG8gduXfTW3O88HenQmyOt/AIllmlEm/940Ncv/xA +mgcvajhSTRmHq4JULKlzM2Beq3ABaa2FKFVh+8hZohhdxrt6BP59GhBq5/UKvjrt +6PGR46UzLvosjVRUDI7sxJQO+DWezdnNolKzw8doPmzkLqPKF4vHGKLU6tZ+KNCU +82CVJe+7X2+lgUs8mQVuQm4tTmKcNa3Yetpi+wG14OVx7Fobcl9uwPL2Kd7/23uQ +peS9dOyzN3IiMsuQaG/n6RyDFfFk64Algi2nW9m/s9CrZlzUhH78yzXxNex8fozs +KDV8n9KbGmtgBsdZC8uSg5+Luj7ri2xb0G2NFyNquCP17BvYkX02/xloWF8WKgCH +4SC/34wNCtu/OlVTRi5ujXZCm0D3U+pNv1xYdq5rJCUfjFtSCFRYRDRZ3wtLM1AS +UQmzGXHu64i+b0XjU2I8PvbUW39L5+/XZjdnbFcOQMVPlVjuh0AQNV5M5go3SVVi +Z+igAASkCvUyakb7LgmYhQjP/xyXa0EzIC5t9QoRkxbw3aWZMPKXA/g92lmDDZuj +IOPAgrFkms0CqYYApOrPoTCTtqx4+SdDP7HB+lFQ4v03552RhQBaZK2ukNcv6H6C +jP6iy6GQJzRWtpXv6lNCL2dg7qn39D5QhU61367MEFlF66v/oTX6RGSWgDeAWJW1 ++QhlCQUCDyNTpb2nkLg/BTrCEpRyq244pDjpFaIJ+MS3LOaGfJyXpOHMjvjWrX+l +EKxQTkuvlJKZLThS5sCejagmdB3DTgJpD/KvaAoaO77VHwSNvSQLA8CdnPiJ6NIg +Q+MUijW+yOPTSF4XE/x/AKg4aAFDthprayJ5u4gzDC568gkdQ034woWDQAHcNF4t +Dd+K/Go18mfo/1xyuBrXqUizkA2Dqe2tQMv9EwXsli4jywLJcqRhbA== +-----END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/nginx/ca.pem b/docker-auth-registry/nginx/ca.pem new file mode 100644 index 00000000..a63e6a8f --- /dev/null +++ b/docker-auth-registry/nginx/ca.pem @@ -0,0 +1,25 @@ +-----BEGIN CERTIFICATE----- +MIIEKjCCAxKgAwIBAgIJAICgl2R8Mq2nMA0GCSqGSIb3DQEBBQUAMGsxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQxJDAiBgNVBAMTG2FsZXgtY29sbGluc3MtbWFjYm9vay5s +b2NhbDAeFw0xNDExMDUyMTU5MzlaFw0xNTExMDUyMTU5MzlaMGsxCzAJBgNVBAYT +AkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRn +aXRzIFB0eSBMdGQxJDAiBgNVBAMTG2FsZXgtY29sbGluc3MtbWFjYm9vay5sb2Nh +bDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOQL3HUvUG5z0aa9C4ob +yh4xh2Xn7Ub0hroa+0VoJ0weplapYq6kRLnngEuHGv0yFps/abc/PndHCU1EUo7N +DmGPDFQ4AOBwymoZOjLHDnk7O76qL49tU9x7mnhqmcttaocTboR1g4c0a7AmgNjP +Da9jKkXP5WrgZeCdQD0azpTQiIVIbFLFYqzNArln8s/08RVW9OeRl5dqwGJIMMBy +DNEliBZEv7ZOBQOzyziwdNISl/PHtYvN45h6mQa4dcaVCU9EMdETfaJVGVQeXXn5 +u3QcnzSJEBnRi0hmQKhHgYXdxRRTraYc1/1nuZi99PVyyqC3zzJYOStbl5i18ZPf +5t0CAwEAAaOB0DCBzTAdBgNVHQ4EFgQUkPh8b4LHRL57tpA/ed6k4PTa+xEwgZ0G +A1UdIwSBlTCBkoAUkPh8b4LHRL57tpA/ed6k4PTa+xGhb6RtMGsxCzAJBgNVBAYT +AkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRn +aXRzIFB0eSBMdGQxJDAiBgNVBAMTG2FsZXgtY29sbGluc3MtbWFjYm9vay5sb2Nh +bIIJAICgl2R8Mq2nMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAFyw +TkjUuVELHPZUt25h1K5Ja20E55ELwu+GaVtPKLK4qCXEEkESKmuNuwJQ//IPkvZ1 +b63/DJeeh8pF9Zia7hrBe1wj5OZ9KqzvFOzTdomLycGPRCh7p/ZUf8f3mVgSLOxZ +gCqbY2Mau3ve7SUB4dkE6wuYeDPjotlSZor4wiobCBuViJj4Z//434vwUh5eNiVv +JS5HCHVsrneN7YNx4FfWSMWjShSNBT4ltSE6yLkuWrSRlmZknWG1wyXQBZj3HqnB +/AcTt2VaGdxuEpXjjE7+sW5YwDtDSOwFqhPdwtUg7iogCUxpc3pwm8ZuLZ7a027Y +wtpHzs0SxSD5yK9eHOU= +-----END CERTIFICATE----- diff --git a/docker-auth-registry/container/ca.srl b/docker-auth-registry/nginx/ca.srl similarity index 100% rename from docker-auth-registry/container/ca.srl rename to docker-auth-registry/nginx/ca.srl diff --git a/docker-auth-registry/container/docker-registry.conf b/docker-auth-registry/nginx/docker-registry.conf similarity index 83% rename from docker-auth-registry/container/docker-registry.conf rename to docker-auth-registry/nginx/docker-registry.conf index 6173e5ca..0e7e368f 100644 --- a/docker-auth-registry/container/docker-registry.conf +++ b/docker-auth-registry/nginx/docker-registry.conf @@ -1,4 +1,4 @@ -proxy_pass http://docker-registry; +proxy_pass http://registry; proxy_set_header Host $http_host; # required for docker client's sake proxy_set_header X-Real-IP $remote_addr; # pass on real client's IP proxy_set_header Authorization ""; # see https://github.com/dotcloud/docker-registry/issues/170 diff --git a/docker-auth-registry/container/docker-registry.htpasswd b/docker-auth-registry/nginx/docker-registry.htpasswd similarity index 100% rename from docker-auth-registry/container/docker-registry.htpasswd rename to docker-auth-registry/nginx/docker-registry.htpasswd diff --git a/docker-auth-registry/container/nginx.conf b/docker-auth-registry/nginx/nginx.conf similarity index 100% rename from docker-auth-registry/container/nginx.conf rename to docker-auth-registry/nginx/nginx.conf diff --git a/docker-auth-registry/nginx/server-cert.pem b/docker-auth-registry/nginx/server-cert.pem new file mode 100644 index 00000000..58b7e0ce --- /dev/null +++ b/docker-auth-registry/nginx/server-cert.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDBTCCAe0CAQIwDQYJKoZIhvcNAQEFBQAwazELMAkGA1UEBhMCQVUxEzARBgNV +BAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0 +ZDEkMCIGA1UEAxMbYWxleC1jb2xsaW5zcy1tYWNib29rLmxvY2FsMB4XDTE0MTEw +NTIxNTk0OVoXDTE1MTEwNTIxNTk0OVowJjEkMCIGA1UEAxMbYWxleC1jb2xsaW5z +cy1tYWNib29rLmxvY2FsMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA +4ksN/P+TQHbN7tKSmAUTa83UPPc3MyGM6aqC/wSjoWNUL19oeGKAGL3+5UfAeN/W +wXkwuu8yceyA7n7965UEOAiF8hr63hyxBCC+MsC6v8hOz/nV0FJAxJXttrznp/KY +228Hv4p9twnaX8BH45dLBfXb/jmnHl8n1epQkDFNGTIqxqtZLqiB+TdxXr1BgIQ0 +R6JmEf348lmC6pQ2Kk1Psmfu1H64p7UGlDzfOIBhm+NXHcE02F2RbgcaR1KBGPLB +HRGiAa88vf5wSqwDLBdvbD1tyJfyS7tpm6wNpZJMwQJC5bsNwzd7eU76xJBm7QcH +uj2bcr8c9utFbtkfNhRYMwIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQARO2RHZ7yh +TcRzPYvG2qFPO/mY0sHqFbZ8bVYrgAcaUIzSdZspQx4DeZzjMBnbHbLtFCBK9nHU +h1ZwxPiu9hyDiEpKtW/tCa4A72I1zDL9PIm5iBFZMg33I6OpHYXEYqhiwv/GctOg +xlzAC9YDbyIG34s+3ZTCLMZHi/PZJWkp5gLOfCr16cmu5acdPubeQEzSWDs7HNOb +DTeK9SoUHSoIjzbipTmnp/3mhTy7xQdmePEuqRHU5QxEsL5zua8O+JkcgSnllYCL +y9MmbRkb7WuP2jen926C7HCJ61UtgSHRlrWD3Bd/jrZja/9Fm/NKVye30fSb9mP2 +I1q7NhGfpkxk +-----END CERTIFICATE----- diff --git a/docker-auth-registry/nginx/server-key.pem b/docker-auth-registry/nginx/server-key.pem new file mode 100644 index 00000000..ba378d81 --- /dev/null +++ b/docker-auth-registry/nginx/server-key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEA4ksN/P+TQHbN7tKSmAUTa83UPPc3MyGM6aqC/wSjoWNUL19o +eGKAGL3+5UfAeN/WwXkwuu8yceyA7n7965UEOAiF8hr63hyxBCC+MsC6v8hOz/nV +0FJAxJXttrznp/KY228Hv4p9twnaX8BH45dLBfXb/jmnHl8n1epQkDFNGTIqxqtZ +LqiB+TdxXr1BgIQ0R6JmEf348lmC6pQ2Kk1Psmfu1H64p7UGlDzfOIBhm+NXHcE0 +2F2RbgcaR1KBGPLBHRGiAa88vf5wSqwDLBdvbD1tyJfyS7tpm6wNpZJMwQJC5bsN +wzd7eU76xJBm7QcHuj2bcr8c9utFbtkfNhRYMwIDAQABAoIBAHectoMhUGNFqOpw +sX3bSP21qVakUbAcLtCgCWfkut0mlKwJoT3oys7JNr9YotsBbhGMDn7wylg/a5Mk +2vC4LqezkaF8M1hOEB8fc4l+J/gRV99ErojTwVpn6WOrDEPQzo1GbfEHshWbBquQ +Bi+9m7FF2IfTT4uVPogqt3TQKnGC/XdYZSc1DOxxH66sesIBYoIG/MpaH3zYw+tI +aW3kOYbYZKmJKBk05XOLlS2T9Jlf0GgDyG+4/Dz3TRvJV2KwB/SH+CUDss+vT2ud +ahJ/fP1oDJYtBDY+IfcY1cOGWD8v5XD3tTTZ+kCFW2080EoAngeupf1m9mR1ETi4 +xs/NxqkCgYEA8m+bcjeeUbZw2ngMRRA+VJf8sAH9HanG2+gEAax8xPXz8O42FuLq +8ex25VpxOPg+8/orcrTgCfkM4CoNV/9PPyMbQRwGMigkEg76MD/dvFmyW2mMRape +hat3Ld+NxG/cuTYPSWa4RtFaMovTwPPIvkjJNK4GGrJmzPchGj9wNd8CgYEA7vQ8 +SnBCBQhXi4tIPF3bFU44WqE9yf2sJmC3y738PIa+FqRfdIgDal6l70a3dZMyNkhO +EFRUDIIoSfNdc1Nywglz3VTeFM93GKYPtbuJDPda1jMT2Evi9bWzYO9OKV9i4rze +WdQ+l+idbJ36tNYgVaoHNx/KhHpWCJzkFwVBIC0CgYBJEDex0W9GQwx52uofukh+ +qBuAU+kbknoa9i6W7ovftBwjhTcJ6LNT26btcjdjKvWWA9QqSramasdlm2bQGWKh +rYveMHrxjMVqJ9dgyS6jQAkPoZyjtjesY0OUsKYCCJBlxRQQVAO/XAKp7xgPM6lR +J5Bz7upqC1AN/4Cbb3j60wKBgQCqTT86/k7PL2bVeWr+OxYNVTYswYY8E6NBpuTX +PIwsxwtrL7MoZleo09QHeKsADOxYa6fXU4Kjd5AnRF9x9iNvzzTYpcexpTsIQjIo +H4RJzXDcAINAQLV80QcLKwLV0bm0R09hTjdeJNcttlob0BAzfX6u9uVrDZWLheW5 +0nDb8QKBgFcgD84A2xcunL+ZLtZ5YwyY3PPCoU3hDnHT2ZFz7H74rthLv/RXTmX0 +BM/ZUVHKeLPzgXyxR0kpojDkVfx8q8Ncz8xZse+TTX1Lk3HGJIFS40gnvTaUc+4I +bpzH7lRdjEuAAK+fDYZa8pEeep6y9tVEa38RrL09F7+XDBuvLY2b +-----END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/nginx/server.csr b/docker-auth-registry/nginx/server.csr new file mode 100644 index 00000000..7d7c16bd --- /dev/null +++ b/docker-auth-registry/nginx/server.csr @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICazCCAVMCAQAwJjEkMCIGA1UEAxMbYWxleC1jb2xsaW5zcy1tYWNib29rLmxv +Y2FsMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4ksN/P+TQHbN7tKS +mAUTa83UPPc3MyGM6aqC/wSjoWNUL19oeGKAGL3+5UfAeN/WwXkwuu8yceyA7n79 +65UEOAiF8hr63hyxBCC+MsC6v8hOz/nV0FJAxJXttrznp/KY228Hv4p9twnaX8BH +45dLBfXb/jmnHl8n1epQkDFNGTIqxqtZLqiB+TdxXr1BgIQ0R6JmEf348lmC6pQ2 +Kk1Psmfu1H64p7UGlDzfOIBhm+NXHcE02F2RbgcaR1KBGPLBHRGiAa88vf5wSqwD +LBdvbD1tyJfyS7tpm6wNpZJMwQJC5bsNwzd7eU76xJBm7QcHuj2bcr8c9utFbtkf +NhRYMwIDAQABoAAwDQYJKoZIhvcNAQEFBQADggEBAA0ZWAcEwZjSlZnf13qzg9C/ +1PIvb4h4Wz2oADHHmszvd+Ze8qUaqin1Ds56gh/tlMomJPxjXUgxW4Y2sg2a3981 +g7C5rtp6Us/2erEKuZUpeQCc36UeCaF9jmWUtmVRo1hMNn3FKlTECQyApVWo9kWW +Sr1RZMuYbxkmD+ZuBXspM2BrRLFwUaBhpGeukORG7cYE2SSbdYVFX85Te4una/+L +Z0WcWDyzSy4MnsSLjMILWV3RhvXkL7ASA/dOnA7+d50GATIYwwpYKte9GzKZfUH/ +ADa1y47ZsJOtBn1cS4HOzWBHqao6WF7mcENE9UQtfPhU3IUmLgeypki47ZNqyGw= +-----END CERTIFICATE REQUEST----- diff --git a/docker-auth-registry/registry.sh b/docker-auth-registry/registry.sh deleted file mode 100755 index 91ea9d53..00000000 --- a/docker-auth-registry/registry.sh +++ /dev/null @@ -1,84 +0,0 @@ -#! /bin/sh -set -eu - -function build() { - echo "building..." - if [ ! -e done ]; then - echo "enter dockerjava each time you are asked for a pass-phase" - H=$(hostname) - echo "enter $H when requested for a common name" - echo "press enter for everything else" - - echo 01 > ca.srl - openssl genrsa -des3 -out ca-key.pem 2048 - openssl req -new -x509 -days 365 -key ca-key.pem -out ca.pem - - openssl genrsa -des3 -out server-key.pem 2048 - openssl req -subj "/CN=$H" -new -key server-key.pem -out server.csr - openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem -out server-cert.pem - - openssl rsa -in server-key.pem -out server-key.pem - - if [ "$(which boot2docker)" != "" ]; then - B=$(echo $DOCKER_HOST|sed 's/.*\/\(.*\):.*/\1/') - - scp -i ~/.ssh/id_boot2docker ca.pem docker@$B: - - echo "mkdir /etc/docker/certs.d/localhost:5443/" | boot2docker ssh - echo "cat ca.pem > /etc/docker/certs.d/localhost:5443/ca.crt" | boot2docker ssh - fi - - touch done - fi - - docker build -t auth-registry . - - if [ "$(which boot2docker)" != "" ]; then - VBoxManage controlvm boot2docker-vm natpf1 "5443,tcp,127.0.0.1,5443,,5443" || true - fi -} - -function start() { - echo "starting..." - docker run -P -p 5443:5443 -d auth-registry - sleep 2s -} - -function stop() { - PS=$(docker ps|grep auth-registry|awk '{print $1}') - if [ "" != "$PS" ]; then - echo "stopping..." - docker kill $PS - fi - if [ "$(which boot2docker)" != "" ]; then - VBoxManage controlvm boot2docker-vm natpf1 delete 5443 || true - fi -} - -function testIt() { - echo "testing..." - curl https://localhost:5443/v1/_ping -f -k - echo - curl https://localhost:5443/v1/users/ -k -f --basic --user dockerjava:dockerjava - echo -} - -C=${1:-''} - -cd container - -case $C in - build) build ;; - start) start ;; - stop) stop ;; - test) testIt ;; - '') - stop - build - start - testIt - ;; - *) - echo "$(basename $0) (build|start|stop|test)" -esac - diff --git a/src/main/java/com/github/dockerjava/api/model/ErrorDetail.java b/src/main/java/com/github/dockerjava/api/model/ErrorDetail.java new file mode 100644 index 00000000..bc9b9bba --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/ErrorDetail.java @@ -0,0 +1,4 @@ +package com.github.dockerjava.api.model; + +public class ErrorDetail { +} diff --git a/src/main/java/com/github/dockerjava/api/model/ErrorResponse.java b/src/main/java/com/github/dockerjava/api/model/ErrorResponse.java new file mode 100644 index 00000000..9993d215 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/ErrorResponse.java @@ -0,0 +1,4 @@ +package com.github.dockerjava.api.model; + +public class ErrorResponse { +} From 1ad712e14e65bdba534c799467db0cda335916a2 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sat, 8 Nov 2014 23:26:30 +0000 Subject: [PATCH 199/452] 1 --- docker-auth-registry/nginx/build.sh | 14 ++---- docker-auth-registry/nginx/ca-key.pem | 30 ----------- docker-auth-registry/nginx/ca.pem | 42 ++++++++-------- docker-auth-registry/nginx/ca.srl | 2 +- .../nginx/docker-registry.htpasswd | 2 +- docker-auth-registry/nginx/server-cert.pem | 31 ++++++------ docker-auth-registry/nginx/server-key.pem | 50 +++++++++---------- docker-auth-registry/nginx/server.csr | 26 +++++----- 8 files changed, 78 insertions(+), 119 deletions(-) diff --git a/docker-auth-registry/nginx/build.sh b/docker-auth-registry/nginx/build.sh index 621ce740..3b2158e8 100755 --- a/docker-auth-registry/nginx/build.sh +++ b/docker-auth-registry/nginx/build.sh @@ -3,9 +3,11 @@ set -eu echo "enter "registry" each time you are asked for a pass-phase" -echo "enter "registry" when requested for a common name" +echo "enter "nginx" when requested for a common name" echo "press enter for everything else" +htpasswd -bc docker-registry.htpasswd registry registry + echo 01 > ca.srl openssl genrsa -des3 -out ca-key.pem 2048 openssl req -new -x509 -days 365 -key ca-key.pem -out ca.pem @@ -15,13 +17,3 @@ openssl req -subj "/CN=registry" -new -key server-key.pem -out server.csr openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem -out server-cert.pem openssl rsa -in server-key.pem -out server-key.pem - -if [ "$(which boot2docker)" != "" ]; then - B=$(echo $DOCKER_HOST|sed 's/.*\/\(.*\):.*/\1/') - - scp -i ~/.ssh/id_boot2docker ca.pem docker@$B: - - echo "mkdir /etc/docker/certs.d/localhost:5443/" | boot2docker ssh - echo "cat ca.pem > /etc/docker/certs.d/localhost:5443/ca.crt" | boot2docker ssh -fi - diff --git a/docker-auth-registry/nginx/ca-key.pem b/docker-auth-registry/nginx/ca-key.pem index 39f7b194..e69de29b 100644 --- a/docker-auth-registry/nginx/ca-key.pem +++ b/docker-auth-registry/nginx/ca-key.pem @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: DES-EDE3-CBC,B5430D61BC639C5C - -16iWQsb9WQyDENfLqJcdF+KuER+0Bg51ZWBOam34z7iRLB3vDiULO718HVAXE+kL -IxA55utKPEkCT74CcUQ6+wlfEqXnBF3p3DPzBEVhLKdMKeciw4EzjCuV4+l+PKR4 -LEMT1NXUud8lzb2vej/HuXEObq2Pc9GTQBOQ/Y6hku4w+W9No4Dmo8jChAOquI5j -obkdsdMKtIu8SbsErbb8K0cngo6NaO/Jmn0E/VTVbDS7A8cn8NlGk59OfuhPP52d -qSegC/Ja3fCQZxuohrf+6UwlqEI4dlyqme1IKWEIXk3vCRy4zfMVpVzi6e2UXdyb -akU4lFCQbQEm1925m9poLqxkA2YXUr3e5KMJ1B6i40p5dWSgge8xpFQBXVFJo/Rf -rj//A5/ML/8LgZPvPtJqnLu3Z59naeGMwYkYscJGKMMfeOUKCtUwBWG3FbXX6Z8G -rlVeJ1YAU06sueur8BGbLbTtNU5i3ujQ2kb7k68CLGWMulY0a7jTLMHNTx6Mq/yH -xZly6hkfUsNjgAModLe6pt5CcoQbFptL+tWVRBMsvSr2P3NRQIoPRRgbvXw1mZ60 -v3FHukIXVczQ9J98GdIPgqDMFLPKL+AIbNarKnlv9hEyNgZ0D5Qu0+4DA1ITPfVy -nlGyKK46vHF4QqjSQXz7482FG8gduXfTW3O88HenQmyOt/AIllmlEm/940Ncv/xA -mgcvajhSTRmHq4JULKlzM2Beq3ABaa2FKFVh+8hZohhdxrt6BP59GhBq5/UKvjrt -6PGR46UzLvosjVRUDI7sxJQO+DWezdnNolKzw8doPmzkLqPKF4vHGKLU6tZ+KNCU -82CVJe+7X2+lgUs8mQVuQm4tTmKcNa3Yetpi+wG14OVx7Fobcl9uwPL2Kd7/23uQ -peS9dOyzN3IiMsuQaG/n6RyDFfFk64Algi2nW9m/s9CrZlzUhH78yzXxNex8fozs -KDV8n9KbGmtgBsdZC8uSg5+Luj7ri2xb0G2NFyNquCP17BvYkX02/xloWF8WKgCH -4SC/34wNCtu/OlVTRi5ujXZCm0D3U+pNv1xYdq5rJCUfjFtSCFRYRDRZ3wtLM1AS -UQmzGXHu64i+b0XjU2I8PvbUW39L5+/XZjdnbFcOQMVPlVjuh0AQNV5M5go3SVVi -Z+igAASkCvUyakb7LgmYhQjP/xyXa0EzIC5t9QoRkxbw3aWZMPKXA/g92lmDDZuj -IOPAgrFkms0CqYYApOrPoTCTtqx4+SdDP7HB+lFQ4v03552RhQBaZK2ukNcv6H6C -jP6iy6GQJzRWtpXv6lNCL2dg7qn39D5QhU61367MEFlF66v/oTX6RGSWgDeAWJW1 -+QhlCQUCDyNTpb2nkLg/BTrCEpRyq244pDjpFaIJ+MS3LOaGfJyXpOHMjvjWrX+l -EKxQTkuvlJKZLThS5sCejagmdB3DTgJpD/KvaAoaO77VHwSNvSQLA8CdnPiJ6NIg -Q+MUijW+yOPTSF4XE/x/AKg4aAFDthprayJ5u4gzDC568gkdQ034woWDQAHcNF4t -Dd+K/Go18mfo/1xyuBrXqUizkA2Dqe2tQMv9EwXsli4jywLJcqRhbA== ------END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/nginx/ca.pem b/docker-auth-registry/nginx/ca.pem index a63e6a8f..5d13a8a8 100644 --- a/docker-auth-registry/nginx/ca.pem +++ b/docker-auth-registry/nginx/ca.pem @@ -1,25 +1,23 @@ -----BEGIN CERTIFICATE----- -MIIEKjCCAxKgAwIBAgIJAICgl2R8Mq2nMA0GCSqGSIb3DQEBBQUAMGsxCzAJBgNV +MIID5jCCAs6gAwIBAgIJAMKZlxOyqvJlMA0GCSqGSIb3DQEBBQUAMFUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX -aWRnaXRzIFB0eSBMdGQxJDAiBgNVBAMTG2FsZXgtY29sbGluc3MtbWFjYm9vay5s -b2NhbDAeFw0xNDExMDUyMTU5MzlaFw0xNTExMDUyMTU5MzlaMGsxCzAJBgNVBAYT -AkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRn -aXRzIFB0eSBMdGQxJDAiBgNVBAMTG2FsZXgtY29sbGluc3MtbWFjYm9vay5sb2Nh -bDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOQL3HUvUG5z0aa9C4ob -yh4xh2Xn7Ub0hroa+0VoJ0weplapYq6kRLnngEuHGv0yFps/abc/PndHCU1EUo7N -DmGPDFQ4AOBwymoZOjLHDnk7O76qL49tU9x7mnhqmcttaocTboR1g4c0a7AmgNjP -Da9jKkXP5WrgZeCdQD0azpTQiIVIbFLFYqzNArln8s/08RVW9OeRl5dqwGJIMMBy -DNEliBZEv7ZOBQOzyziwdNISl/PHtYvN45h6mQa4dcaVCU9EMdETfaJVGVQeXXn5 -u3QcnzSJEBnRi0hmQKhHgYXdxRRTraYc1/1nuZi99PVyyqC3zzJYOStbl5i18ZPf -5t0CAwEAAaOB0DCBzTAdBgNVHQ4EFgQUkPh8b4LHRL57tpA/ed6k4PTa+xEwgZ0G -A1UdIwSBlTCBkoAUkPh8b4LHRL57tpA/ed6k4PTa+xGhb6RtMGsxCzAJBgNVBAYT -AkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRn -aXRzIFB0eSBMdGQxJDAiBgNVBAMTG2FsZXgtY29sbGluc3MtbWFjYm9vay5sb2Nh -bIIJAICgl2R8Mq2nMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAFyw -TkjUuVELHPZUt25h1K5Ja20E55ELwu+GaVtPKLK4qCXEEkESKmuNuwJQ//IPkvZ1 -b63/DJeeh8pF9Zia7hrBe1wj5OZ9KqzvFOzTdomLycGPRCh7p/ZUf8f3mVgSLOxZ -gCqbY2Mau3ve7SUB4dkE6wuYeDPjotlSZor4wiobCBuViJj4Z//434vwUh5eNiVv -JS5HCHVsrneN7YNx4FfWSMWjShSNBT4ltSE6yLkuWrSRlmZknWG1wyXQBZj3HqnB -/AcTt2VaGdxuEpXjjE7+sW5YwDtDSOwFqhPdwtUg7iogCUxpc3pwm8ZuLZ7a027Y -wtpHzs0SxSD5yK9eHOU= +aWRnaXRzIFB0eSBMdGQxDjAMBgNVBAMTBW5naW54MB4XDTE0MTEwODIzMjQyMFoX +DTE1MTEwODIzMjQyMFowVTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3Rh +dGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEOMAwGA1UEAxMF +bmdpbngwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9uw9QacXEkB+C +QNYVPFhL3UrpiLSnNSe8pdyFNgeQ4kqhKmI5dteOG1B8v1gEDNn+sJbWoRtQbNaI +ksyr6NmfFWL3vdYDypgY74cnoVJ3OHHsGBT/MMs540jc9MgfqzlSy98Gr8Eq+Bfa +q/hS+QzuI3tI3/t20B0Pfrs4VLCydG/ZbR1CXpRBzkMl5sKQ+fQZjT3SwE0BHdn8 +EC5rSH2tHGWgm/BIZvQm7o82wv7w46ksDbuZpfhv5vg914/3aa7GPcKGNF6+LALz +omycIP3X62jpsjxohn5sICBSLpm2kSL+MqK0k61EeGVeDwgTYThORaYk/wv/QJ/4 +JNlQ104TAgMBAAGjgbgwgbUwHQYDVR0OBBYEFLQ2Pok5e+v1E2w/f4r24Jr/vAwO +MIGFBgNVHSMEfjB8gBS0Nj6JOXvr9RNsP3+K9uCa/7wMDqFZpFcwVTELMAkGA1UE +BhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdp +ZGdpdHMgUHR5IEx0ZDEOMAwGA1UEAxMFbmdpbniCCQDCmZcTsqryZTAMBgNVHRME +BTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQC6XuA41OvXO4+l39ElKFRjKSdknL6v +kU3mjo6frgW1Vt5MJzAUuwGwGAMum/+62mv//HvbJVUhbyxkk1Iq0gChofOMMyto +I8aEeqWgubMBQJMZUQFVZr2Ye3zEZpeVwezg5RS5M74H2OqCuDwzMHo3vpXAuMrF +Sr1jCB5pMwd6kED5sOteo0pW+etgZRKg+d9IaoE5sDmFghNfaLH+ZzIHJknOarPI +1ZKt+Xa6MQWeqdez4JDGtAyL4Ujv34BHypNnFmmEZRRaJaPaO9Pi2AEOlEyzsBTk +UgPv0Oa4QA8NqRCDF621tHmmBnaINox1AORh3UVuYHXvs7DnsQK2vXmF -----END CERTIFICATE----- diff --git a/docker-auth-registry/nginx/ca.srl b/docker-auth-registry/nginx/ca.srl index 9e22bcb8..8a0f05e1 100644 --- a/docker-auth-registry/nginx/ca.srl +++ b/docker-auth-registry/nginx/ca.srl @@ -1 +1 @@ -02 +01 diff --git a/docker-auth-registry/nginx/docker-registry.htpasswd b/docker-auth-registry/nginx/docker-registry.htpasswd index 8288b160..29d18b5d 100644 --- a/docker-auth-registry/nginx/docker-registry.htpasswd +++ b/docker-auth-registry/nginx/docker-registry.htpasswd @@ -1 +1 @@ -dockerjava:$apr1$9s.aEJml$nivZMa6GEWnJA/FhpTPbj0 +registry:$apr1$7T1Nc0O5$KtMdxpRxf7D2B25.k4n8c0 diff --git a/docker-auth-registry/nginx/server-cert.pem b/docker-auth-registry/nginx/server-cert.pem index 58b7e0ce..8e7b1ab3 100644 --- a/docker-auth-registry/nginx/server-cert.pem +++ b/docker-auth-registry/nginx/server-cert.pem @@ -1,19 +1,18 @@ -----BEGIN CERTIFICATE----- -MIIDBTCCAe0CAQIwDQYJKoZIhvcNAQEFBQAwazELMAkGA1UEBhMCQVUxEzARBgNV +MIIC3DCCAcQCAQIwDQYJKoZIhvcNAQEFBQAwVTELMAkGA1UEBhMCQVUxEzARBgNV BAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0 -ZDEkMCIGA1UEAxMbYWxleC1jb2xsaW5zcy1tYWNib29rLmxvY2FsMB4XDTE0MTEw -NTIxNTk0OVoXDTE1MTEwNTIxNTk0OVowJjEkMCIGA1UEAxMbYWxleC1jb2xsaW5z -cy1tYWNib29rLmxvY2FsMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA -4ksN/P+TQHbN7tKSmAUTa83UPPc3MyGM6aqC/wSjoWNUL19oeGKAGL3+5UfAeN/W -wXkwuu8yceyA7n7965UEOAiF8hr63hyxBCC+MsC6v8hOz/nV0FJAxJXttrznp/KY -228Hv4p9twnaX8BH45dLBfXb/jmnHl8n1epQkDFNGTIqxqtZLqiB+TdxXr1BgIQ0 -R6JmEf348lmC6pQ2Kk1Psmfu1H64p7UGlDzfOIBhm+NXHcE02F2RbgcaR1KBGPLB -HRGiAa88vf5wSqwDLBdvbD1tyJfyS7tpm6wNpZJMwQJC5bsNwzd7eU76xJBm7QcH -uj2bcr8c9utFbtkfNhRYMwIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQARO2RHZ7yh -TcRzPYvG2qFPO/mY0sHqFbZ8bVYrgAcaUIzSdZspQx4DeZzjMBnbHbLtFCBK9nHU -h1ZwxPiu9hyDiEpKtW/tCa4A72I1zDL9PIm5iBFZMg33I6OpHYXEYqhiwv/GctOg -xlzAC9YDbyIG34s+3ZTCLMZHi/PZJWkp5gLOfCr16cmu5acdPubeQEzSWDs7HNOb -DTeK9SoUHSoIjzbipTmnp/3mhTy7xQdmePEuqRHU5QxEsL5zua8O+JkcgSnllYCL -y9MmbRkb7WuP2jen926C7HCJ61UtgSHRlrWD3Bd/jrZja/9Fm/NKVye30fSb9mP2 -I1q7NhGfpkxk +ZDEOMAwGA1UEAxMFbmdpbngwHhcNMTQxMTA4MjMyNDI2WhcNMTUxMTA4MjMyNDI2 +WjATMREwDwYDVQQDEwhyZWdpc3RyeTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC +AQoCggEBALngTSPRHqI1BDVzj3zD6gnFdfBVVLHkWdjH7cD6XI44xDTPOQvefzw0 +Io+Dh2AuS1cqjEWpM5sS0sN4790Nm3EFC6GYa4wINxekEmc57ANOYoo/29PHHjKz +hIV0kZy5uNCcv+rPzAFofJSR8qNI8wT169fTeTLv8ooB588NdDWKMX7CsGDy3kTz +dWw8tUpn0iv8MNspPcu+u1LTe0jiucOv64mQtr3VhL0fVnCSse+qZQ+qrOXcSNIw +CBhmrppaJ0Cu8gpUM0eS8cYm4sfMUpntY1z3ktZ+48WO8/s4L0FADTbAtwLWZr0G +gtLYJjNi0cdpoDBB/hh6L1CGiutGEB8CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA +ghLkKO99yjoMV/UozhAd1mOLiMecgxT3PfURBECnwghnr1AtvZR0XDmvx18wqSdV +fgK9Bkm4oCD9jwZdeaKoUrkUeeFK5rftahLOQhvNfmRGhk6CtS101YVcQkpS8xE/ +HfXNLaHS9eofAky/DLiVxzl2NIScMooCIaCjl/AXChDC3UmtlewoEUCAow8DzKwt +SXcdc6OlpPXW+9TGhTjnweK4tuehQIQTCT6F6Fr9kpgSlCZ+P2Mwp9AJfh0zbBGs +zEukHeY9RHl5cppF/pHeNFikOO2V5iZ0XrdRwcMqjUmCJKphO+2+pR0buAjwBWHU +vDAL1d0OWPT7tSzm4g1m6A== -----END CERTIFICATE----- diff --git a/docker-auth-registry/nginx/server-key.pem b/docker-auth-registry/nginx/server-key.pem index ba378d81..69dbf5a6 100644 --- a/docker-auth-registry/nginx/server-key.pem +++ b/docker-auth-registry/nginx/server-key.pem @@ -1,27 +1,27 @@ -----BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA4ksN/P+TQHbN7tKSmAUTa83UPPc3MyGM6aqC/wSjoWNUL19o -eGKAGL3+5UfAeN/WwXkwuu8yceyA7n7965UEOAiF8hr63hyxBCC+MsC6v8hOz/nV -0FJAxJXttrznp/KY228Hv4p9twnaX8BH45dLBfXb/jmnHl8n1epQkDFNGTIqxqtZ -LqiB+TdxXr1BgIQ0R6JmEf348lmC6pQ2Kk1Psmfu1H64p7UGlDzfOIBhm+NXHcE0 -2F2RbgcaR1KBGPLBHRGiAa88vf5wSqwDLBdvbD1tyJfyS7tpm6wNpZJMwQJC5bsN -wzd7eU76xJBm7QcHuj2bcr8c9utFbtkfNhRYMwIDAQABAoIBAHectoMhUGNFqOpw -sX3bSP21qVakUbAcLtCgCWfkut0mlKwJoT3oys7JNr9YotsBbhGMDn7wylg/a5Mk -2vC4LqezkaF8M1hOEB8fc4l+J/gRV99ErojTwVpn6WOrDEPQzo1GbfEHshWbBquQ -Bi+9m7FF2IfTT4uVPogqt3TQKnGC/XdYZSc1DOxxH66sesIBYoIG/MpaH3zYw+tI -aW3kOYbYZKmJKBk05XOLlS2T9Jlf0GgDyG+4/Dz3TRvJV2KwB/SH+CUDss+vT2ud -ahJ/fP1oDJYtBDY+IfcY1cOGWD8v5XD3tTTZ+kCFW2080EoAngeupf1m9mR1ETi4 -xs/NxqkCgYEA8m+bcjeeUbZw2ngMRRA+VJf8sAH9HanG2+gEAax8xPXz8O42FuLq -8ex25VpxOPg+8/orcrTgCfkM4CoNV/9PPyMbQRwGMigkEg76MD/dvFmyW2mMRape -hat3Ld+NxG/cuTYPSWa4RtFaMovTwPPIvkjJNK4GGrJmzPchGj9wNd8CgYEA7vQ8 -SnBCBQhXi4tIPF3bFU44WqE9yf2sJmC3y738PIa+FqRfdIgDal6l70a3dZMyNkhO -EFRUDIIoSfNdc1Nywglz3VTeFM93GKYPtbuJDPda1jMT2Evi9bWzYO9OKV9i4rze -WdQ+l+idbJ36tNYgVaoHNx/KhHpWCJzkFwVBIC0CgYBJEDex0W9GQwx52uofukh+ -qBuAU+kbknoa9i6W7ovftBwjhTcJ6LNT26btcjdjKvWWA9QqSramasdlm2bQGWKh -rYveMHrxjMVqJ9dgyS6jQAkPoZyjtjesY0OUsKYCCJBlxRQQVAO/XAKp7xgPM6lR -J5Bz7upqC1AN/4Cbb3j60wKBgQCqTT86/k7PL2bVeWr+OxYNVTYswYY8E6NBpuTX -PIwsxwtrL7MoZleo09QHeKsADOxYa6fXU4Kjd5AnRF9x9iNvzzTYpcexpTsIQjIo -H4RJzXDcAINAQLV80QcLKwLV0bm0R09hTjdeJNcttlob0BAzfX6u9uVrDZWLheW5 -0nDb8QKBgFcgD84A2xcunL+ZLtZ5YwyY3PPCoU3hDnHT2ZFz7H74rthLv/RXTmX0 -BM/ZUVHKeLPzgXyxR0kpojDkVfx8q8Ncz8xZse+TTX1Lk3HGJIFS40gnvTaUc+4I -bpzH7lRdjEuAAK+fDYZa8pEeep6y9tVEa38RrL09F7+XDBuvLY2b +MIIEpAIBAAKCAQEAueBNI9EeojUENXOPfMPqCcV18FVUseRZ2MftwPpcjjjENM85 +C95/PDQij4OHYC5LVyqMRakzmxLSw3jv3Q2bcQULoZhrjAg3F6QSZznsA05iij/b +08ceMrOEhXSRnLm40Jy/6s/MAWh8lJHyo0jzBPXr19N5Mu/yigHnzw10NYoxfsKw +YPLeRPN1bDy1SmfSK/ww2yk9y767UtN7SOK5w6/riZC2vdWEvR9WcJKx76plD6qs +5dxI0jAIGGaumlonQK7yClQzR5Lxxibix8xSme1jXPeS1n7jxY7z+zgvQUANNsC3 +AtZmvQaC0tgmM2LRx2mgMEH+GHovUIaK60YQHwIDAQABAoIBADc/Es59fmRp65lT +gqdrt6k11osbYbQKEiZbri/4egAPoUms+eCsPhcPy+HqDxeoSt5amBywYNVLr/dH +f8utGrFp9X4PRo/1dSKCsrGZxqto5eL/fgAhI7mgH9hmwEzb6rGelXBeWN1mR/kE +tCCSMyEbUwDwKwrXxLf+Pv8Mmai7qu3umjSOMa4YZwYEUizuFu2zXMaODM0BL2VB +3CzgdWOes3bTt/cXHdEROi0q4LxwZS6/EZ0yLG0WlBHL0yu38qn6OhU4bSxb6sLb +X8EEP0oQqk161Kkg2EPcYWwxKzeIALeYVNWYCANwZ+QWU+2Ltra0l4zXN8QtZhdf +i8FXaOkCgYEA81FdvxZOTa8J2+HvG3ZS1EzK0yBD6tl6sk6kP5sAWJ3EIh8KU3/q +ENKr1z4dkEW+Qfrt3TqCUJgVorQIfD5EN6Ma5oK/yB4RrJZj+/nCacYRkbP+5hS2 +N4mRuIWkpvrLUckWX6CqSe6WyBii28V7C1wcFSWsAORHxqT4B1XSAL0CgYEAw5B7 +DzA4sHBZvfBmzi8ubIvhLagJ7xcJy9HYjbegqgjcssBygYmbAnf0UKeiVE9sIqv2 +nqUV2DjNTQjLG53FBtASmuuFTLosw2ijwmHZze8n6+qkWgNiRoeMnJZA6gF4BxFk +axkW5I0I2MBNqA6gw3TkjwExMT4QjPWNjYwUqAsCgYEAlzH0Yw1lUvh10+CtSA9a +oPmm/1KJYaIKkEo13iBfMrG2cs1/CSvvMsz2YyYCEOiFtVJMBLCa0aHvr87Xhvza +Pwhnat3MdnnY2boKH0Wv/TJLMJL8zdQI9rHRjyvciLZHKWcfNAUOTCqqH2TPrmkk +cIaoHKvwGg3AXDuetFAr0rECgYEAjFU9OSTtSQ8WFspPu1z3/0RRDaYrmrn5eZzX +vLosPFenp02Z3YKVDSxu0QG55q4ndqnXivgDuOjpyYGp3eNU4xKkhy7CtNBUFtUb +zfzRgok/KHd0AHO1Lc9PA35+jm0HaGr+mCuk1dSuqHs2PoZgrmFPMZ81YZSb48rB +DPWcTQkCgYBqP4m3/Gbd3k/JVjDKZm5dV14fLJSwTuszA3XwmpmF4Y50ejLplV+B +lkcumY8SSCjfYWcV36GPTT31fFzk2dNqmFk2fbYs5AerwOqb1NjVbaSS0DGYTYaL +HHv507INmrv9FkAXQyC/x1q4gMcNSr0DKhMnGR8EphxZpwGHF6nZyQ== -----END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/nginx/server.csr b/docker-auth-registry/nginx/server.csr index 7d7c16bd..b9b45eb8 100644 --- a/docker-auth-registry/nginx/server.csr +++ b/docker-auth-registry/nginx/server.csr @@ -1,15 +1,15 @@ -----BEGIN CERTIFICATE REQUEST----- -MIICazCCAVMCAQAwJjEkMCIGA1UEAxMbYWxleC1jb2xsaW5zcy1tYWNib29rLmxv -Y2FsMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4ksN/P+TQHbN7tKS -mAUTa83UPPc3MyGM6aqC/wSjoWNUL19oeGKAGL3+5UfAeN/WwXkwuu8yceyA7n79 -65UEOAiF8hr63hyxBCC+MsC6v8hOz/nV0FJAxJXttrznp/KY228Hv4p9twnaX8BH -45dLBfXb/jmnHl8n1epQkDFNGTIqxqtZLqiB+TdxXr1BgIQ0R6JmEf348lmC6pQ2 -Kk1Psmfu1H64p7UGlDzfOIBhm+NXHcE02F2RbgcaR1KBGPLBHRGiAa88vf5wSqwD -LBdvbD1tyJfyS7tpm6wNpZJMwQJC5bsNwzd7eU76xJBm7QcHuj2bcr8c9utFbtkf -NhRYMwIDAQABoAAwDQYJKoZIhvcNAQEFBQADggEBAA0ZWAcEwZjSlZnf13qzg9C/ -1PIvb4h4Wz2oADHHmszvd+Ze8qUaqin1Ds56gh/tlMomJPxjXUgxW4Y2sg2a3981 -g7C5rtp6Us/2erEKuZUpeQCc36UeCaF9jmWUtmVRo1hMNn3FKlTECQyApVWo9kWW -Sr1RZMuYbxkmD+ZuBXspM2BrRLFwUaBhpGeukORG7cYE2SSbdYVFX85Te4una/+L -Z0WcWDyzSy4MnsSLjMILWV3RhvXkL7ASA/dOnA7+d50GATIYwwpYKte9GzKZfUH/ -ADa1y47ZsJOtBn1cS4HOzWBHqao6WF7mcENE9UQtfPhU3IUmLgeypki47ZNqyGw= +MIICWDCCAUACAQAwEzERMA8GA1UEAxMIcmVnaXN0cnkwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQC54E0j0R6iNQQ1c498w+oJxXXwVVSx5FnYx+3A+lyO +OMQ0zzkL3n88NCKPg4dgLktXKoxFqTObEtLDeO/dDZtxBQuhmGuMCDcXpBJnOewD +TmKKP9vTxx4ys4SFdJGcubjQnL/qz8wBaHyUkfKjSPME9evX03ky7/KKAefPDXQ1 +ijF+wrBg8t5E83VsPLVKZ9Ir/DDbKT3LvrtS03tI4rnDr+uJkLa91YS9H1ZwkrHv +qmUPqqzl3EjSMAgYZq6aWidArvIKVDNHkvHGJuLHzFKZ7WNc95LWfuPFjvP7OC9B +QA02wLcC1ma9BoLS2CYzYtHHaaAwQf4Yei9QhorrRhAfAgMBAAGgADANBgkqhkiG +9w0BAQUFAAOCAQEAUyNSKcG+5kI2P4AozH+S1xGBgZqyiTyOw8XhwY2XxOzD2pgA +wRvwS8kEKef28myjJtaQFo6FgxsFaXH4LAx8WxeOwjNG6E5io1yVmxUcTX05rjTp +KEaA+usw8Dgr8yWnw4V70/5rHtjO6eTZyO/HJgDDo6MuQRZBOC8TnL/fs0PMAsJC +d9c81IOZuCJaEx/lB+V0lju0FRwRtdPUlWVHwIpW+FMbFN2l1Dx+1DeaLSFJ5x2f +UCC0uOv14nfzJfBECThR6lDHomRM8HdviTBcx/1qQBX92j2K8sOAWExGnXlQr7xl +gUlxHuZc5x2JpgtX86tfW9aQspr4fW+2MndiKw== -----END CERTIFICATE REQUEST----- From 15ce5e0766051bd7ad56f855f16820edaebc6bbd Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sat, 8 Nov 2014 23:46:21 +0000 Subject: [PATCH 200/452] 1 --- docker-auth-registry/nginx/Dockerfile | 10 ++-- docker-auth-registry/nginx/ca-key.pem | 30 +++++++++++ docker-auth-registry/nginx/ca.pem | 36 ++++++------- docker-auth-registry/nginx/ca.srl | 2 +- .../nginx/docker-registry.htpasswd | 2 +- docker-auth-registry/nginx/nginx.htpasswd | 1 + .../nginx/{nginx.conf => registry} | 24 +++------ docker-auth-registry/nginx/server-cert.pem | 26 +++++----- docker-auth-registry/nginx/server-key.pem | 50 +++++++++---------- docker-auth-registry/nginx/server.csr | 24 ++++----- 10 files changed, 113 insertions(+), 92 deletions(-) create mode 100644 docker-auth-registry/nginx/nginx.htpasswd rename docker-auth-registry/nginx/{nginx.conf => registry} (65%) diff --git a/docker-auth-registry/nginx/Dockerfile b/docker-auth-registry/nginx/Dockerfile index c425f4de..411ec995 100644 --- a/docker-auth-registry/nginx/Dockerfile +++ b/docker-auth-registry/nginx/Dockerfile @@ -1,12 +1,12 @@ FROM dockerfile/nginx -ADD server-cert.pem /etc/ssl/certs/docker-registry -ADD server-key.pem /etc/ssl/private/docker-registry +ADD server-cert.pem /etc/ssl/certs/nginx +ADD server-key.pem /etc/ssl/private/nginx -ADD nginx.conf /etc/nginx/ -ADD docker-registry.conf /etc/nginx/ +ADD registry touch /etc/nginx/sites-available/registry +RUN ln -s ln -s /etc/nginx/sites-available/registry /etc/nginx/sites-enabled -ADD docker-registry.htpasswd /etc/nginx/ +ADD nginx.htpasswd /etc/nginx/ EXPOSE 443 diff --git a/docker-auth-registry/nginx/ca-key.pem b/docker-auth-registry/nginx/ca-key.pem index e69de29b..041ec279 100644 --- a/docker-auth-registry/nginx/ca-key.pem +++ b/docker-auth-registry/nginx/ca-key.pem @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: DES-EDE3-CBC,CC08254A16592D94 + +EwbxnlBwH/Y3BkbKmD7eDqc7uAH8aTQtI4wnJH5ISpx6stwv/tdA4by+LseVISV0 +b/NQg4eZ28ANMTVVkpv4dprKASAC/YyZ1Kt1e3Omu/0or/k+Es+saU9XZKsjzgpc +XVRUb+bNnwjDyYdIFPWnapkEFnzy77Y1ZsdIda1W0Xat5oLZbPwQ7uuQ18IrvQog +Yrs9WSZLxa/npPq1/UCDyH8yU6n5RK2pY7dW18tCdP6H2hlYGOiOBImCQZXHDGC7 +7ai6Hb8Z+78FkqhsQUZTX39Y+xFNiLdtp4aolervcKtLbvD8ADL5KMSnOFd875in +QFG8m9dV0maWtZtX8PQBRVcFMKuy0+b48GhxAaWGBGL8NXGk+eEBxIkRB3plwYbl +wdyB5pnQifb4AEdNsUanB/gwPIYY9cGE8Ua54/iDDU0Pxy3dxW69hBBB5Vs2QUVA +kHv+NjyAJfTX1HzVL+2SfOJ6ANHHwuQyxOgWioVZOUzJf3LohFlUGwgoFQ8ZPGdQ +stHz+IvQi2qFVsm5JDpYD8wCW9u4G94XVAu8Xmq4q3H/M9P0sgteJoV6RONdZqnb +XuQVS8k+RI1+ZelzgGNgRbn9pDbc2wuvQnqLRhNYngptXqZwWWuv55/dU4RvyYZz +jImIupHYaXr88d9rCI6zV8Ok0OlCeD7egD+aQUmFcMiaIccXkNPxdAVeppwgyikn +JvyRgAy9hTXAWNUiPUg06iQLkGRTnb2st8rW7H7/9KlzeSQcfCDcNrMca2VGkx+T +z0+JrjARrl6lMl5AGPDkb5U23XnU//58pLBQHoDGLpl115wE0BHqS560wg/vcmf4 +0tknwWTYmmpsjP1EBb4HmNQ4e4574hvD48PvxlV2NDF1cYGFS98mLC8SVRXlEB91 +/SdWKevyyOqRV/MC39KGstQi8jy6KF+9gLWeOROUpgc/9c+dZE3rIUoto7IopkWK +8hklNFTnF2w03ZbL3R2uUO39CoyCVVx7gzyGObcFVB2IOhz348gUf50xCe4diKrd +vwuh5sDGLRv1Iq3uCRtJhVfTmv2AozMpgg+HmJkT7COfT6BGv8hIBGUyyf4umI1Y +G47vKBhApiKBGPKE/zU6BoVXTt8/Xsve0o37v09Yz7rzKflZVmzxouGR5+GRx2XD +dsYuWbyHrdd8wE8PRd7W1DU332ebSj5DJwdWXXW4jsUQ8yPr/awuhRt6bhSQG8B8 +QtoIbu7gBn5tvuiq6IVRs8x1eUtcIlYPJvTD/hTnRLoo1LrNCjfSmN8/MqSL2bUH +MNQ+CRJc0XWGnVwkpzBvcfns8oWd/bPuLOz4DStpr7YwmABzk2OAJ31Hcc9gK0NG +Dp+f/xn8vfVcv6xm1KtoDL2nepYerGc0mYY2KVFKcElSP1r0aMneN5sjNqwCm7CU +e57r3GUW3oFyUVwSXzeRwIonvY228Qhvj0pRCkLVjnmX3tIWVdFooaBJbEuXJa9A +P0qPZjHNX6njRCYSarO5EtbWgOVVs8cyyHY25TOzUsVImgkBeUoMaFQqu7oGBIAs +4JhlYCS4Th/eaITA6h3OvH6FiI+d0ceE5c9i9vO3aqCrqeR9dJIZTMQUHnOy4gFm +-----END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/nginx/ca.pem b/docker-auth-registry/nginx/ca.pem index 5d13a8a8..6f06ce28 100644 --- a/docker-auth-registry/nginx/ca.pem +++ b/docker-auth-registry/nginx/ca.pem @@ -1,23 +1,23 @@ -----BEGIN CERTIFICATE----- -MIID5jCCAs6gAwIBAgIJAMKZlxOyqvJlMA0GCSqGSIb3DQEBBQUAMFUxCzAJBgNV +MIID5jCCAs6gAwIBAgIJAO7ClRbtFEXnMA0GCSqGSIb3DQEBBQUAMFUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX -aWRnaXRzIFB0eSBMdGQxDjAMBgNVBAMTBW5naW54MB4XDTE0MTEwODIzMjQyMFoX -DTE1MTEwODIzMjQyMFowVTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3Rh +aWRnaXRzIFB0eSBMdGQxDjAMBgNVBAMTBW5naW54MB4XDTE0MTEwODIzNDU1NloX +DTE1MTEwODIzNDU1NlowVTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3Rh dGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEOMAwGA1UEAxMF -bmdpbngwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9uw9QacXEkB+C -QNYVPFhL3UrpiLSnNSe8pdyFNgeQ4kqhKmI5dteOG1B8v1gEDNn+sJbWoRtQbNaI -ksyr6NmfFWL3vdYDypgY74cnoVJ3OHHsGBT/MMs540jc9MgfqzlSy98Gr8Eq+Bfa -q/hS+QzuI3tI3/t20B0Pfrs4VLCydG/ZbR1CXpRBzkMl5sKQ+fQZjT3SwE0BHdn8 -EC5rSH2tHGWgm/BIZvQm7o82wv7w46ksDbuZpfhv5vg914/3aa7GPcKGNF6+LALz -omycIP3X62jpsjxohn5sICBSLpm2kSL+MqK0k61EeGVeDwgTYThORaYk/wv/QJ/4 -JNlQ104TAgMBAAGjgbgwgbUwHQYDVR0OBBYEFLQ2Pok5e+v1E2w/f4r24Jr/vAwO -MIGFBgNVHSMEfjB8gBS0Nj6JOXvr9RNsP3+K9uCa/7wMDqFZpFcwVTELMAkGA1UE +bmdpbngwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC14W2hLkozliqo +1TXFRWx+Ij64cdnUGMn6tZSGDMgdZNIqOj5jxeg0ZVRWbqYt0xVqsjw14KXuxWm+ +8h3v9f1KEanAgyrKRPB6tIXmtApp0B05xbx+jpWHU+r6zxlqI60/Szs+I7d99qF1 +xv7zrXU3aEBxEmm+S/AHa/FBXdv2v3ubZpiFOW1YBbJ4F2fVjfFJXevOQL8sydf3 +eO9QI8KauRG7JrucsmVOsBeBVWHl9KVgpu4HvbqjwuPc3DPn9YlwjcIS1DbFV3XH +dZ8qKDcaZmifl0tjkUkz92OXWTCq+z7BDVIh7yCAByNk3uCXDHBXX7ygkEwIhYFc +wBoV5loNAgMBAAGjgbgwgbUwHQYDVR0OBBYEFKisDYhDN4nDcDFEV1gkqsFQ/U27 +MIGFBgNVHSMEfjB8gBSorA2IQzeJw3AxRFdYJKrBUP1Nu6FZpFcwVTELMAkGA1UE BhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdp -ZGdpdHMgUHR5IEx0ZDEOMAwGA1UEAxMFbmdpbniCCQDCmZcTsqryZTAMBgNVHRME -BTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQC6XuA41OvXO4+l39ElKFRjKSdknL6v -kU3mjo6frgW1Vt5MJzAUuwGwGAMum/+62mv//HvbJVUhbyxkk1Iq0gChofOMMyto -I8aEeqWgubMBQJMZUQFVZr2Ye3zEZpeVwezg5RS5M74H2OqCuDwzMHo3vpXAuMrF -Sr1jCB5pMwd6kED5sOteo0pW+etgZRKg+d9IaoE5sDmFghNfaLH+ZzIHJknOarPI -1ZKt+Xa6MQWeqdez4JDGtAyL4Ujv34BHypNnFmmEZRRaJaPaO9Pi2AEOlEyzsBTk -UgPv0Oa4QA8NqRCDF621tHmmBnaINox1AORh3UVuYHXvs7DnsQK2vXmF +ZGdpdHMgUHR5IEx0ZDEOMAwGA1UEAxMFbmdpbniCCQDuwpUW7RRF5zAMBgNVHRME +BTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQAMcYcPejAUfxm42GqFKXRXD6ciYT6A +gKyKfQJyajlZQStCN2MFy1lR0gRhOikb8pZZt97yyG3cGi7R9bhE32D8MqJQlzh5 +G/Nfc9PwdN3PHS+POyDn9+VjAMbSwYEfAFP9bFuMsSmpEtbkYbuwc0jp8fhdTQma +JU0hufwpUObTceUyxM4ze2Qa3bP8I2fLiTEN/MX/QGIeAtQ3fRS62p7dxXrwabc0 +WUmSYYoOa4po/54YPubiPWD77sLwwxh+fpxh3Tp2jkHqjLws9voESWMu8HsJ04eg +c1rjWszwygfTAFOyontgft3QARqX+F7LQa9X0zLWZ84ipxd5SspSWIsX -----END CERTIFICATE----- diff --git a/docker-auth-registry/nginx/ca.srl b/docker-auth-registry/nginx/ca.srl index 8a0f05e1..9e22bcb8 100644 --- a/docker-auth-registry/nginx/ca.srl +++ b/docker-auth-registry/nginx/ca.srl @@ -1 +1 @@ -01 +02 diff --git a/docker-auth-registry/nginx/docker-registry.htpasswd b/docker-auth-registry/nginx/docker-registry.htpasswd index 29d18b5d..8151002d 100644 --- a/docker-auth-registry/nginx/docker-registry.htpasswd +++ b/docker-auth-registry/nginx/docker-registry.htpasswd @@ -1 +1 @@ -registry:$apr1$7T1Nc0O5$KtMdxpRxf7D2B25.k4n8c0 +registry:$apr1$czSY2tcn$x4BAkkTqRHqnpTWqDGu0h0 diff --git a/docker-auth-registry/nginx/nginx.htpasswd b/docker-auth-registry/nginx/nginx.htpasswd new file mode 100644 index 00000000..29d18b5d --- /dev/null +++ b/docker-auth-registry/nginx/nginx.htpasswd @@ -0,0 +1 @@ +registry:$apr1$7T1Nc0O5$KtMdxpRxf7D2B25.k4n8c0 diff --git a/docker-auth-registry/nginx/nginx.conf b/docker-auth-registry/nginx/registry similarity index 65% rename from docker-auth-registry/nginx/nginx.conf rename to docker-auth-registry/nginx/registry index 096aa23d..7c429fc8 100644 --- a/docker-auth-registry/nginx/nginx.conf +++ b/docker-auth-registry/nginx/registry @@ -1,10 +1,9 @@ -http { # FYI: Chunking requires nginx-extras package on Debian Wheezy and some Ubuntu versions # See chunking http://wiki.nginx.org/HttpChunkinModule # Replace with appropriate values where necessary upstream docker-registry { - server localhost:5000; + server registry:5000; } # uncomment if you want a 301 redirect for users attempting to connect @@ -18,11 +17,11 @@ upstream docker-registry { server { listen 5443; - server_name localhost; + server_name nginx; ssl on; - ssl_certificate /etc/ssl/certs/docker-registry; - ssl_certificate_key /etc/ssl/private/docker-registry; + ssl_certificate /etc/ssl/certs/nginx; + ssl_certificate_key /etc/ssl/private/nginx; client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image uploads @@ -31,21 +30,12 @@ server { location / { auth_basic "Restricted"; - auth_basic_user_file docker-registry.htpasswd; - include docker-registry.conf; + auth_basic_user_file nginx.htpasswd; + include nginx.conf; } location /_ping { auth_basic off; - include docker-registry.conf; + include nginx.conf; } - - location /v1/_ping { - auth_basic off; - include docker-registry.conf; - } -} } -events { - worker_connections 1024; -} \ No newline at end of file diff --git a/docker-auth-registry/nginx/server-cert.pem b/docker-auth-registry/nginx/server-cert.pem index 8e7b1ab3..bd1e1628 100644 --- a/docker-auth-registry/nginx/server-cert.pem +++ b/docker-auth-registry/nginx/server-cert.pem @@ -1,18 +1,18 @@ -----BEGIN CERTIFICATE----- MIIC3DCCAcQCAQIwDQYJKoZIhvcNAQEFBQAwVTELMAkGA1UEBhMCQVUxEzARBgNV BAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0 -ZDEOMAwGA1UEAxMFbmdpbngwHhcNMTQxMTA4MjMyNDI2WhcNMTUxMTA4MjMyNDI2 +ZDEOMAwGA1UEAxMFbmdpbngwHhcNMTQxMTA4MjM0NjA0WhcNMTUxMTA4MjM0NjA0 WjATMREwDwYDVQQDEwhyZWdpc3RyeTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC -AQoCggEBALngTSPRHqI1BDVzj3zD6gnFdfBVVLHkWdjH7cD6XI44xDTPOQvefzw0 -Io+Dh2AuS1cqjEWpM5sS0sN4790Nm3EFC6GYa4wINxekEmc57ANOYoo/29PHHjKz -hIV0kZy5uNCcv+rPzAFofJSR8qNI8wT169fTeTLv8ooB588NdDWKMX7CsGDy3kTz -dWw8tUpn0iv8MNspPcu+u1LTe0jiucOv64mQtr3VhL0fVnCSse+qZQ+qrOXcSNIw -CBhmrppaJ0Cu8gpUM0eS8cYm4sfMUpntY1z3ktZ+48WO8/s4L0FADTbAtwLWZr0G -gtLYJjNi0cdpoDBB/hh6L1CGiutGEB8CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA -ghLkKO99yjoMV/UozhAd1mOLiMecgxT3PfURBECnwghnr1AtvZR0XDmvx18wqSdV -fgK9Bkm4oCD9jwZdeaKoUrkUeeFK5rftahLOQhvNfmRGhk6CtS101YVcQkpS8xE/ -HfXNLaHS9eofAky/DLiVxzl2NIScMooCIaCjl/AXChDC3UmtlewoEUCAow8DzKwt -SXcdc6OlpPXW+9TGhTjnweK4tuehQIQTCT6F6Fr9kpgSlCZ+P2Mwp9AJfh0zbBGs -zEukHeY9RHl5cppF/pHeNFikOO2V5iZ0XrdRwcMqjUmCJKphO+2+pR0buAjwBWHU -vDAL1d0OWPT7tSzm4g1m6A== +AQoCggEBALKNod0blw/bw98Zw9IbZ0s7UJ+Oibn9khGgb6ARvHoBfG4fZDLA8NgG +7mR+rxKR8eVsPCjhvivlk27XVEtwEWLfCzbyJaoqpZnbevNY7c1R1GBw770LOjTq +chsIPZff1Oe2ad2ZfC3RrlKPGwG0KHeMjokPFQfMwhAP0zSFy8F85cfccB9JEVbI +UWhgA4zkxnj3VbPgYRu0foR0mP7LCUBfGqT+r6HA03knmfy13zB5n6aZpV6PHcFH +tDxJDUBDTFL3iNFHT2sfEG+uHqcz3Bxs81Xksul5oFZlMBWubXGP0/UcWUA81gY6 +ccgzZyWjsEa8Tdy0rQgNfcJpyDUGtrMCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA +pHaDUN49pYYesQU74T2JYhyza5JSbEPiPRXK9gx8jKy076Hq5dLubM6WdX+eatDX +dw0DMjsyElWElejowIXuwOkH1b8Hm1/nZoqW9ribBDSfVHAbjJjS+ZmMlPdStFql +7SP8xcqKZW1XowLx747UVMyTe6iviePMaA4E4feT6k0+AC2P1ei8fXMULKae3Ugv +GSGfHfTCgljs+syrnotnZp9IxdzTwneUrsMJ+luhiIvKG6XYb2wymPt2WG70JWrK +oacTeASI8G9fwx/1TbBp9c/Q4rRGA8u3PhVu0I0HiBxQjAeBS/JqS5wq9huEg62u +/CA3yXPgMYOxpm9Il99pvw== -----END CERTIFICATE----- diff --git a/docker-auth-registry/nginx/server-key.pem b/docker-auth-registry/nginx/server-key.pem index 69dbf5a6..587b2a76 100644 --- a/docker-auth-registry/nginx/server-key.pem +++ b/docker-auth-registry/nginx/server-key.pem @@ -1,27 +1,27 @@ -----BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEAueBNI9EeojUENXOPfMPqCcV18FVUseRZ2MftwPpcjjjENM85 -C95/PDQij4OHYC5LVyqMRakzmxLSw3jv3Q2bcQULoZhrjAg3F6QSZznsA05iij/b -08ceMrOEhXSRnLm40Jy/6s/MAWh8lJHyo0jzBPXr19N5Mu/yigHnzw10NYoxfsKw -YPLeRPN1bDy1SmfSK/ww2yk9y767UtN7SOK5w6/riZC2vdWEvR9WcJKx76plD6qs -5dxI0jAIGGaumlonQK7yClQzR5Lxxibix8xSme1jXPeS1n7jxY7z+zgvQUANNsC3 -AtZmvQaC0tgmM2LRx2mgMEH+GHovUIaK60YQHwIDAQABAoIBADc/Es59fmRp65lT -gqdrt6k11osbYbQKEiZbri/4egAPoUms+eCsPhcPy+HqDxeoSt5amBywYNVLr/dH -f8utGrFp9X4PRo/1dSKCsrGZxqto5eL/fgAhI7mgH9hmwEzb6rGelXBeWN1mR/kE -tCCSMyEbUwDwKwrXxLf+Pv8Mmai7qu3umjSOMa4YZwYEUizuFu2zXMaODM0BL2VB -3CzgdWOes3bTt/cXHdEROi0q4LxwZS6/EZ0yLG0WlBHL0yu38qn6OhU4bSxb6sLb -X8EEP0oQqk161Kkg2EPcYWwxKzeIALeYVNWYCANwZ+QWU+2Ltra0l4zXN8QtZhdf -i8FXaOkCgYEA81FdvxZOTa8J2+HvG3ZS1EzK0yBD6tl6sk6kP5sAWJ3EIh8KU3/q -ENKr1z4dkEW+Qfrt3TqCUJgVorQIfD5EN6Ma5oK/yB4RrJZj+/nCacYRkbP+5hS2 -N4mRuIWkpvrLUckWX6CqSe6WyBii28V7C1wcFSWsAORHxqT4B1XSAL0CgYEAw5B7 -DzA4sHBZvfBmzi8ubIvhLagJ7xcJy9HYjbegqgjcssBygYmbAnf0UKeiVE9sIqv2 -nqUV2DjNTQjLG53FBtASmuuFTLosw2ijwmHZze8n6+qkWgNiRoeMnJZA6gF4BxFk -axkW5I0I2MBNqA6gw3TkjwExMT4QjPWNjYwUqAsCgYEAlzH0Yw1lUvh10+CtSA9a -oPmm/1KJYaIKkEo13iBfMrG2cs1/CSvvMsz2YyYCEOiFtVJMBLCa0aHvr87Xhvza -Pwhnat3MdnnY2boKH0Wv/TJLMJL8zdQI9rHRjyvciLZHKWcfNAUOTCqqH2TPrmkk -cIaoHKvwGg3AXDuetFAr0rECgYEAjFU9OSTtSQ8WFspPu1z3/0RRDaYrmrn5eZzX -vLosPFenp02Z3YKVDSxu0QG55q4ndqnXivgDuOjpyYGp3eNU4xKkhy7CtNBUFtUb -zfzRgok/KHd0AHO1Lc9PA35+jm0HaGr+mCuk1dSuqHs2PoZgrmFPMZ81YZSb48rB -DPWcTQkCgYBqP4m3/Gbd3k/JVjDKZm5dV14fLJSwTuszA3XwmpmF4Y50ejLplV+B -lkcumY8SSCjfYWcV36GPTT31fFzk2dNqmFk2fbYs5AerwOqb1NjVbaSS0DGYTYaL -HHv507INmrv9FkAXQyC/x1q4gMcNSr0DKhMnGR8EphxZpwGHF6nZyQ== +MIIEogIBAAKCAQEAso2h3RuXD9vD3xnD0htnSztQn46Juf2SEaBvoBG8egF8bh9k +MsDw2AbuZH6vEpHx5Ww8KOG+K+WTbtdUS3ARYt8LNvIlqiqlmdt681jtzVHUYHDv +vQs6NOpyGwg9l9/U57Zp3Zl8LdGuUo8bAbQod4yOiQ8VB8zCEA/TNIXLwXzlx9xw +H0kRVshRaGADjOTGePdVs+BhG7R+hHSY/ssJQF8apP6vocDTeSeZ/LXfMHmfppml +Xo8dwUe0PEkNQENMUveI0UdPax8Qb64epzPcHGzzVeSy6XmgVmUwFa5tcY/T9RxZ +QDzWBjpxyDNnJaOwRrxN3LStCA19wmnINQa2swIDAQABAoIBAHqoe0Jmeq7FPNhd +Xb1PX/U5iRgjFg/z1s1PFn+yz3RM4wrPe8i17H2qvUfCE0jBg5gkc2tuMHL9Yfup +5tlv4jG2oYCcdi1g4KRCN0NGmw4KIcgirT6DoPfK+poBXjaf6CVJlY5Kqxjay1Mh +xd60wXvmzd/vwXW7PrFD/cY+B4whtn9Jx9rqw7kBdb3i7F/8GNHmttlTXsdhXeM7 +AJGakIxAAAV2y4xF/eLElk2horaGvJN57BxMISPcn/HycsC7kzOLM7O3D5+aPqPr +X6XP0Ve5mcBYTR0uBnpwRC8plt4Kia5KxJKcXx6SL8sfxpDLD37cMF+YT4zNM23n +ziQML+kCgYEA7Lm0P40gD6tyPOJYMU4sst7dJ3nrc400AppzGNMQvsxnIr88kFCe +2NduZKVg4UOQ7nq4ZpoEX/nLrs+b6ltYJ4++kl0xII2fV/C9aZTYe/b6hDBXgQCb +6bOji/SE4VuU4QnsNnXUUAXEdSWp5mmoab62AREK/6G4CsgRy6G0Rs8CgYEAwRdj +zawF+cW8hOYOUD8uwU4aSj94nWkbvsOFpOxWN8lA29D0EfWmRinSIXds6ujkVITI +BIikTGg5a16pxwa/8KFo7LmLnP+GrePdfA96IDfx1OEibAJEBDRqnY3Gv6r1E5we +TfyhIxtsW6T6nX9raYCMi4QWFaf+gVojbDymit0CgYA94d3Iry+uaPcYC2NaoED3 +EWNmqmxubH8oHw/vcV1zQyPC5ZMDds/Ph6GIFeNZf7wnW1VRHPn/zOD99a+gd/h3 +fxAmWs444EzDRF9/djWRUmLyo2B8jJg1Y4xhTa5e6v3kRh/FrM+vi5JrvUjIvt4T +ppMVfEsPwErIJrzgKolh6QKBgC5N0Z0st3IiPQcRtDUCMdAhTqSne+Ejp4ejk5Tt +J+/Qz0DnZuA3rFv/A2kLHo9msfqirOSJb/zysXJSDRyxPa4SxvqdtCE+Fan1jtOF +UqAPSmrmYj7MfEsV1stZiGPGN2cwdQP2pR2qId4IPiEuwS9XqFx8nF8tHhce6oe2 +M6nxAoGAVPy22O9XqUxr9QeBANg2CG31Of+OaONEO2Cy4Sq4ZDG4D8WC3KBV6/ez +6thQhN2U/VhrxEBZpTsNNJGpaLokJlzwce7mCJg19LdMMi9QD6Zpf0X9faSOMQrj +XPdc2uyDX/LEGsSezXe/vwlp+H0CcV1j5pWLtylLHYdKm3DAgOs= -----END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/nginx/server.csr b/docker-auth-registry/nginx/server.csr index b9b45eb8..36a8adff 100644 --- a/docker-auth-registry/nginx/server.csr +++ b/docker-auth-registry/nginx/server.csr @@ -1,15 +1,15 @@ -----BEGIN CERTIFICATE REQUEST----- MIICWDCCAUACAQAwEzERMA8GA1UEAxMIcmVnaXN0cnkwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQC54E0j0R6iNQQ1c498w+oJxXXwVVSx5FnYx+3A+lyO -OMQ0zzkL3n88NCKPg4dgLktXKoxFqTObEtLDeO/dDZtxBQuhmGuMCDcXpBJnOewD -TmKKP9vTxx4ys4SFdJGcubjQnL/qz8wBaHyUkfKjSPME9evX03ky7/KKAefPDXQ1 -ijF+wrBg8t5E83VsPLVKZ9Ir/DDbKT3LvrtS03tI4rnDr+uJkLa91YS9H1ZwkrHv -qmUPqqzl3EjSMAgYZq6aWidArvIKVDNHkvHGJuLHzFKZ7WNc95LWfuPFjvP7OC9B -QA02wLcC1ma9BoLS2CYzYtHHaaAwQf4Yei9QhorrRhAfAgMBAAGgADANBgkqhkiG -9w0BAQUFAAOCAQEAUyNSKcG+5kI2P4AozH+S1xGBgZqyiTyOw8XhwY2XxOzD2pgA -wRvwS8kEKef28myjJtaQFo6FgxsFaXH4LAx8WxeOwjNG6E5io1yVmxUcTX05rjTp -KEaA+usw8Dgr8yWnw4V70/5rHtjO6eTZyO/HJgDDo6MuQRZBOC8TnL/fs0PMAsJC -d9c81IOZuCJaEx/lB+V0lju0FRwRtdPUlWVHwIpW+FMbFN2l1Dx+1DeaLSFJ5x2f -UCC0uOv14nfzJfBECThR6lDHomRM8HdviTBcx/1qQBX92j2K8sOAWExGnXlQr7xl -gUlxHuZc5x2JpgtX86tfW9aQspr4fW+2MndiKw== +AQUAA4IBDwAwggEKAoIBAQCyjaHdG5cP28PfGcPSG2dLO1Cfjom5/ZIRoG+gEbx6 +AXxuH2QywPDYBu5kfq8SkfHlbDwo4b4r5ZNu11RLcBFi3ws28iWqKqWZ23rzWO3N +UdRgcO+9Czo06nIbCD2X39TntmndmXwt0a5SjxsBtCh3jI6JDxUHzMIQD9M0hcvB +fOXH3HAfSRFWyFFoYAOM5MZ491Wz4GEbtH6EdJj+ywlAXxqk/q+hwNN5J5n8td8w +eZ+mmaVejx3BR7Q8SQ1AQ0xS94jRR09rHxBvrh6nM9wcbPNV5LLpeaBWZTAVrm1x +j9P1HFlAPNYGOnHIM2clo7BGvE3ctK0IDX3Cacg1BrazAgMBAAGgADANBgkqhkiG +9w0BAQUFAAOCAQEAaoWg7U09ZpngxTDICY/wibPSVgrfI3pSAxTAgUjFFKh0xGU9 +Tg4cBINxIGTNoFnhA5PECyURlSb6cCRmfTP4TaAJt/O4NNNyrvEgA9jAl2pKQnnr +yV4q0vB4iy9KUwMq7HhvCm5dbmE8sMlHLGH8BwoO02Ybw9yNb84G8KvCsWU7D3mO +ElbF7WNtwfYDmQhJwnPXk++jRMk6CfSaEvkF+mEqYOJl0AZIY8MSzHEWp2Vy9MAZ +EjUGuBpAZ4q55yOvyjVNshudUb7VdpBoiIhEMVDBjRGrKpnThkbQZZ295f7I6skY +9/DrShaADMrlk+/Sif+nN5Ke7hwKMp7MqPcr/g== -----END CERTIFICATE REQUEST----- From 05d8d034a1caa9507f10b96b4628aaacec99db85 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 9 Nov 2014 10:17:42 +0000 Subject: [PATCH 201/452] moved to own project --- docker-auth-registry/README.md | 18 -------- docker-auth-registry/fig.yml | 10 ----- docker-auth-registry/nginx/Dockerfile | 13 ------ docker-auth-registry/nginx/build.sh | 19 --------- docker-auth-registry/nginx/ca-key.pem | 30 -------------- docker-auth-registry/nginx/ca.pem | 23 ----------- docker-auth-registry/nginx/ca.srl | 1 - .../nginx/docker-registry.conf | 5 --- .../nginx/docker-registry.htpasswd | 1 - docker-auth-registry/nginx/nginx.htpasswd | 1 - docker-auth-registry/nginx/registry | 41 ------------------- docker-auth-registry/nginx/server-cert.pem | 18 -------- docker-auth-registry/nginx/server-key.pem | 27 ------------ docker-auth-registry/nginx/server.csr | 15 ------- 14 files changed, 222 deletions(-) delete mode 100644 docker-auth-registry/README.md delete mode 100644 docker-auth-registry/fig.yml delete mode 100644 docker-auth-registry/nginx/Dockerfile delete mode 100755 docker-auth-registry/nginx/build.sh delete mode 100644 docker-auth-registry/nginx/ca-key.pem delete mode 100644 docker-auth-registry/nginx/ca.pem delete mode 100644 docker-auth-registry/nginx/ca.srl delete mode 100644 docker-auth-registry/nginx/docker-registry.conf delete mode 100644 docker-auth-registry/nginx/docker-registry.htpasswd delete mode 100644 docker-auth-registry/nginx/nginx.htpasswd delete mode 100644 docker-auth-registry/nginx/registry delete mode 100644 docker-auth-registry/nginx/server-cert.pem delete mode 100644 docker-auth-registry/nginx/server-key.pem delete mode 100644 docker-auth-registry/nginx/server.csr diff --git a/docker-auth-registry/README.md b/docker-auth-registry/README.md deleted file mode 100644 index 8a70b930..00000000 --- a/docker-auth-registry/README.md +++ /dev/null @@ -1,18 +0,0 @@ -Set-up a Docker Registry with Plain Text Authentication --- -This creates a registry that runs locally with SSL and authentication set-up. - -Pre-requisites, fig (on OS-X with Homebrew): - - brew install fig - -To build: - - fig up - -Test it works: - - curl https://localhost:5443/v1/users/ -k -f --basic --user registry:registry - -Based on . - diff --git a/docker-auth-registry/fig.yml b/docker-auth-registry/fig.yml deleted file mode 100644 index 5b833325..00000000 --- a/docker-auth-registry/fig.yml +++ /dev/null @@ -1,10 +0,0 @@ -registry: - image: registry - ports: - - "5000:5000" -nginx: - build: nginx - ports: - - "443:8443" - links: - - registry diff --git a/docker-auth-registry/nginx/Dockerfile b/docker-auth-registry/nginx/Dockerfile deleted file mode 100644 index 411ec995..00000000 --- a/docker-auth-registry/nginx/Dockerfile +++ /dev/null @@ -1,13 +0,0 @@ -FROM dockerfile/nginx - -ADD server-cert.pem /etc/ssl/certs/nginx -ADD server-key.pem /etc/ssl/private/nginx - -ADD registry touch /etc/nginx/sites-available/registry -RUN ln -s ln -s /etc/nginx/sites-available/registry /etc/nginx/sites-enabled - -ADD nginx.htpasswd /etc/nginx/ - -EXPOSE 443 - -CMD nginx diff --git a/docker-auth-registry/nginx/build.sh b/docker-auth-registry/nginx/build.sh deleted file mode 100755 index 3b2158e8..00000000 --- a/docker-auth-registry/nginx/build.sh +++ /dev/null @@ -1,19 +0,0 @@ -#! /bin/sh -set -eu - - -echo "enter "registry" each time you are asked for a pass-phase" -echo "enter "nginx" when requested for a common name" -echo "press enter for everything else" - -htpasswd -bc docker-registry.htpasswd registry registry - -echo 01 > ca.srl -openssl genrsa -des3 -out ca-key.pem 2048 -openssl req -new -x509 -days 365 -key ca-key.pem -out ca.pem - -openssl genrsa -des3 -out server-key.pem 2048 -openssl req -subj "/CN=registry" -new -key server-key.pem -out server.csr -openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem -out server-cert.pem - -openssl rsa -in server-key.pem -out server-key.pem diff --git a/docker-auth-registry/nginx/ca-key.pem b/docker-auth-registry/nginx/ca-key.pem deleted file mode 100644 index 041ec279..00000000 --- a/docker-auth-registry/nginx/ca-key.pem +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: DES-EDE3-CBC,CC08254A16592D94 - -EwbxnlBwH/Y3BkbKmD7eDqc7uAH8aTQtI4wnJH5ISpx6stwv/tdA4by+LseVISV0 -b/NQg4eZ28ANMTVVkpv4dprKASAC/YyZ1Kt1e3Omu/0or/k+Es+saU9XZKsjzgpc -XVRUb+bNnwjDyYdIFPWnapkEFnzy77Y1ZsdIda1W0Xat5oLZbPwQ7uuQ18IrvQog -Yrs9WSZLxa/npPq1/UCDyH8yU6n5RK2pY7dW18tCdP6H2hlYGOiOBImCQZXHDGC7 -7ai6Hb8Z+78FkqhsQUZTX39Y+xFNiLdtp4aolervcKtLbvD8ADL5KMSnOFd875in -QFG8m9dV0maWtZtX8PQBRVcFMKuy0+b48GhxAaWGBGL8NXGk+eEBxIkRB3plwYbl -wdyB5pnQifb4AEdNsUanB/gwPIYY9cGE8Ua54/iDDU0Pxy3dxW69hBBB5Vs2QUVA -kHv+NjyAJfTX1HzVL+2SfOJ6ANHHwuQyxOgWioVZOUzJf3LohFlUGwgoFQ8ZPGdQ -stHz+IvQi2qFVsm5JDpYD8wCW9u4G94XVAu8Xmq4q3H/M9P0sgteJoV6RONdZqnb -XuQVS8k+RI1+ZelzgGNgRbn9pDbc2wuvQnqLRhNYngptXqZwWWuv55/dU4RvyYZz -jImIupHYaXr88d9rCI6zV8Ok0OlCeD7egD+aQUmFcMiaIccXkNPxdAVeppwgyikn -JvyRgAy9hTXAWNUiPUg06iQLkGRTnb2st8rW7H7/9KlzeSQcfCDcNrMca2VGkx+T -z0+JrjARrl6lMl5AGPDkb5U23XnU//58pLBQHoDGLpl115wE0BHqS560wg/vcmf4 -0tknwWTYmmpsjP1EBb4HmNQ4e4574hvD48PvxlV2NDF1cYGFS98mLC8SVRXlEB91 -/SdWKevyyOqRV/MC39KGstQi8jy6KF+9gLWeOROUpgc/9c+dZE3rIUoto7IopkWK -8hklNFTnF2w03ZbL3R2uUO39CoyCVVx7gzyGObcFVB2IOhz348gUf50xCe4diKrd -vwuh5sDGLRv1Iq3uCRtJhVfTmv2AozMpgg+HmJkT7COfT6BGv8hIBGUyyf4umI1Y -G47vKBhApiKBGPKE/zU6BoVXTt8/Xsve0o37v09Yz7rzKflZVmzxouGR5+GRx2XD -dsYuWbyHrdd8wE8PRd7W1DU332ebSj5DJwdWXXW4jsUQ8yPr/awuhRt6bhSQG8B8 -QtoIbu7gBn5tvuiq6IVRs8x1eUtcIlYPJvTD/hTnRLoo1LrNCjfSmN8/MqSL2bUH -MNQ+CRJc0XWGnVwkpzBvcfns8oWd/bPuLOz4DStpr7YwmABzk2OAJ31Hcc9gK0NG -Dp+f/xn8vfVcv6xm1KtoDL2nepYerGc0mYY2KVFKcElSP1r0aMneN5sjNqwCm7CU -e57r3GUW3oFyUVwSXzeRwIonvY228Qhvj0pRCkLVjnmX3tIWVdFooaBJbEuXJa9A -P0qPZjHNX6njRCYSarO5EtbWgOVVs8cyyHY25TOzUsVImgkBeUoMaFQqu7oGBIAs -4JhlYCS4Th/eaITA6h3OvH6FiI+d0ceE5c9i9vO3aqCrqeR9dJIZTMQUHnOy4gFm ------END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/nginx/ca.pem b/docker-auth-registry/nginx/ca.pem deleted file mode 100644 index 6f06ce28..00000000 --- a/docker-auth-registry/nginx/ca.pem +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN CERTIFICATE----- -MIID5jCCAs6gAwIBAgIJAO7ClRbtFEXnMA0GCSqGSIb3DQEBBQUAMFUxCzAJBgNV -BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX -aWRnaXRzIFB0eSBMdGQxDjAMBgNVBAMTBW5naW54MB4XDTE0MTEwODIzNDU1NloX -DTE1MTEwODIzNDU1NlowVTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3Rh -dGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEOMAwGA1UEAxMF -bmdpbngwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC14W2hLkozliqo -1TXFRWx+Ij64cdnUGMn6tZSGDMgdZNIqOj5jxeg0ZVRWbqYt0xVqsjw14KXuxWm+ -8h3v9f1KEanAgyrKRPB6tIXmtApp0B05xbx+jpWHU+r6zxlqI60/Szs+I7d99qF1 -xv7zrXU3aEBxEmm+S/AHa/FBXdv2v3ubZpiFOW1YBbJ4F2fVjfFJXevOQL8sydf3 -eO9QI8KauRG7JrucsmVOsBeBVWHl9KVgpu4HvbqjwuPc3DPn9YlwjcIS1DbFV3XH -dZ8qKDcaZmifl0tjkUkz92OXWTCq+z7BDVIh7yCAByNk3uCXDHBXX7ygkEwIhYFc -wBoV5loNAgMBAAGjgbgwgbUwHQYDVR0OBBYEFKisDYhDN4nDcDFEV1gkqsFQ/U27 -MIGFBgNVHSMEfjB8gBSorA2IQzeJw3AxRFdYJKrBUP1Nu6FZpFcwVTELMAkGA1UE -BhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdp -ZGdpdHMgUHR5IEx0ZDEOMAwGA1UEAxMFbmdpbniCCQDuwpUW7RRF5zAMBgNVHRME -BTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQAMcYcPejAUfxm42GqFKXRXD6ciYT6A -gKyKfQJyajlZQStCN2MFy1lR0gRhOikb8pZZt97yyG3cGi7R9bhE32D8MqJQlzh5 -G/Nfc9PwdN3PHS+POyDn9+VjAMbSwYEfAFP9bFuMsSmpEtbkYbuwc0jp8fhdTQma -JU0hufwpUObTceUyxM4ze2Qa3bP8I2fLiTEN/MX/QGIeAtQ3fRS62p7dxXrwabc0 -WUmSYYoOa4po/54YPubiPWD77sLwwxh+fpxh3Tp2jkHqjLws9voESWMu8HsJ04eg -c1rjWszwygfTAFOyontgft3QARqX+F7LQa9X0zLWZ84ipxd5SspSWIsX ------END CERTIFICATE----- diff --git a/docker-auth-registry/nginx/ca.srl b/docker-auth-registry/nginx/ca.srl deleted file mode 100644 index 9e22bcb8..00000000 --- a/docker-auth-registry/nginx/ca.srl +++ /dev/null @@ -1 +0,0 @@ -02 diff --git a/docker-auth-registry/nginx/docker-registry.conf b/docker-auth-registry/nginx/docker-registry.conf deleted file mode 100644 index 0e7e368f..00000000 --- a/docker-auth-registry/nginx/docker-registry.conf +++ /dev/null @@ -1,5 +0,0 @@ -proxy_pass http://registry; -proxy_set_header Host $http_host; # required for docker client's sake -proxy_set_header X-Real-IP $remote_addr; # pass on real client's IP -proxy_set_header Authorization ""; # see https://github.com/dotcloud/docker-registry/issues/170 -proxy_read_timeout 900; diff --git a/docker-auth-registry/nginx/docker-registry.htpasswd b/docker-auth-registry/nginx/docker-registry.htpasswd deleted file mode 100644 index 8151002d..00000000 --- a/docker-auth-registry/nginx/docker-registry.htpasswd +++ /dev/null @@ -1 +0,0 @@ -registry:$apr1$czSY2tcn$x4BAkkTqRHqnpTWqDGu0h0 diff --git a/docker-auth-registry/nginx/nginx.htpasswd b/docker-auth-registry/nginx/nginx.htpasswd deleted file mode 100644 index 29d18b5d..00000000 --- a/docker-auth-registry/nginx/nginx.htpasswd +++ /dev/null @@ -1 +0,0 @@ -registry:$apr1$7T1Nc0O5$KtMdxpRxf7D2B25.k4n8c0 diff --git a/docker-auth-registry/nginx/registry b/docker-auth-registry/nginx/registry deleted file mode 100644 index 7c429fc8..00000000 --- a/docker-auth-registry/nginx/registry +++ /dev/null @@ -1,41 +0,0 @@ -# FYI: Chunking requires nginx-extras package on Debian Wheezy and some Ubuntu versions -# See chunking http://wiki.nginx.org/HttpChunkinModule -# Replace with appropriate values where necessary - -upstream docker-registry { - server registry:5000; -} - -# uncomment if you want a 301 redirect for users attempting to connect -# on port 80 -# NOTE: docker client will still fail. This is just for convenience -# server { -# listen *:80; -# server_name my.docker.registry.com; -# return 301 https://$server_name$request_uri; -# } - -server { - listen 5443; - server_name nginx; - - ssl on; - ssl_certificate /etc/ssl/certs/nginx; - ssl_certificate_key /etc/ssl/private/nginx; - - client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image uploads - - # required to avoid HTTP 411: see Issue #1486 (https://github.com/docker/docker/issues/1486) - chunked_transfer_encoding on; - - location / { - auth_basic "Restricted"; - auth_basic_user_file nginx.htpasswd; - include nginx.conf; - } - - location /_ping { - auth_basic off; - include nginx.conf; - } -} diff --git a/docker-auth-registry/nginx/server-cert.pem b/docker-auth-registry/nginx/server-cert.pem deleted file mode 100644 index bd1e1628..00000000 --- a/docker-auth-registry/nginx/server-cert.pem +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC3DCCAcQCAQIwDQYJKoZIhvcNAQEFBQAwVTELMAkGA1UEBhMCQVUxEzARBgNV -BAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0 -ZDEOMAwGA1UEAxMFbmdpbngwHhcNMTQxMTA4MjM0NjA0WhcNMTUxMTA4MjM0NjA0 -WjATMREwDwYDVQQDEwhyZWdpc3RyeTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC -AQoCggEBALKNod0blw/bw98Zw9IbZ0s7UJ+Oibn9khGgb6ARvHoBfG4fZDLA8NgG -7mR+rxKR8eVsPCjhvivlk27XVEtwEWLfCzbyJaoqpZnbevNY7c1R1GBw770LOjTq -chsIPZff1Oe2ad2ZfC3RrlKPGwG0KHeMjokPFQfMwhAP0zSFy8F85cfccB9JEVbI -UWhgA4zkxnj3VbPgYRu0foR0mP7LCUBfGqT+r6HA03knmfy13zB5n6aZpV6PHcFH -tDxJDUBDTFL3iNFHT2sfEG+uHqcz3Bxs81Xksul5oFZlMBWubXGP0/UcWUA81gY6 -ccgzZyWjsEa8Tdy0rQgNfcJpyDUGtrMCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA -pHaDUN49pYYesQU74T2JYhyza5JSbEPiPRXK9gx8jKy076Hq5dLubM6WdX+eatDX -dw0DMjsyElWElejowIXuwOkH1b8Hm1/nZoqW9ribBDSfVHAbjJjS+ZmMlPdStFql -7SP8xcqKZW1XowLx747UVMyTe6iviePMaA4E4feT6k0+AC2P1ei8fXMULKae3Ugv -GSGfHfTCgljs+syrnotnZp9IxdzTwneUrsMJ+luhiIvKG6XYb2wymPt2WG70JWrK -oacTeASI8G9fwx/1TbBp9c/Q4rRGA8u3PhVu0I0HiBxQjAeBS/JqS5wq9huEg62u -/CA3yXPgMYOxpm9Il99pvw== ------END CERTIFICATE----- diff --git a/docker-auth-registry/nginx/server-key.pem b/docker-auth-registry/nginx/server-key.pem deleted file mode 100644 index 587b2a76..00000000 --- a/docker-auth-registry/nginx/server-key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEogIBAAKCAQEAso2h3RuXD9vD3xnD0htnSztQn46Juf2SEaBvoBG8egF8bh9k -MsDw2AbuZH6vEpHx5Ww8KOG+K+WTbtdUS3ARYt8LNvIlqiqlmdt681jtzVHUYHDv -vQs6NOpyGwg9l9/U57Zp3Zl8LdGuUo8bAbQod4yOiQ8VB8zCEA/TNIXLwXzlx9xw -H0kRVshRaGADjOTGePdVs+BhG7R+hHSY/ssJQF8apP6vocDTeSeZ/LXfMHmfppml -Xo8dwUe0PEkNQENMUveI0UdPax8Qb64epzPcHGzzVeSy6XmgVmUwFa5tcY/T9RxZ -QDzWBjpxyDNnJaOwRrxN3LStCA19wmnINQa2swIDAQABAoIBAHqoe0Jmeq7FPNhd -Xb1PX/U5iRgjFg/z1s1PFn+yz3RM4wrPe8i17H2qvUfCE0jBg5gkc2tuMHL9Yfup -5tlv4jG2oYCcdi1g4KRCN0NGmw4KIcgirT6DoPfK+poBXjaf6CVJlY5Kqxjay1Mh -xd60wXvmzd/vwXW7PrFD/cY+B4whtn9Jx9rqw7kBdb3i7F/8GNHmttlTXsdhXeM7 -AJGakIxAAAV2y4xF/eLElk2horaGvJN57BxMISPcn/HycsC7kzOLM7O3D5+aPqPr -X6XP0Ve5mcBYTR0uBnpwRC8plt4Kia5KxJKcXx6SL8sfxpDLD37cMF+YT4zNM23n -ziQML+kCgYEA7Lm0P40gD6tyPOJYMU4sst7dJ3nrc400AppzGNMQvsxnIr88kFCe -2NduZKVg4UOQ7nq4ZpoEX/nLrs+b6ltYJ4++kl0xII2fV/C9aZTYe/b6hDBXgQCb -6bOji/SE4VuU4QnsNnXUUAXEdSWp5mmoab62AREK/6G4CsgRy6G0Rs8CgYEAwRdj -zawF+cW8hOYOUD8uwU4aSj94nWkbvsOFpOxWN8lA29D0EfWmRinSIXds6ujkVITI -BIikTGg5a16pxwa/8KFo7LmLnP+GrePdfA96IDfx1OEibAJEBDRqnY3Gv6r1E5we -TfyhIxtsW6T6nX9raYCMi4QWFaf+gVojbDymit0CgYA94d3Iry+uaPcYC2NaoED3 -EWNmqmxubH8oHw/vcV1zQyPC5ZMDds/Ph6GIFeNZf7wnW1VRHPn/zOD99a+gd/h3 -fxAmWs444EzDRF9/djWRUmLyo2B8jJg1Y4xhTa5e6v3kRh/FrM+vi5JrvUjIvt4T -ppMVfEsPwErIJrzgKolh6QKBgC5N0Z0st3IiPQcRtDUCMdAhTqSne+Ejp4ejk5Tt -J+/Qz0DnZuA3rFv/A2kLHo9msfqirOSJb/zysXJSDRyxPa4SxvqdtCE+Fan1jtOF -UqAPSmrmYj7MfEsV1stZiGPGN2cwdQP2pR2qId4IPiEuwS9XqFx8nF8tHhce6oe2 -M6nxAoGAVPy22O9XqUxr9QeBANg2CG31Of+OaONEO2Cy4Sq4ZDG4D8WC3KBV6/ez -6thQhN2U/VhrxEBZpTsNNJGpaLokJlzwce7mCJg19LdMMi9QD6Zpf0X9faSOMQrj -XPdc2uyDX/LEGsSezXe/vwlp+H0CcV1j5pWLtylLHYdKm3DAgOs= ------END RSA PRIVATE KEY----- diff --git a/docker-auth-registry/nginx/server.csr b/docker-auth-registry/nginx/server.csr deleted file mode 100644 index 36a8adff..00000000 --- a/docker-auth-registry/nginx/server.csr +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN CERTIFICATE REQUEST----- -MIICWDCCAUACAQAwEzERMA8GA1UEAxMIcmVnaXN0cnkwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQCyjaHdG5cP28PfGcPSG2dLO1Cfjom5/ZIRoG+gEbx6 -AXxuH2QywPDYBu5kfq8SkfHlbDwo4b4r5ZNu11RLcBFi3ws28iWqKqWZ23rzWO3N -UdRgcO+9Czo06nIbCD2X39TntmndmXwt0a5SjxsBtCh3jI6JDxUHzMIQD9M0hcvB -fOXH3HAfSRFWyFFoYAOM5MZ491Wz4GEbtH6EdJj+ywlAXxqk/q+hwNN5J5n8td8w -eZ+mmaVejx3BR7Q8SQ1AQ0xS94jRR09rHxBvrh6nM9wcbPNV5LLpeaBWZTAVrm1x -j9P1HFlAPNYGOnHIM2clo7BGvE3ctK0IDX3Cacg1BrazAgMBAAGgADANBgkqhkiG -9w0BAQUFAAOCAQEAaoWg7U09ZpngxTDICY/wibPSVgrfI3pSAxTAgUjFFKh0xGU9 -Tg4cBINxIGTNoFnhA5PECyURlSb6cCRmfTP4TaAJt/O4NNNyrvEgA9jAl2pKQnnr -yV4q0vB4iy9KUwMq7HhvCm5dbmE8sMlHLGH8BwoO02Ybw9yNb84G8KvCsWU7D3mO -ElbF7WNtwfYDmQhJwnPXk++jRMk6CfSaEvkF+mEqYOJl0AZIY8MSzHEWp2Vy9MAZ -EjUGuBpAZ4q55yOvyjVNshudUb7VdpBoiIhEMVDBjRGrKpnThkbQZZ295f7I6skY -9/DrShaADMrlk+/Sif+nN5Ke7hwKMp7MqPcr/g== ------END CERTIFICATE REQUEST----- From 2c6ab382369e36f750ba32e6313ea45371b24524 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 9 Nov 2014 12:26:35 +0000 Subject: [PATCH 202/452] tidy up of files --- README.md | 3 --- .../github/dockerjava/api/model/ErrorDetail.java | 8 ++++++++ .../github/dockerjava/api/model/ErrorResponse.java | 14 ++++++++++++++ .../client/AbstractDockerClientTest.java | 13 +++++++------ 4 files changed, 29 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 46c75531..14b3c4ad 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,6 @@ Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/ * Java 1.6 * Maven 3.0.5 * Docker daemon running -* Docker private repository running (see below). - -You'll need to be running a local private registry, as per [these instructions](docker-auth-registry/README.md): If you need SSL, then you'll need to put your `*.pem` file into `~/.docker/`, if you're using boot2docker, do this: diff --git a/src/main/java/com/github/dockerjava/api/model/ErrorDetail.java b/src/main/java/com/github/dockerjava/api/model/ErrorDetail.java index bc9b9bba..8abffe6c 100644 --- a/src/main/java/com/github/dockerjava/api/model/ErrorDetail.java +++ b/src/main/java/com/github/dockerjava/api/model/ErrorDetail.java @@ -1,4 +1,12 @@ package com.github.dockerjava.api.model; +import com.fasterxml.jackson.annotation.JsonProperty; + public class ErrorDetail { + @JsonProperty + private String message; + + public String getMessage() { + return message; + } } diff --git a/src/main/java/com/github/dockerjava/api/model/ErrorResponse.java b/src/main/java/com/github/dockerjava/api/model/ErrorResponse.java index 9993d215..87d9b0d7 100644 --- a/src/main/java/com/github/dockerjava/api/model/ErrorResponse.java +++ b/src/main/java/com/github/dockerjava/api/model/ErrorResponse.java @@ -1,4 +1,18 @@ package com.github.dockerjava.api.model; +import com.fasterxml.jackson.annotation.JsonProperty; + public class ErrorResponse { + @JsonProperty + private ErrorDetail errorDetail; + @JsonProperty + private String error; + + public ErrorDetail getErrorDetail() { + return errorDetail; + } + + public String getError() { + return error; + } } diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index e0d198b8..2e94f230 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -47,15 +47,16 @@ public void beforeTest() { } private DockerClientConfig config() { - return config(DOCKER_JAVA); + return config(null); } protected DockerClientConfig config(String password) { - return DockerClientConfig.createDefaultConfigBuilder() - .withServerAddress("http://localhost:5001") - .withUsername(DOCKER_JAVA) - .withPassword(password) - .withEmail(DOCKER_JAVA + "@github.com") + DockerClientConfig.DockerClientConfigBuilder builder = DockerClientConfig.createDefaultConfigBuilder() + .withServerAddress("https://index.docker.io/v1/"); + if (password!=null) { + builder = builder.withPassword(password); + } + return builder .build(); } From 9503bc0872cf699918263a15a746625da46a0a93 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 9 Nov 2014 21:12:12 +0000 Subject: [PATCH 203/452] updated README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8ec4c012..6060cb97 100644 --- a/README.md +++ b/README.md @@ -81,10 +81,10 @@ There are a couple of configuration items, all of which have sensible defaults: * `url` The Docker URL, e.g. `https://localhost:2376`. * `version` The API version, e.g. `1.15`. -* `username` Your register username (required to push containers). -* `password` Your register password. -* `email` Your register email. -* `serverAddress` Your register's address. +* `username` Your registry username (required to push containers). +* `password` Your registry password. +* `email` Your registry email. +* `serverAddress` Your registry's address. * `dockerCertPath` Path to the docker certs. There are three ways to configure, in descending order of precedence: From df7294a86bbeaea3f4a6d33b7ca46c220e9a0971 Mon Sep 17 00:00:00 2001 From: Robert Szymczak Date: Wed, 12 Nov 2014 19:31:46 +0100 Subject: [PATCH 204/452] Update DockerClientBuilder.java Added method to allow changing the ClassPath used by ServiceLoader. --- .../com/github/dockerjava/core/DockerClientBuilder.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java b/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java index fb7783ce..d47120a0 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java @@ -48,6 +48,12 @@ public DockerClientBuilder withDockerCmdExecFactory( this.dockerCmdExecFactory = dockerCmdExecFactory; return this; } + + public DockerClientBuilder withServiceLoaderClassPath(ClassPath classPath) + { + serviceLoader = ServiceLoader.load(DockerCmdExecFactory.class, classPath); + return this; + } public DockerClient build() { if(dockerCmdExecFactory != null) { From 8c8c9f6ccce37a565416d411296eba6734d73ab0 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Thu, 13 Nov 2014 15:05:04 +0100 Subject: [PATCH 205/452] Removed comment regarding cloudbees --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 6060cb97..8931e36f 100644 --- a/README.md +++ b/README.md @@ -69,8 +69,6 @@ Run build without integration tests: 0.10.4-SNAPSHOT -Latest SNAPSHOT is published to maven repo: https://oss.sonatype.org/content/groups/public via ![Build on CloudBees](http://cloudbees.prod.acquia-sites.com/sites/default/files/styles/large/public/Button-Powered-by-CB.png?itok=uMDWINfY) - ## Documentation For code examples, please look at the [Wiki](https://github.com/docker-java/docker-java/wiki) or [Test cases](https://github.com/docker-java/docker-java/tree/master/src/test/java/com/github/dockerjava/core/command "Test cases") From 7ba7e76e8bbc97d21f3c4c89f2a48949a94b3022 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 13 Nov 2014 19:00:41 +0100 Subject: [PATCH 206/452] Fix compile error --- .../java/com/github/dockerjava/core/DockerClientBuilder.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java b/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java index d47120a0..155b36be 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java @@ -49,9 +49,9 @@ public DockerClientBuilder withDockerCmdExecFactory( return this; } - public DockerClientBuilder withServiceLoaderClassPath(ClassPath classPath) + public DockerClientBuilder withServiceLoaderClassLoader(ClassLoader classLoader) { - serviceLoader = ServiceLoader.load(DockerCmdExecFactory.class, classPath); + serviceLoader = ServiceLoader.load(DockerCmdExecFactory.class, classLoader); return this; } From 796d232fa824b32241d99399eaeff16bd05ea1cc Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Thu, 13 Nov 2014 20:03:48 +0100 Subject: [PATCH 207/452] use travis-ci --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..80b6f4b7 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,4 @@ +language: java +jdk: + - openjdk7 + - oraclejdk7 From 2de47d3e659382226d2f8bc8d3ad38c08f914e33 Mon Sep 17 00:00:00 2001 From: docker-java-maintain Date: Thu, 13 Nov 2014 20:33:47 +0100 Subject: [PATCH 208/452] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 8931e36f..0e15ad16 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,8 @@ Run build without integration tests: docker-java 0.10.4-SNAPSHOT + +TODO ## Documentation From 0432594a5c19496e741ab84abd55e03ae78e90ff Mon Sep 17 00:00:00 2001 From: docker-java-maintain Date: Thu, 13 Nov 2014 20:54:41 +0100 Subject: [PATCH 209/452] Update .travis.yml --- .travis.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 80b6f4b7..37d8d6c7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,6 @@ language: java jdk: - - openjdk7 - - oraclejdk7 + - oraclejdk7 +after_success: + - echo "ossrh\${env.OSSRH_USER}\${env.OSSRH_PASS}" > ~/settings.xml + - mvn deploy --settings ~/settings.xml From 4e2208052f046f8380e3e0cf1114a2da7e698e13 Mon Sep 17 00:00:00 2001 From: docker-java-maintain Date: Thu, 13 Nov 2014 21:05:38 +0100 Subject: [PATCH 210/452] Update .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 37d8d6c7..985c3569 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,4 +3,4 @@ jdk: - oraclejdk7 after_success: - echo "ossrh\${env.OSSRH_USER}\${env.OSSRH_PASS}" > ~/settings.xml - - mvn deploy --settings ~/settings.xml + - mvn deploy -DskipITs --settings ~/settings.xml From 515451074b8fbc84aef3ca829ce4772ffd9525a7 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Thu, 13 Nov 2014 21:59:52 +0100 Subject: [PATCH 211/452] Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 0e15ad16..364837e6 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ +[![Build Status](https://travis-ci.org/docker-java/docker-java.svg?branch=master)](https://travis-ci.org/docker-java/docker-java) # docker-java Java API client for [Docker](http://docs.docker.io/ "Docker") @@ -68,8 +69,6 @@ Run build without integration tests: docker-java 0.10.4-SNAPSHOT - -TODO ## Documentation From 0ae2f88980ff8ee14153e7387a559682cf786a7a Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 16 Nov 2014 16:11:51 +0000 Subject: [PATCH 212/452] Added CHANGELOG.md --- CHANGELOG.md | 111 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..5f16fab6 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,111 @@ +Change Log +=== + + * [#92](https://github.com/docker-java/docker-java/pull/92) Add travis-ci support + * [#90](https://github.com/docker-java/docker-java/pull/90) Update DockerClientBuilder.java + * [#88](https://github.com/docker-java/docker-java/pull/88) Add support for private repositories and pull/push authentication + +docker-java-0.10.3 +--- + + * [#87](https://github.com/docker-java/docker-java/pull/87) Improve adding of port bindings + * [#83](https://github.com/docker-java/docker-java/pull/83) Loading of custom DockerCmdExecFactory + * [#81](https://github.com/docker-java/docker-java/pull/81) Env config + * [#82](https://github.com/docker-java/docker-java/pull/82) Allow multiple port bindings per ExposedPort + * [#80](https://github.com/docker-java/docker-java/pull/80) explicitly use the latest image version + * [#79](https://github.com/docker-java/docker-java/pull/79) Move slow tests to integration test phase, enable tests by default + * [#76](https://github.com/docker-java/docker-java/pull/76) New enum \"InternetProtocol\" for supported IP protocols replaces \"scheme\" + * [#75](https://github.com/docker-java/docker-java/pull/75) Use ExposedPort.toString() in serialization + * [#74](https://github.com/docker-java/docker-java/pull/74) Use project.build.sourceEncoding in compiler + * [#73](https://github.com/docker-java/docker-java/pull/73) Improve parsing and serialization of Link + * [#70](https://github.com/docker-java/docker-java/pull/70) Improve instantiation and serialization of Bind + +docker-java-0.10.2 +--- + + * [#69](https://github.com/docker-java/docker-java/pull/69) Use canonical form of Docker folder when building TAR files + * [#68](https://github.com/docker-java/docker-java/pull/68) Set Jersey client CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE + * [#67](https://github.com/docker-java/docker-java/pull/67) typo in README.md + * [#65](https://github.com/docker-java/docker-java/pull/65) Added static method udp in ExposedPort + * [#63](https://github.com/docker-java/docker-java/pull/63) Bind.parse() fails when access mode is specified + * [#57](https://github.com/docker-java/docker-java/pull/57) Add streaming events API + * [#59](https://github.com/docker-java/docker-java/pull/59) Update readme to include corrected api example + * [#2](https://github.com/docker-java/docker-java/pull/2) Move to new maven coordinate com.github.docker-java:docker-java + * [#56](https://github.com/docker-java/docker-java/pull/56) Update README.md + * [#58](https://github.com/docker-java/docker-java/pull/58) Code clear and bug fix + +docker-java-0.10.1 +--- + + * [#49](https://github.com/docker-java/docker-java/pull/49) Allow user to check where volume is binded on host + * [#47](https://github.com/docker-java/docker-java/pull/47) let CompressArchiveUtil preserve executable flags + * [#46](https://github.com/docker-java/docker-java/pull/46) Fixes to AttachContainerCmd and CreateContainerCmd. + +docker-java-0.10.0 +--- + + * [#45](https://github.com/docker-java/docker-java/pull/45) Fix Issue #44 Adjusting DNS property type to be a String array as specified by the Doc... + * [#38](https://github.com/docker-java/docker-java/pull/38) Remove special-case for one \":\" from PullCommand + * [#37](https://github.com/docker-java/docker-java/pull/37) Starts v0.10.0 + * [#35](https://github.com/docker-java/docker-java/pull/35) Exposing the withTTY method for container creation. + +docker-java-0.9.1 +--- + + * [#31](https://github.com/docker-java/docker-java/pull/31) Change VolumesFrom to handle array + * [#29](https://github.com/docker-java/docker-java/pull/29) Makes Config a public, immutable class with a builder + * [#22](https://github.com/docker-java/docker-java/pull/22) Fixes for startContainerCmd + * [#19](https://github.com/docker-java/docker-java/pull/19) Add missing options to BuildCmd and set them to match Docker client. + * [#16](https://github.com/docker-java/docker-java/pull/16) Build image improvements + +docker-java-0.9.0 +--- + + * [#14](https://github.com/docker-java/docker-java/pull/14) Use RegEx to match ADD command from Dockerfile. + * [#9](https://github.com/docker-java/docker-java/pull/9) Add a build command accepting a tar as a InputStream, so we can build the Dockerfile TAR on the fly without a temporary folder. + +docker-java-0.8.2 +--- + + * [#2](https://github.com/docker-java/docker-java/pull/2) Move to new maven coordinate com.github.docker-java:docker-java + * [#1](https://github.com/docker-java/docker-java/pull/1) Merge + * [#2](https://github.com/docker-java/docker-java/pull/2) Move to new maven coordinate com.github.docker-java:docker-java + * [#66](https://github.com/docker-java/docker-java/pull/66) Backport the new structure to Jersey 1.18 + * [#65](https://github.com/docker-java/docker-java/pull/65) Added static method udp in ExposedPort + * [#61](https://github.com/docker-java/docker-java/pull/61) + * [#60](https://github.com/docker-java/docker-java/pull/60) Added additional callback methods to EventCallback + * [#1](https://github.com/docker-java/docker-java/pull/1) Merge + * [#55](https://github.com/docker-java/docker-java/pull/55) + * [#58](https://github.com/docker-java/docker-java/pull/58) Code clear and bug fix + * [#54](https://github.com/docker-java/docker-java/pull/54) + * [#3](https://github.com/docker-java/docker-java/pull/3) + * [#2](https://github.com/docker-java/docker-java/pull/2) Move to new maven coordinate com.github.docker-java:docker-java + * [#1](https://github.com/docker-java/docker-java/pull/1) Merge + * [#34](https://github.com/docker-java/docker-java/pull/34) + * [#36](https://github.com/docker-java/docker-java/pull/36) + * [#37](https://github.com/docker-java/docker-java/pull/37) Starts v0.10.0 + * [#32](https://github.com/docker-java/docker-java/pull/32) + +docker-java-0.8.1 +--- + + +docker-java-0.8.1 +--- + + * [#28](https://github.com/docker-java/docker-java/pull/28) Improves use of docker-java in unit tests + * [#30](https://github.com/docker-java/docker-java/pull/30) Add ping method + * [#27](https://github.com/docker-java/docker-java/pull/27) Added a close method to DockerClient + * [#26](https://github.com/docker-java/docker-java/pull/26) + * [#24](https://github.com/docker-java/docker-java/pull/24) + * [#23](https://github.com/docker-java/docker-java/pull/23) + * [#22](https://github.com/docker-java/docker-java/pull/22) Fixes for startContainerCmd + * [#20](https://github.com/docker-java/docker-java/pull/20) + * [#19](https://github.com/docker-java/docker-java/pull/19) Add missing options to BuildCmd and set them to match Docker client. + * [#18](https://github.com/docker-java/docker-java/pull/18) Added Container-Linking + * [#16](https://github.com/docker-java/docker-java/pull/16) Build image improvements + * [#15](https://github.com/docker-java/docker-java/pull/15) Collection of changes driven by use in gradle-docker and on Windows + * [#14](https://github.com/docker-java/docker-java/pull/14) Use RegEx to match ADD command from Dockerfile. + * [#9](https://github.com/docker-java/docker-java/pull/9) Add a build command accepting a tar as a InputStream, so we can build the Dockerfile TAR on the fly without a temporary folder. + * [#5](https://github.com/docker-java/docker-java/pull/5) add paused field in ContainerInspectResponse + * [#6](https://github.com/docker-java/docker-java/pull/6) From f98b90469e5bd9e42c188430e9f167634efd5333 Mon Sep 17 00:00:00 2001 From: Ted Crossman Date: Mon, 17 Nov 2014 09:39:20 -0800 Subject: [PATCH 213/452] Add support for .dockerignore files --- .../dockerjava/core/CompressArchiveUtil.java | 2 +- .../dockerjava/core/GoLangFileMatch.java | 257 ++++++++++++++++++ .../core/GoLangFileMatchException.java | 10 + .../core/GoLangMatchFileFilter.java | 27 ++ .../core/command/BuildImageCmdImpl.java | 39 ++- .../dockerjava/core/GoLangFileMatchTest.java | 122 +++++++++ .../core/command/BuildImageCmdImplTest.java | 23 ++ .../testDockerfileIgnored/.dockerignore | 2 + .../testDockerfileIgnored/Dockerfile | 9 + .../testDockerfileIgnored/testrun.sh | 3 + .../resources/testDockerignore/.dockerignore | 1 + .../resources/testDockerignore/Dockerfile | 10 + src/test/resources/testDockerignore/a/a | 0 src/test/resources/testDockerignore/a/b | 0 src/test/resources/testDockerignore/a/c | 0 src/test/resources/testDockerignore/a/d | 0 .../resources/testDockerignore/testrun.sh | 3 + .../.dockerignore | 3 + .../testInvalidDockerignorePattern/Dockerfile | 9 + .../testInvalidDockerignorePattern/testrun.sh | 3 + 20 files changed, 518 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/core/GoLangFileMatch.java create mode 100644 src/main/java/com/github/dockerjava/core/GoLangFileMatchException.java create mode 100644 src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java create mode 100644 src/test/java/com/github/dockerjava/core/GoLangFileMatchTest.java create mode 100644 src/test/resources/testDockerfileIgnored/.dockerignore create mode 100644 src/test/resources/testDockerfileIgnored/Dockerfile create mode 100755 src/test/resources/testDockerfileIgnored/testrun.sh create mode 100644 src/test/resources/testDockerignore/.dockerignore create mode 100644 src/test/resources/testDockerignore/Dockerfile create mode 100644 src/test/resources/testDockerignore/a/a create mode 100644 src/test/resources/testDockerignore/a/b create mode 100644 src/test/resources/testDockerignore/a/c create mode 100644 src/test/resources/testDockerignore/a/d create mode 100755 src/test/resources/testDockerignore/testrun.sh create mode 100644 src/test/resources/testInvalidDockerignorePattern/.dockerignore create mode 100644 src/test/resources/testInvalidDockerignorePattern/Dockerfile create mode 100755 src/test/resources/testInvalidDockerignorePattern/testrun.sh diff --git a/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java b/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java index a9a97238..f07fa1b2 100644 --- a/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java +++ b/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java @@ -37,7 +37,7 @@ public static File archiveTARFiles(File base, Iterable files, String archi return tarFile; } - private static String relativize(File base, File absolute) { + public static String relativize(File base, File absolute) { String relative = base.toURI().relativize(absolute.toURI()).getPath(); return relative; } diff --git a/src/main/java/com/github/dockerjava/core/GoLangFileMatch.java b/src/main/java/com/github/dockerjava/core/GoLangFileMatch.java new file mode 100644 index 00000000..a84bce5b --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/GoLangFileMatch.java @@ -0,0 +1,257 @@ +/** + * Copyright (C) 2014 SignalFuse, Inc. + */ +package com.github.dockerjava.core; + +import java.io.File; +import java.util.List; + +import org.apache.commons.lang.StringUtils; + +/** + * Implementation of golang's file.Match + * + * Match returns true if name matches the shell file name pattern. The pattern syntax is: + * + *

+ *  pattern:
+ *          { term }
+ *   term:
+ *       '*'         matches any sequence of non-Separator characters
+ *      '?'         matches any single non-Separator character
+ *       '[' [ '^' ] { character-range } ']'
+ *                  character class (must be non-empty)
+ *       c           matches character c (c != '*', '?', '\\', '[')
+ *       '\\' c      matches character c
+ *
+ *   character-range:
+ *       c           matches character c (c != '\\', '-', ']')
+ *       '\\' c      matches character c
+ *       lo '-' hi   matches character c for lo <= c <= hi
+ *
+ *  Match requires pattern to match all of name, not just a substring.
+ *  The only possible returned error is ErrBadPattern, when pattern
+ *  is malformed.
+ *
+ * On Windows, escaping is disabled. Instead, '\\' is treated as
+ *  path separator.
+ * 
+ * + * @author tedo + * + */ +public class GoLangFileMatch { + + public static final boolean IS_WINDOWS = File.separatorChar == '\\'; + + public static boolean match(List patterns, File file) { + return match(patterns, file.getPath()); + } + + public static boolean match(String pattern, File file) { + return match(pattern, file.getPath()); + } + + public static boolean match(List patterns, String name) { + for (String pattern : patterns) { + if (match(pattern, name)) { + return true; + } + } + return false; + } + + public static boolean match(String pattern, String name) { + Pattern: while (!pattern.isEmpty()) { + ScanResult scanResult = scanChunk(pattern); + pattern = scanResult.pattern; + if (scanResult.star && StringUtils.isEmpty(scanResult.chunk)) { + // Trailing * matches rest of string unless it has a /. + return name.indexOf(File.separatorChar) < 0; + } + // Look for match at current position. + String matchResult = matchChunk(scanResult.chunk, name); + + // if we're the last chunk, make sure we've exhausted the name + // otherwise we'll give a false result even if we could still match + // using the star + if (matchResult != null && (matchResult.isEmpty() || !pattern.isEmpty())) { + name = matchResult; + continue; + } + if (scanResult.star) { + for (int i = 0; i < name.length() && name.charAt(i) != File.separatorChar; i++) { + matchResult = matchChunk(scanResult.chunk, name.substring(i + 1)); + if (matchResult != null) { + // if we're the last chunk, make sure we exhausted the name + if (pattern.isEmpty() && !matchResult.isEmpty()) { + continue; + } + name = matchResult; + continue Pattern; + } + } + } + return false; + } + return name.isEmpty(); + } + + static ScanResult scanChunk(String pattern) { + boolean star = false; + if (!pattern.isEmpty() && pattern.charAt(0) == '*') { + pattern = pattern.substring(1); + star = true; + } + boolean inRange = false; + int i; + Scan: for (i = 0; i < pattern.length(); i++) { + switch (pattern.charAt(i)) { + case '\\': { + if (!IS_WINDOWS) { + // error check handled in matchChunk: bad pattern. + if (i + 1 < pattern.length()) { + i++; + } + } + break; + } + case '[': + inRange = true; + break; + case ']': + inRange = false; + break; + case '*': + if (!inRange) { + break Scan; + } + } + } + return new ScanResult(star, pattern.substring(0, i), pattern.substring(i)); + } + + static String matchChunk(String chunk, String s) { + int chunkLength = chunk.length(); + int chunkOffset = 0; + int sLength = s.length(); + int sOffset = 0; + char r; + while (chunkOffset < chunkLength) { + if (sOffset == sLength) { + return null; + } + switch (chunk.charAt(chunkOffset)) { + case '[': + r = s.charAt(sOffset); + sOffset++; + chunkOffset++; + // We can't end right after '[', we're expecting at least + // a closing bracket and possibly a caret. + if (chunkOffset == chunkLength) { + throw new GoLangFileMatchException(); + } + // possibly negated + boolean negated = chunk.charAt(chunkOffset) == '^'; + if (negated) { + chunkOffset++; + } + // parse all ranges + boolean match = false; + int nrange = 0; + while (true) { + if (chunkOffset < chunkLength && chunk.charAt(chunkOffset) == ']' && nrange > 0) { + chunkOffset++; + break; + } + GetEscResult result = getEsc(chunk, chunkOffset, chunkLength); + char lo = result.lo; + char hi = lo; + chunkOffset = result.chunkOffset; + if (chunk.charAt(chunkOffset) == '-') { + result = getEsc(chunk, ++chunkOffset, chunkLength); + chunkOffset = result.chunkOffset; + hi = result.lo; + } + if (lo <= r && r <= hi) { + match = true; + } + nrange++; + } + if (match == negated) { + return null; + } + break; + + case '?': + if (s.charAt(sOffset) == File.separatorChar) { + return null; + } + sOffset++; + chunkOffset++; + break; + case '\\': + if (!IS_WINDOWS) { + chunkOffset++; + if (chunkOffset == chunkLength) { + throw new GoLangFileMatchException(); + } + } + // fallthrough + default: + if (chunk.charAt(chunkOffset) != s.charAt(sOffset)) { + return null; + } + sOffset++; + chunkOffset++; + } + } + return s.substring(sOffset); + } + + static GetEscResult getEsc(String chunk, int chunkOffset, int chunkLength) { + if (chunkOffset == chunkLength) { + throw new GoLangFileMatchException(); + } + char r = chunk.charAt(chunkOffset); + if (r == '-' || r == ']') { + throw new GoLangFileMatchException(); + } + if (r == '\\' && !IS_WINDOWS) { + chunkOffset++; + if (chunkOffset == chunkLength) { + throw new GoLangFileMatchException(); + } + + } + r = chunk.charAt(chunkOffset); + chunkOffset++; + if (chunkOffset == chunkLength) { + throw new GoLangFileMatchException(); + } + return new GetEscResult(r, chunkOffset); + } + + private static final class ScanResult { + public boolean star; + public String chunk; + public String pattern; + + public ScanResult(boolean star, String chunk, String pattern) { + this.star = star; + this.chunk = chunk; + this.pattern = pattern; + } + } + + private static final class GetEscResult { + public char lo; + public int chunkOffset; + + public GetEscResult(char lo, int chunkOffset) { + this.lo = lo; + this.chunkOffset = chunkOffset; + } + } + +} diff --git a/src/main/java/com/github/dockerjava/core/GoLangFileMatchException.java b/src/main/java/com/github/dockerjava/core/GoLangFileMatchException.java new file mode 100644 index 00000000..d1f35393 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/GoLangFileMatchException.java @@ -0,0 +1,10 @@ +/** + * Copyright (C) 2014 SignalFuse, Inc. + */ +package com.github.dockerjava.core; + +public class GoLangFileMatchException extends IllegalArgumentException { + + private static final long serialVersionUID = -1204971075600864898L; + +} diff --git a/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java b/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java new file mode 100644 index 00000000..cfd32a7e --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java @@ -0,0 +1,27 @@ +/** + * Copyright (C) 2014 SignalFuse, Inc. + */ +package com.github.dockerjava.core; + +import java.io.File; +import java.util.List; + +import org.apache.commons.io.filefilter.AbstractFileFilter; + +public class GoLangMatchFileFilter extends AbstractFileFilter { + + private final List patterns; + + + public GoLangMatchFileFilter(List patterns) { + super(); + this.patterns = patterns; + } + + @Override + public boolean accept(File file) { + return !GoLangFileMatch.match(patterns, file); + } + + +} diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 4948ce45..3884a374 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -14,11 +14,15 @@ import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.filefilter.TrueFileFilter; import com.github.dockerjava.api.DockerClientException; import com.github.dockerjava.api.command.BuildImageCmd; import com.github.dockerjava.core.CompressArchiveUtil; - +import com.github.dockerjava.core.GoLangFileMatch; +import com.github.dockerjava.core.GoLangFileMatchException; +import com.github.dockerjava.core.GoLangMatchFileFilter; import com.google.common.base.Preconditions; /** @@ -158,6 +162,30 @@ protected InputStream buildDockerFolderTar(File dockerFolder) { "Dockerfile %s is empty", dockerFile)); } + List ignores = new ArrayList(); + File dockerIgnoreFile = new File(dockerFolder, ".dockerignore"); + if (dockerIgnoreFile.exists()) { + int lineNumber = 0; + List dockerIgnoreFileContent = FileUtils.readLines(dockerIgnoreFile); + for (String pattern: dockerIgnoreFileContent) { + lineNumber++; + pattern = pattern.trim(); + if (pattern.isEmpty()) { + continue; // skip empty lines + } + pattern = FilenameUtils.normalize(pattern); + try { + // validate pattern and make sure we aren't excluding Dockerfile + if (GoLangFileMatch.match(pattern, "Dockerfile")) { + throw new DockerClientException( + String.format("Dockerfile is excluded by pattern '%s' on line %s in .dockerignore file", pattern, lineNumber)); + } + ignores.add(pattern); + } catch (GoLangFileMatchException e) { + throw new DockerClientException(String.format("Invalid pattern '%s' on line %s in .dockerignore file", pattern, lineNumber)); + } + } + } List filesToAdd = new ArrayList(); filesToAdd.add(dockerFile); @@ -215,10 +243,13 @@ protected InputStream buildDockerFolderTar(File dockerFolder) { "Source file %s doesn't exist", src)); } if (src.isDirectory()) { - filesToAdd.addAll(FileUtils.listFiles(src, null, - true)); - } else { + filesToAdd.addAll(FileUtils.listFiles(src, + new GoLangMatchFileFilter(ignores), TrueFileFilter.INSTANCE)); + } else if (!GoLangFileMatch.match(ignores, CompressArchiveUtil.relativize(dockerFolder, src))){ filesToAdd.add(src); + } else { + throw new DockerClientException(String.format( + "Source file %s is excluded by .dockerignore file", src)); } } } diff --git a/src/test/java/com/github/dockerjava/core/GoLangFileMatchTest.java b/src/test/java/com/github/dockerjava/core/GoLangFileMatchTest.java new file mode 100644 index 00000000..b556a7e5 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/GoLangFileMatchTest.java @@ -0,0 +1,122 @@ +/** + * Copyright (C) 2014 SignalFuse, Inc. + */ +package com.github.dockerjava.core; + +import java.io.File; +import java.io.IOException; + +import junit.framework.Assert; + +import org.apache.commons.io.FilenameUtils; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class GoLangFileMatchTest { + + @Test(dataProvider = "getTestData") + public void testMatch(MatchTestCase testCase) throws IOException { + String pattern = testCase.pattern; + String s = testCase.s; + if (GoLangFileMatch.IS_WINDOWS) { + if (pattern.indexOf('\\') > 0) { + // no escape allowed on windows. + return; + } + pattern = FilenameUtils.normalize(pattern); + s = FilenameUtils.normalize(s); + } + try { + boolean matched = GoLangFileMatch.match(pattern, s); + if (testCase.expectException) { + Assert.fail("Expected GoFileMatchException"); + } + Assert.assertEquals(testCase.matches, matched); + } catch (GoLangFileMatchException e) { + if (!testCase.expectException) { + throw e; + } + } + } + + @DataProvider + public Object[][] getTestData() { + return new Object[][] { + new Object[] { new MatchTestCase("abc", "abc", true, false) }, + new Object[] { new MatchTestCase("*", "abc", true, false) }, + new Object[] { new MatchTestCase("*c", "abc", true, false) }, + new Object[] { new MatchTestCase("a*", "a", true, false) }, + new Object[] { new MatchTestCase("a*", "abc", true, false) }, + new Object[] { new MatchTestCase("a*", "ab/c", false, false) }, + new Object[] { new MatchTestCase("a*/b", "abc/b", true, false) }, + new Object[] { new MatchTestCase("a*/b", "a/c/b", false, false) }, + new Object[] { new MatchTestCase("a*b*c*d*e*/f", "axbxcxdxe/f", true, false) }, + new Object[] { new MatchTestCase("a*b*c*d*e*/f", "axbxcxdxexxx/f", true, false) }, + new Object[] { new MatchTestCase("a*b*c*d*e*/f", "axbxcxdxe/xxx/f", false, false) }, + new Object[] { new MatchTestCase("a*b*c*d*e*/f", "axbxcxdxexxx/fff", false, false) }, + new Object[] { new MatchTestCase("a*b?c*x", "abxbbxdbxebxczzx", true, false) }, + new Object[] { new MatchTestCase("a*b?c*x", "abxbbxdbxebxczzy", false, false) }, + new Object[] { new MatchTestCase("ab[c]", "abc", true, false) }, + new Object[] { new MatchTestCase("ab[b-d]", "abc", true, false) }, + new Object[] { new MatchTestCase("ab[e-g]", "abc", false, false) }, + new Object[] { new MatchTestCase("ab[^c]", "abc", false, false) }, + new Object[] { new MatchTestCase("ab[^b-d]", "abc", false, false) }, + new Object[] { new MatchTestCase("ab[^e-g]", "abc", true, false) }, + new Object[] { new MatchTestCase("a\\*b", "a*b", true, false) }, + new Object[] { new MatchTestCase("a\\*b", "ab", false, false) }, + new Object[] { new MatchTestCase("a?b", "a☺b", true, false) }, + new Object[] { new MatchTestCase("a[^a]b", "a☺b", true, false) }, + new Object[] { new MatchTestCase("a???b", "a☺b", false, false) }, + new Object[] { new MatchTestCase("a[^a][^a][^a]b", "a☺b", false, false) }, + new Object[] { new MatchTestCase("[a-ζ]*", "α", true, false) }, + new Object[] { new MatchTestCase("*[a-ζ]", "A", false, false) }, + new Object[] { new MatchTestCase("a?b", "a/b", false, false) }, + new Object[] { new MatchTestCase("a*b", "a/b", false, false) }, + new Object[] { new MatchTestCase("[\\]a]", "]", true, false) }, + new Object[] { new MatchTestCase("[\\-]", "-", true, false) }, + new Object[] { new MatchTestCase("[x\\-]", "x", true, false) }, + new Object[] { new MatchTestCase("[x\\-]", "-", true, false) }, + new Object[] { new MatchTestCase("[x\\-]", "z", false, false) }, + new Object[] { new MatchTestCase("[\\-x]", "x", true, false) }, + new Object[] { new MatchTestCase("[\\-x]", "-", true, false) }, + new Object[] { new MatchTestCase("[\\-x]", "a", false, false) }, + new Object[] { new MatchTestCase("[]a]", "]", false, true) }, + new Object[] { new MatchTestCase("[-]", "-", false, true) }, + new Object[] { new MatchTestCase("[x-]", "x", false, true) }, + new Object[] { new MatchTestCase("[x-]", "-", false, true) }, + new Object[] { new MatchTestCase("[x-]", "z", false, true) }, + new Object[] { new MatchTestCase("[-x]", "x", false, true) }, + new Object[] { new MatchTestCase("[-x]", "-", false, true) }, + new Object[] { new MatchTestCase("[-x]", "a", false, true) }, + new Object[] { new MatchTestCase("\\", "a", false, true) }, + new Object[] { new MatchTestCase("[a-b-c]", "a", false, true) }, + new Object[] { new MatchTestCase("[", "a", false, true) }, + new Object[] { new MatchTestCase("[^", "a", false, true) }, + new Object[] { new MatchTestCase("[^bc", "a", false, true) }, + new Object[] { new MatchTestCase("a[", "a", false, false) }, + new Object[] { new MatchTestCase("a[", "ab", false, true) }, + new Object[] { new MatchTestCase("*x", "xxx", true, false) } }; + } + + private final class MatchTestCase { + private final String pattern; + private final String s; + private final boolean matches; + private final boolean expectException; + + public MatchTestCase(String pattern, String s, boolean matches, boolean expectException) { + super(); + this.pattern = pattern; + this.s = s; + this.matches = matches; + this.expectException = expectException; + } + + @Override + public String toString() { + return "MatchTestCase [pattern=" + pattern + ", s=" + s + ", matches=" + matches + + ", expectException=" + expectException + "]"; + } + } + +} diff --git a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index 62603706..7ae29e53 100644 --- a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -22,6 +22,7 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.github.dockerjava.api.DockerClientException; import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; @@ -132,6 +133,28 @@ private InputStream logContainer(String containerId) { return dockerClient.logContainerCmd(containerId).withStdErr().withStdOut().exec(); } + @Test(expectedExceptions={DockerClientException.class}) + public void testDockerfileIgnored() { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("testDockerfileIgnored").getFile()); + dockerClient.buildImageCmd(baseDir).withNoCache().exec(); + } + + @Test(expectedExceptions={DockerClientException.class}) + public void testInvalidDockerIgnorePattern() { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("testInvalidDockerignorePattern").getFile()); + dockerClient.buildImageCmd(baseDir).withNoCache().exec(); + } + + @Test + public void testDockerIgnore() throws DockerException, + IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("testDockerignore").getFile()); + dockerfileBuild(baseDir, "/tmp/a/a /tmp/a/c /tmp/a/d"); + } + @Test public void testNetCatDockerfileBuilder() throws InterruptedException { File baseDir = new File(Thread.currentThread().getContextClassLoader() diff --git a/src/test/resources/testDockerfileIgnored/.dockerignore b/src/test/resources/testDockerfileIgnored/.dockerignore new file mode 100644 index 00000000..9e00faa1 --- /dev/null +++ b/src/test/resources/testDockerfileIgnored/.dockerignore @@ -0,0 +1,2 @@ +Dockerfile +*~ \ No newline at end of file diff --git a/src/test/resources/testDockerfileIgnored/Dockerfile b/src/test/resources/testDockerfileIgnored/Dockerfile new file mode 100644 index 00000000..8a4a6776 --- /dev/null +++ b/src/test/resources/testDockerfileIgnored/Dockerfile @@ -0,0 +1,9 @@ +FROM ubuntu:latest + +# Copy testrun.sh files into the container + +ADD ./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/testDockerfileIgnored/testrun.sh b/src/test/resources/testDockerfileIgnored/testrun.sh new file mode 100755 index 00000000..80b468e7 --- /dev/null +++ b/src/test/resources/testDockerfileIgnored/testrun.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Successfully executed testrun.sh" diff --git a/src/test/resources/testDockerignore/.dockerignore b/src/test/resources/testDockerignore/.dockerignore new file mode 100644 index 00000000..61780798 --- /dev/null +++ b/src/test/resources/testDockerignore/.dockerignore @@ -0,0 +1 @@ +b diff --git a/src/test/resources/testDockerignore/Dockerfile b/src/test/resources/testDockerignore/Dockerfile new file mode 100644 index 00000000..97b93b89 --- /dev/null +++ b/src/test/resources/testDockerignore/Dockerfile @@ -0,0 +1,10 @@ +FROM ubuntu:latest + +# Copy testrun.sh files into the container + +ADD ./testrun.sh /tmp/ +ADD ./a /tmp/a + +RUN cp /tmp/testrun.sh /usr/local/bin/ && chmod +x /usr/local/bin/testrun.sh + +CMD ["testrun.sh"] diff --git a/src/test/resources/testDockerignore/a/a b/src/test/resources/testDockerignore/a/a new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/testDockerignore/a/b b/src/test/resources/testDockerignore/a/b new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/testDockerignore/a/c b/src/test/resources/testDockerignore/a/c new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/testDockerignore/a/d b/src/test/resources/testDockerignore/a/d new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/testDockerignore/testrun.sh b/src/test/resources/testDockerignore/testrun.sh new file mode 100755 index 00000000..a6f7f3fe --- /dev/null +++ b/src/test/resources/testDockerignore/testrun.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +echo /tmp/a/* diff --git a/src/test/resources/testInvalidDockerignorePattern/.dockerignore b/src/test/resources/testInvalidDockerignorePattern/.dockerignore new file mode 100644 index 00000000..89be209e --- /dev/null +++ b/src/test/resources/testInvalidDockerignorePattern/.dockerignore @@ -0,0 +1,3 @@ +*~ +[a-b-c] + diff --git a/src/test/resources/testInvalidDockerignorePattern/Dockerfile b/src/test/resources/testInvalidDockerignorePattern/Dockerfile new file mode 100644 index 00000000..8a4a6776 --- /dev/null +++ b/src/test/resources/testInvalidDockerignorePattern/Dockerfile @@ -0,0 +1,9 @@ +FROM ubuntu:latest + +# Copy testrun.sh files into the container + +ADD ./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/testInvalidDockerignorePattern/testrun.sh b/src/test/resources/testInvalidDockerignorePattern/testrun.sh new file mode 100755 index 00000000..80b468e7 --- /dev/null +++ b/src/test/resources/testInvalidDockerignorePattern/testrun.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Successfully executed testrun.sh" From f625b85a70e3bac09a7f5d0a3ae101ca2618ef29 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 17 Nov 2014 21:52:47 +0100 Subject: [PATCH 214/452] Fix issue #94 --- pom.xml | 101 ++++++++++++++++++++++++++++++++------------------------ 1 file changed, 58 insertions(+), 43 deletions(-) diff --git a/pom.xml b/pom.xml index 89fb8831..c4f1fc36 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 @@ -56,7 +57,7 @@ 4.2.5 1.5 - 1.8 + 1.8 2.3 2.6 1.7.5 @@ -88,11 +89,11 @@ jackson-jaxrs-json-provider ${jackson-jaxrs.version} - - - - - + + + + + org.glassfish.jersey.core jersey-client @@ -104,11 +105,11 @@ commons-compress ${commons-compress.version} - - commons-codec - commons-codec - ${commons-codec.version} - + + commons-codec + commons-codec + ${commons-codec.version} + commons-lang commons-lang @@ -139,16 +140,16 @@ - com.google.guava - guava - ${guava.version} - - - - org.bouncycastle - bcpkix-jdk15on - ${bouncycastle.version} - + com.google.guava + guava + ${guava.version} + + + + org.bouncycastle + bcpkix-jdk15on + ${bouncycastle.version} + @@ -300,6 +301,32 @@ + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + attach-javadocs + + jar + + + + @@ -349,12 +376,20 @@ integration - **/*Test.java + **/*Test.java + + org.apache.maven.plugins + maven-source-plugin + + + org.apache.maven.plugins + maven-javadoc-plugin + @@ -376,33 +411,13 @@ - org.apache.maven.plugins maven-source-plugin - 2.2.1 - - - attach-sources - - jar-no-fork - - - - org.apache.maven.plugins maven-javadoc-plugin - 2.9.1 - - - attach-javadocs - - jar - - - From 39130d3f6ffe28c00de1db60630914cfa036e8f4 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 17 Nov 2014 21:53:49 +0100 Subject: [PATCH 215/452] fix GoLangMatchFileFilter --- .../github/dockerjava/core/GoLangMatchFileFilter.java | 10 ++++++++-- .../dockerjava/core/command/BuildImageCmdImpl.java | 8 ++++---- src/test/resources/testDockerignore/.dockerignore | 2 +- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java b/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java index cfd32a7e..b0bb05c0 100644 --- a/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java +++ b/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java @@ -10,17 +10,23 @@ public class GoLangMatchFileFilter extends AbstractFileFilter { + private final File base; + private final List patterns; - public GoLangMatchFileFilter(List patterns) { + public GoLangMatchFileFilter(File base, List patterns) { super(); + this.base = base; this.patterns = patterns; } @Override public boolean accept(File file) { - return !GoLangFileMatch.match(patterns, file); + String relativePath = file.getAbsolutePath().replaceFirst(base.getAbsolutePath() + File.separatorChar, ""); + + boolean match = GoLangFileMatch.match(patterns, relativePath); + return !match; } diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 3884a374..a62b75c0 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -6,6 +6,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -29,8 +30,6 @@ * * Build an image from Dockerfile. * - * TODO: http://docs.docker.com/reference/builder/#dockerignore - * */ public class BuildImageCmdImpl extends AbstrDockerCmd implements BuildImageCmd { @@ -243,8 +242,9 @@ protected InputStream buildDockerFolderTar(File dockerFolder) { "Source file %s doesn't exist", src)); } if (src.isDirectory()) { - filesToAdd.addAll(FileUtils.listFiles(src, - new GoLangMatchFileFilter(ignores), TrueFileFilter.INSTANCE)); + Collection files = FileUtils.listFiles(src, + new GoLangMatchFileFilter(src, ignores), TrueFileFilter.INSTANCE); + filesToAdd.addAll(files); } else if (!GoLangFileMatch.match(ignores, CompressArchiveUtil.relativize(dockerFolder, src))){ filesToAdd.add(src); } else { diff --git a/src/test/resources/testDockerignore/.dockerignore b/src/test/resources/testDockerignore/.dockerignore index 61780798..63d8dbd4 100644 --- a/src/test/resources/testDockerignore/.dockerignore +++ b/src/test/resources/testDockerignore/.dockerignore @@ -1 +1 @@ -b +b \ No newline at end of file From 6dc4eb290063743fcd8e3c6751f360fbe83c1788 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Tue, 18 Nov 2014 07:23:58 +0100 Subject: [PATCH 216/452] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f16fab6..d233238f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ Change Log === - + * [#95](https://github.com/docker-java/docker-java/pull/95) Add support for .dockerignore files * [#92](https://github.com/docker-java/docker-java/pull/92) Add travis-ci support * [#90](https://github.com/docker-java/docker-java/pull/90) Update DockerClientBuilder.java * [#88](https://github.com/docker-java/docker-java/pull/88) Add support for private repositories and pull/push authentication From 7a8e37971cd71b8936b47df0df5a72717b29a20e Mon Sep 17 00:00:00 2001 From: Robert Szymczak Date: Fri, 21 Nov 2014 14:15:13 +0100 Subject: [PATCH 217/452] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 364837e6..d07fed2f 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,8 @@ Run build without integration tests: ### Latest SNAPSHOT version +You can find the latest SNAPSHOT version including javadoc and source files on [Sonatypes OSS repository](https://oss.sonatype.org/content/groups/public/com/github/docker-java/docker-java/). + com.github.docker-java From eeeabc9e8f9e1965624f53e4ca43bb8f10689020 Mon Sep 17 00:00:00 2001 From: Ted Crossman Date: Fri, 21 Nov 2014 17:42:11 -0800 Subject: [PATCH 218/452] Add support for .dockercfg files to handle auth for push command --- .../dockerjava/api/model/AuthConfig.java | 62 ++++++++ .../dockerjava/core/AuthConfigFile.java | 146 ++++++++++++++++++ .../dockerjava/core/DockerClientConfig.java | 34 +++- .../dockerjava/core/DockerClientImpl.java | 57 ++++--- .../core/InvalidRepositoryNameException.java | 15 ++ .../github/dockerjava/core/NameParser.java | 100 ++++++++++++ src/main/resources/docker.io.properties | 1 + .../dockerjava/core/AuthConfigFileTest.java | 95 ++++++++++++ .../core/DockerClientConfigTest.java | 7 +- .../dockerjava/core/DockerClientImplTest.java | 2 +- .../resources/testAuthConfigFile/emptyFile | 0 .../testAuthConfigFile/invalidJsonInvalidAuth | 1 + .../testAuthConfigFile/invalidLegacyAuthLine | 2 + .../testAuthConfigFile/invalidLegacyEmailLine | 2 + .../invalidLegacyInvalidAuth | 2 + .../resources/testAuthConfigFile/tooSmallFile | 1 + .../resources/testAuthConfigFile/validJson | 1 + .../resources/testAuthConfigFile/validLegacy | 2 + 18 files changed, 502 insertions(+), 28 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/core/AuthConfigFile.java create mode 100644 src/main/java/com/github/dockerjava/core/InvalidRepositoryNameException.java create mode 100644 src/main/java/com/github/dockerjava/core/NameParser.java create mode 100644 src/test/java/com/github/dockerjava/core/AuthConfigFileTest.java create mode 100644 src/test/resources/testAuthConfigFile/emptyFile create mode 100644 src/test/resources/testAuthConfigFile/invalidJsonInvalidAuth create mode 100644 src/test/resources/testAuthConfigFile/invalidLegacyAuthLine create mode 100644 src/test/resources/testAuthConfigFile/invalidLegacyEmailLine create mode 100644 src/test/resources/testAuthConfigFile/invalidLegacyInvalidAuth create mode 100644 src/test/resources/testAuthConfigFile/tooSmallFile create mode 100644 src/test/resources/testAuthConfigFile/validJson create mode 100644 src/test/resources/testAuthConfigFile/validLegacy diff --git a/src/main/java/com/github/dockerjava/api/model/AuthConfig.java b/src/main/java/com/github/dockerjava/api/model/AuthConfig.java index d7f0deab..87307bb5 100644 --- a/src/main/java/com/github/dockerjava/api/model/AuthConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/AuthConfig.java @@ -1,5 +1,6 @@ package com.github.dockerjava.api.model; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; public class AuthConfig { @@ -23,6 +24,8 @@ public class AuthConfig { @JsonProperty("serveraddress") private String serverAddress = DEFAULT_SERVER_ADDRESS; + private String auth; + public String getUsername() { return username; } @@ -55,6 +58,16 @@ public void setServerAddress(String serverAddress) { this.serverAddress = serverAddress; } + @JsonIgnore + public String getAuth() { + return auth; + } + + @JsonProperty("auth") + public void setAuth(String auth) { + this.auth = auth; + } + @Override public String toString() { return "AuthConfig{" + @@ -64,4 +77,53 @@ public String toString() { ", serverAddress='" + serverAddress + '\'' + '}'; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((auth == null) ? 0 : auth.hashCode()); + result = prime * result + ((email == null) ? 0 : email.hashCode()); + result = prime * result + ((password == null) ? 0 : password.hashCode()); + result = prime * result + ((serverAddress == null) ? 0 : serverAddress.hashCode()); + result = prime * result + ((username == null) ? 0 : username.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AuthConfig other = (AuthConfig) obj; + if (auth == null) { + if (other.auth != null) + return false; + } else if (!auth.equals(other.auth)) + return false; + if (email == null) { + if (other.email != null) + return false; + } else if (!email.equals(other.email)) + return false; + if (password == null) { + if (other.password != null) + return false; + } else if (!password.equals(other.password)) + return false; + if (serverAddress == null) { + if (other.serverAddress != null) + return false; + } else if (!serverAddress.equals(other.serverAddress)) + return false; + if (username == null) { + if (other.username != null) + return false; + } else if (!username.equals(other.username)) + return false; + return true; + } } diff --git a/src/main/java/com/github/dockerjava/core/AuthConfigFile.java b/src/main/java/com/github/dockerjava/core/AuthConfigFile.java new file mode 100644 index 00000000..24c7aa5c --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/AuthConfigFile.java @@ -0,0 +1,146 @@ +package com.github.dockerjava.core; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringUtils; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.model.AuthConfig; + +public class AuthConfigFile { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final TypeReference> CONFIG_MAP_TYPE = new TypeReference>() {}; + private final Map authConfigMap; + + public AuthConfigFile() { + authConfigMap = new HashMap(); + } + + void addConfig(AuthConfig config) { + authConfigMap.put(config.getServerAddress(), config); + } + + public AuthConfig resolveAuthConfig(String hostname) { + if (StringUtils.isEmpty(hostname) || AuthConfig.DEFAULT_SERVER_ADDRESS.equals(hostname)) { + return authConfigMap.get(AuthConfig.DEFAULT_SERVER_ADDRESS); + } + AuthConfig c = authConfigMap.get(hostname); + if (c != null) { + return c; + } + + // Maybe they have a legacy config file, we will iterate the keys converting + // them to the new format and testing + String normalizedHostname = convertToHostname(hostname); + for (Map.Entry entry : authConfigMap.entrySet()) { + String registry = entry.getKey(); + AuthConfig config = entry.getValue(); + if (convertToHostname(registry).equals(normalizedHostname)) { + return config; + } + } + return null; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((authConfigMap == null) ? 0 : authConfigMap.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AuthConfigFile other = (AuthConfigFile) obj; + if (authConfigMap == null) { + if (other.authConfigMap != null) + return false; + } else if (!authConfigMap.equals(other.authConfigMap)) + return false; + return true; + } + + @Override + public String toString() { + return "AuthConfigFile [authConfigMap=" + authConfigMap + "]"; + } + + + public static AuthConfigFile loadConfig(File confFile) throws IOException { + AuthConfigFile configFile = new AuthConfigFile(); + if (!confFile.exists()) { + return new AuthConfigFile(); + } + Map configMap = null; + try { + configMap = MAPPER.readValue(confFile, CONFIG_MAP_TYPE); + } catch (IOException e) { + // pass + } + if (configMap != null) { + for (Map.Entry entry : configMap.entrySet()) { + AuthConfig authConfig = entry.getValue(); + decodeAuth(authConfig.getAuth(), authConfig); + authConfig.setAuth(null); + authConfig.setServerAddress(entry.getKey()); + configFile.addConfig(authConfig); + } + } else { + List authFileContent = FileUtils.readLines(confFile); + if (authFileContent.size() < 2) { + throw new IOException("The Auth Config file is empty"); + } + AuthConfig config = new AuthConfig(); + String[] origAuth = authFileContent.get(0).split(" = "); + if (origAuth.length != 2) { + throw new IOException("Invalid Auth config file"); + } + decodeAuth(origAuth[1], config); + + String[] origEmail = authFileContent.get(1).split(" = "); + if (origEmail.length != 2) { + throw new IOException("Invalid Auth config file"); + } + config.setEmail(origEmail[1]); + configFile.addConfig(config); + } + return configFile; + + } + + static void decodeAuth(String auth, AuthConfig config) throws IOException { + String str = new String(Base64.decodeBase64(auth), Charset.forName("UTF-8")); + String[] parts = str.split(":", 2); + if (parts.length != 2) { + throw new IOException("Invalid auth configuration file"); + } + config.setUsername(parts[0]); + config.setPassword(parts[1]); + } + + static String convertToHostname(String server) { + String stripped = server; + if (server.startsWith("http://")) { + stripped = server.substring(7); + } else if (server.startsWith("https://")) { + stripped = server.substring(8); + } + String[] numParts = stripped.split("/", 2); + return numParts[0]; + } +} diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 9f1694b5..ff1329c6 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -23,6 +23,7 @@ public class DockerClientConfig { // this is really confusing, as there are two ways to spell it private static final String DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY = "docker.io.enableLoggingFilter"; private static final String DOCKER_IO_DOCKER_CERT_PATH_PROPERTY = "docker.io.dockerCertPath"; + private static final String DOCKER_IO_DOCKER_CFG_PATH_PROPERTY = "docker.io.dockerCfgPath"; /** * A map from the environment name to the interval name. */ @@ -36,14 +37,15 @@ public class DockerClientConfig { .put("DOCKER_READ_TIMEOUT", DOCKER_IO_READ_TIMEOUT_PROPERTY) .put("DOCKER_LOGGING_FILTER_ENABLED", DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY) .put(DOCKER_CERT_PATH_PROPERTY, DOCKER_IO_DOCKER_CERT_PATH_PROPERTY) + .put("DOCKER_CFG_PATH", DOCKER_IO_DOCKER_CFG_PATH_PROPERTY) .build(); private static final String DOCKER_IO_PROPERTIES_PROPERTY = "docker.io.properties"; private final URI uri; - private final String version, username, password, email, serverAddress, dockerCertPath; + private final String version, username, password, email, serverAddress, dockerCertPath, dockerCfgPath; private final Integer readTimeout; private final boolean loggingFilterEnabled; - DockerClientConfig(URI uri, String version, String username, String password, String email, String serverAddress, String dockerCertPath, Integer readTimeout, boolean loggingFilterEnabled) { + DockerClientConfig(URI uri, String version, String username, String password, String email, String serverAddress, String dockerCertPath, String dockerCfgPath, Integer readTimeout, boolean loggingFilterEnabled) { this.uri = uri; this.version = version; this.username = username; @@ -51,6 +53,7 @@ public class DockerClientConfig { this.email = email; this.serverAddress = serverAddress; this.dockerCertPath = dockerCertPath; + this.dockerCfgPath = dockerCfgPath; this.readTimeout = readTimeout; this.loggingFilterEnabled = loggingFilterEnabled; } @@ -153,6 +156,7 @@ private static Properties overrideDockerPropertiesWithSystemProperties(Propertie DOCKER_IO_READ_TIMEOUT_PROPERTY, DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY, DOCKER_IO_DOCKER_CERT_PATH_PROPERTY, + DOCKER_IO_DOCKER_CFG_PATH_PROPERTY, }) { if (systemProperties.containsKey(key)) { overriddenProperties.setProperty(key, systemProperties.getProperty(key)); @@ -212,6 +216,10 @@ public String getDockerCertPath() { return dockerCertPath; } + public String getDockerCfgPath() { + return dockerCfgPath; + } + @Override public boolean equals(Object o) { if (this == o) return true; @@ -222,6 +230,8 @@ public boolean equals(Object o) { if (loggingFilterEnabled != that.loggingFilterEnabled) return false; if (dockerCertPath != null ? !dockerCertPath.equals(that.dockerCertPath) : that.dockerCertPath != null) return false; + if (dockerCfgPath != null ? !dockerCfgPath.equals(that.dockerCfgPath) : that.dockerCfgPath != null) + return false; if (email != null ? !email.equals(that.email) : that.email != null) return false; if (password != null ? !password.equals(that.password) : that.password != null) return false; if (readTimeout != null ? !readTimeout.equals(that.readTimeout) : that.readTimeout != null) return false; @@ -243,6 +253,7 @@ public int hashCode() { result = 31 * result + (email != null ? email.hashCode() : 0); result = 31 * result + (serverAddress != null ? serverAddress.hashCode() : 0); result = 31 * result + (dockerCertPath != null ? dockerCertPath.hashCode() : 0); + result = 31 * result + (dockerCfgPath != null ? dockerCfgPath.hashCode() : 0); result = 31 * result + (readTimeout != null ? readTimeout.hashCode() : 0); result = 31 * result + (loggingFilterEnabled ? 1 : 0); return result; @@ -258,6 +269,7 @@ public String toString() { ", email='" + email + '\'' + ", serverAddress='" + serverAddress + '\'' + ", dockerCertPath='" + dockerCertPath + '\'' + + ", dockerCfgPath='" + dockerCfgPath + '\'' + ", readTimeout=" + readTimeout + ", loggingFilterEnabled=" + loggingFilterEnabled + '}'; @@ -265,15 +277,15 @@ public String toString() { public static class DockerClientConfigBuilder { private URI uri; - private String version, username, password, email, serverAddress, dockerCertPath; + private String version, username, password, email, serverAddress, dockerCertPath, dockerCfgPath; private Integer readTimeout; private boolean loggingFilterEnabled; /** * This will set all fields in the builder to those contained in the Properties object. The Properties object - * should contain the following docker.io.* keys: url, version, username, password, email, and dockerCertPath. If - * docker.io.readTimeout or docker.io.enableLoggingFilter are not contained, they will be set to 1000 and true, - * respectively. + * should contain the following docker.io.* keys: url, version, username, password, email, dockerCertPath, and + * dockerCfgPath. If docker.io.readTimeout or docker.io.enableLoggingFilter are not contained, they will be set + * to 1000 and true, respectively. */ public DockerClientConfigBuilder withProperties(Properties p) { return withUri(p.getProperty(DOCKER_IO_URL_PROPERTY)) @@ -284,7 +296,8 @@ public DockerClientConfigBuilder withProperties(Properties p) { .withServerAddress(p.getProperty(DOCKER_IO_SERVER_ADDRESS_PROPERTY)) .withReadTimeout(Integer.valueOf(p.getProperty(DOCKER_IO_READ_TIMEOUT_PROPERTY, "0"))) .withLoggingFilter(Boolean.valueOf(p.getProperty(DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY, "true"))) - .withDockerCertPath(p.getProperty(DOCKER_IO_DOCKER_CERT_PATH_PROPERTY)); + .withDockerCertPath(p.getProperty(DOCKER_IO_DOCKER_CERT_PATH_PROPERTY)) + .withDockerCfgPath(p.getProperty(DOCKER_IO_DOCKER_CFG_PATH_PROPERTY)); } public final DockerClientConfigBuilder withUri(String uri) { @@ -333,6 +346,12 @@ public final DockerClientConfigBuilder withDockerCertPath(String dockerCertPath) return this; } + public final DockerClientConfigBuilder withDockerCfgPath(String dockerCfgPath) { + this.dockerCfgPath = dockerCfgPath; + return this; + } + + public DockerClientConfig build() { return new DockerClientConfig( uri, @@ -342,6 +361,7 @@ public DockerClientConfig build() { email, serverAddress, dockerCertPath, + dockerCfgPath, readTimeout, loggingFilterEnabled ); diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 2630d26d..1a2a58c0 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -8,21 +8,24 @@ import java.io.InputStream; import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.DockerClientException; import com.github.dockerjava.api.command.*; import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.core.NameParser.HostnameReposName; +import com.github.dockerjava.core.NameParser.ReposTag; import com.github.dockerjava.core.command.*; import com.google.common.base.Preconditions; /** * @author Konstantin Pelykh (kpelykh@gmail.com) - * + * * @see https://github.com/docker/docker/blob/master/api/client/commands.go */ public class DockerClientImpl implements Closeable, DockerClient { private final DockerClientConfig dockerClientConfig; - - private DockerCmdExecFactory dockerCmdExecFactory; + + private DockerCmdExecFactory dockerCmdExecFactory; private DockerClientImpl() { this(DockerClientConfig.createDefaultConfigBuilder().build()); @@ -36,25 +39,25 @@ private DockerClientImpl(DockerClientConfig dockerClientConfig) { Preconditions.checkNotNull(dockerClientConfig, "config was not specified"); this.dockerClientConfig = dockerClientConfig; } - + private static DockerClientConfig configWithServerUrl(String serverUrl) { return DockerClientConfig.createDefaultConfigBuilder() .withUri(serverUrl) .build(); } - + public static DockerClientImpl getInstance() { return new DockerClientImpl(); } - + public static DockerClientImpl getInstance(DockerClientConfig dockerClientConfig) { return new DockerClientImpl(dockerClientConfig); } - + public static DockerClientImpl getInstance(String serverUrl) { return new DockerClientImpl(serverUrl); } - + public DockerClientImpl withDockerCmdExecFactory( DockerCmdExecFactory dockerCmdExecFactory) { Preconditions.checkNotNull(dockerCmdExecFactory, "dockerCmdExecFactory was not specified"); @@ -62,13 +65,14 @@ public DockerClientImpl withDockerCmdExecFactory( this.dockerCmdExecFactory.init(dockerClientConfig); return this; } - + private DockerCmdExecFactory getDockerCmdExecFactory() { Preconditions.checkNotNull(dockerCmdExecFactory, "dockerCmdExecFactory was not specified"); return dockerCmdExecFactory; } - + + @Override public AuthConfig authConfig() { checkNotNull(dockerClientConfig.getUsername(), "Configured username is null."); checkNotNull(dockerClientConfig.getServerAddress(), "Configured serverAddress is null."); @@ -92,7 +96,7 @@ public AuthConfig authConfig() { @Override public AuthCmd authCmd() { return new AuthCmdImpl(getDockerCmdExecFactory().createAuthCmdExec(), authConfig()); - } + } @Override public InfoCmd infoCmd() { @@ -102,7 +106,7 @@ public InfoCmd infoCmd() { @Override public PingCmd pingCmd() { return new PingCmdImpl(getDockerCmdExecFactory().createPingCmdExec()); - } + } @Override public VersionCmd versionCmd() { @@ -120,7 +124,24 @@ public PullImageCmd pullImageCmd(String repository) { @Override public PushImageCmd pushImageCmd(String name) { - return new PushImageCmdImpl(getDockerCmdExecFactory().createPushImageCmdExec(), name); + PushImageCmd cmd = new PushImageCmdImpl(getDockerCmdExecFactory().createPushImageCmdExec(), + name); + String dockerCfgFile = dockerClientConfig.getDockerCfgPath(); + if (dockerCfgFile != null) { + AuthConfigFile authConfigFile; + try { + authConfigFile = AuthConfigFile.loadConfig(new File(dockerCfgFile)); + } catch (IOException e) { + throw new DockerClientException("Failed to parse dockerCfgFile", e); + } + ReposTag reposTag = NameParser.parseRepositoryTag(name); + HostnameReposName hostnameReposName = NameParser.resolveRepositoryName(reposTag.repos); + AuthConfig authConfig = authConfigFile.resolveAuthConfig(hostnameReposName.hostname); + if (authConfig != null) { + cmd.withAuthConfig(authConfig); + } + } + return cmd; } @Override @@ -132,7 +153,7 @@ public CreateImageCmd createImageCmd(String repository, InputStream imageStream) public SearchImagesCmd searchImagesCmd(String term) { return new SearchImagesCmdImpl(getDockerCmdExecFactory().createSearchImagesCmdExec(), term); } - + @Override public RemoveImageCmd removeImageCmd(String imageId) { return new RemoveImageCmdImpl(getDockerCmdExecFactory().createRemoveImageCmdExec(), imageId); @@ -171,7 +192,7 @@ public StartContainerCmd startContainerCmd(String containerId) { public InspectContainerCmd inspectContainerCmd(String containerId) { return new InspectContainerCmdImpl(getDockerCmdExecFactory().createInspectContainerCmdExec(), containerId); } - + @Override public RemoveContainerCmd removeContainerCmd(String containerId) { return new RemoveContainerCmdImpl(getDockerCmdExecFactory().createRemoveContainerCmdExec(), containerId); @@ -196,7 +217,7 @@ public LogContainerCmd logContainerCmd(String containerId) { public CopyFileFromContainerCmd copyFileFromContainerCmd(String containerId, String resource) { return new CopyFileFromContainerCmdImpl(getDockerCmdExecFactory().createCopyFileFromContainerCmdExec(), containerId, resource); } - + @Override public ContainerDiffCmd containerDiffCmd(String containerId) { return new ContainerDiffCmdImpl(getDockerCmdExecFactory().createContainerDiffCmdExec(), containerId); @@ -206,7 +227,7 @@ public ContainerDiffCmd containerDiffCmd(String containerId) { public StopContainerCmd stopContainerCmd(String containerId) { return new StopContainerCmdImpl(getDockerCmdExecFactory().createStopContainerCmdExec(), containerId); } - + @Override public KillContainerCmd killContainerCmd(String containerId) { return new KillContainerCmdImpl(getDockerCmdExecFactory().createKillContainerCmdExec(), containerId); @@ -246,7 +267,7 @@ public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { public PauseContainerCmd pauseContainerCmd(String containerId) { return new PauseContainerCmdImpl(getDockerCmdExecFactory().createPauseContainerCmdExec(), containerId); } - + @Override public UnpauseContainerCmd unpauseContainerCmd(String containerId) { return new UnpauseContainerCmdImpl(getDockerCmdExecFactory().createUnpauseContainerCmdExec(), containerId); diff --git a/src/main/java/com/github/dockerjava/core/InvalidRepositoryNameException.java b/src/main/java/com/github/dockerjava/core/InvalidRepositoryNameException.java new file mode 100644 index 00000000..8885fc75 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/InvalidRepositoryNameException.java @@ -0,0 +1,15 @@ +package com.github.dockerjava.core; + +public class InvalidRepositoryNameException extends IllegalArgumentException { + + private static final long serialVersionUID = -6908709623436840513L; + + public InvalidRepositoryNameException() { + super(); + } + + public InvalidRepositoryNameException(String s) { + super(s); + } + +} diff --git a/src/main/java/com/github/dockerjava/core/NameParser.java b/src/main/java/com/github/dockerjava/core/NameParser.java new file mode 100644 index 00000000..6b165408 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/NameParser.java @@ -0,0 +1,100 @@ +/** + * Copyright (C) 2014 SignalFuse, Inc. + */ +package com.github.dockerjava.core; + +import java.util.regex.Pattern; + +import com.github.dockerjava.api.model.AuthConfig; + +public class NameParser { + + private static final Pattern VALID_HEX_PATTERN = Pattern.compile("^([a-f0-9]{64})$"); + private static final Pattern VALID_NAMESPACE_PATTERN = Pattern.compile("^([a-z0-9_]{4,30})$"); + private static final Pattern VALID_REPO_PATTERN = Pattern.compile("^([a-z0-9-_.]+)$"); + + public static ReposTag parseRepositoryTag(String name) { + int n = name.lastIndexOf(':'); + if (n < 0) { + return new ReposTag(name, ""); + } + String tag = name.substring(n + 1); + if (!tag.contains("/")) { + return new ReposTag(name.substring(0, n), tag); + } + return new ReposTag(name, ""); + } + + public static class ReposTag { + public final String repos; + public final String tag; + + public ReposTag(String repos, String tag) { + this.repos = repos; + this.tag = tag; + } + } + + public static void validateRepositoryName(String repositoryName) { + String name; + String namespace; + String[] nameParts = repositoryName.split("/", 2); + if (nameParts.length < 2) { + namespace = "library"; + name = nameParts[0]; + if (VALID_HEX_PATTERN.matcher(name).matches()) { + throw new InvalidRepositoryNameException(String.format( + "Invalid repository name (%s), cannot specify 64-byte hexadecimal strings", + name)); + } + } else { + namespace = nameParts[0]; + name = nameParts[1]; + } + if (!VALID_NAMESPACE_PATTERN.matcher(namespace).matches()) { + throw new InvalidRepositoryNameException( + String.format( + "Invalid namespace name (%s), only [a-z0-9_] are allowed, size between 4 and 30", + namespace)); + } + if (!VALID_REPO_PATTERN.matcher(name).matches()) { + throw new InvalidRepositoryNameException(String.format( + "Invalid repository name (%s), only [a-z0-9-_.] are allowed", name)); + } + } + + public static HostnameReposName resolveRepositoryName(String reposName) { + if (reposName.contains("://")) { + // It cannot contain a scheme! + throw new InvalidRepositoryNameException(); + } + + String[] nameParts = reposName.split("/", 2); + if (nameParts.length == 1 + || (!nameParts[0].contains(".") && !nameParts[0].contains(":") && !nameParts[0] + .equals("localhost"))) { + return new HostnameReposName(AuthConfig.DEFAULT_SERVER_ADDRESS, reposName); + } + + String hostname = nameParts[0]; + reposName = nameParts[1]; + if (hostname.contains("index.docker.io")) { + throw new InvalidRepositoryNameException(String.format( + "Invalid repository name, try \"%s\" instead", reposName)); + } + + validateRepositoryName(reposName); + return new HostnameReposName(hostname, reposName); + } + + public static class HostnameReposName { + public final String hostname; + public final String reposName; + + public HostnameReposName(String hostname, String reposName) { + this.hostname = hostname; + this.reposName = reposName; + } + + } +} diff --git a/src/main/resources/docker.io.properties b/src/main/resources/docker.io.properties index 2188cff3..6f0bfc86 100644 --- a/src/main/resources/docker.io.properties +++ b/src/main/resources/docker.io.properties @@ -1,5 +1,6 @@ docker.io.url=https://localhost:2376 docker.io.enableLoggingFilter=true docker.io.dockerCertPath=${user.home}/.docker +docker.io.dockerCfgPath=${user.home}/.dockercfg docker.io.username=${user.name} docker.io.serverAddress=https://index.docker.io/v1/ \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/core/AuthConfigFileTest.java b/src/test/java/com/github/dockerjava/core/AuthConfigFileTest.java new file mode 100644 index 00000000..e1c1b6f8 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/AuthConfigFileTest.java @@ -0,0 +1,95 @@ +/** + * Copyright (C) 2014 SignalFuse, Inc. + */ +package com.github.dockerjava.core; + +import java.io.File; +import java.io.IOException; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.github.dockerjava.api.model.AuthConfig; + +public class AuthConfigFileTest { + + private final File FILESROOT = new File(Thread.currentThread().getContextClassLoader() + .getResource("testAuthConfigFile").getFile()); + + @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "The Auth Config file is empty") + public void emptyFile() throws IOException { + runTest("emptyFile"); + } + + @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "The Auth Config file is empty") + public void tooSmallFile() throws IOException { + runTest("tooSmallFile"); + } + + @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "Invalid auth configuration file") + public void invalidJsonInvalidAuth() throws IOException { + runTest("invalidJsonInvalidAuth"); + } + + @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "Invalid Auth config file") + public void invalidLegacyAuthLine() throws IOException { + runTest("invalidLegacyAuthLine"); + } + + @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "Invalid auth configuration file") + public void invalidLegacyInvalidAuth() throws IOException { + runTest("invalidLegacyInvalidAuth"); + } + + @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "Invalid Auth config file") + public void invalidLegacyEmailLine() throws IOException { + runTest("invalidLegacyEmailLine"); + } + + @Test + public void validJson() throws IOException { + AuthConfig authConfig1 = new AuthConfig(); + authConfig1.setEmail("foo@example.com"); + authConfig1.setUsername("foo"); + authConfig1.setPassword("bar"); + authConfig1.setServerAddress("quay.io"); + + AuthConfig authConfig2 = new AuthConfig(); + authConfig2.setEmail("moo@example.com"); + authConfig2.setUsername("foo1"); + authConfig2.setPassword("bar1"); + authConfig2.setServerAddress(AuthConfig.DEFAULT_SERVER_ADDRESS); + + AuthConfigFile expected = new AuthConfigFile(); + expected.addConfig(authConfig1); + expected.addConfig(authConfig2); + + Assert.assertEquals(runTest("validJson"), expected); + + } + + @Test + public void validLegacy() throws IOException { + AuthConfig authConfig = new AuthConfig(); + authConfig.setEmail("foo@example.com"); + authConfig.setUsername("foo"); + authConfig.setPassword("bar"); + authConfig.setServerAddress(AuthConfig.DEFAULT_SERVER_ADDRESS); + + AuthConfigFile expected = new AuthConfigFile(); + expected.addConfig(authConfig); + + Assert.assertEquals(runTest("validLegacy"), expected); + } + + @Test + public void nonExistent() throws IOException { + AuthConfigFile expected = new AuthConfigFile(); + Assert.assertEquals(runTest("idontexist"), expected); + } + + private AuthConfigFile runTest(String testFileName) throws IOException { + return AuthConfigFile.loadConfig(new File(FILESROOT, testFileName)); + } + +} diff --git a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java index f14640b0..06bb1ea1 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java @@ -16,12 +16,12 @@ public class DockerClientConfigTest { public static final DockerClientConfig EXAMPLE_CONFIG = newExampleConfig(); private static DockerClientConfig newExampleConfig() { - return new DockerClientConfig(URI.create("http://foo"), "bar", "baz", "qux", "blam", "wham", "flim", 877, false); + return new DockerClientConfig(URI.create("http://foo"), "bar", "baz", "qux", "blam", "wham", "flim", "flam", 877, false); } @Test public void string() throws Exception { - assertEquals("DockerClientConfig{uri=http://foo, version='bar', username='baz', password='qux', email='blam', serverAddress='wham', dockerCertPath='flim', readTimeout=877, loggingFilterEnabled=false}", + assertEquals("DockerClientConfig{uri=http://foo, version='bar', username='baz', password='qux', email='blam', serverAddress='wham', dockerCertPath='flim', dockerCfgPath='flam', readTimeout=877, loggingFilterEnabled=false}", EXAMPLE_CONFIG.toString()); } @@ -72,6 +72,7 @@ public void environment() throws Exception { env.put("DOCKER_EMAIL", "blam"); env.put("DOCKER_SERVER_ADDRESS", "wham"); env.put("DOCKER_CERT_PATH", "flim"); + env.put("DOCKER_CFG_PATH", "flam"); env.put("DOCKER_READ_TIMEOUT", "877"); env.put("DOCKER_LOGGING_FILTER_ENABLED", "false"); @@ -104,6 +105,7 @@ public void defaults() throws Exception { assertEquals(config.getVersion(), null); assertEquals(config.isLoggingFilterEnabled(), true); assertEquals(config.getDockerCertPath(), "someHomeDir/.docker"); + assertEquals(config.getDockerCfgPath(), "someHomeDir/.dockercfg"); } @Test @@ -118,6 +120,7 @@ public void systemProperties() throws Exception { systemProperties.setProperty("docker.io.email", "blam"); systemProperties.setProperty("docker.io.serverAddress", "wham"); systemProperties.setProperty("docker.io.dockerCertPath", "flim"); + systemProperties.setProperty("docker.io.dockerCfgPath", "flam"); systemProperties.setProperty("docker.io.readTimeout", "877"); systemProperties.setProperty("docker.io.enableLoggingFilter", "false"); diff --git a/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java b/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java index da1d7f8e..c31db1ba 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java @@ -10,7 +10,7 @@ public class DockerClientImplTest { @Test public void configuredInstanceAuthConfig() throws Exception { // given a config with null serverAddress - DockerClientConfig dockerClientConfig = new DockerClientConfig(null, null, "", "", "", null, null, 0, false); + DockerClientConfig dockerClientConfig = new DockerClientConfig(null, null, "", "", "", null, null, null, 0, false); DockerClientImpl dockerClient = DockerClientImpl.getInstance(dockerClientConfig); // when we get the auth config diff --git a/src/test/resources/testAuthConfigFile/emptyFile b/src/test/resources/testAuthConfigFile/emptyFile new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/testAuthConfigFile/invalidJsonInvalidAuth b/src/test/resources/testAuthConfigFile/invalidJsonInvalidAuth new file mode 100644 index 00000000..d0863065 --- /dev/null +++ b/src/test/resources/testAuthConfigFile/invalidJsonInvalidAuth @@ -0,0 +1 @@ +{"quay.io" : { "auth" : "Zm9vOmJhcg==", "email" :"foo@example.com"}, "https://index.docker.io/v1/" : {"auth" : "bW9vbzEyMw==", "email" : "moo@example.com"}} \ No newline at end of file diff --git a/src/test/resources/testAuthConfigFile/invalidLegacyAuthLine b/src/test/resources/testAuthConfigFile/invalidLegacyAuthLine new file mode 100644 index 00000000..7cbca287 --- /dev/null +++ b/src/test/resources/testAuthConfigFile/invalidLegacyAuthLine @@ -0,0 +1,2 @@ +auth =Zm9vOmJhcg== +email = foo@example.com \ No newline at end of file diff --git a/src/test/resources/testAuthConfigFile/invalidLegacyEmailLine b/src/test/resources/testAuthConfigFile/invalidLegacyEmailLine new file mode 100644 index 00000000..72d157b1 --- /dev/null +++ b/src/test/resources/testAuthConfigFile/invalidLegacyEmailLine @@ -0,0 +1,2 @@ +auth = Zm9vOmJhcg== +email =foo@example.com \ No newline at end of file diff --git a/src/test/resources/testAuthConfigFile/invalidLegacyInvalidAuth b/src/test/resources/testAuthConfigFile/invalidLegacyInvalidAuth new file mode 100644 index 00000000..d0af331a --- /dev/null +++ b/src/test/resources/testAuthConfigFile/invalidLegacyInvalidAuth @@ -0,0 +1,2 @@ +auth = bW9vbzEyMw== +email = foo@example.com \ No newline at end of file diff --git a/src/test/resources/testAuthConfigFile/tooSmallFile b/src/test/resources/testAuthConfigFile/tooSmallFile new file mode 100644 index 00000000..abf1731a --- /dev/null +++ b/src/test/resources/testAuthConfigFile/tooSmallFile @@ -0,0 +1 @@ +auth = Zm9vOmJhcg== \ No newline at end of file diff --git a/src/test/resources/testAuthConfigFile/validJson b/src/test/resources/testAuthConfigFile/validJson new file mode 100644 index 00000000..2b47e382 --- /dev/null +++ b/src/test/resources/testAuthConfigFile/validJson @@ -0,0 +1 @@ +{"quay.io" : { "auth" : "Zm9vOmJhcg==", "email" :"foo@example.com"}, "https://index.docker.io/v1/" : {"auth" : "Zm9vMTpiYXIx", "email" : "moo@example.com"}} \ No newline at end of file diff --git a/src/test/resources/testAuthConfigFile/validLegacy b/src/test/resources/testAuthConfigFile/validLegacy new file mode 100644 index 00000000..9d4e740d --- /dev/null +++ b/src/test/resources/testAuthConfigFile/validLegacy @@ -0,0 +1,2 @@ +auth = Zm9vOmJhcg== +email = foo@example.com \ No newline at end of file From 80b88a1ada17550f9da0dde652271aa682d7fdbe Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Mon, 24 Nov 2014 20:01:42 +0100 Subject: [PATCH 219/452] list filtered images as described in the remote api docs --- .../dockerjava/api/command/ListImagesCmd.java | 8 ++-- .../core/command/ListImagesCmdImpl.java | 20 ++++----- .../dockerjava/jaxrs/ListImagesCmdExec.java | 19 +++++---- .../client/AbstractDockerClientTest.java | 22 +++++----- .../core/command/ListImagesCmdImplTest.java | 42 ++++++++++++++++++- .../core/command/RemoveImageCmdImplTest.java | 8 ++-- 6 files changed, 81 insertions(+), 38 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/ListImagesCmd.java b/src/main/java/com/github/dockerjava/api/command/ListImagesCmd.java index 502af84c..fad6d1da 100644 --- a/src/main/java/com/github/dockerjava/api/command/ListImagesCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/ListImagesCmd.java @@ -8,18 +8,18 @@ * List images * * @param showAll - Show all images (by default filter out the intermediate images used to build) - * @param filter - TODO: undocumented in docker remote api reference + * @param filters - a json encoded value of the filters (a map[string][]string) to process on the images list. */ public interface ListImagesCmd extends DockerCmd> { - public String getFilter(); + public String getFilters(); public boolean hasShowAllEnabled(); public ListImagesCmd withShowAll(boolean showAll); - public ListImagesCmd withFilter(String filter); - + public ListImagesCmd withFilters(String filters); + public static interface Exec extends DockerCmdExec> { } diff --git a/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java index 95e36af8..451a0ac5 100644 --- a/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java @@ -11,21 +11,21 @@ * List images * * @param showAll - Show all images (by default filter out the intermediate images used to build) - * @param filter - TODO: undocumented in docker remote api reference + * @param filters - a json encoded value of the filters (a map[string][]string) to process on the images list. */ public class ListImagesCmdImpl extends AbstrDockerCmd> implements ListImagesCmd { - private String filter; - + private String filters; + private boolean showAll = false; - + public ListImagesCmdImpl(ListImagesCmd.Exec exec) { super(exec); } @Override - public String getFilter() { - return filter; + public String getFilters() { + return filters; } @Override @@ -40,9 +40,9 @@ public ListImagesCmd withShowAll(boolean showAll) { } @Override - public ListImagesCmd withFilter(String filter) { - Preconditions.checkNotNull(filter, "filter was not specified"); - this.filter = filter; + public ListImagesCmd withFilters(String filter) { + Preconditions.checkNotNull(filter, "filters have not been specified"); + this.filters = filter; return this; } @@ -50,7 +50,7 @@ public ListImagesCmd withFilter(String filter) { public String toString() { return new StringBuilder("images ") .append(showAll ? "--all=true" : "") - .append(filter != null ? "--filter " + filter : "") + .append(filters != null ? "--filter " + filters : "") .toString(); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java index 5a000a29..1a50f081 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java @@ -6,16 +6,19 @@ import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; +import com.google.common.net.UrlEscapers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.api.command.ListImagesCmd; import com.github.dockerjava.api.model.Image; +import static com.google.common.net.UrlEscapers.urlPathSegmentEscaper; + public class ListImagesCmdExec extends AbstrDockerCmdExec> implements ListImagesCmd.Exec { - + private static final Logger LOGGER = LoggerFactory.getLogger(ListImagesCmdExec.class); - + public ListImagesCmdExec(WebTarget baseResource) { super(baseResource); } @@ -24,15 +27,17 @@ public ListImagesCmdExec(WebTarget baseResource) { protected List execute(ListImagesCmd command) { WebTarget webResource = getBaseResource() .path("/images/json") - .queryParam("filter", command.getFilter()) + .queryParam("filters", urlPathSegmentEscaper().escape(command.getFilters())) .queryParam("all", command.hasShowAllEnabled() ? "1" : "0"); LOGGER.trace("GET: {}", webResource); - - List images = webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { - }); + + List images = webResource.request() + .accept(MediaType.APPLICATION_JSON) + .get(new GenericType>() { + }); LOGGER.trace("Response: {}", images); - + return images; } diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 2e94f230..4418a8d5 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -20,7 +20,7 @@ import java.net.ServerSocket; public abstract class AbstractDockerClientTest extends Assert { - + public static final Logger LOG = LoggerFactory .getLogger(AbstractDockerClientTest.class); public static final String DOCKER_JAVA = "dockerjava"; @@ -39,8 +39,8 @@ public void beforeTest() { LOG.info("Pulling image 'busybox'"); // need to block until image is pulled completely asString(dockerClient.pullImageCmd("busybox").withTag("latest").exec()); - - + + assertNotNull(dockerClient); LOG.info("======================= END OF BEFORETEST =======================\n\n"); @@ -75,7 +75,7 @@ public void afterMethod(ITestResult result) { for (String container : dockerCmdExecFactory.getContainerNames()) { LOG.info("Cleaning up temporary container {}", container); - + try { dockerClient.removeContainerCmd(container).withForce().exec(); } catch (DockerException ignore) { @@ -90,17 +90,17 @@ public void afterMethod(ITestResult result) { } catch (DockerException ignore) { ignore.printStackTrace(); } - } - + } + LOG.info( "################################## END OF {} ##################################\n", result.getName()); } protected String asString(InputStream response) { - + StringWriter logwriter = new StringWriter(); - + try { LineIterator itr = IOUtils.lineIterator( response, "UTF-8"); @@ -110,7 +110,7 @@ protected String asString(InputStream response) { logwriter.write(line + (itr.hasNext() ? "\n" : "")); //LOG.info("line: "+line); } - + return logwriter.toString(); } catch (IOException e) { throw new RuntimeException(e); @@ -118,12 +118,12 @@ protected String asString(InputStream response) { IOUtils.closeQuietly(response); } } - + // UTIL /** * Checks to see if a specific port is available. - * + * * @param port * the port to check for availability */ diff --git a/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java index b2f3b88e..34a5984d 100644 --- a/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java @@ -6,6 +6,7 @@ import java.lang.reflect.Method; import java.util.List; +import com.github.dockerjava.api.command.CreateContainerResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; @@ -25,7 +26,7 @@ public class ListImagesCmdImplTest extends AbstractDockerClientTest { public void beforeTest() throws DockerException { super.beforeTest(); } - + @AfterTest public void afterTest() { super.afterTest(); @@ -40,7 +41,7 @@ public void beforeMethod(Method method) { public void afterMethod(ITestResult result) { super.afterMethod(result); } - + @Test public void listImages() throws DockerException { List images = dockerClient.listImagesCmd().withShowAll(true).exec(); @@ -57,5 +58,42 @@ public void listImages() throws DockerException { assertThat(img.getRepoTags(), not(emptyArray())); } + @Test + public void listDanglingImages() throws DockerException { + String imageId = createDanglingImage(); + List images = dockerClient.listImagesCmd() + .withFilters("{\"dangling\":[\"true\"]}") + .withShowAll(true).exec(); + assertThat(images, notNullValue()); + LOG.info("Images List: {}", images); + assertThat(images.size(), is(greaterThan(0))); + boolean imageInFilteredList = isImageInFilteredList(images, imageId); + assertTrue(imageInFilteredList); + } + private boolean isImageInFilteredList(List images, String expectedImageId) { + for (Image image : images) { + if (expectedImageId.equals(image.getId())) { + return true; + } + } + return false; + } + + private String createDanglingImage() { + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "5").exec(); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + dockerClient.startContainerCmd(container.getId()).exec(); + + LOG.info("Committing container {}", container.toString()); + String imageId = dockerClient + .commitCmd(container.getId()).exec(); + + dockerClient.stopContainerCmd(container.getId()).exec(); + dockerClient.killContainerCmd(container.getId()).exec(); + dockerClient.removeContainerCmd(container.getId()).exec(); + return imageId; + } } diff --git a/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java index ec6b6ec3..a2a190f6 100644 --- a/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java @@ -59,11 +59,11 @@ public void removeImage() throws DockerException, InterruptedException { LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); - - LOG.info("Commiting container {}", container.toString()); + + LOG.info("Committing container {}", container.toString()); String imageId = dockerClient .commitCmd(container.getId()).exec(); - + dockerClient.stopContainerCmd(container.getId()).exec(); dockerClient.killContainerCmd(container.getId()).exec(); dockerClient.removeContainerCmd(container.getId()).exec(); @@ -72,7 +72,7 @@ public void removeImage() throws DockerException, InterruptedException { dockerClient.removeImageCmd(imageId).exec(); List containers = dockerClient.listContainersCmd().withShowAll(true).exec(); - + Matcher matcher = not(hasItem(hasField("id", startsWith(imageId)))); assertThat(containers, matcher); } From e037e68ca7b7493ee60846a5b6406489c6c42e9f Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 24 Nov 2014 20:46:43 +0100 Subject: [PATCH 220/452] send 'filters' parameter only if needed --- .../dockerjava/jaxrs/ListImagesCmdExec.java | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java index 1a50f081..1fe38617 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java @@ -15,9 +15,12 @@ import static com.google.common.net.UrlEscapers.urlPathSegmentEscaper; -public class ListImagesCmdExec extends AbstrDockerCmdExec> implements ListImagesCmd.Exec { +public class ListImagesCmdExec extends + AbstrDockerCmdExec> implements + ListImagesCmd.Exec { - private static final Logger LOGGER = LoggerFactory.getLogger(ListImagesCmdExec.class); + private static final Logger LOGGER = LoggerFactory + .getLogger(ListImagesCmdExec.class); public ListImagesCmdExec(WebTarget baseResource) { super(baseResource); @@ -25,10 +28,12 @@ public ListImagesCmdExec(WebTarget baseResource) { @Override protected List execute(ListImagesCmd command) { - WebTarget webResource = getBaseResource() - .path("/images/json") - .queryParam("filters", urlPathSegmentEscaper().escape(command.getFilters())) - .queryParam("all", command.hasShowAllEnabled() ? "1" : "0"); + WebTarget webResource = getBaseResource().path("/images/json") + .queryParam("all", command.hasShowAllEnabled() ? "1" : "0"); + + if (command.getFilters() != null) + webResource = webResource.queryParam("filters", + urlPathSegmentEscaper().escape(command.getFilters())); LOGGER.trace("GET: {}", webResource); From 66bbb693283cfa75fee84ea174a6c469fc195d9d Mon Sep 17 00:00:00 2001 From: Robert Szymczak Date: Wed, 26 Nov 2014 12:22:55 +0100 Subject: [PATCH 221/452] Downgraded jackson-jaxrs dependency version For better compatibility in jar-conflict szenarios I'd like to suggest to use jackson 2.1.2 as it seems that no 2.3.3 methods are in use yet. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c4f1fc36..87afc54e 100644 --- a/pom.xml +++ b/pom.xml @@ -53,7 +53,7 @@ 2.11 1.9 - 2.3.3 + 2.1.2 4.2.5 1.5 From eacdd1b95157a4bf0ed617e934eb976cd29ca0f2 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Wed, 26 Nov 2014 17:58:39 +0100 Subject: [PATCH 222/452] Make GoLangMatchFileFilter work on Windows Without this, BuildImageCmdImplTest.testDockerBuilderAddFolder() and BuildImageCmdImplTest.testDockerIgnore() both fail with java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 3 D:\Eclipse\Jenkins\docker-java\target\test-classes\testDockerignore\a\ ^ at java.util.regex.Pattern.error(Pattern.java:1924) at java.util.regex.Pattern.escape(Pattern.java:2416) at java.util.regex.Pattern.atom(Pattern.java:2164) at java.util.regex.Pattern.sequence(Pattern.java:2097) at java.util.regex.Pattern.expr(Pattern.java:1964) at java.util.regex.Pattern.compile(Pattern.java:1665) at java.util.regex.Pattern.(Pattern.java:1337) at java.util.regex.Pattern.compile(Pattern.java:1022) at java.lang.String.replaceFirst(String.java:2119) at com.github.dockerjava.core.GoLangMatchFileFilter.accept(GoLangMatchFileFilter.java:26) at org.apache.commons.io.filefilter.AndFileFilter.accept(AndFileFilter.java:122) at org.apache.commons.io.filefilter.OrFileFilter.accept(OrFileFilter.java:118) at java.io.File.listFiles(File.java:1285) --- .../github/dockerjava/core/GoLangMatchFileFilter.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java b/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java index b0bb05c0..aa88287b 100644 --- a/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java +++ b/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java @@ -3,6 +3,8 @@ */ package com.github.dockerjava.core; +import static org.apache.commons.lang.StringUtils.stripStart; + import java.io.File; import java.util.List; @@ -23,9 +25,10 @@ public GoLangMatchFileFilter(File base, List patterns) { @Override public boolean accept(File file) { - String relativePath = file.getAbsolutePath().replaceFirst(base.getAbsolutePath() + File.separatorChar, ""); - - boolean match = GoLangFileMatch.match(patterns, relativePath); + String basePath = base.getAbsolutePath() + File.separatorChar; + String relativePath = stripStart(file.getAbsolutePath(), basePath); + + boolean match = GoLangFileMatch.match(patterns, relativePath); return !match; } From b9f29723f9eadf6d1358afee16c042b2ecd27c8c Mon Sep 17 00:00:00 2001 From: Vojtech Juranek Date: Mon, 1 Dec 2014 15:21:36 +0100 Subject: [PATCH 223/452] Allow to pass HostConfig when creating a container * Move HostConfig into separate class * Use Links for container links instead of String * Add API for passing HostConfig when creating a container --- .../api/command/CreateContainerCmd.java | 6 + .../api/command/InspectContainerResponse.java | 116 ---------- .../dockerjava/api/model/HostConfig.java | 204 ++++++++++++++++++ .../dockerjava/api/model/PortBinding.java | 1 - .../github/dockerjava/api/model/Ports.java | 1 - .../core/command/CreateContainerCmdImpl.java | 16 +- .../command/CreateContainerCmdImplTest.java | 41 +++- 7 files changed, 264 insertions(+), 121 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/HostConfig.java diff --git a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java index e6e2e2c7..dde2079a 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java @@ -3,6 +3,8 @@ import com.github.dockerjava.api.ConflictException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.model.ExposedPort; +import com.github.dockerjava.api.model.HostConfig; +import com.github.dockerjava.api.model.Links; import com.github.dockerjava.api.model.Volume; public interface CreateContainerCmd extends DockerCmd{ @@ -94,6 +96,10 @@ public interface CreateContainerCmd extends DockerCmd{ public String[] getVolumesFrom(); public CreateContainerCmd withVolumesFrom(String... volumesFrom); + + public HostConfig getHostConfig(); + + public CreateContainerCmd withHostConfig(HostConfig hostConfig); /** diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java index 32156745..5ac4f44e 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java @@ -234,121 +234,5 @@ public String toString() { } } - @JsonIgnoreProperties(ignoreUnknown = true) - public class HostConfig { - - @JsonProperty("Binds") - private String[] binds; - - @JsonProperty("LxcConf") - private LxcConf[] lxcConf; - - @JsonProperty("PortBindings") - private Ports portBindings; - - @JsonProperty("PublishAllPorts") - private boolean publishAllPorts; - - @JsonProperty("Privileged") - private boolean privileged; - - @JsonProperty("Dns") - private String[] dns; - - @JsonProperty("DnsSearch") - private String[] dnsSearch; - - @JsonProperty("VolumesFrom") - private String[] volumesFrom; - - @JsonProperty("ContainerIDFile") - private String containerIDFile; - - // TODO: use Links class here? - @JsonProperty("Links") - private String[] links; - - @JsonProperty("NetworkMode") - private String networkMode; - - @JsonProperty("Devices") - private Device[] devices; - - @JsonProperty("RestartPolicy") - private RestartPolicy restartPolicy; - - @JsonProperty("CapAdd") - private String[] capAdd; - - @JsonProperty("CapDrop") - private String[] capDrop; - - public String[] getBinds() { - return binds; - } - - public LxcConf[] getLxcConf() { - return lxcConf; - } - - public Ports getPortBindings() { - return portBindings; - } - - public boolean isPublishAllPorts() { - return publishAllPorts; - } - - public boolean isPrivileged() { - return privileged; - } - - public String[] getDns() { - return dns; - } - - public String[] getVolumesFrom() { - return volumesFrom; - } - - public String getContainerIDFile() { - return containerIDFile; - } - - public String[] getDnsSearch() { - return dnsSearch; - } - - public String[] getLinks() { - return links; - } - - public String getNetworkMode() { - return networkMode; - } - - public Device[] getDevices() { - return devices; - } - - public RestartPolicy getRestartPolicy() { - return restartPolicy; - } - - public String[] getCapAdd() { - return capAdd; - } - - public String[] getCapDrop() { - return capDrop; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - } - } diff --git a/src/main/java/com/github/dockerjava/api/model/HostConfig.java b/src/main/java/com/github/dockerjava/api/model/HostConfig.java new file mode 100644 index 00000000..6344caab --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/HostConfig.java @@ -0,0 +1,204 @@ +package com.github.dockerjava.api.model; + +import org.apache.commons.lang.builder.ToStringBuilder; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class HostConfig { + + @JsonProperty("Binds") + private String[] binds; + + @JsonProperty("Links") + private Links links; + + @JsonProperty("LxcConf") + private LxcConf[] lxcConf; + + @JsonProperty("PortBindings") + private Ports portBindings; + + @JsonProperty("PublishAllPorts") + private boolean publishAllPorts; + + @JsonProperty("Privileged") + private boolean privileged; + + @JsonProperty("Dns") + private String[] dns; + + @JsonProperty("DnsSearch") + private String[] dnsSearch; + + @JsonProperty("VolumesFrom") + private String[] volumesFrom; + + @JsonProperty("ContainerIDFile") + private String containerIDFile; + + @JsonProperty("CapAdd") + private String[] capAdd; + + @JsonProperty("CapDrop") + private String[] capDrop; + + @JsonProperty("RestartPolicy") + private RestartPolicy restartPolicy; + + @JsonProperty("NetworkMode") + private String networkMode; + + @JsonProperty("Devices") + private Device[] devices; + + public HostConfig() { + } + + public HostConfig(String[] binds, Links links, LxcConf[] lxcConf, Ports portBindings, boolean publishAllPorts, + boolean privileged, String[] dns, String[] dnsSearch, String[] volumesFrom, String containerIDFile, + String[] capAdd, String[] capDrop, RestartPolicy restartPolicy, String networkMode, Device[] devices) { + this.binds = binds; + this.links = links; + this.lxcConf = lxcConf; + this.portBindings = portBindings; + this.publishAllPorts = publishAllPorts; + this.privileged = privileged; + this.dns = dns; + this.dnsSearch = dnsSearch; + this.volumesFrom = volumesFrom; + this.containerIDFile = containerIDFile; + this.capAdd = capAdd; + this.capDrop = capDrop; + this.restartPolicy = restartPolicy; + this.networkMode = networkMode; + this.devices = devices; + } + + public String[] getBinds() { + return binds; + } + + public LxcConf[] getLxcConf() { + return lxcConf; + } + + public Ports getPortBindings() { + return portBindings; + } + + public boolean isPublishAllPorts() { + return publishAllPorts; + } + + public boolean isPrivileged() { + return privileged; + } + + public String[] getDns() { + return dns; + } + + public String[] getVolumesFrom() { + return volumesFrom; + } + + public String getContainerIDFile() { + return containerIDFile; + } + + public String[] getDnsSearch() { + return dnsSearch; + } + + public Links getLinks() { + return links; + } + + public String getNetworkMode() { + return networkMode; + } + + public Device[] getDevices() { + return devices; + } + + public RestartPolicy getRestartPolicy() { + return restartPolicy; + } + + public String[] getCapAdd() { + return capAdd; + } + + public String[] getCapDrop() { + return capDrop; + } + + public void setBinds(String[] binds) { + this.binds = binds; + } + + public void setLinks(Links links) { + this.links = links; + } + + public void setLxcConf(LxcConf[] lxcConf) { + this.lxcConf = lxcConf; + } + + public void setPortBindings(Ports portBindings) { + this.portBindings = portBindings; + } + + public void setPublishAllPorts(boolean publishAllPorts) { + this.publishAllPorts = publishAllPorts; + } + + public void setPrivileged(boolean privileged) { + this.privileged = privileged; + } + + public void setDns(String[] dns) { + this.dns = dns; + } + + public void setDnsSearch(String[] dnsSearch) { + this.dnsSearch = dnsSearch; + } + + public void setVolumesFrom(String[] volumesFrom) { + this.volumesFrom = volumesFrom; + } + + public void setContainerIDFile(String containerIDFile) { + this.containerIDFile = containerIDFile; + } + + public void setCapAdd(String[] capAdd) { + this.capAdd = capAdd; + } + + public void setCapDrop(String[] capDrop) { + this.capDrop = capDrop; + } + + public void setRestartPolicy(RestartPolicy restartPolicy) { + this.restartPolicy = restartPolicy; + } + + public void setNetworkMode(String networkMode) { + this.networkMode = networkMode; + } + + public void setDevices(Device[] devices) { + this.devices = devices; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/src/main/java/com/github/dockerjava/api/model/PortBinding.java b/src/main/java/com/github/dockerjava/api/model/PortBinding.java index df908559..13c91bdb 100644 --- a/src/main/java/com/github/dockerjava/api/model/PortBinding.java +++ b/src/main/java/com/github/dockerjava/api/model/PortBinding.java @@ -4,7 +4,6 @@ import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; -import com.github.dockerjava.api.command.InspectContainerResponse.HostConfig; import com.github.dockerjava.api.command.InspectContainerResponse.NetworkSettings; import com.github.dockerjava.api.model.Ports.Binding; diff --git a/src/main/java/com/github/dockerjava/api/model/Ports.java b/src/main/java/com/github/dockerjava/api/model/Ports.java index d68175a5..e0f3c080 100644 --- a/src/main/java/com/github/dockerjava/api/model/Ports.java +++ b/src/main/java/com/github/dockerjava/api/model/Ports.java @@ -23,7 +23,6 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.node.NullNode; -import com.github.dockerjava.api.command.InspectContainerResponse.HostConfig; import com.github.dockerjava.api.command.InspectContainerResponse.NetworkSettings; /** diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index b3f020f9..e022bdea 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -4,16 +4,15 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; - import com.github.dockerjava.api.ConflictException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.ExposedPorts; +import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Volume; import com.github.dockerjava.api.model.Volumes; - import com.google.common.base.Preconditions; /** @@ -46,6 +45,7 @@ public class CreateContainerCmdImpl extends AbstrDockerCmd Date: Mon, 1 Dec 2014 15:24:28 +0100 Subject: [PATCH 224/452] Fix parsing of Links and Link --- src/main/java/com/github/dockerjava/api/model/Link.java | 6 ++++-- src/main/java/com/github/dockerjava/api/model/Links.java | 8 ++++---- .../java/com/github/dockerjava/api/model/LinkTest.java | 7 +++++++ .../core/command/StartContainerCmdImplTest.java | 2 +- 4 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/model/Link.java b/src/main/java/com/github/dockerjava/api/model/Link.java index 4416dca0..ab8485a3 100644 --- a/src/main/java/com/github/dockerjava/api/model/Link.java +++ b/src/main/java/com/github/dockerjava/api/model/Link.java @@ -53,7 +53,7 @@ public String getAlias() /** * Parses a textual link specification (as used by the Docker CLI) to a {@link Link}. * - * @param serialized the specification, e.g. name:alias + * @param serialized the specification, e.g. name:alias or /name1:/name2/alias * @return a {@link Link} matching the specification * @throws IllegalArgumentException if the specification cannot be parsed */ @@ -63,7 +63,9 @@ public static Link parse(final String serialized) throws IllegalArgumentExceptio final String[] parts = serialized.split(":"); switch (parts.length) { case 2: { - return new Link(parts[0], parts[1]); + String[] nameSplit = parts[0].split("/"); + String[] aliasSplit = parts[1].split("/"); + return new Link(nameSplit[nameSplit.length - 1], aliasSplit[aliasSplit.length - 1]); } default: { throw new IllegalArgumentException(); diff --git a/src/main/java/com/github/dockerjava/api/model/Links.java b/src/main/java/com/github/dockerjava/api/model/Links.java index b0d0cc8d..d901ea8d 100644 --- a/src/main/java/com/github/dockerjava/api/model/Links.java +++ b/src/main/java/com/github/dockerjava/api/model/Links.java @@ -61,11 +61,11 @@ public Links deserialize(final JsonParser jsonParser, final DeserializationConte final List binds = new ArrayList(); final ObjectCodec oc = jsonParser.getCodec(); final JsonNode node = oc.readTree(jsonParser); - for (final Iterator> it = node.fields(); it.hasNext();) { + for (final Iterator it = node.elements(); it.hasNext();) { - final Map.Entry field = it.next(); - if (!field.getValue().equals(NullNode.getInstance())) { - binds.add(Link.parse(field.getKey())); + final JsonNode element = it.next(); + if (!element.equals(NullNode.getInstance())) { + binds.add(Link.parse(element.asText())); } } return new Links(binds.toArray(new Link[0])); diff --git a/src/test/java/com/github/dockerjava/api/model/LinkTest.java b/src/test/java/com/github/dockerjava/api/model/LinkTest.java index c42af9da..2f6df0c5 100644 --- a/src/test/java/com/github/dockerjava/api/model/LinkTest.java +++ b/src/test/java/com/github/dockerjava/api/model/LinkTest.java @@ -12,6 +12,13 @@ public void parse() { assertEquals(link.getName(), "name"); assertEquals(link.getAlias(), "alias"); } + + @Test + public void parseWithContainerNames() { + Link link = Link.parse("/name:/conatiner/alias"); + assertEquals(link.getName(), "name"); + assertEquals(link.getAlias(), "alias"); + } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Error parsing Link 'nonsense'") diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index 469259ee..438597bc 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -228,7 +228,7 @@ public void startContainerWithLinking() throws DockerException { assertThat(inspectContainerResponse2.getId(), not(isEmptyString())); assertThat(inspectContainerResponse2.getHostConfig(), is(notNullValue())); assertThat(inspectContainerResponse2.getHostConfig().getLinks(), is(notNullValue())); - assertThat(inspectContainerResponse2.getHostConfig().getLinks(), equalTo(new String[] {"/container1:/container2/container1Link"})); + assertThat(inspectContainerResponse2.getHostConfig().getLinks().getLinks(), equalTo(new Link[] {new Link("container1","container1Link")})); assertThat(inspectContainerResponse2.getId(), startsWith(container2.getId())); assertThat(inspectContainerResponse2.getName(), equalTo("/container2")); assertThat(inspectContainerResponse2.getImageId(), not(isEmptyString())); From bf0ea1b562cfe75b86de685cea13cb6e098e9489 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Mon, 24 Nov 2014 10:07:13 +0100 Subject: [PATCH 225/452] Represent Linux capabilites as an enum This avoids errors when entering capabilities due to different capabilty names, e.g. "MKNOD" in docker vs. "CAP_MKNOD" in Linux manpages. It also gives a natural home for documenting the meaning of the individual values. --- .../api/command/StartContainerCmd.java | 15 +- .../dockerjava/api/model/Capability.java | 329 ++++++++++++++++++ .../dockerjava/api/model/HostConfig.java | 14 +- .../core/command/StartContainerCmdImpl.java | 13 +- .../dockerjava/api/model/CapabilityTest.java | 29 ++ .../command/StartContainerCmdImplTest.java | 9 +- 6 files changed, 385 insertions(+), 24 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/Capability.java create mode 100644 src/test/java/com/github/dockerjava/api/model/CapabilityTest.java diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index 8535c8ed..59aab1ed 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -3,6 +3,7 @@ import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; import com.github.dockerjava.api.model.Bind; +import com.github.dockerjava.api.model.Capability; import com.github.dockerjava.api.model.Device; import com.github.dockerjava.api.model.Link; import com.github.dockerjava.api.model.LxcConf; @@ -41,9 +42,9 @@ public interface StartContainerCmd extends DockerCmd { public RestartPolicy getRestartPolicy(); - public String[] getCapAdd(); + public Capability[] getCapAdd(); - public String[] getCapDrop(); + public Capability[] getCapDrop(); public StartContainerCmd withBinds(Bind... binds); @@ -115,18 +116,18 @@ public interface StartContainerCmd extends DockerCmd { /** * Add linux kernel - * capability to the container. For example: adding capability "MKNOD" + * capability to the container. For example: adding {@link Capability#MKNOD} * allows the container to create special files using the 'mknod' command. */ - public StartContainerCmd withCapAdd(String... capAdd); + public StartContainerCmd withCapAdd(Capability... capAdd); /** * Drop linux kernel - * capability from the container. For example: dropping capability - * "CHOWN" prevents the container from changing the owner of any files. + * capability from the container. For example: dropping {@link Capability#CHOWN} + * prevents the container from changing the owner of any files. */ - public StartContainerCmd withCapDrop(String... capDrop); + public StartContainerCmd withCapDrop(Capability... capDrop); /** * @throws NotFoundException diff --git a/src/main/java/com/github/dockerjava/api/model/Capability.java b/src/main/java/com/github/dockerjava/api/model/Capability.java new file mode 100644 index 00000000..c86c0796 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/Capability.java @@ -0,0 +1,329 @@ +package com.github.dockerjava.api.model; + +/** + * The Linux capabilities supported by Docker. + * The list of capabilities is defined in Docker's types.go, + * {@link #ALL} was added manually. + * + * @see http://man7.org/linux/man-pages/man7/capabilities.7.html + */ +public enum Capability { + /** + * This meta capability includes all Linux capabilities. + */ + ALL, + /** + *
    + *
  • Enable and disable kernel auditing. + *
  • Change auditing filter rules. + *
  • Retrieve auditing status and filtering rules. + *
+ */ + AUDIT_CONTROL, + /** + * Write records to kernel auditing log. + */ + AUDIT_WRITE, + /** + * Employ features that can block system suspend. + */ + BLOCK_SUSPEND, + /** + * Make arbitrary changes to file UIDs and GIDs (see chown(2)). + */ + CHOWN, + /** + * Bypass file read, write, and execute permission checks. + * (DAC is an abbreviation of "discretionary access control".) + */ + DAC_OVERRIDE, + /** + * Bypass file read permission checks and directory read and + * execute permission checks. + */ + DAC_READ_SEARCH, + /** + *
    + *
  • Bypass permission checks on operations that normally require + * the file system UID of the process to match the UID of the file + * (e.g., chmod(2), utime(2)), excluding those operations covered + * by the {@link #DAC_OVERRIDE} and{@link #DAC_READ_SEARCH}. + *
  • Set extended file attributes (see chattr(1)) on arbitrary files. + *
  • Set Access Control Lists (ACLs) on arbitrary files. + *
  • Ignore directory sticky bit on file deletion. + *
  • Specify O_NOATIME for arbitrary files in open(2)and fcntl(2). + *
+ */ + FOWNER, + /** + *
    + *
  • Don't clear set-user-ID and set-group-ID permission bits when + * a file is modified. + *
  • Set the set-group-ID bit for a file whose GID does not match + * the file system or any of the supplementary GIDs of the calling + * process. + *
+ */ + FSETID, + /** + * Permit memory locking (mlock(2), mlockall(2), mmap(2), shmctl(2)). + */ + IPC_LOCK, + /** + * Bypass permission checks for operations on System V IPC objects. + */ + IPC_OWNER, + /** + * Bypass permission checks for sending signals (see kill(2)). + * This includes use of the ioctl(2) KDSIGACCEPT operation. + */ + KILL, + /** + * Establish leases on arbitrary files (see fcntl(2)). + */ + LEASE, + /** + * Set the FS_APPEND_FL and FS_IMMUTABLE_FL i-node flags (see chattr(1)). + */ + LINUX_IMMUTABLE, + /** + * Override Mandatory Access Control (MAC). + * Implemented for the Smack Linux Security Module (LSM). + */ + MAC_ADMIN, + /** + * Allow MAC configuration or state changes. Implemented for the Smack LSM. + */ + MAC_OVERRIDE, + /** + * Create special files using mknod(2). + */ + MKNOD, + /** + * Perform various network-related operations: + *
    + *
  • Interface configuration. + *
  • Administration of IP firewall, masquerading, and accounting. + *
  • Modify routing tables. + *
  • Bind to any address for transparent proxying. + *
  • Set type-of-service (TOS). + *
  • Clear driver statistics. + *
  • Set promiscuous mode. + *
  • Enabling multicasting. + *
  • Use setsockopt(2) to set the following socket options: SO_DEBUG, + * SO_MARK, SO_PRIORITY (for a priority outside the range 0 to 6), + * SO_RCVBUFFORCE, and SO_SNDBUFFORCE. + *
+ */ + NET_ADMIN, + /** + * Bind a socket to Internet domain privileged ports (port numbers less + * than 1024). + */ + NET_BIND_SERVICE, + /** + * (Unused) Make socket broadcasts, and listen to multicasts. + */ + NET_BROADCAST, + /** + *
    + *
  • Use RAW and PACKET sockets. + *
  • Bind to any address for transparent proxying. + *
+ */ + NET_RAW, + /** + * Set file capabilities. + */ + SETFCAP, + /** + *
    + *
  • Make arbitrary manipulations of process GIDs and supplementary + * GID list. + *
  • Forge GID when passing socket credentials via UNIX domain + * sockets. + *
+ */ + SETGID, + /** + * If file capabilities are not supported: + *
    + *
  • grant or remove any capability in the caller's permitted + * capability set to or from any other process. (This property of + * CAP_SETPCAP is not available when the kernel is configured to + * support file capabilities, since CAP_SETPCAP has entirely different + * semantics for such kernels.) + *
+ *

+ * If file capabilities are supported: + *

    + *
  • Add any capability from the calling thread's bounding set to its + * inheritable set. + *
  • Drop capabilities from the bounding set (via prctl(2) + * PR_CAPBSET_DROP). + *
  • Make changes to the securebits flags. + *
+ */ + SETPCAP, + /** + *
    + *
  • Make arbitrary manipulations of process UIDs (setuid(2), + * setreuid(2), setresuid(2), setfsuid(2)). + *
  • Make forged UID when passing socket credentials via UNIX domain + * sockets. + *
+ */ + SETUID, + /** + *
    + *
  • Perform a range of system administration operations including: + * quotactl(2), mount(2), umount(2), swapon(2), swapoff(2), sethostname(2), + * and setdomainname(2). + *
  • Perform privileged syslog(2) operations (since Linux 2.6.37, + * CAP_SYSLOG should be used to permit such operations). + *
  • Perform VM86_REQUEST_IRQ vm86(2) command. + *
  • Perform IPC_SET and IPC_RMID operations on arbitrary System V IPC objects. + *
  • Perform operations on trusted and security Extended Attributes + * (see attr(5)). + *
  • Use lookup_dcookie(2) + *
  • Use ioprio_set(2) to assign IOPRIO_CLASS_RT and (before Linux 2.6.25) + * IOPRIO_CLASS_IDLE I/O scheduling classes. + *
  • Forge UID when passing socket credentials. + *
  • Exceed /proc/sys/fs/file-max, the system-wide limit on the number of + * open files, in system calls that open files (e.g., accept(2), execve(2), + * open(2), pipe(2)). + *
  • Employ CLONE_* flags that create new namespaces with clone(2) and + * unshare(2). + *
  • Call perf_event_open(2). + *
  • Access privileged perf event information. + *
  • Call setns(2). + *
  • Call fanotify_init(2). + *
  • Perform KEYCTL_CHOWN and KEYCTL_SETPERM keyctl(2) operations. + *
  • Perform madvise(2) MADV_HWPOISON operation. + *
  • Employ the TIOCSTI ioctl(2) to insert characters into the input queue + * of a terminal other than the caller's controlling terminal. + *
  • Employ the obsolete nfsservctl(2) system call. + *
  • Employ the obsolete bdflush(2) system call. + *
  • Perform various privileged block-device ioctl(2) operations. + *
  • Perform various privileged file-system ioctl(2) operations. + *
  • Perform administrative operations on many device drivers. + *
+ */ + SYS_ADMIN, + /** + * Use reboot(2) and kexec_load(2). + */ + SYS_BOOT, + /** + * Use chroot(2). + */ + SYS_CHROOT, + /** + *
    + *
  • Perform privileged syslog(2) operations. See syslog(2) for information + * on which operations require privilege. + *
  • View kernel addresses exposed via /proc and other interfaces when + * /proc/sys/kernel/kptr_restrict has the value 1. (See the discussion of the + * kptr_restrict in proc(5).) + *
+ */ + SYSLOG, + /** + *
    + *
  • Load and unload kernel modules (see init_module(2) and delete_module(2)) + *
  • In kernels before 2.6.25: drop capabilities from the system-wide + * capability bounding set. + *
+ */ + SYS_MODULE, + /** + *
    + *
  • Raise process nice value (nice(2), setpriority(2)) and change the nice + * value for arbitrary processes. + *
  • Set real-time scheduling policies for calling process, and set scheduling + * policies and priorities for arbitrary processes (sched_setscheduler(2), + * sched_setparam(2)). + *
  • Set CPU affinity for arbitrary processes (sched_setaffinity(2)). + *
  • Set I/O scheduling class and priority for arbitrary processes + * (ioprio_set(2)). + *
  • Apply migrate_pages(2) to arbitrary processes and allow processes to be + * migrated to arbitrary nodes. + *
  • Apply move_pages(2) to arbitrary processes. + *
  • Use the MPOL_MF_MOVE_ALL flag with mbind(2) and move_pages(2). + *
+ */ + SYS_NICE, + /** + * Use acct(2). + */ + SYS_PACCT, + /** + *
    + *
  • Trace arbitrary processes using ptrace(2). + *
  • Apply get_robust_list(2) to arbitrary processes. + *
  • Inspect processes using kcmp(2). + *
+ */ + SYS_PTRACE, + /** + *
    + *
  • Perform I/O port operations (iopl(2) and ioperm(2)). + *
  • Access /proc/kcore. + *
  • Employ the FIBMAP ioctl(2) operation. + *
  • Open devices for accessing x86 model-specific registers (MSRs, see + * msr(4)). + *
  • Update /proc/sys/vm/mmap_min_addr. + *
  • Create memory mappings at addresses below the value specified by + * /proc/sys/vm/mmap_min_addr. + *
  • Map files in /proc/pci/bus. + *
  • Open /dev/mem and /dev/kmem. + *
  • Perform various SCSI device commands. + *
  • Perform certain operations on hpsa(4) and cciss(4) devices. + *
  • Perform a range of device-specific operations on other devices. + *
+ */ + SYS_RAWIO, + /** + *
    + *
  • Use reserved space on ext2 file systems. + *
  • Make ioctl(2) calls controlling ext3 journaling. + *
  • Override disk quota limits. + *
  • Increase resource limits (see setrlimit(2)). + *
  • Override RLIMIT_NPROC resource limit. + *
  • Override maximum number of consoles on console allocation. + *
  • Override maximum number of keymaps. + *
  • Allow more than 64hz interrupts from the real-time clock. + *
  • Raise msg_qbytes limit for a System V message queue above the limit + * in /proc/sys/kernel/msgmnb (see msgop(2) and msgctl(2)). + *
  • Override the /proc/sys/fs/pipe-size-max limit when setting the capacity + * of a pipe using the F_SETPIPE_SZ fcntl(2) command. + *
  • Use F_SETPIPE_SZ to increase the capacity of a pipe above the limit + * specified by /proc/sys/fs/pipe-max-size. + *
  • Override /proc/sys/fs/mqueue/queues_max limit when creating POSIX + * message queues (see mq_overview(7)). + *
  • Employ prctl(2) PR_SET_MM operation. + *
  • Set /proc/PID/oom_score_adj to a value lower than the value last set + * by a process with CAP_SYS_RESOURCE. + *
+ */ + SYS_RESOURCE, + /** + *
    + *
  • Set system clock (settimeofday(2), stime(2), adjtimex(2)). + *
  • Set real-time (hardware) clock. + *
+ */ + SYS_TIME, + /** + *
    + *
  • Use vhangup(2). + *
  • Employ various privileged ioctl(2) operations on virtual terminals. + *
+ */ + SYS_TTY_CONFIG, + /** + * Trigger something that will wake up the system (set CLOCK_REALTIME_ALARM and + * CLOCK_BOOTTIME_ALARM timers). + */ + WAKE_ALARM +} diff --git a/src/main/java/com/github/dockerjava/api/model/HostConfig.java b/src/main/java/com/github/dockerjava/api/model/HostConfig.java index 6344caab..3d186501 100644 --- a/src/main/java/com/github/dockerjava/api/model/HostConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/HostConfig.java @@ -39,10 +39,10 @@ public class HostConfig { private String containerIDFile; @JsonProperty("CapAdd") - private String[] capAdd; + private Capability[] capAdd; @JsonProperty("CapDrop") - private String[] capDrop; + private Capability[] capDrop; @JsonProperty("RestartPolicy") private RestartPolicy restartPolicy; @@ -58,7 +58,7 @@ public HostConfig() { public HostConfig(String[] binds, Links links, LxcConf[] lxcConf, Ports portBindings, boolean publishAllPorts, boolean privileged, String[] dns, String[] dnsSearch, String[] volumesFrom, String containerIDFile, - String[] capAdd, String[] capDrop, RestartPolicy restartPolicy, String networkMode, Device[] devices) { + Capability[] capAdd, Capability[] capDrop, RestartPolicy restartPolicy, String networkMode, Device[] devices) { this.binds = binds; this.links = links; this.lxcConf = lxcConf; @@ -128,11 +128,11 @@ public RestartPolicy getRestartPolicy() { return restartPolicy; } - public String[] getCapAdd() { + public Capability[] getCapAdd() { return capAdd; } - public String[] getCapDrop() { + public Capability[] getCapDrop() { return capDrop; } @@ -176,11 +176,11 @@ public void setContainerIDFile(String containerIDFile) { this.containerIDFile = containerIDFile; } - public void setCapAdd(String[] capAdd) { + public void setCapAdd(Capability[] capAdd) { this.capAdd = capAdd; } - public void setCapDrop(String[] capDrop) { + public void setCapDrop(Capability[] capDrop) { this.capDrop = capDrop; } diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index 74fbd679..60d728f0 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -9,6 +9,7 @@ import com.github.dockerjava.api.command.StartContainerCmd; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Binds; +import com.github.dockerjava.api.model.Capability; import com.github.dockerjava.api.model.Device; import com.github.dockerjava.api.model.Link; import com.github.dockerjava.api.model.Links; @@ -62,10 +63,10 @@ public class StartContainerCmdImpl extends AbstrDockerCmd Date: Wed, 3 Dec 2014 11:08:46 +0100 Subject: [PATCH 226/452] Allow to manage Linux capabilities in CreateContainerCmd This was previously only availabale in StartContainerCmd. The introduction of HostConfig as a parameter to /containers/create in Docker API v1.15 allows to specify capabilites here as well. --- .../api/command/CreateContainerCmd.java | 21 +++++++++++++++- .../core/command/CreateContainerCmdImpl.java | 24 ++++++++++++++++++ .../command/CreateContainerCmdImplTest.java | 25 +++++++++++++++++-- 3 files changed, 67 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java index dde2079a..1cf3098e 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java @@ -2,9 +2,9 @@ import com.github.dockerjava.api.ConflictException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.model.Capability; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.HostConfig; -import com.github.dockerjava.api.model.Links; import com.github.dockerjava.api.model.Volume; public interface CreateContainerCmd extends DockerCmd{ @@ -101,6 +101,25 @@ public interface CreateContainerCmd extends DockerCmd{ public CreateContainerCmd withHostConfig(HostConfig hostConfig); + public Capability[] getCapAdd(); + + /** + * Add linux kernel + * capability to the container. For example: adding {@link Capability#MKNOD} + * allows the container to create special files using the 'mknod' command. + */ + public CreateContainerCmd withCapAdd(Capability... capAdd); + + public Capability[] getCapDrop(); + + /** + * Drop linux kernel + * capability from the container. For example: dropping {@link Capability#CHOWN} + * prevents the container from changing the owner of any files. + */ + public CreateContainerCmd withCapDrop(Capability... capDrop); /** * @throws NotFoundException No such container diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index e022bdea..0fab7e69 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -8,6 +8,7 @@ import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.model.Capability; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.ExposedPorts; import com.github.dockerjava.api.model.HostConfig; @@ -312,6 +313,28 @@ public CreateContainerCmd withHostConfig(HostConfig hostConfig) { return this; } + @Override + public Capability[] getCapAdd() { + return hostConfig.getCapAdd(); + } + + @Override + public CreateContainerCmd withCapAdd(Capability... capAdd) { + hostConfig.setCapAdd(capAdd); + return this; + } + + @Override + public Capability[] getCapDrop() { + return hostConfig.getCapDrop(); + } + + @Override + public CreateContainerCmd withCapDrop(Capability... capDrop) { + hostConfig.setCapDrop(capDrop); + return this; + } + @Override public String toString() { return new ToStringBuilder(this).append("create container ") @@ -328,4 +351,5 @@ public String toString() { public CreateContainerResponse exec() throws NotFoundException, ConflictException { return super.exec(); } + } diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index ebb7908f..5bb25b2f 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -1,5 +1,6 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.api.model.Capability.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -8,8 +9,6 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.startsWith; import java.lang.reflect.Method; import java.security.SecureRandom; @@ -198,4 +197,26 @@ public void createContainerWithLink() throws DockerException { assertThat(inspectContainerResponse2.getHostConfig().getLinks().getLinks(), equalTo(new Link[] {new Link("container1","container1Link")})); } + @Test + public void createContainerWithCapAddAndCapDrop() throws DockerException { + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox") + .withCapAdd(NET_ADMIN) + .withCapDrop(MKNOD).exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + assertThat(Arrays.asList(inspectContainerResponse.getHostConfig() + .getCapAdd()), contains(NET_ADMIN)); + + assertThat(Arrays.asList(inspectContainerResponse.getHostConfig() + .getCapDrop()), contains(MKNOD)); + } + } From b54f7a2e4554d7a83587a75d6bce27b7cda3e48e Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Thu, 4 Dec 2014 19:26:49 +0100 Subject: [PATCH 227/452] Fix CreateContainerCmd.withDns() I'm pretty sure this never worked. At least with Docker 1.2.0 it didn't. --- .../core/command/CreateContainerCmdImpl.java | 9 ++++---- .../command/CreateContainerCmdImplTest.java | 21 +++++++++++++++++++ .../command/StartContainerCmdImplTest.java | 7 ++----- 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index 0fab7e69..8a6509bc 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -39,7 +39,6 @@ public class CreateContainerCmdImpl extends AbstrDockerCmd Date: Thu, 4 Dec 2014 17:21:14 -0800 Subject: [PATCH 228/452] Support tag in push image command --- .../dockerjava/api/command/PushImageCmd.java | 9 +++++- .../core/command/PushImageCmdImpl.java | 28 +++++++++++++++---- .../dockerjava/jaxrs/PushImageCmdExec.java | 3 +- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java b/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java index cd3e6681..c746fd7c 100644 --- a/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java @@ -14,12 +14,19 @@ public interface PushImageCmd extends DockerCmd{ public String getName(); + public String getTag(); + /** * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. */ public PushImageCmd withName(String name); - public AuthConfig getAuthConfig(); + /** + * @param tag The image's tag. Not null. + */ + public PushImageCmd withTag(String tag); + + public AuthConfig getAuthConfig(); public PushImageCmd withAuthConfig(AuthConfig authConfig); diff --git a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java index 65ea843f..56f58715 100644 --- a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java @@ -14,18 +14,24 @@ */ public class PushImageCmdImpl extends AbstrAuthCfgDockerCmd implements PushImageCmd { - private String name; + private String name; + private String tag; - public PushImageCmdImpl(PushImageCmd.Exec exec, String name) { - super(exec); - withName(name); - } + public PushImageCmdImpl(PushImageCmd.Exec exec, String name) { + super(exec); + withName(name); + } @Override public String getName() { return name; } + @Override + public String getTag() { + return tag; + } + /** * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. */ @@ -36,6 +42,16 @@ public PushImageCmd withName(String name) { return this; } + /** + * @param tag The image's tag. Can be null or empty. + */ + @Override + public PushImageCmd withTag(String tag) { + Preconditions.checkNotNull(tag, "tag was not specified"); + this.tag = tag; + return this; + } + @Override public String toString() { return new StringBuilder("push ") @@ -46,7 +62,7 @@ public String toString() { /** * @throws NotFoundException No such image */ - @Override + @Override public InputStream exec() throws NotFoundException { return super.exec(); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java index 8d5aabef..9454a0e7 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java @@ -24,7 +24,8 @@ public PushImageCmdExec(WebTarget baseResource) { @Override protected InputStream execute(PushImageCmd command) { - WebTarget webResource = getBaseResource().path("/images/" + name(command) + "/push"); + WebTarget webResource = getBaseResource().path("/images/" + name(command) + "/push") + .queryParam("tag", command.getTag()); final String registryAuth = registryAuth(command.getAuthConfig()); LOGGER.trace("POST: {}", webResource); From d7af26225bf91ee5e2ae3ed59050663d50eeebfa Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 7 Dec 2014 21:41:10 +0100 Subject: [PATCH 229/452] Fix pull image test --- .../github/dockerjava/core/command/PullImageCmdImplTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java index 461bf694..394e86bd 100644 --- a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java @@ -76,7 +76,7 @@ public void testPullImage() throws DockerException, IOException { LOG.info("Removing image: {}", testImage); try { - dockerClient.removeImageCmd(testImage).exec(); + dockerClient.removeImageCmd(testImage).withForce().exec(); } catch (NotFoundException e) { // just ignore if not exist } From 80899259292a9c1260ea7acc235206af4836ce94 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 7 Dec 2014 21:43:17 +0100 Subject: [PATCH 230/452] [maven-release-plugin] prepare release docker-java-0.10.4 --- pom.xml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 87afc54e..2e8f8313 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - + 4.0.0 @@ -11,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.4-SNAPSHOT + 0.10.4 docker-java https://github.com/docker-java/docker-java @@ -29,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-0.10.4 From 2133b66caecfb1a95826210dc26f9a2d41cb5db7 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 7 Dec 2014 21:43:21 +0100 Subject: [PATCH 231/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2e8f8313..0b85dc42 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.4 + 0.10.5-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.10.4 + HEAD From d6fcccfd4f847a31b7db6f6c9570d2574640c7f2 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Mon, 8 Dec 2014 20:37:26 +0100 Subject: [PATCH 232/452] Update CHANGELOG.md --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d233238f..5d189f89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ Change Log === + +docker-java-0.10.4 +--- + + * [#108](https://github.com/docker-java/docker-java/pull/108) Support tag in push image command + * [#106](https://github.com/docker-java/docker-java/pull/106) Allow to manage Linux capabilities in CreateContainerCmd + * [#105](https://github.com/docker-java/docker-java/pull/105) Allow to pass HostConfig when creating a container + * [#103](https://github.com/docker-java/docker-java/pull/103) Make GoLangMatchFileFilter work on Windows + * [#102](https://github.com/docker-java/docker-java/pull/102) Downgraded jackson-jaxrs dependency version + * [#101](https://github.com/docker-java/docker-java/pull/101) list filtered images as described in the remote api docs + * [#100](https://github.com/docker-java/docker-java/pull/100) Add support for .dockercfg files to handle auth for push command * [#95](https://github.com/docker-java/docker-java/pull/95) Add support for .dockerignore files * [#92](https://github.com/docker-java/docker-java/pull/92) Add travis-ci support * [#90](https://github.com/docker-java/docker-java/pull/90) Update DockerClientBuilder.java From f5d2b9e927b34feba634de1ba8a37f2cbed57129 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Tue, 9 Dec 2014 17:32:27 +0100 Subject: [PATCH 233/452] Tests for starting a Container with existing configuration This illustrates an issue with current docker-java: you cannot send a StartContainerCmd without payload. --- .../command/StartContainerCmdImplTest.java | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index fedbc5fa..98704fd3 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -2,6 +2,7 @@ import static com.github.dockerjava.api.model.AccessMode.ro; import static com.github.dockerjava.api.model.Capability.*; +import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; @@ -386,4 +387,55 @@ public void startContainerWithRestartPolicy() throws DockerException { is(equalTo(restartPolicy))); } + @Test + public void existingHostConfigIsPreservedByBlankStartCmd() throws DockerException { + + String dnsServer = "8.8.8.8"; + + // prepare a container with custom DNS + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox") + .withDns(dnsServer) + .withCmd("true").exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + // start container _without_any_customization_ (important!) + dockerClient.startContainerCmd(container.getId()).exec(); + + InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container + .getId()).exec(); + + // The DNS setting survived. + assertThat(inspectContainerResponse.getHostConfig().getDns(), is(notNullValue())); + assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getDns()), + contains(dnsServer)); + } + + @Test + public void existingHostConfigIsResetByConfiguredStartCmd() throws DockerException { + + String dnsServer = "8.8.8.8"; + + // prepare a container with custom DNS + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox") + .withDns(dnsServer) + .withCmd("true").exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + // modify another setting in start command. Leave DNS unchanged. + dockerClient.startContainerCmd(container.getId()).withPublishAllPorts(true).exec(); + + InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container + .getId()).exec(); + + // although start did not modify DNS Settings, they were reset to their default. + assertThat(inspectContainerResponse.getHostConfig().getDns(), is(nullValue(String[].class))); + } } From 72d90218926c76c68817ef432ac1bc90cb23119a Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Tue, 9 Dec 2014 18:37:58 +0100 Subject: [PATCH 234/452] Do not serialize unconfigured values in StartContainerCmd Any payload sent with the StartContainerCmd will cause the target container to lose its customization. So in order to just start a preconfigured container you must be able to send an empty "{}" message to the /containers/{id}/start endpoint. This is accomplished by all configuration defaulting to null in combination with @JsonInclude(NON_EMPTY). --- .../api/command/StartContainerCmd.java | 8 +++--- .../core/command/StartContainerCmdImpl.java | 27 +++++++++++-------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index 59aab1ed..ef96267f 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -24,9 +24,9 @@ public interface StartContainerCmd extends DockerCmd { public Ports getPortBindings(); - public boolean isPublishAllPorts(); + public Boolean isPublishAllPorts(); - public boolean isPrivileged(); + public Boolean isPrivileged(); public String[] getDns(); @@ -70,9 +70,9 @@ public interface StartContainerCmd extends DockerCmd { */ public StartContainerCmd withPortBindings(PortBinding... portBindings); - public StartContainerCmd withPrivileged(boolean privileged); + public StartContainerCmd withPrivileged(Boolean privileged); - public StartContainerCmd withPublishAllPorts(boolean publishAllPorts); + public StartContainerCmd withPublishAllPorts(Boolean publishAllPorts); /** * Set custom DNS servers diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index 60d728f0..63ff4ff0 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -1,8 +1,11 @@ package com.github.dockerjava.core.command; +import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY; + import org.apache.commons.lang.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; @@ -22,15 +25,17 @@ /** * Start a container */ +@JsonInclude(NON_EMPTY) public class StartContainerCmdImpl extends AbstrDockerCmd implements StartContainerCmd { + @JsonIgnore private String containerId; @JsonProperty("Binds") - private Binds binds = new Binds(); + private Binds binds; @JsonProperty("Links") - private Links links = new Links(); + private Links links; @JsonProperty("LxcConf") private LxcConf[] lxcConf; @@ -39,10 +44,10 @@ public class StartContainerCmdImpl extends AbstrDockerCmd Date: Wed, 10 Dec 2014 20:18:45 +0100 Subject: [PATCH 235/452] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d07fed2f..cd881e97 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Run build without integration tests: com.github.docker-java docker-java - 0.10.3 + 0.10.4 ### Latest SNAPSHOT version @@ -69,7 +69,7 @@ You can find the latest SNAPSHOT version including javadoc and source files on [ com.github.docker-java docker-java - 0.10.4-SNAPSHOT + 0.10.5-SNAPSHOT ## Documentation From 3e36ce82d4d402ed734b3941394cdb0f2a734a8a Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 10 Dec 2014 21:19:27 +0100 Subject: [PATCH 236/452] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cd881e97..7380f1db 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Java API client for [Docker](http://docs.docker.io/ "Docker") -Supports a subset of the Docker Client API v1.15, Docker Server version 1.3.0 +Supports a subset of the Docker Client API v1.15, Docker Server version 1.3.2 The current implementation is based on Jersey 2.x and therefore classpath incompatible with older Jersey 1.x dependent libraries! From a89158d969d86fce486f101535ef98676977221f Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Thu, 11 Dec 2014 19:15:39 +0100 Subject: [PATCH 237/452] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d189f89..2f61e1de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ Change Log === +docker-java-0.10.5-SNAPSHOT +--- + + * [#111](https://github.com/docker-java/docker-java/pull/111) Allow to send empty messages in StartContainerCmd + docker-java-0.10.4 --- From 4c960a9a52af5f2b0351986a3c29eb9b7f8a142c Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Thu, 11 Dec 2014 19:19:47 +0100 Subject: [PATCH 238/452] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f61e1de..3f272267 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ docker-java-0.10.5-SNAPSHOT docker-java-0.10.4 --- - * [#108](https://github.com/docker-java/docker-java/pull/108) Support tag in push image command + * [#108](https://github.com/docker-java/docker-java/pull/109) Support tag in push image command * [#106](https://github.com/docker-java/docker-java/pull/106) Allow to manage Linux capabilities in CreateContainerCmd * [#105](https://github.com/docker-java/docker-java/pull/105) Allow to pass HostConfig when creating a container * [#103](https://github.com/docker-java/docker-java/pull/103) Make GoLangMatchFileFilter work on Windows From 5a7014fda2672274764d9e4511bb73021783a4ce Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Thu, 11 Dec 2014 19:20:01 +0100 Subject: [PATCH 239/452] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f272267..9b99ef86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ docker-java-0.10.5-SNAPSHOT docker-java-0.10.4 --- - * [#108](https://github.com/docker-java/docker-java/pull/109) Support tag in push image command + * [#109](https://github.com/docker-java/docker-java/pull/109) Support tag in push image command * [#106](https://github.com/docker-java/docker-java/pull/106) Allow to manage Linux capabilities in CreateContainerCmd * [#105](https://github.com/docker-java/docker-java/pull/105) Allow to pass HostConfig when creating a container * [#103](https://github.com/docker-java/docker-java/pull/103) Make GoLangMatchFileFilter work on Windows From 341558275b3952baaa5fc777032f9ddb86df159b Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Fri, 12 Dec 2014 13:17:57 +0100 Subject: [PATCH 240/452] Test for serialization of an unconfigured StartContainerCmd, documentation --- .../com/github/dockerjava/api/DockerClient.java | 14 ++++++++++++++ .../core/command/StartContainerCmdImplTest.java | 14 ++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index 52323942..4052e87b 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -79,6 +79,20 @@ public CreateImageCmd createImageCmd(String repository, public CreateContainerCmd createContainerCmd(String image); + /** + * Creates a new {@link StartContainerCmd} for the container with the + * given ID. + * The command can then be further customized by using builder + * methods on it like {@link StartContainerCmd#withDns(String...)}. + *

+ * If you customize the command, any existing configuration of the + * target container will get reset to its default before applying the + * new configuration. To preserve the existing configuration, use an + * unconfigured {@link StartContainerCmd}. + *

+ * This command corresponds to the /containers/{id}/start + * endpoint of the Docker Remote API. + */ public StartContainerCmd startContainerCmd(String containerId); public InspectContainerCmd inspectContainerCmd(String containerId); diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index 98704fd3..486f03b3 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -15,10 +15,12 @@ import java.lang.reflect.Method; import java.util.*; +import com.fasterxml.jackson.databind.ObjectMapper; import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.command.StartContainerCmd; import com.github.dockerjava.api.model.*; import org.testng.ITestResult; @@ -416,6 +418,11 @@ public void existingHostConfigIsPreservedByBlankStartCmd() throws DockerExceptio @Test public void existingHostConfigIsResetByConfiguredStartCmd() throws DockerException { + // As of version 1.3.2, Docker assumes that you either configure a container + // when creating it or when starting it, but not mixing both. + // See https://github.com/docker-java/docker-java/pull/111 + // If this test starts to fail, this behavior changed and a review of implementation + // and documentation might be needed. String dnsServer = "8.8.8.8"; @@ -438,4 +445,11 @@ public void existingHostConfigIsResetByConfiguredStartCmd() throws DockerExcepti // although start did not modify DNS Settings, they were reset to their default. assertThat(inspectContainerResponse.getHostConfig().getDns(), is(nullValue(String[].class))); } + + @Test + public void anUnconfiguredCommandSerializesToEmptyJson() throws Exception { + ObjectMapper objectMapper = new ObjectMapper(); + StartContainerCmd command = dockerClient.startContainerCmd(""); + assertThat(objectMapper.writeValueAsString(command), is("{}")); + } } From f592918fd86192a13b0efef9fee8914545bce826 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Fri, 12 Dec 2014 13:47:44 +0100 Subject: [PATCH 241/452] Test for StartContainerCmd.withVolumesFrom() --- .../dockerjava/api/model/VolumeBind.java | 5 +++ .../client/AbstractDockerClientTest.java | 26 +++++++++++ .../command/StartContainerCmdImplTest.java | 43 ++++++++++++++++--- 3 files changed, 68 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/model/VolumeBind.java b/src/main/java/com/github/dockerjava/api/model/VolumeBind.java index d662f2b8..41028b6d 100644 --- a/src/main/java/com/github/dockerjava/api/model/VolumeBind.java +++ b/src/main/java/com/github/dockerjava/api/model/VolumeBind.java @@ -16,4 +16,9 @@ public String getContainerPath() { public String getHostPath() { return hostPath; } + + @Override + public String toString() { + return hostPath + ":" + containerPath; + } } diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 4418a8d5..3ed64d9a 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -1,10 +1,18 @@ package com.github.dockerjava.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; + import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.model.Volume; +import com.github.dockerjava.api.model.VolumeBind; import com.github.dockerjava.core.DockerClientBuilder; import com.github.dockerjava.core.DockerClientConfig; import com.github.dockerjava.core.TestDockerCmdExecFactory; +import com.google.common.base.Joiner; + import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.slf4j.Logger; @@ -18,6 +26,8 @@ import java.lang.reflect.Method; import java.net.DatagramSocket; import java.net.ServerSocket; +import java.util.ArrayList; +import java.util.List; public abstract class AbstractDockerClientTest extends Assert { @@ -158,4 +168,20 @@ public static boolean available(int port) { return false; } + /** + * Asserts that {@link InspectContainerResponse#getVolumes()} (.Volumes) + * has {@link VolumeBind}s for the given {@link Volume}s + */ + public static void assertContainerHasVolumes(InspectContainerResponse inspectContainerResponse, + Volume ... expectedVolumes) { + VolumeBind[] volumeBinds = inspectContainerResponse.getVolumes(); + LOG.info("Inspect .Volumes = [{}]", Joiner.on(", ").join(volumeBinds)); + + List volumes = new ArrayList(); + for (VolumeBind bind : volumeBinds) { + volumes.add(new Volume(bind.getContainerPath())); + } + assertThat(volumes, contains(expectedVolumes)); + } + } diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index 486f03b3..de744b59 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -84,18 +84,49 @@ public void startContainerWithVolumes() throws DockerException { inspectContainerResponse = dockerClient.inspectContainerCmd(container .getId()).exec(); - VolumeBind[] volumeBinds = inspectContainerResponse.getVolumes(); - List volumes = new ArrayList(); - for(VolumeBind bind :volumeBinds){ - volumes.add(bind.getContainerPath()); - } - assertThat(volumes, contains(volume1.getPath(), volume2.getPath())); + assertContainerHasVolumes(inspectContainerResponse, volume1, volume2); assertThat(Arrays.asList(inspectContainerResponse.getVolumesRW()), contains(volume1, volume2)); } + @Test + public void startContainerWithVolumesFrom() throws DockerException { + + Volume volume1 = new Volume("/opt/webapp1"); + Volume volume2 = new Volume("/opt/webapp2"); + + String container1Name = UUID.randomUUID().toString(); + + CreateContainerResponse container1 = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999") + .withName(container1Name).exec(); + LOG.info("Created container1 {}", container1.toString()); + + dockerClient.startContainerCmd(container1.getId()).withBinds( + new Bind("/src/webapp1", volume1), new Bind("/src/webapp2", volume2)).exec(); + LOG.info("Started container1 {}", container1.toString()); + + InspectContainerResponse inspectContainerResponse1 = dockerClient.inspectContainerCmd( + container1.getId()).exec(); + + assertContainerHasVolumes(inspectContainerResponse1, volume1, volume2); + + + CreateContainerResponse container2 = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); + LOG.info("Created container2 {}", container2.toString()); + + dockerClient.startContainerCmd(container2.getId()).withVolumesFrom(container1Name).exec(); + LOG.info("Started container2 {}", container2.toString()); + + InspectContainerResponse inspectContainerResponse2 = dockerClient + .inspectContainerCmd(container2.getId()).exec(); + + assertContainerHasVolumes(inspectContainerResponse2, volume1, volume2); + } + @Test public void startContainerWithDns() throws DockerException { From 91a36fedecf13e20d46bdfdd747a10322d8f4005 Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Wed, 17 Dec 2014 17:36:27 +0100 Subject: [PATCH 242/452] Fix CreateContainerCmdImpl.withVolumesFrom() Another method that did not work until Docker Remote API 1.15, see CreateContainerCmd.withDns(). To fix it, the parameter had to be moved to nested HostConfig. --- .../core/command/CreateContainerCmdImpl.java | 5 +- .../command/CreateContainerCmdImplTest.java | 52 +++++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index 8a6509bc..8a4607c2 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -41,7 +41,6 @@ public class CreateContainerCmdImpl extends AbstrDockerCmd Date: Wed, 17 Dec 2014 18:23:59 +0100 Subject: [PATCH 243/452] Change serialization of RestartPolicy.noRestart() The Docker CLI uses "" as the name for the --restart no policy. --- .../dockerjava/api/model/RestartPolicy.java | 2 +- .../model/RestartPolicy_SerializingTest.java | 41 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/github/dockerjava/api/model/RestartPolicy_SerializingTest.java diff --git a/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java b/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java index 936a5b81..0ce3b0ed 100644 --- a/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java +++ b/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java @@ -23,7 +23,7 @@ public class RestartPolicy { private int maximumRetryCount = 0; @JsonProperty("Name") - private String name = "no"; + private String name = ""; public RestartPolicy() { } diff --git a/src/test/java/com/github/dockerjava/api/model/RestartPolicy_SerializingTest.java b/src/test/java/com/github/dockerjava/api/model/RestartPolicy_SerializingTest.java new file mode 100644 index 00000000..7b13a395 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/RestartPolicy_SerializingTest.java @@ -0,0 +1,41 @@ +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Compares serialization results of various {@link RestartPolicy}s with + * what Docker (as of 1.3.3) actually sends when executing + * docker run --restart xxx. + */ +public class RestartPolicy_SerializingTest { + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Test // --restart no + public void noRestart() throws Exception { + String json = objectMapper.writeValueAsString(RestartPolicy.noRestart()); + assertEquals(json, "{\"MaximumRetryCount\":0,\"Name\":\"\"}"); + } + + @Test // --restart always + public void alwaysRestart() throws Exception { + String json = objectMapper.writeValueAsString(RestartPolicy.alwaysRestart()); + assertEquals(json, "{\"MaximumRetryCount\":0,\"Name\":\"always\"}"); + } + + @Test // --restart on-failure + public void onFailureRestart() throws Exception { + String json = objectMapper.writeValueAsString(RestartPolicy.onFailureRestart(0)); + assertEquals(json, "{\"MaximumRetryCount\":0,\"Name\":\"on-failure\"}"); + } + + @Test // --restart on-failure:2 + public void onFailureRestartWithCount() throws Exception { + String json = objectMapper.writeValueAsString(RestartPolicy.onFailureRestart(2)); + assertEquals(json, "{\"MaximumRetryCount\":2,\"Name\":\"on-failure\"}"); + } + +} From fc6429be2dd8b0248819bf3fa741dc2487b7bd5a Mon Sep 17 00:00:00 2001 From: Harald Albers Date: Wed, 17 Dec 2014 18:52:59 +0100 Subject: [PATCH 244/452] Parser and toString for RestartPolicy --- .../dockerjava/api/model/RestartPolicy.java | 74 +++++++++++++++++-- .../api/model/RestartPolicy_ParsingTest.java | 40 ++++++++++ .../api/model/RestartPolicy_toStringTest.java | 25 +++++++ 3 files changed, 132 insertions(+), 7 deletions(-) create mode 100644 src/test/java/com/github/dockerjava/api/model/RestartPolicy_ParsingTest.java create mode 100644 src/test/java/com/github/dockerjava/api/model/RestartPolicy_toStringTest.java diff --git a/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java b/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java index 0ce3b0ed..5cdcb70b 100644 --- a/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java +++ b/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java @@ -9,10 +9,17 @@ /** * Container restart policy * - * no – Do not restart the container if it dies. (default) - * on-failure – Restart the container if it exits with a non-zero exit code. - * Can also accept an optional maximum restart count (e.g. on-failure:5). - * always – Always restart the container no matter what exit code is returned. + *

+ *
no
+ *
Do not restart the container if it dies. (default)
+ * + *
on-failure
+ *
Restart the container if it exits with a non-zero exit code. + * Can also accept an optional maximum restart count (e.g. on-failure:5).
+ * + *
always
+ *
Always restart the container no matter what exit code is returned.
+ *
* * @author marcus * @@ -33,15 +40,27 @@ private RestartPolicy(int maximumRetryCount, String name) { this.maximumRetryCount = maximumRetryCount; this.name = name; } - + + /** + * Do not restart the container if it dies. (default) + */ public static RestartPolicy noRestart() { return new RestartPolicy(); } - + + /** + * Always restart the container no matter what exit code is returned. + */ public static RestartPolicy alwaysRestart() { return new RestartPolicy(0, "always"); } - + + /** + * Restart the container if it exits with a non-zero exit code. + * + * @param maximumRetryCount the maximum number of restarts. + * Set to 0 for unlimited retries. + */ public static RestartPolicy onFailureRestart(int maximumRetryCount) { return new RestartPolicy(maximumRetryCount, "on-failure"); } @@ -54,6 +73,47 @@ public String getName() { return name; } + /** + * Parses a textual restart polixy specification (as used by the Docker CLI) + * to a {@link RestartPolicy}. + * + * @param serialized the specification, e.g. on-failure:2 + * @return a {@link RestartPolicy} matching the specification + * @throws IllegalArgumentException if the specification cannot be parsed + */ + public static RestartPolicy parse(String serialized) throws IllegalArgumentException { + try { + String[] parts = serialized.split(":"); + String name = parts[0]; + if ("no".equals(name)) + return noRestart(); + if ("always".equals(name)) + return alwaysRestart(); + if ("on-failure".equals(name)) { + int count = 0; + if (parts.length == 2) { + count = Integer.parseInt(parts[1]); + } + return onFailureRestart(count); + } + throw new IllegalArgumentException(); + } catch (Exception e) { + throw new IllegalArgumentException("Error parsing RestartPolicy '" + serialized + "'"); + } + } + + /** + * Returns a string representation of this {@link RestartPolicy}. + * The format is name[:count], like the argument in {@link #parse(String)}. + * + * @return a string representation of this {@link RestartPolicy} + */ + @Override + public String toString() { + String result = name.isEmpty() ? "no" : name; + return maximumRetryCount > 0 ? result + ":" + maximumRetryCount : result; + } + @Override public boolean equals(Object obj) { if (obj instanceof RestartPolicy) { diff --git a/src/test/java/com/github/dockerjava/api/model/RestartPolicy_ParsingTest.java b/src/test/java/com/github/dockerjava/api/model/RestartPolicy_ParsingTest.java new file mode 100644 index 00000000..04823db2 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/RestartPolicy_ParsingTest.java @@ -0,0 +1,40 @@ +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +public class RestartPolicy_ParsingTest { + + @Test + public void noRestart() throws Exception { + assertEquals(RestartPolicy.parse("no"), RestartPolicy.noRestart()); + } + + @Test + public void alwaysRestart() throws Exception { + assertEquals(RestartPolicy.parse("always"), RestartPolicy.alwaysRestart()); + } + + @Test + public void onFailureRestart() throws Exception { + assertEquals(RestartPolicy.parse("on-failure"), RestartPolicy.onFailureRestart(0)); + } + + @Test + public void onFailureRestartWithCount() throws Exception { + assertEquals(RestartPolicy.parse("on-failure:2"), RestartPolicy.onFailureRestart(2)); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing RestartPolicy 'nonsense'") + public void illegalSyntax() throws Exception { + RestartPolicy.parse("nonsense"); + } + + @Test(expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = "Error parsing RestartPolicy 'on-failure:X'") + public void illegalRetryCount() throws Exception { + RestartPolicy.parse("on-failure:X"); + } +} diff --git a/src/test/java/com/github/dockerjava/api/model/RestartPolicy_toStringTest.java b/src/test/java/com/github/dockerjava/api/model/RestartPolicy_toStringTest.java new file mode 100644 index 00000000..a52441d6 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/RestartPolicy_toStringTest.java @@ -0,0 +1,25 @@ +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class RestartPolicy_toStringTest { + + @DataProvider(name = "input") + public Object[][] restartPolicies() { + return new Object[][] { + { "no" }, + { "always" }, + { "on-failure" }, + { "on-failure:2" } + }; + } + + @Test(dataProvider = "input") + public void serializationWithoutCount(String policy) throws Exception { + assertEquals(RestartPolicy.parse(policy).toString(), policy); + } + +} From 0502d10c0b5545bb37cb4aba1a164be5fe0abe71 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 17 Dec 2014 20:57:32 +0100 Subject: [PATCH 245/452] Update CHANGELOG.md --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b99ef86..2370e11e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,9 @@ Change Log docker-java-0.10.5-SNAPSHOT --- - + + * [#115](https://github.com/docker-java/docker-java/pull/115) Polish RestartPolicy + * [#114](https://github.com/docker-java/docker-java/pull/114) Fix CreateContainerCmdImpl.withVolumesFrom() * [#111](https://github.com/docker-java/docker-java/pull/111) Allow to send empty messages in StartContainerCmd docker-java-0.10.4 From 9b45d934c3bed4b14fad54f3ef3c79685ada88e5 Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Tue, 23 Dec 2014 12:11:59 +0000 Subject: [PATCH 246/452] Use chunked encoding when passing the docker image. If you don't do this, you very often run out of heap space, as the webclient will create a buffer for the entire image file (possibly many gigabytes) before sending it. Signed-off-by: Nigel Magnay --- .../java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index 71d3f902..85c5f18c 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -8,6 +8,8 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.client.RequestEntityProcessing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,6 +41,10 @@ protected InputStream execute(BuildImageCmd command) { webResource = webResource.queryParam("q", "true"); } + + webResource.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.CHUNKED); + webResource.property(ClientProperties.CHUNKED_ENCODING_SIZE, 1024*1024); + LOGGER.debug("POST: {}", webResource); return webResource .request() From f86abdbf9240279c3e7c113edecdb2190394c433 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Tue, 23 Dec 2014 20:17:33 +0100 Subject: [PATCH 247/452] Update CHANGELOG.md --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2370e11e..55f09fc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,8 @@ Change Log docker-java-0.10.5-SNAPSHOT --- - + + * [#118](https://github.com/docker-java/docker-java/pull/118) Use chunked encoding when passing the docker image * [#115](https://github.com/docker-java/docker-java/pull/115) Polish RestartPolicy * [#114](https://github.com/docker-java/docker-java/pull/114) Fix CreateContainerCmdImpl.withVolumesFrom() * [#111](https://github.com/docker-java/docker-java/pull/111) Allow to send empty messages in StartContainerCmd From 20a72fc146d61ea9de9f03471fc3380acc127188 Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Fri, 19 Dec 2014 10:21:36 +0000 Subject: [PATCH 248/452] Currently, the certificates present for SSL access must all be accessible on the local disk. This is inconvenient for some clients who may already have a pre-baked keystore in hand. Create different options for retrieving the neccessary SSLContext, so that the two different options can be used. Signed-off-by: Nigel Magnay --- .../dockerjava/core/KeystoreSSLConfig.java | 133 ++++++++++++++++++ .../core/LocalDirectorySSLConfig.java | 101 +++++++++++++ .../com/github/dockerjava/core/SSLConfig.java | 22 +++ 3 files changed, 256 insertions(+) create mode 100644 src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java create mode 100644 src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java create mode 100644 src/main/java/com/github/dockerjava/core/SSLConfig.java diff --git a/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java b/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java new file mode 100644 index 00000000..269b8765 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java @@ -0,0 +1,133 @@ +package com.github.dockerjava.core; + +import com.google.common.base.Objects; +import com.google.common.base.Preconditions; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.Serializable; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +/** + * An SSL Config that is based on an pre-existing or pre-loaded KeyStore. + */ +public class KeystoreSSLConfig implements SSLConfig, Serializable { + + private final KeyStore keystore; + private final String keystorePassword; + + /** + * @param keystore a KeyStore + * @param keystorePassword key password + */ + public KeystoreSSLConfig(KeyStore keystore, String keystorePassword) { + this.keystorePassword = keystorePassword; + Preconditions.checkNotNull(keystore); + this.keystore = keystore; + } + + /** + * + * @param pfxFile a PKCS12 file + * @param password Password for the keystore + * @throws KeyStoreException + * @throws IOException + * @throws CertificateException + * @throws NoSuchAlgorithmException + */ + public KeystoreSSLConfig(File pfxFile, String password) + throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { + Preconditions.checkNotNull(pfxFile); + Preconditions.checkNotNull(password); + keystore = KeyStore.getInstance("pkcs12"); + keystore.load(new FileInputStream(pfxFile), password.toCharArray()); + keystorePassword = password; + } + + + /** + * Get the SSL Context out of the keystore. + * @return java SSLContext + * @throws KeyManagementException + * @throws UnrecoverableKeyException + * @throws NoSuchAlgorithmException + * @throws KeyStoreException + */ + @Override + public SSLContext getSSLContext() + throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, + KeyStoreException { + + final SSLContext context = SSLContext.getInstance("TLS"); + + String httpProtocols = System.getProperty("https.protocols"); + System.setProperty("https.protocols", "TLSv1"); + + if (httpProtocols != null) + System.setProperty("https.protocols", httpProtocols); + + final KeyManagerFactory + keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(keystore, keystorePassword.toCharArray()); + context.init(keyManagerFactory.getKeyManagers(), new TrustManager[]{ + new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[]{}; + } + + @Override + public void checkClientTrusted(final X509Certificate[] arg0, final String arg1) { + + } + + @Override + public void checkServerTrusted(final X509Certificate[] arg0, final String arg1) { + + } + } + }, new SecureRandom()); + + return context; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + KeystoreSSLConfig that = (KeystoreSSLConfig) o; + + return keystore.equals(that.keystore); + + } + + @Override + public int hashCode() { + return keystore.hashCode(); + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("keystore", keystore) + .toString(); + } +} diff --git a/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java b/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java new file mode 100644 index 00000000..ef57a0de --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java @@ -0,0 +1,101 @@ +package com.github.dockerjava.core; + +import com.google.common.base.Objects; +import com.google.common.base.Preconditions; + +import com.github.dockerjava.api.DockerClientException; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.glassfish.jersey.SslConfigurator; + +import java.io.Serializable; +import java.security.KeyStore; +import java.security.Security; + +import javax.net.ssl.SSLContext; + +/** + * SSL Config from local files. + */ +public class LocalDirectorySSLConfig implements SSLConfig, Serializable { + + private final String dockerCertPath; + + public LocalDirectorySSLConfig(String dockerCertPath) { + Preconditions.checkNotNull(dockerCertPath); + this.dockerCertPath = dockerCertPath; + } + + public String getDockerCertPath() { + return dockerCertPath; + } + + @Override + public SSLContext getSSLContext() { + + boolean certificatesExist = CertificateUtils.verifyCertificatesExist(dockerCertPath); + + if (certificatesExist) { + + try { + + Security.addProvider(new BouncyCastleProvider()); + + KeyStore keyStore = CertificateUtils.createKeyStore(dockerCertPath); + KeyStore trustStore = CertificateUtils.createTrustStore(dockerCertPath); + + // properties acrobatics not needed for java > 1.6 + String httpProtocols = System.getProperty("https.protocols"); + System.setProperty("https.protocols", "TLSv1"); + SslConfigurator sslConfig = SslConfigurator.newInstance(true); + if (httpProtocols != null) { + System.setProperty("https.protocols", httpProtocols); + } + + sslConfig.keyStore(keyStore); + sslConfig.keyStorePassword("docker"); + sslConfig.trustStore(trustStore); + + return sslConfig.createSSLContext(); + + + } catch (Exception e) { + throw new DockerClientException(e.getMessage(), e); + } + + } + + return null; + + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + LocalDirectorySSLConfig that = (LocalDirectorySSLConfig) o; + + if (!dockerCertPath.equals(that.dockerCertPath)) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + return dockerCertPath.hashCode(); + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("dockerCertPath", dockerCertPath) + .toString(); + } +} diff --git a/src/main/java/com/github/dockerjava/core/SSLConfig.java b/src/main/java/com/github/dockerjava/core/SSLConfig.java new file mode 100644 index 00000000..21024c4f --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/SSLConfig.java @@ -0,0 +1,22 @@ +package com.github.dockerjava.core; + +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; + +import javax.net.ssl.SSLContext; + +/** + * Get an SSL Config. Allows for various different implementations. + */ +public interface SSLConfig { + + /** + * Get the SSL Context, from wherever it comes (file, keystore). + * @return an SSL context. + */ + SSLContext getSSLContext() + throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, + KeyStoreException; +} From 138b11ef91c0414c889a2bff28733c3f8ef89fec Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Fri, 19 Dec 2014 10:22:24 +0000 Subject: [PATCH 249/452] Change the client configuration so that it can optionally take an SSLConfig. Signed-off-by: Nigel Magnay --- .../dockerjava/core/DockerClientConfig.java | 36 +++++++++------- .../jaxrs/DockerCmdExecFactoryImpl.java | 41 ++++--------------- .../core/DockerClientConfigTest.java | 6 +-- .../dockerjava/core/DockerClientImplTest.java | 2 +- 4 files changed, 33 insertions(+), 52 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index ff1329c6..db27940a 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -6,11 +6,12 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; +import java.io.Serializable; import java.net.URI; import java.util.Map; import java.util.Properties; -public class DockerClientConfig { +public class DockerClientConfig implements Serializable { private static final String DOCKER_HOST_PROPERTY = "DOCKER_HOST"; private static final String DOCKER_CERT_PATH_PROPERTY = "DOCKER_CERT_PATH"; private static final String DOCKER_IO_URL_PROPERTY = "docker.io.url"; @@ -41,21 +42,22 @@ public class DockerClientConfig { .build(); private static final String DOCKER_IO_PROPERTIES_PROPERTY = "docker.io.properties"; private final URI uri; - private final String version, username, password, email, serverAddress, dockerCertPath, dockerCfgPath; + private final String version, username, password, email, serverAddress, dockerCfgPath; private final Integer readTimeout; private final boolean loggingFilterEnabled; + private final SSLConfig sslConfig; - DockerClientConfig(URI uri, String version, String username, String password, String email, String serverAddress, String dockerCertPath, String dockerCfgPath, Integer readTimeout, boolean loggingFilterEnabled) { + DockerClientConfig(URI uri, String version, String username, String password, String email, String serverAddress, String dockerCfgPath, Integer readTimeout, boolean loggingFilterEnabled, SSLConfig sslConfig) { this.uri = uri; this.version = version; this.username = username; this.password = password; this.email = email; this.serverAddress = serverAddress; - this.dockerCertPath = dockerCertPath; this.dockerCfgPath = dockerCfgPath; this.readTimeout = readTimeout; this.loggingFilterEnabled = loggingFilterEnabled; + this.sslConfig = sslConfig; } private static Properties loadIncludedDockerProperties(Properties systemProperties) { @@ -212,15 +214,15 @@ public boolean isLoggingFilterEnabled() { return loggingFilterEnabled; } - public String getDockerCertPath() { - return dockerCertPath; + public SSLConfig getSslConfig() { + return sslConfig; } public String getDockerCfgPath() { return dockerCfgPath; } - @Override + @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; @@ -228,7 +230,7 @@ public boolean equals(Object o) { DockerClientConfig that = (DockerClientConfig) o; if (loggingFilterEnabled != that.loggingFilterEnabled) return false; - if (dockerCertPath != null ? !dockerCertPath.equals(that.dockerCertPath) : that.dockerCertPath != null) + if (sslConfig != null ? !sslConfig.equals(that.sslConfig) : that.sslConfig != null) return false; if (dockerCfgPath != null ? !dockerCfgPath.equals(that.dockerCfgPath) : that.dockerCfgPath != null) return false; @@ -252,8 +254,8 @@ public int hashCode() { result = 31 * result + (password != null ? password.hashCode() : 0); result = 31 * result + (email != null ? email.hashCode() : 0); result = 31 * result + (serverAddress != null ? serverAddress.hashCode() : 0); - result = 31 * result + (dockerCertPath != null ? dockerCertPath.hashCode() : 0); result = 31 * result + (dockerCfgPath != null ? dockerCfgPath.hashCode() : 0); + result = 31 * result + (sslConfig != null ? sslConfig.hashCode() : 0); result = 31 * result + (readTimeout != null ? readTimeout.hashCode() : 0); result = 31 * result + (loggingFilterEnabled ? 1 : 0); return result; @@ -268,8 +270,8 @@ public String toString() { ", password='" + password + '\'' + ", email='" + email + '\'' + ", serverAddress='" + serverAddress + '\'' + - ", dockerCertPath='" + dockerCertPath + '\'' + ", dockerCfgPath='" + dockerCfgPath + '\'' + + ", sslConfig='" + sslConfig + '\'' + ", readTimeout=" + readTimeout + ", loggingFilterEnabled=" + loggingFilterEnabled + '}'; @@ -277,9 +279,10 @@ public String toString() { public static class DockerClientConfigBuilder { private URI uri; - private String version, username, password, email, serverAddress, dockerCertPath, dockerCfgPath; + private String version, username, password, email, serverAddress, dockerCfgPath; private Integer readTimeout; private boolean loggingFilterEnabled; + private SSLConfig sslConfig; /** * This will set all fields in the builder to those contained in the Properties object. The Properties object @@ -342,7 +345,7 @@ public final DockerClientConfigBuilder withLoggingFilter(boolean loggingFilterEn } public final DockerClientConfigBuilder withDockerCertPath(String dockerCertPath) { - this.dockerCertPath = dockerCertPath; + this.sslConfig = new LocalDirectorySSLConfig(dockerCertPath); return this; } @@ -352,6 +355,11 @@ public final DockerClientConfigBuilder withDockerCfgPath(String dockerCfgPath) { } + public final DockerClientConfigBuilder withSSLConfig(SSLConfig config) { + this.sslConfig = config; + return this; + } + public DockerClientConfig build() { return new DockerClientConfig( uri, @@ -360,10 +368,10 @@ public DockerClientConfig build() { password, email, serverAddress, - dockerCertPath, dockerCfgPath, readTimeout, - loggingFilterEnabled + loggingFilterEnabled, + sslConfig ); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 862824fc..64222a97 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -52,43 +52,16 @@ public void init(DockerClientConfig dockerClientConfig) { ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig); - String dockerCertPath = dockerClientConfig.getDockerCertPath(); - - if (dockerCertPath != null) { - boolean certificatesExist = CertificateUtils.verifyCertificatesExist(dockerCertPath); - - if (certificatesExist) { - - try { - - Security.addProvider(new BouncyCastleProvider()); - - KeyStore keyStore = CertificateUtils.createKeyStore(dockerCertPath); - KeyStore trustStore = CertificateUtils.createTrustStore(dockerCertPath); - - // properties acrobatics not needed for java > 1.6 - String httpProtocols = System.getProperty("https.protocols"); - System.setProperty("https.protocols", "TLSv1"); - SslConfigurator sslConfig = SslConfigurator.newInstance(true); - if (httpProtocols != null) System.setProperty("https.protocols", httpProtocols); - - sslConfig.keyStore(keyStore); - sslConfig.keyStorePassword("docker"); - sslConfig.trustStore(trustStore); - - SSLContext sslContext = sslConfig.createSSLContext(); - - - clientBuilder.sslContext(sslContext); - - } catch (Exception e) { - throw new DockerClientException(e.getMessage(), e); - } - - } + try { + SSLContext ssl = dockerClientConfig.getSslConfig().getSSLContext(); + if (ssl != null) + clientBuilder.sslContext(ssl); + } catch(Exception ex) { + throw new DockerClientException("Error in SSL Configuration", ex); } + client = clientBuilder.build(); WebTarget webResource = client.target(dockerClientConfig.getUri()); diff --git a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java index 06bb1ea1..7b5e4e1f 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java @@ -16,12 +16,12 @@ public class DockerClientConfigTest { public static final DockerClientConfig EXAMPLE_CONFIG = newExampleConfig(); private static DockerClientConfig newExampleConfig() { - return new DockerClientConfig(URI.create("http://foo"), "bar", "baz", "qux", "blam", "wham", "flim", "flam", 877, false); + return new DockerClientConfig(URI.create("http://foo"), "bar", "baz", "qux", "blam", "wham", "flam", 877, false, new LocalDirectorySSLConfig("flim")); } @Test public void string() throws Exception { - assertEquals("DockerClientConfig{uri=http://foo, version='bar', username='baz', password='qux', email='blam', serverAddress='wham', dockerCertPath='flim', dockerCfgPath='flam', readTimeout=877, loggingFilterEnabled=false}", + assertEquals("DockerClientConfig{uri=http://foo, version='bar', username='baz', password='qux', email='blam', serverAddress='wham', dockerCfgPath='flam', sslConfig='LocalDirectorySSLConfig{dockerCertPath=flim}', readTimeout=877, loggingFilterEnabled=false}", EXAMPLE_CONFIG.toString()); } @@ -104,8 +104,8 @@ public void defaults() throws Exception { assertEquals(config.getServerAddress(), AuthConfig.DEFAULT_SERVER_ADDRESS); assertEquals(config.getVersion(), null); assertEquals(config.isLoggingFilterEnabled(), true); - assertEquals(config.getDockerCertPath(), "someHomeDir/.docker"); assertEquals(config.getDockerCfgPath(), "someHomeDir/.dockercfg"); + assertEquals( ((LocalDirectorySSLConfig)config.getSslConfig()).getDockerCertPath(), "someHomeDir/.docker"); } @Test diff --git a/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java b/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java index c31db1ba..a91fa109 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java @@ -10,7 +10,7 @@ public class DockerClientImplTest { @Test public void configuredInstanceAuthConfig() throws Exception { // given a config with null serverAddress - DockerClientConfig dockerClientConfig = new DockerClientConfig(null, null, "", "", "", null, null, null, 0, false); + DockerClientConfig dockerClientConfig = new DockerClientConfig(null, null, "", "", "", null, null, 0, false, null); DockerClientImpl dockerClient = DockerClientImpl.getInstance(dockerClientConfig); // when we get the auth config From f0e78bdafd77ccf2fa6d6235e8743601261d01a2 Mon Sep 17 00:00:00 2001 From: Ted Crossman Date: Wed, 7 Jan 2015 07:38:29 -0800 Subject: [PATCH 250/452] Add support for deleting temporary temp files DockerCmd now extends java.io.Closeable. This allows us to cleanup the temporary tar file created when DockerClient.buildImageCmd(File) is invoked. Code would look like: BuildImageCmd cmd = dockerClient.buildCmd(myDir); try { // .. // cmd.exec(); // ... } finally { cmd.close(); } --- .../dockerjava/api/command/DockerCmd.java | 4 +++- .../core/command/AbstrDockerCmd.java | 7 +++++- .../core/command/BuildImageCmdImpl.java | 22 +++++++++++++++---- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/DockerCmd.java b/src/main/java/com/github/dockerjava/api/command/DockerCmd.java index 4c30382b..89c31666 100644 --- a/src/main/java/com/github/dockerjava/api/command/DockerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/DockerCmd.java @@ -1,6 +1,8 @@ package com.github.dockerjava.api.command; -public interface DockerCmd { +import java.io.Closeable; + +public interface DockerCmd extends Closeable { public RES_T exec(); diff --git a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java index 00c89159..54312c50 100644 --- a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java @@ -1,5 +1,7 @@ package com.github.dockerjava.core.command; +import java.io.IOException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,4 +27,7 @@ public RES_T exec() throws DockerException { LOGGER.debug("Cmd: {}", this); return execution.exec((CMD_T)this); } -} \ No newline at end of file + + @Override + public void close() throws IOException {} +} diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index a62b75c0..a9c0a44b 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -40,6 +40,7 @@ public class BuildImageCmdImpl extends AbstrDockerCmd Date: Wed, 7 Jan 2015 22:01:15 +0100 Subject: [PATCH 251/452] call close() after command execution --- .../com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java index 34414d73..727055f9 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java @@ -45,13 +45,21 @@ public RES_T exec(CMD_T command) { RES_T result; try { result = execute(command); + } catch (ProcessingException e) { if(e.getCause() instanceof DockerException) { throw (DockerException)e.getCause(); } else { throw e; } + } finally { + try { + command.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } } + return result; } From 56508c293bcbee51c601f4f7588f62d2cb7a7e08 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 7 Jan 2015 22:01:46 +0100 Subject: [PATCH 252/452] close InputStream --- .../com/github/dockerjava/core/command/BuildImageCmdImpl.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index a9c0a44b..9e8b5a14 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -142,6 +142,8 @@ public void close() throws IOException { if (tarFile != null) { FileUtils.deleteQuietly(tarFile); } + + tarInputStream.close(); } @Override From 4c12ec69ccff6bf688f1fbff16f1ff5fc9f8aa33 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 7 Jan 2015 22:06:25 +0100 Subject: [PATCH 253/452] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 55f09fc2..73aaeb8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ Change Log docker-java-0.10.5-SNAPSHOT --- - + * [#120](https://github.com/docker-java/docker-java/pull/120) Command resource cleanup after command execution * [#118](https://github.com/docker-java/docker-java/pull/118) Use chunked encoding when passing the docker image * [#115](https://github.com/docker-java/docker-java/pull/115) Polish RestartPolicy * [#114](https://github.com/docker-java/docker-java/pull/114) Fix CreateContainerCmdImpl.withVolumesFrom() From bb70d0955e682c6c2fcd9b96b5f32af9e0ead7da Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 7 Jan 2015 22:19:38 +0100 Subject: [PATCH 254/452] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 73aaeb8a..0fe22888 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,8 +3,10 @@ Change Log docker-java-0.10.5-SNAPSHOT --- + * [#120](https://github.com/docker-java/docker-java/pull/120) Command resource cleanup after command execution * [#118](https://github.com/docker-java/docker-java/pull/118) Use chunked encoding when passing the docker image + * [#116](https://github.com/docker-java/docker-java/pull/116) Allow SSL configuration from pre-existing keystore to be used * [#115](https://github.com/docker-java/docker-java/pull/115) Polish RestartPolicy * [#114](https://github.com/docker-java/docker-java/pull/114) Fix CreateContainerCmdImpl.withVolumesFrom() * [#111](https://github.com/docker-java/docker-java/pull/111) Allow to send empty messages in StartContainerCmd From 99b3367e99c50b22e709eaa83a3f30f96f2928be Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 9 Jan 2015 19:55:30 +0100 Subject: [PATCH 255/452] Fix issue#119 --- .../dockerjava/core/DockerClientConfig.java | 50 ++++- .../dockerjava/core/DockerClientImpl.java | 202 ++++++++++-------- .../core/command/PullImageCmdImpl.java | 15 +- 3 files changed, 160 insertions(+), 107 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index db27940a..8506d437 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -1,5 +1,9 @@ package com.github.dockerjava.core; +import com.github.dockerjava.api.DockerClientException; +import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.core.NameParser.HostnameReposName; +import com.github.dockerjava.core.NameParser.ReposTag; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; @@ -12,7 +16,10 @@ import java.util.Properties; public class DockerClientConfig implements Serializable { - private static final String DOCKER_HOST_PROPERTY = "DOCKER_HOST"; + + private static final long serialVersionUID = -4307357472441531489L; + + private static final String DOCKER_HOST_PROPERTY = "DOCKER_HOST"; private static final String DOCKER_CERT_PATH_PROPERTY = "DOCKER_CERT_PATH"; private static final String DOCKER_IO_URL_PROPERTY = "docker.io.url"; private static final String DOCKER_IO_VERSION_PROPERTY = "docker.io.version"; @@ -221,6 +228,47 @@ public SSLConfig getSslConfig() { public String getDockerCfgPath() { return dockerCfgPath; } + + private AuthConfig getAuthConfig() { + AuthConfig authConfig = null; + if(getUsername() != null) { + authConfig = new AuthConfig(); + authConfig.setUsername(getUsername()); + authConfig.setPassword(getPassword()); + authConfig.setEmail(getEmail()); + authConfig.setServerAddress(getServerAddress()); + } + return authConfig; + } + + public AuthConfig effectiveAuthConfig(String imageName) { + AuthConfig authConfig = null; + + String dockerCfgFile = getDockerCfgPath(); + + if (dockerCfgFile != null && imageName != null) { + AuthConfigFile authConfigFile; + try { + authConfigFile = AuthConfigFile.loadConfig(new File( + dockerCfgFile)); + } catch (IOException e) { + throw new DockerClientException( + "Failed to parse dockerCfgFile", e); + } + ReposTag reposTag = NameParser.parseRepositoryTag(imageName); + HostnameReposName hostnameReposName = NameParser + .resolveRepositoryName(reposTag.repos); + + authConfig = authConfigFile + .resolveAuthConfig(hostnameReposName.hostname); + } + + AuthConfig _authConfig = getAuthConfig(); + + if(_authConfig != null) authConfig = _authConfig; + + return authConfig; + } @Override public boolean equals(Object o) { diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 1a2a58c0..09fafd9e 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -18,14 +18,14 @@ /** * @author Konstantin Pelykh (kpelykh@gmail.com) - * + * * @see https://github.com/docker/docker/blob/master/api/client/commands.go */ public class DockerClientImpl implements Closeable, DockerClient { - private final DockerClientConfig dockerClientConfig; + private final DockerClientConfig dockerClientConfig; - private DockerCmdExecFactory dockerCmdExecFactory; + private DockerCmdExecFactory dockerCmdExecFactory; private DockerClientImpl() { this(DockerClientConfig.createDefaultConfigBuilder().build()); @@ -35,53 +35,57 @@ private DockerClientImpl(String serverUrl) { this(configWithServerUrl(serverUrl)); } - private DockerClientImpl(DockerClientConfig dockerClientConfig) { - Preconditions.checkNotNull(dockerClientConfig, "config was not specified"); - this.dockerClientConfig = dockerClientConfig; - } + private DockerClientImpl(DockerClientConfig dockerClientConfig) { + Preconditions.checkNotNull(dockerClientConfig, + "config was not specified"); + this.dockerClientConfig = dockerClientConfig; + } - private static DockerClientConfig configWithServerUrl(String serverUrl) { + private static DockerClientConfig configWithServerUrl(String serverUrl) { return DockerClientConfig.createDefaultConfigBuilder() - .withUri(serverUrl) - .build(); + .withUri(serverUrl).build(); } - public static DockerClientImpl getInstance() { - return new DockerClientImpl(); - } + public static DockerClientImpl getInstance() { + return new DockerClientImpl(); + } - public static DockerClientImpl getInstance(DockerClientConfig dockerClientConfig) { - return new DockerClientImpl(dockerClientConfig); - } + public static DockerClientImpl getInstance( + DockerClientConfig dockerClientConfig) { + return new DockerClientImpl(dockerClientConfig); + } - public static DockerClientImpl getInstance(String serverUrl) { - return new DockerClientImpl(serverUrl); - } + public static DockerClientImpl getInstance(String serverUrl) { + return new DockerClientImpl(serverUrl); + } - public DockerClientImpl withDockerCmdExecFactory( - DockerCmdExecFactory dockerCmdExecFactory) { - Preconditions.checkNotNull(dockerCmdExecFactory, "dockerCmdExecFactory was not specified"); + public DockerClientImpl withDockerCmdExecFactory( + DockerCmdExecFactory dockerCmdExecFactory) { + Preconditions.checkNotNull(dockerCmdExecFactory, + "dockerCmdExecFactory was not specified"); this.dockerCmdExecFactory = dockerCmdExecFactory; this.dockerCmdExecFactory.init(dockerClientConfig); return this; } private DockerCmdExecFactory getDockerCmdExecFactory() { - Preconditions.checkNotNull(dockerCmdExecFactory, "dockerCmdExecFactory was not specified"); + Preconditions.checkNotNull(dockerCmdExecFactory, + "dockerCmdExecFactory was not specified"); return dockerCmdExecFactory; } - - @Override - public AuthConfig authConfig() { - checkNotNull(dockerClientConfig.getUsername(), "Configured username is null."); - checkNotNull(dockerClientConfig.getServerAddress(), "Configured serverAddress is null."); - - AuthConfig authConfig = new AuthConfig(); - authConfig.setUsername(dockerClientConfig.getUsername()); - authConfig.setPassword(dockerClientConfig.getPassword()); - authConfig.setEmail(dockerClientConfig.getEmail()); - authConfig.setServerAddress(dockerClientConfig.getServerAddress()); + @Override + public AuthConfig authConfig() { + checkNotNull(dockerClientConfig.getUsername(), + "Configured username is null."); + checkNotNull(dockerClientConfig.getServerAddress(), + "Configured serverAddress is null."); + + AuthConfig authConfig = new AuthConfig(); + authConfig.setUsername(dockerClientConfig.getUsername()); + authConfig.setPassword(dockerClientConfig.getPassword()); + authConfig.setEmail(dockerClientConfig.getEmail()); + authConfig.setServerAddress(dockerClientConfig.getServerAddress()); return authConfig; } @@ -95,7 +99,8 @@ public AuthConfig authConfig() { */ @Override public AuthCmd authCmd() { - return new AuthCmdImpl(getDockerCmdExecFactory().createAuthCmdExec(), authConfig()); + return new AuthCmdImpl(getDockerCmdExecFactory().createAuthCmdExec(), + authConfig()); } @Override @@ -105,68 +110,59 @@ public InfoCmd infoCmd() { @Override public PingCmd pingCmd() { - return new PingCmdImpl(getDockerCmdExecFactory().createPingCmdExec()); + return new PingCmdImpl(getDockerCmdExecFactory().createPingCmdExec()); } @Override public VersionCmd versionCmd() { - return new VersionCmdImpl(getDockerCmdExecFactory().createVersionCmdExec()); + return new VersionCmdImpl(getDockerCmdExecFactory() + .createVersionCmdExec()); } /** * * IMAGE API * */ - @Override public PullImageCmd pullImageCmd(String repository) { - return new PullImageCmdImpl(getDockerCmdExecFactory().createPullImageCmdExec(), repository); + return new PullImageCmdImpl(getDockerCmdExecFactory() + .createPullImageCmdExec(), repository).withAuthConfig(dockerClientConfig.effectiveAuthConfig(repository)); } @Override public PushImageCmd pushImageCmd(String name) { - PushImageCmd cmd = new PushImageCmdImpl(getDockerCmdExecFactory().createPushImageCmdExec(), - name); - String dockerCfgFile = dockerClientConfig.getDockerCfgPath(); - if (dockerCfgFile != null) { - AuthConfigFile authConfigFile; - try { - authConfigFile = AuthConfigFile.loadConfig(new File(dockerCfgFile)); - } catch (IOException e) { - throw new DockerClientException("Failed to parse dockerCfgFile", e); - } - ReposTag reposTag = NameParser.parseRepositoryTag(name); - HostnameReposName hostnameReposName = NameParser.resolveRepositoryName(reposTag.repos); - AuthConfig authConfig = authConfigFile.resolveAuthConfig(hostnameReposName.hostname); - if (authConfig != null) { - cmd.withAuthConfig(authConfig); - } - } - return cmd; + return new PushImageCmdImpl(getDockerCmdExecFactory() + .createPushImageCmdExec(), name).withAuthConfig(dockerClientConfig.effectiveAuthConfig(name)); } @Override - public CreateImageCmd createImageCmd(String repository, InputStream imageStream) { - return new CreateImageCmdImpl(getDockerCmdExecFactory().createCreateImageCmdExec(), repository, imageStream); + public CreateImageCmd createImageCmd(String repository, + InputStream imageStream) { + return new CreateImageCmdImpl(getDockerCmdExecFactory() + .createCreateImageCmdExec(), repository, imageStream); } @Override public SearchImagesCmd searchImagesCmd(String term) { - return new SearchImagesCmdImpl(getDockerCmdExecFactory().createSearchImagesCmdExec(), term); + return new SearchImagesCmdImpl(getDockerCmdExecFactory() + .createSearchImagesCmdExec(), term); } @Override public RemoveImageCmd removeImageCmd(String imageId) { - return new RemoveImageCmdImpl(getDockerCmdExecFactory().createRemoveImageCmdExec(), imageId); + return new RemoveImageCmdImpl(getDockerCmdExecFactory() + .createRemoveImageCmdExec(), imageId); } @Override public ListImagesCmd listImagesCmd() { - return new ListImagesCmdImpl(getDockerCmdExecFactory().createListImagesCmdExec()); + return new ListImagesCmdImpl(getDockerCmdExecFactory() + .createListImagesCmdExec()); } @Override public InspectImageCmd inspectImageCmd(String imageId) { - return new InspectImageCmdImpl(getDockerCmdExecFactory().createInspectImageCmdExec(), imageId); + return new InspectImageCmdImpl(getDockerCmdExecFactory() + .createInspectImageCmdExec(), imageId); } /** @@ -175,112 +171,134 @@ public InspectImageCmd inspectImageCmd(String imageId) { @Override public ListContainersCmd listContainersCmd() { - return new ListContainersCmdImpl(getDockerCmdExecFactory().createListContainersCmdExec()); + return new ListContainersCmdImpl(getDockerCmdExecFactory() + .createListContainersCmdExec()); } @Override public CreateContainerCmd createContainerCmd(String image) { - return new CreateContainerCmdImpl(getDockerCmdExecFactory().createCreateContainerCmdExec(), image); + return new CreateContainerCmdImpl(getDockerCmdExecFactory() + .createCreateContainerCmdExec(), image); } @Override public StartContainerCmd startContainerCmd(String containerId) { - return new StartContainerCmdImpl(getDockerCmdExecFactory().createStartContainerCmdExec(), containerId); + return new StartContainerCmdImpl(getDockerCmdExecFactory() + .createStartContainerCmdExec(), containerId); } @Override public InspectContainerCmd inspectContainerCmd(String containerId) { - return new InspectContainerCmdImpl(getDockerCmdExecFactory().createInspectContainerCmdExec(), containerId); + return new InspectContainerCmdImpl(getDockerCmdExecFactory() + .createInspectContainerCmdExec(), containerId); } @Override public RemoveContainerCmd removeContainerCmd(String containerId) { - return new RemoveContainerCmdImpl(getDockerCmdExecFactory().createRemoveContainerCmdExec(), containerId); + return new RemoveContainerCmdImpl(getDockerCmdExecFactory() + .createRemoveContainerCmdExec(), containerId); } @Override public WaitContainerCmd waitContainerCmd(String containerId) { - return new WaitContainerCmdImpl(getDockerCmdExecFactory().createWaitContainerCmdExec(), containerId); + return new WaitContainerCmdImpl(getDockerCmdExecFactory() + .createWaitContainerCmdExec(), containerId); } @Override public AttachContainerCmd attachContainerCmd(String containerId) { - return new AttachContainerCmdImpl(getDockerCmdExecFactory().createAttachContainerCmdExec(), containerId); + return new AttachContainerCmdImpl(getDockerCmdExecFactory() + .createAttachContainerCmdExec(), containerId); } @Override public LogContainerCmd logContainerCmd(String containerId) { - return new LogContainerCmdImpl(getDockerCmdExecFactory().createLogContainerCmdExec(), containerId); + return new LogContainerCmdImpl(getDockerCmdExecFactory() + .createLogContainerCmdExec(), containerId); } @Override - public CopyFileFromContainerCmd copyFileFromContainerCmd(String containerId, String resource) { - return new CopyFileFromContainerCmdImpl(getDockerCmdExecFactory().createCopyFileFromContainerCmdExec(), containerId, resource); + public CopyFileFromContainerCmd copyFileFromContainerCmd( + String containerId, String resource) { + return new CopyFileFromContainerCmdImpl(getDockerCmdExecFactory() + .createCopyFileFromContainerCmdExec(), containerId, resource); } @Override public ContainerDiffCmd containerDiffCmd(String containerId) { - return new ContainerDiffCmdImpl(getDockerCmdExecFactory().createContainerDiffCmdExec(), containerId); + return new ContainerDiffCmdImpl(getDockerCmdExecFactory() + .createContainerDiffCmdExec(), containerId); } @Override public StopContainerCmd stopContainerCmd(String containerId) { - return new StopContainerCmdImpl(getDockerCmdExecFactory().createStopContainerCmdExec(), containerId); + return new StopContainerCmdImpl(getDockerCmdExecFactory() + .createStopContainerCmdExec(), containerId); } @Override public KillContainerCmd killContainerCmd(String containerId) { - return new KillContainerCmdImpl(getDockerCmdExecFactory().createKillContainerCmdExec(), containerId); + return new KillContainerCmdImpl(getDockerCmdExecFactory() + .createKillContainerCmdExec(), containerId); } @Override public RestartContainerCmd restartContainerCmd(String containerId) { - return new RestartContainerCmdImpl(getDockerCmdExecFactory().createRestartContainerCmdExec(), containerId); + return new RestartContainerCmdImpl(getDockerCmdExecFactory() + .createRestartContainerCmdExec(), containerId); } @Override public CommitCmd commitCmd(String containerId) { - return new CommitCmdImpl(getDockerCmdExecFactory().createCommitCmdExec(), containerId); + return new CommitCmdImpl(getDockerCmdExecFactory() + .createCommitCmdExec(), containerId); } @Override public BuildImageCmd buildImageCmd(File dockerFolder) { - return new BuildImageCmdImpl(getDockerCmdExecFactory().createBuildImageCmdExec(), dockerFolder); + return new BuildImageCmdImpl(getDockerCmdExecFactory() + .createBuildImageCmdExec(), dockerFolder); } @Override public BuildImageCmd buildImageCmd(InputStream tarInputStream) { - return new BuildImageCmdImpl(getDockerCmdExecFactory().createBuildImageCmdExec(), tarInputStream); + return new BuildImageCmdImpl(getDockerCmdExecFactory() + .createBuildImageCmdExec(), tarInputStream); } @Override public TopContainerCmd topContainerCmd(String containerId) { - return new TopContainerCmdImpl(getDockerCmdExecFactory().createTopContainerCmdExec(), containerId); + return new TopContainerCmdImpl(getDockerCmdExecFactory() + .createTopContainerCmdExec(), containerId); } @Override public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { - return new TagImageCmdImpl(getDockerCmdExecFactory().createTagImageCmdExec(), imageId, repository, tag); + return new TagImageCmdImpl(getDockerCmdExecFactory() + .createTagImageCmdExec(), imageId, repository, tag); } @Override public PauseContainerCmd pauseContainerCmd(String containerId) { - return new PauseContainerCmdImpl(getDockerCmdExecFactory().createPauseContainerCmdExec(), containerId); + return new PauseContainerCmdImpl(getDockerCmdExecFactory() + .createPauseContainerCmdExec(), containerId); } @Override public UnpauseContainerCmd unpauseContainerCmd(String containerId) { - return new UnpauseContainerCmdImpl(getDockerCmdExecFactory().createUnpauseContainerCmdExec(), containerId); + return new UnpauseContainerCmdImpl(getDockerCmdExecFactory() + .createUnpauseContainerCmdExec(), containerId); } - @Override - public EventsCmd eventsCmd(EventCallback eventCallback) { - return new EventsCmdImpl(getDockerCmdExecFactory().createEventsCmdExec(), eventCallback); - } + @Override + public EventsCmd eventsCmd(EventCallback eventCallback) { + return new EventsCmdImpl(getDockerCmdExecFactory() + .createEventsCmdExec(), eventCallback); + } - @Override - public void close() throws IOException { - getDockerCmdExecFactory().close(); - } + @Override + public void close() throws IOException { + getDockerCmdExecFactory().close(); + } } diff --git a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java index ed045878..b2e62434 100644 --- a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java @@ -1,7 +1,6 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.command.PullImageCmd; -import com.github.dockerjava.api.model.AuthConfig; import com.google.common.base.Preconditions; import java.io.InputStream; @@ -11,10 +10,9 @@ * Pull image from repository. * */ -public class PullImageCmdImpl extends AbstrDockerCmd implements PullImageCmd { +public class PullImageCmdImpl extends AbstrAuthCfgDockerCmd implements PullImageCmd { private String repository, tag, registry; - private AuthConfig authConfig; public PullImageCmdImpl(PullImageCmd.Exec exec, String repository) { super(exec); @@ -36,10 +34,6 @@ public String getRegistry() { return registry; } - public AuthConfig getAuthConfig() { - return authConfig; - } - @Override public PullImageCmd withRepository(String repository) { Preconditions.checkNotNull(repository, "repository was not specified"); @@ -61,13 +55,6 @@ public PullImageCmd withRegistry(String registry) { return this; } - @Override - public PullImageCmd withAuthConfig(AuthConfig authConfig) { - Preconditions.checkNotNull(authConfig, "authConfig was not specified"); - this.authConfig = authConfig; - return this; - } - @Override public String toString() { return new StringBuilder("pull ") From b637b59d103659d4d5b09d8c57d14c6031aa4c8a Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 9 Jan 2015 20:35:33 +0100 Subject: [PATCH 256/452] Fix Issue#130 --- .../api/command/CreateContainerCmd.java | 7 ++++++- .../core/command/CreateContainerCmdImpl.java | 12 ++++++++++++ .../command/CreateContainerCmdImplTest.java | 18 ++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java index 1cf3098e..2eeda23e 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java @@ -120,7 +120,12 @@ public interface CreateContainerCmd extends DockerCmd{ * prevents the container from changing the owner of any files. */ public CreateContainerCmd withCapDrop(Capability... capDrop); - + + + public String[] getEntrypoint(); + + public CreateContainerCmd withEntrypoint(String... entrypoint); + /** * @throws NotFoundException No such container * @throws ConflictException Named container already exists diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index 8a4607c2..b8cde7fe 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -39,6 +39,7 @@ public class CreateContainerCmdImpl extends AbstrDockerCmd Date: Fri, 9 Jan 2015 22:08:28 +0000 Subject: [PATCH 257/452] Implementing of Exec-start and Exec-create. --- .../github/dockerjava/api/DockerClient.java | 37 ++-------- .../api/command/DockerCmdExecFactory.java | 4 ++ .../dockerjava/api/command/ExecCreateCmd.java | 19 +++++ .../api/command/ExecCreateCmdResponce.java | 15 ++++ .../dockerjava/api/command/ExecStartCmd.java | 24 +++++++ .../dockerjava/core/DockerClientImpl.java | 10 +++ .../core/command/ExecCreateCmdImpl.java | 69 +++++++++++++++++++ .../core/command/ExecStartCmdImpl.java | 49 +++++++++++++ .../jaxrs/DockerCmdExecFactoryImpl.java | 15 ++-- .../dockerjava/jaxrs/ExecCreateCmdExec.java | 30 ++++++++ .../dockerjava/jaxrs/ExecStartCmdExec.java | 31 +++++++++ .../jaxrs/StartContainerCmdExec.java | 3 +- .../core/TestDockerCmdExecFactory.java | 49 ++++--------- .../command/StartContainerCmdImplTest.java | 2 +- 14 files changed, 281 insertions(+), 76 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/command/ExecCreateCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/ExecCreateCmdResponce.java create mode 100644 src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java create mode 100644 src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java create mode 100644 src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/ExecCreateCmdExec.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index 4052e87b..2c829679 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -2,38 +2,7 @@ import java.io.*; -import com.github.dockerjava.api.command.AttachContainerCmd; -import com.github.dockerjava.api.command.AuthCmd; -import com.github.dockerjava.api.command.BuildImageCmd; -import com.github.dockerjava.api.command.CommitCmd; -import com.github.dockerjava.api.command.ContainerDiffCmd; -import com.github.dockerjava.api.command.CopyFileFromContainerCmd; -import com.github.dockerjava.api.command.CreateContainerCmd; -import com.github.dockerjava.api.command.CreateImageCmd; -import com.github.dockerjava.api.command.EventCallback; -import com.github.dockerjava.api.command.EventsCmd; -import com.github.dockerjava.api.command.InfoCmd; -import com.github.dockerjava.api.command.InspectContainerCmd; -import com.github.dockerjava.api.command.InspectImageCmd; -import com.github.dockerjava.api.command.KillContainerCmd; -import com.github.dockerjava.api.command.ListContainersCmd; -import com.github.dockerjava.api.command.ListImagesCmd; -import com.github.dockerjava.api.command.LogContainerCmd; -import com.github.dockerjava.api.command.PauseContainerCmd; -import com.github.dockerjava.api.command.PingCmd; -import com.github.dockerjava.api.command.PullImageCmd; -import com.github.dockerjava.api.command.PushImageCmd; -import com.github.dockerjava.api.command.RemoveContainerCmd; -import com.github.dockerjava.api.command.RemoveImageCmd; -import com.github.dockerjava.api.command.RestartContainerCmd; -import com.github.dockerjava.api.command.SearchImagesCmd; -import com.github.dockerjava.api.command.StartContainerCmd; -import com.github.dockerjava.api.command.StopContainerCmd; -import com.github.dockerjava.api.command.TagImageCmd; -import com.github.dockerjava.api.command.TopContainerCmd; -import com.github.dockerjava.api.command.UnpauseContainerCmd; -import com.github.dockerjava.api.command.VersionCmd; -import com.github.dockerjava.api.command.WaitContainerCmd; +import com.github.dockerjava.api.command.*; import com.github.dockerjava.api.model.AuthConfig; // https://godoc.org/github.com/fsouza/go-dockerclient @@ -95,6 +64,8 @@ public CreateImageCmd createImageCmd(String repository, */ public StartContainerCmd startContainerCmd(String containerId); + public ExecCreateCmd execCmd(String containerId); + public InspectContainerCmd inspectContainerCmd(String containerId); public RemoveContainerCmd removeContainerCmd(String containerId); @@ -103,6 +74,8 @@ public CreateImageCmd createImageCmd(String repository, public AttachContainerCmd attachContainerCmd(String containerId); + public ExecStartCmd execStartCmd(String containerId); + public LogContainerCmd logContainerCmd(String containerId); public CopyFileFromContainerCmd copyFileFromContainerCmd( diff --git a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java index 24c0a465..df26743e 100644 --- a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java +++ b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java @@ -15,6 +15,8 @@ public interface DockerCmdExecFactory extends Closeable { public PingCmd.Exec createPingCmdExec(); + public ExecCreateCmd.Exec createExecCmdExec(); + public VersionCmd.Exec createVersionCmdExec(); public PullImageCmd.Exec createPullImageCmdExec(); @@ -45,6 +47,8 @@ public interface DockerCmdExecFactory extends Closeable { public AttachContainerCmd.Exec createAttachContainerCmdExec(); + public ExecStartCmd.Exec createExecStartCmdExec(); + public LogContainerCmd.Exec createLogContainerCmdExec(); public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec(); diff --git a/src/main/java/com/github/dockerjava/api/command/ExecCreateCmd.java b/src/main/java/com/github/dockerjava/api/command/ExecCreateCmd.java new file mode 100644 index 00000000..e6146b5f --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/ExecCreateCmd.java @@ -0,0 +1,19 @@ +package com.github.dockerjava.api.command; + +public interface ExecCreateCmd extends DockerCmd { + + public String getContainerId(); + + public ExecCreateCmd withCmd(String... cmd); + + public ExecCreateCmd attachStdin(boolean attachStdin); + + public ExecCreateCmd attachStdout(boolean attachStdout); + + public ExecCreateCmd attachStderr(boolean attachStderr); + + public ExecCreateCmd tty(boolean tty); + + public static interface Exec extends DockerCmdExec { + } +} diff --git a/src/main/java/com/github/dockerjava/api/command/ExecCreateCmdResponce.java b/src/main/java/com/github/dockerjava/api/command/ExecCreateCmdResponce.java new file mode 100644 index 00000000..57197ca8 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/ExecCreateCmdResponce.java @@ -0,0 +1,15 @@ +package com.github.dockerjava.api.command; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class ExecCreateCmdResponce { + + @JsonProperty("Id") + private String id; + + public String getId() { + return id; + } +} diff --git a/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java b/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java new file mode 100644 index 00000000..262dc0f4 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java @@ -0,0 +1,24 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; + +import java.io.InputStream; + +public interface ExecStartCmd extends DockerCmd{ + + public String getContainerId(); + + public boolean isDetach(); + + public boolean isTty(); + + public ExecStartCmd withContainerId(String containerId); + + /** + * @throws com.github.dockerjava.api.NotFoundException No such container + */ + @Override + public InputStream exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec {} +} diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 1a2a58c0..ba5c08bc 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -193,6 +193,11 @@ public InspectContainerCmd inspectContainerCmd(String containerId) { return new InspectContainerCmdImpl(getDockerCmdExecFactory().createInspectContainerCmdExec(), containerId); } + @Override + public ExecCreateCmd execCmd(String containerId) { + return new ExecCreateCmdImpl(getDockerCmdExecFactory().createExecCmdExec(), containerId); + } + @Override public RemoveContainerCmd removeContainerCmd(String containerId) { return new RemoveContainerCmdImpl(getDockerCmdExecFactory().createRemoveContainerCmdExec(), containerId); @@ -208,6 +213,11 @@ public AttachContainerCmd attachContainerCmd(String containerId) { return new AttachContainerCmdImpl(getDockerCmdExecFactory().createAttachContainerCmdExec(), containerId); } + @Override + public ExecStartCmd execStartCmd(String containerId) { + return new ExecStartCmdImpl(getDockerCmdExecFactory().createExecStartCmdExec(), containerId); + } + @Override public LogContainerCmd logContainerCmd(String containerId) { return new LogContainerCmdImpl(getDockerCmdExecFactory().createLogContainerCmdExec(), containerId); diff --git a/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java new file mode 100644 index 00000000..315980a3 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java @@ -0,0 +1,69 @@ +package com.github.dockerjava.core.command; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.ExecCreateCmd; +import com.github.dockerjava.api.command.ExecCreateCmdResponce; + +public class ExecCreateCmdImpl extends AbstrDockerCmd implements ExecCreateCmd { + + private String containerId; + + @JsonProperty("AttachStdin") + private boolean attachStdin; + + @JsonProperty("AttachStdout") + private boolean attachStdout; + + @JsonProperty("AttachStderr") + private boolean attachStderr; + + @JsonProperty("Tty") + private boolean tty; + + @JsonProperty("Cmd") + private String[] cmd; + + public ExecCreateCmdImpl(ExecCreateCmd.Exec exec, String containerId) { + super(exec); + this.containerId = containerId; + } + + public ExecCreateCmd attachStdin(boolean attachStdin) { + this.attachStdin = attachStdin; + return this; + } + + public ExecCreateCmd attachStdout(boolean attachStdout) { + this.attachStdout = attachStdout; + return this; + } + + public ExecCreateCmd tty(boolean tty) { + this.tty = tty; + return this; + } + + public ExecCreateCmd attachStderr(boolean attachStderr) { + this.attachStderr = attachStderr; + return this; + } + + public ExecCreateCmd withCmd(String... cmd) { + this.cmd = cmd; + return this; + } + + @Override + public String getContainerId() { + return containerId; + } + + /** + * @throws NotFoundException No such container + */ + @Override + public ExecCreateCmdResponce exec() throws NotFoundException { + return super.exec(); + } +} diff --git a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java new file mode 100644 index 00000000..edc16362 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java @@ -0,0 +1,49 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.ExecStartCmd; +import com.google.common.base.Preconditions; + +import java.io.InputStream; + +public class ExecStartCmdImpl extends AbstrDockerCmd implements ExecStartCmd { + + private String containerId; + + private boolean detach, tty; + + public ExecStartCmdImpl(ExecStartCmd.Exec exec, String containerId) { + super(exec); + withContainerId(containerId); + } + + @Override + public String getContainerId() { + return containerId; + } + + @Override + public boolean isDetach() { + return detach; + } + + @Override + public boolean isTty() { + return tty; + } + + @Override + public ExecStartCmdImpl withContainerId(String containerId) { + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + return this; + } + + /** + * @throws com.github.dockerjava.api.NotFoundException No such container + */ + @Override + public InputStream exec() throws NotFoundException { + return super.exec(); + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 64222a97..525e4a58 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -3,15 +3,12 @@ import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.github.dockerjava.api.DockerClientException; import com.github.dockerjava.api.command.*; -import com.github.dockerjava.core.CertificateUtils; import com.github.dockerjava.core.DockerClientConfig; import com.github.dockerjava.jaxrs.util.JsonClientFilter; import com.github.dockerjava.jaxrs.util.ResponseStatusExceptionFilter; import com.github.dockerjava.jaxrs.util.SelectiveLoggingFilter; import com.google.common.base.Preconditions; -import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.glassfish.jersey.CommonProperties; -import org.glassfish.jersey.SslConfigurator; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; @@ -20,8 +17,6 @@ import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import java.io.IOException; -import java.security.KeyStore; -import java.security.Security; import java.util.logging.Logger; public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { @@ -154,6 +149,11 @@ public InspectContainerCmd.Exec createInspectContainerCmdExec() { return new InspectContainerCmdExec(getBaseResource()); } + @Override + public ExecCreateCmd.Exec createExecCmdExec() { + return new ExecCreateCmdExec(getBaseResource()); + } + @Override public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { return new RemoveContainerCmdExec(getBaseResource()); @@ -169,6 +169,11 @@ public AttachContainerCmd.Exec createAttachContainerCmdExec() { return new AttachContainerCmdExec(getBaseResource()); } + @Override + public ExecStartCmd.Exec createExecStartCmdExec() { + return new ExecStartCmdExec(getBaseResource()); + } + @Override public LogContainerCmd.Exec createLogContainerCmdExec() { return new LogContainerCmdExec(getBaseResource()); diff --git a/src/main/java/com/github/dockerjava/jaxrs/ExecCreateCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ExecCreateCmdExec.java new file mode 100644 index 00000000..a424e7ca --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/ExecCreateCmdExec.java @@ -0,0 +1,30 @@ +package com.github.dockerjava.jaxrs; + +import com.github.dockerjava.api.command.ExecCreateCmd; +import com.github.dockerjava.api.command.ExecCreateCmdResponce; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import static javax.ws.rs.client.Entity.entity; + +public class ExecCreateCmdExec extends AbstrDockerCmdExec implements ExecCreateCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(VersionCmdExec.class); + + public ExecCreateCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + protected ExecCreateCmdResponce execute(ExecCreateCmd command) { + WebTarget webResource = getBaseResource().path("/containers/{id}/exec").resolveTemplate("id", command.getContainerId()); + + LOGGER.trace("POST: {}", webResource); + + return webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command, MediaType.APPLICATION_JSON), ExecCreateCmdResponce.class); + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java new file mode 100644 index 00000000..d5f7c478 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java @@ -0,0 +1,31 @@ +package com.github.dockerjava.jaxrs; + +import com.github.dockerjava.api.command.ExecStartCmd; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.InputStream; + +import static javax.ws.rs.client.Entity.entity; + +public class ExecStartCmdExec extends AbstrDockerCmdExec implements ExecStartCmd.Exec { + + private static final Logger LOGGER = LoggerFactory.getLogger(ExecStartCmdExec.class); + + public ExecStartCmdExec(WebTarget baseResource) { + super(baseResource); + } + + + @Override + protected InputStream execute(ExecStartCmd command) { + WebTarget webResource = getBaseResource().path("/exec/{id}/start").resolveTemplate("id", command.getContainerId()); + + LOGGER.trace("POST: {}", webResource); + + return webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java index 8a2c09a4..0e7697e4 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java @@ -20,8 +20,7 @@ public StartContainerCmdExec(WebTarget baseResource) { @Override protected Void execute(StartContainerCmd command) { - WebTarget webResource = getBaseResource().path("/containers/{id}/start") - .resolveTemplate("id", command.getContainerId()); + WebTarget webResource = getBaseResource().path("/containers/{id}/start").resolveTemplate("id", command.getContainerId()); LOGGER.trace("POST: {}", webResource); webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command, MediaType.APPLICATION_JSON)); diff --git a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java index 3a5857c9..c63667a0 100644 --- a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java +++ b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java @@ -6,41 +6,8 @@ import java.util.ArrayList; import java.util.List; -import com.github.dockerjava.api.command.AttachContainerCmd; +import com.github.dockerjava.api.command.*; import com.github.dockerjava.api.command.AuthCmd.Exec; -import com.github.dockerjava.api.command.BuildImageCmd; -import com.github.dockerjava.api.command.CommitCmd; -import com.github.dockerjava.api.command.ContainerDiffCmd; -import com.github.dockerjava.api.command.CopyFileFromContainerCmd; -import com.github.dockerjava.api.command.CreateContainerCmd; -import com.github.dockerjava.api.command.CreateContainerResponse; -import com.github.dockerjava.api.command.CreateImageCmd; -import com.github.dockerjava.api.command.CreateImageResponse; -import com.github.dockerjava.api.command.DockerCmdExecFactory; -import com.github.dockerjava.api.command.EventsCmd; -import com.github.dockerjava.api.command.InfoCmd; -import com.github.dockerjava.api.command.InspectContainerCmd; -import com.github.dockerjava.api.command.InspectImageCmd; -import com.github.dockerjava.api.command.KillContainerCmd; -import com.github.dockerjava.api.command.ListContainersCmd; -import com.github.dockerjava.api.command.ListImagesCmd; -import com.github.dockerjava.api.command.LogContainerCmd; -import com.github.dockerjava.api.command.PauseContainerCmd; -import com.github.dockerjava.api.command.PingCmd; -import com.github.dockerjava.api.command.PullImageCmd; -import com.github.dockerjava.api.command.PushImageCmd; -import com.github.dockerjava.api.command.RemoveContainerCmd; -import com.github.dockerjava.api.command.RemoveImageCmd; -import com.github.dockerjava.api.command.RestartContainerCmd; -import com.github.dockerjava.api.command.SearchImagesCmd; -import com.github.dockerjava.api.command.StartContainerCmd; -import com.github.dockerjava.api.command.StopContainerCmd; -import com.github.dockerjava.api.command.TagImageCmd; -import com.github.dockerjava.api.command.TopContainerCmd; -import com.github.dockerjava.api.command.UnpauseContainerCmd; -import com.github.dockerjava.api.command.VersionCmd; -import com.github.dockerjava.api.command.WaitContainerCmd; -import com.github.dockerjava.core.DockerClientConfig; /** * Special {@link DockerCmdExecFactory} implementation that collects container and image creations @@ -154,7 +121,12 @@ public PingCmd.Exec createPingCmdExec() { return delegate.createPingCmdExec(); } - @Override + @Override + public ExecCreateCmd.Exec createExecCmdExec() { + return delegate.createExecCmdExec(); + } + + @Override public VersionCmd.Exec createVersionCmdExec() { return delegate.createVersionCmdExec(); } @@ -209,7 +181,12 @@ public AttachContainerCmd.Exec createAttachContainerCmdExec() { return delegate.createAttachContainerCmdExec(); } - @Override + @Override + public ExecStartCmd.Exec createExecStartCmdExec() { + return delegate.createExecStartCmdExec(); + } + + @Override public LogContainerCmd.Exec createLogContainerCmdExec() { return delegate.createLogContainerCmdExec(); } diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index de744b59..10b656e6 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -200,7 +200,7 @@ public void startContainerWithPortBindings() throws DockerException { dockerClient.startContainerCmd(container.getId()).withPortBindings(portBindings).exec(); inspectContainerResponse = dockerClient.inspectContainerCmd(container - .getId()).exec(); + .getId()).exec(); assertThat(Arrays.asList(inspectContainerResponse.getConfig().getExposedPorts()), contains(tcp22, tcp23)); From e8d9896a2f54fa5758fdcae7af54baf553dcef89 Mon Sep 17 00:00:00 2001 From: Andrey Klimachev Date: Sat, 10 Jan 2015 11:10:56 +0000 Subject: [PATCH 258/452] Adding tests for Exec-start and Exec-create. --- .../github/dockerjava/api/DockerClient.java | 2 +- .../dockerjava/api/command/ExecCreateCmd.java | 4 +- ...sponce.java => ExecCreateCmdResponse.java} | 2 +- .../dockerjava/api/command/ExecStartCmd.java | 2 - .../dockerjava/core/DockerClientImpl.java | 2 +- .../core/command/ExecCreateCmdImpl.java | 6 +- .../core/command/ExecStartCmdImpl.java | 12 +--- .../dockerjava/jaxrs/ExecCreateCmdExec.java | 8 +-- .../core/command/ExecCreateCmdImplTest.java | 59 ++++++++++++++++++ .../core/command/ExecStartCmdImplTest.java | 62 +++++++++++++++++++ 10 files changed, 136 insertions(+), 23 deletions(-) rename src/main/java/com/github/dockerjava/api/command/{ExecCreateCmdResponce.java => ExecCreateCmdResponse.java} (89%) create mode 100644 src/test/java/com/github/dockerjava/core/command/ExecCreateCmdImplTest.java create mode 100644 src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index 2c829679..53b21260 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -64,7 +64,7 @@ public CreateImageCmd createImageCmd(String repository, */ public StartContainerCmd startContainerCmd(String containerId); - public ExecCreateCmd execCmd(String containerId); + public ExecCreateCmd execCreateCmd(String containerId); public InspectContainerCmd inspectContainerCmd(String containerId); diff --git a/src/main/java/com/github/dockerjava/api/command/ExecCreateCmd.java b/src/main/java/com/github/dockerjava/api/command/ExecCreateCmd.java index e6146b5f..e71fb04e 100644 --- a/src/main/java/com/github/dockerjava/api/command/ExecCreateCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/ExecCreateCmd.java @@ -1,6 +1,6 @@ package com.github.dockerjava.api.command; -public interface ExecCreateCmd extends DockerCmd { +public interface ExecCreateCmd extends DockerCmd { public String getContainerId(); @@ -14,6 +14,6 @@ public interface ExecCreateCmd extends DockerCmd { public ExecCreateCmd tty(boolean tty); - public static interface Exec extends DockerCmdExec { + public static interface Exec extends DockerCmdExec { } } diff --git a/src/main/java/com/github/dockerjava/api/command/ExecCreateCmdResponce.java b/src/main/java/com/github/dockerjava/api/command/ExecCreateCmdResponse.java similarity index 89% rename from src/main/java/com/github/dockerjava/api/command/ExecCreateCmdResponce.java rename to src/main/java/com/github/dockerjava/api/command/ExecCreateCmdResponse.java index 57197ca8..391625cf 100644 --- a/src/main/java/com/github/dockerjava/api/command/ExecCreateCmdResponce.java +++ b/src/main/java/com/github/dockerjava/api/command/ExecCreateCmdResponse.java @@ -4,7 +4,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) -public class ExecCreateCmdResponce { +public class ExecCreateCmdResponse { @JsonProperty("Id") private String id; diff --git a/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java b/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java index 262dc0f4..8f6fff7b 100644 --- a/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java @@ -12,8 +12,6 @@ public interface ExecStartCmd extends DockerCmd{ public boolean isTty(); - public ExecStartCmd withContainerId(String containerId); - /** * @throws com.github.dockerjava.api.NotFoundException No such container */ diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index ba5c08bc..1a06c2d5 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -194,7 +194,7 @@ public InspectContainerCmd inspectContainerCmd(String containerId) { } @Override - public ExecCreateCmd execCmd(String containerId) { + public ExecCreateCmd execCreateCmd(String containerId) { return new ExecCreateCmdImpl(getDockerCmdExecFactory().createExecCmdExec(), containerId); } diff --git a/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java index 315980a3..22ff6394 100644 --- a/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java @@ -3,9 +3,9 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.ExecCreateCmd; -import com.github.dockerjava.api.command.ExecCreateCmdResponce; +import com.github.dockerjava.api.command.ExecCreateCmdResponse; -public class ExecCreateCmdImpl extends AbstrDockerCmd implements ExecCreateCmd { +public class ExecCreateCmdImpl extends AbstrDockerCmd implements ExecCreateCmd { private String containerId; @@ -63,7 +63,7 @@ public String getContainerId() { * @throws NotFoundException No such container */ @Override - public ExecCreateCmdResponce exec() throws NotFoundException { + public ExecCreateCmdResponse exec() throws NotFoundException { return super.exec(); } } diff --git a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java index edc16362..b3c37dc5 100644 --- a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java @@ -6,7 +6,7 @@ import java.io.InputStream; -public class ExecStartCmdImpl extends AbstrDockerCmd implements ExecStartCmd { +public class ExecStartCmdImpl extends AbstrDockerCmd implements ExecStartCmd { private String containerId; @@ -14,7 +14,8 @@ public class ExecStartCmdImpl extends AbstrDockerCmd public ExecStartCmdImpl(ExecStartCmd.Exec exec, String containerId) { super(exec); - withContainerId(containerId); + Preconditions.checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; } @Override @@ -32,13 +33,6 @@ public boolean isTty() { return tty; } - @Override - public ExecStartCmdImpl withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); - this.containerId = containerId; - return this; - } - /** * @throws com.github.dockerjava.api.NotFoundException No such container */ diff --git a/src/main/java/com/github/dockerjava/jaxrs/ExecCreateCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ExecCreateCmdExec.java index a424e7ca..69346efd 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ExecCreateCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ExecCreateCmdExec.java @@ -1,7 +1,7 @@ package com.github.dockerjava.jaxrs; import com.github.dockerjava.api.command.ExecCreateCmd; -import com.github.dockerjava.api.command.ExecCreateCmdResponce; +import com.github.dockerjava.api.command.ExecCreateCmdResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -10,7 +10,7 @@ import static javax.ws.rs.client.Entity.entity; -public class ExecCreateCmdExec extends AbstrDockerCmdExec implements ExecCreateCmd.Exec { +public class ExecCreateCmdExec extends AbstrDockerCmdExec implements ExecCreateCmd.Exec { private static final Logger LOGGER = LoggerFactory .getLogger(VersionCmdExec.class); @@ -20,11 +20,11 @@ public ExecCreateCmdExec(WebTarget baseResource) { } @Override - protected ExecCreateCmdResponce execute(ExecCreateCmd command) { + protected ExecCreateCmdResponse execute(ExecCreateCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/exec").resolveTemplate("id", command.getContainerId()); LOGGER.trace("POST: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command, MediaType.APPLICATION_JSON), ExecCreateCmdResponce.class); + return webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command, MediaType.APPLICATION_JSON), ExecCreateCmdResponse.class); } } diff --git a/src/test/java/com/github/dockerjava/core/command/ExecCreateCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ExecCreateCmdImplTest.java new file mode 100644 index 00000000..75751710 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/command/ExecCreateCmdImplTest.java @@ -0,0 +1,59 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.ExecCreateCmdResponse; +import com.github.dockerjava.client.AbstractDockerClientTest; +import org.testng.ITestResult; +import org.testng.annotations.*; + +import java.lang.reflect.Method; +import java.security.SecureRandom; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; + +@Test(groups = "integration") +public class ExecCreateCmdImplTest 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 execCreateTest() { + String containerName = "generated_" + new SecureRandom().nextInt(); + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("env") + .withName(containerName).exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + dockerClient.startContainerCmd(container.getId()).exec(); + + dockerClient.waitContainerCmd(container.getId()).exec(); + + ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()).withCmd("touch file.log").exec(); + + assertThat(execCreateCmdResponse.getId(), not(isEmptyString())); + } +} diff --git a/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java new file mode 100644 index 00000000..4b9ab881 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java @@ -0,0 +1,62 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.ExecCreateCmdResponse; +import com.github.dockerjava.client.AbstractDockerClientTest; +import org.testng.ITestResult; +import org.testng.annotations.*; + +import java.io.InputStream; +import java.lang.reflect.Method; +import java.security.SecureRandom; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; + +public class ExecStartCmdImplTest 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 execStartTest() throws Exception { + String containerName = "generated_" + new SecureRandom().nextInt(); + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("env") + .withName(containerName).exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + dockerClient.startContainerCmd(container.getId()).exec(); + + dockerClient.waitContainerCmd(container.getId()).exec(); + + ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()).withCmd("touch","file.log").exec(); + + dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(); + + InputStream response = dockerClient.copyFileFromContainerCmd(container.getId(), "file.log").exec(); + assertTrue(response.available() > 0, "The file was not copied from the container."); + } +} From 5a6c46d297bc5a0c04b70893a44dd64904548fdb Mon Sep 17 00:00:00 2001 From: Andrey Klimachev Date: Sat, 10 Jan 2015 11:56:11 +0000 Subject: [PATCH 259/452] Fixing tests for Exec-start and Exec-create. --- .../dockerjava/core/command/ExecCreateCmdImplTest.java | 6 ++---- .../dockerjava/core/command/ExecStartCmdImplTest.java | 10 ++++------ 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/ExecCreateCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ExecCreateCmdImplTest.java index 75751710..338763e6 100644 --- a/src/test/java/com/github/dockerjava/core/command/ExecCreateCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ExecCreateCmdImplTest.java @@ -41,7 +41,7 @@ public void execCreateTest() { String containerName = "generated_" + new SecureRandom().nextInt(); CreateContainerResponse container = dockerClient - .createContainerCmd("busybox").withCmd("env") + .createContainerCmd("busybox").withCmd("top") .withName(containerName).exec(); LOG.info("Created container {}", container.toString()); @@ -50,9 +50,7 @@ public void execCreateTest() { dockerClient.startContainerCmd(container.getId()).exec(); - dockerClient.waitContainerCmd(container.getId()).exec(); - - ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()).withCmd("touch file.log").exec(); + ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()).withCmd("touch","file.log").exec(); assertThat(execCreateCmdResponse.getId(), not(isEmptyString())); } diff --git a/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java index 4b9ab881..044d1345 100644 --- a/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java @@ -15,6 +15,7 @@ import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; +@Test(groups = "integration") public class ExecStartCmdImplTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { @@ -41,7 +42,7 @@ public void execStartTest() throws Exception { String containerName = "generated_" + new SecureRandom().nextInt(); CreateContainerResponse container = dockerClient - .createContainerCmd("busybox").withCmd("env") + .createContainerCmd("busybox").withCmd("top") .withName(containerName).exec(); LOG.info("Created container {}", container.toString()); @@ -50,13 +51,10 @@ public void execStartTest() throws Exception { dockerClient.startContainerCmd(container.getId()).exec(); - dockerClient.waitContainerCmd(container.getId()).exec(); - - ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()).withCmd("touch","file.log").exec(); - + ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()).attachStdout(true).withCmd("touch","file.log").exec(); dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(); - InputStream response = dockerClient.copyFileFromContainerCmd(container.getId(), "file.log").exec(); + InputStream response = dockerClient.copyFileFromContainerCmd(container.getId(), "/file.log").exec(); assertTrue(response.available() > 0, "The file was not copied from the container."); } } From c6507bd47bdbe8ec37fd3821f0f20a43e78f672e Mon Sep 17 00:00:00 2001 From: Stephan Classen Date: Mon, 12 Jan 2015 00:28:17 +0100 Subject: [PATCH 260/452] support DOCKER_TLS_VERIFY to detect ssl --- README.md | 6 ++-- .../dockerjava/core/DockerClientConfig.java | 3 +- .../core/DockerClientConfigTest.java | 34 ++++++++++++++++++- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7380f1db..ec3a92a4 100644 --- a/README.md +++ b/README.md @@ -122,10 +122,10 @@ In your application, e.g. ##### System Environment export DOCKER_URL=http://localhost:2376 - -Note: we also auto-detect defaults. If you use `DOCKER_HOST` we use that value, and if `DOCKER_CERT_PATH` is set, we switch to SSL. -##### File System +Note: we also auto-detect defaults. If you use `DOCKER_HOST` we use that value, and if `DOCKER_CERT_PATH` or `DOCKER_TLS_VERIFY=1` is set, we switch to SSL. + +##### File System In `$HOME/.docker.io.properties` diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 8506d437..c90c62cb 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -21,6 +21,7 @@ public class DockerClientConfig implements Serializable { private static final String DOCKER_HOST_PROPERTY = "DOCKER_HOST"; private static final String DOCKER_CERT_PATH_PROPERTY = "DOCKER_CERT_PATH"; + private static final String DOCKER_VERIFY_TLS_PROPERTY = "DOCKER_TLS_VERIFY"; private static final String DOCKER_IO_URL_PROPERTY = "docker.io.url"; private static final String DOCKER_IO_VERSION_PROPERTY = "docker.io.version"; private static final String DOCKER_IO_USERNAME_PROPERTY = "docker.io.username"; @@ -142,7 +143,7 @@ private static Properties overrideDockerPropertiesWithEnv(Properties properties, private static String protocol(Map env) { // if this is set, we assume we need SSL - return env.containsKey(DOCKER_CERT_PATH_PROPERTY) ? "https" : "http"; + return env.containsKey(DOCKER_CERT_PATH_PROPERTY) || "1".equals(env.get(DOCKER_VERIFY_TLS_PROPERTY)) ? "https" : "http"; } /** diff --git a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java index 7b5e4e1f..e452e300 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java @@ -45,7 +45,7 @@ public void environmentDockerHost() throws Exception { } @Test - public void environmentDockerHostHttpsAutoDetect() throws Exception { + public void environmentDockerHostHttpsAutoDetectByCertPath() throws Exception { // given docker host in env Map env = new HashMap(System.getenv()); @@ -60,6 +60,38 @@ public void environmentDockerHostHttpsAutoDetect() throws Exception { assertEquals(config.getUri(), URI.create("https://bar:8768")); } + @Test + public void environmentDockerHostHttpsAutoDetectByTlsVerify() throws Exception { + + // given docker host in env + Map env = new HashMap(System.getenv()); + env.put("DOCKER_HOST", "tcp://bar:8768"); + // and it looks to be SSL enabled + env.put("DOCKER_TLS_VERIFY", "1"); + + // when you build a config + DockerClientConfig config = buildConfig(env, new Properties()); + + // then the URL is that value with "tcp" changed to "https" + assertEquals(config.getUri(), URI.create("https://bar:8768")); + } + + @Test + public void environmentDockerHostWithInvalidTlsVerify() throws Exception { + + // given docker host in env + Map env = new HashMap(System.getenv()); + env.put("DOCKER_HOST", "tcp://bar:8768"); + // and it looks to be SSL enabled + env.put("DOCKER_TLS_VERIFY", "any value different from '1'"); + + // when you build a config + DockerClientConfig config = buildConfig(env, new Properties()); + + // then the URL is that value with "tcp" changed to "https" + assertEquals(config.getUri(), URI.create("http://bar:8768")); + } + @Test public void environment() throws Exception { From 26cd47c01ef57a4ee903c07cc13890c4b640bf5e Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 12 Jan 2015 21:09:53 +0100 Subject: [PATCH 261/452] Polish exec create and start commands --- .../api/command/AttachContainerCmd.java | 2 + .../dockerjava/api/command/ExecCreateCmd.java | 32 +++++++--- .../dockerjava/api/command/ExecStartCmd.java | 33 +++++++---- .../core/command/AttachContainerCmdImpl.java | 5 ++ .../core/command/ExecCreateCmdImpl.java | 59 ++++++++++++++++--- .../core/command/ExecStartCmdImpl.java | 44 +++++++++++--- .../dockerjava/jaxrs/ExecStartCmdExec.java | 2 +- .../core/command/ExecStartCmdImplTest.java | 2 +- 8 files changed, 146 insertions(+), 33 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java index 8abbef72..aeee749e 100644 --- a/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java @@ -51,6 +51,8 @@ public interface AttachContainerCmd extends DockerCmd{ public AttachContainerCmd withStdErr(boolean stderr); public AttachContainerCmd withLogs(boolean logs); + + public AttachContainerCmd withLogs(); /** * @throws NotFoundException No such container diff --git a/src/main/java/com/github/dockerjava/api/command/ExecCreateCmd.java b/src/main/java/com/github/dockerjava/api/command/ExecCreateCmd.java index e71fb04e..c1f32e29 100644 --- a/src/main/java/com/github/dockerjava/api/command/ExecCreateCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/ExecCreateCmd.java @@ -3,16 +3,34 @@ public interface ExecCreateCmd extends DockerCmd { public String getContainerId(); + + public ExecCreateCmd withContainerId(String containerId); public ExecCreateCmd withCmd(String... cmd); - public ExecCreateCmd attachStdin(boolean attachStdin); - - public ExecCreateCmd attachStdout(boolean attachStdout); - - public ExecCreateCmd attachStderr(boolean attachStderr); - - public ExecCreateCmd tty(boolean tty); + public ExecCreateCmd withAttachStdin(boolean attachStdin); + + public ExecCreateCmd withAttachStdin(); + + public boolean hasAttachStdinEnabled(); + + public ExecCreateCmd withAttachStdout(boolean attachStdout); + + public ExecCreateCmd withAttachStdout(); + + public boolean hasAttachStdoutEnabled(); + + public ExecCreateCmd withAttachStderr(boolean attachStderr); + + public ExecCreateCmd withAttachStderr(); + + public boolean hasAttachStderrEnabled(); + + public ExecCreateCmd withTty(boolean tty); + + public ExecCreateCmd withTty(); + + public boolean hasTtyEnabled(); public static interface Exec extends DockerCmdExec { } diff --git a/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java b/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java index 8f6fff7b..bcc7a072 100644 --- a/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java @@ -4,19 +4,32 @@ import java.io.InputStream; -public interface ExecStartCmd extends DockerCmd{ +public interface ExecStartCmd extends DockerCmd { - public String getContainerId(); + public String getExecId(); - public boolean isDetach(); + public ExecStartCmd withExecId(String execId); - public boolean isTty(); + public boolean hasDetachEnabled(); - /** - * @throws com.github.dockerjava.api.NotFoundException No such container - */ - @Override - public InputStream exec() throws NotFoundException; + public ExecStartCmd withDetach(boolean detach); + + public ExecStartCmd withDetach(); - public static interface Exec extends DockerCmdExec {} + public boolean hasTtyEnabled(); + + public ExecStartCmd withTty(boolean tty); + + public ExecStartCmd withTty(); + + /** + * @throws com.github.dockerjava.api.NotFoundException + * No such exec instance + */ + @Override + public InputStream exec() throws NotFoundException; + + public static interface Exec extends + DockerCmdExec { + } } diff --git a/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java index d52ceabe..930fbdfd 100644 --- a/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java @@ -116,6 +116,11 @@ public AttachContainerCmd withLogs(boolean logs) { return this; } + @Override + public AttachContainerCmd withLogs() { + return withLogs(true); + } + /** * @throws NotFoundException No such container */ diff --git a/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java index 22ff6394..5b76941c 100644 --- a/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java @@ -4,6 +4,7 @@ import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.ExecCreateCmd; import com.github.dockerjava.api.command.ExecCreateCmdResponse; +import com.google.common.base.Preconditions; public class ExecCreateCmdImpl extends AbstrDockerCmd implements ExecCreateCmd { @@ -26,28 +27,50 @@ public class ExecCreateCmdImpl extends AbstrDockerCmd implements ExecStartCmd { - private String containerId; + private String execId; private boolean detach, tty; public ExecStartCmdImpl(ExecStartCmd.Exec exec, String containerId) { super(exec); Preconditions.checkNotNull(containerId, "containerId was not specified"); - this.containerId = containerId; + this.execId = containerId; } @Override - public String getContainerId() { - return containerId; + public String getExecId() { + return execId; } + + @Override + public ExecStartCmd withExecId(String execId) { + Preconditions.checkNotNull(execId, "execId was not specified"); + this.execId = execId; + return this; + } @Override - public boolean isDetach() { + public boolean hasDetachEnabled() { return detach; } @Override - public boolean isTty() { + public boolean hasTtyEnabled() { return tty; } + @Override + public ExecStartCmd withDetach(boolean detach) { + this.detach = detach; + return this; + } + + @Override + public ExecStartCmd withTty(boolean tty) { + this.tty = tty; + return null; + } + + @Override + public ExecStartCmd withDetach() { + return withDetach(true); + } + + @Override + public ExecStartCmd withTty() { + return withTty(true); + } + /** - * @throws com.github.dockerjava.api.NotFoundException No such container + * @throws com.github.dockerjava.api.NotFoundException No such exec instance */ @Override public InputStream exec() throws NotFoundException { return super.exec(); } + } diff --git a/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java index d5f7c478..ae4c7181 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java @@ -22,7 +22,7 @@ public ExecStartCmdExec(WebTarget baseResource) { @Override protected InputStream execute(ExecStartCmd command) { - WebTarget webResource = getBaseResource().path("/exec/{id}/start").resolveTemplate("id", command.getContainerId()); + WebTarget webResource = getBaseResource().path("/exec/{id}/start").resolveTemplate("id", command.getExecId()); LOGGER.trace("POST: {}", webResource); diff --git a/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java index 044d1345..a8c3fe8a 100644 --- a/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java @@ -51,7 +51,7 @@ public void execStartTest() throws Exception { dockerClient.startContainerCmd(container.getId()).exec(); - ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()).attachStdout(true).withCmd("touch","file.log").exec(); + ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()).withAttachStdout(true).withCmd("touch","file.log").exec(); dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(); InputStream response = dockerClient.copyFileFromContainerCmd(container.getId(), "/file.log").exec(); From 2561436cc70439ef992a1ab25bd4cccafb93626b Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 12 Jan 2015 22:36:55 +0100 Subject: [PATCH 262/452] Fix issue##122 --- .../java/com/github/dockerjava/api/model/ExposedPorts.java | 4 ++++ src/main/java/com/github/dockerjava/api/model/Volumes.java | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/src/main/java/com/github/dockerjava/api/model/ExposedPorts.java b/src/main/java/com/github/dockerjava/api/model/ExposedPorts.java index 924d1300..983ad3c3 100644 --- a/src/main/java/com/github/dockerjava/api/model/ExposedPorts.java +++ b/src/main/java/com/github/dockerjava/api/model/ExposedPorts.java @@ -29,6 +29,10 @@ public class ExposedPorts { public ExposedPorts(ExposedPort... exposedPorts) { this.exposedPorts = exposedPorts; } + + public ExposedPorts(List exposedPorts) { + this.exposedPorts = exposedPorts.toArray(new ExposedPort[exposedPorts.size()]); + } public ExposedPort[] getExposedPorts() { return exposedPorts; diff --git a/src/main/java/com/github/dockerjava/api/model/Volumes.java b/src/main/java/com/github/dockerjava/api/model/Volumes.java index d06c0c0f..b8a9315b 100644 --- a/src/main/java/com/github/dockerjava/api/model/Volumes.java +++ b/src/main/java/com/github/dockerjava/api/model/Volumes.java @@ -29,6 +29,10 @@ public class Volumes { public Volumes(Volume... volumes) { this.volumes = volumes; } + + public Volumes(List volumes) { + this.volumes = volumes.toArray(new Volume[volumes.size()]); + } public Volume[] getVolumes() { return volumes; From c0c44ee313ec827fbf33dd53d25a66a0629c3935 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 14 Jan 2015 20:39:41 +0100 Subject: [PATCH 263/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fe22888..102e4a7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Change Log docker-java-0.10.5-SNAPSHOT --- + * [#121](https://github.com/docker-java/docker-java/pull/121) Implemented support for commands: Exec-start, Exec-create * [#120](https://github.com/docker-java/docker-java/pull/120) Command resource cleanup after command execution * [#118](https://github.com/docker-java/docker-java/pull/118) Use chunked encoding when passing the docker image * [#116](https://github.com/docker-java/docker-java/pull/116) Allow SSL configuration from pre-existing keystore to be used From 327e5d19188f978b78ece3ab313b9a25c338ea21 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 14 Jan 2015 20:53:50 +0100 Subject: [PATCH 264/452] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 102e4a7f..f225212d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ Change Log docker-java-0.10.5-SNAPSHOT --- - + * [#123](https://github.com/docker-java/docker-java/pull/123) support DOCKER_TLS_VERIFY to detect ssl * [#121](https://github.com/docker-java/docker-java/pull/121) Implemented support for commands: Exec-start, Exec-create * [#120](https://github.com/docker-java/docker-java/pull/120) Command resource cleanup after command execution * [#118](https://github.com/docker-java/docker-java/pull/118) Use chunked encoding when passing the docker image From 421a8731a43ababce1fe6ff5f42d8d16cbd25687 Mon Sep 17 00:00:00 2001 From: Andrey Klimachev Date: Thu, 15 Jan 2015 10:35:21 +0000 Subject: [PATCH 265/452] Fixed NPE on ExecStartCmdImpl. --- .../com/github/dockerjava/core/command/ExecStartCmdImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java index 6090172f..0340a7ac 100644 --- a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java @@ -49,7 +49,7 @@ public ExecStartCmd withDetach(boolean detach) { @Override public ExecStartCmd withTty(boolean tty) { this.tty = tty; - return null; + return this; } @Override From 04eaf1f518680b16b16cb33e80d24664f6846330 Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Fri, 16 Jan 2015 21:45:40 +0100 Subject: [PATCH 266/452] apply a rebased and squashed unixsocket-branch with a working ssl config. other changes: - make all unit tests succeed on Windows - only create a container when needed - read the complete response when copying a file from a container --- pom.xml | 19 + .../dockerjava/api/command/EventCallback.java | 1 + .../dockerjava/api/model/AuthConfig.java | 2 +- .../dockerjava/core/DockerClientConfig.java | 47 ++- .../dockerjava/core/DockerClientImpl.java | 5 +- .../core/LocalDirectorySSLConfig.java | 14 +- .../com/github/dockerjava/core/SSLConfig.java | 5 +- .../dockerjava/jaxrs/ApacheUnixSocket.java | 327 ++++++++++++++++++ .../jaxrs/ContainerDiffCmdExec.java | 3 +- .../jaxrs/DockerCmdExecFactoryImpl.java | 41 ++- .../dockerjava/jaxrs/EventsCmdExec.java | 2 +- .../jaxrs/RemoveContainerCmdExec.java | 4 +- .../dockerjava/jaxrs/RemoveImageCmdExec.java | 2 +- .../jaxrs/UnixConnectionSocketFactory.java | 85 +++++ .../util/ResponseStatusExceptionFilter.java | 5 +- .../client/AbstractDockerClientTest.java | 6 +- .../core/DockerClientConfigTest.java | 4 +- .../dockerjava/core/DockerClientImplTest.java | 2 +- .../dockerjava/core/GoLangFileMatchTest.java | 3 +- .../CopyFileFromContainerCmdImplTest.java | 22 +- .../core/command/EventsCmdImplTest.java | 17 +- .../core/command/ExecStartCmdImplTest.java | 19 +- .../core/command/InfoCmdImplTest.java | 6 +- .../core/command/PullImageCmdImplTest.java | 4 +- .../core/command/PushImageCmdImplTest.java | 1 - 25 files changed, 581 insertions(+), 65 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/jaxrs/ApacheUnixSocket.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/UnixConnectionSocketFactory.java diff --git a/pom.xml b/pom.xml index 0b85dc42..1e6a477e 100644 --- a/pom.xml +++ b/pom.xml @@ -39,6 +39,13 @@
+ + + jcenter + http://jcenter.bintray.com + + + UTF-8 UTF-8 @@ -64,6 +71,7 @@ 0.3 18.0 1.51 + 2014-11-16T14-41-27 1.0.1 @@ -93,12 +101,23 @@ + + org.glassfish.jersey.connectors + jersey-apache-connector + ${jersey.version} + org.glassfish.jersey.core jersey-client ${jersey.version} + + de.gesellix + unix-socket-factory + ${unix-socket-factory.version} + + org.apache.commons commons-compress diff --git a/src/main/java/com/github/dockerjava/api/command/EventCallback.java b/src/main/java/com/github/dockerjava/api/command/EventCallback.java index 45ac34dc..18b8669e 100644 --- a/src/main/java/com/github/dockerjava/api/command/EventCallback.java +++ b/src/main/java/com/github/dockerjava/api/command/EventCallback.java @@ -9,4 +9,5 @@ public interface EventCallback { public void onEvent(Event event); public void onException(Throwable throwable); public void onCompletion(int numEvents); + public boolean isReceiving(); } diff --git a/src/main/java/com/github/dockerjava/api/model/AuthConfig.java b/src/main/java/com/github/dockerjava/api/model/AuthConfig.java index 87307bb5..42c49bce 100644 --- a/src/main/java/com/github/dockerjava/api/model/AuthConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/AuthConfig.java @@ -8,7 +8,7 @@ public class AuthConfig { /** * For backwards compatibility. Make sure you update the properties if you change this. * - * @see /docker.io.properties + * @see "/docker.io.properties" */ public static final String DEFAULT_SERVER_ADDRESS = "https://index.docker.io/v1/"; diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index c90c62cb..21e5778f 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -33,6 +33,9 @@ public class DockerClientConfig implements Serializable { private static final String DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY = "docker.io.enableLoggingFilter"; private static final String DOCKER_IO_DOCKER_CERT_PATH_PROPERTY = "docker.io.dockerCertPath"; private static final String DOCKER_IO_DOCKER_CFG_PATH_PROPERTY = "docker.io.dockerCfgPath"; + // connection pooling properties + private static final String DOCKER_IO_MAX_PER_ROUTE_PROPERTY = "docker.io.perRouteConnections"; + private static final String DOCKER_IO_MAX_TOTAL_PROPERTY = "docker.io.totalConnections"; /** * A map from the environment name to the interval name. */ @@ -49,13 +52,18 @@ public class DockerClientConfig implements Serializable { .put("DOCKER_CFG_PATH", DOCKER_IO_DOCKER_CFG_PATH_PROPERTY) .build(); private static final String DOCKER_IO_PROPERTIES_PROPERTY = "docker.io.properties"; - private final URI uri; + private URI uri; private final String version, username, password, email, serverAddress, dockerCfgPath; private final Integer readTimeout; private final boolean loggingFilterEnabled; private final SSLConfig sslConfig; + + private final int maxTotalConnections; + private final int maxPerRouteConnections; - DockerClientConfig(URI uri, String version, String username, String password, String email, String serverAddress, String dockerCfgPath, Integer readTimeout, boolean loggingFilterEnabled, SSLConfig sslConfig) { + DockerClientConfig(URI uri, String version, String username, String password, String email, String serverAddress, + String dockerCfgPath, Integer readTimeout, boolean loggingFilterEnabled, SSLConfig sslConfig, + int maxTotalConns, int maxPerRouteConns) { this.uri = uri; this.version = version; this.username = username; @@ -66,6 +74,8 @@ public class DockerClientConfig implements Serializable { this.readTimeout = readTimeout; this.loggingFilterEnabled = loggingFilterEnabled; this.sslConfig = sslConfig; + this.maxTotalConnections = maxTotalConns; + this.maxPerRouteConnections = maxPerRouteConns; } private static Properties loadIncludedDockerProperties(Properties systemProperties) { @@ -194,6 +204,10 @@ public URI getUri() { return uri; } + public void setUri(URI uri) { + this.uri = uri; + } + public String getVersion() { return version; } @@ -329,7 +343,7 @@ public String toString() { public static class DockerClientConfigBuilder { private URI uri; private String version, username, password, email, serverAddress, dockerCfgPath; - private Integer readTimeout; + private Integer readTimeout, maxTotalConnections, maxPerRouteConnections; private boolean loggingFilterEnabled; private SSLConfig sslConfig; @@ -349,7 +363,10 @@ public DockerClientConfigBuilder withProperties(Properties p) { .withReadTimeout(Integer.valueOf(p.getProperty(DOCKER_IO_READ_TIMEOUT_PROPERTY, "0"))) .withLoggingFilter(Boolean.valueOf(p.getProperty(DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY, "true"))) .withDockerCertPath(p.getProperty(DOCKER_IO_DOCKER_CERT_PATH_PROPERTY)) - .withDockerCfgPath(p.getProperty(DOCKER_IO_DOCKER_CFG_PATH_PROPERTY)); + .withDockerCfgPath(p.getProperty(DOCKER_IO_DOCKER_CFG_PATH_PROPERTY)) + .withMaxPerRouteConnections(Integer.valueOf(p.getProperty(DOCKER_IO_MAX_PER_ROUTE_PROPERTY, "2"))) + .withMaxTotalConnections(Integer.valueOf(p.getProperty(DOCKER_IO_MAX_TOTAL_PROPERTY, "20"))) + ; } public final DockerClientConfigBuilder withUri(String uri) { @@ -387,6 +404,16 @@ public final DockerClientConfigBuilder withReadTimeout(Integer readTimeout) { this.readTimeout = readTimeout; return this; } + + public final DockerClientConfigBuilder withMaxTotalConnections(Integer maxTotalConnections) { + this.maxTotalConnections = maxTotalConnections; + return this; + } + + public final DockerClientConfigBuilder withMaxPerRouteConnections(Integer maxPerRouteConnections) { + this.maxPerRouteConnections = maxPerRouteConnections; + return this; + } public final DockerClientConfigBuilder withLoggingFilter(boolean loggingFilterEnabled) { this.loggingFilterEnabled = loggingFilterEnabled; @@ -420,8 +447,18 @@ public DockerClientConfig build() { dockerCfgPath, readTimeout, loggingFilterEnabled, - sslConfig + sslConfig, + maxTotalConnections, + maxPerRouteConnections ); } } + + public int getMaxTotalConnections() { + return maxTotalConnections; + } + + public int getMaxPerRoutConnections() { + return maxPerRouteConnections; + } } diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index cee364e0..6b829abd 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -8,18 +8,15 @@ import java.io.InputStream; import com.github.dockerjava.api.DockerClient; -import com.github.dockerjava.api.DockerClientException; import com.github.dockerjava.api.command.*; import com.github.dockerjava.api.model.AuthConfig; -import com.github.dockerjava.core.NameParser.HostnameReposName; -import com.github.dockerjava.core.NameParser.ReposTag; import com.github.dockerjava.core.command.*; import com.google.common.base.Preconditions; /** * @author Konstantin Pelykh (kpelykh@gmail.com) * - * @see https://github.com/docker/docker/blob/master/api/client/commands.go + * @see "https://github.com/docker/docker/blob/master/api/client/commands.go" */ public class DockerClientImpl implements Closeable, DockerClient { diff --git a/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java b/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java index ef57a0de..6415d0c1 100644 --- a/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java +++ b/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java @@ -1,19 +1,16 @@ package com.github.dockerjava.core; +import com.github.dockerjava.api.DockerClientException; import com.google.common.base.Objects; import com.google.common.base.Preconditions; - -import com.github.dockerjava.api.DockerClientException; - import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.glassfish.jersey.SslConfigurator; +import javax.net.ssl.SSLContext; import java.io.Serializable; import java.security.KeyStore; import java.security.Security; -import javax.net.ssl.SSLContext; - /** * SSL Config from local files. */ @@ -41,9 +38,6 @@ public SSLContext getSSLContext() { Security.addProvider(new BouncyCastleProvider()); - KeyStore keyStore = CertificateUtils.createKeyStore(dockerCertPath); - KeyStore trustStore = CertificateUtils.createTrustStore(dockerCertPath); - // properties acrobatics not needed for java > 1.6 String httpProtocols = System.getProperty("https.protocols"); System.setProperty("https.protocols", "TLSv1"); @@ -52,9 +46,9 @@ public SSLContext getSSLContext() { System.setProperty("https.protocols", httpProtocols); } - sslConfig.keyStore(keyStore); + sslConfig.keyStore(CertificateUtils.createKeyStore(dockerCertPath)); sslConfig.keyStorePassword("docker"); - sslConfig.trustStore(trustStore); + sslConfig.trustStore(CertificateUtils.createTrustStore(dockerCertPath)); return sslConfig.createSSLContext(); diff --git a/src/main/java/com/github/dockerjava/core/SSLConfig.java b/src/main/java/com/github/dockerjava/core/SSLConfig.java index 21024c4f..ab639489 100644 --- a/src/main/java/com/github/dockerjava/core/SSLConfig.java +++ b/src/main/java/com/github/dockerjava/core/SSLConfig.java @@ -1,9 +1,6 @@ package com.github.dockerjava.core; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; +import java.security.*; import javax.net.ssl.SSLContext; diff --git a/src/main/java/com/github/dockerjava/jaxrs/ApacheUnixSocket.java b/src/main/java/com/github/dockerjava/jaxrs/ApacheUnixSocket.java new file mode 100644 index 00000000..a4adb1bb --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/ApacheUnixSocket.java @@ -0,0 +1,327 @@ +package com.github.dockerjava.jaxrs; +/* + * Copyright (c) 2014 Spotify AB. + * + * 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. + */ + + + +import com.google.common.collect.Queues; + +import org.newsclub.net.unix.AFUNIXSocket; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.SocketException; +import java.nio.channels.SocketChannel; +import java.util.Queue; + +/** + * Provides a socket that wraps an org.newsclub.net.unix.AFUNIXSocket and delays setting options + * until the socket is connected. This is necessary because the Apache HTTP client attempts to + * set options prior to connecting the socket, which doesn't work for Unix sockets since options + * are being set on the underlying file descriptor. Until the socket is connected, the file + * descriptor doesn't exist. + * + * This class also noop's any calls to setReuseAddress, which is called by the Apache client but + * isn't supported by AFUnixSocket. + */ +public class ApacheUnixSocket extends Socket { + + private final AFUNIXSocket inner; + + private final Queue optionsToSet = Queues.newArrayDeque(); + + public ApacheUnixSocket() throws IOException { + this.inner = AFUNIXSocket.newInstance(); + } + + @Override + public void connect(final SocketAddress endpoint) throws IOException { + inner.connect(endpoint); + setAllSocketOptions(); + } + + @Override + public void connect(final SocketAddress endpoint, final int timeout) throws IOException { + inner.connect(endpoint, timeout); + setAllSocketOptions(); + } + + @Override + public void bind(final SocketAddress bindpoint) throws IOException { + inner.bind(bindpoint); + setAllSocketOptions(); + } + + @Override + public InetAddress getInetAddress() { + return inner.getInetAddress(); + } + + @Override + public InetAddress getLocalAddress() { + return inner.getLocalAddress(); + } + + @Override + public int getPort() { + return inner.getPort(); + } + + @Override + public int getLocalPort() { + return inner.getLocalPort(); + } + + @Override + public SocketAddress getRemoteSocketAddress() { + return inner.getRemoteSocketAddress(); + } + + @Override + public SocketAddress getLocalSocketAddress() { + return inner.getLocalSocketAddress(); + } + + @Override + public SocketChannel getChannel() { + return inner.getChannel(); + } + + @Override + public InputStream getInputStream() throws IOException { + return inner.getInputStream(); + } + + @Override + public OutputStream getOutputStream() throws IOException { + return inner.getOutputStream(); + } + + private void setSocketOption(final SocketOptionSetter s) throws SocketException { + if (inner.isConnected()) { + s.run(); + } else { + if (!optionsToSet.offer(s)) { + throw new SocketException("Failed to queue option"); + } + } + } + + private void setAllSocketOptions() throws SocketException { + for (SocketOptionSetter s : optionsToSet) { + s.run(); + } + } + + @Override + public void setTcpNoDelay(final boolean on) throws SocketException { + setSocketOption(new SocketOptionSetter() { + @Override + public void run() throws SocketException { + inner.setTcpNoDelay(on); + } + }); + } + + @Override + public boolean getTcpNoDelay() throws SocketException { + return inner.getTcpNoDelay(); + } + + @Override + public void setSoLinger(final boolean on, final int linger) throws SocketException { + setSocketOption(new SocketOptionSetter() { + @Override + public void run() throws SocketException { + inner.setSoLinger(on, linger); + } + }); + } + + @Override + public int getSoLinger() throws SocketException { + return inner.getSoLinger(); + } + + @Override + public void sendUrgentData(final int data) throws IOException { + inner.sendUrgentData(data); + } + + @Override + public void setOOBInline(final boolean on) throws SocketException { + setSocketOption(new SocketOptionSetter() { + @Override + public void run() throws SocketException { + inner.setOOBInline(on); + } + }); + } + + @Override + public boolean getOOBInline() throws SocketException { + return inner.getOOBInline(); + } + + @Override + public synchronized void setSoTimeout(final int timeout) throws SocketException { + setSocketOption(new SocketOptionSetter() { + @Override + public void run() throws SocketException { + inner.setSoTimeout(timeout); + } + }); + } + + @Override + public synchronized int getSoTimeout() throws SocketException { + return inner.getSoTimeout(); + } + + @Override + public synchronized void setSendBufferSize(final int size) throws SocketException { + setSocketOption(new SocketOptionSetter() { + @Override + public void run() throws SocketException { + inner.setSendBufferSize(size); + } + }); + } + + @Override + public synchronized int getSendBufferSize() throws SocketException { + return inner.getSendBufferSize(); + } + + @Override + public synchronized void setReceiveBufferSize(final int size) throws SocketException { + setSocketOption(new SocketOptionSetter() { + @Override + public void run() throws SocketException { + inner.setReceiveBufferSize(size); + } + }); + } + + @Override + public synchronized int getReceiveBufferSize() throws SocketException { + return inner.getReceiveBufferSize(); + } + + @Override + public void setKeepAlive(final boolean on) throws SocketException { + setSocketOption(new SocketOptionSetter() { + @Override + public void run() throws SocketException { + inner.setKeepAlive(on); + } + }); + } + + @Override + public boolean getKeepAlive() throws SocketException { + return inner.getKeepAlive(); + } + + @Override + public void setTrafficClass(final int tc) throws SocketException { + setSocketOption(new SocketOptionSetter() { + @Override + public void run() throws SocketException { + inner.setTrafficClass(tc); + } + }); + } + + @Override + public int getTrafficClass() throws SocketException { + return inner.getTrafficClass(); + } + + @Override + public void setReuseAddress(final boolean on) throws SocketException { + // not supported: Apache client tries to set it, but we want to just ignore it + } + + @Override + public boolean getReuseAddress() throws SocketException { + return inner.getReuseAddress(); + } + + @Override + public synchronized void close() throws IOException { + inner.close(); + } + + @Override + public void shutdownInput() throws IOException { + inner.shutdownInput(); + } + + @Override + public void shutdownOutput() throws IOException { + inner.shutdownOutput(); + } + + @Override + public String toString() { + return inner.toString(); + } + + @Override + public boolean isConnected() { + return inner.isConnected(); + } + + @Override + public boolean isBound() { + return inner.isBound(); + } + + @Override + public boolean isClosed() { + return inner.isClosed(); + } + + @Override + public boolean isInputShutdown() { + return inner.isInputShutdown(); + } + + @Override + public boolean isOutputShutdown() { + return inner.isOutputShutdown(); + } + + @Override + public void setPerformancePreferences(final int connectionTime, final int latency, + final int bandwidth) { + inner.setPerformancePreferences(connectionTime, latency, bandwidth); + } + + interface SocketOptionSetter { + void run() throws SocketException; + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/ContainerDiffCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ContainerDiffCmdExec.java index 0a657ed9..2b7059b3 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ContainerDiffCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ContainerDiffCmdExec.java @@ -26,7 +26,8 @@ protected List execute(ContainerDiffCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/changes").resolveTemplate("id", command.getContainerId()); LOGGER.trace("GET: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType>() { + return webResource.request().accept(MediaType.APPLICATION_JSON) + .get(new GenericType>() { }); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 525e4a58..c91b0d56 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -8,7 +8,14 @@ import com.github.dockerjava.jaxrs.util.ResponseStatusExceptionFilter; import com.github.dockerjava.jaxrs.util.SelectiveLoggingFilter; import com.google.common.base.Preconditions; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.glassfish.jersey.CommonProperties; +import org.glassfish.jersey.apache.connector.ApacheClientProperties; +import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; @@ -17,6 +24,7 @@ import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import java.io.IOException; +import java.net.URI; import java.util.logging.Logger; public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { @@ -30,6 +38,7 @@ public void init(DockerClientConfig dockerClientConfig) { Preconditions.checkNotNull(dockerClientConfig, "config was not specified"); ClientConfig clientConfig = new ClientConfig(); + clientConfig.connectorProvider(new ApacheConnectorProvider()); clientConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); clientConfig.register(ResponseStatusExceptionFilter.class); @@ -45,20 +54,31 @@ public void init(DockerClientConfig dockerClientConfig) { clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); } - ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig); + URI originalUri = dockerClientConfig.getUri(); + SSLContext sslContext; try { - SSLContext ssl = dockerClientConfig.getSslConfig().getSSLContext(); - - if (ssl != null) - clientBuilder.sslContext(ssl); + sslContext = dockerClientConfig.getSslConfig().getSSLContext(); } catch(Exception ex) { throw new DockerClientException("Error in SSL Configuration", ex); } + PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(getSchemeRegistry(originalUri, sslContext)); + connManager.setMaxTotal(dockerClientConfig.getMaxTotalConnections()); + connManager.setDefaultMaxPerRoute(dockerClientConfig.getMaxPerRoutConnections()); + clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connManager); + + ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig); + + if (sslContext != null) { + clientBuilder.sslContext(sslContext); + } client = clientBuilder.build(); + if (originalUri.getScheme().equals("unix")) { + dockerClientConfig.setUri(UnixConnectionSocketFactory.sanitizeUri(originalUri)); + } WebTarget webResource = client.target(dockerClientConfig.getUri()); if (dockerClientConfig.getVersion() == null || dockerClientConfig.getVersion().isEmpty()) { @@ -66,9 +86,18 @@ public void init(DockerClientConfig dockerClientConfig) { } else { baseResource = webResource.path("v" + dockerClientConfig.getVersion()); } - } + private org.apache.http.config.Registry getSchemeRegistry(final URI originalUri, SSLContext sslContext) { + RegistryBuilder registryBuilder = RegistryBuilder.create(); + registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory()); + if (sslContext != null) { + registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext)); + } + registryBuilder.register("unix", new UnixConnectionSocketFactory(originalUri)); + return registryBuilder.build(); + } + protected WebTarget getBaseResource() { Preconditions.checkNotNull(baseResource, "Factory not initialized. You probably forgot to call init()!"); return baseResource; diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java index 545d7db9..ffd757e9 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -67,7 +67,7 @@ public Void call() throws Exception { response = webTarget.request().get(Response.class); InputStream inputStream = response.readEntity(InputStream.class); JsonParser jp = JSON_FACTORY.createParser(inputStream); - while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed()) { + while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed() && eventCallback.isReceiving()) { eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); numEvents++; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java index 7f45bdda..7a479ce2 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java @@ -23,8 +23,8 @@ protected Void execute(RemoveContainerCmd command) { .queryParam("force", command.hasForceEnabled() ? "1" : "0"); LOGGER.trace("DELETE: {}", webResource); - String response = webResource.request().accept(MediaType.APPLICATION_JSON).delete(String.class); - LOGGER.trace("Response: {}", response); + /*String response = */webResource.request().accept(MediaType.APPLICATION_JSON).delete().close(); +// LOGGER.trace("Response: {}", response); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java index 54fb327b..6bfeecd7 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java @@ -23,7 +23,7 @@ protected Void execute(RemoveImageCmd command) { .queryParam("noprune", command.hasNoPruneEnabled() ? "1" : "0"); LOGGER.trace("DELETE: {}", webResource); - webResource.request().delete(Response.class); + webResource.request().delete().close(); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/UnixConnectionSocketFactory.java b/src/main/java/com/github/dockerjava/jaxrs/UnixConnectionSocketFactory.java new file mode 100644 index 00000000..4b6cfbba --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/UnixConnectionSocketFactory.java @@ -0,0 +1,85 @@ +package com.github.dockerjava.jaxrs; +/* + * Copyright (c) 2014 Spotify AB. + * + * 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. + */ + + + +import org.apache.http.HttpHost; +import org.apache.http.annotation.Immutable; +import org.apache.http.conn.ConnectTimeoutException; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.protocol.HttpContext; +import org.newsclub.net.unix.AFUNIXSocketAddress; + +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketTimeoutException; +import java.net.URI; + +/** + * Provides a ConnectionSocketFactory for connecting Apache HTTP clients to Unix sockets. + */ +@Immutable +public class UnixConnectionSocketFactory implements ConnectionSocketFactory { + + private File socketFile; + + public UnixConnectionSocketFactory(final URI socketUri) { + super(); + + final String filename = socketUri.toString() + .replaceAll("^unix:///", "unix://localhost/") + .replaceAll("^unix://localhost", ""); + + this.socketFile = new File(filename); + } + + public static URI sanitizeUri(final URI uri) { + if (uri.getScheme().equals("unix")) { + return URI.create("unix://localhost:80"); + } else { + return uri; + } + } + + @Override + public Socket createSocket(final HttpContext context) throws IOException { + return new ApacheUnixSocket(); + } + + @Override + public Socket connectSocket(final int connectTimeout, + final Socket socket, + final HttpHost host, + final InetSocketAddress remoteAddress, + final InetSocketAddress localAddress, + final HttpContext context) throws IOException { + try { + socket.connect(new AFUNIXSocketAddress(socketFile), connectTimeout); + } catch (SocketTimeoutException e) { + throw new ConnectTimeoutException(e, null, remoteAddress.getAddress()); + } + + return socket; + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java index 61d97f93..42158e01 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java @@ -2,6 +2,7 @@ import java.io.EOFException; import java.io.IOException; +import java.io.InputStream; import java.nio.charset.Charset; import javax.ws.rs.client.ClientRequestContext; @@ -63,7 +64,9 @@ public String getBodyAsMessage(ClientResponseContext responseContext) if (contentLength != -1) { byte[] buffer = new byte[contentLength]; try { - IOUtils.readFully(responseContext.getEntityStream(), buffer); + InputStream entityStream = responseContext.getEntityStream(); + IOUtils.readFully(entityStream, buffer); + entityStream.close(); } catch (EOFException e) { return null; diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 3ed64d9a..71bfb930 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -33,7 +33,6 @@ public abstract class AbstractDockerClientTest extends Assert { public static final Logger LOG = LoggerFactory .getLogger(AbstractDockerClientTest.class); - public static final String DOCKER_JAVA = "dockerjava"; protected DockerClient dockerClient; @@ -120,7 +119,8 @@ protected String asString(InputStream response) { logwriter.write(line + (itr.hasNext() ? "\n" : "")); //LOG.info("line: "+line); } - + response.close(); + return logwriter.toString(); } catch (IOException e) { throw new RuntimeException(e); @@ -150,7 +150,7 @@ public static boolean available(int port) { ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; - } catch (IOException e) { + } catch (IOException ignored) { } finally { if (ds != null) { ds.close(); diff --git a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java index e452e300..3a61d034 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java @@ -16,7 +16,7 @@ public class DockerClientConfigTest { public static final DockerClientConfig EXAMPLE_CONFIG = newExampleConfig(); private static DockerClientConfig newExampleConfig() { - return new DockerClientConfig(URI.create("http://foo"), "bar", "baz", "qux", "blam", "wham", "flam", 877, false, new LocalDirectorySSLConfig("flim")); + return new DockerClientConfig(URI.create("http://foo"), "bar", "baz", "qux", "blam", "wham", "flam", 877, false, new LocalDirectorySSLConfig("flim"), 20, 2); } @Test @@ -36,6 +36,8 @@ public void environmentDockerHost() throws Exception { // given docker host in env Map env = new HashMap(); env.put("DOCKER_HOST", "tcp://baz:8768"); + // and it looks to be SSL disabled + env.remove("DOCKER_CERT_PATH"); // when you build a config DockerClientConfig config = buildConfig(env, new Properties()); diff --git a/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java b/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java index a91fa109..1f5604fe 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java @@ -10,7 +10,7 @@ public class DockerClientImplTest { @Test public void configuredInstanceAuthConfig() throws Exception { // given a config with null serverAddress - DockerClientConfig dockerClientConfig = new DockerClientConfig(null, null, "", "", "", null, null, 0, false, null); + DockerClientConfig dockerClientConfig = new DockerClientConfig(null, null, "", "", "", null, null, 0, false, null, 20, 2); DockerClientImpl dockerClient = DockerClientImpl.getInstance(dockerClientConfig); // when we get the auth config diff --git a/src/test/java/com/github/dockerjava/core/GoLangFileMatchTest.java b/src/test/java/com/github/dockerjava/core/GoLangFileMatchTest.java index b556a7e5..215926a5 100644 --- a/src/test/java/com/github/dockerjava/core/GoLangFileMatchTest.java +++ b/src/test/java/com/github/dockerjava/core/GoLangFileMatchTest.java @@ -3,7 +3,6 @@ */ package com.github.dockerjava.core; -import java.io.File; import java.io.IOException; import junit.framework.Assert; @@ -19,7 +18,7 @@ public void testMatch(MatchTestCase testCase) throws IOException { String pattern = testCase.pattern; String s = testCase.s; if (GoLangFileMatch.IS_WINDOWS) { - if (pattern.indexOf('\\') > 0) { + if (pattern.indexOf('\\') >= 0) { // no escape allowed on windows. return; } diff --git a/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java index 945b6198..193b787c 100644 --- a/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImplTest.java @@ -41,7 +41,7 @@ public void copyFromContainer() throws Exception { // TODO extract this into a shared method CreateContainerResponse container = dockerClient.createContainerCmd("busybox") .withName("docker-java-itest-copyFromContainer") - .withCmd("touch", "/test") + .withCmd("touch", "/copyFromContainer") .exec(); LOG.info("Created container: {}", container); @@ -49,16 +49,22 @@ public void copyFromContainer() throws Exception { dockerClient.startContainerCmd(container.getId()).exec(); - InputStream response = dockerClient.copyFileFromContainerCmd(container.getId(), "/test").exec(); - assertTrue(response.available() > 0, "The file was not copied from the container."); + InputStream response = dockerClient.copyFileFromContainerCmd(container.getId(), "/copyFromContainer").exec(); + boolean bytesAvailable = response.available() > 0; + assertTrue(bytesAvailable, "The file was not copied from the container."); + + // read the stream fully. Otherwise, the underlying stream will not be closed. + String responseAsString = asString(response); + assertNotNull(responseAsString); + assertTrue(responseAsString.length() > 0); } @Test public void copyFromNonExistingContainer() throws Exception { - try { - dockerClient.copyFileFromContainerCmd("non-existing", "/test").exec(); - fail("expected NotFoundException"); - } catch (NotFoundException e) { - } + try { + dockerClient.copyFileFromContainerCmd("non-existing", "/test").exec(); + fail("expected NotFoundException"); + } catch (NotFoundException ignored) { + } } } diff --git a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java index 6935227b..329f60b7 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java @@ -19,6 +19,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; @Test(groups = "integration") public class EventsCmdImplTest extends AbstractDockerClientTest { @@ -67,8 +68,7 @@ public void testEventStreamTimeBound() throws InterruptedException, IOException boolean zeroCount = countDownLatch.await(5, TimeUnit.SECONDS); executorService.shutdown(); - - + assertTrue(zeroCount, "Expected 4 events, [create, start, die, stop]"); } @@ -78,7 +78,7 @@ public void testEventStreaming() throws InterruptedException, IOException { TimeUnit.SECONDS.sleep(1); CountDownLatch countDownLatch = new CountDownLatch(KNOWN_NUM_EVENTS); - EventCallback eventCallback = new EventCallbackTest(countDownLatch); + EventCallbackTest eventCallback = new EventCallbackTest(countDownLatch); EventsCmd eventsCmd = dockerClient.eventsCmd(eventCallback).withSince(getEpochTime()); ExecutorService executorService = eventsCmd.exec(); @@ -87,6 +87,7 @@ public void testEventStreaming() throws InterruptedException, IOException { boolean zeroCount = countDownLatch.await(5, TimeUnit.SECONDS); executorService.shutdown(); + eventCallback.close(); assertTrue(zeroCount, "Expected 4 events, [create, start, die, stop]"); } @@ -105,11 +106,16 @@ private int generateEvents() { private class EventCallbackTest implements EventCallback { private final CountDownLatch countDownLatch; + private final AtomicBoolean isReceiving = new AtomicBoolean(true); public EventCallbackTest(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } + public void close() { + isReceiving.set(false); + } + @Override public void onEvent(Event event) { LOG.info("Received event #{}: {}", countDownLatch.getCount(), event); @@ -125,5 +131,10 @@ public void onException(Throwable throwable) { public void onCompletion(int numEvents) { LOG.info("Number of events received: {}", numEvents); } + + @Override + public boolean isReceiving() { + return isReceiving.get(); + } } } diff --git a/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java index a8c3fe8a..497c44c1 100644 --- a/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java @@ -42,19 +42,26 @@ public void execStartTest() throws Exception { String containerName = "generated_" + new SecureRandom().nextInt(); CreateContainerResponse container = dockerClient - .createContainerCmd("busybox").withCmd("top") + .createContainerCmd("busybox") + .withCmd("top") .withName(containerName).exec(); - LOG.info("Created container {}", container.toString()); - assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); - ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()).withAttachStdout(true).withCmd("touch","file.log").exec(); + ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()) + .withAttachStdout(true) + .withCmd("touch", "/execStartTest.log").exec(); dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(); - InputStream response = dockerClient.copyFileFromContainerCmd(container.getId(), "/file.log").exec(); - assertTrue(response.available() > 0, "The file was not copied from the container."); + InputStream response = dockerClient.copyFileFromContainerCmd(container.getId(), "/execStartTest.log").exec(); + boolean bytesAvailable = response.available() > 0; + assertTrue(bytesAvailable, "The file was not copied from the container."); + + // read the stream fully. Otherwise, the underlying stream will not be closed. + String responseAsString = asString(response); + assertNotNull(responseAsString); + assertTrue(responseAsString.length() > 0); } } diff --git a/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java index 37214418..a0a272f2 100644 --- a/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java @@ -45,6 +45,7 @@ public void afterMethod(ITestResult result) { public void info() throws DockerException { // Make sure that there is at least one container for the assertion // TODO extract this into a shared method + if (dockerClient.listContainersCmd().withShowAll(true).exec().size() == 0) { CreateContainerResponse container = dockerClient.createContainerCmd("busybox") .withName("docker-java-itest-info") .withCmd("touch", "/test") @@ -54,8 +55,9 @@ public void info() throws DockerException { assertThat(container.getId(), not(isEmptyOrNullString())); dockerClient.startContainerCmd(container.getId()).exec(); + } - Info dockerInfo = dockerClient.infoCmd().exec(); + Info dockerInfo = dockerClient.infoCmd().exec(); LOG.info(dockerInfo.toString()); assertTrue(dockerInfo.toString().contains("containers")); @@ -68,6 +70,4 @@ public void info() throws DockerException { assertTrue(dockerInfo.getNGoroutines() > 0); assertTrue(dockerInfo.isMemoryLimit()); } - - } diff --git a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java index 394e86bd..31a101f1 100644 --- a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java @@ -109,7 +109,9 @@ public void testPullImage() throws DockerException, IOException { public void testPullNonExistingImage() throws DockerException, IOException { // does not throw an exception - dockerClient.pullImageCmd("nonexisting/foo").exec(); + InputStream is = dockerClient.pullImageCmd("nonexisting/foo").exec(); + // stream needs to be fully read in order to close the underlying connection + this.asString(is); try { dockerClient.pullImageCmd("non-existing/foo").exec(); diff --git a/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java index 2e2c9134..f409aebf 100644 --- a/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PushImageCmdImplTest.java @@ -71,6 +71,5 @@ public void pushExistentImage() throws Exception { assertThat(asString(dockerClient.pushImageCmd(username + "/xxx").exec()), containsString("error")); } - } From bce65f09fe9ee9b6904c9687df17bdbc1c42bd5d Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Sat, 17 Jan 2015 21:27:34 +0100 Subject: [PATCH 267/452] add Dockerfile with minimal build environment --- .dockerignore | 1 + Dockerfile | 18 ++++++++++++++++++ .../core/command/EventsCmdImplTest.java | 3 ++- 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 .dockerignore create mode 100644 Dockerfile diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..1de56593 --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +target \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..eea3db56 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +FROM java:7 +MAINTAINER https://github.com/docker-java/docker-java + +ENV HOME /root +ENV M2_HOME /opt/apache-maven-3.0.5 + +RUN wget http://www.eu.apache.org/dist/maven/maven-3/3.0.5/binaries/apache-maven-3.0.5-bin.tar.gz -O /tmp/apache-maven-3.0.5-bin.tar.gz \ + && cd /tmp \ + && tar xzf apache-maven-3.0.5-bin.tar.gz \ + && mkdir -p /opt \ + && mv apache-maven-3.0.5 /opt \ + && rm apache-maven-3.0.5-bin.tar.gz + +WORKDIR /project +ADD . /project/ + +#ENTRYPOINT $M2_HOME/bin/mvn +CMD $M2_HOME/bin/mvn verify diff --git a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java index 329f60b7..941657a1 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java @@ -60,7 +60,7 @@ public void testEventStreamTimeBound() throws InterruptedException, IOException String endTime = getEpochTime(); CountDownLatch countDownLatch = new CountDownLatch(expectedEvents); - EventCallback eventCallback = new EventCallbackTest(countDownLatch); + EventCallbackTest eventCallback = new EventCallbackTest(countDownLatch); EventsCmd eventsCmd = dockerClient.eventsCmd(eventCallback).withSince(startTime).withUntil(endTime); ExecutorService executorService = eventsCmd.exec(); @@ -68,6 +68,7 @@ public void testEventStreamTimeBound() throws InterruptedException, IOException boolean zeroCount = countDownLatch.await(5, TimeUnit.SECONDS); executorService.shutdown(); + eventCallback.close(); assertTrue(zeroCount, "Expected 4 events, [create, start, die, stop]"); } From 0319b14b2eabf88de3be5e7333f96c728d83ad50 Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Sun, 18 Jan 2015 12:30:15 +0100 Subject: [PATCH 268/452] fix client config test to handle different develeoper environments --- .dockerignore | 3 ++- .../core/DockerClientConfigTest.java | 22 ++++++++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/.dockerignore b/.dockerignore index 1de56593..a96e5522 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1 +1,2 @@ -target \ No newline at end of file +.git/ +target/ diff --git a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java index 3a61d034..4611f430 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java @@ -84,7 +84,9 @@ public void environmentDockerHostWithInvalidTlsVerify() throws Exception { // given docker host in env Map env = new HashMap(System.getenv()); env.put("DOCKER_HOST", "tcp://bar:8768"); - // and it looks to be SSL enabled + // and it looks to be SSL disabled + env.remove("DOCKER_CERT_PATH"); + // and it has an invalid TLS_VERIFY value env.put("DOCKER_TLS_VERIFY", "any value different from '1'"); // when you build a config @@ -94,6 +96,24 @@ public void environmentDockerHostWithInvalidTlsVerify() throws Exception { assertEquals(config.getUri(), URI.create("http://bar:8768")); } + @Test + public void environmentDockerHostWithInvalidTlsVerifyButWithCertPath() throws Exception { + + // given docker host in env + Map env = new HashMap(System.getenv()); + env.put("DOCKER_HOST", "tcp://bar:8768"); + // and it looks to be SSL enabled + env.put("DOCKER_CERT_PATH", "any value"); + // and it has an invalid TLS_VERIFY value + env.put("DOCKER_TLS_VERIFY", "any value different from '1'"); + + // when you build a config + DockerClientConfig config = buildConfig(env, new Properties()); + + // then the URL is that value with "tcp" changed to "https" + assertEquals(config.getUri(), URI.create("https://bar:8768")); + } + @Test public void environment() throws Exception { From f4ddcb35662c9e3d1c9acc6406dec305c369f9c7 Mon Sep 17 00:00:00 2001 From: Tobias Gesellchen Date: Sun, 18 Jan 2015 12:35:14 +0100 Subject: [PATCH 269/452] explicitly declare the Exception as ignored --- .../github/dockerjava/core/command/PullImageCmdImplTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java index 31a101f1..43291f07 100644 --- a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java @@ -116,7 +116,7 @@ public void testPullNonExistingImage() throws DockerException, IOException { try { dockerClient.pullImageCmd("non-existing/foo").exec(); fail("expected InternalServerErrorException"); - } catch (InternalServerErrorException e) { + } catch (InternalServerErrorException ignored) { } } From 4f969dcff36635b242fdec38a2bb398ea7c68bac Mon Sep 17 00:00:00 2001 From: Roman Timushev Date: Mon, 19 Jan 2015 10:52:11 +0300 Subject: [PATCH 270/452] Allow unauthorized pullImageCmd --- .../com/github/dockerjava/core/DockerClientImpl.java | 2 +- .../core/command/AbstrAuthCfgDockerCmd.java | 11 ++++++++++- .../dockerjava/core/command/PullImageCmdImpl.java | 5 +++-- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index cee364e0..9581a5b8 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -125,7 +125,7 @@ public VersionCmd versionCmd() { @Override public PullImageCmd pullImageCmd(String repository) { return new PullImageCmdImpl(getDockerCmdExecFactory() - .createPullImageCmdExec(), repository).withAuthConfig(dockerClientConfig.effectiveAuthConfig(repository)); + .createPullImageCmdExec(), dockerClientConfig.effectiveAuthConfig(repository), repository); } @Override diff --git a/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java index 72aa94d8..96e92da4 100644 --- a/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java @@ -15,6 +15,11 @@ public abstract class AbstrAuthCfgDockerCmd, RES_T> extends AbstrDockerCmd { + public AbstrAuthCfgDockerCmd(DockerCmdExec execution, AuthConfig authConfig) { + super(execution); + withOptionalAuthConfig(authConfig); + } + public AbstrAuthCfgDockerCmd(DockerCmdExec execution) { super(execution); } @@ -25,9 +30,13 @@ public AuthConfig getAuthConfig() { return authConfig; } - @SuppressWarnings("unchecked") public T withAuthConfig(AuthConfig authConfig) { Preconditions.checkNotNull(authConfig, "authConfig was not specified"); + return withOptionalAuthConfig(authConfig); + } + + @SuppressWarnings("unchecked") + private T withOptionalAuthConfig(AuthConfig authConfig) { this.authConfig = authConfig; return (T)this; } diff --git a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java index b2e62434..bcd3613b 100644 --- a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java @@ -1,6 +1,7 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.model.AuthConfig; import com.google.common.base.Preconditions; import java.io.InputStream; @@ -14,8 +15,8 @@ public class PullImageCmdImpl extends AbstrAuthCfgDockerCmd Date: Tue, 20 Jan 2015 22:13:22 +0100 Subject: [PATCH 271/452] Fix misleading variable name in Exec-start --- .../com/github/dockerjava/core/command/ExecStartCmdImpl.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java index 0340a7ac..3b21f9b2 100644 --- a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java @@ -12,10 +12,9 @@ public class ExecStartCmdImpl extends AbstrDockerCmd private boolean detach, tty; - public ExecStartCmdImpl(ExecStartCmd.Exec exec, String containerId) { + public ExecStartCmdImpl(ExecStartCmd.Exec exec, String execId) { super(exec); - Preconditions.checkNotNull(containerId, "containerId was not specified"); - this.execId = containerId; + withExecId(execId); } @Override From 60fb248a7acc4e6bedbe56503d5ae142862b68f5 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 20 Jan 2015 22:23:21 +0100 Subject: [PATCH 272/452] Support wildcards in Dockerfile. Fix issue#129 --- .../core/command/BuildImageCmdImpl.java | 79 +++++++++++++------ .../core/command/BuildImageCmdImplTest.java | 32 +++++--- .../testAddFilesViaWildcard/Dockerfile | 9 +++ .../folder1/testrun.sh | 5 ++ .../folder2/testinclude1.sh | 3 + .../ignore/testinclude2.sh | 3 + 6 files changed, 100 insertions(+), 31 deletions(-) create mode 100644 src/test/resources/testAddFilesViaWildcard/Dockerfile create mode 100755 src/test/resources/testAddFilesViaWildcard/folder1/testrun.sh create mode 100755 src/test/resources/testAddFilesViaWildcard/folder2/testinclude1.sh create mode 100755 src/test/resources/testAddFilesViaWildcard/ignore/testinclude2.sh diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 9e8b5a14..ec3406b1 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -31,7 +31,8 @@ * Build an image from Dockerfile. * */ -public class BuildImageCmdImpl extends AbstrDockerCmd implements BuildImageCmd { +public class BuildImageCmdImpl extends + AbstrDockerCmd implements BuildImageCmd { private static final Pattern ADD_OR_COPY_PATTERN = Pattern .compile("^(ADD|COPY)\\s+(.*)\\s+(.*)$"); @@ -62,8 +63,8 @@ public BuildImageCmdImpl(BuildImageCmd.Exec exec, InputStream tarInputStream) { super(exec); Preconditions.checkNotNull(tarInputStream, "tarInputStream is null"); withTarInputStream(tarInputStream); - } - + } + @Override public InputStream getTarInputStream() { return tarInputStream; @@ -75,7 +76,7 @@ public BuildImageCmdImpl withTarInputStream(InputStream tarInputStream) { this.tarInputStream = tarInputStream; return this; } - + @Override public BuildImageCmdImpl withTag(String tag) { Preconditions.checkNotNull(tag, "Tag is null"); @@ -113,7 +114,7 @@ public BuildImageCmdImpl withNoCache(boolean noCache) { this.noCache = noCache; return this; } - + @Override public BuildImageCmdImpl withRemove() { return withRemove(true); @@ -124,7 +125,7 @@ public BuildImageCmdImpl withRemove(boolean rm) { this.remove = rm; return this; } - + @Override public BuildImageCmdImpl withQuiet() { return withQuiet(true); @@ -142,7 +143,7 @@ public void close() throws IOException { if (tarFile != null) { FileUtils.deleteQuietly(tarFile); } - + tarInputStream.close(); } @@ -152,8 +153,7 @@ public String toString() { .append(tag != null ? "-t " + tag + " " : "") .append(noCache ? "--nocache=true " : "") .append(quiet ? "--quiet=true " : "") - .append(!remove ? "--rm=false " : "") - .toString(); + .append(!remove ? "--rm=false " : "").toString(); } protected File buildDockerFolderTar(File dockerFolder) { @@ -182,8 +182,9 @@ protected File buildDockerFolderTar(File dockerFolder) { File dockerIgnoreFile = new File(dockerFolder, ".dockerignore"); if (dockerIgnoreFile.exists()) { int lineNumber = 0; - List dockerIgnoreFileContent = FileUtils.readLines(dockerIgnoreFile); - for (String pattern: dockerIgnoreFileContent) { + List dockerIgnoreFileContent = FileUtils + .readLines(dockerIgnoreFile); + for (String pattern : dockerIgnoreFileContent) { lineNumber++; pattern = pattern.trim(); if (pattern.isEmpty()) { @@ -191,14 +192,20 @@ protected File buildDockerFolderTar(File dockerFolder) { } pattern = FilenameUtils.normalize(pattern); try { - // validate pattern and make sure we aren't excluding Dockerfile + // validate pattern and make sure we aren't excluding + // Dockerfile if (GoLangFileMatch.match(pattern, "Dockerfile")) { throw new DockerClientException( - String.format("Dockerfile is excluded by pattern '%s' on line %s in .dockerignore file", pattern, lineNumber)); + String.format( + "Dockerfile is excluded by pattern '%s' on line %s in .dockerignore file", + pattern, lineNumber)); } ignores.add(pattern); } catch (GoLangFileMatchException e) { - throw new DockerClientException(String.format("Invalid pattern '%s' on line %s in .dockerignore file", pattern, lineNumber)); + throw new DockerClientException( + String.format( + "Invalid pattern '%s' on line %s in .dockerignore file", + pattern, lineNumber)); } } } @@ -254,19 +261,26 @@ protected File buildDockerFolderTar(File dockerFolder) { src, dockerFolder)); } - if (!src.exists()) { - throw new DockerClientException(String.format( - "Source file %s doesn't exist", src)); - } + // if (!src.exists()) { + // throw new DockerClientException(String.format( + // "Source file %s doesn't exist", src)); + // } if (src.isDirectory()) { Collection files = FileUtils.listFiles(src, - new GoLangMatchFileFilter(src, ignores), TrueFileFilter.INSTANCE); + new GoLangMatchFileFilter(src, ignores), + TrueFileFilter.INSTANCE); filesToAdd.addAll(files); - } else if (!GoLangFileMatch.match(ignores, CompressArchiveUtil.relativize(dockerFolder, src))){ + } else if (!src.exists()) { + filesToAdd.addAll(resolveWildcards(src, ignores)); + } else if (!GoLangFileMatch.match(ignores, + CompressArchiveUtil.relativize(dockerFolder, + src))) { filesToAdd.add(src); } else { - throw new DockerClientException(String.format( - "Source file %s is excluded by .dockerignore file", src)); + throw new DockerClientException( + String.format( + "Source file %s is excluded by .dockerignore file", + src)); } } } @@ -281,6 +295,27 @@ protected File buildDockerFolderTar(File dockerFolder) { } } + private Collection resolveWildcards(File file, List ignores) { + List filesToAdd = new ArrayList(); + + File parent = file.getParentFile(); + if (parent != null) { + if (parent.isDirectory()) { + Collection files = FileUtils.listFiles(parent, + new GoLangMatchFileFilter(parent, ignores), + TrueFileFilter.INSTANCE); + filesToAdd.addAll(files); + } else { + filesToAdd.addAll(resolveWildcards(parent, ignores)); + } + } else { + throw new DockerClientException(String.format( + "Source file %s doesn't exist", file)); + } + + return filesToAdd; + } + private String filterForEnvironmentVars(String extractedResource, Map environmentMap) { diff --git a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index 7ae29e53..3692f56d 100644 --- a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -78,7 +78,8 @@ public void testNginxDockerfileBuilder() { public void testDockerBuilderAddUrl() { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("testAddUrl").getFile()); - dockerfileBuild(baseDir, "Docker"); + String response = dockerfileBuild(baseDir); + assertThat(response, containsString("Docker")); } @Test @@ -86,7 +87,18 @@ public void testDockerBuilderAddFileInSubfolder() throws DockerException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("testAddFileInSubfolder").getFile()); - dockerfileBuild(baseDir, "Successfully executed testrun.sh"); + String response = dockerfileBuild(baseDir); + assertThat(response, containsString("Successfully executed testrun.sh")); + } + + @Test + public void testDockerBuilderAddFilesViaWildcard() throws DockerException, + IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("testAddFilesViaWildcard").getFile()); + String response = dockerfileBuild(baseDir); + assertThat(response, containsString("Successfully executed testinclude1.sh")); + assertThat(response, not(containsString("Successfully executed testinclude2.sh"))); } @Test @@ -94,11 +106,12 @@ public void testDockerBuilderAddFolder() throws DockerException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("testAddFolder").getFile()); - dockerfileBuild(baseDir, "Successfully executed testAddFolder.sh"); + String response = dockerfileBuild(baseDir); + assertThat(response, containsString("Successfully executed testAddFolder.sh")); } - private String dockerfileBuild(File baseDir, String expectedText) { + private String dockerfileBuild(File baseDir) { // Build image InputStream response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); @@ -123,9 +136,9 @@ private String dockerfileBuild(File baseDir, String expectedText) { InputStream logResponse = logContainer(container .getId()); - assertThat(asString(logResponse), containsString(expectedText)); + //assertThat(asString(logResponse), containsString(expectedText)); - return container.getId(); + return asString(logResponse); } @@ -152,7 +165,8 @@ public void testDockerIgnore() throws DockerException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("testDockerignore").getFile()); - dockerfileBuild(baseDir, "/tmp/a/a /tmp/a/c /tmp/a/d"); + String response = dockerfileBuild(baseDir); + assertThat(response, containsString("/tmp/a/a /tmp/a/c /tmp/a/d")); } @Test @@ -201,7 +215,7 @@ public void testNetCatDockerfileBuilder() throws InterruptedException { public void testAddAndCopySubstitution () throws DockerException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("testENVSubstitution").getFile()); - dockerfileBuild(baseDir, "testENVSubstitution successfully completed"); - + String response = dockerfileBuild(baseDir); + assertThat(response, containsString("testENVSubstitution successfully completed")); } } diff --git a/src/test/resources/testAddFilesViaWildcard/Dockerfile b/src/test/resources/testAddFilesViaWildcard/Dockerfile new file mode 100644 index 00000000..a9a9ad2b --- /dev/null +++ b/src/test/resources/testAddFilesViaWildcard/Dockerfile @@ -0,0 +1,9 @@ +FROM ubuntu:latest + +# Copy testrun.sh files into the container + +ADD ./folder*/* /tmp/ + +RUN cp /tmp/*.sh /usr/local/bin/ && chmod +x /usr/local/bin/*.sh + +CMD ["testrun.sh"] diff --git a/src/test/resources/testAddFilesViaWildcard/folder1/testrun.sh b/src/test/resources/testAddFilesViaWildcard/folder1/testrun.sh new file mode 100755 index 00000000..fcfb1ee9 --- /dev/null +++ b/src/test/resources/testAddFilesViaWildcard/folder1/testrun.sh @@ -0,0 +1,5 @@ +#!/bin/sh + +/usr/local/bin/testinclude1.sh +/usr/local/bin/testinclude2.sh + diff --git a/src/test/resources/testAddFilesViaWildcard/folder2/testinclude1.sh b/src/test/resources/testAddFilesViaWildcard/folder2/testinclude1.sh new file mode 100755 index 00000000..7953ce67 --- /dev/null +++ b/src/test/resources/testAddFilesViaWildcard/folder2/testinclude1.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Successfully executed testinclude1.sh" diff --git a/src/test/resources/testAddFilesViaWildcard/ignore/testinclude2.sh b/src/test/resources/testAddFilesViaWildcard/ignore/testinclude2.sh new file mode 100755 index 00000000..259944b2 --- /dev/null +++ b/src/test/resources/testAddFilesViaWildcard/ignore/testinclude2.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Successfully executed testinclude2.sh" From 4c69b518f455d346e40631cef53be5893ed639ae Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 21 Jan 2015 21:12:12 +0100 Subject: [PATCH 273/452] some cleanup --- Dockerfile | 18 ------------------ pom.xml | 11 ++--------- 2 files changed, 2 insertions(+), 27 deletions(-) delete mode 100644 Dockerfile diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index eea3db56..00000000 --- a/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM java:7 -MAINTAINER https://github.com/docker-java/docker-java - -ENV HOME /root -ENV M2_HOME /opt/apache-maven-3.0.5 - -RUN wget http://www.eu.apache.org/dist/maven/maven-3/3.0.5/binaries/apache-maven-3.0.5-bin.tar.gz -O /tmp/apache-maven-3.0.5-bin.tar.gz \ - && cd /tmp \ - && tar xzf apache-maven-3.0.5-bin.tar.gz \ - && mkdir -p /opt \ - && mv apache-maven-3.0.5 /opt \ - && rm apache-maven-3.0.5-bin.tar.gz - -WORKDIR /project -ADD . /project/ - -#ENTRYPOINT $M2_HOME/bin/mvn -CMD $M2_HOME/bin/mvn verify diff --git a/pom.xml b/pom.xml index 1e6a477e..ce566d4d 100644 --- a/pom.xml +++ b/pom.xml @@ -39,20 +39,13 @@
- - - jcenter - http://jcenter.bintray.com - - - UTF-8 UTF-8 true false - 1.6 - 1.6 + 1.7 + 1.7 1.6.1 From 55e42ad2e21ed2cb198a913a7f95ed05dc6e8f98 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 21 Jan 2015 21:16:55 +0100 Subject: [PATCH 274/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f225212d..4baf40e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ Change Log docker-java-0.10.5-SNAPSHOT --- + * [#125](https://github.com/docker-java/docker-java/pull/125) Unixsocket support * [#123](https://github.com/docker-java/docker-java/pull/123) support DOCKER_TLS_VERIFY to detect ssl * [#121](https://github.com/docker-java/docker-java/pull/121) Implemented support for commands: Exec-start, Exec-create * [#120](https://github.com/docker-java/docker-java/pull/120) Command resource cleanup after command execution From f71c2d9eaf988201e61b4b497b8bff7b2c505df7 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 21 Jan 2015 21:20:38 +0100 Subject: [PATCH 275/452] [maven-release-plugin] prepare release docker-java-0.10.5 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index ce566d4d..f1987efa 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.5-SNAPSHOT + 0.10.5 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-0.10.5 From e2e30cd2d88eca44f9bfccbebf0ae9f12a7fee76 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 21 Jan 2015 21:21:23 +0100 Subject: [PATCH 276/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index f1987efa..4a9af78d 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.5 + 0.10.6-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-0.10.5 + HEAD From e022c44fc615c2a0f2e9747db744b1c9bd6113fb Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 21 Jan 2015 21:25:47 +0100 Subject: [PATCH 277/452] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ec3a92a4..53d47021 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Run build without integration tests: com.github.docker-java docker-java - 0.10.4 + 0.10.5 ### Latest SNAPSHOT version @@ -69,7 +69,7 @@ You can find the latest SNAPSHOT version including javadoc and source files on [ com.github.docker-java docker-java - 0.10.5-SNAPSHOT + 0.10.6-SNAPSHOT ## Documentation From de1611efa0935ea3a23fe8f56fcba48e5e00015f Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 21 Jan 2015 21:27:23 +0100 Subject: [PATCH 278/452] Update README.md --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 53d47021..63c8d64b 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Java API client for [Docker](http://docs.docker.io/ "Docker") -Supports a subset of the Docker Client API v1.15, Docker Server version 1.3.2 +Supports a subset of the Docker Client API v1.16, Docker Server version 1.4.1 The current implementation is based on Jersey 2.x and therefore classpath incompatible with older Jersey 1.x dependent libraries! @@ -13,7 +13,7 @@ Developer forum for [docker-java](https://groups.google.com/forum/?hl=de#!forum/ ###### Prerequisites: -* Java 1.6 +* Java 1.7 * Maven 3.0.5 * Docker daemon running @@ -81,7 +81,7 @@ For code examples, please look at the [Wiki](https://github.com/docker-java/dock There are a couple of configuration items, all of which have sensible defaults: * `url` The Docker URL, e.g. `https://localhost:2376`. -* `version` The API version, e.g. `1.15`. +* `version` The API version, e.g. `1.16`. * `username` Your registry username (required to push containers). * `password` Your registry password. * `email` Your registry email. @@ -94,7 +94,7 @@ There are three ways to configure, in descending order of precedence: In your application, e.g. DockerClientConfig config = DockerClientConfig.createDefaultConfigBuilder() - .withVersion("1.15") + .withVersion("1.16") .withUri("https://my-docker-host.tld:2376") .withUsername("dockeruser") .withPassword("ilovedocker") @@ -107,7 +107,7 @@ In your application, e.g. #### Properties docker.io.url=https://localhost:2376 - docker.io.version=1.15 + docker.io.version=1.16 docker.io.username=dockeruser docker.io.password=ilovedocker docker.io.email=dockeruser@github.com From 2f9b736398dd650c4a1feb7d2dbedd5fa1387970 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 21 Jan 2015 21:31:38 +0100 Subject: [PATCH 279/452] Update CHANGELOG.md --- CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4baf40e1..d5cc1880 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,10 @@ Change Log === -docker-java-0.10.5-SNAPSHOT +docker-java-0.10.6-SNAPSHOT +--- + +docker-java-0.10.5 --- * [#125](https://github.com/docker-java/docker-java/pull/125) Unixsocket support * [#123](https://github.com/docker-java/docker-java/pull/123) support DOCKER_TLS_VERIFY to detect ssl From 06c3ffe7d9769087b607fe7186e975a4df66d4b8 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 21 Jan 2015 23:19:55 +0100 Subject: [PATCH 280/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d5cc1880..0b0d2c6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ Change Log docker-java-0.10.6-SNAPSHOT --- + * [#128](https://github.com/docker-java/docker-java/pull/128) Allow unauthorized pullImageCmd docker-java-0.10.5 --- From 0a3a28ea767c79a86bc41e0a26d8f2e389795528 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 21 Jan 2015 23:33:15 +0100 Subject: [PATCH 281/452] Fix compile error --- .../github/dockerjava/core/command/PullImageCmdImplTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java index 43291f07..861c1078 100644 --- a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java @@ -49,7 +49,7 @@ public void afterMethod(ITestResult result) { @Test public void nullAuthConfig() throws Exception { - PullImageCmdImpl pullImageCmd = new PullImageCmdImpl(NOP_EXEC, ""); + PullImageCmdImpl pullImageCmd = new PullImageCmdImpl(NOP_EXEC, null, ""); try { pullImageCmd.withAuthConfig(null); fail(); From ad7881a05de88dea57c9e3b752728b354236a4fd Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 27 Jan 2015 13:05:10 +0100 Subject: [PATCH 282/452] Remove Google Guava as dependency --- pom.xml | 7 - .../com/github/dockerjava/Preconditions.java | 145 +++++++++ .../api/command/TopContainerResponse.java | 9 +- .../github/dockerjava/api/model/Device.java | 9 +- .../dockerjava/api/model/RestartPolicy.java | 5 +- .../dockerjava/core/DockerClientConfig.java | 45 +-- .../dockerjava/core/DockerClientImpl.java | 79 ++++- .../dockerjava/core/KeystoreSSLConfig.java | 15 +- .../core/LocalDirectorySSLConfig.java | 24 +- .../core/command/AbstrAuthCfgDockerCmd.java | 11 +- .../core/command/AbstrDockerCmd.java | 5 +- .../core/command/AttachContainerCmdImpl.java | 6 +- .../core/command/BuildImageCmdImpl.java | 19 +- .../core/command/CommitCmdImpl.java | 36 +-- .../core/command/ContainerDiffCmdImpl.java | 6 +- .../command/CopyFileFromContainerCmdImpl.java | 10 +- .../core/command/CreateContainerCmdImpl.java | 10 +- .../core/command/CreateImageCmdImpl.java | 11 +- .../core/command/ExecCreateCmdImpl.java | 5 +- .../core/command/ExecStartCmdImpl.java | 9 +- .../core/command/InspectContainerCmdImpl.java | 6 +- .../core/command/InspectImageCmdImpl.java | 5 +- .../core/command/KillContainerCmdImpl.java | 7 +- .../core/command/ListContainersCmdImpl.java | 10 +- .../core/command/ListImagesCmdImpl.java | 6 +- .../core/command/LogContainerCmdImpl.java | 6 +- .../core/command/PauseContainerCmdImpl.java | 6 +- .../core/command/PullImageCmdImpl.java | 13 +- .../core/command/PushImageCmdImpl.java | 8 +- .../core/command/RemoveContainerCmdImpl.java | 6 +- .../core/command/RemoveImageCmdImpl.java | 6 +- .../core/command/RestartContainerCmdImpl.java | 9 +- .../core/command/SearchImagesCmdImpl.java | 6 +- .../core/command/StartContainerCmdImpl.java | 33 +- .../core/command/StopContainerCmdImpl.java | 9 +- .../core/command/TagImageCmdImpl.java | 9 +- .../core/command/TopContainerCmdImpl.java | 8 +- .../core/command/UnpauseContainerCmdImpl.java | 6 +- .../core/command/WaitContainerCmdImpl.java | 5 +- .../dockerjava/jaxrs/AbstrDockerCmdExec.java | 7 +- .../dockerjava/jaxrs/ApacheUnixSocket.java | 9 +- .../jaxrs/DockerCmdExecFactoryImpl.java | 72 +++-- .../dockerjava/jaxrs/EventsCmdExec.java | 19 +- .../dockerjava/jaxrs/ListImagesCmdExec.java | 5 +- .../jaxrs/util/SelectiveLoggingFilter.java | 17 +- .../dockerjava/jaxrs/util/guava/Guava.java | 45 +++ .../jaxrs/util/guava/PercentEscaper.java | 245 ++++++++++++++ .../jaxrs/util/guava/UnicodeEscaper.java | 304 ++++++++++++++++++ 48 files changed, 1108 insertions(+), 245 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/Preconditions.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/util/guava/Guava.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/util/guava/PercentEscaper.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/util/guava/UnicodeEscaper.java diff --git a/pom.xml b/pom.xml index 4a9af78d..b8f45ccd 100644 --- a/pom.xml +++ b/pom.xml @@ -62,7 +62,6 @@ 1.7.5 1.3.9 0.3 - 18.0 1.51 2014-11-16T14-41-27 @@ -150,12 +149,6 @@ ${slf4j-api.version}
- - com.google.guava - guava - ${guava.version} - - org.bouncycastle bcpkix-jdk15on diff --git a/src/main/java/com/github/dockerjava/Preconditions.java b/src/main/java/com/github/dockerjava/Preconditions.java new file mode 100644 index 00000000..183e640b --- /dev/null +++ b/src/main/java/com/github/dockerjava/Preconditions.java @@ -0,0 +1,145 @@ +/* Copyright (C) 2008 The Guava Authors + * + * Licensed 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.github.dockerjava; + + +public final class Preconditions { + private Preconditions() {} + + /** + * Ensures the truth of an expression involving one or more parameters to the calling method. + * + * @param expression a boolean expression + * @param errorMessageTemplate a template for the exception message should the check fail. The + * message is formed by replacing each {@code %s} placeholder in the template with an + * argument. These are matched by position - the first {@code %s} gets {@code + * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message + * in square braces. Unmatched placeholders will be left as-is. + * @param errorMessageArgs the arguments to be substituted into the message template. Arguments + * are converted to strings using {@link String#valueOf(Object)}. + * @throws IllegalArgumentException if {@code expression} is false + * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or + * {@code errorMessageArgs} is null (don't let this happen) + */ + public static void checkArgument(boolean expression, + String errorMessageTemplate, + Object... errorMessageArgs) { + if (!expression) { + throw new IllegalArgumentException(Preconditions.format(errorMessageTemplate, errorMessageArgs)); + } + } + + /** + * Ensures that an object reference passed as a parameter to the calling method is not null. + * + * @param reference an object reference + * @param errorMessage the exception message to use if the check fails; will be converted to a + * string using {@link String#valueOf(Object)} + * @return the non-null reference that was validated + * @throws NullPointerException if {@code reference} is null + */ + public static T checkNotNull(T reference, Object errorMessage) { + if (reference == null) { + throw new NullPointerException(String.valueOf(errorMessage)); + } + return reference; + } + + /** + * Ensures the truth of an expression involving one or more parameters to the calling method. + * + * @param expression a boolean expression + * @param errorMessage the exception message to use if the check fails; will be converted to a + * string using {@link String#valueOf(Object)} + * @throws IllegalArgumentException if {@code expression} is false + */ + public static void checkArgument(boolean expression, Object errorMessage) { + if (!expression) { + throw new IllegalArgumentException(String.valueOf(errorMessage)); + } + } + + /** + * Ensures that an object reference passed as a parameter to the calling method is not null. + * + * @param reference an object reference + * @return the non-null reference that was validated + * @throws NullPointerException if {@code reference} is null + */ + public static T checkNotNull(T reference) { + if (reference == null) { + throw new NullPointerException(); + } + return reference; + } + + /** + * Ensures the truth of an expression involving the state of the calling instance, but not + * involving any parameters to the calling method. + * + * @param expression a boolean expression + * @param errorMessage the exception message to use if the check fails; will be converted to a + * string using {@link String#valueOf(Object)} + * @throws IllegalStateException if {@code expression} is false + */ + public static void checkState(boolean expression, Object errorMessage) { + if (!expression) { + throw new IllegalStateException(String.valueOf(errorMessage)); + } + } + + /** + * Substitutes each {@code %s} in {@code template} with an argument. These are matched by + * position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than + * placeholders, the unmatched arguments will be appended to the end of the formatted message in + * square braces. + * + * @param template a non-null string containing 0 or more {@code %s} placeholders. + * @param args the arguments to be substituted into the message template. Arguments are converted + * to strings using {@link String#valueOf(Object)}. Arguments can be null. + */ + // Note that this is somewhat-improperly used from Verify.java as well. + public static String format(String template, Object... args) { + template = String.valueOf(template); // null -> "null" + + // start substituting the arguments into the '%s' placeholders + StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); + int templateStart = 0; + int i = 0; + while (i < args.length) { + int placeholderStart = template.indexOf("%s", templateStart); + if (placeholderStart == -1) { + break; + } + builder.append(template.substring(templateStart, placeholderStart)); + builder.append(args[i++]); + templateStart = placeholderStart + 2; + } + builder.append(template.substring(templateStart)); + + // if we run out of placeholders, append the extra args in square braces + if (i < args.length) { + builder.append(" ["); + builder.append(args[i++]); + while (i < args.length) { + builder.append(", "); + builder.append(args[i++]); + } + builder.append(']'); + } + + return builder.toString(); + } +} diff --git a/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java index e479b269..099da368 100644 --- a/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java @@ -1,8 +1,9 @@ package com.github.dockerjava.api.command; +import static com.github.dockerjava.jaxrs.util.guava.Guava.join; + import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.base.Joiner; /** * @@ -28,17 +29,15 @@ public String[][] getProcesses() { @Override public String toString() { - Joiner joiner = Joiner.on("; ").skipNulls(); - StringBuffer buffer = new StringBuffer(); buffer.append("["); for(String[] fields: processes) { - buffer.append("[" + joiner.join(fields) + "]"); + buffer.append("[" + join(fields, "; ", true) + "]"); } buffer.append("]"); return "TopContainerResponse{" + - "titles=" + joiner.join(titles) + + "titles=" + join(titles, "; ", true) + ", processes=" + buffer.toString() + '}'; } diff --git a/src/main/java/com/github/dockerjava/api/model/Device.java b/src/main/java/com/github/dockerjava/api/model/Device.java index b0b32515..76b0ddbf 100644 --- a/src/main/java/com/github/dockerjava/api/model/Device.java +++ b/src/main/java/com/github/dockerjava/api/model/Device.java @@ -1,10 +1,11 @@ package com.github.dockerjava.api.model; +import static com.github.dockerjava.Preconditions.checkNotNull; + import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.base.Preconditions; public class Device { @@ -22,10 +23,10 @@ public Device() { public Device(String cGroupPermissions, String pathInContainer, String pathOnHost) { - Preconditions.checkNotNull(cGroupPermissions, + checkNotNull(cGroupPermissions, "cGroupPermissions is null"); - Preconditions.checkNotNull(pathInContainer, "pathInContainer is null"); - Preconditions.checkNotNull(pathOnHost, "pathOnHost is null"); + checkNotNull(pathInContainer, "pathInContainer is null"); + checkNotNull(pathOnHost, "pathOnHost is null"); this.cGroupPermissions = cGroupPermissions; this.pathInContainer = pathInContainer; this.pathOnHost = pathOnHost; diff --git a/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java b/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java index 5cdcb70b..e08dd138 100644 --- a/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java +++ b/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java @@ -1,10 +1,11 @@ package com.github.dockerjava.api.model; +import static com.github.dockerjava.Preconditions.checkNotNull; + import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.base.Preconditions; /** * Container restart policy @@ -36,7 +37,7 @@ public RestartPolicy() { } private RestartPolicy(int maximumRetryCount, String name) { - Preconditions.checkNotNull(name, "name is null"); + checkNotNull(name, "name is null"); this.maximumRetryCount = maximumRetryCount; this.name = name; } diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 21e5778f..9a7a2e9f 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -1,20 +1,22 @@ package com.github.dockerjava.core; -import com.github.dockerjava.api.DockerClientException; -import com.github.dockerjava.api.model.AuthConfig; -import com.github.dockerjava.core.NameParser.HostnameReposName; -import com.github.dockerjava.core.NameParser.ReposTag; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableMap; +import static com.github.dockerjava.Preconditions.checkNotNull; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.Serializable; import java.net.URI; +import java.util.Collections; +import java.util.HashMap; import java.util.Map; import java.util.Properties; +import com.github.dockerjava.api.DockerClientException; +import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.core.NameParser.HostnameReposName; +import com.github.dockerjava.core.NameParser.ReposTag; + public class DockerClientConfig implements Serializable { private static final long serialVersionUID = -4307357472441531489L; @@ -39,18 +41,23 @@ public class DockerClientConfig implements Serializable { /** * A map from the environment name to the interval name. */ - private static final Map ENV_NAME_TO_IO_NAME = ImmutableMap.builder() - .put("DOCKER_URL", DOCKER_IO_URL_PROPERTY) - .put("DOCKER_VERSION", DOCKER_IO_VERSION_PROPERTY) - .put("DOCKER_USERNAME", DOCKER_IO_USERNAME_PROPERTY) - .put("DOCKER_PASSWORD", DOCKER_IO_PASSWORD_PROPERTY) - .put("DOCKER_EMAIL", DOCKER_IO_EMAIL_PROPERTY) - .put("DOCKER_SERVER_ADDRESS", DOCKER_IO_SERVER_ADDRESS_PROPERTY) - .put("DOCKER_READ_TIMEOUT", DOCKER_IO_READ_TIMEOUT_PROPERTY) - .put("DOCKER_LOGGING_FILTER_ENABLED", DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY) - .put(DOCKER_CERT_PATH_PROPERTY, DOCKER_IO_DOCKER_CERT_PATH_PROPERTY) - .put("DOCKER_CFG_PATH", DOCKER_IO_DOCKER_CFG_PATH_PROPERTY) - .build(); + // Immutable ish + private static final Map ENV_NAME_TO_IO_NAME; + static { + Map m = new HashMap(); + m.put("DOCKER_URL", DOCKER_IO_URL_PROPERTY); + m.put("DOCKER_VERSION", DOCKER_IO_VERSION_PROPERTY); + m.put("DOCKER_USERNAME", DOCKER_IO_USERNAME_PROPERTY); + m.put("DOCKER_PASSWORD", DOCKER_IO_PASSWORD_PROPERTY); + m.put("DOCKER_EMAIL", DOCKER_IO_EMAIL_PROPERTY); + m.put("DOCKER_SERVER_ADDRESS", DOCKER_IO_SERVER_ADDRESS_PROPERTY); + m.put("DOCKER_READ_TIMEOUT", DOCKER_IO_READ_TIMEOUT_PROPERTY); + m.put("DOCKER_LOGGING_FILTER_ENABLED", DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY); + m.put(DOCKER_CERT_PATH_PROPERTY, DOCKER_IO_DOCKER_CERT_PATH_PROPERTY); + m.put("DOCKER_CFG_PATH", DOCKER_IO_DOCKER_CFG_PATH_PROPERTY); + ENV_NAME_TO_IO_NAME = Collections.unmodifiableMap(m); + } + private static final String DOCKER_IO_PROPERTIES_PROPERTY = "docker.io.properties"; private URI uri; private final String version, username, password, email, serverAddress, dockerCfgPath; @@ -370,7 +377,7 @@ public DockerClientConfigBuilder withProperties(Properties p) { } public final DockerClientConfigBuilder withUri(String uri) { - Preconditions.checkNotNull(uri, "uri was not specified"); + checkNotNull(uri, "uri was not specified"); this.uri = URI.create(uri); return this; } diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 556c7f91..f1175921 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core; -import static com.google.common.base.Preconditions.checkNotNull; +import static com.github.dockerjava.Preconditions.checkNotNull; import java.io.Closeable; import java.io.File; @@ -8,10 +8,75 @@ import java.io.InputStream; import com.github.dockerjava.api.DockerClient; -import com.github.dockerjava.api.command.*; +import com.github.dockerjava.api.command.AttachContainerCmd; +import com.github.dockerjava.api.command.AuthCmd; +import com.github.dockerjava.api.command.BuildImageCmd; +import com.github.dockerjava.api.command.CommitCmd; +import com.github.dockerjava.api.command.ContainerDiffCmd; +import com.github.dockerjava.api.command.CopyFileFromContainerCmd; +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.command.CreateImageCmd; +import com.github.dockerjava.api.command.DockerCmdExecFactory; +import com.github.dockerjava.api.command.EventCallback; +import com.github.dockerjava.api.command.EventsCmd; +import com.github.dockerjava.api.command.ExecCreateCmd; +import com.github.dockerjava.api.command.ExecStartCmd; +import com.github.dockerjava.api.command.InfoCmd; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectImageCmd; +import com.github.dockerjava.api.command.KillContainerCmd; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.command.ListImagesCmd; +import com.github.dockerjava.api.command.LogContainerCmd; +import com.github.dockerjava.api.command.PauseContainerCmd; +import com.github.dockerjava.api.command.PingCmd; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.command.PushImageCmd; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.command.RemoveImageCmd; +import com.github.dockerjava.api.command.RestartContainerCmd; +import com.github.dockerjava.api.command.SearchImagesCmd; +import com.github.dockerjava.api.command.StartContainerCmd; +import com.github.dockerjava.api.command.StopContainerCmd; +import com.github.dockerjava.api.command.TagImageCmd; +import com.github.dockerjava.api.command.TopContainerCmd; +import com.github.dockerjava.api.command.UnpauseContainerCmd; +import com.github.dockerjava.api.command.VersionCmd; +import com.github.dockerjava.api.command.WaitContainerCmd; import com.github.dockerjava.api.model.AuthConfig; -import com.github.dockerjava.core.command.*; -import com.google.common.base.Preconditions; +import com.github.dockerjava.core.command.AttachContainerCmdImpl; +import com.github.dockerjava.core.command.AuthCmdImpl; +import com.github.dockerjava.core.command.BuildImageCmdImpl; +import com.github.dockerjava.core.command.CommitCmdImpl; +import com.github.dockerjava.core.command.ContainerDiffCmdImpl; +import com.github.dockerjava.core.command.CopyFileFromContainerCmdImpl; +import com.github.dockerjava.core.command.CreateContainerCmdImpl; +import com.github.dockerjava.core.command.CreateImageCmdImpl; +import com.github.dockerjava.core.command.EventsCmdImpl; +import com.github.dockerjava.core.command.ExecCreateCmdImpl; +import com.github.dockerjava.core.command.ExecStartCmdImpl; +import com.github.dockerjava.core.command.InfoCmdImpl; +import com.github.dockerjava.core.command.InspectContainerCmdImpl; +import com.github.dockerjava.core.command.InspectImageCmdImpl; +import com.github.dockerjava.core.command.KillContainerCmdImpl; +import com.github.dockerjava.core.command.ListContainersCmdImpl; +import com.github.dockerjava.core.command.ListImagesCmdImpl; +import com.github.dockerjava.core.command.LogContainerCmdImpl; +import com.github.dockerjava.core.command.PauseContainerCmdImpl; +import com.github.dockerjava.core.command.PingCmdImpl; +import com.github.dockerjava.core.command.PullImageCmdImpl; +import com.github.dockerjava.core.command.PushImageCmdImpl; +import com.github.dockerjava.core.command.RemoveContainerCmdImpl; +import com.github.dockerjava.core.command.RemoveImageCmdImpl; +import com.github.dockerjava.core.command.RestartContainerCmdImpl; +import com.github.dockerjava.core.command.SearchImagesCmdImpl; +import com.github.dockerjava.core.command.StartContainerCmdImpl; +import com.github.dockerjava.core.command.StopContainerCmdImpl; +import com.github.dockerjava.core.command.TagImageCmdImpl; +import com.github.dockerjava.core.command.TopContainerCmdImpl; +import com.github.dockerjava.core.command.UnpauseContainerCmdImpl; +import com.github.dockerjava.core.command.VersionCmdImpl; +import com.github.dockerjava.core.command.WaitContainerCmdImpl; /** * @author Konstantin Pelykh (kpelykh@gmail.com) @@ -33,7 +98,7 @@ private DockerClientImpl(String serverUrl) { } private DockerClientImpl(DockerClientConfig dockerClientConfig) { - Preconditions.checkNotNull(dockerClientConfig, + checkNotNull(dockerClientConfig, "config was not specified"); this.dockerClientConfig = dockerClientConfig; } @@ -58,7 +123,7 @@ public static DockerClientImpl getInstance(String serverUrl) { public DockerClientImpl withDockerCmdExecFactory( DockerCmdExecFactory dockerCmdExecFactory) { - Preconditions.checkNotNull(dockerCmdExecFactory, + checkNotNull(dockerCmdExecFactory, "dockerCmdExecFactory was not specified"); this.dockerCmdExecFactory = dockerCmdExecFactory; this.dockerCmdExecFactory.init(dockerClientConfig); @@ -66,7 +131,7 @@ public DockerClientImpl withDockerCmdExecFactory( } private DockerCmdExecFactory getDockerCmdExecFactory() { - Preconditions.checkNotNull(dockerCmdExecFactory, + checkNotNull(dockerCmdExecFactory, "dockerCmdExecFactory was not specified"); return dockerCmdExecFactory; } diff --git a/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java b/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java index 269b8765..fe5e6509 100644 --- a/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java +++ b/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java @@ -1,7 +1,6 @@ package com.github.dockerjava.core; -import com.google.common.base.Objects; -import com.google.common.base.Preconditions; +import static com.github.dockerjava.Preconditions.checkNotNull; import java.io.File; import java.io.FileInputStream; @@ -35,7 +34,7 @@ public class KeystoreSSLConfig implements SSLConfig, Serializable { */ public KeystoreSSLConfig(KeyStore keystore, String keystorePassword) { this.keystorePassword = keystorePassword; - Preconditions.checkNotNull(keystore); + checkNotNull(keystore); this.keystore = keystore; } @@ -50,8 +49,8 @@ public KeystoreSSLConfig(KeyStore keystore, String keystorePassword) { */ public KeystoreSSLConfig(File pfxFile, String password) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { - Preconditions.checkNotNull(pfxFile); - Preconditions.checkNotNull(password); + checkNotNull(pfxFile); + checkNotNull(password); keystore = KeyStore.getInstance("pkcs12"); keystore.load(new FileInputStream(pfxFile), password.toCharArray()); keystorePassword = password; @@ -126,8 +125,10 @@ public int hashCode() { @Override public String toString() { - return Objects.toStringHelper(this) - .add("keystore", keystore) + return new StringBuilder() + .append(this.getClass().getSimpleName()).append("{") + .append("keystore=").append(keystore) + .append("}") .toString(); } } diff --git a/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java b/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java index 6415d0c1..d60db72c 100644 --- a/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java +++ b/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java @@ -1,16 +1,18 @@ package com.github.dockerjava.core; -import com.github.dockerjava.api.DockerClientException; -import com.google.common.base.Objects; -import com.google.common.base.Preconditions; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.glassfish.jersey.SslConfigurator; +import static com.github.dockerjava.Preconditions.checkNotNull; -import javax.net.ssl.SSLContext; import java.io.Serializable; -import java.security.KeyStore; import java.security.Security; +import javax.net.ssl.SSLContext; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.glassfish.jersey.SslConfigurator; + +import com.github.dockerjava.api.DockerClientException; + + /** * SSL Config from local files. */ @@ -19,7 +21,7 @@ public class LocalDirectorySSLConfig implements SSLConfig, Serializable { private final String dockerCertPath; public LocalDirectorySSLConfig(String dockerCertPath) { - Preconditions.checkNotNull(dockerCertPath); + checkNotNull(dockerCertPath); this.dockerCertPath = dockerCertPath; } @@ -88,8 +90,10 @@ public int hashCode() { @Override public String toString() { - return Objects.toStringHelper(this) - .add("dockerCertPath", dockerCertPath) + return new StringBuilder() + .append(this.getClass().getSimpleName()).append("{") + .append("dockerCertPath=").append(dockerCertPath) + .append("}") .toString(); } } diff --git a/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java index 96e92da4..8069ed6b 100644 --- a/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java @@ -1,17 +1,16 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import java.io.IOException; -import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.codec.binary.Base64; +import com.fasterxml.jackson.databind.ObjectMapper; import com.github.dockerjava.api.command.DockerCmd; import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.model.AuthConfig; -import com.google.common.base.Preconditions; - -import org.apache.commons.codec.binary.Base64; - public abstract class AbstrAuthCfgDockerCmd, RES_T> extends AbstrDockerCmd { @@ -31,7 +30,7 @@ public AuthConfig getAuthConfig() { } public T withAuthConfig(AuthConfig authConfig) { - Preconditions.checkNotNull(authConfig, "authConfig was not specified"); + checkNotNull(authConfig, "authConfig was not specified"); return withOptionalAuthConfig(authConfig); } diff --git a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java index 54312c50..ed289c98 100644 --- a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java @@ -1,5 +1,7 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import java.io.IOException; import org.slf4j.Logger; @@ -8,7 +10,6 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.command.DockerCmd; import com.github.dockerjava.api.command.DockerCmdExec; -import com.google.common.base.Preconditions; public abstract class AbstrDockerCmd, RES_T> implements DockerCmd { @@ -17,7 +18,7 @@ public abstract class AbstrDockerCmd, RES_T> impl protected DockerCmdExec execution; public AbstrDockerCmd(DockerCmdExec execution) { - Preconditions.checkNotNull(execution, "execution was not specified"); + checkNotNull(execution, "execution was not specified"); this.execution = execution; } diff --git a/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java index 930fbdfd..6ac220c0 100644 --- a/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java @@ -1,12 +1,12 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import java.io.InputStream; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.AttachContainerCmd; -import com.google.common.base.Preconditions; - /** * Attach to container * @@ -66,7 +66,7 @@ public boolean hasStderrEnabled() { @Override public AttachContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index ec3406b1..b2286bc8 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -1,5 +1,9 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkArgument; +import static com.github.dockerjava.Preconditions.checkNotNull; +import static com.github.dockerjava.Preconditions.checkState; + import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -24,7 +28,6 @@ import com.github.dockerjava.core.GoLangFileMatch; import com.github.dockerjava.core.GoLangFileMatchException; import com.github.dockerjava.core.GoLangMatchFileFilter; -import com.google.common.base.Preconditions; /** * @@ -49,7 +52,7 @@ public class BuildImageCmdImpl extends public BuildImageCmdImpl(BuildImageCmd.Exec exec, File dockerFolder) { super(exec); - Preconditions.checkNotNull(dockerFolder, "dockerFolder is null"); + checkNotNull(dockerFolder, "dockerFolder is null"); tarFile = buildDockerFolderTar(dockerFolder); try { withTarInputStream(FileUtils.openInputStream(tarFile)); @@ -61,7 +64,7 @@ public BuildImageCmdImpl(BuildImageCmd.Exec exec, File dockerFolder) { public BuildImageCmdImpl(BuildImageCmd.Exec exec, InputStream tarInputStream) { super(exec); - Preconditions.checkNotNull(tarInputStream, "tarInputStream is null"); + checkNotNull(tarInputStream, "tarInputStream is null"); withTarInputStream(tarInputStream); } @@ -72,14 +75,14 @@ public InputStream getTarInputStream() { @Override public BuildImageCmdImpl withTarInputStream(InputStream tarInputStream) { - Preconditions.checkNotNull(tarInputStream, "tarInputStream is null"); + checkNotNull(tarInputStream, "tarInputStream is null"); this.tarInputStream = tarInputStream; return this; } @Override public BuildImageCmdImpl withTag(String tag) { - Preconditions.checkNotNull(tag, "Tag is null"); + checkNotNull(tag, "Tag is null"); this.tag = tag; return this; } @@ -157,11 +160,11 @@ public String toString() { } protected File buildDockerFolderTar(File dockerFolder) { - Preconditions.checkArgument(dockerFolder.exists(), + checkArgument(dockerFolder.exists(), "Path %s doesn't exist", dockerFolder); - Preconditions.checkArgument(dockerFolder.isDirectory(), + checkArgument(dockerFolder.isDirectory(), "Folder %s doesn't exist", dockerFolder); - Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(), + checkState(new File(dockerFolder, "Dockerfile").exists(), "Dockerfile doesn't exist in " + dockerFolder); // ARCHIVE TAR diff --git a/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java index ee9c4db6..6ba3d4a3 100644 --- a/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java @@ -1,15 +1,15 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import org.apache.commons.lang.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonProperty; - import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CommitCmd; import com.github.dockerjava.api.model.ExposedPorts; import com.github.dockerjava.api.model.Volumes; -import com.google.common.base.Preconditions; /** * @@ -86,7 +86,7 @@ public String getContainerId() { @Override public CommitCmdImpl withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } @@ -152,7 +152,7 @@ public CommitCmdImpl withAttachStdout() { @Override public CommitCmdImpl withCmd(String... cmd) { - Preconditions.checkNotNull(cmd, "cmd was not specified"); + checkNotNull(cmd, "cmd was not specified"); this.cmd = cmd; return this; } @@ -165,28 +165,28 @@ public CommitCmdImpl withDisableNetwork(boolean disableNetwork) { @Override public CommitCmdImpl withAuthor(String author) { - Preconditions.checkNotNull(author, "author was not specified"); + checkNotNull(author, "author was not specified"); this.author = author; return this; } @Override public CommitCmdImpl withMessage(String message) { - Preconditions.checkNotNull(message, "message was not specified"); + checkNotNull(message, "message was not specified"); this.message = message; return this; } @Override public CommitCmdImpl withTag(String tag) { - Preconditions.checkNotNull(tag, "tag was not specified"); + checkNotNull(tag, "tag was not specified"); this.tag = tag; return this; } @Override public CommitCmdImpl withRepository(String repository) { - Preconditions.checkNotNull(repository, "repository was not specified"); + checkNotNull(repository, "repository was not specified"); this.repository = repository; return this; } @@ -204,7 +204,7 @@ public String[] getEnv() { @Override public CommitCmdImpl withEnv(String... env) { - Preconditions.checkNotNull(env, "env was not specified"); + checkNotNull(env, "env was not specified"); this.env = env; return this; } @@ -216,7 +216,7 @@ public ExposedPorts getExposedPorts() { @Override public CommitCmdImpl withExposedPorts(ExposedPorts exposedPorts) { - Preconditions.checkNotNull(exposedPorts, "exposedPorts was not specified"); + checkNotNull(exposedPorts, "exposedPorts was not specified"); this.exposedPorts = exposedPorts; return this; } @@ -228,7 +228,7 @@ public String getHostname() { @Override public CommitCmdImpl withHostname(String hostname) { - Preconditions.checkNotNull(hostname, "hostname was not specified"); + checkNotNull(hostname, "hostname was not specified"); this.hostname = hostname; return this; } @@ -240,7 +240,7 @@ public Integer getMemory() { @Override public CommitCmdImpl withMemory(Integer memory) { - Preconditions.checkNotNull(memory, "memory was not specified"); + checkNotNull(memory, "memory was not specified"); this.memory = memory; return this; } @@ -252,7 +252,7 @@ public Integer getMemorySwap() { @Override public CommitCmdImpl withMemorySwap(Integer memorySwap) { - Preconditions.checkNotNull(memorySwap, "memorySwap was not specified"); + checkNotNull(memorySwap, "memorySwap was not specified"); this.memorySwap = memorySwap; return this; } @@ -264,7 +264,7 @@ public boolean isOpenStdin() { @Override public CommitCmdImpl withOpenStdin(boolean openStdin) { - Preconditions.checkNotNull(openStdin, "openStdin was not specified"); + checkNotNull(openStdin, "openStdin was not specified"); this.openStdin = openStdin; return this; } @@ -276,7 +276,7 @@ public String[] getPortSpecs() { @Override public CommitCmdImpl withPortSpecs(String... portSpecs) { - Preconditions.checkNotNull(portSpecs, "portSpecs was not specified"); + checkNotNull(portSpecs, "portSpecs was not specified"); this.portSpecs = portSpecs; return this; } @@ -320,7 +320,7 @@ public String getUser() { @Override public CommitCmdImpl withUser(String user) { - Preconditions.checkNotNull(user, "user was not specified"); + checkNotNull(user, "user was not specified"); this.user = user; return this; } @@ -332,7 +332,7 @@ public Volumes getVolumes() { @Override public CommitCmdImpl withVolumes(Volumes volumes) { - Preconditions.checkNotNull(volumes, "volumes was not specified"); + checkNotNull(volumes, "volumes was not specified"); this.volumes = volumes; return this; } @@ -344,7 +344,7 @@ public String getWorkingDir() { @Override public CommitCmdImpl withWorkingDir(String workingDir) { - Preconditions.checkNotNull(workingDir, "workingDir was not specified"); + checkNotNull(workingDir, "workingDir was not specified"); this.workingDir = workingDir; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java index f6a414b1..68293107 100644 --- a/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java @@ -1,5 +1,7 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import java.util.List; import com.github.dockerjava.api.DockerException; @@ -8,8 +10,6 @@ import com.github.dockerjava.api.command.ContainerDiffCmd; import com.github.dockerjava.api.model.ChangeLog; -import com.google.common.base.Preconditions; - /** * Inspect changes on a container's filesystem * @@ -32,7 +32,7 @@ public String getContainerId() { @Override public ContainerDiffCmdImpl withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java index 929b6bf5..2d91bb72 100644 --- a/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java @@ -1,15 +1,15 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import java.io.InputStream; import org.apache.commons.lang.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonProperty; - import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CopyFileFromContainerCmd; -import com.google.common.base.Preconditions; /** * @@ -44,14 +44,14 @@ public String getResource() { @Override public CopyFileFromContainerCmdImpl withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } @Override public CopyFileFromContainerCmdImpl withResource(String resource) { - Preconditions.checkNotNull(resource, "resource was not specified"); + checkNotNull(resource, "resource was not specified"); this.resource = resource; return this; } @@ -63,7 +63,7 @@ public String getHostPath() { @Override public CopyFileFromContainerCmdImpl withHostPath(String hostPath) { - Preconditions.checkNotNull(hostPath, "hostPath was not specified"); + checkNotNull(hostPath, "hostPath was not specified"); this.hostPath = hostPath; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index b8cde7fe..ea6d721e 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -1,5 +1,7 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import org.apache.commons.lang.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -14,7 +16,7 @@ import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Volume; import com.github.dockerjava.api.model.Volumes; -import com.google.common.base.Preconditions; + /** * @@ -49,13 +51,13 @@ public class CreateContainerCmdImpl extends AbstrDockerCmd implements ExecCreateCmd { @@ -31,7 +32,7 @@ public ExecCreateCmdImpl(ExecCreateCmd.Exec exec, String containerId) { } public ExecCreateCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java index 3b21f9b2..8f9028d2 100644 --- a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java @@ -1,11 +1,12 @@ package com.github.dockerjava.core.command; -import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.command.ExecStartCmd; -import com.google.common.base.Preconditions; +import static com.github.dockerjava.Preconditions.checkNotNull; import java.io.InputStream; +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.ExecStartCmd; + public class ExecStartCmdImpl extends AbstrDockerCmd implements ExecStartCmd { private String execId; @@ -24,7 +25,7 @@ public String getExecId() { @Override public ExecStartCmd withExecId(String execId) { - Preconditions.checkNotNull(execId, "execId was not specified"); + checkNotNull(execId, "execId was not specified"); this.execId = execId; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java index 0fd55b76..f48101b8 100644 --- a/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java @@ -1,11 +1,11 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectContainerResponse; -import com.google.common.base.Preconditions; - /** * Inspect the details of a container. */ @@ -25,7 +25,7 @@ public String getContainerId() { @Override public InspectContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java index b52b15d5..11a0ea7f 100644 --- a/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java @@ -1,10 +1,11 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.InspectImageCmd; import com.github.dockerjava.api.command.InspectImageResponse; -import com.google.common.base.Preconditions; /** * Inspect the details of an image. @@ -25,7 +26,7 @@ public String getImageId() { @Override public InspectImageCmd withImageId(String imageId) { - Preconditions.checkNotNull(imageId, "imageId was not specified"); + checkNotNull(imageId, "imageId was not specified"); this.imageId = imageId; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java index f8ca070f..ccc7b58b 100644 --- a/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java @@ -1,9 +1,10 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.KillContainerCmd; -import com.google.common.base.Preconditions; /** * Kill a running container. @@ -29,14 +30,14 @@ public String getSignal() { @Override public KillContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } @Override public KillContainerCmd withSignal(String signal) { - Preconditions.checkNotNull(signal, "signal was not specified"); + checkNotNull(signal, "signal was not specified"); this.signal = signal; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java index c2ebd491..5bfe61af 100644 --- a/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java @@ -1,11 +1,13 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkArgument; +import static com.github.dockerjava.Preconditions.checkNotNull; + import java.util.List; import com.github.dockerjava.api.command.ListContainersCmd; import com.github.dockerjava.api.model.Container; -import com.google.common.base.Preconditions; /** * List containers @@ -68,21 +70,21 @@ public ListContainersCmd withShowSize(boolean showSize) { @Override public ListContainersCmd withLimit(int limit) { - Preconditions.checkArgument(limit > 0, "limit must be greater 0"); + checkArgument(limit > 0, "limit must be greater 0"); this.limit = limit; return this; } @Override public ListContainersCmd withSince(String since) { - Preconditions.checkNotNull(since, "since was not specified"); + checkNotNull(since, "since was not specified"); this.sinceId = since; return this; } @Override public ListContainersCmd withBefore(String before) { - Preconditions.checkNotNull(before, "before was not specified"); + checkNotNull(before, "before was not specified"); this.beforeId = before; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java index 451a0ac5..01c5eb01 100644 --- a/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java @@ -1,12 +1,12 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import java.util.List; import com.github.dockerjava.api.command.ListImagesCmd; import com.github.dockerjava.api.model.Image; -import com.google.common.base.Preconditions; - /** * List images * @@ -41,7 +41,7 @@ public ListImagesCmd withShowAll(boolean showAll) { @Override public ListImagesCmd withFilters(String filter) { - Preconditions.checkNotNull(filter, "filters have not been specified"); + checkNotNull(filter, "filters have not been specified"); this.filters = filter; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java index 26c9a3b0..b71a149c 100644 --- a/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java @@ -1,12 +1,12 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import java.io.InputStream; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.LogContainerCmd; -import com.google.common.base.Preconditions; - /** * Get container logs * @@ -67,7 +67,7 @@ public boolean hasStderrEnabled() { @Override public LogContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java index fa6b816f..4d8702b1 100644 --- a/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java @@ -1,10 +1,10 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.PauseContainerCmd; -import com.google.common.base.Preconditions; - /** * Pause a container. * @@ -27,7 +27,7 @@ public String getContainerId() { @Override public PauseContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java index bcd3613b..b4cde794 100644 --- a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java @@ -1,11 +1,12 @@ package com.github.dockerjava.core.command; -import com.github.dockerjava.api.command.PullImageCmd; -import com.github.dockerjava.api.model.AuthConfig; -import com.google.common.base.Preconditions; +import static com.github.dockerjava.Preconditions.checkNotNull; import java.io.InputStream; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.model.AuthConfig; + /** * * Pull image from repository. @@ -37,21 +38,21 @@ public String getRegistry() { @Override public PullImageCmd withRepository(String repository) { - Preconditions.checkNotNull(repository, "repository was not specified"); + checkNotNull(repository, "repository was not specified"); this.repository = repository; return this; } @Override public PullImageCmd withTag(String tag) { - Preconditions.checkNotNull(tag, "tag was not specified"); + checkNotNull(tag, "tag was not specified"); this.tag = tag; return this; } @Override public PullImageCmd withRegistry(String registry) { - Preconditions.checkNotNull(registry, "registry was not specified"); + checkNotNull(registry, "registry was not specified"); this.registry = registry; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java index 56f58715..2a279550 100644 --- a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java @@ -1,12 +1,12 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import java.io.InputStream; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.PushImageCmd; -import com.google.common.base.Preconditions; - /** * Push the latest image to the repository. * @@ -37,7 +37,7 @@ public String getTag() { */ @Override public PushImageCmd withName(String name) { - Preconditions.checkNotNull(name, "name was not specified"); + checkNotNull(name, "name was not specified"); this.name = name; return this; } @@ -47,7 +47,7 @@ public PushImageCmd withName(String name) { */ @Override public PushImageCmd withTag(String tag) { - Preconditions.checkNotNull(tag, "tag was not specified"); + checkNotNull(tag, "tag was not specified"); this.tag = tag; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java index 31344fdb..84d7cc12 100644 --- a/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java @@ -1,10 +1,10 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.RemoveContainerCmd; -import com.google.common.base.Preconditions; - /** * Remove a container. * @@ -39,7 +39,7 @@ public boolean hasForceEnabled() { @Override public RemoveContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java index dda905fe..6e7f4fb1 100644 --- a/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java @@ -1,10 +1,10 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.RemoveImageCmd; -import com.google.common.base.Preconditions; - /** * * Remove an image, deleting any tags it might have. @@ -38,7 +38,7 @@ public boolean hasNoPruneEnabled() { @Override public RemoveImageCmd withImageId(String imageId) { - Preconditions.checkNotNull(imageId, "imageId was not specified"); + checkNotNull(imageId, "imageId was not specified"); this.imageId = imageId; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java index f82a65b6..0f105e53 100644 --- a/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java @@ -1,10 +1,11 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkArgument; +import static com.github.dockerjava.Preconditions.checkNotNull; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.RestartContainerCmd; -import com.google.common.base.Preconditions; - /** * Restart a running container. * @@ -34,14 +35,14 @@ public int getTimeout() { @Override public RestartContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } @Override public RestartContainerCmd withtTimeout(int timeout) { - Preconditions.checkArgument(timeout >= 0, "timeout must be greater or equal 0"); + checkArgument(timeout >= 0, "timeout must be greater or equal 0"); this.timeout = timeout; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java index 3ca878f1..7462cdbd 100644 --- a/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java @@ -1,12 +1,12 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import java.util.List; import com.github.dockerjava.api.command.SearchImagesCmd; import com.github.dockerjava.api.model.SearchItem; -import com.google.common.base.Preconditions; - /** * Search images * @@ -29,7 +29,7 @@ public String getTerm() { @Override public SearchImagesCmd withTerm(String term) { - Preconditions.checkNotNull(term, "term was not specified"); + checkNotNull(term, "term was not specified"); this.term = term; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index 63ff4ff0..1ca2124d 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -1,6 +1,7 @@ package com.github.dockerjava.core.command; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY; +import static com.github.dockerjava.Preconditions.checkNotNull; import org.apache.commons.lang.builder.ToStringBuilder; @@ -20,7 +21,7 @@ import com.github.dockerjava.api.model.PortBinding; import com.github.dockerjava.api.model.Ports; import com.github.dockerjava.api.model.RestartPolicy; -import com.google.common.base.Preconditions; + /** * Start a container @@ -158,7 +159,7 @@ public Capability[] getCapDrop() { @Override @JsonIgnore public StartContainerCmd withBinds(Bind... binds) { - Preconditions.checkNotNull(binds, "binds was not specified"); + checkNotNull(binds, "binds was not specified"); this.binds = new Binds(binds); return this; } @@ -166,21 +167,21 @@ public StartContainerCmd withBinds(Bind... binds) { @Override @JsonIgnore public StartContainerCmd withLinks(Link... links) { - Preconditions.checkNotNull(links, "links was not specified"); + checkNotNull(links, "links was not specified"); this.links = new Links(links); return this; } @Override public StartContainerCmd withLxcConf(LxcConf... lxcConf) { - Preconditions.checkNotNull(lxcConf, "lxcConf was not specified"); + checkNotNull(lxcConf, "lxcConf was not specified"); this.lxcConf = lxcConf; return this; } @Override public StartContainerCmd withPortBindings(Ports portBindings) { - Preconditions.checkNotNull(portBindings, + checkNotNull(portBindings, "portBindings was not specified"); this.portBindings = portBindings; return this; @@ -188,7 +189,7 @@ public StartContainerCmd withPortBindings(Ports portBindings) { @Override public StartContainerCmd withPortBindings(PortBinding... portBindings) { - Preconditions.checkNotNull(portBindings, "portBindings was not specified"); + checkNotNull(portBindings, "portBindings was not specified"); if (this.portBindings == null) { this.portBindings = new Ports(); } @@ -210,65 +211,63 @@ public StartContainerCmd withPublishAllPorts(Boolean publishAllPorts) { @Override public StartContainerCmd withDns(String... dns) { - Preconditions.checkNotNull(dns, "dns was not specified"); + checkNotNull(dns, "dns was not specified"); this.dns = dns; return this; } @Override public StartContainerCmd withDnsSearch(String... dnsSearch) { - Preconditions.checkNotNull(dnsSearch, "dnsSearch was not specified"); + checkNotNull(dnsSearch, "dnsSearch was not specified"); this.dnsSearch = dnsSearch; return this; } @Override public StartContainerCmd withVolumesFrom(String volumesFrom) { - Preconditions - .checkNotNull(volumesFrom, "volumesFrom was not specified"); + checkNotNull(volumesFrom, "volumesFrom was not specified"); this.volumesFrom = volumesFrom; return this; } @Override public StartContainerCmd withContainerId(String containerId) { - Preconditions - .checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } @Override public StartContainerCmd withNetworkMode(String networkMode) { - Preconditions.checkNotNull(networkMode, "networkMode was not specified"); + checkNotNull(networkMode, "networkMode was not specified"); this.networkMode = networkMode; return this; } @Override public StartContainerCmd withDevices(Device... devices) { - Preconditions.checkNotNull(devices, "devices was not specified"); + checkNotNull(devices, "devices was not specified"); this.devices = devices; return this; } @Override public StartContainerCmd withRestartPolicy(RestartPolicy restartPolicy) { - Preconditions.checkNotNull(restartPolicy, "restartPolicy was not specified"); + checkNotNull(restartPolicy, "restartPolicy was not specified"); this.restartPolicy = restartPolicy; return this; } @Override public StartContainerCmd withCapAdd(Capability... capAdd) { - Preconditions.checkNotNull(capAdd, "capAdd was not specified"); + checkNotNull(capAdd, "capAdd was not specified"); this.capAdd = capAdd; return this; } @Override public StartContainerCmd withCapDrop(Capability... capDrop) { - Preconditions.checkNotNull(capDrop, "capDrop was not specified"); + checkNotNull(capDrop, "capDrop was not specified"); this.capDrop = capDrop; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java index 7033cad6..26372b9f 100644 --- a/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java @@ -1,11 +1,12 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkArgument; +import static com.github.dockerjava.Preconditions.checkNotNull; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; import com.github.dockerjava.api.command.StopContainerCmd; -import com.google.common.base.Preconditions; - /** * Stop a running container. * @@ -36,14 +37,14 @@ public int getTimeout() { @Override public StopContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } @Override public StopContainerCmd withTimeout(int timeout) { - Preconditions.checkArgument(timeout >= 0, "timeout must be greater or equal 0"); + checkArgument(timeout >= 0, "timeout must be greater or equal 0"); this.timeout = timeout; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java index fe981218..cdcc7450 100644 --- a/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java @@ -1,8 +1,9 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import com.github.dockerjava.api.command.TagImageCmd; -import com.google.common.base.Preconditions; /** * Tag an image into a repository @@ -47,21 +48,21 @@ public boolean hasForceEnabled() { @Override public TagImageCmd withImageId(String imageId) { - Preconditions.checkNotNull(imageId, "imageId was not specified"); + checkNotNull(imageId, "imageId was not specified"); this.imageId = imageId; return this; } @Override public TagImageCmd withRepository(String repository) { - Preconditions.checkNotNull(repository, "repository was not specified"); + checkNotNull(repository, "repository was not specified"); this.repository = repository; return this; } @Override public TagImageCmd withTag(String tag) { - Preconditions.checkNotNull(tag, "tag was not specified"); + checkNotNull(tag, "tag was not specified"); this.tag = tag; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java index 92b82523..c49698cf 100644 --- a/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java @@ -1,11 +1,11 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.TopContainerCmd; import com.github.dockerjava.api.command.TopContainerResponse; -import com.google.common.base.Preconditions; - /** * List processes running inside a container */ @@ -32,7 +32,7 @@ public String getPsArgs() { @Override public TopContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } @@ -40,7 +40,7 @@ public TopContainerCmd withContainerId(String containerId) { @Override public TopContainerCmd withPsArgs(String psArgs) { - Preconditions.checkNotNull(psArgs, "psArgs was not specified"); + checkNotNull(psArgs, "psArgs was not specified"); this.psArgs = psArgs; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java index 3ecc0acb..97d12eaa 100644 --- a/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java @@ -1,10 +1,10 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.UnpauseContainerCmd; -import com.google.common.base.Preconditions; - /** * Unpause a container. * @@ -27,7 +27,7 @@ public String getContainerId() { @Override public UnpauseContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } diff --git a/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java index 80baf2cc..c5952e53 100644 --- a/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java @@ -1,7 +1,8 @@ package com.github.dockerjava.core.command; +import static com.github.dockerjava.Preconditions.checkNotNull; + import com.github.dockerjava.api.command.WaitContainerCmd; -import com.google.common.base.Preconditions; /** * Wait a container @@ -24,7 +25,7 @@ public String getContainerId() { @Override public WaitContainerCmd withContainerId(String containerId) { - Preconditions.checkNotNull(containerId, "containerId was not specified"); + checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java index 727055f9..4e63d8a4 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java @@ -1,5 +1,7 @@ package com.github.dockerjava.jaxrs; +import static com.github.dockerjava.Preconditions.checkNotNull; + import java.io.IOException; import javax.ws.rs.ProcessingException; @@ -8,21 +10,18 @@ import org.apache.commons.codec.binary.Base64; import com.fasterxml.jackson.databind.ObjectMapper; - import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.command.DockerCmd; import com.github.dockerjava.api.command.DockerCmdExec; import com.github.dockerjava.api.model.AuthConfig; -import com.google.common.base.Preconditions; - public abstract class AbstrDockerCmdExec, RES_T> implements DockerCmdExec { private WebTarget baseResource; public AbstrDockerCmdExec(WebTarget baseResource) { - Preconditions.checkNotNull(baseResource, + checkNotNull(baseResource, "baseResource was not specified"); this.baseResource = baseResource; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/ApacheUnixSocket.java b/src/main/java/com/github/dockerjava/jaxrs/ApacheUnixSocket.java index a4adb1bb..23d6d1ab 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ApacheUnixSocket.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ApacheUnixSocket.java @@ -22,10 +22,6 @@ -import com.google.common.collect.Queues; - -import org.newsclub.net.unix.AFUNIXSocket; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -34,8 +30,11 @@ import java.net.SocketAddress; import java.net.SocketException; import java.nio.channels.SocketChannel; +import java.util.ArrayDeque; import java.util.Queue; +import org.newsclub.net.unix.AFUNIXSocket; + /** * Provides a socket that wraps an org.newsclub.net.unix.AFUNIXSocket and delays setting options * until the socket is connected. This is necessary because the Apache HTTP client attempts to @@ -50,7 +49,7 @@ public class ApacheUnixSocket extends Socket { private final AFUNIXSocket inner; - private final Queue optionsToSet = Queues.newArrayDeque(); + private final Queue optionsToSet = new ArrayDeque(); public ApacheUnixSocket() throws IOException { this.inner = AFUNIXSocket.newInstance(); diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index c91b0d56..3f59a283 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -1,13 +1,16 @@ package com.github.dockerjava.jaxrs; -import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; -import com.github.dockerjava.api.DockerClientException; -import com.github.dockerjava.api.command.*; -import com.github.dockerjava.core.DockerClientConfig; -import com.github.dockerjava.jaxrs.util.JsonClientFilter; -import com.github.dockerjava.jaxrs.util.ResponseStatusExceptionFilter; -import com.github.dockerjava.jaxrs.util.SelectiveLoggingFilter; -import com.google.common.base.Preconditions; +import static com.github.dockerjava.Preconditions.checkNotNull; + +import java.io.IOException; +import java.net.URI; +import java.util.logging.Logger; + +import javax.net.ssl.SSLContext; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; + import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; @@ -19,13 +22,46 @@ import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; -import javax.net.ssl.SSLContext; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import java.io.IOException; -import java.net.URI; -import java.util.logging.Logger; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import com.github.dockerjava.api.DockerClientException; +import com.github.dockerjava.api.command.AttachContainerCmd; +import com.github.dockerjava.api.command.AuthCmd; +import com.github.dockerjava.api.command.BuildImageCmd; +import com.github.dockerjava.api.command.CommitCmd; +import com.github.dockerjava.api.command.ContainerDiffCmd; +import com.github.dockerjava.api.command.CopyFileFromContainerCmd; +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.command.CreateImageCmd; +import com.github.dockerjava.api.command.DockerCmdExecFactory; +import com.github.dockerjava.api.command.EventsCmd; +import com.github.dockerjava.api.command.ExecCreateCmd; +import com.github.dockerjava.api.command.ExecStartCmd; +import com.github.dockerjava.api.command.InfoCmd; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectImageCmd; +import com.github.dockerjava.api.command.KillContainerCmd; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.command.ListImagesCmd; +import com.github.dockerjava.api.command.LogContainerCmd; +import com.github.dockerjava.api.command.PauseContainerCmd; +import com.github.dockerjava.api.command.PingCmd; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.command.PushImageCmd; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.command.RemoveImageCmd; +import com.github.dockerjava.api.command.RestartContainerCmd; +import com.github.dockerjava.api.command.SearchImagesCmd; +import com.github.dockerjava.api.command.StartContainerCmd; +import com.github.dockerjava.api.command.StopContainerCmd; +import com.github.dockerjava.api.command.TagImageCmd; +import com.github.dockerjava.api.command.TopContainerCmd; +import com.github.dockerjava.api.command.UnpauseContainerCmd; +import com.github.dockerjava.api.command.VersionCmd; +import com.github.dockerjava.api.command.WaitContainerCmd; +import com.github.dockerjava.core.DockerClientConfig; +import com.github.dockerjava.jaxrs.util.JsonClientFilter; +import com.github.dockerjava.jaxrs.util.ResponseStatusExceptionFilter; +import com.github.dockerjava.jaxrs.util.SelectiveLoggingFilter; public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { @@ -35,7 +71,7 @@ public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { @Override public void init(DockerClientConfig dockerClientConfig) { - Preconditions.checkNotNull(dockerClientConfig, "config was not specified"); + checkNotNull(dockerClientConfig, "config was not specified"); ClientConfig clientConfig = new ClientConfig(); clientConfig.connectorProvider(new ApacheConnectorProvider()); @@ -99,7 +135,7 @@ private org.apache.http.config.Registry getSchemeRegist } protected WebTarget getBaseResource() { - Preconditions.checkNotNull(baseResource, "Factory not initialized. You probably forgot to call init()!"); + checkNotNull(baseResource, "Factory not initialized. You probably forgot to call init()!"); return baseResource; } @@ -270,7 +306,7 @@ public EventsCmd.Exec createEventsCmdExec() { @Override public void close() throws IOException { - Preconditions.checkNotNull(client, "Factory not initialized. You probably forgot to call init()!"); + checkNotNull(client, "Factory not initialized. You probably forgot to call init()!"); client.close(); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java index ffd757e9..ba15e995 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -1,10 +1,18 @@ package com.github.dockerjava.jaxrs; +import static com.github.dockerjava.Preconditions.checkNotNull; + import java.io.InputStream; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; @@ -12,13 +20,6 @@ import com.github.dockerjava.api.command.EventCallback; import com.github.dockerjava.api.command.EventsCmd; import com.github.dockerjava.api.model.Event; -import com.google.common.base.Preconditions; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; public class EventsCmdExec extends AbstrDockerCmdExec implements EventsCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(EventsCmdExec.class); @@ -54,8 +55,8 @@ private EventNotifier(EventCallback eventCallback, WebTarget webTarget) { } public static EventNotifier create(EventCallback eventCallback, WebTarget webTarget) { - Preconditions.checkNotNull(eventCallback, "An EventCallback must be provided"); - Preconditions.checkNotNull(webTarget, "An WebTarget must be provided"); + checkNotNull(eventCallback, "An EventCallback must be provided"); + checkNotNull(webTarget, "An WebTarget must be provided"); return new EventNotifier(eventCallback, webTarget); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java index 1fe38617..84ede89b 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java @@ -1,20 +1,19 @@ package com.github.dockerjava.jaxrs; +import static com.github.dockerjava.jaxrs.util.guava.Guava.urlPathSegmentEscaper; + import java.util.List; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; -import com.google.common.net.UrlEscapers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.api.command.ListImagesCmd; import com.github.dockerjava.api.model.Image; -import static com.google.common.net.UrlEscapers.urlPathSegmentEscaper; - public class ListImagesCmdExec extends AbstrDockerCmdExec> implements ListImagesCmd.Exec { diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java index 7f7e06c7..42898008 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java @@ -1,6 +1,8 @@ package com.github.dockerjava.jaxrs.util; import java.io.IOException; +import java.util.Collections; +import java.util.HashSet; import java.util.Set; import java.util.logging.Logger; @@ -8,8 +10,6 @@ import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; -import com.google.common.collect.ImmutableSet; - import org.glassfish.jersey.filter.LoggingFilter; /** @@ -21,10 +21,15 @@ */ public class SelectiveLoggingFilter extends LoggingFilter { - private static final Set SKIPPED_CONTENT = ImmutableSet.builder() - .add(MediaType.APPLICATION_OCTET_STREAM) - .add("application/tar") - .build(); + // Immutable'ish + private static final Set SKIPPED_CONTENT; + static { + Set s = new HashSet(); + s.add(MediaType.APPLICATION_OCTET_STREAM); + s.add("application/tar"); + SKIPPED_CONTENT = Collections.unmodifiableSet(s); + } + public SelectiveLoggingFilter(Logger logger, boolean b) { super(logger, b); diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/guava/Guava.java b/src/main/java/com/github/dockerjava/jaxrs/util/guava/Guava.java new file mode 100644 index 00000000..13f87142 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/util/guava/Guava.java @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2008 The Guava Authors + * + * Licensed 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.github.dockerjava.jaxrs.util.guava; + +public class Guava { + + static final String URL_PATH_OTHER_SAFE_CHARS_LACKING_PLUS = + "-._~" + // Unreserved characters. + "!$'()*,;&=" + // The subdelim characters (excluding '+'). + "@:"; // The gendelim characters permitted in paths. + + public static PercentEscaper urlPathSegmentEscaper() { + return URL_PATH_SEGMENT_ESCAPER; + } + + private static final PercentEscaper URL_PATH_SEGMENT_ESCAPER = + new PercentEscaper(URL_PATH_OTHER_SAFE_CHARS_LACKING_PLUS + "+", false); + + public static String join(String[] joins, String sep, boolean skipNulls) { + StringBuilder sb = new StringBuilder(); + for(int i = 0; i < joins.length; i++) { + if(skipNulls && joins[i] == null) { + continue; + } + sb.append(joins[i]); + if(i < joins.length -1) { + sb.append(sep); + } + } + return sb.toString(); + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/guava/PercentEscaper.java b/src/main/java/com/github/dockerjava/jaxrs/util/guava/PercentEscaper.java new file mode 100644 index 00000000..b8c2b271 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/util/guava/PercentEscaper.java @@ -0,0 +1,245 @@ +/* + * Copyright (C) 2008 The Guava Authors + * + * Licensed 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.github.dockerjava.jaxrs.util.guava; + +import com.github.dockerjava.Preconditions; + +/** + * A {@code UnicodeEscaper} that escapes some set of Java characters using a + * UTF-8 based percent encoding scheme. The set of safe characters (those which + * remain unescaped) can be specified on construction. + * + *

This class is primarily used for creating URI escapers in UrlEscapers + * but can be used directly if required. While URI escapers impose + * specific semantics on which characters are considered 'safe', this class has + * a minimal set of restrictions. + * + *

When escaping a String, the following rules apply: + *

    + *
  • All specified safe characters remain unchanged. + *
  • If {@code plusForSpace} was specified, the space character " " is + * converted into a plus sign {@code "+"}. + *
  • All other characters are converted into one or more bytes using UTF-8 + * encoding and each byte is then represented by the 3-character string + * "%XX", where "XX" is the two-digit, uppercase, hexadecimal representation + * of the byte value. + *
+ * + *

For performance reasons the only currently supported character encoding of + * this class is UTF-8. + * + *

Note: This escaper produces uppercase hexadecimal sequences. From + * RFC 3986:
+ * "URI producers and normalizers should use uppercase hexadecimal digits + * for all percent-encodings." + * + * @author David Beaumont + * @since 15.0 + */ +public final class PercentEscaper extends UnicodeEscaper { + + // In some escapers spaces are escaped to '+' + private static final char[] PLUS_SIGN = { '+' }; + + // Percent escapers output upper case hex digits (uri escapers require this). + private static final char[] UPPER_HEX_DIGITS = + "0123456789ABCDEF".toCharArray(); + + /** + * If true we should convert space to the {@code +} character. + */ + private final boolean plusForSpace; + + /** + * An array of flags where for any {@code char c} if {@code safeOctets[c]} is + * true then {@code c} should remain unmodified in the output. If + * {@code c > safeOctets.length} then it should be escaped. + */ + private final boolean[] safeOctets; + + /** + * Constructs a percent escaper with the specified safe characters and + * optional handling of the space character. + * + *

Not that it is allowed, but not necessarily desirable to specify {@code %} + * as a safe character. This has the effect of creating an escaper which has no + * well defined inverse but it can be useful when escaping additional characters. + * + * @param safeChars a non null string specifying additional safe characters + * for this escaper (the ranges 0..9, a..z and A..Z are always safe and + * should not be specified here) + * @param plusForSpace true if ASCII space should be escaped to {@code +} + * rather than {@code %20} + * @throws IllegalArgumentException if any of the parameters were invalid + */ + public PercentEscaper(String safeChars, boolean plusForSpace) { + // TODO(user): Switch to static factory methods for creation now that class is final. + // TODO(user): Support escapers where alphanumeric chars are not safe. + Preconditions.checkNotNull(safeChars); // eager for GWT. + // Avoid any misunderstandings about the behavior of this escaper + if (safeChars.matches(".*[0-9A-Za-z].*")) { + throw new IllegalArgumentException( + "Alphanumeric characters are always 'safe' and should not be " + + "explicitly specified"); + } + safeChars += "abcdefghijklmnopqrstuvwxyz" + + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + "0123456789"; + // Avoid ambiguous parameters. Safe characters are never modified so if + // space is a safe character then setting plusForSpace is meaningless. + if (plusForSpace && safeChars.contains(" ")) { + throw new IllegalArgumentException( + "plusForSpace cannot be specified when space is a 'safe' character"); + } + this.plusForSpace = plusForSpace; + this.safeOctets = createSafeOctets(safeChars); + } + + /** + * Creates a boolean array with entries corresponding to the character values + * specified in safeChars set to true. The array is as small as is required to + * hold the given character information. + */ + private static boolean[] createSafeOctets(String safeChars) { + int maxChar = -1; + char[] safeCharArray = safeChars.toCharArray(); + for (char c : safeCharArray) { + maxChar = Math.max(c, maxChar); + } + boolean[] octets = new boolean[maxChar + 1]; + for (char c : safeCharArray) { + octets[c] = true; + } + return octets; + } + + /* + * Overridden for performance. For unescaped strings this improved the + * performance of the uri escaper from ~760ns to ~400ns as measured by + * CharEscapersBenchmark. + */ + @Override + protected int nextEscapeIndex(CharSequence csq, int index, int end) { + Preconditions.checkNotNull(csq); + for (; index < end; index++) { + char c = csq.charAt(index); + if (c >= safeOctets.length || !safeOctets[c]) { + break; + } + } + return index; + } + + /* + * Overridden for performance. For unescaped strings this improved the + * performance of the uri escaper from ~400ns to ~170ns as measured by + * CharEscapersBenchmark. + */ + @Override + public String escape(String s) { + Preconditions.checkNotNull(s); + int slen = s.length(); + for (int index = 0; index < slen; index++) { + char c = s.charAt(index); + if (c >= safeOctets.length || !safeOctets[c]) { + return escapeSlow(s, index); + } + } + return s; + } + + /** + * Escapes the given Unicode code point in UTF-8. + */ + @Override + protected char[] escape(int cp) { + // We should never get negative values here but if we do it will throw an + // IndexOutOfBoundsException, so at least it will get spotted. + if (cp < safeOctets.length && safeOctets[cp]) { + return null; + } else if (cp == ' ' && plusForSpace) { + return PLUS_SIGN; + } else if (cp <= 0x7F) { + // Single byte UTF-8 characters + // Start with "%--" and fill in the blanks + char[] dest = new char[3]; + dest[0] = '%'; + dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; + dest[1] = UPPER_HEX_DIGITS[cp >>> 4]; + return dest; + } else if (cp <= 0x7ff) { + // Two byte UTF-8 characters [cp >= 0x80 && cp <= 0x7ff] + // Start with "%--%--" and fill in the blanks + char[] dest = new char[6]; + dest[0] = '%'; + dest[3] = '%'; + dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; + cp >>>= 2; + dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[1] = UPPER_HEX_DIGITS[0xC | cp]; + return dest; + } else if (cp <= 0xffff) { + // Three byte UTF-8 characters [cp >= 0x800 && cp <= 0xffff] + // Start with "%E-%--%--" and fill in the blanks + char[] dest = new char[9]; + dest[0] = '%'; + dest[1] = 'E'; + dest[3] = '%'; + dest[6] = '%'; + dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; + cp >>>= 2; + dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; + cp >>>= 2; + dest[2] = UPPER_HEX_DIGITS[cp]; + return dest; + } else if (cp <= 0x10ffff) { + char[] dest = new char[12]; + // Four byte UTF-8 characters [cp >= 0xffff && cp <= 0x10ffff] + // Start with "%F-%--%--%--" and fill in the blanks + dest[0] = '%'; + dest[1] = 'F'; + dest[3] = '%'; + dest[6] = '%'; + dest[9] = '%'; + dest[11] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[10] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; + cp >>>= 2; + dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; + cp >>>= 2; + dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; + cp >>>= 2; + dest[2] = UPPER_HEX_DIGITS[cp & 0x7]; + return dest; + } else { + // If this ever happens it is due to bug in UnicodeEscaper, not bad input. + throw new IllegalArgumentException( + "Invalid unicode character value " + cp); + } + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/guava/UnicodeEscaper.java b/src/main/java/com/github/dockerjava/jaxrs/util/guava/UnicodeEscaper.java new file mode 100644 index 00000000..a5823948 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/util/guava/UnicodeEscaper.java @@ -0,0 +1,304 @@ +/* + * Copyright (C) 2008 The Guava Authors + * + * Licensed 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.github.dockerjava.jaxrs.util.guava; + + +import com.github.dockerjava.Preconditions; + +/** + * An Escaper that converts literal text into a format safe for + * inclusion in a particular context (such as an XML document). Typically (but + * not always), the inverse process of "unescaping" the text is performed + * automatically by the relevant parser. + * + *

For example, an XML escaper would convert the literal string {@code + * "Foo"} into {@code "Foo<Bar>"} to prevent {@code ""} from + * being confused with an XML tag. When the resulting XML document is parsed, + * the parser API will return this text as the original literal string {@code + * "Foo"}. + * + *

Note: This class is similar to CharEscaper but with one + * very important difference. A CharEscaper can only process Java + * UTF16 characters in + * isolation and may not cope when it encounters surrogate pairs. This class + * facilitates the correct escaping of all Unicode characters. + * + *

As there are important reasons, including potential security issues, to + * handle Unicode correctly if you are considering implementing a new escaper + * you should favor using UnicodeEscaper wherever possible. + * + *

A {@code UnicodeEscaper} instance is required to be stateless, and safe + * when used concurrently by multiple threads. + * + *

Several popular escapers are defined as constants in classes like + * com.google.common.html.HtmlEscapers, com.google.common.xml.XmlEscapers, + * and SourceCodeEscapers. To create + * your own escapers extend this class and implement the #escape(int) + * method. + * + * @author David Beaumont + * @since 15.0 + */ +public abstract class UnicodeEscaper { + /** The amount of padding (chars) to use when growing the escape buffer. */ + private static final int DEST_PAD = 32; + + /** Constructor for use by subclasses. */ + protected UnicodeEscaper() {} + + /** + * Returns the escaped form of the given Unicode code point, or {@code null} + * if this code point does not need to be escaped. When called as part of an + * escaping operation, the given code point is guaranteed to be in the range + * {@code 0 <= cp <= Character#MAX_CODE_POINT}. + * + *

If an empty array is returned, this effectively strips the input + * character from the resulting text. + * + *

If the character does not need to be escaped, this method should return + * {@code null}, rather than an array containing the character representation + * of the code point. This enables the escaping algorithm to perform more + * efficiently. + * + *

If the implementation of this method cannot correctly handle a + * particular code point then it should either throw an appropriate runtime + * exception or return a suitable replacement character. It must never + * silently discard invalid input as this may constitute a security risk. + * + * @param cp the Unicode code point to escape if necessary + * @return the replacement characters, or {@code null} if no escaping was + * needed + */ + protected abstract char[] escape(int cp); + + /** + * Scans a sub-sequence of characters from a given CharSequence, + * returning the index of the next character that requires escaping. + * + *

Note: When implementing an escaper, it is a good idea to override + * this method for efficiency. The base class implementation determines + * successive Unicode code points and invokes #escape(int) for each of + * them. If the semantics of your escaper are such that code points in the + * supplementary range are either all escaped or all unescaped, this method + * can be implemented more efficiently using CharSequence#charAt(int). + * + *

Note however that if your escaper does not escape characters in the + * supplementary range, you should either continue to validate the correctness + * of any surrogate characters encountered or provide a clear warning to users + * that your escaper does not validate its input. + * + *

See com.google.common.net.PercentEscaper for an example. + * + * @param csq a sequence of characters + * @param start the index of the first character to be scanned + * @param end the index immediately after the last character to be scanned + * @throws IllegalArgumentException if the scanned sub-sequence of {@code csq} + * contains invalid surrogate pairs + */ + protected int nextEscapeIndex(CharSequence csq, int start, int end) { + int index = start; + while (index < end) { + int cp = codePointAt(csq, index, end); + if (cp < 0 || escape(cp) != null) { + break; + } + index += Character.isSupplementaryCodePoint(cp) ? 2 : 1; + } + return index; + } + + /** + * Returns the escaped form of a given literal string. + * + *

If you are escaping input in arbitrary successive chunks, then it is not + * generally safe to use this method. If an input string ends with an + * unmatched high surrogate character, then this method will throw + * IllegalArgumentException. You should ensure your input is valid UTF-16 before calling this + * method. + * + *

Note: When implementing an escaper it is a good idea to override + * this method for efficiency by inlining the implementation of + * #nextEscapeIndex(CharSequence, int, int) directly. Doing this for + * com.google.common.net.PercentEscaper more than doubled the + * performance for unescaped strings (as measured by CharEscapersBenchmark}. + * + * @param string the literal string to be escaped + * @return the escaped form of {@code string} + * @throws NullPointerException if {@code string} is null + * @throws IllegalArgumentException if invalid surrogate characters are + * encountered + */ + public String escape(String string) { + Preconditions.checkNotNull(string); + int end = string.length(); + int index = nextEscapeIndex(string, 0, end); + return index == end ? string : escapeSlow(string, index); + } + + /** + * Returns the escaped form of a given literal string, starting at the given + * index. This method is called by the #escape(String) method when it + * discovers that escaping is required. It is protected to allow subclasses + * to override the fastpath escaping function to inline their escaping test. + * See CharEscaperBuilder for an example usage. + * + *

This method is not reentrant and may only be invoked by the top level + * #escape(String) method. + * + * @param s the literal string to be escaped + * @param index the index to start escaping from + * @return the escaped form of {@code string} + * @throws NullPointerException if {@code string} is null + * @throws IllegalArgumentException if invalid surrogate characters are + * encountered + */ + protected final String escapeSlow(String s, int index) { + int end = s.length(); + + // Get a destination buffer and setup some loop variables. + char[] dest = new char[1024]; + int destIndex = 0; + int unescapedChunkStart = 0; + + while (index < end) { + int cp = codePointAt(s, index, end); + if (cp < 0) { + throw new IllegalArgumentException( + "Trailing high surrogate at end of input"); + } + // It is possible for this to return null because nextEscapeIndex() may + // (for performance reasons) yield some false positives but it must never + // give false negatives. + char[] escaped = escape(cp); + int nextIndex = index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1); + if (escaped != null) { + int charsSkipped = index - unescapedChunkStart; + + // This is the size needed to add the replacement, not the full + // size needed by the string. We only regrow when we absolutely must. + int sizeNeeded = destIndex + charsSkipped + escaped.length; + if (dest.length < sizeNeeded) { + int destLength = sizeNeeded + (end - index) + DEST_PAD; + dest = growBuffer(dest, destIndex, destLength); + } + // If we have skipped any characters, we need to copy them now. + if (charsSkipped > 0) { + s.getChars(unescapedChunkStart, index, dest, destIndex); + destIndex += charsSkipped; + } + if (escaped.length > 0) { + System.arraycopy(escaped, 0, dest, destIndex, escaped.length); + destIndex += escaped.length; + } + // If we dealt with an escaped character, reset the unescaped range. + unescapedChunkStart = nextIndex; + } + index = nextEscapeIndex(s, nextIndex, end); + } + + // Process trailing unescaped characters - no need to account for escaped + // length or padding the allocation. + int charsSkipped = end - unescapedChunkStart; + if (charsSkipped > 0) { + int endIndex = destIndex + charsSkipped; + if (dest.length < endIndex) { + dest = growBuffer(dest, destIndex, endIndex); + } + s.getChars(unescapedChunkStart, end, dest, destIndex); + destIndex = endIndex; + } + return new String(dest, 0, destIndex); + } + + /** + * Returns the Unicode code point of the character at the given index. + * + *

Unlike Character#codePointAt(CharSequence, int) or + * String#codePointAt(int) this method will never fail silently when + * encountering an invalid surrogate pair. + * + *

The behaviour of this method is as follows: + *

    + *
  1. If {@code index >= end}, IndexOutOfBoundsException is thrown. + *
  2. If the character at the specified index is not a surrogate, it is + * returned. + *
  3. If the first character was a high surrogate value, then an attempt is + * made to read the next character. + *
      + *
    1. If the end of the sequence was reached, the negated value of + * the trailing high surrogate is returned. + *
    2. If the next character was a valid low surrogate, the code point + * value of the high/low surrogate pair is returned. + *
    3. If the next character was not a low surrogate value, then + * IllegalArgumentException is thrown. + *
    + *
  4. If the first character was a low surrogate value, + * IllegalArgumentException is thrown. + *
+ * + * @param seq the sequence of characters from which to decode the code point + * @param index the index of the first character to decode + * @param end the index beyond the last valid character to decode + * @return the Unicode code point for the given index or the negated value of + * the trailing high surrogate character at the end of the sequence + */ + protected static int codePointAt(CharSequence seq, int index, int end) { + Preconditions.checkNotNull(seq); + if (index < end) { + char c1 = seq.charAt(index++); + if (c1 < Character.MIN_HIGH_SURROGATE || + c1 > Character.MAX_LOW_SURROGATE) { + // Fast path (first test is probably all we need to do) + return c1; + } else if (c1 <= Character.MAX_HIGH_SURROGATE) { + // If the high surrogate was the last character, return its inverse + if (index == end) { + return -c1; + } + // Otherwise look for the low surrogate following it + char c2 = seq.charAt(index); + if (Character.isLowSurrogate(c2)) { + return Character.toCodePoint(c1, c2); + } + throw new IllegalArgumentException( + "Expected low surrogate but got char '" + c2 + + "' with value " + (int) c2 + " at index " + index + + " in '" + seq + "'"); + } else { + throw new IllegalArgumentException( + "Unexpected low surrogate character '" + c1 + + "' with value " + (int) c1 + " at index " + (index - 1) + + " in '" + seq + "'"); + } + } + throw new IndexOutOfBoundsException("Index exceeds specified range"); + } + + /** + * Helper method to grow the character buffer as needed, this only happens + * once in a while so it's ok if it's in a method call. If the index passed + * in is 0 then no copying will be done. + */ + private static char[] growBuffer(char[] dest, int index, int size) { + char[] copy = new char[size]; + if (index > 0) { + System.arraycopy(dest, 0, copy, 0, index); + } + return copy; + } +} From 6c4ab6a18e00a8cd97e03d49d4681610a6b7e526 Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 27 Jan 2015 17:32:44 +0100 Subject: [PATCH 283/452] Update to latest unix-socket-factory * Removes transitive dep on groovy-all --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 4a9af78d..4bc6b719 100644 --- a/pom.xml +++ b/pom.xml @@ -64,7 +64,7 @@ 0.3 18.0 1.51 - 2014-11-16T14-41-27 + 2015-01-27T15-02-14 1.0.1 From a19dc6b6a30615e1f1b9361193e98b47c08ac5bc Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Tue, 27 Jan 2015 20:27:00 +0100 Subject: [PATCH 284/452] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b0d2c6c..fbf6d65c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ Change Log docker-java-0.10.6-SNAPSHOT --- + * [#135](https://github.com/docker-java/docker-java/pull/135) Update to latest unix-socket-factory + * [#134](https://github.com/docker-java/docker-java/pull/134) Remove Google Guava as dependency * [#128](https://github.com/docker-java/docker-java/pull/128) Allow unauthorized pullImageCmd docker-java-0.10.5 From 5a7e79c0f7750d0e5ddc3937c493138d2bbd8ffe Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 27 Jan 2015 21:33:24 +0100 Subject: [PATCH 285/452] Fix some CFX interoperability issues --- .../command/CopyFileFromContainerCmdImpl.java | 14 - .../jaxrs/AttachContainerCmdExec.java | 33 +- .../dockerjava/jaxrs/ExecCreateCmdExec.java | 5 +- .../dockerjava/jaxrs/ExecStartCmdExec.java | 5 +- .../jaxrs/KillContainerCmdExec.java | 19 +- .../jaxrs/PauseContainerCmdExec.java | 21 +- .../dockerjava/jaxrs/PullImageCmdExec.java | 52 +-- .../dockerjava/jaxrs/PushImageCmdExec.java | 29 +- .../jaxrs/RestartContainerCmdExec.java | 16 +- .../jaxrs/StopContainerCmdExec.java | 13 +- .../dockerjava/jaxrs/TagImageCmdExec.java | 6 +- .../jaxrs/WaitContainerCmdExec.java | 4 +- .../dockerjava/jaxrs/util/LoggingFilter.java | 330 ++++++++++++++++++ .../jaxrs/util/SelectiveLoggingFilter.java | 1 - 14 files changed, 436 insertions(+), 112 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java diff --git a/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java index 2d91bb72..fe1a57b6 100644 --- a/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java @@ -84,18 +84,4 @@ public String toString() { public InputStream exec() throws NotFoundException { return super.exec(); } - -// protected InputStream impl() throws DockerException { -// -// CopyFileFromContainerCmd command = this; -// -// WebTarget webResource = -// baseResource.path("/containers/{id}/copy").resolveTemplate("id", command.getContainerId()); -// -// LOGGER.trace("POST: " + webResource.toString()); -// -// return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(entity(command, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); -// } - - } diff --git a/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java index 5ed84c34..1fafd1f0 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java @@ -1,7 +1,5 @@ package com.github.dockerjava.jaxrs; -import static javax.ws.rs.client.Entity.entity; - import java.io.InputStream; import javax.ws.rs.client.WebTarget; @@ -13,29 +11,34 @@ import com.github.dockerjava.api.command.AttachContainerCmd; -public class AttachContainerCmdExec extends AbstrDockerCmdExec implements AttachContainerCmd.Exec { - +public class AttachContainerCmdExec extends + AbstrDockerCmdExec implements + AttachContainerCmd.Exec { + private static final Logger LOGGER = LoggerFactory .getLogger(AttachContainerCmdExec.class); - + public AttachContainerCmdExec(WebTarget baseResource) { super(baseResource); } @Override protected InputStream execute(AttachContainerCmd command) { - WebTarget webResource = getBaseResource().path("/containers/{id}/attach") - .resolveTemplate("id", command.getContainerId()) - .queryParam("logs", command.hasLogsEnabled() ? "1" : "0") - // .queryParam("stdin", command.hasStdinEnabled() ? "1" : "0") - .queryParam("stdout", command.hasStdoutEnabled() ? "1" : "0") - .queryParam("stderr", command.hasStderrEnabled() ? "1" : "0") - .queryParam("stream", command.hasFollowStreamEnabled() ? "1" : "0"); + WebTarget webResource = getBaseResource() + .path("/containers/{id}/attach") + .resolveTemplate("id", command.getContainerId()) + .queryParam("logs", command.hasLogsEnabled() ? "1" : "0") + // .queryParam("stdin", command.hasStdinEnabled() ? "1" : "0") + .queryParam("stdout", command.hasStdoutEnabled() ? "1" : "0") + .queryParam("stderr", command.hasStderrEnabled() ? "1" : "0") + .queryParam("stream", + command.hasFollowStreamEnabled() ? "1" : "0"); LOGGER.trace("POST: {}", webResource); - - return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .post(entity(null, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); + + return webResource.request() + .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .post(null, Response.class).readEntity(InputStream.class); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/ExecCreateCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ExecCreateCmdExec.java index 69346efd..02ea4d8a 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ExecCreateCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ExecCreateCmdExec.java @@ -25,6 +25,9 @@ protected ExecCreateCmdResponse execute(ExecCreateCmd command) { LOGGER.trace("POST: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command, MediaType.APPLICATION_JSON), ExecCreateCmdResponse.class); + return webResource + .request() + .accept(MediaType.APPLICATION_JSON) + .post(entity(command, MediaType.APPLICATION_JSON), ExecCreateCmdResponse.class); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java index ae4c7181..effd3904 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java @@ -26,6 +26,9 @@ protected InputStream execute(ExecStartCmd command) { LOGGER.trace("POST: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); + return webResource + .request() + .accept(MediaType.APPLICATION_JSON) + .post(entity(command, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java index 28496edc..21a6b9d6 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java @@ -1,7 +1,5 @@ package com.github.dockerjava.jaxrs; -import static javax.ws.rs.client.Entity.entity; - import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; @@ -10,25 +8,28 @@ import com.github.dockerjava.api.command.KillContainerCmd; -public class KillContainerCmdExec extends AbstrDockerCmdExec implements KillContainerCmd.Exec { - +public class KillContainerCmdExec extends + AbstrDockerCmdExec implements + KillContainerCmd.Exec { + private static final Logger LOGGER = LoggerFactory .getLogger(KillContainerCmdExec.class); - + public KillContainerCmdExec(WebTarget baseResource) { super(baseResource); } @Override protected Void execute(KillContainerCmd command) { - WebTarget webResource = getBaseResource().path("/containers/{id}/kill").resolveTemplate("id", command.getContainerId()); + WebTarget webResource = getBaseResource().path("/containers/{id}/kill") + .resolveTemplate("id", command.getContainerId()); - if(command.getSignal() != null) { + if (command.getSignal() != null) { webResource = webResource.queryParam("signal", command.getSignal()); } - + LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON)); + webResource.request().accept(MediaType.APPLICATION_JSON).post(null); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java index ee84a320..6b3eeaf0 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java @@ -1,19 +1,19 @@ package com.github.dockerjava.jaxrs; -import static javax.ws.rs.client.Entity.entity; - import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.api.command.PauseContainerCmd; -public class PauseContainerCmdExec extends AbstrDockerCmdExec implements PauseContainerCmd.Exec { +public class PauseContainerCmdExec extends + AbstrDockerCmdExec implements + PauseContainerCmd.Exec { - private static final Logger LOGGER = LoggerFactory.getLogger(PauseContainerCmdExec.class); + private static final Logger LOGGER = LoggerFactory + .getLogger(PauseContainerCmdExec.class); public PauseContainerCmdExec(WebTarget baseResource) { super(baseResource); @@ -21,13 +21,12 @@ public PauseContainerCmdExec(WebTarget baseResource) { @Override protected Void execute(PauseContainerCmd command) { - WebTarget webResource = getBaseResource().path("/containers/{id}/pause") - .resolveTemplate("id", command.getContainerId()); - + WebTarget webResource = getBaseResource() + .path("/containers/{id}/pause").resolveTemplate("id", + command.getContainerId()); + LOGGER.trace("POST: {}", webResource); - webResource.request() - .accept(MediaType.APPLICATION_JSON) - .post(entity(null, MediaType.APPLICATION_JSON), Response.class); + webResource.request().accept(MediaType.APPLICATION_JSON).post(null); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java index dea72f42..725483f8 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java @@ -1,22 +1,24 @@ package com.github.dockerjava.jaxrs; -import com.github.dockerjava.api.command.PullImageCmd; -import com.github.dockerjava.api.model.AuthConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.io.InputStream; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.InputStream; -import static javax.ws.rs.client.Entity.entity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.model.AuthConfig; + +public class PullImageCmdExec extends + AbstrDockerCmdExec implements + PullImageCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(PullImageCmdExec.class); -public class PullImageCmdExec extends AbstrDockerCmdExec implements PullImageCmd.Exec { - - private static final Logger LOGGER = LoggerFactory.getLogger(PullImageCmdExec.class); - public PullImageCmdExec(WebTarget baseResource) { super(baseResource); } @@ -24,22 +26,24 @@ public PullImageCmdExec(WebTarget baseResource) { @Override protected InputStream execute(PullImageCmd command) { WebTarget webResource = getBaseResource().path("/images/create") - .queryParam("tag", command.getTag()) - .queryParam("fromImage", command.getRepository()) - .queryParam("registry", command.getRegistry()); + .queryParam("tag", command.getTag()) + .queryParam("fromImage", command.getRepository()) + .queryParam("registry", command.getRegistry()); LOGGER.trace("POST: {}", webResource); - return resourceWithOptionalAuthConfig(command, webResource.request()) - .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .post(entity(Response.class, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); + return resourceWithOptionalAuthConfig(command, webResource.request()) + .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(null) + .readEntity(InputStream.class); } - private Invocation.Builder resourceWithOptionalAuthConfig(PullImageCmd command, Invocation.Builder request) { - AuthConfig authConfig = command.getAuthConfig(); - if (authConfig != null) { - request = request.header("X-Registry-Auth", registryAuth(authConfig)); - } - return request; - } + private Invocation.Builder resourceWithOptionalAuthConfig( + PullImageCmd command, Invocation.Builder request) { + AuthConfig authConfig = command.getAuthConfig(); + if (authConfig != null) { + request = request.header("X-Registry-Auth", + registryAuth(authConfig)); + } + return request; + } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java index 9454a0e7..b970d42f 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java @@ -1,12 +1,9 @@ package com.github.dockerjava.jaxrs; -import static javax.ws.rs.client.Entity.entity; - import java.io.InputStream; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,28 +11,30 @@ import com.github.dockerjava.api.command.PushImageCmd; import com.github.dockerjava.api.model.AuthConfig; -public class PushImageCmdExec extends AbstrDockerCmdExec implements PushImageCmd.Exec { - - private static final Logger LOGGER = LoggerFactory.getLogger(PushImageCmdExec.class); - +public class PushImageCmdExec extends + AbstrDockerCmdExec implements + PushImageCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(PushImageCmdExec.class); + public PushImageCmdExec(WebTarget baseResource) { super(baseResource); } @Override protected InputStream execute(PushImageCmd command) { - WebTarget webResource = getBaseResource().path("/images/" + name(command) + "/push") - .queryParam("tag", command.getTag()); + WebTarget webResource = getBaseResource().path( + "/images/" + name(command) + "/push").queryParam("tag", + command.getTag()); final String registryAuth = registryAuth(command.getAuthConfig()); LOGGER.trace("POST: {}", webResource); - return webResource - .request() - .header("X-Registry-Auth", registryAuth) - .accept(MediaType.APPLICATION_JSON) - .post(entity(Response.class, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); + return webResource.request().header("X-Registry-Auth", registryAuth) + .accept(MediaType.APPLICATION_JSON).post(null) + .readEntity(InputStream.class); } - + private String name(PushImageCmd command) { String name = command.getName(); AuthConfig authConfig = command.getAuthConfig(); diff --git a/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java index fe544f13..b08aa032 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java @@ -1,7 +1,5 @@ package com.github.dockerjava.jaxrs; -import static javax.ws.rs.client.Entity.entity; - import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; @@ -10,9 +8,12 @@ import com.github.dockerjava.api.command.RestartContainerCmd; -public class RestartContainerCmdExec extends AbstrDockerCmdExec implements RestartContainerCmd.Exec { +public class RestartContainerCmdExec extends + AbstrDockerCmdExec implements + RestartContainerCmd.Exec { - private static final Logger LOGGER = LoggerFactory.getLogger(RestartContainerCmdExec.class); + private static final Logger LOGGER = LoggerFactory + .getLogger(RestartContainerCmdExec.class); public RestartContainerCmdExec(WebTarget baseResource) { super(baseResource); @@ -20,12 +21,13 @@ public RestartContainerCmdExec(WebTarget baseResource) { @Override protected Void execute(RestartContainerCmd command) { - WebTarget webResource = getBaseResource().path("/containers/{id}/restart") + WebTarget webResource = getBaseResource() + .path("/containers/{id}/restart") .resolveTemplate("id", command.getContainerId()) .queryParam("t", String.valueOf(command.getTimeout())); - + LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON_TYPE)); + webResource.request().accept(MediaType.APPLICATION_JSON).post(null); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java index 337c71b2..956f3d0b 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java @@ -1,7 +1,5 @@ package com.github.dockerjava.jaxrs; -import static javax.ws.rs.client.Entity.entity; - import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; @@ -10,9 +8,12 @@ import com.github.dockerjava.api.command.StopContainerCmd; -public class StopContainerCmdExec extends AbstrDockerCmdExec implements StopContainerCmd.Exec { +public class StopContainerCmdExec extends + AbstrDockerCmdExec implements + StopContainerCmd.Exec { - private static final Logger LOGGER = LoggerFactory.getLogger(StopContainerCmdExec.class); + private static final Logger LOGGER = LoggerFactory + .getLogger(StopContainerCmdExec.class); public StopContainerCmdExec(WebTarget baseResource) { super(baseResource); @@ -23,9 +24,9 @@ protected Void execute(StopContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/stop") .resolveTemplate("id", command.getContainerId()) .queryParam("t", String.valueOf(command.getTimeout())); - + LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(null, MediaType.APPLICATION_JSON)); + webResource.request().accept(MediaType.APPLICATION_JSON).post(null); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java index d8545e33..b1c770ba 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java @@ -1,10 +1,6 @@ package com.github.dockerjava.jaxrs; -import static javax.ws.rs.client.Entity.entity; - import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,7 +24,7 @@ protected Void execute(TagImageCmd command) { .queryParam("force", command.hasForceEnabled() ? "1" : "0"); LOGGER.trace("POST: {}", webResource); - webResource.request().post(entity(null, MediaType.APPLICATION_JSON), Response.class); + webResource.request().post(null); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/WaitContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/WaitContainerCmdExec.java index e6f95586..1b81eee3 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/WaitContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/WaitContainerCmdExec.java @@ -1,7 +1,5 @@ package com.github.dockerjava.jaxrs; -import static javax.ws.rs.client.Entity.entity; - import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; @@ -27,7 +25,7 @@ protected Integer execute(WaitContainerCmd command) { LOGGER.trace("POST: {}", webResource); ObjectNode ObjectNode = webResource.request().accept(MediaType.APPLICATION_JSON) - .post(entity(null, MediaType.TEXT_PLAIN), ObjectNode.class); + .post(null, ObjectNode.class); return ObjectNode.get("StatusCode").asInt(); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java new file mode 100644 index 00000000..5a37720a --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java @@ -0,0 +1,330 @@ +package com.github.dockerjava.jaxrs.util; + +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2011-2014 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * http://glassfish.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.atomic.AtomicLong; +import java.util.logging.Logger; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.container.PreMatching; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.WriterInterceptor; +import javax.ws.rs.ext.WriterInterceptorContext; + +import javax.annotation.Priority; + + +/** + * Universal logging filter. + * + * Can be used on client or server side. Has the highest priority. + * + * @author Pavel Bucek (pavel.bucek at oracle.com) + * @author Martin Matula (martin.matula at oracle.com) + */ +@PreMatching +@Priority(Integer.MIN_VALUE) +@SuppressWarnings("ClassWithMultipleLoggers") +public class LoggingFilter implements ContainerRequestFilter, ClientRequestFilter, ContainerResponseFilter, + ClientResponseFilter, WriterInterceptor { + + private static final Logger LOGGER = Logger.getLogger(LoggingFilter.class.getName()); + private static final String NOTIFICATION_PREFIX = "* "; + private static final String REQUEST_PREFIX = "> "; + private static final String RESPONSE_PREFIX = "< "; + private static final String ENTITY_LOGGER_PROPERTY = LoggingFilter.class.getName() + ".entityLogger"; + + private static final Comparator>> COMPARATOR = + new Comparator>>() { + + @Override + public int compare(final Map.Entry> o1, final Map.Entry> o2) { + return o1.getKey().compareToIgnoreCase(o2.getKey()); + } + }; + + private static final int DEFAULT_MAX_ENTITY_SIZE = 8 * 1024; + + // + @SuppressWarnings("NonConstantLogger") + private final Logger logger; + private final AtomicLong _id = new AtomicLong(0); + private final boolean printEntity; + private final int maxEntitySize; + + /** + * Create a logging filter logging the request and response to a default JDK + * logger, named as the fully qualified class name of this class. Entity + * logging is turned off by default. + */ + public LoggingFilter() { + this(LOGGER, false); + } + + /** + * Create a logging filter with custom logger and custom settings of entity + * logging. + * + * @param logger the logger to log requests and responses. + * @param printEntity if true, entity will be logged as well up to the default maxEntitySize, which is 8KB + */ + @SuppressWarnings("BooleanParameter") + public LoggingFilter(final Logger logger, final boolean printEntity) { + this.logger = logger; + this.printEntity = printEntity; + this.maxEntitySize = DEFAULT_MAX_ENTITY_SIZE; + } + + /** + * Creates a logging filter with custom logger and entity logging turned on, but potentially limiting the size + * of entity to be buffered and logged. + * + * @param logger the logger to log requests and responses. + * @param maxEntitySize maximum number of entity bytes to be logged (and buffered) - if the entity is larger, + * logging filter will print (and buffer in memory) only the specified number of bytes + * and print "...more..." string at the end. + */ + public LoggingFilter(final Logger logger, final int maxEntitySize) { + this.logger = logger; + this.printEntity = true; + this.maxEntitySize = maxEntitySize; + } + + private void log(final StringBuilder b) { + if (logger != null) { + logger.info(b.toString()); + } + } + + private StringBuilder prefixId(final StringBuilder b, final long id) { + b.append(Long.toString(id)).append(" "); + return b; + } + + private void printRequestLine(final StringBuilder b, final String note, final long id, final String method, final URI uri) { + prefixId(b, id).append(NOTIFICATION_PREFIX) + .append(note) + .append(" on thread ").append(Thread.currentThread().getName()) + .append("\n"); + prefixId(b, id).append(REQUEST_PREFIX).append(method).append(" "). + append(uri.toASCIIString()).append("\n"); + } + + private void printResponseLine(final StringBuilder b, final String note, final long id, final int status) { + prefixId(b, id).append(NOTIFICATION_PREFIX) + .append(note) + .append(" on thread ").append(Thread.currentThread().getName()).append("\n"); + prefixId(b, id).append(RESPONSE_PREFIX). + append(Integer.toString(status)). + append("\n"); + } + + private void printPrefixedHeaders(final StringBuilder b, final long id, final String prefix, final MultivaluedMap headers) { + for (final Map.Entry> headerEntry : getSortedHeaders(headers.entrySet())) { + final List val = headerEntry.getValue(); + final String header = headerEntry.getKey(); + + if (val.size() == 1) { + prefixId(b, id).append(prefix).append(header).append(": ").append(val.get(0)).append("\n"); + } else { + final StringBuilder sb = new StringBuilder(); + boolean add = false; + for (final Object s : val) { + if (add) { + sb.append(','); + } + add = true; + sb.append(s); + } + prefixId(b, id).append(prefix).append(header).append(": ").append(sb.toString()).append("\n"); + } + } + } + + private Set>> getSortedHeaders(final Set>> headers) { + final TreeSet>> sortedHeaders = new TreeSet>>(COMPARATOR); + sortedHeaders.addAll(headers); + return sortedHeaders; + } + + private InputStream logInboundEntity(final StringBuilder b, InputStream stream) throws IOException { + if (!stream.markSupported()) { + stream = new BufferedInputStream(stream); + } + stream.mark(maxEntitySize + 1); + final byte[] entity = new byte[maxEntitySize + 1]; + final int entitySize = stream.read(entity); + b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize))); + if (entitySize > maxEntitySize) { + b.append("...more..."); + } + b.append('\n'); + stream.reset(); + return stream; + } + + @Override + public void filter(final ClientRequestContext context) throws IOException { + final long id = this._id.incrementAndGet(); + final StringBuilder b = new StringBuilder(); + + printRequestLine(b, "Sending client request", id, context.getMethod(), context.getUri()); + printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getStringHeaders()); + + if (printEntity && context.hasEntity()) { + final OutputStream stream = new LoggingStream(b, context.getEntityStream()); + context.setEntityStream(stream); + context.setProperty(ENTITY_LOGGER_PROPERTY, stream); + // not calling log(b) here - it will be called by the interceptor + } else { + log(b); + } + } + + @Override + public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext) throws IOException { + final long id = this._id.incrementAndGet(); + final StringBuilder b = new StringBuilder(); + + printResponseLine(b, "Client response received", id, responseContext.getStatus()); + printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getHeaders()); + + if (printEntity && responseContext.hasEntity()) { + responseContext.setEntityStream(logInboundEntity(b, responseContext.getEntityStream())); + } + + log(b); + } + + @Override + public void filter(final ContainerRequestContext context) throws IOException { + final long id = this._id.incrementAndGet(); + final StringBuilder b = new StringBuilder(); + + printRequestLine(b, "Server has received a request", id, context.getMethod(), context.getUriInfo().getRequestUri()); + printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getHeaders()); + + if (printEntity && context.hasEntity()) { + context.setEntityStream(logInboundEntity(b, context.getEntityStream())); + } + + log(b); + } + + @Override + public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) throws IOException { + final long id = this._id.incrementAndGet(); + final StringBuilder b = new StringBuilder(); + + printResponseLine(b, "Server responded with a response", id, responseContext.getStatus()); + printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getStringHeaders()); + + if (printEntity && responseContext.hasEntity()) { + final OutputStream stream = new LoggingStream(b, responseContext.getEntityStream()); + responseContext.setEntityStream(stream); + requestContext.setProperty(ENTITY_LOGGER_PROPERTY, stream); + // not calling log(b) here - it will be called by the interceptor + } else { + log(b); + } + } + + @Override + public void aroundWriteTo(final WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { + final LoggingStream stream = (LoggingStream) writerInterceptorContext.getProperty(ENTITY_LOGGER_PROPERTY); + writerInterceptorContext.proceed(); + if (stream != null) { + log(stream.getStringBuilder()); + } + } + + private class LoggingStream extends OutputStream { + private final StringBuilder b; + private final OutputStream inner; + private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + LoggingStream(final StringBuilder b, final OutputStream inner) { + this.b = b; + this.inner = inner; + } + + StringBuilder getStringBuilder() { + // write entity to the builder + final byte[] entity = baos.toByteArray(); + + b.append(new String(entity, 0, Math.min(entity.length, maxEntitySize))); + if (entity.length > maxEntitySize) { + b.append("...more..."); + } + b.append('\n'); + + return b; + } + + @Override + public void write(final int i) throws IOException { + if (baos.size() <= maxEntitySize) { + baos.write(i); + } + inner.write(i); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java index 42898008..9c577fd5 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java @@ -10,7 +10,6 @@ import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; -import org.glassfish.jersey.filter.LoggingFilter; /** * A version of the logging filter that will avoid trying to log entities which can cause From db4cf1d5821b8e6d96660f4af288b74e9e86155d Mon Sep 17 00:00:00 2001 From: Nuno Santos Date: Wed, 28 Jan 2015 13:49:47 +0100 Subject: [PATCH 286/452] Patched LoggingFilter to work with CXF. Added missing @Override tags. --- .../java/com/github/dockerjava/api/DockerClient.java | 1 + .../com/github/dockerjava/api/command/CommitCmd.java | 1 + .../dockerjava/api/command/ContainerDiffCmd.java | 2 ++ .../api/command/CopyFileFromContainerCmd.java | 1 + .../dockerjava/api/command/DockerCmdExecFactory.java | 1 + .../dockerjava/api/command/InspectContainerCmd.java | 1 + .../github/dockerjava/api/command/InspectImageCmd.java | 1 + .../dockerjava/api/command/KillContainerCmd.java | 1 + .../github/dockerjava/api/command/LogContainerCmd.java | 1 + .../dockerjava/api/command/PauseContainerCmd.java | 1 + .../github/dockerjava/api/command/PushImageCmd.java | 1 + .../dockerjava/api/command/RemoveContainerCmd.java | 1 + .../github/dockerjava/api/command/RemoveImageCmd.java | 1 + .../dockerjava/api/command/RestartContainerCmd.java | 1 + .../dockerjava/api/command/StartContainerCmd.java | 1 + .../dockerjava/api/command/StopContainerCmd.java | 1 + .../github/dockerjava/api/command/TopContainerCmd.java | 1 + .../dockerjava/api/command/UnpauseContainerCmd.java | 1 + .../java/com/github/dockerjava/api/model/Links.java | 1 - .../dockerjava/core/command/ExecCreateCmdImpl.java | 10 ++++++++++ .../github/dockerjava/jaxrs/AbstrDockerCmdExec.java | 1 + .../github/dockerjava/jaxrs/RemoveImageCmdExec.java | 1 - .../github/dockerjava/jaxrs/util/LoggingFilter.java | 2 +- .../core/command/WaitContainerCmdImplTest.java | 1 - 24 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index 53b21260..f7addfa2 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -105,6 +105,7 @@ public CopyFileFromContainerCmd copyFileFromContainerCmd( public EventsCmd eventsCmd(EventCallback eventCallback); + @Override public void close() throws IOException; } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/CommitCmd.java b/src/main/java/com/github/dockerjava/api/command/CommitCmd.java index 5eb5a3e8..ac0a7bb5 100644 --- a/src/main/java/com/github/dockerjava/api/command/CommitCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CommitCmd.java @@ -106,6 +106,7 @@ public interface CommitCmd extends DockerCmd{ /** * @throws NotFoundException No such container */ + @Override public String exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/ContainerDiffCmd.java b/src/main/java/com/github/dockerjava/api/command/ContainerDiffCmd.java index 516ea365..21d99045 100644 --- a/src/main/java/com/github/dockerjava/api/command/ContainerDiffCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/ContainerDiffCmd.java @@ -13,6 +13,7 @@ public interface ContainerDiffCmd extends DockerCmd> { public ContainerDiffCmd withContainerId(String containerId); + @Override public String toString(); /** @@ -20,6 +21,7 @@ public interface ContainerDiffCmd extends DockerCmd> { * @throws InternalServerErrorException server error * @throws DockerException unexpected http status code */ + @Override public List exec() throws NotFoundException; public static interface Exec extends DockerCmdExec> { diff --git a/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java index 0ebd3cc1..8d2bfbb4 100644 --- a/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java @@ -21,6 +21,7 @@ public interface CopyFileFromContainerCmd extends DockerCmd { /** * @throws NotFoundException No such container */ + @Override public InputStream exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java index df26743e..73381d69 100644 --- a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java +++ b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java @@ -75,6 +75,7 @@ public interface DockerCmdExecFactory extends Closeable { public EventsCmd.Exec createEventsCmdExec(); + @Override public void close() throws IOException; } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerCmd.java index ca6a9a69..f67fe4ae 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerCmd.java @@ -11,6 +11,7 @@ public interface InspectContainerCmd extends DockerCmd /** * @throws NotFoundException No such container */ + @Override public InspectContainerResponse exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/InspectImageCmd.java b/src/main/java/com/github/dockerjava/api/command/InspectImageCmd.java index f2523487..d064badb 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectImageCmd.java @@ -14,6 +14,7 @@ public interface InspectImageCmd extends DockerCmd{ /** * @throws NotFoundException No such image */ + @Override public InspectImageResponse exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/KillContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/KillContainerCmd.java index aff39f9e..b9522cb8 100644 --- a/src/main/java/com/github/dockerjava/api/command/KillContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/KillContainerCmd.java @@ -18,6 +18,7 @@ public interface KillContainerCmd extends DockerCmd { /** * @throws NotFoundException No such container */ + @Override public Void exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java index e0f20f9a..36a41beb 100644 --- a/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java @@ -58,6 +58,7 @@ public interface LogContainerCmd extends DockerCmd{ /** * @throws NotFoundException No such container */ + @Override public InputStream exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/PauseContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/PauseContainerCmd.java index a05733f9..652d433e 100644 --- a/src/main/java/com/github/dockerjava/api/command/PauseContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/PauseContainerCmd.java @@ -17,6 +17,7 @@ public interface PauseContainerCmd extends DockerCmd{ /** * @throws NotFoundException No such container */ + @Override public Void exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java b/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java index c746fd7c..f50beb01 100644 --- a/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java @@ -33,6 +33,7 @@ public interface PushImageCmd extends DockerCmd{ /** * @throws NotFoundException No such image */ + @Override public InputStream exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/RemoveContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/RemoveContainerCmd.java index be9b9d25..b9c1f943 100644 --- a/src/main/java/com/github/dockerjava/api/command/RemoveContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/RemoveContainerCmd.java @@ -27,6 +27,7 @@ public interface RemoveContainerCmd extends DockerCmd { /** * @throws NotFoundException No such container */ + @Override public Void exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java b/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java index 212c9290..be65ca41 100644 --- a/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/RemoveImageCmd.java @@ -41,6 +41,7 @@ public interface RemoveImageCmd extends DockerCmd{ /** * @throws NotFoundException No such image */ + @Override public Void exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/RestartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/RestartContainerCmd.java index 793919c2..8da41d38 100644 --- a/src/main/java/com/github/dockerjava/api/command/RestartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/RestartContainerCmd.java @@ -21,6 +21,7 @@ public interface RestartContainerCmd extends DockerCmd { /** * @throws NotFoundException No such container */ + @Override public Void exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index ef96267f..40fb23a9 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -135,6 +135,7 @@ public interface StartContainerCmd extends DockerCmd { * @throws NotModifiedException * Container already started */ + @Override public Void exec() throws NotFoundException, NotModifiedException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/StopContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StopContainerCmd.java index 7e706c06..19c24855 100644 --- a/src/main/java/com/github/dockerjava/api/command/StopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StopContainerCmd.java @@ -24,6 +24,7 @@ public interface StopContainerCmd extends DockerCmd { * @throws NotFoundException No such container * @throws NotModifiedException Container already stopped */ + @Override public Void exec() throws NotFoundException, NotModifiedException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/TopContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/TopContainerCmd.java index c7818a79..63865c2a 100644 --- a/src/main/java/com/github/dockerjava/api/command/TopContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/TopContainerCmd.java @@ -18,6 +18,7 @@ public interface TopContainerCmd extends DockerCmd { /** * @throws NotFoundException No such container */ + @Override public TopContainerResponse exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/command/UnpauseContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/UnpauseContainerCmd.java index e74df14c..166bfa6a 100644 --- a/src/main/java/com/github/dockerjava/api/command/UnpauseContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/UnpauseContainerCmd.java @@ -17,6 +17,7 @@ public interface UnpauseContainerCmd extends DockerCmd { /** * @throws NotFoundException No such container */ + @Override public Void exec() throws NotFoundException; public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/api/model/Links.java b/src/main/java/com/github/dockerjava/api/model/Links.java index d901ea8d..9bbef25d 100644 --- a/src/main/java/com/github/dockerjava/api/model/Links.java +++ b/src/main/java/com/github/dockerjava/api/model/Links.java @@ -5,7 +5,6 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.Map; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; diff --git a/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java index 219b789d..5819fa49 100644 --- a/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java @@ -31,48 +31,58 @@ public ExecCreateCmdImpl(ExecCreateCmd.Exec exec, String containerId) { withContainerId(containerId); } + @Override public ExecCreateCmd withContainerId(String containerId) { checkNotNull(containerId, "containerId was not specified"); this.containerId = containerId; return this; } + @Override public ExecCreateCmd withAttachStdin(boolean attachStdin) { this.attachStdin = attachStdin; return this; } + @Override public ExecCreateCmd withAttachStdin() { return withAttachStdin(true); } + @Override public ExecCreateCmd withAttachStdout(boolean attachStdout) { this.attachStdout = attachStdout; return this; } + @Override public ExecCreateCmd withAttachStdout() { return withAttachStdout(true); } + @Override public ExecCreateCmd withAttachStderr(boolean attachStderr) { this.attachStderr = attachStderr; return this; } + @Override public ExecCreateCmd withAttachStderr() { return withAttachStderr(true); } + @Override public ExecCreateCmd withTty(boolean tty) { this.tty = tty; return this; } + @Override public ExecCreateCmd withTty() { return withTty(true); } + @Override public ExecCreateCmd withCmd(String... cmd) { this.cmd = cmd; return this; diff --git a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java index 4e63d8a4..95c13b26 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java @@ -39,6 +39,7 @@ protected String registryAuth(AuthConfig authConfig) { } } + @Override public RES_T exec(CMD_T command) { // this hack works because of ResponseStatusExceptionFilter RES_T result; diff --git a/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java index 6bfeecd7..d5d7b800 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/RemoveImageCmdExec.java @@ -1,7 +1,6 @@ package com.github.dockerjava.jaxrs; import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java index 5a37720a..9679f230 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java @@ -211,7 +211,7 @@ private InputStream logInboundEntity(final StringBuilder b, InputStream stream) } stream.mark(maxEntitySize + 1); final byte[] entity = new byte[maxEntitySize + 1]; - final int entitySize = stream.read(entity); + final int entitySize = Math.max(0, stream.read(entity)); b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize))); if (entitySize > maxEntitySize) { b.append("...more..."); diff --git a/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java index 32434eea..19c7057d 100644 --- a/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/WaitContainerCmdImplTest.java @@ -16,7 +16,6 @@ import org.testng.annotations.Test; import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.api.InternalServerErrorException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; From 48ba911ee7c9c6ff834dcd839f9a3abc5d9ddc4c Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 28 Jan 2015 23:55:29 +0100 Subject: [PATCH 287/452] Multiple volumesFrom option when creating a container --- .../api/command/CreateContainerCmd.java | 5 +- .../dockerjava/api/model/AccessMode.java | 1 + .../com/github/dockerjava/api/model/Bind.java | 18 +--- .../dockerjava/api/model/HostConfig.java | 8 +- .../github/dockerjava/api/model/Volume.java | 17 ++-- .../dockerjava/api/model/VolumeFrom.java | 87 +++++++++++++++++++ .../github/dockerjava/api/model/Volumes.java | 2 +- .../dockerjava/api/model/VolumesFrom.java | 69 +++++++++++++++ .../core/command/CreateContainerCmdImpl.java | 10 ++- .../api/model/VolumeFrom_SerializingTest.java | 33 +++++++ .../command/CreateContainerCmdImplTest.java | 7 +- 11 files changed, 220 insertions(+), 37 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/VolumeFrom.java create mode 100644 src/main/java/com/github/dockerjava/api/model/VolumesFrom.java create mode 100644 src/test/java/com/github/dockerjava/api/model/VolumeFrom_SerializingTest.java diff --git a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java index 2eeda23e..8d290125 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java @@ -6,6 +6,7 @@ import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Volume; +import com.github.dockerjava.api.model.VolumeFrom; public interface CreateContainerCmd extends DockerCmd{ @@ -93,9 +94,9 @@ public interface CreateContainerCmd extends DockerCmd{ public CreateContainerCmd withVolumes(Volume... volumes); - public String[] getVolumesFrom(); + public VolumeFrom[] getVolumesFrom(); - public CreateContainerCmd withVolumesFrom(String... volumesFrom); + public CreateContainerCmd withVolumesFrom(VolumeFrom... volumesFrom); public HostConfig getHostConfig(); diff --git a/src/main/java/com/github/dockerjava/api/model/AccessMode.java b/src/main/java/com/github/dockerjava/api/model/AccessMode.java index e0106536..a1f53f57 100644 --- a/src/main/java/com/github/dockerjava/api/model/AccessMode.java +++ b/src/main/java/com/github/dockerjava/api/model/AccessMode.java @@ -16,4 +16,5 @@ public enum AccessMode { */ public static final AccessMode DEFAULT = rw; + } diff --git a/src/main/java/com/github/dockerjava/api/model/Bind.java b/src/main/java/com/github/dockerjava/api/model/Bind.java index 2a838c27..eb0b8fd4 100644 --- a/src/main/java/com/github/dockerjava/api/model/Bind.java +++ b/src/main/java/com/github/dockerjava/api/model/Bind.java @@ -1,7 +1,6 @@ package com.github.dockerjava.api.model; -import static com.github.dockerjava.api.model.AccessMode.ro; -import static com.github.dockerjava.api.model.AccessMode.rw; + import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; @@ -29,14 +28,6 @@ public Bind(String path, Volume volume, AccessMode accessMode) { this.accessMode = accessMode; } - /** - * @deprecated use {@link #Bind(String, Volume, AccessMode)} - */ - @Deprecated - public Bind(String path, Volume volume, boolean readOnly) { - this(path, volume, readOnly ? ro : rw); - } - public String getPath() { return path; } @@ -49,13 +40,6 @@ public AccessMode getAccessMode() { return accessMode; } - /** - * @deprecated use {@link #getAccessMode()} - */ - @Deprecated - public boolean isReadOnly() { - return ro.equals(accessMode); - } /** * Parses a bind mount specification to a {@link Bind}. diff --git a/src/main/java/com/github/dockerjava/api/model/HostConfig.java b/src/main/java/com/github/dockerjava/api/model/HostConfig.java index 3d186501..dd25e79b 100644 --- a/src/main/java/com/github/dockerjava/api/model/HostConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/HostConfig.java @@ -33,7 +33,7 @@ public class HostConfig { private String[] dnsSearch; @JsonProperty("VolumesFrom") - private String[] volumesFrom; + private VolumesFrom volumesFrom; @JsonProperty("ContainerIDFile") private String containerIDFile; @@ -57,7 +57,7 @@ public HostConfig() { } public HostConfig(String[] binds, Links links, LxcConf[] lxcConf, Ports portBindings, boolean publishAllPorts, - boolean privileged, String[] dns, String[] dnsSearch, String[] volumesFrom, String containerIDFile, + boolean privileged, String[] dns, String[] dnsSearch, VolumesFrom volumesFrom, String containerIDFile, Capability[] capAdd, Capability[] capDrop, RestartPolicy restartPolicy, String networkMode, Device[] devices) { this.binds = binds; this.links = links; @@ -100,7 +100,7 @@ public String[] getDns() { return dns; } - public String[] getVolumesFrom() { + public VolumesFrom getVolumesFrom() { return volumesFrom; } @@ -168,7 +168,7 @@ public void setDnsSearch(String[] dnsSearch) { this.dnsSearch = dnsSearch; } - public void setVolumesFrom(String[] volumesFrom) { + public void setVolumesFrom(VolumesFrom volumesFrom) { this.volumesFrom = volumesFrom; } diff --git a/src/main/java/com/github/dockerjava/api/model/Volume.java b/src/main/java/com/github/dockerjava/api/model/Volume.java index 1a189014..3ec5e24c 100644 --- a/src/main/java/com/github/dockerjava/api/model/Volume.java +++ b/src/main/java/com/github/dockerjava/api/model/Volume.java @@ -30,18 +30,23 @@ public class Volume { private String path; - private boolean readWrite = true; + private AccessMode accessMode = AccessMode.rw; public Volume(String path) { this.path = path; } + + public Volume(String path, AccessMode accessMode) { + this.path = path; + this.accessMode = accessMode; + } public String getPath() { return path; } - public boolean isReadWrite() { - return readWrite; + public AccessMode getAccessMode() { + return accessMode; } public static Volume parse(String serialized) { @@ -64,7 +69,7 @@ public String toString() { public boolean equals(Object obj) { if (obj instanceof Volume) { Volume other = (Volume) obj; - return new EqualsBuilder().append(path, other.getPath()).append(readWrite, other.isReadWrite()) + return new EqualsBuilder().append(path, other.getPath()).append(accessMode, other.getAccessMode()) .isEquals(); } else return super.equals(obj); @@ -72,7 +77,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return new HashCodeBuilder().append(path).append(readWrite).toHashCode(); + return new HashCodeBuilder().append(path).append(accessMode).toHashCode(); } public static class Serializer extends JsonSerializer { @@ -84,7 +89,7 @@ public void serialize(Volume volume, JsonGenerator jsonGen, jsonGen.writeStartObject(); jsonGen.writeFieldName(volume.getPath()); - jsonGen.writeString(Boolean.toString(volume.isReadWrite())); + jsonGen.writeString(Boolean.toString(volume.getAccessMode().equals(AccessMode.rw) ? true: false)); jsonGen.writeEndObject(); } diff --git a/src/main/java/com/github/dockerjava/api/model/VolumeFrom.java b/src/main/java/com/github/dockerjava/api/model/VolumeFrom.java new file mode 100644 index 00000000..8554c2f6 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/VolumeFrom.java @@ -0,0 +1,87 @@ +package com.github.dockerjava.api.model; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +public class VolumeFrom { + + private String container; + + private AccessMode accessMode; + + public VolumeFrom(String container) { + this(container, AccessMode.DEFAULT); + } + + public VolumeFrom(String container, AccessMode accessMode) { + this.container = container; + this.accessMode = accessMode; + } + + public String getContainer() { + return container; + } + + public AccessMode getAccessMode() { + return accessMode; + } + + + /** + * Parses a volume from specification to a {@link VolumeFrom}. + * + * @param serialized the specification, e.g. container:ro + * @return a {@link VolumeFrom} matching the specification + * @throws IllegalArgumentException if the specification cannot be parsed + */ + public static VolumeFrom parse(String serialized) { + try { + String[] parts = serialized.split(":"); + switch (parts.length) { + case 1: { + return new VolumeFrom(parts[0]); + } + case 2: { + return new VolumeFrom(parts[0], AccessMode.valueOf(parts[1])); + } + + default: { + throw new IllegalArgumentException(); + } + } + } catch (Exception e) { + throw new IllegalArgumentException("Error parsing Bind '" + serialized + + "'"); + } + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof VolumeFrom) { + VolumeFrom other = (VolumeFrom) obj; + return new EqualsBuilder().append(container, other.getContainer()) + .append(accessMode, other.getAccessMode()).isEquals(); + } else + return super.equals(obj); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(container) + .append(accessMode).toHashCode(); + } + + /** + * Returns a string representation of this {@link VolumeFrom} suitable + * for inclusion in a JSON message. + * The format is <container>:<access mode>, + * like the argument in {@link #parse(String)}. + * + * @return a string representation of this {@link VolumeFrom} + */ + @Override + public String toString() { + return container + ":" + accessMode.toString(); + } + +} diff --git a/src/main/java/com/github/dockerjava/api/model/Volumes.java b/src/main/java/com/github/dockerjava/api/model/Volumes.java index b8a9315b..69753d6a 100644 --- a/src/main/java/com/github/dockerjava/api/model/Volumes.java +++ b/src/main/java/com/github/dockerjava/api/model/Volumes.java @@ -48,7 +48,7 @@ public void serialize(Volumes volumes, JsonGenerator jsonGen, jsonGen.writeStartObject(); for (Volume volume : volumes.getVolumes()) { jsonGen.writeFieldName(volume.getPath()); - jsonGen.writeString(Boolean.toString(volume.isReadWrite())); + jsonGen.writeString(Boolean.toString(volume.getAccessMode().equals(AccessMode.rw) ? true: false)); } jsonGen.writeEndObject(); } diff --git a/src/main/java/com/github/dockerjava/api/model/VolumesFrom.java b/src/main/java/com/github/dockerjava/api/model/VolumesFrom.java new file mode 100644 index 00000000..a16e0c67 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/VolumesFrom.java @@ -0,0 +1,69 @@ +package com.github.dockerjava.api.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +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.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +@JsonSerialize(using = VolumesFrom.Serializer.class) +@JsonDeserialize(using = VolumesFrom.Deserializer.class) +public class VolumesFrom { + + private VolumeFrom[] volumesFrom; + + public VolumesFrom(VolumeFrom... volumesFrom) { + this.volumesFrom = volumesFrom; + } + + public VolumeFrom[] getVolumesFrom() { + return volumesFrom; + } + + public static class Serializer extends JsonSerializer { + + @Override + public void serialize(VolumesFrom volumesFrom, JsonGenerator jsonGen, + SerializerProvider serProvider) throws IOException, + JsonProcessingException { + + // + jsonGen.writeStartArray(); + for (VolumeFrom bind : volumesFrom.getVolumesFrom()) { + jsonGen.writeString(bind.toString()); + } + jsonGen.writeEndArray(); + // + } + + } + + public static class Deserializer extends JsonDeserializer { + @Override + public VolumesFrom deserialize(JsonParser jsonParser, + DeserializationContext deserializationContext) + throws IOException, JsonProcessingException { + + List volumesFrom = new ArrayList(); + ObjectCodec oc = jsonParser.getCodec(); + JsonNode node = oc.readTree(jsonParser); + for (Iterator it = node.iterator(); it.hasNext();) { + JsonNode field = it.next(); + volumesFrom.add(VolumeFrom.parse(field.asText())); + } + return new VolumesFrom(volumesFrom.toArray(new VolumeFrom[0])); + } + } + +} diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index ea6d721e..991ecc8e 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -15,7 +15,9 @@ import com.github.dockerjava.api.model.ExposedPorts; import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Volume; +import com.github.dockerjava.api.model.VolumeFrom; import com.github.dockerjava.api.model.Volumes; +import com.github.dockerjava.api.model.VolumesFrom; /** @@ -303,13 +305,13 @@ public CreateContainerCmdImpl withVolumes(Volume... volumes) { } @Override - public String[] getVolumesFrom() { - return hostConfig.getVolumesFrom(); + public VolumeFrom[] getVolumesFrom() { + return hostConfig.getVolumesFrom() == null ? new VolumeFrom[0] : hostConfig.getVolumesFrom().getVolumesFrom(); } @Override - public CreateContainerCmdImpl withVolumesFrom(String... volumesFrom) { - this.hostConfig.setVolumesFrom(volumesFrom); + public CreateContainerCmdImpl withVolumesFrom(VolumeFrom... volumesFrom) { + this.hostConfig.setVolumesFrom(new VolumesFrom(volumesFrom)); return this; } diff --git a/src/test/java/com/github/dockerjava/api/model/VolumeFrom_SerializingTest.java b/src/test/java/com/github/dockerjava/api/model/VolumeFrom_SerializingTest.java new file mode 100644 index 00000000..37a3e37a --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/VolumeFrom_SerializingTest.java @@ -0,0 +1,33 @@ +package com.github.dockerjava.api.model; + +import static org.testng.Assert.assertEquals; + +import java.util.Map; + +import org.testng.annotations.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.model.Ports.Binding; + +public class VolumeFrom_SerializingTest { + private final ObjectMapper objectMapper = new ObjectMapper(); + private final String json = + "[\"container1:ro\",\"container2:rw\"]"; + @Test + public void deserializing() throws Exception { + VolumesFrom volumesFrom = objectMapper.readValue(json, VolumesFrom.class); + + VolumesFrom expected = new VolumesFrom(new VolumeFrom("container1", AccessMode.ro), new VolumeFrom("container2", AccessMode.rw)); + + assertEquals(volumesFrom.getVolumesFrom(), expected.getVolumesFrom()); + } + + @Test + public void serializing() throws Exception { + VolumesFrom volumesFrom = new VolumesFrom(new VolumeFrom("container1", AccessMode.ro), new VolumeFrom("container2", AccessMode.rw)); + + assertEquals(objectMapper.writeValueAsString(volumesFrom), json); + } + + +} diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index 2b879a9a..71358ff5 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -32,6 +32,7 @@ import com.github.dockerjava.api.model.Link; import com.github.dockerjava.api.model.Links; import com.github.dockerjava.api.model.Volume; +import com.github.dockerjava.api.model.VolumeFrom; import com.github.dockerjava.client.AbstractDockerClientTest; @Test(groups = "integration") @@ -125,14 +126,14 @@ public void createContainerWithVolumesFrom() throws DockerException { // create a second container with volumes from first container CreateContainerResponse container2 = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999") - .withVolumesFrom(container1Name).exec(); + .withVolumesFrom(new VolumeFrom(container1Name)).exec(); LOG.info("Created container2 {}", container2.toString()); InspectContainerResponse inspectContainerResponse2 = dockerClient .inspectContainerCmd(container2.getId()).exec(); // No volumes are created, the information is just stored in .HostConfig.VolumesFrom - assertThat(inspectContainerResponse2.getHostConfig().getVolumesFrom(), hasItemInArray(container1Name)); + assertThat(inspectContainerResponse2.getHostConfig().getVolumesFrom().getVolumesFrom(), hasItemInArray(new VolumeFrom(container1Name))); // To ensure that the information stored in VolumesFrom really is considered // when starting the container, we start it and verify that it has the same @@ -144,7 +145,7 @@ public void createContainerWithVolumesFrom() throws DockerException { inspectContainerResponse2 = dockerClient.inspectContainerCmd(container2.getId()).exec(); - assertThat(inspectContainerResponse2.getHostConfig().getVolumesFrom(), hasItemInArray(container1Name)); + assertThat(inspectContainerResponse2.getHostConfig().getVolumesFrom().getVolumesFrom(), hasItemInArray(new VolumeFrom(container1Name))); assertContainerHasVolumes(inspectContainerResponse2, volume1, volume2); } From afdafe9fbd3507c0a7a7f22a2789764d70b7b120 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 28 Jan 2015 23:59:46 +0100 Subject: [PATCH 288/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fbf6d65c..4d70968f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ Change Log docker-java-0.10.6-SNAPSHOT --- + * [#137](https://github.com/docker-java/docker-java/pull/137) Multiple volumesFrom option when creating a container * [#135](https://github.com/docker-java/docker-java/pull/135) Update to latest unix-socket-factory * [#134](https://github.com/docker-java/docker-java/pull/134) Remove Google Guava as dependency * [#128](https://github.com/docker-java/docker-java/pull/128) Allow unauthorized pullImageCmd From cc5331d7de228601fa817f0212ee107953470075 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 29 Jan 2015 22:03:41 +0100 Subject: [PATCH 289/452] Simplify volumesFrom handling --- .../api/command/CreateContainerCmd.java | 6 +- .../dockerjava/api/model/HostConfig.java | 8 +- .../dockerjava/api/model/VolumeFrom.java | 87 --------------- .../dockerjava/api/model/VolumesFrom.java | 104 ++++++++++++++---- .../core/command/CreateContainerCmdImpl.java | 12 +- .../api/model/VolumeFrom_SerializingTest.java | 24 ++-- .../command/CreateContainerCmdImplTest.java | 8 +- 7 files changed, 106 insertions(+), 143 deletions(-) delete mode 100644 src/main/java/com/github/dockerjava/api/model/VolumeFrom.java diff --git a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java index 8d290125..88a6caf0 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java @@ -6,7 +6,7 @@ import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Volume; -import com.github.dockerjava.api.model.VolumeFrom; +import com.github.dockerjava.api.model.VolumesFrom; public interface CreateContainerCmd extends DockerCmd{ @@ -94,9 +94,9 @@ public interface CreateContainerCmd extends DockerCmd{ public CreateContainerCmd withVolumes(Volume... volumes); - public VolumeFrom[] getVolumesFrom(); + public VolumesFrom[] getVolumesFrom(); - public CreateContainerCmd withVolumesFrom(VolumeFrom... volumesFrom); + public CreateContainerCmd withVolumesFrom(VolumesFrom... volumesFrom); public HostConfig getHostConfig(); diff --git a/src/main/java/com/github/dockerjava/api/model/HostConfig.java b/src/main/java/com/github/dockerjava/api/model/HostConfig.java index dd25e79b..5532fba3 100644 --- a/src/main/java/com/github/dockerjava/api/model/HostConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/HostConfig.java @@ -33,7 +33,7 @@ public class HostConfig { private String[] dnsSearch; @JsonProperty("VolumesFrom") - private VolumesFrom volumesFrom; + private VolumesFrom[] volumesFrom; @JsonProperty("ContainerIDFile") private String containerIDFile; @@ -57,7 +57,7 @@ public HostConfig() { } public HostConfig(String[] binds, Links links, LxcConf[] lxcConf, Ports portBindings, boolean publishAllPorts, - boolean privileged, String[] dns, String[] dnsSearch, VolumesFrom volumesFrom, String containerIDFile, + boolean privileged, String[] dns, String[] dnsSearch, VolumesFrom[] volumesFrom, String containerIDFile, Capability[] capAdd, Capability[] capDrop, RestartPolicy restartPolicy, String networkMode, Device[] devices) { this.binds = binds; this.links = links; @@ -100,7 +100,7 @@ public String[] getDns() { return dns; } - public VolumesFrom getVolumesFrom() { + public VolumesFrom[] getVolumesFrom() { return volumesFrom; } @@ -168,7 +168,7 @@ public void setDnsSearch(String[] dnsSearch) { this.dnsSearch = dnsSearch; } - public void setVolumesFrom(VolumesFrom volumesFrom) { + public void setVolumesFrom(VolumesFrom[] volumesFrom) { this.volumesFrom = volumesFrom; } diff --git a/src/main/java/com/github/dockerjava/api/model/VolumeFrom.java b/src/main/java/com/github/dockerjava/api/model/VolumeFrom.java deleted file mode 100644 index 8554c2f6..00000000 --- a/src/main/java/com/github/dockerjava/api/model/VolumeFrom.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.github.dockerjava.api.model; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; - -public class VolumeFrom { - - private String container; - - private AccessMode accessMode; - - public VolumeFrom(String container) { - this(container, AccessMode.DEFAULT); - } - - public VolumeFrom(String container, AccessMode accessMode) { - this.container = container; - this.accessMode = accessMode; - } - - public String getContainer() { - return container; - } - - public AccessMode getAccessMode() { - return accessMode; - } - - - /** - * Parses a volume from specification to a {@link VolumeFrom}. - * - * @param serialized the specification, e.g. container:ro - * @return a {@link VolumeFrom} matching the specification - * @throws IllegalArgumentException if the specification cannot be parsed - */ - public static VolumeFrom parse(String serialized) { - try { - String[] parts = serialized.split(":"); - switch (parts.length) { - case 1: { - return new VolumeFrom(parts[0]); - } - case 2: { - return new VolumeFrom(parts[0], AccessMode.valueOf(parts[1])); - } - - default: { - throw new IllegalArgumentException(); - } - } - } catch (Exception e) { - throw new IllegalArgumentException("Error parsing Bind '" + serialized - + "'"); - } - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof VolumeFrom) { - VolumeFrom other = (VolumeFrom) obj; - return new EqualsBuilder().append(container, other.getContainer()) - .append(accessMode, other.getAccessMode()).isEquals(); - } else - return super.equals(obj); - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(container) - .append(accessMode).toHashCode(); - } - - /** - * Returns a string representation of this {@link VolumeFrom} suitable - * for inclusion in a JSON message. - * The format is <container>:<access mode>, - * like the argument in {@link #parse(String)}. - * - * @return a string representation of this {@link VolumeFrom} - */ - @Override - public String toString() { - return container + ":" + accessMode.toString(); - } - -} diff --git a/src/main/java/com/github/dockerjava/api/model/VolumesFrom.java b/src/main/java/com/github/dockerjava/api/model/VolumesFrom.java index a16e0c67..9aae9f30 100644 --- a/src/main/java/com/github/dockerjava/api/model/VolumesFrom.java +++ b/src/main/java/com/github/dockerjava/api/model/VolumesFrom.java @@ -1,9 +1,9 @@ package com.github.dockerjava.api.model; import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; @@ -21,30 +21,94 @@ @JsonDeserialize(using = VolumesFrom.Deserializer.class) public class VolumesFrom { - private VolumeFrom[] volumesFrom; + private String container; + + private AccessMode accessMode; - public VolumesFrom(VolumeFrom... volumesFrom) { - this.volumesFrom = volumesFrom; + public VolumesFrom(String container) { + this(container, AccessMode.DEFAULT); } - public VolumeFrom[] getVolumesFrom() { - return volumesFrom; + public VolumesFrom(String container, AccessMode accessMode) { + this.container = container; + this.accessMode = accessMode; + } + + public String getContainer() { + return container; } + + public AccessMode getAccessMode() { + return accessMode; + } + + /** + * Parses a volume from specification to a {@link VolumesFrom}. + * + * @param serialized the specification, e.g. container:ro + * @return a {@link VolumesFrom} matching the specification + * @throws IllegalArgumentException if the specification cannot be parsed + */ + public static VolumesFrom parse(String serialized) { + try { + String[] parts = serialized.split(":"); + switch (parts.length) { + case 1: { + return new VolumesFrom(parts[0]); + } + case 2: { + return new VolumesFrom(parts[0], AccessMode.valueOf(parts[1])); + } + + default: { + throw new IllegalArgumentException(); + } + } + } catch (Exception e) { + throw new IllegalArgumentException("Error parsing Bind '" + serialized + + "'"); + } + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof VolumesFrom) { + VolumesFrom other = (VolumesFrom) obj; + return new EqualsBuilder().append(container, other.getContainer()) + .append(accessMode, other.getAccessMode()).isEquals(); + } else + return super.equals(obj); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(container) + .append(accessMode).toHashCode(); + } + + /** + * Returns a string representation of this {@link VolumesFrom} suitable + * for inclusion in a JSON message. + * The format is <container>:<access mode>, + * like the argument in {@link #parse(String)}. + * + * @return a string representation of this {@link VolumesFrom} + */ + @Override + public String toString() { + return container + ":" + accessMode.toString(); + } + public static class Serializer extends JsonSerializer { @Override - public void serialize(VolumesFrom volumesFrom, JsonGenerator jsonGen, + public void serialize(VolumesFrom volumeFrom, JsonGenerator jsonGen, SerializerProvider serProvider) throws IOException, JsonProcessingException { - // - jsonGen.writeStartArray(); - for (VolumeFrom bind : volumesFrom.getVolumesFrom()) { - jsonGen.writeString(bind.toString()); - } - jsonGen.writeEndArray(); - // + jsonGen.writeString(volumeFrom.toString()); + } } @@ -55,14 +119,10 @@ public VolumesFrom deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { - List volumesFrom = new ArrayList(); ObjectCodec oc = jsonParser.getCodec(); JsonNode node = oc.readTree(jsonParser); - for (Iterator it = node.iterator(); it.hasNext();) { - JsonNode field = it.next(); - volumesFrom.add(VolumeFrom.parse(field.asText())); - } - return new VolumesFrom(volumesFrom.toArray(new VolumeFrom[0])); + return VolumesFrom.parse(node.asText()); + } } diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index 991ecc8e..59a08b91 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -15,10 +15,8 @@ import com.github.dockerjava.api.model.ExposedPorts; import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Volume; -import com.github.dockerjava.api.model.VolumeFrom; -import com.github.dockerjava.api.model.Volumes; import com.github.dockerjava.api.model.VolumesFrom; - +import com.github.dockerjava.api.model.Volumes; /** * @@ -305,13 +303,13 @@ public CreateContainerCmdImpl withVolumes(Volume... volumes) { } @Override - public VolumeFrom[] getVolumesFrom() { - return hostConfig.getVolumesFrom() == null ? new VolumeFrom[0] : hostConfig.getVolumesFrom().getVolumesFrom(); + public VolumesFrom[] getVolumesFrom() { + return hostConfig.getVolumesFrom(); } @Override - public CreateContainerCmdImpl withVolumesFrom(VolumeFrom... volumesFrom) { - this.hostConfig.setVolumesFrom(new VolumesFrom(volumesFrom)); + public CreateContainerCmdImpl withVolumesFrom(VolumesFrom... volumesFrom) { + this.hostConfig.setVolumesFrom(volumesFrom); return this; } diff --git a/src/test/java/com/github/dockerjava/api/model/VolumeFrom_SerializingTest.java b/src/test/java/com/github/dockerjava/api/model/VolumeFrom_SerializingTest.java index 37a3e37a..b7c3bbff 100644 --- a/src/test/java/com/github/dockerjava/api/model/VolumeFrom_SerializingTest.java +++ b/src/test/java/com/github/dockerjava/api/model/VolumeFrom_SerializingTest.java @@ -2,32 +2,24 @@ import static org.testng.Assert.assertEquals; -import java.util.Map; - import org.testng.annotations.Test; import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.dockerjava.api.model.Ports.Binding; public class VolumeFrom_SerializingTest { private final ObjectMapper objectMapper = new ObjectMapper(); - private final String json = - "[\"container1:ro\",\"container2:rw\"]"; + private final String json = "\"container1:ro\""; + @Test public void deserializing() throws Exception { - VolumesFrom volumesFrom = objectMapper.readValue(json, VolumesFrom.class); - - VolumesFrom expected = new VolumesFrom(new VolumeFrom("container1", AccessMode.ro), new VolumeFrom("container2", AccessMode.rw)); - - assertEquals(volumesFrom.getVolumesFrom(), expected.getVolumesFrom()); + VolumesFrom volumeFrom = objectMapper.readValue(json, VolumesFrom.class); + assertEquals(volumeFrom, new VolumesFrom("container1", AccessMode.ro)); } - + @Test public void serializing() throws Exception { - VolumesFrom volumesFrom = new VolumesFrom(new VolumeFrom("container1", AccessMode.ro), new VolumeFrom("container2", AccessMode.rw)); - - assertEquals(objectMapper.writeValueAsString(volumesFrom), json); + VolumesFrom volumeFrom = new VolumesFrom("container1", AccessMode.ro); + assertEquals(objectMapper.writeValueAsString(volumeFrom), json); } - - + } diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index 71358ff5..ed81a529 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -32,7 +32,7 @@ import com.github.dockerjava.api.model.Link; import com.github.dockerjava.api.model.Links; import com.github.dockerjava.api.model.Volume; -import com.github.dockerjava.api.model.VolumeFrom; +import com.github.dockerjava.api.model.VolumesFrom; import com.github.dockerjava.client.AbstractDockerClientTest; @Test(groups = "integration") @@ -126,14 +126,14 @@ public void createContainerWithVolumesFrom() throws DockerException { // create a second container with volumes from first container CreateContainerResponse container2 = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999") - .withVolumesFrom(new VolumeFrom(container1Name)).exec(); + .withVolumesFrom(new VolumesFrom(container1Name)).exec(); LOG.info("Created container2 {}", container2.toString()); InspectContainerResponse inspectContainerResponse2 = dockerClient .inspectContainerCmd(container2.getId()).exec(); // No volumes are created, the information is just stored in .HostConfig.VolumesFrom - assertThat(inspectContainerResponse2.getHostConfig().getVolumesFrom().getVolumesFrom(), hasItemInArray(new VolumeFrom(container1Name))); + assertThat(inspectContainerResponse2.getHostConfig().getVolumesFrom(), hasItemInArray(new VolumesFrom(container1Name))); // To ensure that the information stored in VolumesFrom really is considered // when starting the container, we start it and verify that it has the same @@ -145,7 +145,7 @@ public void createContainerWithVolumesFrom() throws DockerException { inspectContainerResponse2 = dockerClient.inspectContainerCmd(container2.getId()).exec(); - assertThat(inspectContainerResponse2.getHostConfig().getVolumesFrom().getVolumesFrom(), hasItemInArray(new VolumeFrom(container1Name))); + assertThat(inspectContainerResponse2.getHostConfig().getVolumesFrom(), hasItemInArray(new VolumesFrom(container1Name))); assertContainerHasVolumes(inspectContainerResponse2, volume1, volume2); } From 91b81072e5a358b9a283efa486f800c2c851fff8 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Thu, 29 Jan 2015 22:23:12 +0100 Subject: [PATCH 290/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d70968f..80b6fc4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ Change Log docker-java-0.10.6-SNAPSHOT --- + * [#138](https://github.com/docker-java/docker-java/pull/138) Apache CXF interopabilty * [#137](https://github.com/docker-java/docker-java/pull/137) Multiple volumesFrom option when creating a container * [#135](https://github.com/docker-java/docker-java/pull/135) Update to latest unix-socket-factory * [#134](https://github.com/docker-java/docker-java/pull/134) Remove Google Guava as dependency From 11ae37f1fabc6e3dc0a929bfbda3021f27f8c8f9 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 31 Jan 2015 21:08:04 +0100 Subject: [PATCH 291/452] Removed own Preconditons implementation --- .../com/github/dockerjava/Preconditions.java | 145 ------------------ .../github/dockerjava/api/model/Device.java | 2 +- .../dockerjava/api/model/RestartPolicy.java | 2 +- .../dockerjava/core/DockerClientConfig.java | 2 +- .../dockerjava/core/DockerClientImpl.java | 2 +- .../dockerjava/core/KeystoreSSLConfig.java | 2 +- .../core/LocalDirectorySSLConfig.java | 2 +- .../core/command/AbstrAuthCfgDockerCmd.java | 2 +- .../core/command/AbstrDockerCmd.java | 2 +- .../core/command/AttachContainerCmdImpl.java | 2 +- .../core/command/BuildImageCmdImpl.java | 6 +- .../core/command/CommitCmdImpl.java | 2 +- .../core/command/ContainerDiffCmdImpl.java | 2 +- .../command/CopyFileFromContainerCmdImpl.java | 2 +- .../core/command/CreateContainerCmdImpl.java | 2 +- .../core/command/CreateImageCmdImpl.java | 2 +- .../core/command/ExecCreateCmdImpl.java | 2 +- .../core/command/ExecStartCmdImpl.java | 2 +- .../core/command/InspectContainerCmdImpl.java | 2 +- .../core/command/InspectImageCmdImpl.java | 2 +- .../core/command/KillContainerCmdImpl.java | 2 +- .../core/command/ListContainersCmdImpl.java | 4 +- .../core/command/ListImagesCmdImpl.java | 2 +- .../core/command/LogContainerCmdImpl.java | 2 +- .../core/command/PauseContainerCmdImpl.java | 2 +- .../core/command/PullImageCmdImpl.java | 2 +- .../core/command/PushImageCmdImpl.java | 2 +- .../core/command/RemoveContainerCmdImpl.java | 2 +- .../core/command/RemoveImageCmdImpl.java | 2 +- .../core/command/RestartContainerCmdImpl.java | 4 +- .../core/command/SearchImagesCmdImpl.java | 2 +- .../core/command/StartContainerCmdImpl.java | 2 +- .../core/command/StopContainerCmdImpl.java | 4 +- .../core/command/TagImageCmdImpl.java | 2 +- .../core/command/TopContainerCmdImpl.java | 2 +- .../core/command/UnpauseContainerCmdImpl.java | 2 +- .../core/command/WaitContainerCmdImpl.java | 2 +- .../dockerjava/jaxrs/AbstrDockerCmdExec.java | 2 +- .../jaxrs/DockerCmdExecFactoryImpl.java | 2 +- .../dockerjava/jaxrs/EventsCmdExec.java | 2 +- .../jaxrs/util/guava/PercentEscaper.java | 2 +- .../jaxrs/util/guava/UnicodeEscaper.java | 2 +- 42 files changed, 45 insertions(+), 192 deletions(-) delete mode 100644 src/main/java/com/github/dockerjava/Preconditions.java diff --git a/src/main/java/com/github/dockerjava/Preconditions.java b/src/main/java/com/github/dockerjava/Preconditions.java deleted file mode 100644 index 183e640b..00000000 --- a/src/main/java/com/github/dockerjava/Preconditions.java +++ /dev/null @@ -1,145 +0,0 @@ -/* Copyright (C) 2008 The Guava Authors - * - * Licensed 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.github.dockerjava; - - -public final class Preconditions { - private Preconditions() {} - - /** - * Ensures the truth of an expression involving one or more parameters to the calling method. - * - * @param expression a boolean expression - * @param errorMessageTemplate a template for the exception message should the check fail. The - * message is formed by replacing each {@code %s} placeholder in the template with an - * argument. These are matched by position - the first {@code %s} gets {@code - * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message - * in square braces. Unmatched placeholders will be left as-is. - * @param errorMessageArgs the arguments to be substituted into the message template. Arguments - * are converted to strings using {@link String#valueOf(Object)}. - * @throws IllegalArgumentException if {@code expression} is false - * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or - * {@code errorMessageArgs} is null (don't let this happen) - */ - public static void checkArgument(boolean expression, - String errorMessageTemplate, - Object... errorMessageArgs) { - if (!expression) { - throw new IllegalArgumentException(Preconditions.format(errorMessageTemplate, errorMessageArgs)); - } - } - - /** - * Ensures that an object reference passed as a parameter to the calling method is not null. - * - * @param reference an object reference - * @param errorMessage the exception message to use if the check fails; will be converted to a - * string using {@link String#valueOf(Object)} - * @return the non-null reference that was validated - * @throws NullPointerException if {@code reference} is null - */ - public static T checkNotNull(T reference, Object errorMessage) { - if (reference == null) { - throw new NullPointerException(String.valueOf(errorMessage)); - } - return reference; - } - - /** - * Ensures the truth of an expression involving one or more parameters to the calling method. - * - * @param expression a boolean expression - * @param errorMessage the exception message to use if the check fails; will be converted to a - * string using {@link String#valueOf(Object)} - * @throws IllegalArgumentException if {@code expression} is false - */ - public static void checkArgument(boolean expression, Object errorMessage) { - if (!expression) { - throw new IllegalArgumentException(String.valueOf(errorMessage)); - } - } - - /** - * Ensures that an object reference passed as a parameter to the calling method is not null. - * - * @param reference an object reference - * @return the non-null reference that was validated - * @throws NullPointerException if {@code reference} is null - */ - public static T checkNotNull(T reference) { - if (reference == null) { - throw new NullPointerException(); - } - return reference; - } - - /** - * Ensures the truth of an expression involving the state of the calling instance, but not - * involving any parameters to the calling method. - * - * @param expression a boolean expression - * @param errorMessage the exception message to use if the check fails; will be converted to a - * string using {@link String#valueOf(Object)} - * @throws IllegalStateException if {@code expression} is false - */ - public static void checkState(boolean expression, Object errorMessage) { - if (!expression) { - throw new IllegalStateException(String.valueOf(errorMessage)); - } - } - - /** - * Substitutes each {@code %s} in {@code template} with an argument. These are matched by - * position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than - * placeholders, the unmatched arguments will be appended to the end of the formatted message in - * square braces. - * - * @param template a non-null string containing 0 or more {@code %s} placeholders. - * @param args the arguments to be substituted into the message template. Arguments are converted - * to strings using {@link String#valueOf(Object)}. Arguments can be null. - */ - // Note that this is somewhat-improperly used from Verify.java as well. - public static String format(String template, Object... args) { - template = String.valueOf(template); // null -> "null" - - // start substituting the arguments into the '%s' placeholders - StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); - int templateStart = 0; - int i = 0; - while (i < args.length) { - int placeholderStart = template.indexOf("%s", templateStart); - if (placeholderStart == -1) { - break; - } - builder.append(template.substring(templateStart, placeholderStart)); - builder.append(args[i++]); - templateStart = placeholderStart + 2; - } - builder.append(template.substring(templateStart)); - - // if we run out of placeholders, append the extra args in square braces - if (i < args.length) { - builder.append(" ["); - builder.append(args[i++]); - while (i < args.length) { - builder.append(", "); - builder.append(args[i++]); - } - builder.append(']'); - } - - return builder.toString(); - } -} diff --git a/src/main/java/com/github/dockerjava/api/model/Device.java b/src/main/java/com/github/dockerjava/api/model/Device.java index 76b0ddbf..63d26b41 100644 --- a/src/main/java/com/github/dockerjava/api/model/Device.java +++ b/src/main/java/com/github/dockerjava/api/model/Device.java @@ -1,6 +1,6 @@ package com.github.dockerjava.api.model; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; diff --git a/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java b/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java index e08dd138..d2dd6d94 100644 --- a/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java +++ b/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java @@ -1,6 +1,6 @@ package com.github.dockerjava.api.model; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 9a7a2e9f..881a7663 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index f1175921..5f0876bb 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.Closeable; import java.io.File; diff --git a/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java b/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java index fe5e6509..7f141142 100644 --- a/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java +++ b/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java b/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java index d60db72c..a27cb01f 100644 --- a/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java +++ b/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.Serializable; import java.security.Security; diff --git a/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java index 8069ed6b..c1ccab51 100644 --- a/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; diff --git a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java index ed289c98..300489a0 100644 --- a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; diff --git a/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java index 6ac220c0..65155a1a 100644 --- a/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index b2286bc8..0bdb6db3 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -1,9 +1,5 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkArgument; -import static com.github.dockerjava.Preconditions.checkNotNull; -import static com.github.dockerjava.Preconditions.checkState; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -29,6 +25,8 @@ import com.github.dockerjava.core.GoLangFileMatchException; import com.github.dockerjava.core.GoLangMatchFileFilter; +import static jersey.repackaged.com.google.common.base.Preconditions.*; + /** * * Build an image from Dockerfile. diff --git a/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java index 6ba3d4a3..df8b1a66 100644 --- a/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import org.apache.commons.lang.builder.ToStringBuilder; diff --git a/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java index 68293107..abb6469d 100644 --- a/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.util.List; diff --git a/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java index fe1a57b6..d335bf8c 100644 --- a/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index 59a08b91..7a41f1d4 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import org.apache.commons.lang.builder.ToStringBuilder; diff --git a/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java index fc6ce912..71c333e7 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java index 5819fa49..3fac9013 100644 --- a/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.api.NotFoundException; diff --git a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java index 8f9028d2..70a95b85 100644 --- a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java index f48101b8..de7c268c 100644 --- a/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.InspectContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java index 11a0ea7f..c2c91b99 100644 --- a/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.InspectImageCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java index ccc7b58b..ba4da47c 100644 --- a/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.KillContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java index 5bfe61af..741da75e 100644 --- a/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java @@ -1,7 +1,7 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkArgument; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkArgument; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.util.List; diff --git a/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java index 01c5eb01..ed163bb8 100644 --- a/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.util.List; diff --git a/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java index b71a149c..547165f1 100644 --- a/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java index 4d8702b1..a2fd73ee 100644 --- a/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.PauseContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java index b4cde794..8dd3af41 100644 --- a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java index 2a279550..137c008a 100644 --- a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java index 84d7cc12..51dd4b0c 100644 --- a/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.RemoveContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java index 6e7f4fb1..938e2b81 100644 --- a/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.RemoveImageCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java index 0f105e53..3548e04f 100644 --- a/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java @@ -1,7 +1,7 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkArgument; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkArgument; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.RestartContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java index 7462cdbd..164425fc 100644 --- a/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.util.List; diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index 1ca2124d..44476e0a 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -1,7 +1,7 @@ package com.github.dockerjava.core.command; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import org.apache.commons.lang.builder.ToStringBuilder; diff --git a/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java index 26372b9f..bed0aab7 100644 --- a/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java @@ -1,7 +1,7 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkArgument; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkArgument; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; diff --git a/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java index cdcc7450..3e0370cb 100644 --- a/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.command.TagImageCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java index c49698cf..713ac2f2 100644 --- a/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.TopContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java index 97d12eaa..ce266162 100644 --- a/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.UnpauseContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java index c5952e53..ecfc89e4 100644 --- a/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.command.WaitContainerCmd; diff --git a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java index 95c13b26..a33e11a1 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java @@ -1,6 +1,6 @@ package com.github.dockerjava.jaxrs; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 3f59a283..744f0c63 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.jaxrs; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.net.URI; diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java index ba15e995..3c525bae 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -1,6 +1,6 @@ package com.github.dockerjava.jaxrs; -import static com.github.dockerjava.Preconditions.checkNotNull; +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; import java.util.concurrent.Callable; diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/guava/PercentEscaper.java b/src/main/java/com/github/dockerjava/jaxrs/util/guava/PercentEscaper.java index b8c2b271..8625121e 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/guava/PercentEscaper.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/guava/PercentEscaper.java @@ -16,7 +16,7 @@ package com.github.dockerjava.jaxrs.util.guava; -import com.github.dockerjava.Preconditions; +import jersey.repackaged.com.google.common.base.Preconditions; /** * A {@code UnicodeEscaper} that escapes some set of Java characters using a diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/guava/UnicodeEscaper.java b/src/main/java/com/github/dockerjava/jaxrs/util/guava/UnicodeEscaper.java index a5823948..b0b74d8f 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/guava/UnicodeEscaper.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/guava/UnicodeEscaper.java @@ -16,8 +16,8 @@ package com.github.dockerjava.jaxrs.util.guava; +import jersey.repackaged.com.google.common.base.Preconditions; -import com.github.dockerjava.Preconditions; /** * An Escaper that converts literal text into a format safe for From 93348ec80459da959d70649d25bd771797fb8a51 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 2 Feb 2015 21:17:38 +0100 Subject: [PATCH 292/452] Fix Issue #139 --- pom.xml | 12 ++++++------ .../dockerjava/jaxrs/DockerCmdExecFactoryImpl.java | 6 ++++-- .../github/dockerjava/jaxrs/util/LoggingFilter.java | 9 +++++---- .../jaxrs/util/SelectiveLoggingFilter.java | 3 ++- .../dockerjava/client/AbstractDockerClientTest.java | 2 ++ src/test/resources/logback.xml | 6 +++--- 6 files changed, 22 insertions(+), 16 deletions(-) diff --git a/pom.xml b/pom.xml index 2d011653..3ae2e1f8 100644 --- a/pom.xml +++ b/pom.xml @@ -66,7 +66,7 @@ 2015-01-27T15-02-14 - 1.0.1 + 1.1.0 5.12.1 1.3 1.6 @@ -143,11 +143,11 @@ ${slf4j-api.version}
- - org.slf4j - jul-to-slf4j - ${slf4j-api.version} - + + + + + org.bouncycastle diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 744f0c63..78cd8427 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -4,7 +4,9 @@ import java.io.IOException; import java.net.URI; -import java.util.logging.Logger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import javax.ws.rs.client.Client; @@ -65,7 +67,7 @@ public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { - private static final Logger LOGGER = Logger.getLogger(DockerCmdExecFactoryImpl.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(DockerCmdExecFactoryImpl.class.getName()); private Client client; private WebTarget baseResource; diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java index 9679f230..eda72b83 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java @@ -53,7 +53,9 @@ import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicLong; -import java.util.logging.Logger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.ClientRequestContext; @@ -68,7 +70,6 @@ import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; - import javax.annotation.Priority; @@ -86,7 +87,7 @@ public class LoggingFilter implements ContainerRequestFilter, ClientRequestFilter, ContainerResponseFilter, ClientResponseFilter, WriterInterceptor { - private static final Logger LOGGER = Logger.getLogger(LoggingFilter.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class.getName()); private static final String NOTIFICATION_PREFIX = "* "; private static final String REQUEST_PREFIX = "> "; private static final String RESPONSE_PREFIX = "< "; @@ -150,7 +151,7 @@ public LoggingFilter(final Logger logger, final int maxEntitySize) { private void log(final StringBuilder b) { if (logger != null) { - logger.info(b.toString()); + logger.debug(b.toString()); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java index 9c577fd5..6771ebe8 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java @@ -4,12 +4,13 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; -import java.util.logging.Logger; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; +import org.slf4j.Logger; + /** * A version of the logging filter that will avoid trying to log entities which can cause diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 71bfb930..f5519283 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -39,6 +39,8 @@ public abstract class AbstractDockerClientTest extends Assert { protected TestDockerCmdExecFactory dockerCmdExecFactory = new TestDockerCmdExecFactory(DockerClientBuilder.getDefaultDockerCmdExecFactory()); public void beforeTest() { + + LOG.info("======================= BEFORETEST ======================="); LOG.info("Connecting to Docker server"); dockerClient = DockerClientBuilder.getInstance(config()) diff --git a/src/test/resources/logback.xml b/src/test/resources/logback.xml index 318af286..bdb0ee75 100644 --- a/src/test/resources/logback.xml +++ b/src/test/resources/logback.xml @@ -6,10 +6,10 @@ - - + + - + From 602008c241469d6bc41d406d8504aa1fc6021a08 Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Fri, 2 Jan 2015 11:30:10 +0000 Subject: [PATCH 293/452] There are two different event streamed JSON objects that come back from commands. Create representations for them. Signed-off-by: Nigel Magnay --- .../dockerjava/api/model/EventStreamItem.java | 62 +++++++++++++++++++ .../api/model/PushEventStreamItem.java | 58 +++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 src/main/java/com/github/dockerjava/api/model/EventStreamItem.java create mode 100644 src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java diff --git a/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java b/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java new file mode 100644 index 00000000..98c61a86 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java @@ -0,0 +1,62 @@ +package com.github.dockerjava.api.model; + +import com.google.common.base.Objects; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.Serializable; + +/** + * Represents an event stream + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class EventStreamItem implements Serializable { + + @JsonProperty("stream") + private String stream; + + // {"error":"Error...", "errorDetail":{"code": 123, "message": "Error..."}} + @JsonProperty("error") + private String error; + + @JsonProperty("errorDetail") + private ErrorDetail errorDetail; + + public String getStream() { + return stream; + } + + public String getError() { + return error; + } + + public ErrorDetail getErrorDetail() { + return errorDetail; + } + + @JsonIgnoreProperties(ignoreUnknown=true) + public static class ErrorDetail implements Serializable { + @JsonProperty("code") + String code; + @JsonProperty("message") + String message; + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("code", code) + .add("message", message) + .toString(); + } + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("stream", stream) + .add("error", error) + .add("errorDetail", errorDetail) + .toString(); + } +} diff --git a/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java b/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java new file mode 100644 index 00000000..df7f59f5 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java @@ -0,0 +1,58 @@ +package com.github.dockerjava.api.model; + +import com.google.common.base.Objects; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.Serializable; + +/** + * Represents an item returned from push + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class PushEventStreamItem implements Serializable { + + @JsonProperty("status") + private String status; + + @JsonProperty("progress") + private String progress; + + @JsonProperty("progressDetail") + private ProgressDetail progressDetail; + + + public String getStatus() { + return status; + } + + public String getProgress() { + return progress; + } + + public ProgressDetail getProgressDetail() { + return progressDetail; + } + + @JsonIgnoreProperties(ignoreUnknown=true) + public static class ProgressDetail implements Serializable { + @JsonProperty("current") + int current; + + + @Override + public String toString() { + return "current " + current; + } + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("status", status) + .add("progress", progress) + .add("progressDetail", progressDetail) + .toString(); + } +} From 8140c4707886246480eb5e330c53c85e84ebe0d7 Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Fri, 2 Jan 2015 11:35:36 +0000 Subject: [PATCH 294/452] Make BuildImage and PushImage return an object that can be iterated over in a typed fashion so that clients can read out the responses. Use Iterable so the response does not have to be 'complete' before consuming. Derive from InputStream to maintain backwards compatibility and for clients that don't want to parse the response. Signed-off-by: Nigel Magnay --- .../dockerjava/api/command/BuildImageCmd.java | 11 +++- .../dockerjava/api/command/PushImageCmd.java | 13 ++-- .../core/command/BuildImageCmdImpl.java | 3 +- .../core/command/PushImageCmdImpl.java | 6 +- .../dockerjava/jaxrs/BuildImageCmdExec.java | 49 ++++++++++++--- .../dockerjava/jaxrs/PushImageCmdExec.java | 63 +++++++++++++++---- .../core/TestDockerCmdExecFactory.java | 9 +-- 7 files changed, 119 insertions(+), 35 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java index 7c2deb63..8a1e6211 100644 --- a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java @@ -1,5 +1,9 @@ package com.github.dockerjava.api.command; +import com.github.dockerjava.api.model.EventStreamItem; +import com.github.dockerjava.api.model.PushEventStreamItem; + +import java.io.IOException; import java.io.InputStream; /** @@ -9,7 +13,7 @@ * TODO: http://docs.docker.com/reference/builder/#dockerignore * */ -public interface BuildImageCmd extends DockerCmd{ +public interface BuildImageCmd extends DockerCmd{ public BuildImageCmd withTag(String tag); @@ -37,7 +41,10 @@ public interface BuildImageCmd extends DockerCmd{ public BuildImageCmd withQuiet(boolean quiet); - public static interface Exec extends DockerCmdExec { + public static interface Exec extends DockerCmdExec { } + public static abstract class Response extends InputStream { + public abstract Iterable getItems() throws IOException; + } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java b/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java index f50beb01..80e16c6d 100644 --- a/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java @@ -1,16 +1,18 @@ package com.github.dockerjava.api.command; +import java.io.IOException; import java.io.InputStream; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.PushEventStreamItem; /** * 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 interface PushImageCmd extends DockerCmd{ +public interface PushImageCmd extends DockerCmd{ public String getName(); @@ -33,10 +35,13 @@ public interface PushImageCmd extends DockerCmd{ /** * @throws NotFoundException No such image */ - @Override - public InputStream exec() throws NotFoundException; + public Response exec() throws NotFoundException; - public static interface Exec extends DockerCmdExec { + public static interface Exec extends DockerCmdExec { + } + + public static abstract class Response extends InputStream { + public abstract Iterable getItems() throws IOException; } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 0bdb6db3..468dac7e 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -32,8 +32,7 @@ * Build an image from Dockerfile. * */ -public class BuildImageCmdImpl extends - AbstrDockerCmd implements BuildImageCmd { +public class BuildImageCmdImpl extends AbstrDockerCmd implements BuildImageCmd { private static final Pattern ADD_OR_COPY_PATTERN = Pattern .compile("^(ADD|COPY)\\s+(.*)\\s+(.*)$"); diff --git a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java index 137c008a..1914f91d 100644 --- a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java @@ -2,8 +2,6 @@ import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; -import java.io.InputStream; - import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.PushImageCmd; @@ -12,7 +10,7 @@ * * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. */ -public class PushImageCmdImpl extends AbstrAuthCfgDockerCmd implements PushImageCmd { +public class PushImageCmdImpl extends AbstrAuthCfgDockerCmd implements PushImageCmd { private String name; private String tag; @@ -63,7 +61,7 @@ public String toString() { * @throws NotFoundException No such image */ @Override - public InputStream exec() throws NotFoundException { + public Response exec() throws NotFoundException { return super.exec(); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index 85c5f18c..2b5d9a57 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -1,8 +1,12 @@ package com.github.dockerjava.jaxrs; +import com.google.common.collect.ImmutableList; + import static javax.ws.rs.client.Entity.entity; +import java.io.IOException; import java.io.InputStream; +import java.util.Iterator; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; @@ -13,9 +17,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; import com.github.dockerjava.api.command.BuildImageCmd; +import com.github.dockerjava.api.command.PushImageCmd; +import com.github.dockerjava.api.model.EventStreamItem; +import com.github.dockerjava.api.model.PushEventStreamItem; -public class BuildImageCmdExec extends AbstrDockerCmdExec implements BuildImageCmd.Exec { +public class BuildImageCmdExec extends AbstrDockerCmdExec implements BuildImageCmd.Exec { private static final Logger LOGGER = LoggerFactory .getLogger(BuildImageCmdExec.class); @@ -25,7 +34,7 @@ public BuildImageCmdExec(WebTarget baseResource) { } @Override - protected InputStream execute(BuildImageCmd command) { + protected ResponseImpl execute(BuildImageCmd command) { WebTarget webResource = getBaseResource().path("/build"); if(command.getTag() != null) { @@ -45,12 +54,38 @@ protected InputStream execute(BuildImageCmd command) { webResource.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.CHUNKED); webResource.property(ClientProperties.CHUNKED_ENCODING_SIZE, 1024*1024); - LOGGER.debug("POST: {}", webResource); - return webResource - .request() - .accept(MediaType.TEXT_PLAIN) - .post(entity(command.getTarInputStream(), "application/tar"), Response.class).readEntity(InputStream.class); + + LOGGER.debug("POST: {}", webResource); + InputStream is = webResource + .request() + .accept(MediaType.TEXT_PLAIN) + .post(entity(command.getTarInputStream(), "application/tar"), Response.class).readEntity(InputStream.class); + + return new ResponseImpl(is); } + public static class ResponseImpl extends BuildImageCmd.Response { + + private final InputStream proxy; + + public ResponseImpl(InputStream proxy) { + this.proxy = proxy; + } + + @Override + public Iterable getItems() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + // we'll be reading instances of MyBean + ObjectReader reader = mapper.reader(EventStreamItem.class); + // and then do other configuration, if any, and read: + Iterator items = reader.readValues(proxy); + + return ImmutableList.copyOf(items); + } + @Override + public int read() throws IOException { + return proxy.read(); + } + } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java index b970d42f..838c9b89 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java @@ -1,6 +1,12 @@ package com.github.dockerjava.jaxrs; +import com.google.common.collect.ImmutableList; + +import static javax.ws.rs.client.Entity.entity; + +import java.io.IOException; import java.io.InputStream; +import java.util.Iterator; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; @@ -8,37 +14,70 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; import com.github.dockerjava.api.command.PushImageCmd; +import com.github.dockerjava.api.command.PushImageCmd.Response; import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.PushEventStreamItem; -public class PushImageCmdExec extends - AbstrDockerCmdExec implements - PushImageCmd.Exec { +public class PushImageCmdExec extends AbstrDockerCmdExec implements PushImageCmd.Exec { + private static final Logger LOGGER = LoggerFactory .getLogger(PushImageCmdExec.class); - + public PushImageCmdExec(WebTarget baseResource) { super(baseResource); } @Override - protected InputStream execute(PushImageCmd command) { - WebTarget webResource = getBaseResource().path( - "/images/" + name(command) + "/push").queryParam("tag", - command.getTag()); + protected ResponseImpl execute(PushImageCmd command) { + WebTarget webResource = getBaseResource().path("/images/" + name(command) + "/push") + .queryParam("tag", command.getTag()); final String registryAuth = registryAuth(command.getAuthConfig()); LOGGER.trace("POST: {}", webResource); - return webResource.request().header("X-Registry-Auth", registryAuth) - .accept(MediaType.APPLICATION_JSON).post(null) - .readEntity(InputStream.class); - } + InputStream is = webResource + .request() + .header("X-Registry-Auth", registryAuth) + .accept(MediaType.APPLICATION_JSON) + .post( + entity(Response.class, MediaType.APPLICATION_JSON)).readEntity( + InputStream.class); + return new ResponseImpl(is); + } + private String name(PushImageCmd command) { String name = command.getName(); AuthConfig authConfig = command.getAuthConfig(); return name.contains("/") ? name : authConfig.getUsername(); } + + public static class ResponseImpl extends Response { + + private final InputStream proxy; + + ResponseImpl(InputStream proxy) { + this.proxy = proxy; + } + + @Override + public Iterable getItems() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + // we'll be reading instances of MyBean + ObjectReader reader = mapper.reader(PushEventStreamItem.class); + // and then do other configuration, if any, and read: + Iterator items = reader.readValues(proxy); + + return ImmutableList.copyOf(items); + } + + @Override + public int read() throws IOException { + return proxy.read(); + } + } } diff --git a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java index c63667a0..4fcf26b6 100644 --- a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java +++ b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java @@ -8,6 +8,7 @@ import com.github.dockerjava.api.command.*; import com.github.dockerjava.api.command.AuthCmd.Exec; +import com.github.dockerjava.jaxrs.BuildImageCmdExec; /** * Special {@link DockerCmdExecFactory} implementation that collects container and image creations @@ -92,18 +93,18 @@ public Void exec(RemoveImageCmd command) { public BuildImageCmd.Exec createBuildImageCmdExec() { return new BuildImageCmd.Exec() { @Override - public InputStream exec(BuildImageCmd command) { + public BuildImageCmd.Response exec(BuildImageCmd command) { // can't detect image id here so tagging it String tag = command.getTag(); if(tag == null || "".equals(tag.trim())) { tag = "" + new SecureRandom().nextInt(Integer.MAX_VALUE); command.withTag(tag); } - InputStream inputStream = delegate.createBuildImageCmdExec().exec(command); + InputStream inputStream = delegate.createBuildImageCmdExec().exec(command); imageNames.add(tag); - return inputStream; + return new BuildImageCmdExec.ResponseImpl(inputStream); } - }; + }; } @Override From f18697161e744463be0d033095b450eaf2598cf7 Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Tue, 3 Feb 2015 13:58:09 +0000 Subject: [PATCH 295/452] Repoint to shaded, imported jersey.repackaged guava (!) Signed-off-by: Nigel Magnay --- .../java/com/github/dockerjava/api/model/EventStreamItem.java | 4 +++- .../com/github/dockerjava/api/model/PushEventStreamItem.java | 4 ++-- .../java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java | 4 +++- .../java/com/github/dockerjava/jaxrs/PushImageCmdExec.java | 4 +++- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java b/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java index 98c61a86..6e6ce035 100644 --- a/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java +++ b/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java @@ -1,12 +1,14 @@ package com.github.dockerjava.api.model; -import com.google.common.base.Objects; + import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; +import jersey.repackaged.com.google.common.base.Objects; + /** * Represents an event stream */ diff --git a/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java b/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java index df7f59f5..f5e845b2 100644 --- a/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java +++ b/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java @@ -1,12 +1,12 @@ package com.github.dockerjava.api.model; -import com.google.common.base.Objects; - import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; +import jersey.repackaged.com.google.common.base.Objects; + /** * Represents an item returned from push */ diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index 2b5d9a57..faf3d9f2 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -1,6 +1,6 @@ package com.github.dockerjava.jaxrs; -import com.google.common.collect.ImmutableList; + import static javax.ws.rs.client.Entity.entity; @@ -24,6 +24,8 @@ import com.github.dockerjava.api.model.EventStreamItem; import com.github.dockerjava.api.model.PushEventStreamItem; +import jersey.repackaged.com.google.common.collect.ImmutableList; + public class BuildImageCmdExec extends AbstrDockerCmdExec implements BuildImageCmd.Exec { private static final Logger LOGGER = LoggerFactory diff --git a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java index 838c9b89..152f31a3 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java @@ -1,6 +1,6 @@ package com.github.dockerjava.jaxrs; -import com.google.common.collect.ImmutableList; + import static javax.ws.rs.client.Entity.entity; @@ -21,6 +21,8 @@ import com.github.dockerjava.api.model.AuthConfig; import com.github.dockerjava.api.model.PushEventStreamItem; +// Shaded, but imported +import jersey.repackaged.com.google.common.collect.ImmutableList; public class PushImageCmdExec extends AbstrDockerCmdExec implements PushImageCmd.Exec { From b4d30f68f09587dbbd38dc4c2b98068f6e7dc57c Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Tue, 3 Feb 2015 14:30:56 +0000 Subject: [PATCH 296/452] Update test to show typed API. Signed-off-by: Nigel Magnay --- .../core/command/BuildImageCmdImplTest.java | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index 3692f56d..8be2f8f8 100644 --- a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -27,8 +27,10 @@ import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.command.InspectImageResponse; +import com.github.dockerjava.api.model.EventStreamItem; import com.github.dockerjava.client.AbstractDockerClientTest; + @Test(groups = "integration") public class BuildImageCmdImplTest extends AbstractDockerClientTest { @@ -170,18 +172,24 @@ public void testDockerIgnore() throws DockerException, } @Test - public void testNetCatDockerfileBuilder() throws InterruptedException { + public void testNetCatDockerfileBuilder() throws InterruptedException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("netcat").getFile()); - InputStream response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); + Iterable response = dockerClient.buildImageCmd(baseDir).withNoCache().exec().getItems(); - String fullLog = asString(response); + String imageId = null; + + for(EventStreamItem item : response) { + String text = item.getStream(); + if( text.startsWith("Successfully built ")) { + imageId = StringUtils.substringBetween(text, + "Successfully built ", "\n").trim(); + } + } - assertThat(fullLog, containsString("Successfully built")); + assertNotNull(imageId, "Not successful in build"); - String imageId = StringUtils.substringBetween(fullLog, - "Successfully built ", "\\n\"}").trim(); InspectImageResponse inspectImageResponse = dockerClient .inspectImageCmd(imageId).exec(); From 6fa4cc0225a598fd756f36edabccd311de6c1cc1 Mon Sep 17 00:00:00 2001 From: Ted Crossman Date: Thu, 5 Feb 2015 07:59:12 -0800 Subject: [PATCH 297/452] Only override AuthConfig iff username/password/email/server address are all set Unless this is done, it is possible to create an invalid AuthConfig with null values for password and other fields. --- .../java/com/github/dockerjava/core/DockerClientConfig.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 881a7663..7513c7f2 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -253,7 +253,8 @@ public String getDockerCfgPath() { private AuthConfig getAuthConfig() { AuthConfig authConfig = null; - if(getUsername() != null) { + if (getUsername() != null && getPassword() != null && getEmail() != null + && getServerAddress() != null) { authConfig = new AuthConfig(); authConfig.setUsername(getUsername()); authConfig.setPassword(getPassword()); From ea72e14fd219359a9eab7249e433573daa3b023a Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 5 Feb 2015 20:27:36 +0100 Subject: [PATCH 298/452] Added testcase for conflicting ports binding --- .../command/StartContainerCmdImplTest.java | 385 ++++++++++-------- 1 file changed, 216 insertions(+), 169 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index 10b656e6..7579b5ec 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -17,6 +17,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.InternalServerErrorException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; @@ -77,12 +78,15 @@ public void startContainerWithVolumes() throws DockerException { assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), contains("/opt/webapp1", "/opt/webapp2")); - dockerClient.startContainerCmd(container.getId()).withBinds(new Bind("/src/webapp1", volume1, ro), new Bind("/src/webapp2", volume2)).exec(); + dockerClient + .startContainerCmd(container.getId()) + .withBinds(new Bind("/src/webapp1", volume1, ro), + new Bind("/src/webapp2", volume2)).exec(); dockerClient.waitContainerCmd(container.getId()).exec(); - inspectContainerResponse = dockerClient.inspectContainerCmd(container - .getId()).exec(); + inspectContainerResponse = dockerClient.inspectContainerCmd( + container.getId()).exec(); assertContainerHasVolumes(inspectContainerResponse, volume1, volume2); @@ -98,27 +102,29 @@ public void startContainerWithVolumesFrom() throws DockerException { Volume volume2 = new Volume("/opt/webapp2"); String container1Name = UUID.randomUUID().toString(); - + CreateContainerResponse container1 = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999") .withName(container1Name).exec(); LOG.info("Created container1 {}", container1.toString()); - dockerClient.startContainerCmd(container1.getId()).withBinds( - new Bind("/src/webapp1", volume1), new Bind("/src/webapp2", volume2)).exec(); + dockerClient + .startContainerCmd(container1.getId()) + .withBinds(new Bind("/src/webapp1", volume1), + new Bind("/src/webapp2", volume2)).exec(); LOG.info("Started container1 {}", container1.toString()); - InspectContainerResponse inspectContainerResponse1 = dockerClient.inspectContainerCmd( - container1.getId()).exec(); + InspectContainerResponse inspectContainerResponse1 = dockerClient + .inspectContainerCmd(container1.getId()).exec(); assertContainerHasVolumes(inspectContainerResponse1, volume1, volume2); - CreateContainerResponse container2 = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); LOG.info("Created container2 {}", container2.toString()); - dockerClient.startContainerCmd(container2.getId()).withVolumesFrom(container1Name).exec(); + dockerClient.startContainerCmd(container2.getId()) + .withVolumesFrom(container1Name).exec(); LOG.info("Started container2 {}", container2.toString()); InspectContainerResponse inspectContainerResponse2 = dockerClient @@ -134,30 +140,29 @@ public void startContainerWithDns() throws DockerException { String anotherDnsServer = "8.8.4.4"; CreateContainerResponse container = dockerClient - .createContainerCmd("busybox") - .withCmd("true").exec(); + .createContainerCmd("busybox").withCmd("true").exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); - dockerClient.startContainerCmd(container.getId()).withDns(aDnsServer, anotherDnsServer).exec(); + dockerClient.startContainerCmd(container.getId()) + .withDns(aDnsServer, anotherDnsServer).exec(); - InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container - .getId()).exec(); + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); - assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getDns()), - contains(aDnsServer, anotherDnsServer)); + assertThat(Arrays.asList(inspectContainerResponse.getHostConfig() + .getDns()), contains(aDnsServer, anotherDnsServer)); } - + @Test public void startContainerWithDnsSearch() throws DockerException { String dnsSearch = "example.com"; - + CreateContainerResponse container = dockerClient - .createContainerCmd("busybox") - .withCmd("true").exec(); + .createContainerCmd("busybox").withCmd("true").exec(); LOG.info("Created container {}", container.toString()); @@ -166,15 +171,16 @@ public void startContainerWithDnsSearch() throws DockerException { InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); - dockerClient.startContainerCmd(container.getId()).withDnsSearch(dnsSearch).exec(); + dockerClient.startContainerCmd(container.getId()) + .withDnsSearch(dnsSearch).exec(); - inspectContainerResponse = dockerClient.inspectContainerCmd(container - .getId()).exec(); + inspectContainerResponse = dockerClient.inspectContainerCmd( + container.getId()).exec(); - assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getDnsSearch()), - contains(dnsSearch)); + assertThat(Arrays.asList(inspectContainerResponse.getHostConfig() + .getDnsSearch()), contains(dnsSearch)); } - + @Test public void startContainerWithPortBindings() throws DockerException { @@ -182,8 +188,8 @@ public void startContainerWithPortBindings() throws DockerException { ExposedPort tcp23 = ExposedPort.tcp(23); CreateContainerResponse container = dockerClient - .createContainerCmd("busybox") - .withCmd("true").withExposedPorts(tcp22, tcp23).exec(); + .createContainerCmd("busybox").withCmd("true") + .withExposedPorts(tcp22, tcp23).exec(); LOG.info("Created container {}", container.toString()); @@ -197,22 +203,52 @@ public void startContainerWithPortBindings() throws DockerException { portBindings.bind(tcp23, Ports.Binding(11023)); portBindings.bind(tcp23, Ports.Binding(11024)); - dockerClient.startContainerCmd(container.getId()).withPortBindings(portBindings).exec(); + dockerClient.startContainerCmd(container.getId()) + .withPortBindings(portBindings).exec(); + + inspectContainerResponse = dockerClient.inspectContainerCmd( + container.getId()).exec(); + + assertThat(Arrays.asList(inspectContainerResponse.getConfig() + .getExposedPorts()), contains(tcp22, tcp23)); + + assertThat(inspectContainerResponse.getHostConfig().getPortBindings() + .getBindings().get(tcp22)[0], is(equalTo(Ports.Binding(11022)))); + + assertThat(inspectContainerResponse.getHostConfig().getPortBindings() + .getBindings().get(tcp23)[0], is(equalTo(Ports.Binding(11023)))); + + assertThat(inspectContainerResponse.getHostConfig().getPortBindings() + .getBindings().get(tcp23)[1], is(equalTo(Ports.Binding(11024)))); + + } + + @Test + public void startContainerWithConflictingPortBindings() + throws DockerException { + + ExposedPort tcp22 = ExposedPort.tcp(22); + ExposedPort tcp23 = ExposedPort.tcp(23); + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("true") + .withExposedPorts(tcp22, tcp23).exec(); - inspectContainerResponse = dockerClient.inspectContainerCmd(container - .getId()).exec(); + LOG.info("Created container {}", container.toString()); - assertThat(Arrays.asList(inspectContainerResponse.getConfig().getExposedPorts()), - contains(tcp22, tcp23)); + assertThat(container.getId(), not(isEmptyString())); - assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp22)[0], - is(equalTo(Ports.Binding(11022)))); + Ports portBindings = new Ports(); + portBindings.bind(tcp22, Ports.Binding(11022)); + portBindings.bind(tcp23, Ports.Binding(11022)); - assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23)[0], - is(equalTo(Ports.Binding(11023)))); + try { + dockerClient.startContainerCmd(container.getId()) + .withPortBindings(portBindings).exec(); + fail("expected InternalServerErrorException"); + } catch (InternalServerErrorException e) { - assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23)[1], - is(equalTo(Ports.Binding(11024)))); + } } @@ -220,11 +256,12 @@ public void startContainerWithPortBindings() throws DockerException { public void startContainerWithLinking() throws DockerException { CreateContainerResponse container1 = dockerClient - .createContainerCmd("busybox").withCmd("sleep", "9999").withName("container1").exec(); + .createContainerCmd("busybox").withCmd("sleep", "9999") + .withName("container1").exec(); LOG.info("Created container1 {}", container1.toString()); assertThat(container1.getId(), not(isEmptyString())); - + dockerClient.startContainerCmd(container1.getId()).exec(); InspectContainerResponse inspectContainerResponse1 = dockerClient @@ -233,7 +270,8 @@ public void startContainerWithLinking() throws DockerException { assertThat(inspectContainerResponse1.getConfig(), is(notNullValue())); assertThat(inspectContainerResponse1.getId(), not(isEmptyString())); - assertThat(inspectContainerResponse1.getId(), startsWith(container1.getId())); + assertThat(inspectContainerResponse1.getId(), + startsWith(container1.getId())); assertThat(inspectContainerResponse1.getName(), equalTo("/container1")); assertThat(inspectContainerResponse1.getImageId(), not(isEmptyString())); assertThat(inspectContainerResponse1.getState(), is(notNullValue())); @@ -245,12 +283,14 @@ public void startContainerWithLinking() throws DockerException { } CreateContainerResponse container2 = dockerClient - .createContainerCmd("busybox").withCmd("true").withName("container2").exec(); + .createContainerCmd("busybox").withCmd("true") + .withName("container2").exec(); LOG.info("Created container2 {}", container2.toString()); assertThat(container2.getId(), not(isEmptyString())); - - dockerClient.startContainerCmd(container2.getId()).withLinks(new Link("container1", "container1Link")).exec(); + + dockerClient.startContainerCmd(container2.getId()) + .withLinks(new Link("container1", "container1Link")).exec(); InspectContainerResponse inspectContainerResponse2 = dockerClient .inspectContainerCmd(container2.getId()).exec(); @@ -258,10 +298,15 @@ public void startContainerWithLinking() throws DockerException { assertThat(inspectContainerResponse2.getConfig(), is(notNullValue())); assertThat(inspectContainerResponse2.getId(), not(isEmptyString())); - assertThat(inspectContainerResponse2.getHostConfig(), is(notNullValue())); - assertThat(inspectContainerResponse2.getHostConfig().getLinks(), is(notNullValue())); - assertThat(inspectContainerResponse2.getHostConfig().getLinks().getLinks(), equalTo(new Link[] {new Link("container1","container1Link")})); - assertThat(inspectContainerResponse2.getId(), startsWith(container2.getId())); + assertThat(inspectContainerResponse2.getHostConfig(), + is(notNullValue())); + assertThat(inspectContainerResponse2.getHostConfig().getLinks(), + is(notNullValue())); + assertThat(inspectContainerResponse2.getHostConfig().getLinks() + .getLinks(), equalTo(new Link[] { new Link("container1", + "container1Link") })); + assertThat(inspectContainerResponse2.getId(), + startsWith(container2.getId())); assertThat(inspectContainerResponse2.getName(), equalTo("/container2")); assertThat(inspectContainerResponse2.getImageId(), not(isEmptyString())); assertThat(inspectContainerResponse2.getState(), is(notNullValue())); @@ -269,16 +314,16 @@ public void startContainerWithLinking() throws DockerException { } - @Test public void startContainer() throws DockerException { CreateContainerResponse container = dockerClient - .createContainerCmd("busybox").withCmd(new String[] { "top" }).exec(); + .createContainerCmd("busybox").withCmd(new String[] { "top" }) + .exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); - + dockerClient.startContainerCmd(container.getId()).exec(); InspectContainerResponse inspectContainerResponse = dockerClient @@ -301,7 +346,7 @@ public void startContainer() throws DockerException { is(equalTo(0))); } } - + @Test public void testStartNonExistingContainer() throws DockerException { try { @@ -310,171 +355,173 @@ public void testStartNonExistingContainer() throws DockerException { } catch (NotFoundException e) { } } - + /** * This tests support for --net option for the docker run command: - * --net="bridge" Set the Network mode for the container - * 'bridge': creates a new network stack for the container on the docker bridge - * 'none': no networking for this container - * 'container:': reuses another container network stack - * 'host': use the host network stack inside the container. - * Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure. + * --net="bridge" Set the Network mode for the container 'bridge': creates a + * new network stack for the container on the docker bridge 'none': no + * networking for this container 'container:': reuses another container + * network stack 'host': use the host network stack inside the container. + * Note: the host mode gives the container full access to local system + * services such as D-bus and is therefore considered insecure. */ @Test - public void startContainerWithNetworkMode() throws DockerException { + public void startContainerWithNetworkMode() throws DockerException { + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("true").exec(); + + LOG.info("Created container {}", container.toString()); - CreateContainerResponse container = dockerClient - .createContainerCmd("busybox") - .withCmd("true").exec(); + assertThat(container.getId(), not(isEmptyString())); - LOG.info("Created container {}", container.toString()); + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); - assertThat(container.getId(), not(isEmptyString())); - - InspectContainerResponse inspectContainerResponse = dockerClient - .inspectContainerCmd(container.getId()).exec(); + dockerClient.startContainerCmd(container.getId()) + .withNetworkMode("host").exec(); - dockerClient.startContainerCmd(container.getId()).withNetworkMode("host").exec(); + inspectContainerResponse = dockerClient.inspectContainerCmd( + container.getId()).exec(); - inspectContainerResponse = dockerClient.inspectContainerCmd(container - .getId()).exec(); + assertThat(inspectContainerResponse.getHostConfig().getNetworkMode(), + is(equalTo("host"))); + } - assertThat(inspectContainerResponse.getHostConfig().getNetworkMode(), - is(equalTo("host"))); - } - @Test - public void startContainerWithCapAddAndCapDrop() throws DockerException { + public void startContainerWithCapAddAndCapDrop() throws DockerException { - CreateContainerResponse container = dockerClient - .createContainerCmd("busybox") - .withCmd("sleep", "9999").exec(); + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); - LOG.info("Created container {}", container.toString()); + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + dockerClient.startContainerCmd(container.getId()).withCapAdd(NET_ADMIN) + .withCapDrop(MKNOD).exec(); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); - assertThat(container.getId(), not(isEmptyString())); + assertThat(inspectContainerResponse.getState().isRunning(), is(true)); - dockerClient.startContainerCmd(container.getId()) - .withCapAdd(NET_ADMIN) - .withCapDrop(MKNOD).exec(); + assertThat(Arrays.asList(inspectContainerResponse.getHostConfig() + .getCapAdd()), contains(NET_ADMIN)); - InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container - .getId()).exec(); - - assertThat(inspectContainerResponse.getState().isRunning(), is(true)); + assertThat(Arrays.asList(inspectContainerResponse.getHostConfig() + .getCapDrop()), contains(MKNOD)); + } - assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getCapAdd()), - contains(NET_ADMIN)); - - assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getCapDrop()), - contains(MKNOD)); - } - @Test - public void startContainerWithDevices() throws DockerException { + public void startContainerWithDevices() throws DockerException { + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); - CreateContainerResponse container = dockerClient - .createContainerCmd("busybox") - .withCmd("sleep", "9999").exec(); + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); - LOG.info("Created container {}", container.toString()); + dockerClient.startContainerCmd(container.getId()) + .withDevices(new Device("rwm", "/dev/nulo", "/dev/zero")) + .exec(); - assertThat(container.getId(), not(isEmptyString())); + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); - dockerClient.startContainerCmd(container.getId()) - .withDevices(new Device("rwm", "/dev/nulo", "/dev/zero")) - .exec(); + assertThat(inspectContainerResponse.getState().isRunning(), is(true)); - InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container - .getId()).exec(); - - assertThat(inspectContainerResponse.getState().isRunning(), is(true)); + assertThat(Arrays.asList(inspectContainerResponse.getHostConfig() + .getDevices()), contains(new Device("rwm", "/dev/nulo", + "/dev/zero"))); + } - assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getDevices()), - contains(new Device("rwm", "/dev/nulo", "/dev/zero"))); - } - @Test - public void startContainerWithRestartPolicy() throws DockerException { + public void startContainerWithRestartPolicy() throws DockerException { - CreateContainerResponse container = dockerClient - .createContainerCmd("busybox") - .withCmd("sleep", "9999").exec(); + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999").exec(); - LOG.info("Created container {}", container.toString()); + LOG.info("Created container {}", container.toString()); - assertThat(container.getId(), not(isEmptyString())); + assertThat(container.getId(), not(isEmptyString())); - RestartPolicy restartPolicy = RestartPolicy.onFailureRestart(5); - - dockerClient.startContainerCmd(container.getId()) - .withRestartPolicy(restartPolicy) - .exec(); + RestartPolicy restartPolicy = RestartPolicy.onFailureRestart(5); - InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container - .getId()).exec(); - - assertThat(inspectContainerResponse.getState().isRunning(), is(true)); + dockerClient.startContainerCmd(container.getId()) + .withRestartPolicy(restartPolicy).exec(); - assertThat(inspectContainerResponse.getHostConfig().getRestartPolicy(), - is(equalTo(restartPolicy))); - } + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + assertThat(inspectContainerResponse.getState().isRunning(), is(true)); + + assertThat(inspectContainerResponse.getHostConfig().getRestartPolicy(), + is(equalTo(restartPolicy))); + } @Test - public void existingHostConfigIsPreservedByBlankStartCmd() throws DockerException { - + public void existingHostConfigIsPreservedByBlankStartCmd() + throws DockerException { + String dnsServer = "8.8.8.8"; - - // prepare a container with custom DNS + + // prepare a container with custom DNS CreateContainerResponse container = dockerClient - .createContainerCmd("busybox") - .withDns(dnsServer) + .createContainerCmd("busybox").withDns(dnsServer) .withCmd("true").exec(); - + LOG.info("Created container {}", container.toString()); - + assertThat(container.getId(), not(isEmptyString())); - - // start container _without_any_customization_ (important!) + + // start container _without_any_customization_ (important!) dockerClient.startContainerCmd(container.getId()).exec(); - - InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container - .getId()).exec(); - + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + // The DNS setting survived. - assertThat(inspectContainerResponse.getHostConfig().getDns(), is(notNullValue())); - assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getDns()), - contains(dnsServer)); + assertThat(inspectContainerResponse.getHostConfig().getDns(), + is(notNullValue())); + assertThat(Arrays.asList(inspectContainerResponse.getHostConfig() + .getDns()), contains(dnsServer)); } @Test - public void existingHostConfigIsResetByConfiguredStartCmd() throws DockerException { - // As of version 1.3.2, Docker assumes that you either configure a container - // when creating it or when starting it, but not mixing both. + public void existingHostConfigIsResetByConfiguredStartCmd() + throws DockerException { + // As of version 1.3.2, Docker assumes that you either configure a + // container + // when creating it or when starting it, but not mixing both. // See https://github.com/docker-java/docker-java/pull/111 - // If this test starts to fail, this behavior changed and a review of implementation + // If this test starts to fail, this behavior changed and a review of + // implementation // and documentation might be needed. - + String dnsServer = "8.8.8.8"; - - // prepare a container with custom DNS + + // prepare a container with custom DNS CreateContainerResponse container = dockerClient - .createContainerCmd("busybox") - .withDns(dnsServer) + .createContainerCmd("busybox").withDns(dnsServer) .withCmd("true").exec(); - + LOG.info("Created container {}", container.toString()); - + assertThat(container.getId(), not(isEmptyString())); - - // modify another setting in start command. Leave DNS unchanged. - dockerClient.startContainerCmd(container.getId()).withPublishAllPorts(true).exec(); - - InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container - .getId()).exec(); - - // although start did not modify DNS Settings, they were reset to their default. - assertThat(inspectContainerResponse.getHostConfig().getDns(), is(nullValue(String[].class))); + + // modify another setting in start command. Leave DNS unchanged. + dockerClient.startContainerCmd(container.getId()) + .withPublishAllPorts(true).exec(); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + // although start did not modify DNS Settings, they were reset to their + // default. + assertThat(inspectContainerResponse.getHostConfig().getDns(), + is(nullValue(String[].class))); } @Test From ad3277235c55d29df40692295a05b989315bec03 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 5 Feb 2015 22:26:38 +0100 Subject: [PATCH 299/452] Fix events tests --- .../dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java | 2 +- .../com/github/dockerjava/core/command/EventsCmdImplTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java index 42158e01..af141bf3 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java @@ -57,7 +57,7 @@ public void filter(ClientRequestContext requestContext, ClientResponseContext re } } - public String getBodyAsMessage(ClientResponseContext responseContext) + private String getBodyAsMessage(ClientResponseContext responseContext) throws IOException { if (responseContext.hasEntity()) { int contentLength = responseContext.getLength(); diff --git a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java index 941657a1..4d0b0c15 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java @@ -99,7 +99,7 @@ private int generateEvents() { String testImage = "busybox"; asString(dockerClient.pullImageCmd(testImage).exec()); CreateContainerResponse container = dockerClient - .createContainerCmd(testImage).withCmd("echo").exec(); + .createContainerCmd(testImage).withCmd("sleep 9999").exec(); dockerClient.startContainerCmd(container.getId()).exec(); dockerClient.stopContainerCmd(container.getId()).exec(); return KNOWN_NUM_EVENTS; From 62cd7e9dd53e500216bf913c7c89463ccb3cf312 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 5 Feb 2015 22:26:38 +0100 Subject: [PATCH 300/452] Fix events tests --- .../dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java | 2 +- .../com/github/dockerjava/core/command/EventsCmdImplTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java b/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java index 42158e01..af141bf3 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java +++ b/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java @@ -57,7 +57,7 @@ public void filter(ClientRequestContext requestContext, ClientResponseContext re } } - public String getBodyAsMessage(ClientResponseContext responseContext) + private String getBodyAsMessage(ClientResponseContext responseContext) throws IOException { if (responseContext.hasEntity()) { int contentLength = responseContext.getLength(); diff --git a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java index 941657a1..6f227e43 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java @@ -99,7 +99,7 @@ private int generateEvents() { String testImage = "busybox"; asString(dockerClient.pullImageCmd(testImage).exec()); CreateContainerResponse container = dockerClient - .createContainerCmd(testImage).withCmd("echo").exec(); + .createContainerCmd(testImage).withCmd("sleep", "9999").exec(); dockerClient.startContainerCmd(container.getId()).exec(); dockerClient.stopContainerCmd(container.getId()).exec(); return KNOWN_NUM_EVENTS; From e820c21208343856016a7f2d93e2f4ab3bcfe16d Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Fri, 6 Feb 2015 13:45:53 +0000 Subject: [PATCH 301/452] Introduce the notion of a Dockerfile, which can read specifications and generate the resultant TAR file. Splitting the file down into statements makes it easier to understand and extend, particularly around property replacements. This separates out the functionality from BuildImageCmd so that it can be tested separately, and re-used elsewhere. Signed-off-by: Nigel Magnay --- .../core/dockerfile/Dockerfile.java | 282 ++++++++++++++++++ .../core/dockerfile/DockerfileStatement.java | 208 +++++++++++++ .../core/dockerfile/DockerfileTest.java | 50 ++++ 3 files changed, 540 insertions(+) create mode 100644 src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java create mode 100644 src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java create mode 100644 src/test/java/com/github/dockerjava/core/dockerfile/DockerfileTest.java diff --git a/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java b/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java new file mode 100644 index 00000000..72c6c795 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java @@ -0,0 +1,282 @@ +package com.github.dockerjava.core.dockerfile; + +import com.github.dockerjava.api.DockerClientException; +import com.github.dockerjava.core.CompressArchiveUtil; +import com.github.dockerjava.core.GoLangFileMatch; +import com.github.dockerjava.core.GoLangFileMatchException; +import com.github.dockerjava.core.GoLangMatchFileFilter; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.filefilter.TrueFileFilter; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import jersey.repackaged.com.google.common.base.Function; +import jersey.repackaged.com.google.common.base.Objects; +import jersey.repackaged.com.google.common.base.Optional; +import jersey.repackaged.com.google.common.base.Predicate; +import jersey.repackaged.com.google.common.collect.Collections2; + +/** + * Parse a Dockerfile. + */ +public class Dockerfile { + + public final File dockerFile; + + public Dockerfile(File dockerFile) { + + if (!dockerFile.exists()) { + throw new IllegalStateException( + String.format("Dockerfile %s does not exist", dockerFile.getAbsolutePath())); + } + + if (!dockerFile.isFile()) { + throw new IllegalStateException( + String.format("Dockerfile %s is not a file", dockerFile.getAbsolutePath())); + } + + this.dockerFile = dockerFile; + + } + + private static class LineTransformer + implements Function> { + + private int line = 0; + + @Override + public Optional apply(String input) { + try { + line++; + return DockerfileStatement.createFromLine(input); + + } catch (Exception ex) { + throw new DockerClientException("Error on dockerfile line " + line); + } + } + } + + /** + * Not needed in modern guava + */ + private static class MissingOptionalFilter + implements Predicate> { + + @Override + public boolean apply(Optional optional) { + return (optional.orNull() != null); + } + } + + /** + * Not needed in modern guava + */ + private static class OptionalItemTransformer + implements Function, DockerfileStatement> { + + @Override + public DockerfileStatement apply(Optional optional) { + return optional.orNull(); + } + } + + public Collection getStatements() throws IOException { + Collection dockerFileContent = FileUtils.readLines(dockerFile); + + if (dockerFileContent.size() <= 0) { + throw new DockerClientException(String.format( + "Dockerfile %s is empty", dockerFile)); + } + + Collection> optionals = Collections2 + .transform(dockerFileContent, new LineTransformer()); + + // Modern guava would be done here, + // With simply return Optional.presentInstances( optionals ); + // + // So this entire function could simply be + // return Optional.presentInstances( Collections2.transform( FileUtils.readLines(dockerFile), new LineTransformer() ) ); + // + // Until the dawn of that day, do it manually + + return Collections2.transform(Collections2.filter(optionals, new MissingOptionalFilter()), + new OptionalItemTransformer()); + + } + + public List getIgnores() throws IOException { + List ignores = new ArrayList(); + File dockerIgnoreFile = new File(getDockerFolder(), ".dockerignore"); + if (dockerIgnoreFile.exists()) { + int lineNumber = 0; + List dockerIgnoreFileContent = FileUtils.readLines(dockerIgnoreFile); + for (String pattern : dockerIgnoreFileContent) { + lineNumber++; + pattern = pattern.trim(); + if (pattern.isEmpty()) { + continue; // skip empty lines + } + pattern = FilenameUtils.normalize(pattern); + try { + // validate pattern and make sure we aren't excluding Dockerfile + if (GoLangFileMatch.match(pattern, "Dockerfile")) { + throw new DockerClientException( + String.format( + "Dockerfile is excluded by pattern '%s' on line %s in .dockerignore file", + pattern, lineNumber)); + } + ignores.add(pattern); + } catch (GoLangFileMatchException e) { + throw new DockerClientException(String.format( + "Invalid pattern '%s' on line %s in .dockerignore file", pattern, lineNumber)); + } + } + } + return ignores; + } + + + public ScannedResult parse() throws IOException { + return new ScannedResult(); + } + + + public File getDockerFolder() { + return dockerFile.getParentFile(); + } + + + /** + * Result of scanning / parsing a docker file. + */ + public class ScannedResult { + + final List ignores; + final Map environmentMap = new HashMap(); + final List filesToAdd = new ArrayList(); + + public InputStream buildDockerFolderTar() { + + // ARCHIVE TAR + File dockerFolderTar = null; + + try { + String archiveNameWithOutExtension = UUID.randomUUID().toString(); + + dockerFolderTar = CompressArchiveUtil.archiveTARFiles(getDockerFolder(), + filesToAdd, + archiveNameWithOutExtension); + return FileUtils.openInputStream(dockerFolderTar); + + } catch (IOException ex) { + FileUtils.deleteQuietly(dockerFolderTar); + throw new DockerClientException( + "Error occurred while preparing Docker context folder.", ex); + } + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("ignores", ignores) + .add("environmentMap", environmentMap) + .add("filesToAdd", filesToAdd) + .toString(); + } + + public ScannedResult() throws IOException { + + ignores = getIgnores(); + filesToAdd.add(dockerFile); + + for (DockerfileStatement statement : getStatements()) { + if (statement instanceof DockerfileStatement.Env) { + processEnvStatement((DockerfileStatement.Env) statement); + } else if (statement instanceof DockerfileStatement.Add) { + processAddStatement((DockerfileStatement.Add) statement); + } + } + } + + private void processAddStatement(DockerfileStatement.Add add) throws IOException { + + add = add.transform(environmentMap); + + if (add.isFileResource()) { + + File dockerFolder = getDockerFolder(); + String resource = add.source; + + File src = new File(resource); + if (!src.isAbsolute()) { + src = new File(dockerFolder, resource) + .getCanonicalFile(); + } else { + throw new DockerClientException(String.format( + "Source file %s must be relative to %s", + src, dockerFolder)); + } + + // if (!src.exists()) { + // throw new DockerClientException(String.format( + // "Source file %s doesn't exist", src)); + // } + if (src.isDirectory()) { + Collection files = FileUtils.listFiles(src, + new GoLangMatchFileFilter(src, ignores), + TrueFileFilter.INSTANCE); + filesToAdd.addAll(files); + } else if (!src.exists()) { + filesToAdd.addAll(resolveWildcards(src, ignores)); + } else if (!GoLangFileMatch.match(ignores, + CompressArchiveUtil.relativize(dockerFolder, + src))) { + filesToAdd.add(src); + } else { + throw new DockerClientException( + String.format( + "Source file %s is excluded by .dockerignore file", + src)); + } + } + } + + private Collection resolveWildcards(File file, List ignores) { + List filesToAdd = new ArrayList(); + + File parent = file.getParentFile(); + if (parent != null) { + if (parent.isDirectory()) { + Collection files = FileUtils.listFiles(parent, + new GoLangMatchFileFilter(parent, ignores), + TrueFileFilter.INSTANCE); + filesToAdd.addAll(files); + } else { + filesToAdd.addAll(resolveWildcards(parent, ignores)); + } + } else { + throw new DockerClientException(String.format( + "Source file %s doesn't exist", file)); + } + + return filesToAdd; + } + + private void processEnvStatement(DockerfileStatement.Env env) { + + environmentMap.put(env.variable, env.value); + } + + } + +} diff --git a/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java b/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java new file mode 100644 index 00000000..1e2ddf1b --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java @@ -0,0 +1,208 @@ +package com.github.dockerjava.core.dockerfile; + +import com.github.dockerjava.api.DockerClientException; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import jersey.repackaged.com.google.common.base.Objects; +import jersey.repackaged.com.google.common.base.Optional; + +/** + * A statement present in a dockerfile. + */ +public abstract class DockerfileStatement { + + private DockerfileStatement() { + } + + public T transform(Map env) { + return (T) this; + } + + protected String filterForEnvironmentVars(Map environmentMap, + String extractedResource) { + + if (environmentMap.size() > 0) { + + String currentResourceContent = extractedResource; + + for (Map.Entry entry : environmentMap.entrySet()) { + + String variable = entry.getKey(); + + String replacementValue = entry.getValue(); + + // handle: $VARIABLE case + currentResourceContent = currentResourceContent.replaceAll( + "\\$" + variable, replacementValue); + + // handle ${VARIABLE} case + currentResourceContent = currentResourceContent.replaceAll( + "\\$\\{" + variable + "\\}", replacementValue); + + } + + return currentResourceContent; + } else { + return extractedResource; + } + } + + + /** + * A statement that we don't particularly care about. + */ + public static class OtherLine extends DockerfileStatement { + + public final String statement; + + public OtherLine(String statement) { + this.statement = statement; + } + + @Override + public String toString() { + return statement; + } + } + + /** + * An ADD or a COPY + */ + public static class Add extends DockerfileStatement { + + private static final Pattern ADD_OR_COPY_PATTERN = Pattern + .compile("^(ADD|COPY)\\s+(.*)\\s+(.*)$"); + + public final String source; + public final String destination; + + private Add(String source, String destination) { + this.source = source; + this.destination = destination; + } + + private Add(final Matcher matcher) { + source = matcher.group(2); + destination = matcher.group(3); + } + + @Override + public Add transform(Map env) { + String resource = filterForEnvironmentVars(env, source).trim(); + return new Add(resource, destination); + } + + public boolean isFileResource() { + URI uri; + try { + uri = new URI(source); + } catch (URISyntaxException e) { + return false; + } + return uri.getScheme() == null || "file".equals(uri.getScheme()); + } + + /** + * Createa an Add if it matches, or missing if not. + * + * @param statement statement that may be an ADD or a COPY + * @return optional typed item. + */ + public static Optional create(String statement) { + Matcher matcher = ADD_OR_COPY_PATTERN.matcher(statement.trim()); + if (!matcher.find()) { + return Optional.absent(); + } + + if (matcher.groupCount() != 3) { + throw new DockerClientException("Wrong ADD or COPY format"); + } + + return Optional.of(new Add(matcher)); + } + + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("source", source) + .add("destination", destination) + .toString(); + } + } + + public static class Env extends DockerfileStatement { + + private static final Pattern ENV_PATTERN = Pattern + .compile("^ENV\\s+(.*)\\s+(.*)$"); + + public final String variable; + public final String value; + + private Env(String variable, String value) { + this.variable = variable; + this.value = value; + } + + private Env(Matcher envMatcher) { + this.variable = envMatcher.group(1).trim(); + this.value = envMatcher.group(2).trim(); + } + + public static Optional create(String statement) { + Matcher matcher = ENV_PATTERN.matcher(statement.trim()); + if (!matcher.find()) { + return Optional.absent(); + } + + if (matcher.groupCount() != 2) { + throw new DockerClientException("Wrong ENV format"); + } + + return Optional.of(new Env(matcher)); + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("variable", variable) + .add("value", value) + .toString(); + } + } + + /** + * Return a dockerfile statement + */ + public static Optional createFromLine(String cmd) { + if (cmd.trim().isEmpty() || cmd.startsWith("#")) { + return Optional.absent(); + } + + Optional line; + + line = Add.create(cmd); + + // if (line.isPresent()) { : Newer guava + if (line.orNull() != null) { + return line; + } + + line = Env.create(cmd); + + // if (line.isPresent()) { : Newer guava + if (line.orNull() != null) { + return line; + } + + return Optional.of(new OtherLine(cmd)); + + + } + +} diff --git a/src/test/java/com/github/dockerjava/core/dockerfile/DockerfileTest.java b/src/test/java/com/github/dockerjava/core/dockerfile/DockerfileTest.java new file mode 100644 index 00000000..428511c2 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/dockerfile/DockerfileTest.java @@ -0,0 +1,50 @@ +package com.github.dockerjava.core.dockerfile; + +import junit.framework.TestCase; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class DockerfileTest extends TestCase { + + private static final Logger log = LoggerFactory.getLogger(DockerfileTest.class); + + @Test + public void testAllItems() throws IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("netcat").getFile()); + + File root = baseDir.getParentFile(); + + Map dockerfiles = new HashMap(); + Map results = new HashMap(); + + for (File child : root.listFiles()) { + if (new File(child, "Dockerfile").exists()) { + Dockerfile dockerfile = new Dockerfile(new File(child, "Dockerfile")); + dockerfiles.put(child.getName(), dockerfile); + } + } + + for (String name : dockerfiles.keySet()) { + log.info("Scanning {}", name); + try { + results.put(name, dockerfiles.get(name).parse()); + } catch (Exception ex) { + log.error("Error in {}", name, ex); + } + + } + + for (String name : results.keySet()) { + log.info("Name: {} = {}", name, results.get(name)); + } + } + +} \ No newline at end of file From 509bd2e9a1a95910e2f446642f7e764a36452e0f Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Fri, 6 Feb 2015 13:54:23 +0000 Subject: [PATCH 302/452] Make BuildImage use DockerFile impl. Signed-off-by: Nigel Magnay --- .../core/command/BuildImageCmdImpl.java | 213 +----------------- 1 file changed, 6 insertions(+), 207 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 468dac7e..0634651b 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -24,6 +24,7 @@ import com.github.dockerjava.core.GoLangFileMatch; import com.github.dockerjava.core.GoLangFileMatchException; import com.github.dockerjava.core.GoLangMatchFileFilter; +import com.github.dockerjava.core.dockerfile.Dockerfile; import static jersey.repackaged.com.google.common.base.Preconditions.*; @@ -34,14 +35,8 @@ */ public class BuildImageCmdImpl extends AbstrDockerCmd implements BuildImageCmd { - private static final Pattern ADD_OR_COPY_PATTERN = Pattern - .compile("^(ADD|COPY)\\s+(.*)\\s+(.*)$"); - - private static final Pattern ENV_PATTERN = Pattern - .compile("^ENV\\s+(.*)\\s+(.*)$"); private InputStream tarInputStream = null; - private File tarFile = null; private String tag; private boolean noCache; private boolean remove = true; @@ -50,9 +45,12 @@ public class BuildImageCmdImpl extends AbstrDockerCmd dockerFileContent = FileUtils.readLines(dockerFile); - - if (dockerFileContent.size() <= 0) { - throw new DockerClientException(String.format( - "Dockerfile %s is empty", dockerFile)); - } - - List ignores = new ArrayList(); - File dockerIgnoreFile = new File(dockerFolder, ".dockerignore"); - if (dockerIgnoreFile.exists()) { - int lineNumber = 0; - List dockerIgnoreFileContent = FileUtils - .readLines(dockerIgnoreFile); - for (String pattern : dockerIgnoreFileContent) { - lineNumber++; - pattern = pattern.trim(); - if (pattern.isEmpty()) { - continue; // skip empty lines - } - pattern = FilenameUtils.normalize(pattern); - try { - // validate pattern and make sure we aren't excluding - // Dockerfile - if (GoLangFileMatch.match(pattern, "Dockerfile")) { - throw new DockerClientException( - String.format( - "Dockerfile is excluded by pattern '%s' on line %s in .dockerignore file", - pattern, lineNumber)); - } - ignores.add(pattern); - } catch (GoLangFileMatchException e) { - throw new DockerClientException( - String.format( - "Invalid pattern '%s' on line %s in .dockerignore file", - pattern, lineNumber)); - } - } - } - List filesToAdd = new ArrayList(); - filesToAdd.add(dockerFile); - - Map environmentMap = new HashMap(); - - int lineNumber = 0; - - for (String cmd : dockerFileContent) { - - lineNumber++; - - if (cmd.trim().isEmpty() || cmd.startsWith("#")) - continue; // skip emtpy and commend lines - - final Matcher envMatcher = ENV_PATTERN.matcher(cmd.trim()); - - if (envMatcher.find()) { - if (envMatcher.groupCount() != 2) - throw new DockerClientException(String.format( - "Wrong ENV format on line [%d]", lineNumber)); - - String variable = envMatcher.group(1).trim(); - - String value = envMatcher.group(2).trim(); - - environmentMap.put(variable, value); - } - - final Matcher matcher = ADD_OR_COPY_PATTERN.matcher(cmd.trim()); - if (matcher.find()) { - if (matcher.groupCount() != 3) { - throw new DockerClientException(String.format( - "Wrong ADD or COPY format on line [%d]", - lineNumber)); - } - - String extractedResource = matcher.group(2); - - String resource = filterForEnvironmentVars( - extractedResource, environmentMap).trim(); - - if (isFileResource(resource)) { - File src = new File(resource); - if (!src.isAbsolute()) { - src = new File(dockerFolder, resource) - .getCanonicalFile(); - } else { - throw new DockerClientException(String.format( - "Source file %s must be relative to %s", - src, dockerFolder)); - } - - // if (!src.exists()) { - // throw new DockerClientException(String.format( - // "Source file %s doesn't exist", src)); - // } - if (src.isDirectory()) { - Collection files = FileUtils.listFiles(src, - new GoLangMatchFileFilter(src, ignores), - TrueFileFilter.INSTANCE); - filesToAdd.addAll(files); - } else if (!src.exists()) { - filesToAdd.addAll(resolveWildcards(src, ignores)); - } else if (!GoLangFileMatch.match(ignores, - CompressArchiveUtil.relativize(dockerFolder, - src))) { - filesToAdd.add(src); - } else { - throw new DockerClientException( - String.format( - "Source file %s is excluded by .dockerignore file", - src)); - } - } - } - } - return CompressArchiveUtil.archiveTARFiles(dockerFolder, - filesToAdd, archiveNameWithOutExtension); - } catch (IOException ex) { - FileUtils.deleteQuietly(dockerFolderTar); - throw new DockerClientException( - "Error occurred while preparing Docker context folder.", ex); - } - } - - private Collection resolveWildcards(File file, List ignores) { - List filesToAdd = new ArrayList(); - - File parent = file.getParentFile(); - if (parent != null) { - if (parent.isDirectory()) { - Collection files = FileUtils.listFiles(parent, - new GoLangMatchFileFilter(parent, ignores), - TrueFileFilter.INSTANCE); - filesToAdd.addAll(files); - } else { - filesToAdd.addAll(resolveWildcards(parent, ignores)); - } - } else { - throw new DockerClientException(String.format( - "Source file %s doesn't exist", file)); - } - - return filesToAdd; - } - - private String filterForEnvironmentVars(String extractedResource, - Map environmentMap) { - - if (environmentMap.size() > 0) { - - String currentResourceContent = extractedResource; - - for (Map.Entry entry : environmentMap.entrySet()) { - - String variable = entry.getKey(); - - String replacementValue = entry.getValue(); - - // handle: $VARIABLE case - currentResourceContent = currentResourceContent.replaceAll( - "\\$" + variable, replacementValue); - - // handle ${VARIABLE} case - currentResourceContent = currentResourceContent.replaceAll( - "\\$\\{" + variable + "\\}", replacementValue); - - } - - return currentResourceContent; - } else - return extractedResource; - } - - 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()); - } } From 06fea216b583237d4f0441e2963cbadde2a5e819 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 6 Feb 2015 20:49:14 +0100 Subject: [PATCH 303/452] Fix Issue #110 --- .../java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java | 2 ++ .../dockerjava/jaxrs/CopyFileFromContainerCmdExec.java | 2 +- src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java | 3 ++- .../com/github/dockerjava/jaxrs/KillContainerCmdExec.java | 2 +- .../com/github/dockerjava/jaxrs/LogContainerCmdExec.java | 2 +- .../com/github/dockerjava/jaxrs/PauseContainerCmdExec.java | 2 +- src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java | 2 +- .../java/com/github/dockerjava/jaxrs/PushImageCmdExec.java | 2 ++ .../com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java | 3 +-- .../com/github/dockerjava/jaxrs/RestartContainerCmdExec.java | 2 +- .../com/github/dockerjava/jaxrs/StartContainerCmdExec.java | 5 +++-- .../com/github/dockerjava/jaxrs/StopContainerCmdExec.java | 2 +- .../java/com/github/dockerjava/jaxrs/TagImageCmdExec.java | 2 +- .../com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java | 4 +--- 14 files changed, 19 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index faf3d9f2..ed36c62c 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -81,6 +81,8 @@ public Iterable getItems() throws IOException { ObjectReader reader = mapper.reader(EventStreamItem.class); // and then do other configuration, if any, and read: Iterator items = reader.readValues(proxy); + + proxy.close(); return ImmutableList.copyOf(items); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java index 27b4d5bd..3061df53 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java @@ -30,7 +30,7 @@ protected InputStream execute(CopyFileFromContainerCmd command) { LOGGER.trace("POST: " + webResource.toString()); - return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(entity(command, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); + return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(entity(command, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java index aff72fab..c585f31c 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/InfoCmdExec.java @@ -23,6 +23,7 @@ protected Info execute(InfoCmd command) { WebTarget webResource = getBaseResource().path("/info"); LOGGER.trace("GET: {}", webResource); - return webResource.request().accept(MediaType.APPLICATION_JSON).get(Info.class); } + return webResource.request().accept(MediaType.APPLICATION_JSON).get(Info.class); + } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java index 21a6b9d6..6164064c 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/KillContainerCmdExec.java @@ -29,7 +29,7 @@ protected Void execute(KillContainerCmd command) { } LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON).post(null); + webResource.request().accept(MediaType.APPLICATION_JSON).post(null).close(); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java index 46d25942..ad1d6185 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java @@ -29,7 +29,7 @@ protected InputStream execute(LogContainerCmd command) { .queryParam("tail", command.getTail() < 0 ? "all" : "" + command.getTail()); LOGGER.trace("GET: {}", webResource); - return webResource.request().get(Response.class).readEntity(InputStream.class); + return webResource.request().get().readEntity(InputStream.class); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java index 6b3eeaf0..429c61ed 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PauseContainerCmdExec.java @@ -26,7 +26,7 @@ protected Void execute(PauseContainerCmd command) { command.getContainerId()); LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON).post(null); + webResource.request().accept(MediaType.APPLICATION_JSON).post(null).close(); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java index abfb0f4c..f8a172a1 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java @@ -21,7 +21,7 @@ protected Void execute(PingCmd command) { WebTarget webResource = getBaseResource().path("/_ping"); LOGGER.trace("GET: {}", webResource); - webResource.request().get(Response.class); + webResource.request().get().close(); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java index 152f31a3..8a9b9ebc 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java @@ -74,6 +74,8 @@ public Iterable getItems() throws IOException { // and then do other configuration, if any, and read: Iterator items = reader.readValues(proxy); + proxy.close(); + return ImmutableList.copyOf(items); } diff --git a/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java index 7a479ce2..d2ff1b83 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/RemoveContainerCmdExec.java @@ -23,8 +23,7 @@ protected Void execute(RemoveContainerCmd command) { .queryParam("force", command.hasForceEnabled() ? "1" : "0"); LOGGER.trace("DELETE: {}", webResource); - /*String response = */webResource.request().accept(MediaType.APPLICATION_JSON).delete().close(); -// LOGGER.trace("Response: {}", response); + webResource.request().accept(MediaType.APPLICATION_JSON).delete().close(); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java index b08aa032..9ac76a36 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/RestartContainerCmdExec.java @@ -27,7 +27,7 @@ protected Void execute(RestartContainerCmd command) { .queryParam("t", String.valueOf(command.getTimeout())); LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON).post(null); + webResource.request().accept(MediaType.APPLICATION_JSON).post(null).close(); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java index 0e7697e4..66131726 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java @@ -4,6 +4,7 @@ import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,8 +24,8 @@ protected Void execute(StartContainerCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/start").resolveTemplate("id", command.getContainerId()); LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command, MediaType.APPLICATION_JSON)); - + webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command, MediaType.APPLICATION_JSON)).close(); + return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java index 956f3d0b..bf683be5 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/StopContainerCmdExec.java @@ -26,7 +26,7 @@ protected Void execute(StopContainerCmd command) { .queryParam("t", String.valueOf(command.getTimeout())); LOGGER.trace("POST: {}", webResource); - webResource.request().accept(MediaType.APPLICATION_JSON).post(null); + webResource.request().accept(MediaType.APPLICATION_JSON).post(null).close(); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java index b1c770ba..dfbeba07 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/TagImageCmdExec.java @@ -24,7 +24,7 @@ protected Void execute(TagImageCmd command) { .queryParam("force", command.hasForceEnabled() ? "1" : "0"); LOGGER.trace("POST: {}", webResource); - webResource.request().post(null); + webResource.request().post(null).close(); return null; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java index 361f9adc..7fed603a 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/UnpauseContainerCmdExec.java @@ -1,9 +1,7 @@ package com.github.dockerjava.jaxrs; -import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,7 +23,7 @@ protected Void execute(UnpauseContainerCmd command) { LOGGER.trace("POST: {}", webResource); webResource.request().accept(MediaType.APPLICATION_JSON) - .post(Entity.entity(Response.class, MediaType.APPLICATION_JSON)); + .post(null).close(); return null; } From abee7f659e8431066a8b3d75daf455d3fed08b89 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 6 Feb 2015 21:06:45 +0100 Subject: [PATCH 304/452] Move utilities classes to core package --- .../github/dockerjava/api/command/TopContainerResponse.java | 2 +- .../dockerjava/{jaxrs => core}/util/JsonClientFilter.java | 2 +- .../dockerjava/{jaxrs => core}/util/LoggingFilter.java | 2 +- .../{jaxrs => core}/util/ResponseStatusExceptionFilter.java | 2 +- .../{jaxrs => core}/util/SelectiveLoggingFilter.java | 2 +- .../github/dockerjava/{jaxrs => core}/util/guava/Guava.java | 2 +- .../{jaxrs => core}/util/guava/PercentEscaper.java | 2 +- .../{jaxrs => core}/util/guava/UnicodeEscaper.java | 2 +- .../github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java | 6 +++--- .../java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java | 2 +- 10 files changed, 12 insertions(+), 12 deletions(-) rename src/main/java/com/github/dockerjava/{jaxrs => core}/util/JsonClientFilter.java (95%) rename src/main/java/com/github/dockerjava/{jaxrs => core}/util/LoggingFilter.java (99%) rename src/main/java/com/github/dockerjava/{jaxrs => core}/util/ResponseStatusExceptionFilter.java (98%) rename src/main/java/com/github/dockerjava/{jaxrs => core}/util/SelectiveLoggingFilter.java (96%) rename src/main/java/com/github/dockerjava/{jaxrs => core}/util/guava/Guava.java (97%) rename src/main/java/com/github/dockerjava/{jaxrs => core}/util/guava/PercentEscaper.java (99%) rename src/main/java/com/github/dockerjava/{jaxrs => core}/util/guava/UnicodeEscaper.java (99%) diff --git a/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java index 099da368..89aa3645 100644 --- a/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java @@ -1,6 +1,6 @@ package com.github.dockerjava.api.command; -import static com.github.dockerjava.jaxrs.util.guava.Guava.join; +import static com.github.dockerjava.core.util.guava.Guava.join; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/JsonClientFilter.java b/src/main/java/com/github/dockerjava/core/util/JsonClientFilter.java similarity index 95% rename from src/main/java/com/github/dockerjava/jaxrs/util/JsonClientFilter.java rename to src/main/java/com/github/dockerjava/core/util/JsonClientFilter.java index e0eaa4a4..f2911d96 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/JsonClientFilter.java +++ b/src/main/java/com/github/dockerjava/core/util/JsonClientFilter.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.jaxrs.util; +package com.github.dockerjava.core.util; import javax.ws.rs.client.ClientRequestContext; diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java b/src/main/java/com/github/dockerjava/core/util/LoggingFilter.java similarity index 99% rename from src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java rename to src/main/java/com/github/dockerjava/core/util/LoggingFilter.java index eda72b83..5a72ba23 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/LoggingFilter.java +++ b/src/main/java/com/github/dockerjava/core/util/LoggingFilter.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.jaxrs.util; +package com.github.dockerjava.core.util; /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java b/src/main/java/com/github/dockerjava/core/util/ResponseStatusExceptionFilter.java similarity index 98% rename from src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java rename to src/main/java/com/github/dockerjava/core/util/ResponseStatusExceptionFilter.java index af141bf3..7e970856 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/ResponseStatusExceptionFilter.java +++ b/src/main/java/com/github/dockerjava/core/util/ResponseStatusExceptionFilter.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.jaxrs.util; +package com.github.dockerjava.core.util; import java.io.EOFException; import java.io.IOException; diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java b/src/main/java/com/github/dockerjava/core/util/SelectiveLoggingFilter.java similarity index 96% rename from src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java rename to src/main/java/com/github/dockerjava/core/util/SelectiveLoggingFilter.java index 6771ebe8..8cfe88b7 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/SelectiveLoggingFilter.java +++ b/src/main/java/com/github/dockerjava/core/util/SelectiveLoggingFilter.java @@ -1,4 +1,4 @@ -package com.github.dockerjava.jaxrs.util; +package com.github.dockerjava.core.util; import java.io.IOException; import java.util.Collections; diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/guava/Guava.java b/src/main/java/com/github/dockerjava/core/util/guava/Guava.java similarity index 97% rename from src/main/java/com/github/dockerjava/jaxrs/util/guava/Guava.java rename to src/main/java/com/github/dockerjava/core/util/guava/Guava.java index 13f87142..84e27b34 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/guava/Guava.java +++ b/src/main/java/com/github/dockerjava/core/util/guava/Guava.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.github.dockerjava.jaxrs.util.guava; +package com.github.dockerjava.core.util.guava; public class Guava { diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/guava/PercentEscaper.java b/src/main/java/com/github/dockerjava/core/util/guava/PercentEscaper.java similarity index 99% rename from src/main/java/com/github/dockerjava/jaxrs/util/guava/PercentEscaper.java rename to src/main/java/com/github/dockerjava/core/util/guava/PercentEscaper.java index 8625121e..e136ec7b 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/guava/PercentEscaper.java +++ b/src/main/java/com/github/dockerjava/core/util/guava/PercentEscaper.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.github.dockerjava.jaxrs.util.guava; +package com.github.dockerjava.core.util.guava; import jersey.repackaged.com.google.common.base.Preconditions; diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/guava/UnicodeEscaper.java b/src/main/java/com/github/dockerjava/core/util/guava/UnicodeEscaper.java similarity index 99% rename from src/main/java/com/github/dockerjava/jaxrs/util/guava/UnicodeEscaper.java rename to src/main/java/com/github/dockerjava/core/util/guava/UnicodeEscaper.java index b0b74d8f..9bee03a7 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/util/guava/UnicodeEscaper.java +++ b/src/main/java/com/github/dockerjava/core/util/guava/UnicodeEscaper.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.github.dockerjava.jaxrs.util.guava; +package com.github.dockerjava.core.util.guava; import jersey.repackaged.com.google.common.base.Preconditions; diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 78cd8427..cdb85117 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -61,9 +61,9 @@ import com.github.dockerjava.api.command.VersionCmd; import com.github.dockerjava.api.command.WaitContainerCmd; import com.github.dockerjava.core.DockerClientConfig; -import com.github.dockerjava.jaxrs.util.JsonClientFilter; -import com.github.dockerjava.jaxrs.util.ResponseStatusExceptionFilter; -import com.github.dockerjava.jaxrs.util.SelectiveLoggingFilter; +import com.github.dockerjava.core.util.JsonClientFilter; +import com.github.dockerjava.core.util.ResponseStatusExceptionFilter; +import com.github.dockerjava.core.util.SelectiveLoggingFilter; public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { diff --git a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java index 84ede89b..001ba1d0 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java @@ -1,6 +1,6 @@ package com.github.dockerjava.jaxrs; -import static com.github.dockerjava.jaxrs.util.guava.Guava.urlPathSegmentEscaper; +import static com.github.dockerjava.core.util.guava.Guava.urlPathSegmentEscaper; import java.util.List; From cbcfba47ed2af9778ee1cd238fedb73efb549cdc Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 6 Feb 2015 21:07:22 +0100 Subject: [PATCH 305/452] switch to 1.0.0-SNAPSHOT --- CHANGELOG.md | 4 +++- README.md | 2 +- pom.xml | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80b6fc4a..3525f87e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,14 @@ Change Log === -docker-java-0.10.6-SNAPSHOT +docker-java-1.0.0-SNAPSHOT --- + * [#142](https://github.com/docker-java/docker-java/pull/142) Reduce Logging Level * [#138](https://github.com/docker-java/docker-java/pull/138) Apache CXF interopabilty * [#137](https://github.com/docker-java/docker-java/pull/137) Multiple volumesFrom option when creating a container * [#135](https://github.com/docker-java/docker-java/pull/135) Update to latest unix-socket-factory * [#134](https://github.com/docker-java/docker-java/pull/134) Remove Google Guava as dependency + * [#131](https://github.com/docker-java/docker-java/pull/128) Utility classes and streamed JSON representations * [#128](https://github.com/docker-java/docker-java/pull/128) Allow unauthorized pullImageCmd docker-java-0.10.5 diff --git a/README.md b/README.md index 63c8d64b..717b1b65 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ You can find the latest SNAPSHOT version including javadoc and source files on [ com.github.docker-java docker-java - 0.10.6-SNAPSHOT + 1.0.0-SNAPSHOT ## Documentation diff --git a/pom.xml b/pom.xml index 3ae2e1f8..82b7ce82 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 0.10.6-SNAPSHOT + 1.0.0-SNAPSHOT docker-java https://github.com/docker-java/docker-java From 1d098f8604e389476060eaa38142544dcbe84f65 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 7 Feb 2015 16:18:08 +0100 Subject: [PATCH 306/452] Fix Issue #147 --- .../dockerjava/core/util/ResponseStatusExceptionFilter.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/github/dockerjava/core/util/ResponseStatusExceptionFilter.java b/src/main/java/com/github/dockerjava/core/util/ResponseStatusExceptionFilter.java index 7e970856..99893a42 100644 --- a/src/main/java/com/github/dockerjava/core/util/ResponseStatusExceptionFilter.java +++ b/src/main/java/com/github/dockerjava/core/util/ResponseStatusExceptionFilter.java @@ -37,6 +37,7 @@ public void filter(ClientRequestContext requestContext, ClientResponseContext re case 200: case 201: case 204: + case 301: return; case 304: throw new NotModifiedException(getBodyAsMessage(responseContext)); From 8af3d6fa83a0298a40ad2075fc4f48cd789b376f Mon Sep 17 00:00:00 2001 From: Arthur Tsang Date: Sun, 8 Feb 2015 00:10:22 -0800 Subject: [PATCH 307/452] feat(save): add save image to docker client add saveImageCmd which will return a InputStream. the file is a tar file. https://docs.docker.com/reference/api/docker_remote_api_v1.15/#image-tarball-format --- .../github/dockerjava/api/DockerClient.java | 2 + .../api/command/DockerCmdExecFactory.java | 2 + .../dockerjava/api/command/SaveImageCmd.java | 39 ++++++++++ .../dockerjava/core/DockerClientImpl.java | 77 +++---------------- .../core/command/SaveImageCmdImpl.java | 63 +++++++++++++++ .../jaxrs/DockerCmdExecFactoryImpl.java | 38 +-------- .../dockerjava/jaxrs/SaveImageCmdExec.java | 44 +++++++++++ .../core/TestDockerCmdExecFactory.java | 3 + .../core/command/SaveImageCmdImplTest.java | 62 +++++++++++++++ 9 files changed, 228 insertions(+), 102 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java create mode 100644 src/main/java/com/github/dockerjava/core/command/SaveImageCmdImpl.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java create mode 100644 src/test/java/com/github/dockerjava/core/command/SaveImageCmdImplTest.java diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index f7addfa2..c2b15cf3 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -39,6 +39,8 @@ public CreateImageCmd createImageCmd(String repository, public ListImagesCmd listImagesCmd(); public InspectImageCmd inspectImageCmd(String imageId); + + public SaveImageCmd saveImageCmd(String name); /** * * CONTAINER API * diff --git a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java index 73381d69..ca2bbcae 100644 --- a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java +++ b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java @@ -22,6 +22,8 @@ public interface DockerCmdExecFactory extends Closeable { public PullImageCmd.Exec createPullImageCmdExec(); public PushImageCmd.Exec createPushImageCmdExec(); + + public SaveImageCmd.Exec createSaveImageCmdExec(); public CreateImageCmd.Exec createCreateImageCmdExec(); diff --git a/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java b/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java new file mode 100644 index 00000000..b8a5af4a --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java @@ -0,0 +1,39 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.PushEventStreamItem; + +import java.io.IOException; +import java.io.InputStream; + +public interface SaveImageCmd extends DockerCmd{ + + public String getName(); + + public String getTag(); + + /** + * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. + */ + public SaveImageCmd withName(String name); + + /** + * @param tag The image's tag. Not null. + */ + public SaveImageCmd withTag(String tag); + + public AuthConfig getAuthConfig(); + + public SaveImageCmd withAuthConfig(AuthConfig authConfig); + + /** + * @throws com.github.dockerjava.api.NotFoundException No such image + */ + public InputStream exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec { + } + + +} \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 5f0876bb..522afe3b 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -8,75 +8,9 @@ import java.io.InputStream; import com.github.dockerjava.api.DockerClient; -import com.github.dockerjava.api.command.AttachContainerCmd; -import com.github.dockerjava.api.command.AuthCmd; -import com.github.dockerjava.api.command.BuildImageCmd; -import com.github.dockerjava.api.command.CommitCmd; -import com.github.dockerjava.api.command.ContainerDiffCmd; -import com.github.dockerjava.api.command.CopyFileFromContainerCmd; -import com.github.dockerjava.api.command.CreateContainerCmd; -import com.github.dockerjava.api.command.CreateImageCmd; -import com.github.dockerjava.api.command.DockerCmdExecFactory; -import com.github.dockerjava.api.command.EventCallback; -import com.github.dockerjava.api.command.EventsCmd; -import com.github.dockerjava.api.command.ExecCreateCmd; -import com.github.dockerjava.api.command.ExecStartCmd; -import com.github.dockerjava.api.command.InfoCmd; -import com.github.dockerjava.api.command.InspectContainerCmd; -import com.github.dockerjava.api.command.InspectImageCmd; -import com.github.dockerjava.api.command.KillContainerCmd; -import com.github.dockerjava.api.command.ListContainersCmd; -import com.github.dockerjava.api.command.ListImagesCmd; -import com.github.dockerjava.api.command.LogContainerCmd; -import com.github.dockerjava.api.command.PauseContainerCmd; -import com.github.dockerjava.api.command.PingCmd; -import com.github.dockerjava.api.command.PullImageCmd; -import com.github.dockerjava.api.command.PushImageCmd; -import com.github.dockerjava.api.command.RemoveContainerCmd; -import com.github.dockerjava.api.command.RemoveImageCmd; -import com.github.dockerjava.api.command.RestartContainerCmd; -import com.github.dockerjava.api.command.SearchImagesCmd; -import com.github.dockerjava.api.command.StartContainerCmd; -import com.github.dockerjava.api.command.StopContainerCmd; -import com.github.dockerjava.api.command.TagImageCmd; -import com.github.dockerjava.api.command.TopContainerCmd; -import com.github.dockerjava.api.command.UnpauseContainerCmd; -import com.github.dockerjava.api.command.VersionCmd; -import com.github.dockerjava.api.command.WaitContainerCmd; +import com.github.dockerjava.api.command.*; import com.github.dockerjava.api.model.AuthConfig; -import com.github.dockerjava.core.command.AttachContainerCmdImpl; -import com.github.dockerjava.core.command.AuthCmdImpl; -import com.github.dockerjava.core.command.BuildImageCmdImpl; -import com.github.dockerjava.core.command.CommitCmdImpl; -import com.github.dockerjava.core.command.ContainerDiffCmdImpl; -import com.github.dockerjava.core.command.CopyFileFromContainerCmdImpl; -import com.github.dockerjava.core.command.CreateContainerCmdImpl; -import com.github.dockerjava.core.command.CreateImageCmdImpl; -import com.github.dockerjava.core.command.EventsCmdImpl; -import com.github.dockerjava.core.command.ExecCreateCmdImpl; -import com.github.dockerjava.core.command.ExecStartCmdImpl; -import com.github.dockerjava.core.command.InfoCmdImpl; -import com.github.dockerjava.core.command.InspectContainerCmdImpl; -import com.github.dockerjava.core.command.InspectImageCmdImpl; -import com.github.dockerjava.core.command.KillContainerCmdImpl; -import com.github.dockerjava.core.command.ListContainersCmdImpl; -import com.github.dockerjava.core.command.ListImagesCmdImpl; -import com.github.dockerjava.core.command.LogContainerCmdImpl; -import com.github.dockerjava.core.command.PauseContainerCmdImpl; -import com.github.dockerjava.core.command.PingCmdImpl; -import com.github.dockerjava.core.command.PullImageCmdImpl; -import com.github.dockerjava.core.command.PushImageCmdImpl; -import com.github.dockerjava.core.command.RemoveContainerCmdImpl; -import com.github.dockerjava.core.command.RemoveImageCmdImpl; -import com.github.dockerjava.core.command.RestartContainerCmdImpl; -import com.github.dockerjava.core.command.SearchImagesCmdImpl; -import com.github.dockerjava.core.command.StartContainerCmdImpl; -import com.github.dockerjava.core.command.StopContainerCmdImpl; -import com.github.dockerjava.core.command.TagImageCmdImpl; -import com.github.dockerjava.core.command.TopContainerCmdImpl; -import com.github.dockerjava.core.command.UnpauseContainerCmdImpl; -import com.github.dockerjava.core.command.VersionCmdImpl; -import com.github.dockerjava.core.command.WaitContainerCmdImpl; +import com.github.dockerjava.core.command.*; /** * @author Konstantin Pelykh (kpelykh@gmail.com) @@ -195,6 +129,13 @@ public PushImageCmd pushImageCmd(String name) { return new PushImageCmdImpl(getDockerCmdExecFactory() .createPushImageCmdExec(), name).withAuthConfig(dockerClientConfig.effectiveAuthConfig(name)); } + + @Override + public SaveImageCmd saveImageCmd(String name) { + return new SaveImageCmdImpl(getDockerCmdExecFactory() + .createSaveImageCmdExec(), name).withAuthConfig(dockerClientConfig.effectiveAuthConfig(name)); + + } @Override public CreateImageCmd createImageCmd(String repository, diff --git a/src/main/java/com/github/dockerjava/core/command/SaveImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/SaveImageCmdImpl.java new file mode 100644 index 00000000..85f7cfe6 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/SaveImageCmdImpl.java @@ -0,0 +1,63 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.SaveImageCmd; + +import java.io.InputStream; + +import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; + +public class SaveImageCmdImpl extends AbstrAuthCfgDockerCmd implements SaveImageCmd { + private String name; + private String tag; + + public SaveImageCmdImpl(SaveImageCmd.Exec exec, String name) { + super(exec); + withName(name); + } + + @Override + public String getName() { + return name; + } + + @Override + public String getTag() { + return tag; + } + + /** + * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null. + */ + @Override + public SaveImageCmd withName(String name) { + checkNotNull(name, "name was not specified"); + this.name = name; + return this; + } + + /** + * @param tag The image's tag. Can be null or empty. + */ + @Override + public SaveImageCmd withTag(String tag) { + checkNotNull(tag, "tag was not specified"); + this.tag = tag; + return this; + } + + @Override + public String toString() { + return new StringBuilder("get ") + .append(name) + .toString(); + } + + /** + * @throws com.github.dockerjava.api.NotFoundException No such image + */ + @Override + public InputStream exec() throws NotFoundException { + return super.exec(); + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index cdb85117..4edba9fc 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -5,6 +5,7 @@ import java.io.IOException; import java.net.URI; +import com.github.dockerjava.api.command.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,40 +27,6 @@ import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.github.dockerjava.api.DockerClientException; -import com.github.dockerjava.api.command.AttachContainerCmd; -import com.github.dockerjava.api.command.AuthCmd; -import com.github.dockerjava.api.command.BuildImageCmd; -import com.github.dockerjava.api.command.CommitCmd; -import com.github.dockerjava.api.command.ContainerDiffCmd; -import com.github.dockerjava.api.command.CopyFileFromContainerCmd; -import com.github.dockerjava.api.command.CreateContainerCmd; -import com.github.dockerjava.api.command.CreateImageCmd; -import com.github.dockerjava.api.command.DockerCmdExecFactory; -import com.github.dockerjava.api.command.EventsCmd; -import com.github.dockerjava.api.command.ExecCreateCmd; -import com.github.dockerjava.api.command.ExecStartCmd; -import com.github.dockerjava.api.command.InfoCmd; -import com.github.dockerjava.api.command.InspectContainerCmd; -import com.github.dockerjava.api.command.InspectImageCmd; -import com.github.dockerjava.api.command.KillContainerCmd; -import com.github.dockerjava.api.command.ListContainersCmd; -import com.github.dockerjava.api.command.ListImagesCmd; -import com.github.dockerjava.api.command.LogContainerCmd; -import com.github.dockerjava.api.command.PauseContainerCmd; -import com.github.dockerjava.api.command.PingCmd; -import com.github.dockerjava.api.command.PullImageCmd; -import com.github.dockerjava.api.command.PushImageCmd; -import com.github.dockerjava.api.command.RemoveContainerCmd; -import com.github.dockerjava.api.command.RemoveImageCmd; -import com.github.dockerjava.api.command.RestartContainerCmd; -import com.github.dockerjava.api.command.SearchImagesCmd; -import com.github.dockerjava.api.command.StartContainerCmd; -import com.github.dockerjava.api.command.StopContainerCmd; -import com.github.dockerjava.api.command.TagImageCmd; -import com.github.dockerjava.api.command.TopContainerCmd; -import com.github.dockerjava.api.command.UnpauseContainerCmd; -import com.github.dockerjava.api.command.VersionCmd; -import com.github.dockerjava.api.command.WaitContainerCmd; import com.github.dockerjava.core.DockerClientConfig; import com.github.dockerjava.core.util.JsonClientFilter; import com.github.dockerjava.core.util.ResponseStatusExceptionFilter; @@ -170,6 +137,9 @@ public PullImageCmd.Exec createPullImageCmdExec() { public PushImageCmd.Exec createPushImageCmdExec() { return new PushImageCmdExec(getBaseResource()); } + + @Override + public SaveImageCmd.Exec createSaveImageCmdExec() { return new SaveImageCmdExec(getBaseResource()); } @Override public CreateImageCmd.Exec createCreateImageCmdExec() { diff --git a/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java new file mode 100644 index 00000000..16ad0012 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java @@ -0,0 +1,44 @@ +package com.github.dockerjava.jaxrs; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.github.dockerjava.api.command.PushImageCmd; +import com.github.dockerjava.api.command.SaveImageCmd; +import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.PushEventStreamItem; +import jersey.repackaged.com.google.common.collect.ImmutableList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import java.io.IOException; +import java.io.InputStream; +import java.util.Iterator; + +import static javax.ws.rs.client.Entity.entity; + +public class SaveImageCmdExec extends AbstrDockerCmdExec implements SaveImageCmd.Exec { + private static final Logger LOGGER = LoggerFactory + .getLogger(PushImageCmdExec.class); + + public SaveImageCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + protected InputStream execute(SaveImageCmd command) { + WebTarget webResource = getBaseResource().path("/images/" + command.getName() + "/get") + .queryParam("tag", command.getTag()); + + final String registryAuth = registryAuth(command.getAuthConfig()); + LOGGER.trace("GET: {}", webResource); + InputStream is = webResource + .request() + .header("X-Registry-Auth", registryAuth) + .accept(MediaType.APPLICATION_JSON) + .get().readEntity(InputStream.class); + + return is; + } +} diff --git a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java index 4fcf26b6..5e7f2974 100644 --- a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java +++ b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java @@ -141,6 +141,9 @@ public PullImageCmd.Exec createPullImageCmdExec() { public PushImageCmd.Exec createPushImageCmdExec() { return delegate.createPushImageCmdExec(); } + + @Override + public SaveImageCmd.Exec createSaveImageCmdExec() { return delegate.createSaveImageCmdExec(); } @Override public SearchImagesCmd.Exec createSearchImagesCmdExec() { diff --git a/src/test/java/com/github/dockerjava/core/command/SaveImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/SaveImageCmdImplTest.java new file mode 100644 index 00000000..b62594be --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/command/SaveImageCmdImplTest.java @@ -0,0 +1,62 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.client.AbstractDockerClientTest; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.ITestResult; +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 java.io.BufferedInputStream; +import java.io.DataInputStream; +import java.io.InputStream; +import java.lang.reflect.Method; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; + +@Test(groups = "integration") +public class SaveImageCmdImplTest extends AbstractDockerClientTest { + public static final Logger LOG = LoggerFactory + .getLogger(PushImageCmdImplTest.class); + + String username; + + @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 saveImage() throws Exception { + + InputStream image = IOUtils.toBufferedInputStream(dockerClient + .saveImageCmd("busybox").exec()); + assertThat(image.available(), greaterThan(0)); + + } + +} From 0c6f2b4424b62add3dbb6c9f2c0d76150aa27a62 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sun, 8 Feb 2015 20:33:25 +0100 Subject: [PATCH 308/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3525f87e..63fc6e78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ Change Log docker-java-1.0.0-SNAPSHOT --- + * [#148](https://github.com/docker-java/docker-java/pull/148) Save image functionality * [#142](https://github.com/docker-java/docker-java/pull/142) Reduce Logging Level * [#138](https://github.com/docker-java/docker-java/pull/138) Apache CXF interopabilty * [#137](https://github.com/docker-java/docker-java/pull/137) Multiple volumesFrom option when creating a container From 19ec0dbdd10fd940f9fb88399a0afa92cf41d560 Mon Sep 17 00:00:00 2001 From: Gabe Ki Date: Wed, 11 Feb 2015 14:31:52 -0800 Subject: [PATCH 309/452] Add redirection for 301 - Issue #147 --- .../dockerjava/core/DockerClientConfig.java | 22 +++++++++-- .../core/util/FollowRedirectsFilter.java | 37 +++++++++++++++++++ .../util/ResponseStatusExceptionFilter.java | 1 - .../jaxrs/DockerCmdExecFactoryImpl.java | 5 +++ 4 files changed, 61 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/core/util/FollowRedirectsFilter.java diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 7513c7f2..f4881c19 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -33,6 +33,7 @@ public class DockerClientConfig implements Serializable { private static final String DOCKER_IO_READ_TIMEOUT_PROPERTY = "docker.io.readTimeout"; // this is really confusing, as there are two ways to spell it private static final String DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY = "docker.io.enableLoggingFilter"; + private static final String DOCKER_IO_FOLLOW_REDIRECTS_FILTER_PROPERTY = "docker.io.followRedirectsFilterEnabled"; private static final String DOCKER_IO_DOCKER_CERT_PATH_PROPERTY = "docker.io.dockerCertPath"; private static final String DOCKER_IO_DOCKER_CFG_PATH_PROPERTY = "docker.io.dockerCfgPath"; // connection pooling properties @@ -53,6 +54,7 @@ public class DockerClientConfig implements Serializable { m.put("DOCKER_SERVER_ADDRESS", DOCKER_IO_SERVER_ADDRESS_PROPERTY); m.put("DOCKER_READ_TIMEOUT", DOCKER_IO_READ_TIMEOUT_PROPERTY); m.put("DOCKER_LOGGING_FILTER_ENABLED", DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY); + m.put("DOCKER_IO_FOLLOW_REDIRECTS_FILTER_PROPERTY", DOCKER_IO_FOLLOW_REDIRECTS_FILTER_PROPERTY); m.put(DOCKER_CERT_PATH_PROPERTY, DOCKER_IO_DOCKER_CERT_PATH_PROPERTY); m.put("DOCKER_CFG_PATH", DOCKER_IO_DOCKER_CFG_PATH_PROPERTY); ENV_NAME_TO_IO_NAME = Collections.unmodifiableMap(m); @@ -63,14 +65,15 @@ public class DockerClientConfig implements Serializable { private final String version, username, password, email, serverAddress, dockerCfgPath; private final Integer readTimeout; private final boolean loggingFilterEnabled; + private final boolean followRedirectsFilterEnabled; private final SSLConfig sslConfig; private final int maxTotalConnections; private final int maxPerRouteConnections; DockerClientConfig(URI uri, String version, String username, String password, String email, String serverAddress, - String dockerCfgPath, Integer readTimeout, boolean loggingFilterEnabled, SSLConfig sslConfig, - int maxTotalConns, int maxPerRouteConns) { + String dockerCfgPath, Integer readTimeout, boolean loggingFilterEnabled, boolean followRedirectsFilterEnabled, + SSLConfig sslConfig, int maxTotalConns, int maxPerRouteConns) { this.uri = uri; this.version = version; this.username = username; @@ -80,6 +83,7 @@ public class DockerClientConfig implements Serializable { this.dockerCfgPath = dockerCfgPath; this.readTimeout = readTimeout; this.loggingFilterEnabled = loggingFilterEnabled; + this.followRedirectsFilterEnabled = followRedirectsFilterEnabled; this.sslConfig = sslConfig; this.maxTotalConnections = maxTotalConns; this.maxPerRouteConnections = maxPerRouteConns; @@ -243,6 +247,10 @@ public boolean isLoggingFilterEnabled() { return loggingFilterEnabled; } + public boolean followRedirectsFilterEnabled() { + return followRedirectsFilterEnabled; + } + public SSLConfig getSslConfig() { return sslConfig; } @@ -345,6 +353,7 @@ public String toString() { ", sslConfig='" + sslConfig + '\'' + ", readTimeout=" + readTimeout + ", loggingFilterEnabled=" + loggingFilterEnabled + + ", followRedirectsFilterEnabled=" + followRedirectsFilterEnabled + '}'; } @@ -352,7 +361,7 @@ public static class DockerClientConfigBuilder { private URI uri; private String version, username, password, email, serverAddress, dockerCfgPath; private Integer readTimeout, maxTotalConnections, maxPerRouteConnections; - private boolean loggingFilterEnabled; + private boolean loggingFilterEnabled, followRedirectsFilterEnabled; private SSLConfig sslConfig; /** @@ -370,6 +379,7 @@ public DockerClientConfigBuilder withProperties(Properties p) { .withServerAddress(p.getProperty(DOCKER_IO_SERVER_ADDRESS_PROPERTY)) .withReadTimeout(Integer.valueOf(p.getProperty(DOCKER_IO_READ_TIMEOUT_PROPERTY, "0"))) .withLoggingFilter(Boolean.valueOf(p.getProperty(DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY, "true"))) + .withFollowRedirectsFilter(Boolean.valueOf(p.getProperty(DOCKER_IO_FOLLOW_REDIRECTS_FILTER_PROPERTY, "true"))) .withDockerCertPath(p.getProperty(DOCKER_IO_DOCKER_CERT_PATH_PROPERTY)) .withDockerCfgPath(p.getProperty(DOCKER_IO_DOCKER_CFG_PATH_PROPERTY)) .withMaxPerRouteConnections(Integer.valueOf(p.getProperty(DOCKER_IO_MAX_PER_ROUTE_PROPERTY, "2"))) @@ -428,6 +438,11 @@ public final DockerClientConfigBuilder withLoggingFilter(boolean loggingFilterEn return this; } + public final DockerClientConfigBuilder withFollowRedirectsFilter(boolean followRedirectsFilterEnabled) { + this.followRedirectsFilterEnabled = followRedirectsFilterEnabled; + return this; + } + public final DockerClientConfigBuilder withDockerCertPath(String dockerCertPath) { this.sslConfig = new LocalDirectorySSLConfig(dockerCertPath); return this; @@ -455,6 +470,7 @@ public DockerClientConfig build() { dockerCfgPath, readTimeout, loggingFilterEnabled, + followRedirectsFilterEnabled, sslConfig, maxTotalConnections, maxPerRouteConnections diff --git a/src/main/java/com/github/dockerjava/core/util/FollowRedirectsFilter.java b/src/main/java/com/github/dockerjava/core/util/FollowRedirectsFilter.java new file mode 100644 index 00000000..fd375ece --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/util/FollowRedirectsFilter.java @@ -0,0 +1,37 @@ +package com.github.dockerjava.core.util; + +import java.io.IOException; +import java.io.InputStream; + +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.core.Response; + +/** + * Default implementation of RedirectStrategy honors the restrictions + * on automatic redirection of entity enclosing methods such as POST + * and PUT imposed by the HTTP specification. 302 Moved Temporarily, + * 301 Moved Permanently and 307 Temporary Redirect status codes will + * result in an automatic redirect of HEAD and GET methods only. + * + * {@link org.apache.http.impl.client.DefaultRedirectStrategy} + * + * This filter allows arbitrary redirection for other methods. + */ +public class FollowRedirectsFilter implements ClientResponseFilter { + + @Override + public void filter(ClientRequestContext requestContext, + ClientResponseContext responseContext) throws IOException { + if (!responseContext.getStatusInfo().getFamily().equals(Response.Status.Family.REDIRECTION)) { + return; + } + + Response resp = requestContext.getClient().target(responseContext.getLocation()) + .request().method(requestContext.getMethod()); + responseContext.setEntityStream((InputStream) resp.getEntity()); + responseContext.setStatusInfo(resp.getStatusInfo()); + responseContext.setStatus(resp.getStatus()); + } +} diff --git a/src/main/java/com/github/dockerjava/core/util/ResponseStatusExceptionFilter.java b/src/main/java/com/github/dockerjava/core/util/ResponseStatusExceptionFilter.java index 99893a42..7e970856 100644 --- a/src/main/java/com/github/dockerjava/core/util/ResponseStatusExceptionFilter.java +++ b/src/main/java/com/github/dockerjava/core/util/ResponseStatusExceptionFilter.java @@ -37,7 +37,6 @@ public void filter(ClientRequestContext requestContext, ClientResponseContext re case 200: case 201: case 204: - case 301: return; case 304: throw new NotModifiedException(getBodyAsMessage(responseContext)); diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 4edba9fc..4652b4b9 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -6,6 +6,7 @@ import java.net.URI; import com.github.dockerjava.api.command.*; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +29,7 @@ import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.github.dockerjava.api.DockerClientException; import com.github.dockerjava.core.DockerClientConfig; +import com.github.dockerjava.core.util.FollowRedirectsFilter; import com.github.dockerjava.core.util.JsonClientFilter; import com.github.dockerjava.core.util.ResponseStatusExceptionFilter; import com.github.dockerjava.core.util.SelectiveLoggingFilter; @@ -49,6 +51,9 @@ public void init(DockerClientConfig dockerClientConfig) { clientConfig.register(ResponseStatusExceptionFilter.class); clientConfig.register(JsonClientFilter.class); clientConfig.register(JacksonJsonProvider.class); + if (dockerClientConfig.followRedirectsFilterEnabled()) { + clientConfig.register(FollowRedirectsFilter.class); + } if (dockerClientConfig.isLoggingFilterEnabled()) { clientConfig.register(new SelectiveLoggingFilter(LOGGER, true)); From adb85a84ca0ea94d246e3d4d8000136ef7d3dffd Mon Sep 17 00:00:00 2001 From: Gabe Ki Date: Wed, 11 Feb 2015 15:13:47 -0800 Subject: [PATCH 310/452] fix unit tests --- .../dockerjava/core/DockerClientConfig.java | 7 ++++--- .../core/util/FollowRedirectsFilter.java | 18 +++++++++--------- .../jaxrs/DockerCmdExecFactoryImpl.java | 6 +++--- .../core/DockerClientConfigTest.java | 4 ++-- .../dockerjava/core/DockerClientImplTest.java | 2 +- 5 files changed, 19 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index f4881c19..6b87a927 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -33,7 +33,7 @@ public class DockerClientConfig implements Serializable { private static final String DOCKER_IO_READ_TIMEOUT_PROPERTY = "docker.io.readTimeout"; // this is really confusing, as there are two ways to spell it private static final String DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY = "docker.io.enableLoggingFilter"; - private static final String DOCKER_IO_FOLLOW_REDIRECTS_FILTER_PROPERTY = "docker.io.followRedirectsFilterEnabled"; + private static final String DOCKER_IO_FOLLOW_REDIRECTS_FILTER_PROPERTY = "docker.io.followRedirectsFilter"; private static final String DOCKER_IO_DOCKER_CERT_PATH_PROPERTY = "docker.io.dockerCertPath"; private static final String DOCKER_IO_DOCKER_CFG_PATH_PROPERTY = "docker.io.dockerCfgPath"; // connection pooling properties @@ -54,7 +54,7 @@ public class DockerClientConfig implements Serializable { m.put("DOCKER_SERVER_ADDRESS", DOCKER_IO_SERVER_ADDRESS_PROPERTY); m.put("DOCKER_READ_TIMEOUT", DOCKER_IO_READ_TIMEOUT_PROPERTY); m.put("DOCKER_LOGGING_FILTER_ENABLED", DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY); - m.put("DOCKER_IO_FOLLOW_REDIRECTS_FILTER_PROPERTY", DOCKER_IO_FOLLOW_REDIRECTS_FILTER_PROPERTY); + m.put("DOCKER_FOLLOW_REDIRECTS_FILTER_ENABLED", DOCKER_IO_FOLLOW_REDIRECTS_FILTER_PROPERTY); m.put(DOCKER_CERT_PATH_PROPERTY, DOCKER_IO_DOCKER_CERT_PATH_PROPERTY); m.put("DOCKER_CFG_PATH", DOCKER_IO_DOCKER_CFG_PATH_PROPERTY); ENV_NAME_TO_IO_NAME = Collections.unmodifiableMap(m); @@ -186,6 +186,7 @@ private static Properties overrideDockerPropertiesWithSystemProperties(Propertie DOCKER_IO_SERVER_ADDRESS_PROPERTY, DOCKER_IO_READ_TIMEOUT_PROPERTY, DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY, + DOCKER_IO_FOLLOW_REDIRECTS_FILTER_PROPERTY, DOCKER_IO_DOCKER_CERT_PATH_PROPERTY, DOCKER_IO_DOCKER_CFG_PATH_PROPERTY, }) { @@ -379,7 +380,7 @@ public DockerClientConfigBuilder withProperties(Properties p) { .withServerAddress(p.getProperty(DOCKER_IO_SERVER_ADDRESS_PROPERTY)) .withReadTimeout(Integer.valueOf(p.getProperty(DOCKER_IO_READ_TIMEOUT_PROPERTY, "0"))) .withLoggingFilter(Boolean.valueOf(p.getProperty(DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY, "true"))) - .withFollowRedirectsFilter(Boolean.valueOf(p.getProperty(DOCKER_IO_FOLLOW_REDIRECTS_FILTER_PROPERTY, "true"))) + .withFollowRedirectsFilter(Boolean.valueOf(p.getProperty(DOCKER_IO_FOLLOW_REDIRECTS_FILTER_PROPERTY, "false"))) .withDockerCertPath(p.getProperty(DOCKER_IO_DOCKER_CERT_PATH_PROPERTY)) .withDockerCfgPath(p.getProperty(DOCKER_IO_DOCKER_CFG_PATH_PROPERTY)) .withMaxPerRouteConnections(Integer.valueOf(p.getProperty(DOCKER_IO_MAX_PER_ROUTE_PROPERTY, "2"))) diff --git a/src/main/java/com/github/dockerjava/core/util/FollowRedirectsFilter.java b/src/main/java/com/github/dockerjava/core/util/FollowRedirectsFilter.java index fd375ece..b4431b1f 100644 --- a/src/main/java/com/github/dockerjava/core/util/FollowRedirectsFilter.java +++ b/src/main/java/com/github/dockerjava/core/util/FollowRedirectsFilter.java @@ -21,17 +21,17 @@ */ public class FollowRedirectsFilter implements ClientResponseFilter { - @Override + @Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { - if (!responseContext.getStatusInfo().getFamily().equals(Response.Status.Family.REDIRECTION)) { - return; - } + if (!responseContext.getStatusInfo().getFamily().equals(Response.Status.Family.REDIRECTION)) { + return; + } - Response resp = requestContext.getClient().target(responseContext.getLocation()) - .request().method(requestContext.getMethod()); - responseContext.setEntityStream((InputStream) resp.getEntity()); - responseContext.setStatusInfo(resp.getStatusInfo()); - responseContext.setStatus(resp.getStatus()); + Response resp = requestContext.getClient().target(responseContext.getLocation()) + .request().method(requestContext.getMethod()); + responseContext.setEntityStream((InputStream) resp.getEntity()); + responseContext.setStatusInfo(resp.getStatusInfo()); + responseContext.setStatus(resp.getStatus()); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 4652b4b9..5bff4c66 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -48,12 +48,12 @@ public void init(DockerClientConfig dockerClientConfig) { clientConfig.connectorProvider(new ApacheConnectorProvider()); clientConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); - clientConfig.register(ResponseStatusExceptionFilter.class); - clientConfig.register(JsonClientFilter.class); - clientConfig.register(JacksonJsonProvider.class); if (dockerClientConfig.followRedirectsFilterEnabled()) { clientConfig.register(FollowRedirectsFilter.class); } + clientConfig.register(ResponseStatusExceptionFilter.class); + clientConfig.register(JsonClientFilter.class); + clientConfig.register(JacksonJsonProvider.class); if (dockerClientConfig.isLoggingFilterEnabled()) { clientConfig.register(new SelectiveLoggingFilter(LOGGER, true)); diff --git a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java index 4611f430..64ab912d 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientConfigTest.java @@ -16,12 +16,12 @@ public class DockerClientConfigTest { public static final DockerClientConfig EXAMPLE_CONFIG = newExampleConfig(); private static DockerClientConfig newExampleConfig() { - return new DockerClientConfig(URI.create("http://foo"), "bar", "baz", "qux", "blam", "wham", "flam", 877, false, new LocalDirectorySSLConfig("flim"), 20, 2); + return new DockerClientConfig(URI.create("http://foo"), "bar", "baz", "qux", "blam", "wham", "flam", 877, false, false, new LocalDirectorySSLConfig("flim"), 20, 2); } @Test public void string() throws Exception { - assertEquals("DockerClientConfig{uri=http://foo, version='bar', username='baz', password='qux', email='blam', serverAddress='wham', dockerCfgPath='flam', sslConfig='LocalDirectorySSLConfig{dockerCertPath=flim}', readTimeout=877, loggingFilterEnabled=false}", + assertEquals("DockerClientConfig{uri=http://foo, version='bar', username='baz', password='qux', email='blam', serverAddress='wham', dockerCfgPath='flam', sslConfig='LocalDirectorySSLConfig{dockerCertPath=flim}', readTimeout=877, loggingFilterEnabled=false, followRedirectsFilterEnabled=false}", EXAMPLE_CONFIG.toString()); } diff --git a/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java b/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java index 1f5604fe..2a961e3b 100644 --- a/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java +++ b/src/test/java/com/github/dockerjava/core/DockerClientImplTest.java @@ -10,7 +10,7 @@ public class DockerClientImplTest { @Test public void configuredInstanceAuthConfig() throws Exception { // given a config with null serverAddress - DockerClientConfig dockerClientConfig = new DockerClientConfig(null, null, "", "", "", null, null, 0, false, null, 20, 2); + DockerClientConfig dockerClientConfig = new DockerClientConfig(null, null, "", "", "", null, null, 0, false, false, null, 20, 2); DockerClientImpl dockerClient = DockerClientImpl.getInstance(dockerClientConfig); // when we get the auth config From f28972b235eaa7edad2b682f8b7f5c28cb900359 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 16 Feb 2015 20:42:13 +0100 Subject: [PATCH 311/452] Fix Issue #150 --- .../dockerjava/core/DockerClientConfig.java | 34 +- .../jaxrs/DockerCmdExecFactoryImpl.java | 517 +++++++++--------- 2 files changed, 291 insertions(+), 260 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 7513c7f2..aed3028f 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -65,12 +65,12 @@ public class DockerClientConfig implements Serializable { private final boolean loggingFilterEnabled; private final SSLConfig sslConfig; - private final int maxTotalConnections; - private final int maxPerRouteConnections; + private final Integer maxTotalConnections; + private final Integer maxPerRouteConnections; DockerClientConfig(URI uri, String version, String username, String password, String email, String serverAddress, String dockerCfgPath, Integer readTimeout, boolean loggingFilterEnabled, SSLConfig sslConfig, - int maxTotalConns, int maxPerRouteConns) { + Integer maxTotalConns, Integer maxPerRouteConns) { this.uri = uri; this.version = version; this.username = username; @@ -251,6 +251,14 @@ public String getDockerCfgPath() { return dockerCfgPath; } + public Integer getMaxTotalConnections() { + return maxTotalConnections; + } + + public Integer getMaxPerRoutConnections() { + return maxPerRouteConnections; + } + private AuthConfig getAuthConfig() { AuthConfig authConfig = null; if (getUsername() != null && getPassword() != null && getEmail() != null @@ -372,9 +380,15 @@ public DockerClientConfigBuilder withProperties(Properties p) { .withLoggingFilter(Boolean.valueOf(p.getProperty(DOCKER_IO_ENABLE_LOGGING_FILTER_PROPERTY, "true"))) .withDockerCertPath(p.getProperty(DOCKER_IO_DOCKER_CERT_PATH_PROPERTY)) .withDockerCfgPath(p.getProperty(DOCKER_IO_DOCKER_CFG_PATH_PROPERTY)) - .withMaxPerRouteConnections(Integer.valueOf(p.getProperty(DOCKER_IO_MAX_PER_ROUTE_PROPERTY, "2"))) - .withMaxTotalConnections(Integer.valueOf(p.getProperty(DOCKER_IO_MAX_TOTAL_PROPERTY, "20"))) - ; + .withMaxPerRouteConnections(integerValue(p.getProperty(DOCKER_IO_MAX_PER_ROUTE_PROPERTY))) + .withMaxTotalConnections(integerValue(p.getProperty(DOCKER_IO_MAX_TOTAL_PROPERTY))); + } + + private Integer integerValue(String value) { + if(value != null) + return Integer.valueOf(value); + else + return null; } public final DockerClientConfigBuilder withUri(String uri) { @@ -462,11 +476,5 @@ public DockerClientConfig build() { } } - public int getMaxTotalConnections() { - return maxTotalConnections; - } - - public int getMaxPerRoutConnections() { - return maxPerRouteConnections; - } +// } diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 4edba9fc..e874d9da 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -34,252 +34,275 @@ public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { - private static final Logger LOGGER = LoggerFactory.getLogger(DockerCmdExecFactoryImpl.class.getName()); - private Client client; - private WebTarget baseResource; - - @Override - public void init(DockerClientConfig dockerClientConfig) { - checkNotNull(dockerClientConfig, "config was not specified"); - - ClientConfig clientConfig = new ClientConfig(); - clientConfig.connectorProvider(new ApacheConnectorProvider()); - clientConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); - - clientConfig.register(ResponseStatusExceptionFilter.class); - clientConfig.register(JsonClientFilter.class); - clientConfig.register(JacksonJsonProvider.class); - - if (dockerClientConfig.isLoggingFilterEnabled()) { - clientConfig.register(new SelectiveLoggingFilter(LOGGER, true)); - } - - if (dockerClientConfig.getReadTimeout() != null) { - int readTimeout = dockerClientConfig.getReadTimeout(); - clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); - } - - URI originalUri = dockerClientConfig.getUri(); - - SSLContext sslContext; - try { - sslContext = dockerClientConfig.getSslConfig().getSSLContext(); - } catch(Exception ex) { - throw new DockerClientException("Error in SSL Configuration", ex); - } - - PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(getSchemeRegistry(originalUri, sslContext)); - connManager.setMaxTotal(dockerClientConfig.getMaxTotalConnections()); - connManager.setDefaultMaxPerRoute(dockerClientConfig.getMaxPerRoutConnections()); - clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connManager); - - ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig); - - if (sslContext != null) { - clientBuilder.sslContext(sslContext); - } - - client = clientBuilder.build(); - - if (originalUri.getScheme().equals("unix")) { - dockerClientConfig.setUri(UnixConnectionSocketFactory.sanitizeUri(originalUri)); - } - WebTarget webResource = client.target(dockerClientConfig.getUri()); - - if (dockerClientConfig.getVersion() == null || dockerClientConfig.getVersion().isEmpty()) { - baseResource = webResource; - } else { - baseResource = webResource.path("v" + dockerClientConfig.getVersion()); - } - } - - private org.apache.http.config.Registry getSchemeRegistry(final URI originalUri, SSLContext sslContext) { - RegistryBuilder registryBuilder = RegistryBuilder.create(); - registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory()); - if (sslContext != null) { - registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext)); - } - registryBuilder.register("unix", new UnixConnectionSocketFactory(originalUri)); - return registryBuilder.build(); - } - - protected WebTarget getBaseResource() { - checkNotNull(baseResource, "Factory not initialized. You probably forgot to call init()!"); - return baseResource; - } - - @Override - public AuthCmd.Exec createAuthCmdExec() { - return new AuthCmdExec(getBaseResource()); - } - - @Override - public InfoCmd.Exec createInfoCmdExec() { - return new InfoCmdExec(getBaseResource()); - } - - @Override - public PingCmd.Exec createPingCmdExec() { - return new PingCmdExec(getBaseResource()); - } - - @Override - public VersionCmd.Exec createVersionCmdExec() { - return new VersionCmdExec(getBaseResource()); - } - - @Override - public PullImageCmd.Exec createPullImageCmdExec() { - return new PullImageCmdExec(getBaseResource()); - } - - @Override - public PushImageCmd.Exec createPushImageCmdExec() { - return new PushImageCmdExec(getBaseResource()); - } - - @Override - public SaveImageCmd.Exec createSaveImageCmdExec() { return new SaveImageCmdExec(getBaseResource()); } - - @Override - public CreateImageCmd.Exec createCreateImageCmdExec() { - return new CreateImageCmdExec(getBaseResource()); - } - - @Override - public SearchImagesCmd.Exec createSearchImagesCmdExec() { - return new SearchImagesCmdExec(getBaseResource()); - } - - @Override - public RemoveImageCmd.Exec createRemoveImageCmdExec() { - return new RemoveImageCmdExec(getBaseResource()); - } - - @Override - public ListImagesCmd.Exec createListImagesCmdExec() { - return new ListImagesCmdExec(getBaseResource()); - } - - @Override - public InspectImageCmd.Exec createInspectImageCmdExec() { - return new InspectImageCmdExec(getBaseResource()); - } - - @Override - public ListContainersCmd.Exec createListContainersCmdExec() { - return new ListContainersCmdExec(getBaseResource()); - } - - @Override - public CreateContainerCmd.Exec createCreateContainerCmdExec() { - return new CreateContainerCmdExec(getBaseResource()); - } - - @Override - public StartContainerCmd.Exec createStartContainerCmdExec() { - return new StartContainerCmdExec(getBaseResource()); - } - - @Override - public InspectContainerCmd.Exec createInspectContainerCmdExec() { - return new InspectContainerCmdExec(getBaseResource()); - } - - @Override - public ExecCreateCmd.Exec createExecCmdExec() { - return new ExecCreateCmdExec(getBaseResource()); - } - - @Override - public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { - return new RemoveContainerCmdExec(getBaseResource()); - } - - @Override - public WaitContainerCmd.Exec createWaitContainerCmdExec() { - return new WaitContainerCmdExec(getBaseResource()); - } - - @Override - public AttachContainerCmd.Exec createAttachContainerCmdExec() { - return new AttachContainerCmdExec(getBaseResource()); - } - - @Override - public ExecStartCmd.Exec createExecStartCmdExec() { - return new ExecStartCmdExec(getBaseResource()); - } - - @Override - public LogContainerCmd.Exec createLogContainerCmdExec() { - return new LogContainerCmdExec(getBaseResource()); - } - - @Override - public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() { - return new CopyFileFromContainerCmdExec(getBaseResource()); - } - - @Override - public StopContainerCmd.Exec createStopContainerCmdExec() { - return new StopContainerCmdExec(getBaseResource()); - } - - @Override - public ContainerDiffCmd.Exec createContainerDiffCmdExec() { - return new ContainerDiffCmdExec(getBaseResource()); - } - - @Override - public KillContainerCmd.Exec createKillContainerCmdExec() { - return new KillContainerCmdExec(getBaseResource()); - } - - @Override - public RestartContainerCmd.Exec createRestartContainerCmdExec() { - return new RestartContainerCmdExec(getBaseResource()); - } - - @Override - public CommitCmd.Exec createCommitCmdExec() { - return new CommitCmdExec(getBaseResource()); - } - - @Override - public BuildImageCmd.Exec createBuildImageCmdExec() { - return new BuildImageCmdExec(getBaseResource()); - } - - @Override - public TopContainerCmd.Exec createTopContainerCmdExec() { - return new TopContainerCmdExec(getBaseResource()); - } - - @Override - public TagImageCmd.Exec createTagImageCmdExec() { - return new TagImageCmdExec(getBaseResource()); - } - - @Override - public PauseContainerCmd.Exec createPauseContainerCmdExec() { - return new PauseContainerCmdExec(getBaseResource()); - } - - @Override - public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { - return new UnpauseContainerCmdExec(baseResource); - } - - @Override - public EventsCmd.Exec createEventsCmdExec() { - return new EventsCmdExec(getBaseResource()); - } - - @Override - public void close() throws IOException { - checkNotNull(client, "Factory not initialized. You probably forgot to call init()!"); - client.close(); - } + private static final Logger LOGGER = LoggerFactory + .getLogger(DockerCmdExecFactoryImpl.class.getName()); + private Client client; + private WebTarget baseResource; + + @Override + public void init(DockerClientConfig dockerClientConfig) { + checkNotNull(dockerClientConfig, "config was not specified"); + + ClientConfig clientConfig = new ClientConfig(); + clientConfig.connectorProvider(new ApacheConnectorProvider()); + clientConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, + true); + + clientConfig.register(ResponseStatusExceptionFilter.class); + clientConfig.register(JsonClientFilter.class); + clientConfig.register(JacksonJsonProvider.class); + + if (dockerClientConfig.isLoggingFilterEnabled()) { + clientConfig.register(new SelectiveLoggingFilter(LOGGER, true)); + } + + if (dockerClientConfig.getReadTimeout() != null) { + int readTimeout = dockerClientConfig.getReadTimeout(); + clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); + } + + URI originalUri = dockerClientConfig.getUri(); + + SSLContext sslContext; + try { + sslContext = dockerClientConfig.getSslConfig().getSSLContext(); + } catch (Exception ex) { + throw new DockerClientException("Error in SSL Configuration", ex); + } + + PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager( + getSchemeRegistry(originalUri, sslContext)); + if (dockerClientConfig.getMaxTotalConnections() != null) + connManager + .setMaxTotal(dockerClientConfig.getMaxTotalConnections()); + + if (dockerClientConfig.getMaxPerRoutConnections() != null) + connManager.setDefaultMaxPerRoute(dockerClientConfig + .getMaxPerRoutConnections()); + + clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, + connManager); + + ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig( + clientConfig); + + if (sslContext != null) { + clientBuilder.sslContext(sslContext); + } + + client = clientBuilder.build(); + + if (originalUri.getScheme().equals("unix")) { + dockerClientConfig.setUri(UnixConnectionSocketFactory + .sanitizeUri(originalUri)); + } + WebTarget webResource = client.target(dockerClientConfig.getUri()); + + if (dockerClientConfig.getVersion() == null + || dockerClientConfig.getVersion().isEmpty()) { + baseResource = webResource; + } else { + baseResource = webResource.path("v" + + dockerClientConfig.getVersion()); + } + } + + private org.apache.http.config.Registry getSchemeRegistry( + final URI originalUri, SSLContext sslContext) { + RegistryBuilder registryBuilder = RegistryBuilder + .create(); + registryBuilder.register("http", + PlainConnectionSocketFactory.getSocketFactory()); + if (sslContext != null) { + registryBuilder.register("https", new SSLConnectionSocketFactory( + sslContext)); + } + registryBuilder.register("unix", new UnixConnectionSocketFactory( + originalUri)); + return registryBuilder.build(); + } + + protected WebTarget getBaseResource() { + checkNotNull(baseResource, + "Factory not initialized. You probably forgot to call init()!"); + return baseResource; + } + + @Override + public AuthCmd.Exec createAuthCmdExec() { + return new AuthCmdExec(getBaseResource()); + } + + @Override + public InfoCmd.Exec createInfoCmdExec() { + return new InfoCmdExec(getBaseResource()); + } + + @Override + public PingCmd.Exec createPingCmdExec() { + return new PingCmdExec(getBaseResource()); + } + + @Override + public VersionCmd.Exec createVersionCmdExec() { + return new VersionCmdExec(getBaseResource()); + } + + @Override + public PullImageCmd.Exec createPullImageCmdExec() { + return new PullImageCmdExec(getBaseResource()); + } + + @Override + public PushImageCmd.Exec createPushImageCmdExec() { + return new PushImageCmdExec(getBaseResource()); + } + + @Override + public SaveImageCmd.Exec createSaveImageCmdExec() { + return new SaveImageCmdExec(getBaseResource()); + } + + @Override + public CreateImageCmd.Exec createCreateImageCmdExec() { + return new CreateImageCmdExec(getBaseResource()); + } + + @Override + public SearchImagesCmd.Exec createSearchImagesCmdExec() { + return new SearchImagesCmdExec(getBaseResource()); + } + + @Override + public RemoveImageCmd.Exec createRemoveImageCmdExec() { + return new RemoveImageCmdExec(getBaseResource()); + } + + @Override + public ListImagesCmd.Exec createListImagesCmdExec() { + return new ListImagesCmdExec(getBaseResource()); + } + + @Override + public InspectImageCmd.Exec createInspectImageCmdExec() { + return new InspectImageCmdExec(getBaseResource()); + } + + @Override + public ListContainersCmd.Exec createListContainersCmdExec() { + return new ListContainersCmdExec(getBaseResource()); + } + + @Override + public CreateContainerCmd.Exec createCreateContainerCmdExec() { + return new CreateContainerCmdExec(getBaseResource()); + } + + @Override + public StartContainerCmd.Exec createStartContainerCmdExec() { + return new StartContainerCmdExec(getBaseResource()); + } + + @Override + public InspectContainerCmd.Exec createInspectContainerCmdExec() { + return new InspectContainerCmdExec(getBaseResource()); + } + + @Override + public ExecCreateCmd.Exec createExecCmdExec() { + return new ExecCreateCmdExec(getBaseResource()); + } + + @Override + public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { + return new RemoveContainerCmdExec(getBaseResource()); + } + + @Override + public WaitContainerCmd.Exec createWaitContainerCmdExec() { + return new WaitContainerCmdExec(getBaseResource()); + } + + @Override + public AttachContainerCmd.Exec createAttachContainerCmdExec() { + return new AttachContainerCmdExec(getBaseResource()); + } + + @Override + public ExecStartCmd.Exec createExecStartCmdExec() { + return new ExecStartCmdExec(getBaseResource()); + } + + @Override + public LogContainerCmd.Exec createLogContainerCmdExec() { + return new LogContainerCmdExec(getBaseResource()); + } + + @Override + public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() { + return new CopyFileFromContainerCmdExec(getBaseResource()); + } + + @Override + public StopContainerCmd.Exec createStopContainerCmdExec() { + return new StopContainerCmdExec(getBaseResource()); + } + + @Override + public ContainerDiffCmd.Exec createContainerDiffCmdExec() { + return new ContainerDiffCmdExec(getBaseResource()); + } + + @Override + public KillContainerCmd.Exec createKillContainerCmdExec() { + return new KillContainerCmdExec(getBaseResource()); + } + + @Override + public RestartContainerCmd.Exec createRestartContainerCmdExec() { + return new RestartContainerCmdExec(getBaseResource()); + } + + @Override + public CommitCmd.Exec createCommitCmdExec() { + return new CommitCmdExec(getBaseResource()); + } + + @Override + public BuildImageCmd.Exec createBuildImageCmdExec() { + return new BuildImageCmdExec(getBaseResource()); + } + + @Override + public TopContainerCmd.Exec createTopContainerCmdExec() { + return new TopContainerCmdExec(getBaseResource()); + } + + @Override + public TagImageCmd.Exec createTagImageCmdExec() { + return new TagImageCmdExec(getBaseResource()); + } + + @Override + public PauseContainerCmd.Exec createPauseContainerCmdExec() { + return new PauseContainerCmdExec(getBaseResource()); + } + + @Override + public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { + return new UnpauseContainerCmdExec(baseResource); + } + + @Override + public EventsCmd.Exec createEventsCmdExec() { + return new EventsCmdExec(getBaseResource()); + } + + @Override + public void close() throws IOException { + checkNotNull(client, + "Factory not initialized. You probably forgot to call init()!"); + client.close(); + } } From 8f9c275e9534e365790fb239c760a166ccf07b41 Mon Sep 17 00:00:00 2001 From: Nate Rosenblum Date: Mon, 16 Feb 2015 14:34:26 -0800 Subject: [PATCH 312/452] Restore guava as a dependency The repackaged guava classes provided by Jersey are incomplete and attempting to export these repackaged types will lead to path lookup errors in consumers. Fixes #151 --- pom.xml | 7 +++++++ .../java/com/github/dockerjava/api/model/Device.java | 2 +- .../github/dockerjava/api/model/EventStreamItem.java | 2 +- .../dockerjava/api/model/PushEventStreamItem.java | 2 +- .../com/github/dockerjava/api/model/RestartPolicy.java | 2 +- .../com/github/dockerjava/core/DockerClientConfig.java | 2 +- .../com/github/dockerjava/core/DockerClientImpl.java | 2 +- .../com/github/dockerjava/core/KeystoreSSLConfig.java | 2 +- .../dockerjava/core/LocalDirectorySSLConfig.java | 2 +- .../dockerjava/core/command/AbstrAuthCfgDockerCmd.java | 2 +- .../github/dockerjava/core/command/AbstrDockerCmd.java | 2 +- .../core/command/AttachContainerCmdImpl.java | 2 +- .../dockerjava/core/command/BuildImageCmdImpl.java | 2 +- .../github/dockerjava/core/command/CommitCmdImpl.java | 2 +- .../dockerjava/core/command/ContainerDiffCmdImpl.java | 2 +- .../core/command/CopyFileFromContainerCmdImpl.java | 2 +- .../core/command/CreateContainerCmdImpl.java | 2 +- .../dockerjava/core/command/CreateImageCmdImpl.java | 2 +- .../dockerjava/core/command/ExecCreateCmdImpl.java | 2 +- .../dockerjava/core/command/ExecStartCmdImpl.java | 2 +- .../core/command/InspectContainerCmdImpl.java | 2 +- .../dockerjava/core/command/InspectImageCmdImpl.java | 2 +- .../dockerjava/core/command/KillContainerCmdImpl.java | 2 +- .../dockerjava/core/command/ListContainersCmdImpl.java | 4 ++-- .../dockerjava/core/command/ListImagesCmdImpl.java | 2 +- .../dockerjava/core/command/LogContainerCmdImpl.java | 2 +- .../dockerjava/core/command/PauseContainerCmdImpl.java | 2 +- .../dockerjava/core/command/PullImageCmdImpl.java | 2 +- .../dockerjava/core/command/PushImageCmdImpl.java | 2 +- .../core/command/RemoveContainerCmdImpl.java | 2 +- .../dockerjava/core/command/RemoveImageCmdImpl.java | 2 +- .../core/command/RestartContainerCmdImpl.java | 4 ++-- .../dockerjava/core/command/SaveImageCmdImpl.java | 2 +- .../dockerjava/core/command/SearchImagesCmdImpl.java | 2 +- .../dockerjava/core/command/StartContainerCmdImpl.java | 2 +- .../dockerjava/core/command/StopContainerCmdImpl.java | 4 ++-- .../dockerjava/core/command/TagImageCmdImpl.java | 2 +- .../dockerjava/core/command/TopContainerCmdImpl.java | 2 +- .../core/command/UnpauseContainerCmdImpl.java | 2 +- .../dockerjava/core/command/WaitContainerCmdImpl.java | 2 +- .../github/dockerjava/core/dockerfile/Dockerfile.java | 10 +++++----- .../core/dockerfile/DockerfileStatement.java | 4 ++-- .../dockerjava/core/util/guava/PercentEscaper.java | 2 +- .../dockerjava/core/util/guava/UnicodeEscaper.java | 2 +- .../github/dockerjava/jaxrs/AbstrDockerCmdExec.java | 2 +- .../com/github/dockerjava/jaxrs/BuildImageCmdExec.java | 2 +- .../dockerjava/jaxrs/DockerCmdExecFactoryImpl.java | 2 +- .../com/github/dockerjava/jaxrs/EventsCmdExec.java | 2 +- .../com/github/dockerjava/jaxrs/PushImageCmdExec.java | 2 +- .../com/github/dockerjava/jaxrs/SaveImageCmdExec.java | 2 +- 50 files changed, 64 insertions(+), 57 deletions(-) diff --git a/pom.xml b/pom.xml index 82b7ce82..17bdc728 100644 --- a/pom.xml +++ b/pom.xml @@ -64,6 +64,7 @@ 0.3 1.51 2015-01-27T15-02-14 + 18.0 1.1.0 @@ -143,6 +144,12 @@ ${slf4j-api.version} + + com.google.guava + guava + ${guava.version} + + diff --git a/src/main/java/com/github/dockerjava/api/model/Device.java b/src/main/java/com/github/dockerjava/api/model/Device.java index 63d26b41..574d1ad5 100644 --- a/src/main/java/com/github/dockerjava/api/model/Device.java +++ b/src/main/java/com/github/dockerjava/api/model/Device.java @@ -1,6 +1,6 @@ package com.github.dockerjava.api.model; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; diff --git a/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java b/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java index 6e6ce035..5dd9d65c 100644 --- a/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java +++ b/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java @@ -7,7 +7,7 @@ import java.io.Serializable; -import jersey.repackaged.com.google.common.base.Objects; +import com.google.common.base.Objects; /** * Represents an event stream diff --git a/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java b/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java index f5e845b2..7230a7ce 100644 --- a/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java +++ b/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java @@ -5,7 +5,7 @@ import java.io.Serializable; -import jersey.repackaged.com.google.common.base.Objects; +import com.google.common.base.Objects; /** * Represents an item returned from push diff --git a/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java b/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java index d2dd6d94..bb933f18 100644 --- a/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java +++ b/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java @@ -1,6 +1,6 @@ package com.github.dockerjava.api.model; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 2eb1ab2a..aa5f99b0 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 522afe3b..dd9e566d 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.Closeable; import java.io.File; diff --git a/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java b/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java index 7f141142..ec5a2ba8 100644 --- a/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java +++ b/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java b/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java index a27cb01f..bafe6221 100644 --- a/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java +++ b/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.Serializable; import java.security.Security; diff --git a/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java index c1ccab51..31259f1f 100644 --- a/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrAuthCfgDockerCmd.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; diff --git a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java index 300489a0..751b02cb 100644 --- a/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java +++ b/src/main/java/com/github/dockerjava/core/command/AbstrDockerCmd.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; diff --git a/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java index 65155a1a..fc38ae7d 100644 --- a/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/AttachContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 0634651b..32b5b2f9 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -26,7 +26,7 @@ import com.github.dockerjava.core.GoLangMatchFileFilter; import com.github.dockerjava.core.dockerfile.Dockerfile; -import static jersey.repackaged.com.google.common.base.Preconditions.*; +import static com.google.common.base.Preconditions.*; /** * diff --git a/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java index df8b1a66..55fe5e2e 100644 --- a/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CommitCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import org.apache.commons.lang.builder.ToStringBuilder; diff --git a/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java index abb6469d..36286423 100644 --- a/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ContainerDiffCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; diff --git a/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java index d335bf8c..f4f2ae54 100644 --- a/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CopyFileFromContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index 7a41f1d4..0948bf16 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import org.apache.commons.lang.builder.ToStringBuilder; diff --git a/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java index 71c333e7..daa883f9 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateImageCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java index 3fac9013..65b86ed9 100644 --- a/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ExecCreateCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.api.NotFoundException; diff --git a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java index 70a95b85..193a2cb6 100644 --- a/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ExecStartCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java index de7c268c..9215f233 100644 --- a/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/InspectContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.InspectContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java index c2c91b99..0b477e80 100644 --- a/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/InspectImageCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.InspectImageCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java index ba4da47c..c6175a8a 100644 --- a/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.KillContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java index 741da75e..7144e767 100644 --- a/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ListContainersCmdImpl.java @@ -1,7 +1,7 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkArgument; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; diff --git a/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java index ed163bb8..998dded5 100644 --- a/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; diff --git a/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java index 547165f1..d405a802 100644 --- a/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/LogContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java index a2fd73ee..5ea60fe8 100644 --- a/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PauseContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.PauseContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java index 8dd3af41..d1d4ee02 100644 --- a/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PullImageCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java index 1914f91d..a775bffd 100644 --- a/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/PushImageCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.PushImageCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java index 51dd4b0c..7cd06395 100644 --- a/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RemoveContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.RemoveContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java index 938e2b81..87e096aa 100644 --- a/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RemoveImageCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.RemoveImageCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java index 3548e04f..adcac9b4 100644 --- a/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/RestartContainerCmdImpl.java @@ -1,7 +1,7 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkArgument; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.RestartContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/SaveImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/SaveImageCmdImpl.java index 85f7cfe6..6a4596c7 100644 --- a/src/main/java/com/github/dockerjava/core/command/SaveImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/SaveImageCmdImpl.java @@ -5,7 +5,7 @@ import java.io.InputStream; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; public class SaveImageCmdImpl extends AbstrAuthCfgDockerCmd implements SaveImageCmd { private String name; diff --git a/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java index 164425fc..82c94e49 100644 --- a/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/SearchImagesCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index 44476e0a..c3a5cada 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -1,7 +1,7 @@ package com.github.dockerjava.core.command; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import org.apache.commons.lang.builder.ToStringBuilder; diff --git a/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java index bed0aab7..e961bf8b 100644 --- a/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StopContainerCmdImpl.java @@ -1,7 +1,7 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkArgument; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.NotModifiedException; diff --git a/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java index 3e0370cb..8655ddfe 100644 --- a/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/TagImageCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.command.TagImageCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java index 713ac2f2..5f7190fb 100644 --- a/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/TopContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.TopContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java index ce266162..92d715bc 100644 --- a/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/UnpauseContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.UnpauseContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java index ecfc89e4..d6250cc6 100644 --- a/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/WaitContainerCmdImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.core.command; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import com.github.dockerjava.api.command.WaitContainerCmd; diff --git a/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java b/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java index 72c6c795..72e85c35 100644 --- a/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java +++ b/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java @@ -20,11 +20,11 @@ import java.util.Map; import java.util.UUID; -import jersey.repackaged.com.google.common.base.Function; -import jersey.repackaged.com.google.common.base.Objects; -import jersey.repackaged.com.google.common.base.Optional; -import jersey.repackaged.com.google.common.base.Predicate; -import jersey.repackaged.com.google.common.collect.Collections2; +import com.google.common.base.Function; +import com.google.common.base.Objects; +import com.google.common.base.Optional; +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; /** * Parse a Dockerfile. diff --git a/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java b/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java index 1e2ddf1b..fd22e098 100644 --- a/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java +++ b/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java @@ -8,8 +8,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import jersey.repackaged.com.google.common.base.Objects; -import jersey.repackaged.com.google.common.base.Optional; +import com.google.common.base.Objects; +import com.google.common.base.Optional; /** * A statement present in a dockerfile. diff --git a/src/main/java/com/github/dockerjava/core/util/guava/PercentEscaper.java b/src/main/java/com/github/dockerjava/core/util/guava/PercentEscaper.java index e136ec7b..1d726dca 100644 --- a/src/main/java/com/github/dockerjava/core/util/guava/PercentEscaper.java +++ b/src/main/java/com/github/dockerjava/core/util/guava/PercentEscaper.java @@ -16,7 +16,7 @@ package com.github.dockerjava.core.util.guava; -import jersey.repackaged.com.google.common.base.Preconditions; +import com.google.common.base.Preconditions; /** * A {@code UnicodeEscaper} that escapes some set of Java characters using a diff --git a/src/main/java/com/github/dockerjava/core/util/guava/UnicodeEscaper.java b/src/main/java/com/github/dockerjava/core/util/guava/UnicodeEscaper.java index 9bee03a7..3631193f 100644 --- a/src/main/java/com/github/dockerjava/core/util/guava/UnicodeEscaper.java +++ b/src/main/java/com/github/dockerjava/core/util/guava/UnicodeEscaper.java @@ -16,7 +16,7 @@ package com.github.dockerjava.core.util.guava; -import jersey.repackaged.com.google.common.base.Preconditions; +import com.google.common.base.Preconditions; /** diff --git a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java index a33e11a1..ccb53806 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/AbstrDockerCmdExec.java @@ -1,6 +1,6 @@ package com.github.dockerjava.jaxrs; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index ed36c62c..ffbd8306 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -24,7 +24,7 @@ import com.github.dockerjava.api.model.EventStreamItem; import com.github.dockerjava.api.model.PushEventStreamItem; -import jersey.repackaged.com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList; public class BuildImageCmdExec extends AbstrDockerCmdExec implements BuildImageCmd.Exec { diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index ced652d7..9df09ba7 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -1,6 +1,6 @@ package com.github.dockerjava.jaxrs; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.net.URI; diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java index 3c525bae..75114542 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -1,6 +1,6 @@ package com.github.dockerjava.jaxrs; -import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; import java.util.concurrent.Callable; diff --git a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java index 8a9b9ebc..4d7be3f0 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java @@ -22,7 +22,7 @@ import com.github.dockerjava.api.model.PushEventStreamItem; // Shaded, but imported -import jersey.repackaged.com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList; public class PushImageCmdExec extends AbstrDockerCmdExec implements PushImageCmd.Exec { diff --git a/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java index 16ad0012..49f50856 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java @@ -6,7 +6,7 @@ import com.github.dockerjava.api.command.SaveImageCmd; import com.github.dockerjava.api.model.AuthConfig; import com.github.dockerjava.api.model.PushEventStreamItem; -import jersey.repackaged.com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; From 09a71fedc4c03343ab214928ec72e40c84aa1b17 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 18 Feb 2015 20:39:07 +0100 Subject: [PATCH 313/452] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63fc6e78..e16f9a35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ Change Log docker-java-1.0.0-SNAPSHOT --- + * [#152](https://github.com/docker-java/docker-java/pull/152) Restore guava as a dependency + * [#149](https://github.com/docker-java/docker-java/pull/149) Handle HTTP-Redirects #149 * [#148](https://github.com/docker-java/docker-java/pull/148) Save image functionality * [#142](https://github.com/docker-java/docker-java/pull/142) Reduce Logging Level * [#138](https://github.com/docker-java/docker-java/pull/138) Apache CXF interopabilty From 4bdfd6f1b5aa8230a87eacd3bac6414c53f8f2f0 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 18 Feb 2015 20:39:23 +0100 Subject: [PATCH 314/452] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e16f9a35..a7765b41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Change Log docker-java-1.0.0-SNAPSHOT --- * [#152](https://github.com/docker-java/docker-java/pull/152) Restore guava as a dependency - * [#149](https://github.com/docker-java/docker-java/pull/149) Handle HTTP-Redirects #149 + * [#149](https://github.com/docker-java/docker-java/pull/149) Handle HTTP-Redirects * [#148](https://github.com/docker-java/docker-java/pull/148) Save image functionality * [#142](https://github.com/docker-java/docker-java/pull/142) Reduce Logging Level * [#138](https://github.com/docker-java/docker-java/pull/138) Apache CXF interopabilty From 126fae13e1b87cbcac0277ab8b6a038e50808fc4 Mon Sep 17 00:00:00 2001 From: kalmanb Date: Thu, 19 Feb 2015 13:51:39 +1300 Subject: [PATCH 315/452] Add support for configuring ExtraHosts Extends HostConfig to support adding entries to /etc/hosts on startup. --- .../dockerjava/api/model/HostConfig.java | 15 +++++++++++- .../command/CreateContainerCmdImplTest.java | 23 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/api/model/HostConfig.java b/src/main/java/com/github/dockerjava/api/model/HostConfig.java index 5532fba3..c72d078b 100644 --- a/src/main/java/com/github/dockerjava/api/model/HostConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/HostConfig.java @@ -53,12 +53,16 @@ public class HostConfig { @JsonProperty("Devices") private Device[] devices; + @JsonProperty("ExtraHosts") + private String[] extraHosts; + public HostConfig() { } public HostConfig(String[] binds, Links links, LxcConf[] lxcConf, Ports portBindings, boolean publishAllPorts, boolean privileged, String[] dns, String[] dnsSearch, VolumesFrom[] volumesFrom, String containerIDFile, - Capability[] capAdd, Capability[] capDrop, RestartPolicy restartPolicy, String networkMode, Device[] devices) { + Capability[] capAdd, Capability[] capDrop, RestartPolicy restartPolicy, String networkMode, Device[] devices, + String[] extraHosts) { this.binds = binds; this.links = links; this.lxcConf = lxcConf; @@ -74,6 +78,7 @@ public HostConfig(String[] binds, Links links, LxcConf[] lxcConf, Ports portBind this.restartPolicy = restartPolicy; this.networkMode = networkMode; this.devices = devices; + this.extraHosts = extraHosts; } public String[] getBinds() { @@ -124,6 +129,10 @@ public Device[] getDevices() { return devices; } + public String[] getExtraHosts() { + return extraHosts; + } + public RestartPolicy getRestartPolicy() { return restartPolicy; } @@ -196,6 +205,10 @@ public void setDevices(Device[] devices) { this.devices = devices; } + public void setExtraHosts(String[] extraHosts) { + this.extraHosts = extraHosts; + } + @Override public String toString() { return ToStringBuilder.reflectionToString(this); diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index ed81a529..ba05b268 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -311,4 +311,27 @@ public void createContainerWithEntrypoint() throws DockerException { } + @Test + public void createContainerWithExtraHosts() throws DockerException { + + String[] extraHosts = {"dockerhost:127.0.0.1", "otherhost:10.0.0.1"}; + + HostConfig hostConfig = new HostConfig(); + hostConfig.setExtraHosts(extraHosts); + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withName("container") + .withHostConfig(hostConfig).exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getExtraHosts()), + containsInAnyOrder("dockerhost:127.0.0.1", "otherhost:10.0.0.1")); + } + } From 30e2688b610ed0e12dcafa023159735b2d471fc3 Mon Sep 17 00:00:00 2001 From: kalmanb Date: Fri, 20 Feb 2015 11:28:23 +1300 Subject: [PATCH 316/452] Support for withExtraHosts on StartContainerCmd --- .../api/command/StartContainerCmd.java | 9 +++++++- .../core/command/StartContainerCmdImpl.java | 16 +++++++++++++ .../command/StartContainerCmdImplTest.java | 23 +++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index 40fb23a9..b48e3050 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -40,6 +40,8 @@ public interface StartContainerCmd extends DockerCmd { public Device[] getDevices(); + public String[] getExtraHosts(); + public RestartPolicy getRestartPolicy(); public Capability[] getCapAdd(); @@ -107,6 +109,11 @@ public interface StartContainerCmd extends DockerCmd { */ public StartContainerCmd withDevices(Device... devices); + /** + * Add hostnames to /etc/hosts in the container + */ + public StartContainerCmd withExtraHosts(String... extraHosts); + /** * Set custom {@link RestartPolicy} for the container. Defaults to * {@link RestartPolicy#noRestart()} @@ -141,4 +148,4 @@ public interface StartContainerCmd extends DockerCmd { public static interface Exec extends DockerCmdExec { } -} \ No newline at end of file +} diff --git a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java index c3a5cada..dba35fb9 100644 --- a/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/StartContainerCmdImpl.java @@ -65,6 +65,9 @@ public class StartContainerCmdImpl extends AbstrDockerCmd Date: Tue, 20 Jan 2015 23:36:34 +0100 Subject: [PATCH 317/452] add certificates for integration test on CI --- etc/certs/README.md | 175 ++++++++++++++++++++++++++++++++++++++ etc/certs/ca-key.pem | 30 +++++++ etc/certs/ca.pem | 20 +++++ etc/certs/ca.srl | 1 + etc/certs/cert.pem | 18 ++++ etc/certs/client.csr | 15 ++++ etc/certs/extfile.cnf | 1 + etc/certs/key.pem | 27 ++++++ etc/certs/server-cert.pem | 18 ++++ etc/certs/server-cert.txt | 13 +++ etc/certs/server-key.pem | 27 ++++++ etc/certs/server.csr | 16 ++++ 12 files changed, 361 insertions(+) create mode 100644 etc/certs/README.md create mode 100644 etc/certs/ca-key.pem create mode 100644 etc/certs/ca.pem create mode 100644 etc/certs/ca.srl create mode 100644 etc/certs/cert.pem create mode 100644 etc/certs/client.csr create mode 100644 etc/certs/extfile.cnf create mode 100644 etc/certs/key.pem create mode 100644 etc/certs/server-cert.pem create mode 100644 etc/certs/server-cert.txt create mode 100644 etc/certs/server-key.pem create mode 100644 etc/certs/server.csr diff --git a/etc/certs/README.md b/etc/certs/README.md new file mode 100644 index 00000000..165265a0 --- /dev/null +++ b/etc/certs/README.md @@ -0,0 +1,175 @@ +# Creating Certificates for Docker + +## Warning +> These certificates are only meant for integration tests on CI environments (like circleCI). Do not use them for any real machine. +> Since all keys are publicly available anybody could gain root access to your machine. + +### 1. Create the certificate files +There is an [excellent guide](https://docs.docker.com/articles/https/) on the official docker homepage. +This document contains the log on how the certificates in this folder were created. +It differs slightly form the official guide. + - Certificates are valid for 10 years instead of 1 year. + - Certificates use v3_req extension to support both `127.0.0.1` and `localhost` (see config file [server-cert.txt](server-cert.txt)). + +``` +$ cd ~ +``` + +``` +$ mkdir .docker +``` + +``` +$ cd .docker +``` + +``` +$ echo 01 > ca.srl +``` + +``` +$ openssl genrsa -des3 -out ca-key.pem 2048 +Generating RSA private key, 2048 bit long modulus +............................................+++ +..................+++ +e is 65537 (0x10001) +Enter pass phrase for ca-key.pem: docker-java +Verifying - Enter pass phrase for ca-key.pem: docker-java +``` + +``` +$ openssl req -new -x509 -days 3650 -key ca-key.pem -out ca.pem +Enter pass phrase for ca-key.pem: docker-java +You are about to be asked to enter information that will be incorporated +into your certificate request. +What you are about to enter is what is called a Distinguished Name or a DN. +There are quite a few fields but you can leave some blank +For some fields there will be a default value, +If you enter '.', the field will be left blank. +----- +Country Name (2 letter code) [AU]: +State or Province Name (full name) [Some-State]: +Locality Name (eg, city) []: +Organization Name (eg, company) [Internet Widgits Pty Ltd]: docker-java +Organizational Unit Name (eg, section) []: +Common Name (e.g. server FQDN or YOUR name) []: +Email Address []: +``` + +``` +$ openssl genrsa -des3 -out server-key.pem 2048 +Generating RSA private key, 2048 bit long modulus +..........+++ +.........+++ +e is 65537 (0x10001) +Enter pass phrase for server-key.pem: docker-java +Verifying - Enter pass phrase for server-key.pem: docker-java +``` + +``` +$ openssl req -new -key server-key.pem -out server.csr -config server-cert.txt +Enter pass phrase for server-key.pem: docker-java +You are about to be asked to enter information that will be incorporated +into your certificate request. +What you are about to enter is what is called a Distinguished Name or a DN. +There are quite a few fields but you can leave some blank +For some fields there will be a default value, +If you enter '.', the field will be left blank. +----- +TypeCommonNameHere []: localhost +``` + +``` +$ openssl x509 -req -days 3650 -in server.csr -CA ca.pem -CAkey ca-key.pem -out server-cert.pem -extensions v3_req -extfile server-cert.txt +Signature ok +subject=/CN=localhost +Getting CA Private Key +Enter pass phrase for ca-key.pem: docker-java +``` + +``` +$ openssl genrsa -des3 -out key.pem 2048 +Generating RSA private key, 2048 bit long modulus +............................................+++ +.......................................................+++ +e is 65537 (0x10001) +Enter pass phrase for key.pem: docker-java +Verifying - Enter pass phrase for key.pem: docker-java +``` + +``` +$ openssl req -subj '/CN=client' -new -key key.pem -out client.csr +Enter pass phrase for key.pem: docker-java +``` + +``` +$ echo extendedKeyUsage = clientAuth > extfile.cnf +``` + +``` +$ openssl x509 -req -days 3650 -in client.csr -CA ca.pem -CAkey ca-key.pem -out cert.pem -extfile extfile.cnf +Signature ok +subject=/CN=client +Getting CA Private Key +Enter pass phrase for ca-key.pem: docker-java +``` + +``` +$ openssl rsa -in server-key.pem -out server-key.pem +Enter pass phrase for server-key.pem: docker-java +writing RSA key +``` + +``` +$ openssl rsa -in key.pem -out key.pem +Enter pass phrase for key.pem: docker-java +writing RSA key +``` + +Once you created all the files you can have a look at their content with the following command + +``` +openssl x509 -in .pem -inform pem -noout -text +``` + +### 2. Configuring the docker daemon +On linux the docker daemon allows to specify options in the file `/etc/default/docker`. +By adding the following line (or modifying an existing line) one can get the docker daemon to listen on both *unix socket* and *https*. +``` +DOCKER_OPTS="-H unix:///var/run/docker.sock -H tcp://127.0.0.1:2376 --tlsverify --tlscacert=~/.docker/ca.pem --tlscert=~/.docker/server-cert.pem --tlskey=~/.docker/server-key.pem" +``` + +### 3. Restart the daemon and test the setup +After changing the daemon options it must be restarted + +``` +$ sudo service docker restart +``` + +To test the socket and the https connection: + +``` +$ docker -H tcp://127.0.0.1:2376 --tlsverify version +Client version: 1.4.1 +Client API version: 1.16 +Go version (client): go1.3.3 +Git commit (client): 5bc2ff8 +OS/Arch (client): linux/amd64 +Server version: 1.4.1 +Server API version: 1.16 +Go version (server): go1.3.3 +Git commit (server): 5bc2ff8 +``` + +``` +$ docker -H unix:///var/run/docker.sock version +Client version: 1.4.1 +Client API version: 1.16 +Go version (client): go1.3.3 +Git commit (client): 5bc2ff8 +OS/Arch (client): linux/amd64 +Server version: 1.4.1 +Server API version: 1.16 +Go version (server): go1.3.3 +Git commit (server): 5bc2ff8 +``` diff --git a/etc/certs/ca-key.pem b/etc/certs/ca-key.pem new file mode 100644 index 00000000..bf1b0e2d --- /dev/null +++ b/etc/certs/ca-key.pem @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: DES-EDE3-CBC,A5E7732EBEA97F20 + +/KgdVVIFc++tLxcot9FCziUqi6uZMk2pFy676Vh9ZILuHE5t8WZ66sn+aXjsNb0T +L9Z67+Yx9E3Y7L2wl/NwwpYZctt9XWo8wR1fVucYf98PEbRWXlbS1GYK3bMtYPeU +iGxLOK/WU3uqItH9g2uxCeXf+wjP14kiFrzrrd1XrShxTUs/bqIbHd7+GJetgvpS +5UKXiISLUf+5EwuODVhe6zYg80P616HuitkKDekAM7PZz6YsVIhPNnxOlSIEIylS +sPK71Aiy6yu57Qp6Jm1E1JsPVcoEOAEtAUlMxxyVNhj5fQ35lX/OkkhJGXmKXfIl +U6YVBreAwSeuwv7ochmyIsoOHzw5QJGlm8ycMYaxrceh7J3cGT0+04WgLi9+ieZ/ +AseXPryryqhIgR4qN0/9vAnA++N+YtelzhIeXqJhtpMEc5yb7po/OJejMboFJyAa +5P4IvCXohfSVSMBwaB2Vh9xA+2d34hQS5AKFkzlfbMJU81HmCUh70CKYJ9PGSdh4 +itkSoc9iQ2e0RxOxhJSqjpYYbKcxL2PTkMTpxqDGiJQ8FfLWuDhpz5mUWSvt3a41 +zbypHsKntibKP8Ceem1vckIid0mnWaZolbOcHBzErsa/3BvO5ZP3q7HTf35yyy7o +VO1LXQqO8trYnkG2PiXk0eWUzTVgiGQYFoGdAdFOkF95y2LBRcgyBhQTfxIbqMW3 +Nr2wkSHU0JT1NLI0UKhVAB7/uLJKwGgLcYU9j4DAA4rT8sZF9zbdjLuSFx5dnV+h +g8H+QOKbvmGpvTIeDrxwSpgzu7mqmPcpf1gFHBTdYCV8QXF4u96VZlar6dnoYoVj +OdS96HYxC2gsrDJJ5Nls0deTWqdKxbnDRXs4Vu7yTO1B/nMnSgptksOoVq50SD1a +IrtA4d6aZzfr1U647nWXTdaeDJ2acq4u8fM8JZNbMj0/Y7HJa3BQz+55yCQb+iFE +1VOzm1D9xcU8NCBgquT4C6FcPIQQpyq50B7lez8SEyAvqPnoMlqAulF6qo+0ZtZC +MaS+C2dlNUUjVOV7qDsracSY6esf5WF40nc1jzNflV+Pwqk7ISDkv4GiiH+yXq8t +hrP2sAiWHd2oHw1RCoEW7UgWAyW72wAOFTwnvQBCkVmxk/kBgrNDU+8SBmClqSod +CEWOcb6apore20xXmhq8mEddW2Xjk+U1dLRkBBp5oaopbYQ25LO+PZIpIJr1mcCi +6D42EHmCGQovkaL4G40IhXDrU98u2J72be8i/B7sQ8s3A5d7CwJwICG5PoiM7MJU +dfwWPmpKVAt38PQ4fWmZjw3pUnU2qyXGUc5TV6J8ZhU5yFvx4P7n7/Zd1QaZ34ar +A3XcHoAidu8O/C1N/bdSttJHniirTIYYgiqVTtjT66qALSeDCab3JT9C7Zfxr39+ +YamKTXu+dMw7C91Cg9ETiNcNvNsjVK1cMVmcwirJjSlK1Wr1cRbFkWg55uVSuO52 +r08qGAHge9gekW1Rcc/RKp0qv193PYCYMzKUoW28MEspHPbs84fhGIiK8v/OF9Pg +nu0T8r+Xzr2a7TSSTsO77WTjXrEfgjrddfUhsIiSNWVePL86iNkZoB5QrWH7DgKW +-----END RSA PRIVATE KEY----- diff --git a/etc/certs/ca.pem b/etc/certs/ca.pem new file mode 100644 index 00000000..0cf1b2b9 --- /dev/null +++ b/etc/certs/ca.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQzCCAiugAwIBAgIJAN94VLe4RxmkMA0GCSqGSIb3DQEBCwUAMDgxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMRQwEgYDVQQKDAtkb2NrZXItamF2 +YTAeFw0xNTAxMjAyMTE5MzBaFw0yNTAxMTcyMTE5MzBaMDgxCzAJBgNVBAYTAkFV +MRMwEQYDVQQIDApTb21lLVN0YXRlMRQwEgYDVQQKDAtkb2NrZXItamF2YTCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANiZy9f+AHejo9s9Ve1WwXQeKR28 +s2SbSpf82+kMtLHL0/r0HIDwhA9uOSglqpFY21vVWFYGY+Mh8Z4bgoyUOFIM/WQn +fgS2trYjfRZuZeR8u57dVyqLyzMV7eWdPBbnU1rTavwvsQMwWWwKF+AXhKpUoDtT +N+gQyqTQYdEsyhQS/HzC7fH3QC0deSrUS5yjX9qIEr3dZwE93BK2wqUFEy9JvyQ5 +DIh5N6HpRKzFcH/zHd/GPeXXnWKVCO5plDn/XTv85a5PesyFV2Zi//0g3UWgpzFC +2sTh5Brj7kamlVbOLBpQTV2LFY38c3MNYbiNTzKtkAQgVtHA4YS5ym3z8PcCAwEA +AaNQME4wHQYDVR0OBBYEFJME9p4vpy900Ryw/E/Mz750ZK9xMB8GA1UdIwQYMBaA +FJME9p4vpy900Ryw/E/Mz750ZK9xMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEL +BQADggEBANZPR1572nkOKEsxZkV1jou64NqZLGGVjXEdjJP56R5G8cyoBoZfqiT0 +J2/IxU7UZ5n65C79FLeLnAq/0GuWw07BREzAZjBZmBOe3Ma3qZi47MESIEEJ06XL +g4/rGFbeDlV9otVhKQ27U//4qodLUNzZBq+VrQNUfSk8vqEb0iGKHSSLTV6DZx8w +Yb79ZFA53+LOloKKbrGQsSKshSDUxnl+19jVXMUgvvrcyEE20I30wB0ZVE5pPME7 +tAqBFjqe+SR+gxwVXrpRSPhjZfqDhSOvsbZwuJqNVqE1sVnZCbwcnvIGGRu8TWej +JARvyGHOlwoE3kVH+4VKeYQ7PcL5wck= +-----END CERTIFICATE----- diff --git a/etc/certs/ca.srl b/etc/certs/ca.srl new file mode 100644 index 00000000..75016ea3 --- /dev/null +++ b/etc/certs/ca.srl @@ -0,0 +1 @@ +03 diff --git a/etc/certs/cert.pem b/etc/certs/cert.pem new file mode 100644 index 00000000..7063ef99 --- /dev/null +++ b/etc/certs/cert.pem @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC2zCCAcOgAwIBAgIBAzANBgkqhkiG9w0BAQsFADA4MQswCQYDVQQGEwJBVTET +MBEGA1UECAwKU29tZS1TdGF0ZTEUMBIGA1UECgwLZG9ja2VyLWphdmEwHhcNMTUw +MTIwMjEzNjIzWhcNMjUwMTE3MjEzNjIzWjARMQ8wDQYDVQQDDAZjbGllbnQwggEi +MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZlY8JUY4VqGyi/h9b0WHvqjgt +y+nyQd9vdgY6IvjsLDcl0fjp4knFxSpl1U0oLA1JnElT3Qgv1zv4GYvc/DUbld7d +5B1jQzOYbUWgOzRa/903wpEXn9waBU2mwtyObzmXvmZ6XUA+fgx3EFnimflzEkjm +vYskH2lW0pbbt4/3cCeD282DEmmzaOOkFR8agV6aE4T/x+BRFkVgR1T8Dfiu6Yyy +CJ57OO7kcCGoAPIEe3dGi5UGQVKuDjlohZKApg6E2ISINVvbxsHqKkGU9lNRqxkg +P6qV8LAhypo5sEqeAvlnIgOrhpb0c+zzoqgV0d+s2gU2GVa6SvT0OcidwyzjAgMB +AAGjFzAVMBMGA1UdJQQMMAoGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUAA4IBAQCL +2T/pu5weRuXcPEvBvmyOfEZZp0bzfGw0DYsp5XKARV7M6qJPPTpjqLm3AbjPqsv2 +fn0GQq8hWThveJhYps6mnhAsYC5rlfxFH+JC2i1EfhTIjWCP7WKdjXJr6hmhrVNc +7cxyQjWh/vSAk4nRcH3fNLUF1HNhZBuB1aOniTWTeoTgd7sIQjVpX4V6avOEcSGo +mylt3fqHO5X/CONFJnvv0SHFOCGr9WX/9Sq0GlpHoEK80gBVQt/O22U1PGZ2kYaT +Z/Fs2r85ltC/POPTCyQ3oKk4j2YF7HwJhJ2gP8jwKl4aX1iypwpCa/d9hvCFn8Wh +bEv9E557EH9PjLyqlnwi +-----END CERTIFICATE----- diff --git a/etc/certs/client.csr b/etc/certs/client.csr new file mode 100644 index 00000000..44748724 --- /dev/null +++ b/etc/certs/client.csr @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICVjCCAT4CAQAwETEPMA0GA1UEAwwGY2xpZW50MIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEA2ZWPCVGOFahsov4fW9Fh76o4Lcvp8kHfb3YGOiL47Cw3 +JdH46eJJxcUqZdVNKCwNSZxJU90IL9c7+BmL3Pw1G5Xe3eQdY0MzmG1FoDs0Wv/d +N8KRF5/cGgVNpsLcjm85l75mel1APn4MdxBZ4pn5cxJI5r2LJB9pVtKW27eP93An +g9vNgxJps2jjpBUfGoFemhOE/8fgURZFYEdU/A34rumMsgieezju5HAhqADyBHt3 +RouVBkFSrg45aIWSgKYOhNiEiDVb28bB6ipBlPZTUasZID+qlfCwIcqaObBKngL5 +ZyIDq4aW9HPs86KoFdHfrNoFNhlWukr09DnIncMs4wIDAQABoAAwDQYJKoZIhvcN +AQELBQADggEBAJ+IARXkgVRRj2sARH4D+1cwD5WSZwlTr5dsB5myGlNx7crNrWeu +Rqhu2r3xh8b5FlIbggC+aR8U5ikeBHfiRYXV3lt41+AKriKqNR348AAw/WLWPEDG +V6WWieVyicTdN2yMH3tWcisIsqTiVGWDcagVhRmAPP0VBdQ8OyTJCIjIiOhG0LDg +LlEiFuO7npc5ywXJjfh4TjFsyfSjTJv3UYY7zWYgfalWit9OeDbMhgGOwOwOFyDj +lOpQKeBxDwhnH5DC90OmbjK4FkMbQhrTXvURfUts/wz2SLqkQVB8FWuVc0RwUhnX +s2KWbehobjOpK3WkOgDfLGY72HnhU5IbP9Q= +-----END CERTIFICATE REQUEST----- diff --git a/etc/certs/extfile.cnf b/etc/certs/extfile.cnf new file mode 100644 index 00000000..74dedb38 --- /dev/null +++ b/etc/certs/extfile.cnf @@ -0,0 +1 @@ +extendedKeyUsage = clientAuth diff --git a/etc/certs/key.pem b/etc/certs/key.pem new file mode 100644 index 00000000..4319223e --- /dev/null +++ b/etc/certs/key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEA2ZWPCVGOFahsov4fW9Fh76o4Lcvp8kHfb3YGOiL47Cw3JdH4 +6eJJxcUqZdVNKCwNSZxJU90IL9c7+BmL3Pw1G5Xe3eQdY0MzmG1FoDs0Wv/dN8KR +F5/cGgVNpsLcjm85l75mel1APn4MdxBZ4pn5cxJI5r2LJB9pVtKW27eP93Ang9vN +gxJps2jjpBUfGoFemhOE/8fgURZFYEdU/A34rumMsgieezju5HAhqADyBHt3RouV +BkFSrg45aIWSgKYOhNiEiDVb28bB6ipBlPZTUasZID+qlfCwIcqaObBKngL5ZyID +q4aW9HPs86KoFdHfrNoFNhlWukr09DnIncMs4wIDAQABAoIBAAT2o2+r+5jE4c2K +DH8UtK457NQmnayYEhfB0nyLBbClhZCITKxRLCulxsTR69OpxZfTR9zw4tnsiAKt +2oHtAu0hKxdWt9Dm3Itymq8ACr60rYAzIQov7F5vlojiUxOwt9idUEskS23hhDlH +FzXTG1yjoyQYWM83JDkFzskuU8tqKcdZUGHxwDqWaLpCJRCqaXGBbwBsiBE0WpD4 +U2Iq32Cbcf2KK/iI2CpEhEVSLZAHuh1Ovv4l2kb3PSFV1x4zSOJjHO6LM+4nAgmx +1XcVH+Qpw7oRoRpEajBss6XlIvRRohhXRlzUDi5T6smkoo69pXn1OFaav6U8BwVN +2nIrnJECgYEA8Wn9OBnxgJvVji+Wdc92IoHgSB8Y/xPuI4a2go84AHd0Ek7GzE6g +o52eq1v+7+Uj2y/xTIvcGEfOz8/oeOzWJqsLpi34CeqhewwWHNogAD2Xg6DpCHmc +ARzKKod9djwU0y5+/8YBsfpSM6ZKzbnP5HzblA+oIllAY50VJvp+HhsCgYEA5rr8 +8EsjnuNo+/RuVp4vATP2ML6D/ILHQEZR6tPgfjaiEZfMm22yX6J8F/kNVHO2c1Pt +94A+dKa3QyQBieb27u1+N0iUOkAYvnExkaazkVwOH4sXwn4EzxGFTdwwSW5Uenl4 +8Qry08mnnJwKP38TlNrw3Q9PbZNFFlXLdaAteNkCgYEAjhmFI3Ch5sHTgk4gklf7 +gXRRQCKN5BcnJWI2K8OBg0TM3bng6oGdrLEqpFMSTMLjyDEAJ75rXx9lbI1EmWlO +5JPp13dXeP7S7kq++VyrWXjnpmMgyAxM95qqpT37a40R9Px5ZLR4avqdSCmp/k5R +QHz+Arj0jsNaU0gzGy527eECgYEAu1Mk+JKIoP9QxP52dqyGzRs6zehfkCs9SdnN +uDG9GbuRaWctHyO4phxtU6lIQUCQ6KFDmqXsDxkrwL8C4Ms7wE/hIVEzxvczH6sW +64HEWEe8z69F4wodLWC0MbqLGZMR0z28CzcwXvJhuqyVRWgOpdP7qf48JmJivPd6 +8EzTnkECgYA5x137xZgFZGYOdRF4yCLkbZ8weDKbcTotUgNSFR2xMYzytzWmEg5D +rvjhGXmhqvxNTzEJehWVVJoQHFW0aJhC7ML2VP56DQ7p2gM75HrojZpdoUzwF73T ++E6W/Nddm6N8tuQ/q/rIrsgF6/FJ9H5D9ZeK69En3QwC4xUgHlWQGA== +-----END RSA PRIVATE KEY----- diff --git a/etc/certs/server-cert.pem b/etc/certs/server-cert.pem new file mode 100644 index 00000000..1edc7b79 --- /dev/null +++ b/etc/certs/server-cert.pem @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC5TCCAc2gAwIBAgIBAjANBgkqhkiG9w0BAQsFADA4MQswCQYDVQQGEwJBVTET +MBEGA1UECAwKU29tZS1TdGF0ZTEUMBIGA1UECgwLZG9ja2VyLWphdmEwHhcNMTUw +MTIwMjEzMTQ4WhcNMjUwMTE3MjEzMTQ4WjAUMRIwEAYDVQQDEwlsb2NhbGhvc3Qw +ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDECxOHu9oVQX2IGivToPdC +gcVcewBOQJClLDmnGdfP99gtBdNaa59cXnPudd+r24lfnIs98XUbAWZoYFYTmj1s +jukyL1jwH2zcPVmcTKWz6zTbComxaNQJRHZGPIeR1qJIiJHIMa0Xt9y0w/SH0qHw +Ts69PkRCILaUGRhsms5qYJ91fsRzYO4jXYR3F0vEEoUzhlI7qw4n3QaTOVbZ154v +3VEvlrECCLVpE4KUcccgenNNoEeqTdkiAe4ywupHjkzo3ThcWSfv+a+oRRmQlhsD +BPL2RxyNiu2NvML6WyMPKQNvyV7s6kyDKmpbLg3Y0QV/VhneZ90+bPG/VslpMPzb +AgMBAAGjHjAcMBoGA1UdEQQTMBGHBH8AAAGCCWxvY2FsaG9zdDANBgkqhkiG9w0B +AQsFAAOCAQEAInNXInEzAA9AbEOsNXKyAXHJQWCUK6+tCQkxNIiGKaRWtEYLmrpx +1xx7xTACZihpK+vRyG4MUNkHIoVqNi/Jg4Z0cJq3lU3FnCpU0TUY2avj8iWbn2Ke +B5SFnPyi2JSZhw8ZsssA6/cs7EoTbQYSi1CO7SoKXj8RvQJcYWc8dx3Ydkq05pIT +e897LxrHjrpiGK+a+2ghw9amfnXmElYneKP5WrpZcIiHAD3Fp6ecvYkLGLf1G5D/ +bjjMUfbsYMjeZFVG6wzTJ8tBDeJkovpb2vPpuLM+raYkqGDiUBD2Kqgyq1uL6ZLc +PYmsXVGiosG7QpVxDsaYy8DQa/4FeQWC1g== +-----END CERTIFICATE----- diff --git a/etc/certs/server-cert.txt b/etc/certs/server-cert.txt new file mode 100644 index 00000000..4ce34a14 --- /dev/null +++ b/etc/certs/server-cert.txt @@ -0,0 +1,13 @@ +[req] +distinguished_name = req_distinguished_name +req_extensions = v3_req + +[req_distinguished_name] +commonName = TypeCommonNameHere + +[v3_req] +subjectAltName = @alt_names + +[alt_names] +IP.1 = 127.0.0.1 +DNS.1 = localhost diff --git a/etc/certs/server-key.pem b/etc/certs/server-key.pem new file mode 100644 index 00000000..7490cbcb --- /dev/null +++ b/etc/certs/server-key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAxAsTh7vaFUF9iBor06D3QoHFXHsATkCQpSw5pxnXz/fYLQXT +WmufXF5z7nXfq9uJX5yLPfF1GwFmaGBWE5o9bI7pMi9Y8B9s3D1ZnEyls+s02wqJ +sWjUCUR2RjyHkdaiSIiRyDGtF7fctMP0h9Kh8E7OvT5EQiC2lBkYbJrOamCfdX7E +c2DuI12EdxdLxBKFM4ZSO6sOJ90GkzlW2deeL91RL5axAgi1aROClHHHIHpzTaBH +qk3ZIgHuMsLqR45M6N04XFkn7/mvqEUZkJYbAwTy9kccjYrtjbzC+lsjDykDb8le +7OpMgypqWy4N2NEFf1YZ3mfdPmzxv1bJaTD82wIDAQABAoIBAEpDT+CpHpHSvzTh +hRyj60Z8VkEULyd1edW4DRbpyUD0yCU2AbxM7I9XEF+Ss2osvbtEV9LdNtlGDH8Z +j0HZuc73zArAuNYtcVV0wA9fUZ34SYt4UHSuGzRvhMZSg6CRR+RmJ6NIfiNv+OFZ +IbaZ6dJYaCR0A/Nw5PjxELmDYxIUYcXKZAwjVP+GLvOmjE/xSD1kwEVeIzmtgEeX +UixqI8KgDpASuf0N21fJ67pcAIohrmsWzjeSXMFINFCMuUuqAKCuPpUthybHjMy/ +7vjEI7ViEcpcHd7IW5h+RTl3r4hnQaNbbbcwGWmc+8u7qOcPJe6cEBXD8ud6dZUz +wdLdRwECgYEA8z9Vw/Ms2NQwQA4FUcnoQQ4pnK5bJIPLAa7MaomEYfVciMU1oWcI +4gspTelHSSY4+D/AlyLD5FgDpi0YfeYQJjcZVs2m/5mZn5BFqQKAmmMWtBxo6RSO +VF6SyfNsqpQTsFY0dp9HKCDVo0mtTKFizLBDrmSCroGv3fb6KodH25sCgYEAzlI0 +3Lan70ABn3cO4iGfQvvrUw2A/ZX01lVtDJzq8LJ+IXy9zev4C+ZOUT/8/L/D4K3W +hO1px7WrUSaMr5F9scXC0PYfMNoMn9YzfxEYCMQA5dCWnUhf6t2ESUFeh1Qt3b7j +kz7U2/pSk7VXithwITKKEgicG0EBABHuyio0l8ECgYEAjF90YwwmSUrKPWzZ7QUT +ntdJdD26IyxbLrFtDd4mI1GxAMyt0mLfYXMHdwq0NKZ2IezIe294lIGmOXO0upLV +pvgNC2bKhJ5jZQ2g5ZOoG3ArXe03LarLKC0bkKeFgjrJ0e0tgXcRXTr1jrGp7JsF +pRHjPPSL5aC5mOI6I+jFsxkCgYAV6uG2uKiqX9BMUmeAWjYC9aQQFJUpWy7BPh3x +gxHqM+v2PrwjDfgxu2uCchu79dsnGRB62oWsM35ZhpDXbcs+gVWqwRqbI+7HZAfg +bb5x3/CAeWImnzOhTZrp9UnHcofU0Jx4Xepa3AK9sjv0gf2XaTkFpWh/9K3Yhg8p +5sXjgQKBgGv3a1VpQ0YG3PoN7l8Pjzg6/IYslxUkZwdyUqeTJD3hRDbQybXIhJGw +0GbAkxTkXwFFQpRplCj5wk6U0M/JZRW3IhiuHovmZd/WSvl3EgzLT/5U3kYE3K6V +ZH1Hgs1SCQhQXIWm/QerI1KlNg4PKhctPohSc1ttW3hQUBh1reTR +-----END RSA PRIVATE KEY----- diff --git a/etc/certs/server.csr b/etc/certs/server.csr new file mode 100644 index 00000000..f4fc6d38 --- /dev/null +++ b/etc/certs/server.csr @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIChjCCAW4CAQAwFDESMBAGA1UEAxMJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEAxAsTh7vaFUF9iBor06D3QoHFXHsATkCQpSw5pxnX +z/fYLQXTWmufXF5z7nXfq9uJX5yLPfF1GwFmaGBWE5o9bI7pMi9Y8B9s3D1ZnEyl +s+s02wqJsWjUCUR2RjyHkdaiSIiRyDGtF7fctMP0h9Kh8E7OvT5EQiC2lBkYbJrO +amCfdX7Ec2DuI12EdxdLxBKFM4ZSO6sOJ90GkzlW2deeL91RL5axAgi1aROClHHH +IHpzTaBHqk3ZIgHuMsLqR45M6N04XFkn7/mvqEUZkJYbAwTy9kccjYrtjbzC+lsj +DykDb8le7OpMgypqWy4N2NEFf1YZ3mfdPmzxv1bJaTD82wIDAQABoC0wKwYJKoZI +hvcNAQkOMR4wHDAaBgNVHREEEzARhwR/AAABgglsb2NhbGhvc3QwDQYJKoZIhvcN +AQELBQADggEBAGaf5ZlZMuUmLzdyWQEm90YPu9jpqrFocu2GUmHLEuW23/p3JRHX +gljn8VJkHaaAtP8gqPnk6Fn2BZJZrqVsjg+KoLxHuKUC0K2ZdYoFBl4usmfpQqe9 +3F0qUvScHaqdxff6OKORD1hXqCYF6V1WGwb2cTSbYr1xy/ehK+VhhPd+zTaQg0Es +CcacEJTYd61gIsW2FD0XkokUUokNLj0FL9dt2ANgaefJPKBH/Pp/2hTiXEhEjIm6 +MkQVjnMbx/5/5k48yhpwPEl0FdiyLQdbzT03sHbrDKCeAdOJgOibZUnJYCJ8/1vu +AH28ajlCUMvKsUE+mtDU/VYvci758n5CiYc= +-----END CERTIFICATE REQUEST----- From 22d4b2ac665ee410284a5b3cae574dac8ff1d1a2 Mon Sep 17 00:00:00 2001 From: Stephan Classen Date: Sat, 21 Feb 2015 23:30:53 +0100 Subject: [PATCH 318/452] add configuration for circle CI --- circle.sh | 45 +++++++++++++++++++++++++++++++++++++++++++++ circle.yml | 28 ++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100755 circle.sh create mode 100644 circle.yml diff --git a/circle.sh b/circle.sh new file mode 100755 index 00000000..c84ca3fe --- /dev/null +++ b/circle.sh @@ -0,0 +1,45 @@ +#!/bin/bash -ex + +case "$1" in + pre_machine) + # copy certificates to default directory ~/.docker + mkdir .docker + cp $CIRCLE_PROJECT_REPONAME/etc/certs/* .docker + + # configure docker deamon to use SSL and provide the path to the certificates + docker_opts='DOCKER_OPTS="$DOCKER_OPTS -H tcp://127.0.0.1:2376 --tlsverify --tlscacert='$HOME'/.docker/ca.pem --tlscert='$HOME'/.docker/server-cert.pem --tlskey='$HOME'/.docker/server-key.pem"' + sudo sh -c "echo '$docker_opts' >> /etc/default/docker" + + # debug output + cat /etc/default/docker + ls -la $HOME/.docker + ;; + + post_machine) + # fix permissions on docker.log so it can be collected as an artifact + sudo chown ubuntu:ubuntu /var/log/upstart/docker.log + + # validate that docker is working + docker version + ;; + + dependencies) + mvn clean install -T 2 -Dmaven.javadoc.skip=true -DskipTests=true -B -V + ;; + + test) + mvn clean verify + ;; + + collect_artifacts) + # collect artifacts into the artifacts dir + cp target/*.jar $CIRCLE_ARTIFACTS + ;; + + collect_test_reports) + mkdir -p $CIRCLE_TEST_REPORTS/surefire + mkdir -p $CIRCLE_TEST_REPORTS/failsafe + cp target/surefire-reports/TEST-*.xml $CIRCLE_TEST_REPORTS/surefire + cp target/failsafe-reports/TEST-*.xml $CIRCLE_TEST_REPORTS/failsafe + ;; +esac diff --git a/circle.yml b/circle.yml new file mode 100644 index 00000000..d8a80371 --- /dev/null +++ b/circle.yml @@ -0,0 +1,28 @@ +dependencies: + override: + - ./circle.sh dependencies + +test: + override: + - ./circle.sh test + post: + - ./circle.sh collect_artifacts + - ./circle.sh collect_test_reports + +machine: + pre: + - ls -la docker-java + - $CIRCLE_PROJECT_REPONAME/circle.sh pre_machine + post: + - $CIRCLE_PROJECT_REPONAME/circle.sh post_machine + services: + - docker + environment: + MAVEN_OPTS: -Xmx128m + DOCKER_HOST: tcp://127.0.0.1:2376 + DOCKER_CERT_PATH: $HOME/.docker + DOCKER_TLS_VERIFY: 1 + +general: + artifacts: + - /var/log/upstart/docker.log From dc52e605dc345b09250f4792f1af7b2f2ee7f3bf Mon Sep 17 00:00:00 2001 From: Stephan Classen Date: Sat, 21 Feb 2015 23:32:40 +0100 Subject: [PATCH 319/452] exclude tests which are failing in circle CI --- pom.xml | 1 + .../github/dockerjava/core/command/BuildImageCmdImplTest.java | 2 +- .../dockerjava/core/command/ContainerDiffCmdImplTest.java | 2 +- .../github/dockerjava/core/command/ExecCreateCmdImplTest.java | 2 +- .../github/dockerjava/core/command/ExecStartCmdImplTest.java | 2 +- .../dockerjava/core/command/KillContainerCmdImplTest.java | 2 +- .../github/dockerjava/core/command/ListImagesCmdImplTest.java | 2 +- .../dockerjava/core/command/RemoveContainerCmdImplTest.java | 2 +- .../github/dockerjava/core/command/RemoveImageCmdImplTest.java | 2 +- .../dockerjava/core/command/StopContainerCmdImplTest.java | 2 +- 10 files changed, 10 insertions(+), 9 deletions(-) diff --git a/pom.xml b/pom.xml index 17bdc728..9ce4d6ef 100644 --- a/pom.xml +++ b/pom.xml @@ -386,6 +386,7 @@ integration + ignoreInCircleCi **/*Test.java diff --git a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index 8be2f8f8..f3cefb2f 100644 --- a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -162,7 +162,7 @@ public void testInvalidDockerIgnorePattern() { dockerClient.buildImageCmd(baseDir).withNoCache().exec(); } - @Test + @Test(groups = "ignoreInCircleCi") public void testDockerIgnore() throws DockerException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() diff --git a/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java index 8d6f9254..58c95486 100644 --- a/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ContainerDiffCmdImplTest.java @@ -46,7 +46,7 @@ public void afterMethod(ITestResult result) { super.afterMethod(result); } - @Test + @Test(groups = "ignoreInCircleCi") public void testContainerDiff() throws DockerException { CreateContainerResponse container = dockerClient .createContainerCmd("busybox").withCmd("touch", "/test" ).exec(); diff --git a/src/test/java/com/github/dockerjava/core/command/ExecCreateCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ExecCreateCmdImplTest.java index 338763e6..028f4cac 100644 --- a/src/test/java/com/github/dockerjava/core/command/ExecCreateCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ExecCreateCmdImplTest.java @@ -36,7 +36,7 @@ public void afterMethod(ITestResult result) { super.afterMethod(result); } - @Test + @Test(groups = "ignoreInCircleCi") public void execCreateTest() { String containerName = "generated_" + new SecureRandom().nextInt(); diff --git a/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java index 497c44c1..80619efe 100644 --- a/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java @@ -37,7 +37,7 @@ public void afterMethod(ITestResult result) { super.afterMethod(result); } - @Test + @Test(groups = "ignoreInCircleCi") public void execStartTest() throws Exception { String containerName = "generated_" + new SecureRandom().nextInt(); diff --git a/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java index 419d6e02..33d80ef2 100644 --- a/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/KillContainerCmdImplTest.java @@ -49,7 +49,7 @@ public void afterMethod(ITestResult result) { super.afterMethod(result); } - @Test + @Test(groups = "ignoreInCircleCi") public void killContainer() throws DockerException { CreateContainerResponse container = dockerClient diff --git a/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java index 34a5984d..05bf9483 100644 --- a/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/ListImagesCmdImplTest.java @@ -58,7 +58,7 @@ public void listImages() throws DockerException { assertThat(img.getRepoTags(), not(emptyArray())); } - @Test + @Test(groups = "ignoreInCircleCi") public void listDanglingImages() throws DockerException { String imageId = createDanglingImage(); List images = dockerClient.listImagesCmd() diff --git a/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java index 9c23d70e..b6fe173a 100644 --- a/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RemoveContainerCmdImplTest.java @@ -50,7 +50,7 @@ public void afterMethod(ITestResult result) { super.afterMethod(result); } - @Test + @Test(groups = "ignoreInCircleCi") public void removeContainer() throws DockerException { CreateContainerResponse container = dockerClient diff --git a/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java index a2a190f6..af6bc39c 100644 --- a/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/RemoveImageCmdImplTest.java @@ -51,7 +51,7 @@ public void afterMethod(ITestResult result) { super.afterMethod(result); } - @Test + @Test(groups = "ignoreInCircleCi") public void removeImage() throws DockerException, InterruptedException { CreateContainerResponse container = dockerClient diff --git a/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java index d4681428..3cf643c4 100644 --- a/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StopContainerCmdImplTest.java @@ -49,7 +49,7 @@ public void afterMethod(ITestResult result) { super.afterMethod(result); } - @Test + @Test(groups = "ignoreInCircleCi") public void testStopContainer() throws DockerException { CreateContainerResponse container = dockerClient From abd73f5c7cfa65a733ad7dec434b997a59cf4dba Mon Sep 17 00:00:00 2001 From: Stephan Classen Date: Sat, 21 Feb 2015 23:33:23 +0100 Subject: [PATCH 320/452] do not validate isMemoryLimit() since it is host dependent --- .../java/com/github/dockerjava/core/command/InfoCmdImplTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java index a0a272f2..d1de7076 100644 --- a/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java @@ -68,6 +68,5 @@ public void info() throws DockerException { assertTrue(dockerInfo.getImages() > 0); assertTrue(dockerInfo.getNFd() > 0); assertTrue(dockerInfo.getNGoroutines() > 0); - assertTrue(dockerInfo.isMemoryLimit()); } } From 977a98ff5fbd9899326caa96a84fcfbd69adb25b Mon Sep 17 00:00:00 2001 From: Stephan Classen Date: Sat, 21 Feb 2015 23:34:00 +0100 Subject: [PATCH 321/452] add missing toString() --- .../dockerjava/api/command/InspectContainerResponse.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java index 5ac4f44e..80d52634 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java @@ -153,6 +153,11 @@ public String getMountLabel() { return mountLabel; } + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + @JsonIgnoreProperties(ignoreUnknown = true) public class NetworkSettings { From cc3e6dcc6a97294c05aaec5be705573750f9f7b7 Mon Sep 17 00:00:00 2001 From: Stephan Classen Date: Sun, 22 Feb 2015 00:53:58 +0100 Subject: [PATCH 322/452] add circle.md --- circle.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 circle.md diff --git a/circle.md b/circle.md new file mode 100644 index 00000000..f5cbc0ed --- /dev/null +++ b/circle.md @@ -0,0 +1,51 @@ +# docker-java on circleCI + +The build including tests and integration tests can be automatically run on [circleCI](https://circleci.com/). + +## Setup +1. create an account on circle CI using your github account. +2. select docker-java from the github projects listed in your profile. +3. go to the project settings for docker-java (click on the gear-wheel icon beside the docker-java title). +4. open the *Environemnt variable* page. +5. add the following environment variables: + - DOCKER_EMAIL + - DOCKER_PASSWORD + - DOCKER_USERNAME + +## Ignored Tests +ExecCreateCmdImplTest.execCreateTest + + - Exec is not supported by the lxc driver + +ExecStartCmdImplTest.execStartTest + + - Exec is not supported by the lxc driver + +KillContainerCmdImplTest.killContainer + + - Killed container has ExitCode 0 + +ListImagesCmdImplTest.listDanglingImages + + - caused by [docker#9939](https://github.com/docker/docker/issues/9939) + +RemoveContainerCmdImplTest.removeContainer + + - caused by [docker#9939](https://github.com/docker/docker/issues/9939) + +RemoveImageCmdImplTest.removeImage + + - caused by [docker#9939](https://github.com/docker/docker/issues/9939) + +ContainerDiffCmdImplTest.testContainerDiff + + - too many diffs [{"Kind":0,"Path":"/dev"} ,{"Kind":1,"Path":"/dev/fuse"} ,{"Kind":1,"Path":"/dev/ptmx"} ,{"Kind":1,"Path":"/dev/tty"} ,{"Kind":1,"Path":"/dev/tty1"} ,{"Kind":1,"Path":"/dev/stdout"} ,{"Kind":1,"Path":"/dev/urandom"} ,{"Kind":1,"Path":"/dev/full"} ,{"Kind":1,"Path":"/dev/kmsg"} ,{"Kind":1,"Path":"/dev/null"} ,{"Kind":1,"Path":"/dev/stdin"} ,{"Kind":1,"Path":"/dev/stderr"} ,{"Kind":1,"Path":"/dev/zero"} ,{"Kind":1,"Path":"/dev/fd"} ,{"Kind":1,"Path":"/dev/random"} ,{"Kind":1,"Path":"/test"} ] + +BuildImageCmdImplTest.testDockerIgnore + + - ignore is not working + +StopContainerCmdImplTest.testStopContainer + + - Stopped container has ExitCode 0 + From a4a19fe1b04203717c9c9cffb91e3fdaaf0caa88 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 22 Feb 2015 20:24:33 +0100 Subject: [PATCH 323/452] [maven-release-plugin] prepare release docker-java-1.0.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 17bdc728..d8e43cfa 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 1.0.0-SNAPSHOT + 1.0.0 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-1.0.0 From f73c4933360b515b33f356a129dc5de8615f73f0 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 22 Feb 2015 20:24:38 +0100 Subject: [PATCH 324/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index d8e43cfa..f947cd10 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 1.0.0 + 1.0.1-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-1.0.0 + HEAD From b61918d478e2cb9522131da635eff085b3a2fd4c Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sun, 22 Feb 2015 20:32:02 +0100 Subject: [PATCH 325/452] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a7765b41..782a174c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,7 @@ Change Log === -docker-java-1.0.0-SNAPSHOT +docker-java-1.0.0 --- * [#152](https://github.com/docker-java/docker-java/pull/152) Restore guava as a dependency * [#149](https://github.com/docker-java/docker-java/pull/149) Handle HTTP-Redirects From 63fe62f25843c7481c5638da23dad244f2542a48 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sun, 22 Feb 2015 20:32:42 +0100 Subject: [PATCH 326/452] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 717b1b65..aa171e41 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Run build without integration tests: com.github.docker-java docker-java - 0.10.5 + 1.0.0 ### Latest SNAPSHOT version @@ -69,7 +69,7 @@ You can find the latest SNAPSHOT version including javadoc and source files on [ com.github.docker-java docker-java - 1.0.0-SNAPSHOT + 1.0.1-SNAPSHOT ## Documentation From 238c4dd3d95807c8f47cd93c4329d86c22d4056c Mon Sep 17 00:00:00 2001 From: kalmanb Date: Mon, 23 Feb 2015 17:45:21 +1300 Subject: [PATCH 327/452] Adding volumes that was commented for some reason --- pom.xml | 8 -------- 1 file changed, 8 deletions(-) diff --git a/pom.xml b/pom.xml index 17bdc728..43300cee 100644 --- a/pom.xml +++ b/pom.xml @@ -397,10 +397,6 @@ org.apache.maven.plugins maven-source-plugin - - org.apache.maven.plugins - maven-javadoc-plugin - @@ -426,10 +422,6 @@ org.apache.maven.plugins maven-source-plugin - - org.apache.maven.plugins - maven-javadoc-plugin - From 3a7240ebb9750bd9484e6b7de240fca28f98b80c Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Mon, 23 Feb 2015 20:04:37 +0100 Subject: [PATCH 328/452] Update CHANGELOG.md --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 782a174c..fe196f17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ Change Log === +docker-java-SNAPSHOT +--- + * [#156](https://github.com/docker-java/docker-java/pull/156) Add support for configuring ExtraHosts + docker-java-1.0.0 --- From a4e02ea17f2dd942fc093817ec64fcaadd71d1c2 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Mon, 23 Feb 2015 20:10:44 +0100 Subject: [PATCH 329/452] Update CHANGELOG.md --- CHANGELOG.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe196f17..fc73713c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,11 @@ Change Log === -docker-java-SNAPSHOT +SNAPSHOT --- * [#156](https://github.com/docker-java/docker-java/pull/156) Add support for configuring ExtraHosts -docker-java-1.0.0 +v1.0.0 --- * [#152](https://github.com/docker-java/docker-java/pull/152) Restore guava as a dependency * [#149](https://github.com/docker-java/docker-java/pull/149) Handle HTTP-Redirects @@ -18,7 +18,7 @@ docker-java-1.0.0 * [#131](https://github.com/docker-java/docker-java/pull/128) Utility classes and streamed JSON representations * [#128](https://github.com/docker-java/docker-java/pull/128) Allow unauthorized pullImageCmd -docker-java-0.10.5 +v0.10.5 --- * [#125](https://github.com/docker-java/docker-java/pull/125) Unixsocket support * [#123](https://github.com/docker-java/docker-java/pull/123) support DOCKER_TLS_VERIFY to detect ssl @@ -30,7 +30,7 @@ docker-java-0.10.5 * [#114](https://github.com/docker-java/docker-java/pull/114) Fix CreateContainerCmdImpl.withVolumesFrom() * [#111](https://github.com/docker-java/docker-java/pull/111) Allow to send empty messages in StartContainerCmd -docker-java-0.10.4 +v0.10.4 --- * [#109](https://github.com/docker-java/docker-java/pull/109) Support tag in push image command @@ -45,7 +45,7 @@ docker-java-0.10.4 * [#90](https://github.com/docker-java/docker-java/pull/90) Update DockerClientBuilder.java * [#88](https://github.com/docker-java/docker-java/pull/88) Add support for private repositories and pull/push authentication -docker-java-0.10.3 +v0.10.3 --- * [#87](https://github.com/docker-java/docker-java/pull/87) Improve adding of port bindings @@ -60,7 +60,7 @@ docker-java-0.10.3 * [#73](https://github.com/docker-java/docker-java/pull/73) Improve parsing and serialization of Link * [#70](https://github.com/docker-java/docker-java/pull/70) Improve instantiation and serialization of Bind -docker-java-0.10.2 +v0.10.2 --- * [#69](https://github.com/docker-java/docker-java/pull/69) Use canonical form of Docker folder when building TAR files @@ -74,14 +74,14 @@ docker-java-0.10.2 * [#56](https://github.com/docker-java/docker-java/pull/56) Update README.md * [#58](https://github.com/docker-java/docker-java/pull/58) Code clear and bug fix -docker-java-0.10.1 +v0.10.1 --- * [#49](https://github.com/docker-java/docker-java/pull/49) Allow user to check where volume is binded on host * [#47](https://github.com/docker-java/docker-java/pull/47) let CompressArchiveUtil preserve executable flags * [#46](https://github.com/docker-java/docker-java/pull/46) Fixes to AttachContainerCmd and CreateContainerCmd. -docker-java-0.10.0 +v0.10.0 --- * [#45](https://github.com/docker-java/docker-java/pull/45) Fix Issue #44 Adjusting DNS property type to be a String array as specified by the Doc... @@ -89,7 +89,7 @@ docker-java-0.10.0 * [#37](https://github.com/docker-java/docker-java/pull/37) Starts v0.10.0 * [#35](https://github.com/docker-java/docker-java/pull/35) Exposing the withTTY method for container creation. -docker-java-0.9.1 +v0.9.1 --- * [#31](https://github.com/docker-java/docker-java/pull/31) Change VolumesFrom to handle array @@ -98,13 +98,13 @@ docker-java-0.9.1 * [#19](https://github.com/docker-java/docker-java/pull/19) Add missing options to BuildCmd and set them to match Docker client. * [#16](https://github.com/docker-java/docker-java/pull/16) Build image improvements -docker-java-0.9.0 +v0.9.0 --- * [#14](https://github.com/docker-java/docker-java/pull/14) Use RegEx to match ADD command from Dockerfile. * [#9](https://github.com/docker-java/docker-java/pull/9) Add a build command accepting a tar as a InputStream, so we can build the Dockerfile TAR on the fly without a temporary folder. -docker-java-0.8.2 +v0.8.2 --- * [#2](https://github.com/docker-java/docker-java/pull/2) Move to new maven coordinate com.github.docker-java:docker-java @@ -126,11 +126,11 @@ docker-java-0.8.2 * [#37](https://github.com/docker-java/docker-java/pull/37) Starts v0.10.0 * [#32](https://github.com/docker-java/docker-java/pull/32) -docker-java-0.8.1 +v0.8.1 --- -docker-java-0.8.1 +v0.8.1 --- * [#28](https://github.com/docker-java/docker-java/pull/28) Improves use of docker-java in unit tests From decbe7121188c19be3309b171ce75bb1ff9536f3 Mon Sep 17 00:00:00 2001 From: docker-java-maintain Date: Mon, 23 Feb 2015 20:42:08 +0100 Subject: [PATCH 330/452] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc73713c..29c1ef3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ Change Log === -SNAPSHOT +Latest SNAPSHOT --- * [#156](https://github.com/docker-java/docker-java/pull/156) Add support for configuring ExtraHosts From 9be273fc57a968c166ea7e9db9250acaf8524dca Mon Sep 17 00:00:00 2001 From: docker-java-maintain Date: Mon, 23 Feb 2015 21:24:46 +0100 Subject: [PATCH 331/452] Update circle.md --- circle.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circle.md b/circle.md index f5cbc0ed..d2d671d8 100644 --- a/circle.md +++ b/circle.md @@ -6,7 +6,7 @@ The build including tests and integration tests can be automatically run on [cir 1. create an account on circle CI using your github account. 2. select docker-java from the github projects listed in your profile. 3. go to the project settings for docker-java (click on the gear-wheel icon beside the docker-java title). -4. open the *Environemnt variable* page. +4. open the *Environment variable* page. 5. add the following environment variables: - DOCKER_EMAIL - DOCKER_PASSWORD From 1098c29b0ffc534114b3fb8efbd1634daa4f40c5 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 23 Feb 2015 21:31:39 +0100 Subject: [PATCH 332/452] Fixing imports --- .../github/dockerjava/api/DockerClient.java | 2 +- .../dockerjava/api/command/BuildImageCmd.java | 1 - .../dockerjava/api/command/SaveImageCmd.java | 2 -- .../core/command/BuildImageCmdImpl.java | 25 +++---------------- .../dockerjava/jaxrs/BuildImageCmdExec.java | 5 +--- .../jaxrs/CopyFileFromContainerCmdExec.java | 1 - .../dockerjava/jaxrs/LogContainerCmdExec.java | 1 - .../github/dockerjava/jaxrs/PingCmdExec.java | 1 - .../dockerjava/jaxrs/SaveImageCmdExec.java | 18 ++++--------- .../jaxrs/StartContainerCmdExec.java | 1 - 10 files changed, 10 insertions(+), 47 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index c2b15cf3..d905ef10 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -110,4 +110,4 @@ public CopyFileFromContainerCmd copyFileFromContainerCmd( @Override public void close() throws IOException; -} \ No newline at end of file +} diff --git a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java index 8a1e6211..d9e45b4b 100644 --- a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java @@ -1,7 +1,6 @@ package com.github.dockerjava.api.command; import com.github.dockerjava.api.model.EventStreamItem; -import com.github.dockerjava.api.model.PushEventStreamItem; import java.io.IOException; import java.io.InputStream; diff --git a/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java b/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java index b8a5af4a..8b26c24a 100644 --- a/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java @@ -2,9 +2,7 @@ import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.model.AuthConfig; -import com.github.dockerjava.api.model.PushEventStreamItem; -import java.io.IOException; import java.io.InputStream; public interface SaveImageCmd extends DockerCmd{ diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 32b5b2f9..40f4fcfd 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -1,33 +1,14 @@ package com.github.dockerjava.core.command; +import static com.google.common.base.Preconditions.checkNotNull; + import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.filefilter.TrueFileFilter; - -import com.github.dockerjava.api.DockerClientException; + import com.github.dockerjava.api.command.BuildImageCmd; -import com.github.dockerjava.core.CompressArchiveUtil; -import com.github.dockerjava.core.GoLangFileMatch; -import com.github.dockerjava.core.GoLangFileMatchException; -import com.github.dockerjava.core.GoLangMatchFileFilter; import com.github.dockerjava.core.dockerfile.Dockerfile; -import static com.google.common.base.Preconditions.*; - /** * * Build an image from Dockerfile. diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index ffbd8306..43198046 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -1,7 +1,5 @@ package com.github.dockerjava.jaxrs; - - import static javax.ws.rs.client.Entity.entity; import java.io.IOException; @@ -20,9 +18,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.github.dockerjava.api.command.BuildImageCmd; -import com.github.dockerjava.api.command.PushImageCmd; + import com.github.dockerjava.api.model.EventStreamItem; -import com.github.dockerjava.api.model.PushEventStreamItem; import com.google.common.collect.ImmutableList; diff --git a/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java index 3061df53..5126aaed 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java @@ -6,7 +6,6 @@ import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java index ad1d6185..b279ebdc 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java @@ -3,7 +3,6 @@ import java.io.InputStream; import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java index f8a172a1..65bdc04b 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PingCmdExec.java @@ -1,7 +1,6 @@ package com.github.dockerjava.jaxrs; import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java index 49f50856..d5087d7f 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java @@ -1,22 +1,14 @@ package com.github.dockerjava.jaxrs; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectReader; -import com.github.dockerjava.api.command.PushImageCmd; -import com.github.dockerjava.api.command.SaveImageCmd; -import com.github.dockerjava.api.model.AuthConfig; -import com.github.dockerjava.api.model.PushEventStreamItem; -import com.google.common.collect.ImmutableList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.io.InputStream; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; -import java.io.IOException; -import java.io.InputStream; -import java.util.Iterator; -import static javax.ws.rs.client.Entity.entity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.SaveImageCmd; public class SaveImageCmdExec extends AbstrDockerCmdExec implements SaveImageCmd.Exec { private static final Logger LOGGER = LoggerFactory diff --git a/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java index 66131726..8ca1a42f 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/StartContainerCmdExec.java @@ -4,7 +4,6 @@ import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; From 8462173378da554529af48cc10ac866fcbbd8fce Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 23 Feb 2015 21:35:28 +0100 Subject: [PATCH 333/452] Disable test cleanup exceptions stacktraces --- .../client/AbstractDockerClientTest.java | 9 +-- .../core/TestDockerCmdExecFactory.java | 78 ++++++++++--------- 2 files changed, 43 insertions(+), 44 deletions(-) diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index f5519283..1e61b9a7 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -39,8 +39,7 @@ public abstract class AbstractDockerClientTest extends Assert { protected TestDockerCmdExecFactory dockerCmdExecFactory = new TestDockerCmdExecFactory(DockerClientBuilder.getDefaultDockerCmdExecFactory()); public void beforeTest() { - - + LOG.info("======================= BEFORETEST ======================="); LOG.info("Connecting to Docker server"); dockerClient = DockerClientBuilder.getInstance(config()) @@ -51,8 +50,6 @@ public void beforeTest() { // need to block until image is pulled completely asString(dockerClient.pullImageCmd("busybox").withTag("latest").exec()); - - assertNotNull(dockerClient); LOG.info("======================= END OF BEFORETEST =======================\n\n"); } @@ -90,7 +87,7 @@ public void afterMethod(ITestResult result) { try { dockerClient.removeContainerCmd(container).withForce().exec(); } catch (DockerException ignore) { - ignore.printStackTrace(); + //ignore.printStackTrace(); } } @@ -99,7 +96,7 @@ public void afterMethod(ITestResult result) { try { dockerClient.removeImageCmd(image).withForce().exec(); } catch (DockerException ignore) { - ignore.printStackTrace(); + //ignore.printStackTrace(); } } diff --git a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java index 5e7f2974..1c9342dd 100644 --- a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java +++ b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java @@ -11,24 +11,25 @@ import com.github.dockerjava.jaxrs.BuildImageCmdExec; /** - * Special {@link DockerCmdExecFactory} implementation that collects container and image creations - * while test execution for the purpose of automatically cleanup. + * Special {@link DockerCmdExecFactory} implementation that collects container + * and image creations while test execution for the purpose of automatically + * cleanup. * * @author marcus - * + * */ public class TestDockerCmdExecFactory implements DockerCmdExecFactory { - + private List containerNames = new ArrayList(); - + private List imageNames = new ArrayList(); - + private DockerCmdExecFactory delegate; - + public TestDockerCmdExecFactory(DockerCmdExecFactory delegate) { this.delegate = delegate; } - + @Override public void init(DockerClientConfig dockerClientConfig) { delegate.init(dockerClientConfig); @@ -38,19 +39,20 @@ public void init(DockerClientConfig dockerClientConfig) { public void close() throws IOException { delegate.close(); } - + @Override public CreateContainerCmd.Exec createCreateContainerCmdExec() { return new CreateContainerCmd.Exec() { @Override public CreateContainerResponse exec(CreateContainerCmd command) { - CreateContainerResponse createContainerResponse = delegate.createCreateContainerCmdExec().exec(command); + CreateContainerResponse createContainerResponse = delegate + .createCreateContainerCmdExec().exec(command); containerNames.add(createContainerResponse.getId()); return createContainerResponse; } }; } - + @Override public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { return new RemoveContainerCmd.Exec() { @@ -62,21 +64,20 @@ public Void exec(RemoveContainerCmd command) { } }; } - + @Override public CreateImageCmd.Exec createCreateImageCmdExec() { return new CreateImageCmd.Exec() { @Override public CreateImageResponse exec(CreateImageCmd command) { - CreateImageResponse createImageResponse = delegate.createCreateImageCmdExec().exec(command); + CreateImageResponse createImageResponse = delegate + .createCreateImageCmdExec().exec(command); imageNames.add(createImageResponse.getId()); return createImageResponse; } }; } - - - + @Override public RemoveImageCmd.Exec createRemoveImageCmdExec() { return new RemoveImageCmd.Exec() { @@ -88,25 +89,26 @@ public Void exec(RemoveImageCmd command) { } }; } - + @Override public BuildImageCmd.Exec createBuildImageCmdExec() { return new BuildImageCmd.Exec() { @Override - public BuildImageCmd.Response exec(BuildImageCmd command) { + public BuildImageCmd.Response exec(BuildImageCmd command) { // can't detect image id here so tagging it String tag = command.getTag(); - if(tag == null || "".equals(tag.trim())) { + if (tag == null || "".equals(tag.trim())) { tag = "" + new SecureRandom().nextInt(Integer.MAX_VALUE); command.withTag(tag); } - InputStream inputStream = delegate.createBuildImageCmdExec().exec(command); + InputStream inputStream = delegate.createBuildImageCmdExec() + .exec(command); imageNames.add(tag); return new BuildImageCmdExec.ResponseImpl(inputStream); } - }; + }; } - + @Override public Exec createAuthCmdExec() { return delegate.createAuthCmdExec(); @@ -122,12 +124,12 @@ public PingCmd.Exec createPingCmdExec() { return delegate.createPingCmdExec(); } - @Override - public ExecCreateCmd.Exec createExecCmdExec() { - return delegate.createExecCmdExec(); - } + @Override + public ExecCreateCmd.Exec createExecCmdExec() { + return delegate.createExecCmdExec(); + } - @Override + @Override public VersionCmd.Exec createVersionCmdExec() { return delegate.createVersionCmdExec(); } @@ -141,9 +143,11 @@ public PullImageCmd.Exec createPullImageCmdExec() { public PushImageCmd.Exec createPushImageCmdExec() { return delegate.createPushImageCmdExec(); } - - @Override - public SaveImageCmd.Exec createSaveImageCmdExec() { return delegate.createSaveImageCmdExec(); } + + @Override + public SaveImageCmd.Exec createSaveImageCmdExec() { + return delegate.createSaveImageCmdExec(); + } @Override public SearchImagesCmd.Exec createSearchImagesCmdExec() { @@ -185,12 +189,12 @@ public AttachContainerCmd.Exec createAttachContainerCmdExec() { return delegate.createAttachContainerCmdExec(); } - @Override - public ExecStartCmd.Exec createExecStartCmdExec() { - return delegate.createExecStartCmdExec(); - } + @Override + public ExecStartCmd.Exec createExecStartCmdExec() { + return delegate.createExecStartCmdExec(); + } - @Override + @Override public LogContainerCmd.Exec createLogContainerCmdExec() { return delegate.createLogContainerCmdExec(); } @@ -253,11 +257,9 @@ public EventsCmd.Exec createEventsCmdExec() { public List getContainerNames() { return new ArrayList(containerNames); } - + public List getImageNames() { return new ArrayList(imageNames); } - - } From f0c4acb174ae535fe188d80d55d2030bb6a62240 Mon Sep 17 00:00:00 2001 From: docker-java-maintain Date: Tue, 24 Feb 2015 06:44:00 +0100 Subject: [PATCH 334/452] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index aa171e41..2036bc94 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ [![Build Status](https://travis-ci.org/docker-java/docker-java.svg?branch=master)](https://travis-ci.org/docker-java/docker-java) +[![Circle CI](https://circleci.com/gh/docker-java/docker-java.svg?style=svg)](https://circleci.com/gh/docker-java/docker-java) # docker-java Java API client for [Docker](http://docs.docker.io/ "Docker") From ec8f1f9b0e636b5155035a25ebbd3377dcab0d92 Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Tue, 24 Feb 2015 15:53:56 +0300 Subject: [PATCH 335/452] Added InspectExec command --- .../github/dockerjava/api/DockerClient.java | 2 + .../api/command/DockerCmdExecFactory.java | 2 + .../api/command/InspectContainerResponse.java | 8 ++ .../api/command/InspectExecCmd.java | 16 ++++ .../api/command/InspectExecResponse.java | 93 +++++++++++++++++++ .../dockerjava/core/DockerClientImpl.java | 7 +- .../core/command/InspectExecCmdImpl.java | 41 ++++++++ .../jaxrs/DockerCmdExecFactoryImpl.java | 5 + .../dockerjava/jaxrs/InspectExecCmdExec.java | 24 +++++ .../core/TestDockerCmdExecFactory.java | 7 +- 10 files changed, 203 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/command/InspectExecCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/command/InspectExecResponse.java create mode 100644 src/main/java/com/github/dockerjava/core/command/InspectExecCmdImpl.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/InspectExecCmdExec.java diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index d905ef10..16e70b6c 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -78,6 +78,8 @@ public CreateImageCmd createImageCmd(String repository, public ExecStartCmd execStartCmd(String containerId); + public InspectExecCmd inspectExecCmd(String execId); + public LogContainerCmd logContainerCmd(String containerId); public CopyFileFromContainerCmd copyFileFromContainerCmd( diff --git a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java index ca2bbcae..8b988074 100644 --- a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java +++ b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java @@ -51,6 +51,8 @@ public interface DockerCmdExecFactory extends Closeable { public ExecStartCmd.Exec createExecStartCmdExec(); + public InspectExecCmd.Exec createInspectExecCmdExec(); + public LogContainerCmd.Exec createLogContainerCmdExec(); public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec(); diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java index 80d52634..c86e13c5 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java @@ -1,6 +1,7 @@ package com.github.dockerjava.api.command; +import java.util.List; import java.util.Map; import com.github.dockerjava.api.model.*; @@ -66,6 +67,9 @@ public class InspectContainerResponse { @JsonProperty("ResolvConfPath") private String resolvConfPath; + @JsonProperty("ExecIDs") + private List execIds; + @JsonProperty("State") private ContainerState state; @@ -153,6 +157,10 @@ public String getMountLabel() { return mountLabel; } + public List getExecIds() { + return execIds; + } + @Override public String toString() { return ToStringBuilder.reflectionToString(this); diff --git a/src/main/java/com/github/dockerjava/api/command/InspectExecCmd.java b/src/main/java/com/github/dockerjava/api/command/InspectExecCmd.java new file mode 100644 index 00000000..13882b8f --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/InspectExecCmd.java @@ -0,0 +1,16 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.NotFoundException; + +public interface InspectExecCmd extends DockerCmd { + public String getExecId(); + public InspectExecCmd withExecId(String execId); + + /** + * @throws NotFoundException if no such exec has been found + */ + @Override + public InspectExecResponse exec() throws NotFoundException; + + public static interface Exec extends DockerCmdExec {} +} diff --git a/src/main/java/com/github/dockerjava/api/command/InspectExecResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectExecResponse.java new file mode 100644 index 00000000..2eee14f2 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/InspectExecResponse.java @@ -0,0 +1,93 @@ +package com.github.dockerjava.api.command; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; + +import java.util.List; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class InspectExecResponse { + @JsonProperty("ID") + private String id; + + @JsonProperty("OpenStdin") + private boolean openStdin; + + @JsonProperty("OpenStderr") + private boolean openStderr; + + @JsonProperty("OpenStdout") + private boolean openStdout; + + @JsonProperty("Running") + private boolean running; + + public String getId() { + return id; + } + + public boolean isOpenStdin() { + return openStdin; + } + + public boolean isOpenStderr() { + return openStderr; + } + + public boolean isOpenStdout() { + return openStdout; + } + + public boolean isRunning() { + return running; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public class ProcessConfig { + @JsonProperty("arguments") + private List arguments; + + @JsonProperty("entrypoint") + private String entryPoint; + + @JsonProperty("privileged") + private boolean privileged; + + @JsonProperty("tty") + private boolean tty; + + @JsonProperty("user") + private String user; + + public List getArguments() { + return arguments; + } + + public String getEntryPoint() { + return entryPoint; + } + + public boolean isPrivileged() { + return privileged; + } + + public boolean isTty() { + return tty; + } + + public String getUser() { + return user; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + } +} diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index dd9e566d..8f561dff 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -224,7 +224,12 @@ public ExecStartCmd execStartCmd(String containerId) { return new ExecStartCmdImpl(getDockerCmdExecFactory().createExecStartCmdExec(), containerId); } - @Override + @Override + public InspectExecCmd inspectExecCmd(String execId) { + return new InspectExecCmdImpl(getDockerCmdExecFactory().createInspectExecCmdExec(), execId); + } + + @Override public LogContainerCmd logContainerCmd(String containerId) { return new LogContainerCmdImpl(getDockerCmdExecFactory() .createLogContainerCmdExec(), containerId); diff --git a/src/main/java/com/github/dockerjava/core/command/InspectExecCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/InspectExecCmdImpl.java new file mode 100644 index 00000000..1fd72862 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/InspectExecCmdImpl.java @@ -0,0 +1,41 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.command.DockerCmdExec; +import com.github.dockerjava.api.command.InspectExecCmd; +import com.github.dockerjava.api.command.InspectExecResponse; +import com.google.common.base.Preconditions; + +public class InspectExecCmdImpl extends AbstrDockerCmd implements InspectExecCmd { + private String execId; + + public InspectExecCmdImpl(InspectExecCmd.Exec execution, String execId) { + super(execution); + withExecId(execId); + } + + @Override + public String getExecId() { + return execId; + } + + @Override + public InspectExecCmd withExecId(String execId) { + Preconditions.checkNotNull(execId, "execId was not specified"); + this.execId = execId; + return this; + } + + @Override + public String toString() { + return "inspect " + execId; + } + + /** + * @throws NotFoundException No such exec + */ + @Override + public InspectExecResponse exec() throws NotFoundException { + return super.exec(); + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 9df09ba7..f1f178dc 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -221,6 +221,11 @@ public ExecStartCmd.Exec createExecStartCmdExec() { return new ExecStartCmdExec(getBaseResource()); } + @Override + public InspectExecCmd.Exec createInspectExecCmdExec() { + return new InspectExecCmdExec(getBaseResource()); + } + @Override public LogContainerCmd.Exec createLogContainerCmdExec() { return new LogContainerCmdExec(getBaseResource()); diff --git a/src/main/java/com/github/dockerjava/jaxrs/InspectExecCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/InspectExecCmdExec.java new file mode 100644 index 00000000..b9ee33d6 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/InspectExecCmdExec.java @@ -0,0 +1,24 @@ +package com.github.dockerjava.jaxrs; + +import com.github.dockerjava.api.command.InspectExecCmd; +import com.github.dockerjava.api.command.InspectExecResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +public class InspectExecCmdExec extends AbstrDockerCmdExec implements InspectExecCmd.Exec { + private static final Logger LOGGER = LoggerFactory.getLogger(InspectExecCmdExec.class); + + public InspectExecCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + protected InspectExecResponse execute(InspectExecCmd command) { + WebTarget webResource = getBaseResource().path("/exec/{id}/json").resolveTemplate("id", command.getExecId()); + LOGGER.debug("GET: {}", webResource); + return webResource.request().accept(MediaType.APPLICATION_JSON).get(InspectExecResponse.class); + } +} diff --git a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java index 1c9342dd..869a12fc 100644 --- a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java +++ b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java @@ -194,7 +194,12 @@ public ExecStartCmd.Exec createExecStartCmdExec() { return delegate.createExecStartCmdExec(); } - @Override + @Override + public InspectExecCmd.Exec createInspectExecCmdExec() { + return delegate.createInspectExecCmdExec(); + } + + @Override public LogContainerCmd.Exec createLogContainerCmdExec() { return delegate.createLogContainerCmdExec(); } From bcfcb47c479e691ff358bfbdfc59ea86ad096968 Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Tue, 24 Feb 2015 16:44:11 +0300 Subject: [PATCH 336/452] Added missing ExitCode field --- .../github/dockerjava/api/command/InspectExecResponse.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/com/github/dockerjava/api/command/InspectExecResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectExecResponse.java index 2eee14f2..1532f7d5 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectExecResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectExecResponse.java @@ -23,6 +23,9 @@ public class InspectExecResponse { @JsonProperty("Running") private boolean running; + @JsonProperty("ExitCode") + private int exitCode; + public String getId() { return id; } @@ -43,6 +46,10 @@ public boolean isRunning() { return running; } + public int getExitCode() { + return exitCode; + } + @Override public String toString() { return ToStringBuilder.reflectionToString(this); From 553b39453324ad4a8d85101e520fe2cffd718352 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 24 Feb 2015 20:55:41 +0100 Subject: [PATCH 337/452] Fix issue #158 --- .../com/github/dockerjava/api/model/Info.java | 57 +++++++++++++++++-- .../core/command/InfoCmdImplTest.java | 1 + 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/model/Info.java b/src/main/java/com/github/dockerjava/api/model/Info.java index 7fe6ae79..fb63f2ff 100644 --- a/src/main/java/com/github/dockerjava/api/model/Info.java +++ b/src/main/java/com/github/dockerjava/api/model/Info.java @@ -25,6 +25,9 @@ public class Info { @JsonProperty("Debug") private boolean debug; + + @JsonProperty("DockerRootDir") + private String DockerRootDir; @JsonProperty("Driver") private String driver; @@ -34,9 +37,12 @@ public class Info { @JsonProperty("ExecutionDriver") private String executionDriver; + + @JsonProperty("ID") + private String ID; @JsonProperty("IPv4Forwarding") - private String IPv4Forwarding; + private boolean IPv4Forwarding; @JsonProperty("Images") private int images; @@ -52,9 +58,21 @@ public class Info { @JsonProperty("KernelVersion") private String kernelVersion; + + @JsonProperty("Labels") + private String Labels; @JsonProperty("MemoryLimit") private boolean memoryLimit; + + @JsonProperty("MemTotal") + private long memTotal; + + @JsonProperty("Name") + private String name; + + @JsonProperty("NCPU") + private int NCPU; @JsonProperty("NEventsListener") private long nEventListener; @@ -64,12 +82,15 @@ public class Info { @JsonProperty("NGoroutines") private int NGoroutines; + + @JsonProperty("OperatingSystem") + private String OperatingSystem; @JsonProperty("Sockets") private String[] sockets; @JsonProperty("SwapLimit") - private int swapLimit; + private boolean swapLimit; public boolean isDebug() { return debug; @@ -78,6 +99,10 @@ public boolean isDebug() { public int getContainers() { return containers; } + + public String getDockerRootDir() { + return DockerRootDir; + } public String getDriver() { return driver; @@ -90,8 +115,12 @@ public List getDriverStatuses() { public int getImages() { return images; } + + public String getID() { + return ID; + } - public String getIPv4Forwarding() { + public boolean getIPv4Forwarding() { return IPv4Forwarding; } @@ -110,6 +139,10 @@ public String getInitSha1() { public String getKernelVersion() { return kernelVersion; } + + public String getLabels() { + return Labels; + } public String[] getSockets() { return sockets; @@ -122,6 +155,18 @@ public boolean isMemoryLimit() { public long getnEventListener() { return nEventListener; } + + public long getMemTotal() { + return memTotal; + } + + public String getName() { + return name; + } + + public int getNCPU() { + return NCPU; + } public int getNFd() { return NFd; @@ -130,8 +175,12 @@ public int getNFd() { public int getNGoroutines() { return NGoroutines; } + + public String getOperatingSystem() { + return OperatingSystem; + } - public int getSwapLimit() { + public boolean getSwapLimit() { return swapLimit; } diff --git a/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java index d1de7076..7170c12f 100644 --- a/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/InfoCmdImplTest.java @@ -68,5 +68,6 @@ public void info() throws DockerException { assertTrue(dockerInfo.getImages() > 0); assertTrue(dockerInfo.getNFd() > 0); assertTrue(dockerInfo.getNGoroutines() > 0); + assertTrue(dockerInfo.getNCPU() > 0); } } From 5bed982f2bb31d9e7971bd3123f343288f72653c Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 24 Feb 2015 21:04:31 +0100 Subject: [PATCH 338/452] Fix race condition --- .../dockerjava/core/command/StartContainerCmdImplTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index 22307b07..37d805aa 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -283,7 +283,7 @@ public void startContainerWithLinking() throws DockerException { } CreateContainerResponse container2 = dockerClient - .createContainerCmd("busybox").withCmd("true") + .createContainerCmd("busybox").withCmd("sleep", "9999") .withName("container2").exec(); LOG.info("Created container2 {}", container2.toString()); From 0f018636539da923a9529fb4f373c8ee0dcc058b Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Tue, 24 Feb 2015 21:17:11 +0100 Subject: [PATCH 339/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29c1ef3d..ead9068e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ Change Log === Latest SNAPSHOT --- + * [#159](https://github.com/docker-java/docker-java/pull/159) Add missing Info fields * [#156](https://github.com/docker-java/docker-java/pull/156) Add support for configuring ExtraHosts From 1e2c99acb1123cd358d0bad774d48b14adc9a91a Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Mon, 2 Mar 2015 14:13:28 +0300 Subject: [PATCH 340/452] Added a test for InspectExec command --- .../core/command/InspectExecCmdImplTest.java | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 src/test/java/com/github/dockerjava/core/command/InspectExecCmdImplTest.java diff --git a/src/test/java/com/github/dockerjava/core/command/InspectExecCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/InspectExecCmdImplTest.java new file mode 100644 index 00000000..aacc51f6 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/command/InspectExecCmdImplTest.java @@ -0,0 +1,96 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.ExecCreateCmdResponse; +import com.github.dockerjava.api.command.InspectExecResponse; +import com.github.dockerjava.client.AbstractDockerClientTest; +import org.testng.ITestResult; +import org.testng.annotations.*; + +import java.io.InputStream; +import java.lang.reflect.Method; +import java.security.SecureRandom; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; + +@Test(groups = "integration") +public class InspectExecCmdImplTest 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 inspectExecTest() { + String containerName = "generated_" + new SecureRandom().nextInt(); + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox") + .withCmd("top") + .withName(containerName).exec(); + LOG.info("Created container {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + + dockerClient.startContainerCmd(container.getId()).exec(); + + ExecCreateCmdResponse touchFileCmdCreateResponse = dockerClient.execCreateCmd(container.getId()) + .withAttachStdout() + .withAttachStderr() + .withCmd("touch", "/marker").exec(); + LOG.info("Created exec {}", touchFileCmdCreateResponse.toString()); + assertThat(touchFileCmdCreateResponse.getId(), not(isEmptyString())); + ExecCreateCmdResponse checkFileCmdCreateResponse = dockerClient.execCreateCmd(container.getId()) + .withAttachStdout() + .withAttachStderr() + .withCmd("test", "-e", "/marker").exec(); + LOG.info("Created exec {}", checkFileCmdCreateResponse.toString()); + assertThat(checkFileCmdCreateResponse.getId(), not(isEmptyString())); + + // Check that file does not exist + InputStream response1 = dockerClient.execStartCmd(container.getId()) + .withExecId(checkFileCmdCreateResponse.getId()) + .exec(); + asString(response1); // consume + + InspectExecResponse first = dockerClient.inspectExecCmd(checkFileCmdCreateResponse.getId()).exec(); + assertThat(first.getExitCode(), is(1)); + + // Create the file + InputStream response2 = dockerClient.execStartCmd(container.getId()) + .withExecId(touchFileCmdCreateResponse.getId()) + .exec(); + asString(response2); + + InspectExecResponse second = dockerClient.inspectExecCmd(touchFileCmdCreateResponse.getId()).exec(); + assertThat(second.getExitCode(), is(0)); + + // Check that file does exist now + InputStream response3 = dockerClient.execStartCmd(container.getId()) + .withExecId(checkFileCmdCreateResponse.getId()) + .exec(); + asString(response3); + + InspectExecResponse third = dockerClient.inspectExecCmd(checkFileCmdCreateResponse.getId()).exec(); + assertThat(third.getExitCode(), is(0)); + + } +} From c88167b52d46926523522be25f5626885ba51783 Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Wed, 4 Mar 2015 08:56:21 +0000 Subject: [PATCH 341/452] PushImageCmd assumes that you have an auth config setup for the host that you are pushing to, which is not mandatory. This generates an exception because if fails the precondition of the config not being null. Signed-off-by: Nigel Magnay --- .../com/github/dockerjava/core/DockerClientImpl.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index dd9e566d..5f085490 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -126,8 +126,13 @@ public PullImageCmd pullImageCmd(String repository) { @Override public PushImageCmd pushImageCmd(String name) { - return new PushImageCmdImpl(getDockerCmdExecFactory() - .createPushImageCmdExec(), name).withAuthConfig(dockerClientConfig.effectiveAuthConfig(name)); + PushImageCmd cmd = new PushImageCmdImpl(getDockerCmdExecFactory() + .createPushImageCmdExec(), name); + + AuthConfig cfg = dockerClientConfig.effectiveAuthConfig(name); + if( cfg != null ) + cmd.withAuthConfig(cfg); + return cmd; } @Override From 2b4ca239d7033d20fd1516184f1fe31bdd902d9d Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Fri, 6 Feb 2015 14:30:22 +0000 Subject: [PATCH 342/452] Add some utility classes for splitting up "tag parameters" passed at various points (e.g: 10.0.0.1:8000/mybuild:1234) Signed-off-by: Nigel Magnay --- .../dockerjava/api/model/Identifier.java | 59 +++++++++++++++++++ .../dockerjava/api/model/Repository.java | 46 +++++++++++++++ .../dockerjava/api/model/IdentifierTest.java | 39 ++++++++++++ .../dockerjava/api/model/RepositoryTest.java | 18 ++++++ 4 files changed, 162 insertions(+) create mode 100644 src/main/java/com/github/dockerjava/api/model/Identifier.java create mode 100644 src/main/java/com/github/dockerjava/api/model/Repository.java create mode 100644 src/test/java/com/github/dockerjava/api/model/IdentifierTest.java create mode 100644 src/test/java/com/github/dockerjava/api/model/RepositoryTest.java diff --git a/src/main/java/com/github/dockerjava/api/model/Identifier.java b/src/main/java/com/github/dockerjava/api/model/Identifier.java new file mode 100644 index 00000000..498104e2 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/Identifier.java @@ -0,0 +1,59 @@ +package com.github.dockerjava.api.model; + + +import com.google.common.base.Objects; +import com.google.common.base.Optional; + +/** + * Created by magnayn on 22/07/2014. + */ +public class Identifier { + public final Repository repository; + public final Optional tag; + + public Identifier(Repository repository, String tag) { + this.repository = repository; + + if( tag == null ) + this.tag = Optional.absent(); + else + this.tag = Optional.of(tag); + } + + + /** + * Return an identifier that correctly splits up the repository and tag. + * There can be > 1 ":" + * fred/jim --> fred/jim, [] + * fred/jim:123 --> fred/jim, 123 + * fred:123/jim:123 --> fred:123/jim, 123 + * + * + * @param identifier as a string + * @return parsed identifier. + */ + public static Identifier fromCompoundString(String identifier) { + String[] parts = identifier.split("/"); + if( parts.length != 2 ) { + String[] rhs = identifier.split(":"); + if( rhs.length != 2 ) + return new Identifier( new Repository(identifier), null); + else + return new Identifier( new Repository(rhs[0]), rhs[1]); + } + + String[] rhs = parts[1].split(":"); + if( rhs.length != 2 ) + return new Identifier( new Repository(identifier), null); + + return new Identifier( new Repository(parts[0] + "/" + rhs[0]), rhs[1]); + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("repository", repository) + .add("tag", tag) + .toString(); + } +} diff --git a/src/main/java/com/github/dockerjava/api/model/Repository.java b/src/main/java/com/github/dockerjava/api/model/Repository.java new file mode 100644 index 00000000..673eabee --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/Repository.java @@ -0,0 +1,46 @@ +package com.github.dockerjava.api.model; + +import com.google.common.base.Objects; + +import java.net.MalformedURLException; +import java.net.URL; + +/** + * A repository or image name. + */ +public class Repository { + public final String name; + + /** + * Name may be eg. 'busybox' or '10.0.0.1:5000/fred' + * @param name Repository name + */ + public Repository(String name) { + this.name = name; + } + + /** + * Return the URL portion (repository). + * Note that this might not actually BE a repository location. + * @return + * @throws java.net.MalformedURLException + */ + public URL getURL() throws MalformedURLException { + return new URL("http://" + name); + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("name", name) + .toString(); + } + + + public String getPath() { + if( !name.contains("/") ) + return name; + + return name.substring(name.indexOf("/") + 1 ); + } +} diff --git a/src/test/java/com/github/dockerjava/api/model/IdentifierTest.java b/src/test/java/com/github/dockerjava/api/model/IdentifierTest.java new file mode 100644 index 00000000..d57c0b57 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/IdentifierTest.java @@ -0,0 +1,39 @@ +package com.github.dockerjava.api.model; + +import junit.framework.TestCase; + + +public class IdentifierTest extends TestCase { + + public void testFromCompoundString() throws Exception { + + Identifier i1 = Identifier.fromCompoundString("10.0.0.1/jim"); + Identifier i2 = Identifier.fromCompoundString("10.0.0.1/jim:123"); + Identifier i3 = Identifier.fromCompoundString("10.0.0.1:123/jim:124"); + Identifier i3A = Identifier.fromCompoundString("10.0.0.1:123/jim:latest"); + + assertTrue(!i1.tag.isPresent()); + assertEquals(i1.repository.name, "10.0.0.1/jim"); + + assertTrue(i2.tag.isPresent()); + assertEquals(i2.tag.get(), "123"); + assertEquals(i2.repository.name, "10.0.0.1/jim"); + + assertTrue(i3.tag.isPresent()); + assertEquals(i3.tag.get(), "124"); + assertEquals(i3.repository.name, "10.0.0.1:123/jim"); + assertEquals(i3.repository.getURL().getPort(), 123); + assertEquals(i3A.tag.get(), "latest"); + + + Identifier i4 = Identifier.fromCompoundString("centos:latest"); + assertTrue(i4.tag.isPresent()); + assertEquals(i4.tag.get(), "latest"); + + Identifier i5 = Identifier.fromCompoundString("busybox"); + assertTrue(!i5.tag.isPresent()); + + Identifier i6 = Identifier.fromCompoundString("10.0.0.1:5000/my-test-image:1234"); + assertEquals(i6.repository.getPath(), "my-test-image"); + } +} \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/api/model/RepositoryTest.java b/src/test/java/com/github/dockerjava/api/model/RepositoryTest.java new file mode 100644 index 00000000..8a40de28 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/model/RepositoryTest.java @@ -0,0 +1,18 @@ +package com.github.dockerjava.api.model; + +import junit.framework.TestCase; + +public class RepositoryTest extends TestCase { + public void testRepository() throws Exception { + + Repository repo = new Repository("10.0.0.1/jim"); + Repository repo1 = new Repository("10.0.0.1:1234/jim"); + Repository repo2 = new Repository("busybox"); + + assertEquals("jim", repo.getPath()); + assertEquals("jim", repo1.getPath()); + assertEquals("busybox", repo2.getPath()); + + assertEquals(1234, repo1.getURL().getPort()); + } +} \ No newline at end of file From 81b30b2625b87b7cd46ed8a78b47bcf11fba24a9 Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Mon, 23 Feb 2015 16:55:46 +0000 Subject: [PATCH 343/452] Convenience function for pushing by full tag. Signed-off-by: Nigel Magnay --- .../github/dockerjava/api/DockerClient.java | 3 +++ .../dockerjava/core/DockerClientImpl.java | 18 ++++++++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index d905ef10..1a3a285f 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -4,6 +4,7 @@ import com.github.dockerjava.api.command.*; import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.Identifier; // https://godoc.org/github.com/fsouza/go-dockerclient public interface DockerClient extends Closeable { @@ -29,6 +30,8 @@ public interface DockerClient extends Closeable { public PushImageCmd pushImageCmd(String name); + public PushImageCmd pushImageCmd(Identifier identifier); + public CreateImageCmd createImageCmd(String repository, InputStream imageStream); diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index dd9e566d..06009d87 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -10,6 +10,7 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.*; import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.Identifier; import com.github.dockerjava.core.command.*; /** @@ -129,8 +130,21 @@ public PushImageCmd pushImageCmd(String name) { return new PushImageCmdImpl(getDockerCmdExecFactory() .createPushImageCmdExec(), name).withAuthConfig(dockerClientConfig.effectiveAuthConfig(name)); } - - @Override + + @Override + public PushImageCmd pushImageCmd(Identifier identifier) { + PushImageCmd cmd = pushImageCmd(identifier.repository.name); + if( identifier.tag.isPresent() ) + cmd.withTag(identifier.tag.get()); + + AuthConfig cfg = dockerClientConfig.effectiveAuthConfig(identifier.repository.name); + if( cfg != null ) + cmd.withAuthConfig(cfg); + + return cmd; + } + + @Override public SaveImageCmd saveImageCmd(String name) { return new SaveImageCmdImpl(getDockerCmdExecFactory() .createSaveImageCmdExec(), name).withAuthConfig(dockerClientConfig.effectiveAuthConfig(name)); From c2b14dc5947d6a89461ef12076efc64f9220a7e1 Mon Sep 17 00:00:00 2001 From: Ales Justin Date: Fri, 6 Mar 2015 15:27:03 +0100 Subject: [PATCH 344/452] Close in finally. --- .../com/github/dockerjava/jaxrs/BuildImageCmdExec.java | 8 +++++--- .../com/github/dockerjava/jaxrs/PushImageCmdExec.java | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index 43198046..b34926c6 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -79,9 +79,11 @@ public Iterable getItems() throws IOException { // and then do other configuration, if any, and read: Iterator items = reader.readValues(proxy); - proxy.close(); - - return ImmutableList.copyOf(items); + try { + return ImmutableList.copyOf(items); + } finally { + proxy.close(); + } } @Override diff --git a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java index 4d7be3f0..e0120c2f 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java @@ -74,9 +74,11 @@ public Iterable getItems() throws IOException { // and then do other configuration, if any, and read: Iterator items = reader.readValues(proxy); - proxy.close(); - - return ImmutableList.copyOf(items); + try { + return ImmutableList.copyOf(items); + } finally { + proxy.close(); + } } @Override From 037c2f3b6fd6374f932343a016c4defd79d073cc Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 6 Mar 2015 20:19:03 +0100 Subject: [PATCH 345/452] Ignore test in circle CI --- .../github/dockerjava/core/command/InspectExecCmdImplTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/github/dockerjava/core/command/InspectExecCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/InspectExecCmdImplTest.java index aacc51f6..2deddca0 100644 --- a/src/test/java/com/github/dockerjava/core/command/InspectExecCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/InspectExecCmdImplTest.java @@ -5,6 +5,7 @@ import com.github.dockerjava.api.command.ExecCreateCmdResponse; import com.github.dockerjava.api.command.InspectExecResponse; import com.github.dockerjava.client.AbstractDockerClientTest; + import org.testng.ITestResult; import org.testng.annotations.*; @@ -39,7 +40,7 @@ public void afterMethod(ITestResult result) { super.afterMethod(result); } - @Test + @Test(groups = "ignoreInCircleCi") public void inspectExecTest() { String containerName = "generated_" + new SecureRandom().nextInt(); From cb3ee13d661ef283538a01c9132c9f54c3c1929b Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Fri, 6 Mar 2015 20:21:09 +0100 Subject: [PATCH 346/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ead9068e..4961c320 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ Change Log === Latest SNAPSHOT --- + * [#161](https://github.com/docker-java/docker-java/pull/161) Inspect exec command * [#159](https://github.com/docker-java/docker-java/pull/159) Add missing Info fields * [#156](https://github.com/docker-java/docker-java/pull/156) Add support for configuring ExtraHosts From 78226ccd88dd6310ea3d1a2ed6b13dae9468aa6c Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Fri, 6 Mar 2015 20:57:03 +0100 Subject: [PATCH 347/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4961c320..f068a5f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ Change Log === Latest SNAPSHOT --- + * [#165](https://github.com/docker-java/docker-java/pull/165) PushImageCmd assumes that you have an auth config setup * [#161](https://github.com/docker-java/docker-java/pull/161) Inspect exec command * [#159](https://github.com/docker-java/docker-java/pull/159) Add missing Info fields * [#156](https://github.com/docker-java/docker-java/pull/156) Add support for configuring ExtraHosts From b8034385ec062976750e05bcb56c9d39aabef2fd Mon Sep 17 00:00:00 2001 From: efj Date: Wed, 4 Mar 2015 17:47:20 +0100 Subject: [PATCH 348/452] Implemented AuthConfigurations for the Build command. Required when creating an image with a FROM command, using a private registry. --- .../dockerjava/api/command/BuildImageCmd.java | 10 +++++++-- .../api/model/AuthConfigurations.java | 21 +++++++++++++++++++ .../dockerjava/api/model/EventStreamItem.java | 4 +++- .../api/model/PushEventStreamItem.java | 4 +++- .../core/command/BuildImageCmdImpl.java | 14 +++++++++++++ .../dockerjava/jaxrs/AbstrDockerCmdExec.java | 10 +++++++++ .../dockerjava/jaxrs/BuildImageCmdExec.java | 16 ++++++++++---- 7 files changed, 71 insertions(+), 8 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/AuthConfigurations.java diff --git a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java index d9e45b4b..62d8abed 100644 --- a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java @@ -1,10 +1,11 @@ package com.github.dockerjava.api.command; -import com.github.dockerjava.api.model.EventStreamItem; - import java.io.IOException; import java.io.InputStream; +import com.github.dockerjava.api.model.AuthConfigurations; +import com.github.dockerjava.api.model.EventStreamItem; + /** * * Build an image from Dockerfile. @@ -26,6 +27,8 @@ public interface BuildImageCmd extends DockerCmd{ public boolean isQuiet(); + public AuthConfigurations getBuildAuthConfigs(); + public BuildImageCmd withTarInputStream(InputStream tarInputStream); public BuildImageCmd withNoCache(); @@ -40,10 +43,13 @@ public interface BuildImageCmd extends DockerCmd{ public BuildImageCmd withQuiet(boolean quiet); + public BuildImageCmd withBuildAuthConfigs(AuthConfigurations authConfig); + public static interface Exec extends DockerCmdExec { } public static abstract class Response extends InputStream { public abstract Iterable getItems() throws IOException; } + } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/model/AuthConfigurations.java b/src/main/java/com/github/dockerjava/api/model/AuthConfigurations.java new file mode 100644 index 00000000..5a62c758 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/AuthConfigurations.java @@ -0,0 +1,21 @@ +package com.github.dockerjava.api.model; + +import java.util.Map; +import java.util.TreeMap; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class AuthConfigurations { + + @JsonProperty("configs") + private Map configs = new TreeMap<>(); + + public void addConfig(AuthConfig authConfig){ + configs.put(authConfig.getServerAddress(), authConfig); + } + + public Map getConfigs(){ + return this.configs; + } + +} diff --git a/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java b/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java index 5dd9d65c..010ed9af 100644 --- a/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java +++ b/src/main/java/com/github/dockerjava/api/model/EventStreamItem.java @@ -15,7 +15,9 @@ @JsonIgnoreProperties(ignoreUnknown=true) public class EventStreamItem implements Serializable { - @JsonProperty("stream") + private static final long serialVersionUID = 638778515773898651L; + + @JsonProperty("stream") private String stream; // {"error":"Error...", "errorDetail":{"code": 123, "message": "Error..."}} diff --git a/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java b/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java index 7230a7ce..c8aac4c9 100644 --- a/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java +++ b/src/main/java/com/github/dockerjava/api/model/PushEventStreamItem.java @@ -13,7 +13,9 @@ @JsonIgnoreProperties(ignoreUnknown=true) public class PushEventStreamItem implements Serializable { - @JsonProperty("status") + private static final long serialVersionUID = -5187169652557467828L; + + @JsonProperty("status") private String status; @JsonProperty("progress") diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 40f4fcfd..9f57bd74 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -7,6 +7,7 @@ import java.io.InputStream; import com.github.dockerjava.api.command.BuildImageCmd; +import com.github.dockerjava.api.model.AuthConfigurations; import com.github.dockerjava.core.dockerfile.Dockerfile; /** @@ -22,6 +23,7 @@ public class BuildImageCmdImpl extends AbstrDockerCmd, RES_T> implements DockerCmdExec { @@ -38,6 +39,15 @@ protected String registryAuth(AuthConfig authConfig) { throw new RuntimeException(e); } } + + protected String registryConfigs(AuthConfigurations authConfigs) { + try { + return Base64.encodeBase64String(new ObjectMapper() + .writeValueAsString(authConfigs).getBytes()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } @Override public RES_T exec(CMD_T command) { diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index b34926c6..405192ad 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -6,6 +6,7 @@ import java.io.InputStream; import java.util.Iterator; +import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -18,9 +19,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.github.dockerjava.api.command.BuildImageCmd; - +import com.github.dockerjava.api.model.AuthConfigurations; import com.github.dockerjava.api.model.EventStreamItem; - import com.google.common.collect.ImmutableList; public class BuildImageCmdExec extends AbstrDockerCmdExec implements BuildImageCmd.Exec { @@ -55,14 +55,22 @@ protected ResponseImpl execute(BuildImageCmd command) { LOGGER.debug("POST: {}", webResource); - InputStream is = webResource - .request() + InputStream is = resourceWithOptionalAuthConfig(command, webResource.request()) .accept(MediaType.TEXT_PLAIN) .post(entity(command.getTarInputStream(), "application/tar"), Response.class).readEntity(InputStream.class); return new ResponseImpl(is); } + + private Invocation.Builder resourceWithOptionalAuthConfig(BuildImageCmd command, Invocation.Builder request) { + AuthConfigurations authConfigs = command.getBuildAuthConfigs(); + if (authConfigs != null) { + request = request.header("X-Registry-Config", registryConfigs(authConfigs)); + } + return request; + } + public static class ResponseImpl extends BuildImageCmd.Response { private final InputStream proxy; From 0fd5a8d8556c52e4fc36eb486ffcab00d757172a Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Fri, 6 Mar 2015 22:12:34 +0100 Subject: [PATCH 349/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f068a5f6..9abc7be8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Latest SNAPSHOT * [#161](https://github.com/docker-java/docker-java/pull/161) Inspect exec command * [#159](https://github.com/docker-java/docker-java/pull/159) Add missing Info fields * [#156](https://github.com/docker-java/docker-java/pull/156) Add support for configuring ExtraHosts + * [#146](https://github.com/docker-java/docker-java/pull/146) Create Identifier type v1.0.0 From c42720a1e479248b9c46527f2475e187b569b9e1 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Fri, 6 Mar 2015 22:48:33 +0100 Subject: [PATCH 350/452] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2036bc94..ab181a53 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ For code examples, please look at the [Wiki](https://github.com/docker-java/dock There are a couple of configuration items, all of which have sensible defaults: -* `url` The Docker URL, e.g. `https://localhost:2376`. +* `url` The Docker URL, e.g. `https://localhost:2376` or `unix:///var/run/docker.sock` * `version` The API version, e.g. `1.16`. * `username` Your registry username (required to push containers). * `password` Your registry password. From 920c9009c3cb42b80286018bad06d443a9e92d95 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Fri, 6 Mar 2015 22:56:51 +0100 Subject: [PATCH 351/452] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ab181a53..830ce6b0 100644 --- a/README.md +++ b/README.md @@ -31,11 +31,13 @@ If you do not have access to a Docker server or just want to execute the build q $ mvn clean install -DskipITs By default Docker server is using UNIX sockets for communication with the Docker client, however docker-java -client uses TCP/IP to connect to the Docker server, so you will need to make sure that your Docker server is +client uses TCP/IP to connect to the Docker server by default, so you will need to make sure that your Docker server is listening on TCP port. To allow Docker server to use TCP add the following line to /etc/default/docker DOCKER_OPTS="-H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock" +However you can force docker-java to use UNIX socket communication by configure the following url: ```unix:///var/run/docker.sock``` + More details setting up Docker server can be found in official documentation: http://docs.docker.io/en/latest/use/basics/ Now make sure that docker is up: From f38e9350cad4c627645b0a9d45cd4afc747db77c Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Fri, 6 Mar 2015 22:57:38 +0100 Subject: [PATCH 352/452] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 830ce6b0..b7e9c621 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,9 @@ listening on TCP port. To allow Docker server to use TCP add the following line DOCKER_OPTS="-H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock" -However you can force docker-java to use UNIX socket communication by configure the following url: ```unix:///var/run/docker.sock``` +However you can force docker-java to use UNIX socket communication by configure the following url: + + unix:///var/run/docker.sock More details setting up Docker server can be found in official documentation: http://docs.docker.io/en/latest/use/basics/ From 73602ad9ca862dd2350f242de25a5a2257073792 Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Mon, 9 Mar 2015 13:33:58 +0000 Subject: [PATCH 353/452] Since docker 1.5.0, it has been allowable to specify files other than 'Dockerfile' for building images. Alter the BuildImageCmd so that you can either specify the directory (which assumes Dockerfile, for backwards compat) or the actual file you wish to use. Signed-off-by: Nigel Magnay --- .../dockerjava/api/command/BuildImageCmd.java | 5 ++- .../dockerjava/core/DockerClientImpl.java | 4 +- .../core/command/BuildImageCmdImpl.java | 39 +++++++++++++------ 3 files changed, 34 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java index 62d8abed..becaeccc 100644 --- a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java @@ -1,5 +1,6 @@ package com.github.dockerjava.api.command; +import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -26,9 +27,11 @@ public interface BuildImageCmd extends DockerCmd{ public boolean hasRemoveEnabled(); public boolean isQuiet(); - + public AuthConfigurations getBuildAuthConfigs(); + public BuildImageCmd withDockerfile(File dockerfile); + public BuildImageCmd withTarInputStream(InputStream tarInputStream); public BuildImageCmd withNoCache(); diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 4adf5079..0dd560af 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -292,9 +292,9 @@ public CommitCmd commitCmd(String containerId) { } @Override - public BuildImageCmd buildImageCmd(File dockerFolder) { + public BuildImageCmd buildImageCmd(File dockerFileOrFolder) { return new BuildImageCmdImpl(getDockerCmdExecFactory() - .createBuildImageCmdExec(), dockerFolder); + .createBuildImageCmdExec(), dockerFileOrFolder); } @Override diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 9f57bd74..c793ed6e 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -25,19 +25,18 @@ public class BuildImageCmdImpl extends AbstrDockerCmd Date: Mon, 16 Mar 2015 22:37:45 +0100 Subject: [PATCH 354/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9abc7be8..f8841d76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ Change Log === Latest SNAPSHOT --- + * [#170](https://github.com/docker-java/docker-java/pull/170) Allow to specify alternative files other than 'Dockerfile' for building images * [#165](https://github.com/docker-java/docker-java/pull/165) PushImageCmd assumes that you have an auth config setup * [#161](https://github.com/docker-java/docker-java/pull/161) Inspect exec command * [#159](https://github.com/docker-java/docker-java/pull/159) Add missing Info fields From 6a890723d26a6c65303a2c3c7432360a1cde6788 Mon Sep 17 00:00:00 2001 From: Xavier Fournet Date: Thu, 19 Mar 2015 11:25:56 +0100 Subject: [PATCH 355/452] SaveImageCmd assumes that you have an auth config setup --- .../com/github/dockerjava/core/DockerClientImpl.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 0dd560af..d83c26d2 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -151,9 +151,13 @@ public PushImageCmd pushImageCmd(Identifier identifier) { @Override public SaveImageCmd saveImageCmd(String name) { - return new SaveImageCmdImpl(getDockerCmdExecFactory() - .createSaveImageCmdExec(), name).withAuthConfig(dockerClientConfig.effectiveAuthConfig(name)); - + SaveImageCmdImpl cmd = new SaveImageCmdImpl(getDockerCmdExecFactory().createSaveImageCmdExec(), name); + + AuthConfig cfg = dockerClientConfig.effectiveAuthConfig(name); + if (cfg != null) + cmd.withAuthConfig(cfg); + + return cmd; } @Override From fc3f7b750ea91d5259883b35a051b25d78324c08 Mon Sep 17 00:00:00 2001 From: Xavier Fournet Date: Thu, 19 Mar 2015 11:47:11 +0100 Subject: [PATCH 356/452] SaveImageCmd API doesn't support X-Registry-Auth header --- .../com/github/dockerjava/api/command/SaveImageCmd.java | 7 +------ .../java/com/github/dockerjava/core/DockerClientImpl.java | 8 +------- .../github/dockerjava/core/command/SaveImageCmdImpl.java | 2 +- .../com/github/dockerjava/jaxrs/SaveImageCmdExec.java | 2 -- 4 files changed, 3 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java b/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java index 8b26c24a..957ae05c 100644 --- a/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java @@ -1,7 +1,6 @@ package com.github.dockerjava.api.command; import com.github.dockerjava.api.NotFoundException; -import com.github.dockerjava.api.model.AuthConfig; import java.io.InputStream; @@ -21,10 +20,6 @@ public interface SaveImageCmd extends DockerCmd{ */ public SaveImageCmd withTag(String tag); - public AuthConfig getAuthConfig(); - - public SaveImageCmd withAuthConfig(AuthConfig authConfig); - /** * @throws com.github.dockerjava.api.NotFoundException No such image */ @@ -34,4 +29,4 @@ public static interface Exec extends DockerCmdExec { } -} \ No newline at end of file +} diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index d83c26d2..3ee08823 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -151,13 +151,7 @@ public PushImageCmd pushImageCmd(Identifier identifier) { @Override public SaveImageCmd saveImageCmd(String name) { - SaveImageCmdImpl cmd = new SaveImageCmdImpl(getDockerCmdExecFactory().createSaveImageCmdExec(), name); - - AuthConfig cfg = dockerClientConfig.effectiveAuthConfig(name); - if (cfg != null) - cmd.withAuthConfig(cfg); - - return cmd; + return new SaveImageCmdImpl(getDockerCmdExecFactory().createSaveImageCmdExec(), name); } @Override diff --git a/src/main/java/com/github/dockerjava/core/command/SaveImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/SaveImageCmdImpl.java index 6a4596c7..30bb13b2 100644 --- a/src/main/java/com/github/dockerjava/core/command/SaveImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/SaveImageCmdImpl.java @@ -7,7 +7,7 @@ import static com.google.common.base.Preconditions.checkNotNull; -public class SaveImageCmdImpl extends AbstrAuthCfgDockerCmd implements SaveImageCmd { +public class SaveImageCmdImpl extends AbstrDockerCmd implements SaveImageCmd { private String name; private String tag; diff --git a/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java index d5087d7f..e9918d2a 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java @@ -23,11 +23,9 @@ protected InputStream execute(SaveImageCmd command) { WebTarget webResource = getBaseResource().path("/images/" + command.getName() + "/get") .queryParam("tag", command.getTag()); - final String registryAuth = registryAuth(command.getAuthConfig()); LOGGER.trace("GET: {}", webResource); InputStream is = webResource .request() - .header("X-Registry-Auth", registryAuth) .accept(MediaType.APPLICATION_JSON) .get().readEntity(InputStream.class); From 749a9af324ef90cd27d12c70486a8a1156569332 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 20 Mar 2015 21:46:02 +0100 Subject: [PATCH 357/452] Fix pull image test to work with 1.17 --- .../dockerjava/core/command/PullImageCmdImplTest.java | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java index 861c1078..f9968a44 100644 --- a/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/PullImageCmdImplTest.java @@ -109,16 +109,9 @@ public void testPullImage() throws DockerException, IOException { public void testPullNonExistingImage() throws DockerException, IOException { // does not throw an exception - InputStream is = dockerClient.pullImageCmd("nonexisting/foo").exec(); + InputStream is = dockerClient.pullImageCmd("xvxcv/foo").exec(); // stream needs to be fully read in order to close the underlying connection - this.asString(is); - - try { - dockerClient.pullImageCmd("non-existing/foo").exec(); - fail("expected InternalServerErrorException"); - } catch (InternalServerErrorException ignored) { - } - + asString(is); } } From d57bed76f52d4feb69880bcbc6d26e09844bf292 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 20 Mar 2015 21:48:24 +0100 Subject: [PATCH 358/452] Fix issue # 171 with nested ENV variables in Dockerfile --- .../core/dockerfile/DockerfileStatement.java | 4 ++-- .../dockerjava/core/command/BuildImageCmdImplTest.java | 9 +++++++++ src/test/resources/testEnv/Dockerfile | 10 ++++++++++ src/test/resources/testEnv/subFolder/testrun.sh | 3 +++ 4 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 src/test/resources/testEnv/Dockerfile create mode 100755 src/test/resources/testEnv/subFolder/testrun.sh diff --git a/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java b/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java index fd22e098..a1bcc271 100644 --- a/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java +++ b/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java @@ -38,11 +38,11 @@ protected String filterForEnvironmentVars(Map environmentMap, // handle: $VARIABLE case currentResourceContent = currentResourceContent.replaceAll( - "\\$" + variable, replacementValue); + "\\$" + variable, Matcher.quoteReplacement(replacementValue)); // handle ${VARIABLE} case currentResourceContent = currentResourceContent.replaceAll( - "\\$\\{" + variable + "\\}", replacementValue); + "\\$\\{" + variable + "\\}", Matcher.quoteReplacement(replacementValue)); } diff --git a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index f3cefb2f..4c69d86e 100644 --- a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -111,6 +111,15 @@ public void testDockerBuilderAddFolder() throws DockerException, String response = dockerfileBuild(baseDir); assertThat(response, containsString("Successfully executed testAddFolder.sh")); } + + @Test + public void testDockerBuilderEnv() throws DockerException, + IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("testEnv").getFile()); + String response = dockerfileBuild(baseDir); + assertThat(response, containsString("Successfully executed testrun.sh")); + } private String dockerfileBuild(File baseDir) { diff --git a/src/test/resources/testEnv/Dockerfile b/src/test/resources/testEnv/Dockerfile new file mode 100644 index 00000000..a0a08463 --- /dev/null +++ b/src/test/resources/testEnv/Dockerfile @@ -0,0 +1,10 @@ +FROM ubuntu:latest + +ENV varA ./subFolder +ENV varB $varA/testrun.sh + +ADD $varB /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/testEnv/subFolder/testrun.sh b/src/test/resources/testEnv/subFolder/testrun.sh new file mode 100755 index 00000000..14259aa7 --- /dev/null +++ b/src/test/resources/testEnv/subFolder/testrun.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Successfully executed testrun.sh" \ No newline at end of file From 408a320adefea160881dbf5036eaab09aa21a4f9 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 20 Mar 2015 23:49:56 +0100 Subject: [PATCH 359/452] Fix issue #176 --- .../dockerjava/core/DockerClientConfig.java | 4 +- .../jaxrs/DockerCmdExecFactoryImpl.java | 543 +++++++++--------- 2 files changed, 286 insertions(+), 261 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index aa5f99b0..05491ec6 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -459,7 +459,9 @@ public final DockerClientConfigBuilder withFollowRedirectsFilter(boolean followR } public final DockerClientConfigBuilder withDockerCertPath(String dockerCertPath) { - this.sslConfig = new LocalDirectorySSLConfig(dockerCertPath); + if(dockerCertPath != null) { + this.sslConfig = new LocalDirectorySSLConfig(dockerCertPath); + } return this; } diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index f1f178dc..bc3afeca 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -36,265 +36,288 @@ public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { - private static final Logger LOGGER = LoggerFactory.getLogger(DockerCmdExecFactoryImpl.class.getName()); - private Client client; - private WebTarget baseResource; - - @Override - public void init(DockerClientConfig dockerClientConfig) { - checkNotNull(dockerClientConfig, "config was not specified"); - - ClientConfig clientConfig = new ClientConfig(); - clientConfig.connectorProvider(new ApacheConnectorProvider()); - clientConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); - - clientConfig.register(ResponseStatusExceptionFilter.class); - clientConfig.register(JsonClientFilter.class); - clientConfig.register(JacksonJsonProvider.class); - - if (dockerClientConfig.followRedirectsFilterEnabled()) { - clientConfig.register(FollowRedirectsFilter.class); - } - - if (dockerClientConfig.isLoggingFilterEnabled()) { - clientConfig.register(new SelectiveLoggingFilter(LOGGER, true)); - } - - if (dockerClientConfig.getReadTimeout() != null) { - int readTimeout = dockerClientConfig.getReadTimeout(); - clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); - } - - URI originalUri = dockerClientConfig.getUri(); - - SSLContext sslContext; - try { - sslContext = dockerClientConfig.getSslConfig().getSSLContext(); - } catch(Exception ex) { - throw new DockerClientException("Error in SSL Configuration", ex); - } - - PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(getSchemeRegistry(originalUri, sslContext)); - - if(dockerClientConfig.getMaxTotalConnections() != null) - connManager.setMaxTotal(dockerClientConfig.getMaxTotalConnections()); - if(dockerClientConfig.getMaxPerRoutConnections() != null) - connManager.setDefaultMaxPerRoute(dockerClientConfig.getMaxPerRoutConnections()); - - clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connManager); - - ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig); - - if (sslContext != null) { - clientBuilder.sslContext(sslContext); - } - - client = clientBuilder.build(); - - if (originalUri.getScheme().equals("unix")) { - dockerClientConfig.setUri(UnixConnectionSocketFactory.sanitizeUri(originalUri)); - } - WebTarget webResource = client.target(dockerClientConfig.getUri()); - - if (dockerClientConfig.getVersion() == null || dockerClientConfig.getVersion().isEmpty()) { - baseResource = webResource; - } else { - baseResource = webResource.path("v" + dockerClientConfig.getVersion()); - } - } - - private org.apache.http.config.Registry getSchemeRegistry(final URI originalUri, SSLContext sslContext) { - RegistryBuilder registryBuilder = RegistryBuilder.create(); - registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory()); - if (sslContext != null) { - registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext)); - } - registryBuilder.register("unix", new UnixConnectionSocketFactory(originalUri)); - return registryBuilder.build(); - } - - protected WebTarget getBaseResource() { - checkNotNull(baseResource, "Factory not initialized. You probably forgot to call init()!"); - return baseResource; - } - - @Override - public AuthCmd.Exec createAuthCmdExec() { - return new AuthCmdExec(getBaseResource()); - } - - @Override - public InfoCmd.Exec createInfoCmdExec() { - return new InfoCmdExec(getBaseResource()); - } - - @Override - public PingCmd.Exec createPingCmdExec() { - return new PingCmdExec(getBaseResource()); - } - - @Override - public VersionCmd.Exec createVersionCmdExec() { - return new VersionCmdExec(getBaseResource()); - } - - @Override - public PullImageCmd.Exec createPullImageCmdExec() { - return new PullImageCmdExec(getBaseResource()); - } - - @Override - public PushImageCmd.Exec createPushImageCmdExec() { - return new PushImageCmdExec(getBaseResource()); - } - - @Override - public SaveImageCmd.Exec createSaveImageCmdExec() { return new SaveImageCmdExec(getBaseResource()); } - - @Override - public CreateImageCmd.Exec createCreateImageCmdExec() { - return new CreateImageCmdExec(getBaseResource()); - } - - @Override - public SearchImagesCmd.Exec createSearchImagesCmdExec() { - return new SearchImagesCmdExec(getBaseResource()); - } - - @Override - public RemoveImageCmd.Exec createRemoveImageCmdExec() { - return new RemoveImageCmdExec(getBaseResource()); - } - - @Override - public ListImagesCmd.Exec createListImagesCmdExec() { - return new ListImagesCmdExec(getBaseResource()); - } - - @Override - public InspectImageCmd.Exec createInspectImageCmdExec() { - return new InspectImageCmdExec(getBaseResource()); - } - - @Override - public ListContainersCmd.Exec createListContainersCmdExec() { - return new ListContainersCmdExec(getBaseResource()); - } - - @Override - public CreateContainerCmd.Exec createCreateContainerCmdExec() { - return new CreateContainerCmdExec(getBaseResource()); - } - - @Override - public StartContainerCmd.Exec createStartContainerCmdExec() { - return new StartContainerCmdExec(getBaseResource()); - } - - @Override - public InspectContainerCmd.Exec createInspectContainerCmdExec() { - return new InspectContainerCmdExec(getBaseResource()); - } - - @Override - public ExecCreateCmd.Exec createExecCmdExec() { - return new ExecCreateCmdExec(getBaseResource()); - } - - @Override - public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { - return new RemoveContainerCmdExec(getBaseResource()); - } - - @Override - public WaitContainerCmd.Exec createWaitContainerCmdExec() { - return new WaitContainerCmdExec(getBaseResource()); - } - - @Override - public AttachContainerCmd.Exec createAttachContainerCmdExec() { - return new AttachContainerCmdExec(getBaseResource()); - } - - @Override - public ExecStartCmd.Exec createExecStartCmdExec() { - return new ExecStartCmdExec(getBaseResource()); - } - - @Override - public InspectExecCmd.Exec createInspectExecCmdExec() { - return new InspectExecCmdExec(getBaseResource()); - } - - @Override - public LogContainerCmd.Exec createLogContainerCmdExec() { - return new LogContainerCmdExec(getBaseResource()); - } - - @Override - public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() { - return new CopyFileFromContainerCmdExec(getBaseResource()); - } - - @Override - public StopContainerCmd.Exec createStopContainerCmdExec() { - return new StopContainerCmdExec(getBaseResource()); - } - - @Override - public ContainerDiffCmd.Exec createContainerDiffCmdExec() { - return new ContainerDiffCmdExec(getBaseResource()); - } - - @Override - public KillContainerCmd.Exec createKillContainerCmdExec() { - return new KillContainerCmdExec(getBaseResource()); - } - - @Override - public RestartContainerCmd.Exec createRestartContainerCmdExec() { - return new RestartContainerCmdExec(getBaseResource()); - } - - @Override - public CommitCmd.Exec createCommitCmdExec() { - return new CommitCmdExec(getBaseResource()); - } - - @Override - public BuildImageCmd.Exec createBuildImageCmdExec() { - return new BuildImageCmdExec(getBaseResource()); - } - - @Override - public TopContainerCmd.Exec createTopContainerCmdExec() { - return new TopContainerCmdExec(getBaseResource()); - } - - @Override - public TagImageCmd.Exec createTagImageCmdExec() { - return new TagImageCmdExec(getBaseResource()); - } - - @Override - public PauseContainerCmd.Exec createPauseContainerCmdExec() { - return new PauseContainerCmdExec(getBaseResource()); - } - - @Override - public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { - return new UnpauseContainerCmdExec(baseResource); - } - - @Override - public EventsCmd.Exec createEventsCmdExec() { - return new EventsCmdExec(getBaseResource()); - } - - @Override - public void close() throws IOException { - checkNotNull(client, "Factory not initialized. You probably forgot to call init()!"); - client.close(); - } + private static final Logger LOGGER = LoggerFactory + .getLogger(DockerCmdExecFactoryImpl.class.getName()); + private Client client; + private WebTarget baseResource; + + @Override + public void init(DockerClientConfig dockerClientConfig) { + checkNotNull(dockerClientConfig, "config was not specified"); + + ClientConfig clientConfig = new ClientConfig(); + clientConfig.connectorProvider(new ApacheConnectorProvider()); + clientConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, + true); + + clientConfig.register(ResponseStatusExceptionFilter.class); + clientConfig.register(JsonClientFilter.class); + clientConfig.register(JacksonJsonProvider.class); + + if (dockerClientConfig.followRedirectsFilterEnabled()) { + clientConfig.register(FollowRedirectsFilter.class); + } + + if (dockerClientConfig.isLoggingFilterEnabled()) { + clientConfig.register(new SelectiveLoggingFilter(LOGGER, true)); + } + + if (dockerClientConfig.getReadTimeout() != null) { + int readTimeout = dockerClientConfig.getReadTimeout(); + clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); + } + + URI originalUri = dockerClientConfig.getUri(); + + SSLContext sslContext = null; + + if (dockerClientConfig.getSslConfig() != null) { + try { + sslContext = dockerClientConfig.getSslConfig().getSSLContext(); + } catch (Exception ex) { + throw new DockerClientException("Error in SSL Configuration", + ex); + } + } + + PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager( + getSchemeRegistry(originalUri, sslContext)); + + if (dockerClientConfig.getMaxTotalConnections() != null) + connManager + .setMaxTotal(dockerClientConfig.getMaxTotalConnections()); + if (dockerClientConfig.getMaxPerRoutConnections() != null) + connManager.setDefaultMaxPerRoute(dockerClientConfig + .getMaxPerRoutConnections()); + + clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, + connManager); + + ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig( + clientConfig); + + if (sslContext != null) { + clientBuilder.sslContext(sslContext); + } + + client = clientBuilder.build(); + + if (originalUri.getScheme().equals("unix")) { + dockerClientConfig.setUri(UnixConnectionSocketFactory + .sanitizeUri(originalUri)); + } + WebTarget webResource = client.target(dockerClientConfig.getUri()); + + if (dockerClientConfig.getVersion() == null + || dockerClientConfig.getVersion().isEmpty()) { + baseResource = webResource; + } else { + baseResource = webResource.path("v" + + dockerClientConfig.getVersion()); + } + } + + private org.apache.http.config.Registry getSchemeRegistry( + final URI originalUri, SSLContext sslContext) { + RegistryBuilder registryBuilder = RegistryBuilder + .create(); + registryBuilder.register("http", + PlainConnectionSocketFactory.getSocketFactory()); + if (sslContext != null) { + registryBuilder.register("https", new SSLConnectionSocketFactory( + sslContext)); + } + registryBuilder.register("unix", new UnixConnectionSocketFactory( + originalUri)); + return registryBuilder.build(); + } + + protected WebTarget getBaseResource() { + checkNotNull(baseResource, + "Factory not initialized. You probably forgot to call init()!"); + return baseResource; + } + + @Override + public AuthCmd.Exec createAuthCmdExec() { + return new AuthCmdExec(getBaseResource()); + } + + @Override + public InfoCmd.Exec createInfoCmdExec() { + return new InfoCmdExec(getBaseResource()); + } + + @Override + public PingCmd.Exec createPingCmdExec() { + return new PingCmdExec(getBaseResource()); + } + + @Override + public VersionCmd.Exec createVersionCmdExec() { + return new VersionCmdExec(getBaseResource()); + } + + @Override + public PullImageCmd.Exec createPullImageCmdExec() { + return new PullImageCmdExec(getBaseResource()); + } + + @Override + public PushImageCmd.Exec createPushImageCmdExec() { + return new PushImageCmdExec(getBaseResource()); + } + + @Override + public SaveImageCmd.Exec createSaveImageCmdExec() { + return new SaveImageCmdExec(getBaseResource()); + } + + @Override + public CreateImageCmd.Exec createCreateImageCmdExec() { + return new CreateImageCmdExec(getBaseResource()); + } + + @Override + public SearchImagesCmd.Exec createSearchImagesCmdExec() { + return new SearchImagesCmdExec(getBaseResource()); + } + + @Override + public RemoveImageCmd.Exec createRemoveImageCmdExec() { + return new RemoveImageCmdExec(getBaseResource()); + } + + @Override + public ListImagesCmd.Exec createListImagesCmdExec() { + return new ListImagesCmdExec(getBaseResource()); + } + + @Override + public InspectImageCmd.Exec createInspectImageCmdExec() { + return new InspectImageCmdExec(getBaseResource()); + } + + @Override + public ListContainersCmd.Exec createListContainersCmdExec() { + return new ListContainersCmdExec(getBaseResource()); + } + + @Override + public CreateContainerCmd.Exec createCreateContainerCmdExec() { + return new CreateContainerCmdExec(getBaseResource()); + } + + @Override + public StartContainerCmd.Exec createStartContainerCmdExec() { + return new StartContainerCmdExec(getBaseResource()); + } + + @Override + public InspectContainerCmd.Exec createInspectContainerCmdExec() { + return new InspectContainerCmdExec(getBaseResource()); + } + + @Override + public ExecCreateCmd.Exec createExecCmdExec() { + return new ExecCreateCmdExec(getBaseResource()); + } + + @Override + public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { + return new RemoveContainerCmdExec(getBaseResource()); + } + + @Override + public WaitContainerCmd.Exec createWaitContainerCmdExec() { + return new WaitContainerCmdExec(getBaseResource()); + } + + @Override + public AttachContainerCmd.Exec createAttachContainerCmdExec() { + return new AttachContainerCmdExec(getBaseResource()); + } + + @Override + public ExecStartCmd.Exec createExecStartCmdExec() { + return new ExecStartCmdExec(getBaseResource()); + } + + @Override + public InspectExecCmd.Exec createInspectExecCmdExec() { + return new InspectExecCmdExec(getBaseResource()); + } + + @Override + public LogContainerCmd.Exec createLogContainerCmdExec() { + return new LogContainerCmdExec(getBaseResource()); + } + + @Override + public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() { + return new CopyFileFromContainerCmdExec(getBaseResource()); + } + + @Override + public StopContainerCmd.Exec createStopContainerCmdExec() { + return new StopContainerCmdExec(getBaseResource()); + } + + @Override + public ContainerDiffCmd.Exec createContainerDiffCmdExec() { + return new ContainerDiffCmdExec(getBaseResource()); + } + + @Override + public KillContainerCmd.Exec createKillContainerCmdExec() { + return new KillContainerCmdExec(getBaseResource()); + } + + @Override + public RestartContainerCmd.Exec createRestartContainerCmdExec() { + return new RestartContainerCmdExec(getBaseResource()); + } + + @Override + public CommitCmd.Exec createCommitCmdExec() { + return new CommitCmdExec(getBaseResource()); + } + + @Override + public BuildImageCmd.Exec createBuildImageCmdExec() { + return new BuildImageCmdExec(getBaseResource()); + } + + @Override + public TopContainerCmd.Exec createTopContainerCmdExec() { + return new TopContainerCmdExec(getBaseResource()); + } + + @Override + public TagImageCmd.Exec createTagImageCmdExec() { + return new TagImageCmdExec(getBaseResource()); + } + + @Override + public PauseContainerCmd.Exec createPauseContainerCmdExec() { + return new PauseContainerCmdExec(getBaseResource()); + } + + @Override + public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { + return new UnpauseContainerCmdExec(baseResource); + } + + @Override + public EventsCmd.Exec createEventsCmdExec() { + return new EventsCmdExec(getBaseResource()); + } + + @Override + public void close() throws IOException { + checkNotNull(client, + "Factory not initialized. You probably forgot to call init()!"); + client.close(); + } } From 8523236da4be5c9280d4a528365db0ed3b18c9e8 Mon Sep 17 00:00:00 2001 From: Kanstantsin Shautsou Date: Sun, 22 Mar 2015 21:23:09 +0300 Subject: [PATCH 360/452] Fix httpclient dep As i see PoolingHttpClientConnectionManager used from DockerCmdExecFactoryImpl.class appeared only in httpclient 4.3 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 9f9ab3a6..7e22a91e 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,7 @@ 2.1.2 - 4.2.5 + 4.3.6 1.5 1.8 2.3 From 7f68a267a37d9f22300b531f80229c970b797645 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 23 Mar 2015 21:33:30 +0100 Subject: [PATCH 361/452] Cleanup POM.xml --- pom.xml | 66 ++++++++++++--------------------------------------------- 1 file changed, 14 insertions(+), 52 deletions(-) diff --git a/pom.xml b/pom.xml index 7e22a91e..ba60602a 100644 --- a/pom.xml +++ b/pom.xml @@ -47,28 +47,22 @@ 1.7 1.7 - 1.6.1 - 2.11 - 1.9 - 2.1.2 - - 4.3.6 + 4.3.1 1.5 1.8 2.3 2.6 1.7.5 - 1.3.9 - 0.3 + 1.51 2015-01-27T15-02-14 18.0 - - 1.1.0 - 5.12.1 + + 1.1.0 + 5.12.1 1.3 1.6 2.3.3 @@ -89,22 +83,21 @@ jackson-jaxrs-json-provider ${jackson-jaxrs.version} - - - - - org.glassfish.jersey.connectors jersey-apache-connector ${jersey.version} + + org.apache.httpcomponents + httpclient + ${httpclient.version} + org.glassfish.jersey.core jersey-client ${jersey.version} - de.gesellix unix-socket-factory @@ -131,31 +124,16 @@ commons-io ${commons-io.version} - - - com.github.jnr - jnr-unixsocket - ${jnr.unixsocket.version} - - org.slf4j slf4j-api ${slf4j-api.version} - com.google.guava guava ${guava.version} - - - - - - - org.bouncycastle bcpkix-jdk15on @@ -166,21 +144,21 @@ ch.qos.logback logback-core - ${version.logback} + ${logback.version} test ch.qos.logback logback-classic - ${version.logback} + ${logback.version} test org.testng testng - ${version.testng} + ${testng.version} test @@ -211,23 +189,7 @@ test - - - - com.github.jnr - jffi - 1.2.7 - - - com.github.jnr - jffi - native - 1.2.7 - - - - - + ossrh From 59ca504fa0524d275c177c546dc02f15bc3e15d9 Mon Sep 17 00:00:00 2001 From: Matt Austin Date: Wed, 25 Mar 2015 01:09:19 -0400 Subject: [PATCH 362/452] Add support for cpuset in CreateContainerCmd --- .../dockerjava/api/command/CreateContainerCmd.java | 4 ++++ .../core/command/CreateContainerCmdImpl.java | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java index 88a6caf0..c6a1234c 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java @@ -62,6 +62,10 @@ public interface CreateContainerCmd extends DockerCmd{ public CreateContainerCmd withCpuShares(int cpuShares); + public String getCpuset(); + + public CreateContainerCmd withCpuset(String cpuset); + public boolean isAttachStdin(); public CreateContainerCmd withAttachStdin(boolean attachStdin); diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index 0948bf16..ac32960a 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -32,6 +32,7 @@ public class CreateContainerCmdImpl extends AbstrDockerCmd Date: Wed, 25 Mar 2015 20:53:43 +0100 Subject: [PATCH 363/452] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f8841d76..7c659958 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ Change Log === Latest SNAPSHOT --- + + * [#179](https://github.com/docker-java/docker-java/pull/170) Add support for cpuset in CreateContainerCmd * [#170](https://github.com/docker-java/docker-java/pull/170) Allow to specify alternative files other than 'Dockerfile' for building images * [#165](https://github.com/docker-java/docker-java/pull/165) PushImageCmd assumes that you have an auth config setup * [#161](https://github.com/docker-java/docker-java/pull/161) Inspect exec command From a9c478bd6eb3f7afae5f0a62013b701eb614eb5c Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Wed, 25 Mar 2015 19:58:18 +0000 Subject: [PATCH 364/452] Dockerfiles not called 'dockerfile' Pass the name of the Dockerfile to docker. Adjust the TAR file to build from the correct path Implement some tests to show it working with a nonstandard name. Signed-off-by: Nigel Magnay --- .../github/dockerjava/api/DockerClient.java | 4 +- .../dockerjava/api/command/BuildImageCmd.java | 6 ++- .../dockerjava/core/DockerClientImpl.java | 6 +++ .../core/command/BuildImageCmdImpl.java | 40 +++++++++++++++---- .../core/dockerfile/Dockerfile.java | 6 ++- .../dockerjava/jaxrs/BuildImageCmdExec.java | 4 ++ .../core/command/BuildImageCmdImplTest.java | 28 +++++++++++++ .../subdirectory/Dockerfile-nonstandard | 12 ++++++ 8 files changed, 96 insertions(+), 10 deletions(-) create mode 100644 src/test/resources/nonstandard/subdirectory/Dockerfile-nonstandard diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index c4e4859c..9e275eb3 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -98,7 +98,9 @@ public CopyFileFromContainerCmd copyFileFromContainerCmd( public CommitCmd commitCmd(String containerId); - public BuildImageCmd buildImageCmd(File dockerFolder); + public BuildImageCmd buildImageCmd(); + + public BuildImageCmd buildImageCmd(File dockerFileOrFolder); public BuildImageCmd buildImageCmd(InputStream tarInputStream); diff --git a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java index becaeccc..1f26d37d 100644 --- a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java @@ -28,8 +28,12 @@ public interface BuildImageCmd extends DockerCmd{ public boolean isQuiet(); + public String getPathToDockerfile(); + public AuthConfigurations getBuildAuthConfigs(); - + + public BuildImageCmd withBaseDirectory(File baseDirectory); + public BuildImageCmd withDockerfile(File dockerfile); public BuildImageCmd withTarInputStream(InputStream tarInputStream); diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 0dd560af..de3d9e23 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -291,6 +291,12 @@ public CommitCmd commitCmd(String containerId) { .createCommitCmdExec(), containerId); } + @Override + public BuildImageCmd buildImageCmd() { + return new BuildImageCmdImpl(getDockerCmdExecFactory() + .createBuildImageCmdExec()); + } + @Override public BuildImageCmd buildImageCmd(File dockerFileOrFolder) { return new BuildImageCmdImpl(getDockerCmdExecFactory() diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index c793ed6e..180befd0 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -9,6 +9,7 @@ import com.github.dockerjava.api.command.BuildImageCmd; import com.github.dockerjava.api.model.AuthConfigurations; import com.github.dockerjava.core.dockerfile.Dockerfile; +import com.google.common.base.Optional; /** * @@ -24,6 +25,8 @@ public class BuildImageCmdImpl extends AbstrDockerCmd filesToAdd = new ArrayList(); public InputStream buildDockerFolderTar() { + return buildDockerFolderTar(getDockerFolder()); + } + + public InputStream buildDockerFolderTar(File directory) { // ARCHIVE TAR File dockerFolderTar = null; @@ -173,7 +177,7 @@ public InputStream buildDockerFolderTar() { try { String archiveNameWithOutExtension = UUID.randomUUID().toString(); - dockerFolderTar = CompressArchiveUtil.archiveTARFiles(getDockerFolder(), + dockerFolderTar = CompressArchiveUtil.archiveTARFiles(directory, filesToAdd, archiveNameWithOutExtension); return FileUtils.openInputStream(dockerFolderTar); diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index 405192ad..5c2b87fc 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -35,6 +35,7 @@ public BuildImageCmdExec(WebTarget baseResource) { @Override protected ResponseImpl execute(BuildImageCmd command) { WebTarget webResource = getBaseResource().path("/build"); + String dockerFilePath = command.getPathToDockerfile(); if(command.getTag() != null) { webResource = webResource.queryParam("t", command.getTag()); @@ -48,6 +49,9 @@ protected ResponseImpl execute(BuildImageCmd command) { if (command.isQuiet()) { webResource = webResource.queryParam("q", "true"); } + if( dockerFilePath != null && !"Dockerfile".equals(dockerFilePath)) { + webResource = webResource.queryParam("dockerfile", dockerFilePath); + } webResource.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.CHUNKED); diff --git a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index 4c69d86e..c1a70ef2 100644 --- a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -76,6 +76,34 @@ public void testNginxDockerfileBuilder() { equalTo("Guillaume J. Charmes \"guillaume@dotcloud.com\"")); } + @Test + public void testNonstandard1() { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("nonstandard/subdirectory/Dockerfile-nonstandard").getFile()); + + InputStream response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); + + String fullLog = asString(response); + assertThat(fullLog, containsString("Successfully built")); + } + + @Test + public void testNonstandard2() { + File baseDir = new File(Thread.currentThread().getContextClassLoader() + .getResource("nonstandard").getFile()); + File dockerFile = new File(Thread.currentThread().getContextClassLoader() + .getResource("nonstandard/subdirectory/Dockerfile-nonstandard").getFile()); + + + InputStream response = dockerClient.buildImageCmd() + .withBaseDirectory(baseDir) + .withDockerfile(dockerFile) + .withNoCache().exec(); + + String fullLog = asString(response); + assertThat(fullLog, containsString("Successfully built")); + } + @Test public void testDockerBuilderAddUrl() { File baseDir = new File(Thread.currentThread().getContextClassLoader() diff --git a/src/test/resources/nonstandard/subdirectory/Dockerfile-nonstandard b/src/test/resources/nonstandard/subdirectory/Dockerfile-nonstandard new file mode 100644 index 00000000..2d0fa24c --- /dev/null +++ b/src/test/resources/nonstandard/subdirectory/Dockerfile-nonstandard @@ -0,0 +1,12 @@ +# Nginx +# +# VERSION 0.0.1 + +FROM ubuntu:latest +MAINTAINER Guillaume J. Charmes "guillaume@dotcloud.com" + +# make sure the package repository is up to date +RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list +RUN apt-get update + +RUN apt-get install -y inotify-tools nginx apache2 openssh-server \ No newline at end of file From 0366cdf82e1bed9525768ab71d2ee8c7f869c1d1 Mon Sep 17 00:00:00 2001 From: Xavier Fournet Date: Sat, 28 Mar 2015 22:51:28 +0100 Subject: [PATCH 365/452] Fix logger for SaveImageCmd and SaveImageCmdImplTest classes --- src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java | 2 +- .../github/dockerjava/core/command/SaveImageCmdImplTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java index e9918d2a..b1eccd8f 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java @@ -12,7 +12,7 @@ public class SaveImageCmdExec extends AbstrDockerCmdExec implements SaveImageCmd.Exec { private static final Logger LOGGER = LoggerFactory - .getLogger(PushImageCmdExec.class); + .getLogger(SaveImageCmdExec.class); public SaveImageCmdExec(WebTarget baseResource) { super(baseResource); diff --git a/src/test/java/com/github/dockerjava/core/command/SaveImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/SaveImageCmdImplTest.java index b62594be..859a76cc 100644 --- a/src/test/java/com/github/dockerjava/core/command/SaveImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/SaveImageCmdImplTest.java @@ -27,7 +27,7 @@ @Test(groups = "integration") public class SaveImageCmdImplTest extends AbstractDockerClientTest { public static final Logger LOG = LoggerFactory - .getLogger(PushImageCmdImplTest.class); + .getLogger(SaveImageCmdImplTest.class); String username; From 6ac275300dbfecb12ded3863a38405e630379906 Mon Sep 17 00:00:00 2001 From: Nigel Magnay Date: Tue, 31 Mar 2015 10:26:32 +0100 Subject: [PATCH 366/452] We are now on a modern version of guava, so remove code that is a copy of guava clasess, and simplify. Signed-off-by: Nigel Magnay --- .../api/command/TopContainerResponse.java | 7 +- .../core/dockerfile/Dockerfile.java | 38 +-- .../core/dockerfile/DockerfileStatement.java | 6 +- .../dockerjava/core/util/guava/Guava.java | 45 --- .../core/util/guava/PercentEscaper.java | 245 -------------- .../core/util/guava/UnicodeEscaper.java | 304 ------------------ .../dockerjava/jaxrs/ListImagesCmdExec.java | 4 +- 7 files changed, 9 insertions(+), 640 deletions(-) delete mode 100644 src/main/java/com/github/dockerjava/core/util/guava/Guava.java delete mode 100644 src/main/java/com/github/dockerjava/core/util/guava/PercentEscaper.java delete mode 100644 src/main/java/com/github/dockerjava/core/util/guava/UnicodeEscaper.java diff --git a/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java index 89aa3645..c92ffa4c 100644 --- a/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/TopContainerResponse.java @@ -1,9 +1,8 @@ package com.github.dockerjava.api.command; -import static com.github.dockerjava.core.util.guava.Guava.join; - import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.common.base.Joiner; /** * @@ -32,12 +31,12 @@ public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("["); for(String[] fields: processes) { - buffer.append("[" + join(fields, "; ", true) + "]"); + buffer.append("[" + Joiner.on("; ").skipNulls().join(fields) + "]"); } buffer.append("]"); return "TopContainerResponse{" + - "titles=" + join(titles, "; ", true) + + "titles=" + Joiner.on("; ").skipNulls().join(titles) + ", processes=" + buffer.toString() + '}'; } diff --git a/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java b/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java index 72e85c35..d1930ee7 100644 --- a/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java +++ b/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java @@ -66,31 +66,7 @@ public Optional apply(String input) { } } - /** - * Not needed in modern guava - */ - private static class MissingOptionalFilter - implements Predicate> { - - @Override - public boolean apply(Optional optional) { - return (optional.orNull() != null); - } - } - - /** - * Not needed in modern guava - */ - private static class OptionalItemTransformer - implements Function, DockerfileStatement> { - - @Override - public DockerfileStatement apply(Optional optional) { - return optional.orNull(); - } - } - - public Collection getStatements() throws IOException { + public Iterable getStatements() throws IOException { Collection dockerFileContent = FileUtils.readLines(dockerFile); if (dockerFileContent.size() <= 0) { @@ -101,17 +77,7 @@ public Collection getStatements() throws IOException { Collection> optionals = Collections2 .transform(dockerFileContent, new LineTransformer()); - // Modern guava would be done here, - // With simply return Optional.presentInstances( optionals ); - // - // So this entire function could simply be - // return Optional.presentInstances( Collections2.transform( FileUtils.readLines(dockerFile), new LineTransformer() ) ); - // - // Until the dawn of that day, do it manually - - return Collections2.transform(Collections2.filter(optionals, new MissingOptionalFilter()), - new OptionalItemTransformer()); - + return Optional.presentInstances(optionals); } public List getIgnores() throws IOException { diff --git a/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java b/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java index a1bcc271..c048f77d 100644 --- a/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java +++ b/src/main/java/com/github/dockerjava/core/dockerfile/DockerfileStatement.java @@ -188,15 +188,13 @@ public static Optional createFromLine(String cmd) line = Add.create(cmd); - // if (line.isPresent()) { : Newer guava - if (line.orNull() != null) { + if (line.isPresent()) { return line; } line = Env.create(cmd); - // if (line.isPresent()) { : Newer guava - if (line.orNull() != null) { + if (line.isPresent()) { return line; } diff --git a/src/main/java/com/github/dockerjava/core/util/guava/Guava.java b/src/main/java/com/github/dockerjava/core/util/guava/Guava.java deleted file mode 100644 index 84e27b34..00000000 --- a/src/main/java/com/github/dockerjava/core/util/guava/Guava.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2008 The Guava Authors - * - * Licensed 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.github.dockerjava.core.util.guava; - -public class Guava { - - static final String URL_PATH_OTHER_SAFE_CHARS_LACKING_PLUS = - "-._~" + // Unreserved characters. - "!$'()*,;&=" + // The subdelim characters (excluding '+'). - "@:"; // The gendelim characters permitted in paths. - - public static PercentEscaper urlPathSegmentEscaper() { - return URL_PATH_SEGMENT_ESCAPER; - } - - private static final PercentEscaper URL_PATH_SEGMENT_ESCAPER = - new PercentEscaper(URL_PATH_OTHER_SAFE_CHARS_LACKING_PLUS + "+", false); - - public static String join(String[] joins, String sep, boolean skipNulls) { - StringBuilder sb = new StringBuilder(); - for(int i = 0; i < joins.length; i++) { - if(skipNulls && joins[i] == null) { - continue; - } - sb.append(joins[i]); - if(i < joins.length -1) { - sb.append(sep); - } - } - return sb.toString(); - } -} diff --git a/src/main/java/com/github/dockerjava/core/util/guava/PercentEscaper.java b/src/main/java/com/github/dockerjava/core/util/guava/PercentEscaper.java deleted file mode 100644 index 1d726dca..00000000 --- a/src/main/java/com/github/dockerjava/core/util/guava/PercentEscaper.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright (C) 2008 The Guava Authors - * - * Licensed 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.github.dockerjava.core.util.guava; - -import com.google.common.base.Preconditions; - -/** - * A {@code UnicodeEscaper} that escapes some set of Java characters using a - * UTF-8 based percent encoding scheme. The set of safe characters (those which - * remain unescaped) can be specified on construction. - * - *

This class is primarily used for creating URI escapers in UrlEscapers - * but can be used directly if required. While URI escapers impose - * specific semantics on which characters are considered 'safe', this class has - * a minimal set of restrictions. - * - *

When escaping a String, the following rules apply: - *

    - *
  • All specified safe characters remain unchanged. - *
  • If {@code plusForSpace} was specified, the space character " " is - * converted into a plus sign {@code "+"}. - *
  • All other characters are converted into one or more bytes using UTF-8 - * encoding and each byte is then represented by the 3-character string - * "%XX", where "XX" is the two-digit, uppercase, hexadecimal representation - * of the byte value. - *
- * - *

For performance reasons the only currently supported character encoding of - * this class is UTF-8. - * - *

Note: This escaper produces uppercase hexadecimal sequences. From - * RFC 3986:
- * "URI producers and normalizers should use uppercase hexadecimal digits - * for all percent-encodings." - * - * @author David Beaumont - * @since 15.0 - */ -public final class PercentEscaper extends UnicodeEscaper { - - // In some escapers spaces are escaped to '+' - private static final char[] PLUS_SIGN = { '+' }; - - // Percent escapers output upper case hex digits (uri escapers require this). - private static final char[] UPPER_HEX_DIGITS = - "0123456789ABCDEF".toCharArray(); - - /** - * If true we should convert space to the {@code +} character. - */ - private final boolean plusForSpace; - - /** - * An array of flags where for any {@code char c} if {@code safeOctets[c]} is - * true then {@code c} should remain unmodified in the output. If - * {@code c > safeOctets.length} then it should be escaped. - */ - private final boolean[] safeOctets; - - /** - * Constructs a percent escaper with the specified safe characters and - * optional handling of the space character. - * - *

Not that it is allowed, but not necessarily desirable to specify {@code %} - * as a safe character. This has the effect of creating an escaper which has no - * well defined inverse but it can be useful when escaping additional characters. - * - * @param safeChars a non null string specifying additional safe characters - * for this escaper (the ranges 0..9, a..z and A..Z are always safe and - * should not be specified here) - * @param plusForSpace true if ASCII space should be escaped to {@code +} - * rather than {@code %20} - * @throws IllegalArgumentException if any of the parameters were invalid - */ - public PercentEscaper(String safeChars, boolean plusForSpace) { - // TODO(user): Switch to static factory methods for creation now that class is final. - // TODO(user): Support escapers where alphanumeric chars are not safe. - Preconditions.checkNotNull(safeChars); // eager for GWT. - // Avoid any misunderstandings about the behavior of this escaper - if (safeChars.matches(".*[0-9A-Za-z].*")) { - throw new IllegalArgumentException( - "Alphanumeric characters are always 'safe' and should not be " + - "explicitly specified"); - } - safeChars += "abcdefghijklmnopqrstuvwxyz" + - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - "0123456789"; - // Avoid ambiguous parameters. Safe characters are never modified so if - // space is a safe character then setting plusForSpace is meaningless. - if (plusForSpace && safeChars.contains(" ")) { - throw new IllegalArgumentException( - "plusForSpace cannot be specified when space is a 'safe' character"); - } - this.plusForSpace = plusForSpace; - this.safeOctets = createSafeOctets(safeChars); - } - - /** - * Creates a boolean array with entries corresponding to the character values - * specified in safeChars set to true. The array is as small as is required to - * hold the given character information. - */ - private static boolean[] createSafeOctets(String safeChars) { - int maxChar = -1; - char[] safeCharArray = safeChars.toCharArray(); - for (char c : safeCharArray) { - maxChar = Math.max(c, maxChar); - } - boolean[] octets = new boolean[maxChar + 1]; - for (char c : safeCharArray) { - octets[c] = true; - } - return octets; - } - - /* - * Overridden for performance. For unescaped strings this improved the - * performance of the uri escaper from ~760ns to ~400ns as measured by - * CharEscapersBenchmark. - */ - @Override - protected int nextEscapeIndex(CharSequence csq, int index, int end) { - Preconditions.checkNotNull(csq); - for (; index < end; index++) { - char c = csq.charAt(index); - if (c >= safeOctets.length || !safeOctets[c]) { - break; - } - } - return index; - } - - /* - * Overridden for performance. For unescaped strings this improved the - * performance of the uri escaper from ~400ns to ~170ns as measured by - * CharEscapersBenchmark. - */ - @Override - public String escape(String s) { - Preconditions.checkNotNull(s); - int slen = s.length(); - for (int index = 0; index < slen; index++) { - char c = s.charAt(index); - if (c >= safeOctets.length || !safeOctets[c]) { - return escapeSlow(s, index); - } - } - return s; - } - - /** - * Escapes the given Unicode code point in UTF-8. - */ - @Override - protected char[] escape(int cp) { - // We should never get negative values here but if we do it will throw an - // IndexOutOfBoundsException, so at least it will get spotted. - if (cp < safeOctets.length && safeOctets[cp]) { - return null; - } else if (cp == ' ' && plusForSpace) { - return PLUS_SIGN; - } else if (cp <= 0x7F) { - // Single byte UTF-8 characters - // Start with "%--" and fill in the blanks - char[] dest = new char[3]; - dest[0] = '%'; - dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; - dest[1] = UPPER_HEX_DIGITS[cp >>> 4]; - return dest; - } else if (cp <= 0x7ff) { - // Two byte UTF-8 characters [cp >= 0x80 && cp <= 0x7ff] - // Start with "%--%--" and fill in the blanks - char[] dest = new char[6]; - dest[0] = '%'; - dest[3] = '%'; - dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; - cp >>>= 2; - dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[1] = UPPER_HEX_DIGITS[0xC | cp]; - return dest; - } else if (cp <= 0xffff) { - // Three byte UTF-8 characters [cp >= 0x800 && cp <= 0xffff] - // Start with "%E-%--%--" and fill in the blanks - char[] dest = new char[9]; - dest[0] = '%'; - dest[1] = 'E'; - dest[3] = '%'; - dest[6] = '%'; - dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; - cp >>>= 2; - dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; - cp >>>= 2; - dest[2] = UPPER_HEX_DIGITS[cp]; - return dest; - } else if (cp <= 0x10ffff) { - char[] dest = new char[12]; - // Four byte UTF-8 characters [cp >= 0xffff && cp <= 0x10ffff] - // Start with "%F-%--%--%--" and fill in the blanks - dest[0] = '%'; - dest[1] = 'F'; - dest[3] = '%'; - dest[6] = '%'; - dest[9] = '%'; - dest[11] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[10] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; - cp >>>= 2; - dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; - cp >>>= 2; - dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; - cp >>>= 2; - dest[2] = UPPER_HEX_DIGITS[cp & 0x7]; - return dest; - } else { - // If this ever happens it is due to bug in UnicodeEscaper, not bad input. - throw new IllegalArgumentException( - "Invalid unicode character value " + cp); - } - } -} diff --git a/src/main/java/com/github/dockerjava/core/util/guava/UnicodeEscaper.java b/src/main/java/com/github/dockerjava/core/util/guava/UnicodeEscaper.java deleted file mode 100644 index 3631193f..00000000 --- a/src/main/java/com/github/dockerjava/core/util/guava/UnicodeEscaper.java +++ /dev/null @@ -1,304 +0,0 @@ -/* - * Copyright (C) 2008 The Guava Authors - * - * Licensed 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.github.dockerjava.core.util.guava; - -import com.google.common.base.Preconditions; - - -/** - * An Escaper that converts literal text into a format safe for - * inclusion in a particular context (such as an XML document). Typically (but - * not always), the inverse process of "unescaping" the text is performed - * automatically by the relevant parser. - * - *

For example, an XML escaper would convert the literal string {@code - * "Foo"} into {@code "Foo<Bar>"} to prevent {@code ""} from - * being confused with an XML tag. When the resulting XML document is parsed, - * the parser API will return this text as the original literal string {@code - * "Foo"}. - * - *

Note: This class is similar to CharEscaper but with one - * very important difference. A CharEscaper can only process Java - * UTF16 characters in - * isolation and may not cope when it encounters surrogate pairs. This class - * facilitates the correct escaping of all Unicode characters. - * - *

As there are important reasons, including potential security issues, to - * handle Unicode correctly if you are considering implementing a new escaper - * you should favor using UnicodeEscaper wherever possible. - * - *

A {@code UnicodeEscaper} instance is required to be stateless, and safe - * when used concurrently by multiple threads. - * - *

Several popular escapers are defined as constants in classes like - * com.google.common.html.HtmlEscapers, com.google.common.xml.XmlEscapers, - * and SourceCodeEscapers. To create - * your own escapers extend this class and implement the #escape(int) - * method. - * - * @author David Beaumont - * @since 15.0 - */ -public abstract class UnicodeEscaper { - /** The amount of padding (chars) to use when growing the escape buffer. */ - private static final int DEST_PAD = 32; - - /** Constructor for use by subclasses. */ - protected UnicodeEscaper() {} - - /** - * Returns the escaped form of the given Unicode code point, or {@code null} - * if this code point does not need to be escaped. When called as part of an - * escaping operation, the given code point is guaranteed to be in the range - * {@code 0 <= cp <= Character#MAX_CODE_POINT}. - * - *

If an empty array is returned, this effectively strips the input - * character from the resulting text. - * - *

If the character does not need to be escaped, this method should return - * {@code null}, rather than an array containing the character representation - * of the code point. This enables the escaping algorithm to perform more - * efficiently. - * - *

If the implementation of this method cannot correctly handle a - * particular code point then it should either throw an appropriate runtime - * exception or return a suitable replacement character. It must never - * silently discard invalid input as this may constitute a security risk. - * - * @param cp the Unicode code point to escape if necessary - * @return the replacement characters, or {@code null} if no escaping was - * needed - */ - protected abstract char[] escape(int cp); - - /** - * Scans a sub-sequence of characters from a given CharSequence, - * returning the index of the next character that requires escaping. - * - *

Note: When implementing an escaper, it is a good idea to override - * this method for efficiency. The base class implementation determines - * successive Unicode code points and invokes #escape(int) for each of - * them. If the semantics of your escaper are such that code points in the - * supplementary range are either all escaped or all unescaped, this method - * can be implemented more efficiently using CharSequence#charAt(int). - * - *

Note however that if your escaper does not escape characters in the - * supplementary range, you should either continue to validate the correctness - * of any surrogate characters encountered or provide a clear warning to users - * that your escaper does not validate its input. - * - *

See com.google.common.net.PercentEscaper for an example. - * - * @param csq a sequence of characters - * @param start the index of the first character to be scanned - * @param end the index immediately after the last character to be scanned - * @throws IllegalArgumentException if the scanned sub-sequence of {@code csq} - * contains invalid surrogate pairs - */ - protected int nextEscapeIndex(CharSequence csq, int start, int end) { - int index = start; - while (index < end) { - int cp = codePointAt(csq, index, end); - if (cp < 0 || escape(cp) != null) { - break; - } - index += Character.isSupplementaryCodePoint(cp) ? 2 : 1; - } - return index; - } - - /** - * Returns the escaped form of a given literal string. - * - *

If you are escaping input in arbitrary successive chunks, then it is not - * generally safe to use this method. If an input string ends with an - * unmatched high surrogate character, then this method will throw - * IllegalArgumentException. You should ensure your input is valid UTF-16 before calling this - * method. - * - *

Note: When implementing an escaper it is a good idea to override - * this method for efficiency by inlining the implementation of - * #nextEscapeIndex(CharSequence, int, int) directly. Doing this for - * com.google.common.net.PercentEscaper more than doubled the - * performance for unescaped strings (as measured by CharEscapersBenchmark}. - * - * @param string the literal string to be escaped - * @return the escaped form of {@code string} - * @throws NullPointerException if {@code string} is null - * @throws IllegalArgumentException if invalid surrogate characters are - * encountered - */ - public String escape(String string) { - Preconditions.checkNotNull(string); - int end = string.length(); - int index = nextEscapeIndex(string, 0, end); - return index == end ? string : escapeSlow(string, index); - } - - /** - * Returns the escaped form of a given literal string, starting at the given - * index. This method is called by the #escape(String) method when it - * discovers that escaping is required. It is protected to allow subclasses - * to override the fastpath escaping function to inline their escaping test. - * See CharEscaperBuilder for an example usage. - * - *

This method is not reentrant and may only be invoked by the top level - * #escape(String) method. - * - * @param s the literal string to be escaped - * @param index the index to start escaping from - * @return the escaped form of {@code string} - * @throws NullPointerException if {@code string} is null - * @throws IllegalArgumentException if invalid surrogate characters are - * encountered - */ - protected final String escapeSlow(String s, int index) { - int end = s.length(); - - // Get a destination buffer and setup some loop variables. - char[] dest = new char[1024]; - int destIndex = 0; - int unescapedChunkStart = 0; - - while (index < end) { - int cp = codePointAt(s, index, end); - if (cp < 0) { - throw new IllegalArgumentException( - "Trailing high surrogate at end of input"); - } - // It is possible for this to return null because nextEscapeIndex() may - // (for performance reasons) yield some false positives but it must never - // give false negatives. - char[] escaped = escape(cp); - int nextIndex = index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1); - if (escaped != null) { - int charsSkipped = index - unescapedChunkStart; - - // This is the size needed to add the replacement, not the full - // size needed by the string. We only regrow when we absolutely must. - int sizeNeeded = destIndex + charsSkipped + escaped.length; - if (dest.length < sizeNeeded) { - int destLength = sizeNeeded + (end - index) + DEST_PAD; - dest = growBuffer(dest, destIndex, destLength); - } - // If we have skipped any characters, we need to copy them now. - if (charsSkipped > 0) { - s.getChars(unescapedChunkStart, index, dest, destIndex); - destIndex += charsSkipped; - } - if (escaped.length > 0) { - System.arraycopy(escaped, 0, dest, destIndex, escaped.length); - destIndex += escaped.length; - } - // If we dealt with an escaped character, reset the unescaped range. - unescapedChunkStart = nextIndex; - } - index = nextEscapeIndex(s, nextIndex, end); - } - - // Process trailing unescaped characters - no need to account for escaped - // length or padding the allocation. - int charsSkipped = end - unescapedChunkStart; - if (charsSkipped > 0) { - int endIndex = destIndex + charsSkipped; - if (dest.length < endIndex) { - dest = growBuffer(dest, destIndex, endIndex); - } - s.getChars(unescapedChunkStart, end, dest, destIndex); - destIndex = endIndex; - } - return new String(dest, 0, destIndex); - } - - /** - * Returns the Unicode code point of the character at the given index. - * - *

Unlike Character#codePointAt(CharSequence, int) or - * String#codePointAt(int) this method will never fail silently when - * encountering an invalid surrogate pair. - * - *

The behaviour of this method is as follows: - *

    - *
  1. If {@code index >= end}, IndexOutOfBoundsException is thrown. - *
  2. If the character at the specified index is not a surrogate, it is - * returned. - *
  3. If the first character was a high surrogate value, then an attempt is - * made to read the next character. - *
      - *
    1. If the end of the sequence was reached, the negated value of - * the trailing high surrogate is returned. - *
    2. If the next character was a valid low surrogate, the code point - * value of the high/low surrogate pair is returned. - *
    3. If the next character was not a low surrogate value, then - * IllegalArgumentException is thrown. - *
    - *
  4. If the first character was a low surrogate value, - * IllegalArgumentException is thrown. - *
- * - * @param seq the sequence of characters from which to decode the code point - * @param index the index of the first character to decode - * @param end the index beyond the last valid character to decode - * @return the Unicode code point for the given index or the negated value of - * the trailing high surrogate character at the end of the sequence - */ - protected static int codePointAt(CharSequence seq, int index, int end) { - Preconditions.checkNotNull(seq); - if (index < end) { - char c1 = seq.charAt(index++); - if (c1 < Character.MIN_HIGH_SURROGATE || - c1 > Character.MAX_LOW_SURROGATE) { - // Fast path (first test is probably all we need to do) - return c1; - } else if (c1 <= Character.MAX_HIGH_SURROGATE) { - // If the high surrogate was the last character, return its inverse - if (index == end) { - return -c1; - } - // Otherwise look for the low surrogate following it - char c2 = seq.charAt(index); - if (Character.isLowSurrogate(c2)) { - return Character.toCodePoint(c1, c2); - } - throw new IllegalArgumentException( - "Expected low surrogate but got char '" + c2 + - "' with value " + (int) c2 + " at index " + index + - " in '" + seq + "'"); - } else { - throw new IllegalArgumentException( - "Unexpected low surrogate character '" + c1 + - "' with value " + (int) c1 + " at index " + (index - 1) + - " in '" + seq + "'"); - } - } - throw new IndexOutOfBoundsException("Index exceeds specified range"); - } - - /** - * Helper method to grow the character buffer as needed, this only happens - * once in a while so it's ok if it's in a method call. If the index passed - * in is 0 then no copying will be done. - */ - private static char[] growBuffer(char[] dest, int index, int size) { - char[] copy = new char[size]; - if (index > 0) { - System.arraycopy(dest, 0, copy, 0, index); - } - return copy; - } -} diff --git a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java index 001ba1d0..59e08fb6 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ListImagesCmdExec.java @@ -1,7 +1,5 @@ package com.github.dockerjava.jaxrs; -import static com.github.dockerjava.core.util.guava.Guava.urlPathSegmentEscaper; - import java.util.List; import javax.ws.rs.client.WebTarget; @@ -14,6 +12,8 @@ import com.github.dockerjava.api.command.ListImagesCmd; import com.github.dockerjava.api.model.Image; +import static com.google.common.net.UrlEscapers.urlPathSegmentEscaper; + public class ListImagesCmdExec extends AbstrDockerCmdExec> implements ListImagesCmd.Exec { From 6987a1f9ac4624bef3e03da145637cb0e4263fbb Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 1 Apr 2015 20:38:46 +0200 Subject: [PATCH 367/452] Update CHANGELOG.md --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c659958..88c44bb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,8 @@ Change Log === Latest SNAPSHOT --- - - * [#179](https://github.com/docker-java/docker-java/pull/170) Add support for cpuset in CreateContainerCmd + * [#180](https://github.com/docker-java/docker-java/pull/180) Dockerfiles not called 'dockerfile' + * [#179](https://github.com/docker-java/docker-java/pull/179) Add support for cpuset in CreateContainerCmd * [#170](https://github.com/docker-java/docker-java/pull/170) Allow to specify alternative files other than 'Dockerfile' for building images * [#165](https://github.com/docker-java/docker-java/pull/165) PushImageCmd assumes that you have an auth config setup * [#161](https://github.com/docker-java/docker-java/pull/161) Inspect exec command From fd0bf88c129becb1991963d33b302623fa970c05 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 1 Apr 2015 20:49:50 +0200 Subject: [PATCH 368/452] exclude tests from circleCI --- .../dockerjava/core/command/BuildImageCmdImplTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index c1a70ef2..bd8a56d2 100644 --- a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -76,7 +76,8 @@ public void testNginxDockerfileBuilder() { equalTo("Guillaume J. Charmes \"guillaume@dotcloud.com\"")); } - @Test + + @Test(groups = "ignoreInCircleCi") public void testNonstandard1() { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("nonstandard/subdirectory/Dockerfile-nonstandard").getFile()); @@ -87,7 +88,7 @@ public void testNonstandard1() { assertThat(fullLog, containsString("Successfully built")); } - @Test + @Test(groups = "ignoreInCircleCi") public void testNonstandard2() { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("nonstandard").getFile()); From 376e7edb218fad8d26f84a0cc7d3420f47deb145 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 1 Apr 2015 22:41:23 +0200 Subject: [PATCH 369/452] Introduce WrappedResponseInputStream to close underlying Response --- .../api/command/AttachContainerCmd.java | 3 + .../api/command/CopyFileFromContainerCmd.java | 3 + .../dockerjava/api/command/ExecStartCmd.java | 3 + .../api/command/LogContainerCmd.java | 3 + .../dockerjava/api/command/PullImageCmd.java | 7 + .../dockerjava/api/command/SaveImageCmd.java | 3 + .../jaxrs/AttachContainerCmdExec.java | 7 +- .../dockerjava/jaxrs/BuildImageCmdExec.java | 131 +++++++++--------- .../jaxrs/CopyFileFromContainerCmdExec.java | 6 +- .../dockerjava/jaxrs/EventsCmdExec.java | 3 +- .../dockerjava/jaxrs/ExecStartCmdExec.java | 9 +- .../dockerjava/jaxrs/LogContainerCmdExec.java | 4 +- .../dockerjava/jaxrs/PullImageCmdExec.java | 9 +- .../dockerjava/jaxrs/PushImageCmdExec.java | 8 +- .../dockerjava/jaxrs/SaveImageCmdExec.java | 8 +- .../util/WrappedResponseInputStream.java | 70 ++++++++++ .../core/command/LogContainerCmdImplTest.java | 35 +++++ 17 files changed, 233 insertions(+), 79 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/jaxrs/util/WrappedResponseInputStream.java diff --git a/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java index aeee749e..abdec8f5 100644 --- a/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java @@ -55,6 +55,9 @@ public interface AttachContainerCmd extends DockerCmd{ public AttachContainerCmd withLogs(); /** + * Its the responsibility of the caller to consume and/or close the {@link InputStream} to prevent + * connection leaks. + * * @throws NotFoundException No such container */ @Override diff --git a/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java index 8d2bfbb4..5e85d998 100644 --- a/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CopyFileFromContainerCmd.java @@ -19,6 +19,9 @@ public interface CopyFileFromContainerCmd extends DockerCmd { public CopyFileFromContainerCmd withHostPath(String hostPath); /** + * Its the responsibility of the caller to consume and/or close the {@link InputStream} to prevent + * connection leaks. + * * @throws NotFoundException No such container */ @Override diff --git a/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java b/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java index bcc7a072..7ccb90cf 100644 --- a/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/ExecStartCmd.java @@ -23,6 +23,9 @@ public interface ExecStartCmd extends DockerCmd { public ExecStartCmd withTty(); /** + * Its the responsibility of the caller to consume and/or close the {@link InputStream} to prevent + * connection leaks. + * * @throws com.github.dockerjava.api.NotFoundException * No such exec instance */ diff --git a/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java index 36a41beb..74512b39 100644 --- a/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java @@ -56,6 +56,9 @@ public interface LogContainerCmd extends DockerCmd{ public LogContainerCmd withTail(int tail); /** + * Its the responsibility of the caller to consume and/or close the {@link InputStream} to prevent + * connection leaks. + * * @throws NotFoundException No such container */ @Override diff --git a/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java b/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java index 27d5b978..c39617dd 100644 --- a/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java @@ -29,5 +29,12 @@ public interface PullImageCmd extends DockerCmd{ public static interface Exec extends DockerCmdExec { } + + /** + * Its the responsibility of the caller to consume and/or close the {@link InputStream} to prevent + * connection leaks. + */ + @Override + public InputStream exec(); } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java b/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java index 957ae05c..48c5f319 100644 --- a/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/SaveImageCmd.java @@ -21,6 +21,9 @@ public interface SaveImageCmd extends DockerCmd{ public SaveImageCmd withTag(String tag); /** + * Its the responsibility of the caller to consume and/or close the {@link InputStream} to prevent + * connection leaks. + * * @throws com.github.dockerjava.api.NotFoundException No such image */ public InputStream exec() throws NotFoundException; diff --git a/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java index 1fafd1f0..de4bb3f0 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/AttachContainerCmdExec.java @@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory; import com.github.dockerjava.api.command.AttachContainerCmd; +import com.github.dockerjava.jaxrs.util.WrappedResponseInputStream; public class AttachContainerCmdExec extends AbstrDockerCmdExec implements @@ -36,9 +37,11 @@ protected InputStream execute(AttachContainerCmd command) { LOGGER.trace("POST: {}", webResource); - return webResource.request() + Response response = webResource.request() .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .post(null, Response.class).readEntity(InputStream.class); + .post(null, Response.class); + + return new WrappedResponseInputStream(response); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index 5c2b87fc..18aceb4e 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -21,13 +21,16 @@ import com.github.dockerjava.api.command.BuildImageCmd; import com.github.dockerjava.api.model.AuthConfigurations; import com.github.dockerjava.api.model.EventStreamItem; +import com.github.dockerjava.jaxrs.util.WrappedResponseInputStream; import com.google.common.collect.ImmutableList; -public class BuildImageCmdExec extends AbstrDockerCmdExec implements BuildImageCmd.Exec { - +public class BuildImageCmdExec extends + AbstrDockerCmdExec implements + BuildImageCmd.Exec { + private static final Logger LOGGER = LoggerFactory .getLogger(BuildImageCmdExec.class); - + public BuildImageCmdExec(WebTarget baseResource) { super(baseResource); } @@ -35,72 +38,76 @@ public BuildImageCmdExec(WebTarget baseResource) { @Override protected ResponseImpl execute(BuildImageCmd command) { WebTarget webResource = getBaseResource().path("/build"); - String dockerFilePath = command.getPathToDockerfile(); - - if(command.getTag() != null) { + String dockerFilePath = command.getPathToDockerfile(); + + if (command.getTag() != null) { webResource = webResource.queryParam("t", command.getTag()); } - if (command.hasNoCacheEnabled()) { - webResource = webResource.queryParam("nocache", "true"); - } - if (command.hasRemoveEnabled()) { - webResource = webResource.queryParam("rm", "true"); - } - if (command.isQuiet()) { - webResource = webResource.queryParam("q", "true"); - } - if( dockerFilePath != null && !"Dockerfile".equals(dockerFilePath)) { - webResource = webResource.queryParam("dockerfile", dockerFilePath); - } - - - webResource.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.CHUNKED); - webResource.property(ClientProperties.CHUNKED_ENCODING_SIZE, 1024*1024); - - - LOGGER.debug("POST: {}", webResource); - InputStream is = resourceWithOptionalAuthConfig(command, webResource.request()) - .accept(MediaType.TEXT_PLAIN) - .post(entity(command.getTarInputStream(), "application/tar"), Response.class).readEntity(InputStream.class); - - return new ResponseImpl(is); - + if (command.hasNoCacheEnabled()) { + webResource = webResource.queryParam("nocache", "true"); + } + if (command.hasRemoveEnabled()) { + webResource = webResource.queryParam("rm", "true"); + } + if (command.isQuiet()) { + webResource = webResource.queryParam("q", "true"); + } + if (dockerFilePath != null && !"Dockerfile".equals(dockerFilePath)) { + webResource = webResource.queryParam("dockerfile", dockerFilePath); + } + + webResource.property(ClientProperties.REQUEST_ENTITY_PROCESSING, + RequestEntityProcessing.CHUNKED); + webResource.property(ClientProperties.CHUNKED_ENCODING_SIZE, + 1024 * 1024); + + LOGGER.debug("POST: {}", webResource); + Response response = resourceWithOptionalAuthConfig(command, + webResource.request()) + .accept(MediaType.TEXT_PLAIN) + .post(entity(command.getTarInputStream(), "application/tar"), + Response.class); + + return new ResponseImpl(new WrappedResponseInputStream(response)); + } - private Invocation.Builder resourceWithOptionalAuthConfig(BuildImageCmd command, Invocation.Builder request) { + private Invocation.Builder resourceWithOptionalAuthConfig( + BuildImageCmd command, Invocation.Builder request) { AuthConfigurations authConfigs = command.getBuildAuthConfigs(); if (authConfigs != null) { - request = request.header("X-Registry-Config", registryConfigs(authConfigs)); + request = request.header("X-Registry-Config", + registryConfigs(authConfigs)); } return request; } - - public static class ResponseImpl extends BuildImageCmd.Response { - - private final InputStream proxy; - - public ResponseImpl(InputStream proxy) { - this.proxy = proxy; - } - - @Override - public Iterable getItems() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - // we'll be reading instances of MyBean - ObjectReader reader = mapper.reader(EventStreamItem.class); - // and then do other configuration, if any, and read: - Iterator items = reader.readValues(proxy); - - try { - return ImmutableList.copyOf(items); - } finally { - proxy.close(); - } - } - - @Override - public int read() throws IOException { - return proxy.read(); - } - } + + public static class ResponseImpl extends BuildImageCmd.Response { + + private final InputStream proxy; + + public ResponseImpl(InputStream proxy) { + this.proxy = proxy; + } + + @Override + public Iterable getItems() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + // we'll be reading instances of MyBean + ObjectReader reader = mapper.reader(EventStreamItem.class); + // and then do other configuration, if any, and read: + Iterator items = reader.readValues(proxy); + + try { + return ImmutableList.copyOf(items); + } finally { + proxy.close(); + } + } + + @Override + public int read() throws IOException { + return proxy.read(); + } + } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java index 5126aaed..0a738be8 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/CopyFileFromContainerCmdExec.java @@ -6,11 +6,13 @@ import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.api.command.CopyFileFromContainerCmd; +import com.github.dockerjava.jaxrs.util.WrappedResponseInputStream; public class CopyFileFromContainerCmdExec extends AbstrDockerCmdExec implements CopyFileFromContainerCmd.Exec { @@ -29,7 +31,9 @@ protected InputStream execute(CopyFileFromContainerCmd command) { LOGGER.trace("POST: " + webResource.toString()); - return webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(entity(command, MediaType.APPLICATION_JSON)).readEntity(InputStream.class); + Response response = webResource.request().accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(entity(command, MediaType.APPLICATION_JSON)); + + return new WrappedResponseInputStream(response); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java index 75114542..78d26fea 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -20,6 +20,7 @@ import com.github.dockerjava.api.command.EventCallback; import com.github.dockerjava.api.command.EventsCmd; import com.github.dockerjava.api.model.Event; +import com.github.dockerjava.jaxrs.util.WrappedResponseInputStream; public class EventsCmdExec extends AbstrDockerCmdExec implements EventsCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(EventsCmdExec.class); @@ -66,7 +67,7 @@ public Void call() throws Exception { Response response = null; try { response = webTarget.request().get(Response.class); - InputStream inputStream = response.readEntity(InputStream.class); + InputStream inputStream = new WrappedResponseInputStream(response); JsonParser jp = JSON_FACTORY.createParser(inputStream); while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed() && eventCallback.isReceiving()) { eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); diff --git a/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java index effd3904..cbac951d 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/ExecStartCmdExec.java @@ -1,12 +1,15 @@ package com.github.dockerjava.jaxrs; import com.github.dockerjava.api.command.ExecStartCmd; +import com.github.dockerjava.jaxrs.util.WrappedResponseInputStream; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.InputStream; import static javax.ws.rs.client.Entity.entity; @@ -26,9 +29,11 @@ protected InputStream execute(ExecStartCmd command) { LOGGER.trace("POST: {}", webResource); - return webResource + Response response = webResource .request() .accept(MediaType.APPLICATION_JSON) - .post(entity(command, MediaType.APPLICATION_JSON), Response.class).readEntity(InputStream.class); + .post(entity(command, MediaType.APPLICATION_JSON), Response.class); + + return new WrappedResponseInputStream(response); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java index b279ebdc..7d031bdd 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/LogContainerCmdExec.java @@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory; import com.github.dockerjava.api.command.LogContainerCmd; +import com.github.dockerjava.jaxrs.util.WrappedResponseInputStream; public class LogContainerCmdExec extends AbstrDockerCmdExec implements LogContainerCmd.Exec { @@ -28,7 +29,8 @@ protected InputStream execute(LogContainerCmd command) { .queryParam("tail", command.getTail() < 0 ? "all" : "" + command.getTail()); LOGGER.trace("GET: {}", webResource); - return webResource.request().get().readEntity(InputStream.class); + + return new WrappedResponseInputStream(webResource.request().get()); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java index 725483f8..bd89d22f 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PullImageCmdExec.java @@ -5,12 +5,14 @@ import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.api.command.PullImageCmd; import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.jaxrs.util.WrappedResponseInputStream; public class PullImageCmdExec extends AbstrDockerCmdExec implements @@ -31,9 +33,10 @@ protected InputStream execute(PullImageCmd command) { .queryParam("registry", command.getRegistry()); LOGGER.trace("POST: {}", webResource); - return resourceWithOptionalAuthConfig(command, webResource.request()) - .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(null) - .readEntity(InputStream.class); + Response response = resourceWithOptionalAuthConfig(command, webResource.request()) + .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(null); + + return new WrappedResponseInputStream(response); } private Invocation.Builder resourceWithOptionalAuthConfig( diff --git a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java index e0120c2f..7fc88d91 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/PushImageCmdExec.java @@ -21,6 +21,7 @@ import com.github.dockerjava.api.model.AuthConfig; import com.github.dockerjava.api.model.PushEventStreamItem; +import com.github.dockerjava.jaxrs.util.WrappedResponseInputStream; // Shaded, but imported import com.google.common.collect.ImmutableList; @@ -40,15 +41,14 @@ protected ResponseImpl execute(PushImageCmd command) { final String registryAuth = registryAuth(command.getAuthConfig()); LOGGER.trace("POST: {}", webResource); - InputStream is = webResource + javax.ws.rs.core.Response response = webResource .request() .header("X-Registry-Auth", registryAuth) .accept(MediaType.APPLICATION_JSON) .post( - entity(Response.class, MediaType.APPLICATION_JSON)).readEntity( - InputStream.class); + entity(Response.class, MediaType.APPLICATION_JSON)); - return new ResponseImpl(is); + return new ResponseImpl(new WrappedResponseInputStream(response)); } private String name(PushImageCmd command) { diff --git a/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java index b1eccd8f..8d70e2f6 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/SaveImageCmdExec.java @@ -4,11 +4,13 @@ import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.api.command.SaveImageCmd; +import com.github.dockerjava.jaxrs.util.WrappedResponseInputStream; public class SaveImageCmdExec extends AbstrDockerCmdExec implements SaveImageCmd.Exec { private static final Logger LOGGER = LoggerFactory @@ -24,11 +26,11 @@ protected InputStream execute(SaveImageCmd command) { .queryParam("tag", command.getTag()); LOGGER.trace("GET: {}", webResource); - InputStream is = webResource + Response response = webResource .request() .accept(MediaType.APPLICATION_JSON) - .get().readEntity(InputStream.class); + .get(); - return is; + return new WrappedResponseInputStream(response); } } diff --git a/src/main/java/com/github/dockerjava/jaxrs/util/WrappedResponseInputStream.java b/src/main/java/com/github/dockerjava/jaxrs/util/WrappedResponseInputStream.java new file mode 100644 index 00000000..bf40dbfc --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/util/WrappedResponseInputStream.java @@ -0,0 +1,70 @@ +package com.github.dockerjava.jaxrs.util; + +import java.io.IOException; +import java.io.InputStream; + +import javax.ws.rs.core.Response; + +/** + * This is a wrapper around {@link Response} that acts as a {@link InputStream}. + * When this {@link WrappedResponseInputStream} is closed it closes the + * underlying {@link Response} object also to prevent connection leaks. + * + * @author marcus + */ +public class WrappedResponseInputStream extends InputStream { + + private Response response; + private InputStream delegate; + + public WrappedResponseInputStream(Response response) { + this.response = response; + this.delegate = response.readEntity(InputStream.class); + } + + public int read() throws IOException { + return delegate.read(); + } + + public int hashCode() { + return delegate.hashCode(); + } + + public int read(byte[] b) throws IOException { + return delegate.read(b); + } + + public boolean equals(Object obj) { + return delegate.equals(obj); + } + + public int read(byte[] b, int off, int len) throws IOException { + return delegate.read(b, off, len); + } + + public long skip(long n) throws IOException { + return delegate.skip(n); + } + + public int available() throws IOException { + return delegate.available(); + } + + public void close() throws IOException { + response.close(); + delegate.close(); + } + + public void mark(int readlimit) { + delegate.mark(readlimit); + } + + public void reset() throws IOException { + delegate.reset(); + } + + public boolean markSupported() { + return delegate.markSupported(); + } + +} diff --git a/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java index 84299219..94a27b1d 100644 --- a/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/LogContainerCmdImplTest.java @@ -79,6 +79,41 @@ public void logNonExistingContainer() throws Exception { } catch (NotFoundException e) { } } + + @Test + public void multipleLogContainer() throws Exception { + + String snippet = "hello world"; + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("/bin/echo", snippet).exec(); + + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); + + dockerClient.startContainerCmd(container.getId()).exec(); + + int exitCode = dockerClient.waitContainerCmd(container.getId()).exec(); + + assertThat(exitCode, equalTo(0)); + + InputStream response = dockerClient.logContainerCmd(container.getId()).withStdErr().withStdOut().exec(); + + response.close(); + + //String log = asString(response); + + response = dockerClient.logContainerCmd(container.getId()).withStdErr().withStdOut().exec(); + + //log = asString(response); + response.close(); + + response = dockerClient.logContainerCmd(container.getId()).withStdErr().withStdOut().exec(); + + String log = asString(response); + + assertThat(log, endsWith(snippet)); + } } From e08695bafaa71e8381c8ba4158a37528665a8571 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 1 Apr 2015 22:54:29 +0200 Subject: [PATCH 370/452] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88c44bb7..6c338660 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ Change Log === Latest SNAPSHOT --- + + * [#185](https://github.com/docker-java/docker-java/pull/185) Introduce WrappedResponseInputStream to close underlying Response * [#180](https://github.com/docker-java/docker-java/pull/180) Dockerfiles not called 'dockerfile' * [#179](https://github.com/docker-java/docker-java/pull/179) Add support for cpuset in CreateContainerCmd * [#170](https://github.com/docker-java/docker-java/pull/170) Allow to specify alternative files other than 'Dockerfile' for building images From 3214f5f42ae0bb0f2d63c6f57568571101ffacab Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 1 Apr 2015 23:22:24 +0200 Subject: [PATCH 371/452] Added withPull method to BuilImageCmd --- .../dockerjava/api/command/BuildImageCmd.java | 8 +++++++- .../core/command/BuildImageCmdImpl.java | 18 ++++++++++++++++++ .../dockerjava/jaxrs/BuildImageCmdExec.java | 3 +++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java index 1f26d37d..ec013d42 100644 --- a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java @@ -25,8 +25,10 @@ public interface BuildImageCmd extends DockerCmd{ public boolean hasNoCacheEnabled(); public boolean hasRemoveEnabled(); - + public boolean isQuiet(); + + public boolean hasPullEnabled(); public String getPathToDockerfile(); @@ -50,6 +52,10 @@ public interface BuildImageCmd extends DockerCmd{ public BuildImageCmd withQuiet(boolean quiet); + public BuildImageCmd withPull(); + + public BuildImageCmd withPull(boolean pull); + public BuildImageCmd withBuildAuthConfigs(AuthConfigurations authConfig); public static interface Exec extends DockerCmdExec { diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 180befd0..046565d3 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -24,6 +24,8 @@ public class BuildImageCmdImpl extends AbstrDockerCmd Date: Wed, 1 Apr 2015 23:25:50 +0200 Subject: [PATCH 372/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c338660..a033ccb4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ Change Log Latest SNAPSHOT --- + * [#186](https://github.com/docker-java/docker-java/pull/186) Added withPull method to BuilImageCmd * [#185](https://github.com/docker-java/docker-java/pull/185) Introduce WrappedResponseInputStream to close underlying Response * [#180](https://github.com/docker-java/docker-java/pull/180) Dockerfiles not called 'dockerfile' * [#179](https://github.com/docker-java/docker-java/pull/179) Add support for cpuset in CreateContainerCmd From ca54f9c758087bce519f5b59fdd5c4a0482dc313 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Wed, 1 Apr 2015 23:38:03 +0200 Subject: [PATCH 373/452] Deprecate StartContainerCmd methods in favor of using CreateContainerCmd --- .../api/command/StartContainerCmd.java | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index b48e3050..de70b97c 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -12,7 +12,9 @@ import com.github.dockerjava.api.model.RestartPolicy; /** - * Start a container + * Start a container. + * + * TODO: Almost all methods are deprecated as they have corresponding siblings in {@link CreateContainerCmd} now. */ public interface StartContainerCmd extends DockerCmd { @@ -48,13 +50,16 @@ public interface StartContainerCmd extends DockerCmd { public Capability[] getCapDrop(); + @Deprecated public StartContainerCmd withBinds(Bind... binds); /** * Add link to another container. */ + @Deprecated public StartContainerCmd withLinks(Link... links); + @Deprecated public StartContainerCmd withLxcConf(LxcConf... lxcConf); /** @@ -63,6 +68,7 @@ public interface StartContainerCmd extends DockerCmd { * * @see #withPortBindings(PortBinding...) */ + @Deprecated public StartContainerCmd withPortBindings(Ports portBindings); /** @@ -70,24 +76,31 @@ public interface StartContainerCmd extends DockerCmd { * This corresponds to the --publish (-p) * option of the docker run CLI command. */ + @Deprecated public StartContainerCmd withPortBindings(PortBinding... portBindings); + @Deprecated public StartContainerCmd withPrivileged(Boolean privileged); + @Deprecated public StartContainerCmd withPublishAllPorts(Boolean publishAllPorts); /** * Set custom DNS servers */ + @Deprecated public StartContainerCmd withDns(String... dns); /** * Set custom DNS search domains */ + @Deprecated public StartContainerCmd withDnsSearch(String... dnsSearch); + @Deprecated public StartContainerCmd withVolumesFrom(String volumesFrom); + @Deprecated public StartContainerCmd withContainerId(String containerId); /** @@ -102,22 +115,26 @@ public interface StartContainerCmd extends DockerCmd { * as D-bus and is therefore considered insecure. * */ + @Deprecated public StartContainerCmd withNetworkMode(String networkMode); /** * Add host devices to the container */ + @Deprecated public StartContainerCmd withDevices(Device... devices); /** * Add hostnames to /etc/hosts in the container */ + @Deprecated public StartContainerCmd withExtraHosts(String... extraHosts); /** * Set custom {@link RestartPolicy} for the container. Defaults to * {@link RestartPolicy#noRestart()} */ + @Deprecated public StartContainerCmd withRestartPolicy(RestartPolicy restartPolicy); /** @@ -126,6 +143,7 @@ public interface StartContainerCmd extends DockerCmd { * capability to the container. For example: adding {@link Capability#MKNOD} * allows the container to create special files using the 'mknod' command. */ + @Deprecated public StartContainerCmd withCapAdd(Capability... capAdd); /** @@ -134,6 +152,7 @@ public interface StartContainerCmd extends DockerCmd { * capability from the container. For example: dropping {@link Capability#CHOWN} * prevents the container from changing the owner of any files. */ + @Deprecated public StartContainerCmd withCapDrop(Capability... capDrop); /** From bef79df8ae4a60f56c40efcab807360c6163c7b5 Mon Sep 17 00:00:00 2001 From: Martin Ahrer Date: Sat, 4 Apr 2015 23:25:37 +0200 Subject: [PATCH 374/452] Added a Links constructor accepting a List object --- src/main/java/com/github/dockerjava/api/model/Links.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/com/github/dockerjava/api/model/Links.java b/src/main/java/com/github/dockerjava/api/model/Links.java index 9bbef25d..888c0aa2 100644 --- a/src/main/java/com/github/dockerjava/api/model/Links.java +++ b/src/main/java/com/github/dockerjava/api/model/Links.java @@ -31,6 +31,10 @@ public Links(final Link... links) this.links = links; } + public Links(final List links) { + this.links = links.toArray(new Link[links.size()]); + } + public Link[] getLinks() { return links; From ccd56e90022f01a34b480d84be08d1a291e808f8 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 5 Apr 2015 15:27:36 +0200 Subject: [PATCH 375/452] Switch to 1.1.0-SNAPSHOT according to semantic versioning --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ba60602a..c0905b77 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 1.0.1-SNAPSHOT + 1.1.0-SNAPSHOT docker-java https://github.com/docker-java/docker-java From ed1fba471788a46acf462e1193c727730ee7ebfc Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 5 Apr 2015 15:31:01 +0200 Subject: [PATCH 376/452] [maven-release-plugin] prepare release docker-java-1.1.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index c0905b77..e8f612e8 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 1.1.0-SNAPSHOT + 1.1.0 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-1.1.0 From a3bbeae15d3f5dab5ab8a6c0f09b208a02f10642 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 5 Apr 2015 15:31:06 +0200 Subject: [PATCH 377/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index e8f612e8..957c157c 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 1.1.0 + 1.1.1-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-1.1.0 + HEAD From 52cb771b0c81852da1fc30973312318f05268cd9 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sun, 5 Apr 2015 15:36:04 +0200 Subject: [PATCH 378/452] Update CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a033ccb4..0892535a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,9 @@ Change Log === Latest SNAPSHOT +--- + +v1.1.0 --- * [#186](https://github.com/docker-java/docker-java/pull/186) Added withPull method to BuilImageCmd From bdedec016ef62783970dda2ff9d336273a3ccf65 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sun, 5 Apr 2015 16:38:01 +0200 Subject: [PATCH 379/452] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0892535a..62f76dd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ Change Log Latest SNAPSHOT --- +* [#192](https://github.com/docker-java/docker-java/pull/192) Added withPull method to BuilImageCmd Added a Links constructor accepting a List object + v1.1.0 --- From 3b4c34631cc5a7d0dadbe8cc29cbe7055427d24c Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sun, 5 Apr 2015 16:38:22 +0200 Subject: [PATCH 380/452] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62f76dd1..c1b319a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ Change Log Latest SNAPSHOT --- -* [#192](https://github.com/docker-java/docker-java/pull/192) Added withPull method to BuilImageCmd Added a Links constructor accepting a List object +* [#192](https://github.com/docker-java/docker-java/pull/192) Added a Links constructor accepting a List object v1.1.0 --- From b42a3e1f9b74f75126bf3b2dff981b05f92abcb3 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 7 Apr 2015 21:06:16 +0200 Subject: [PATCH 381/452] Fix issue #164 --- .../api/command/CreateContainerCmd.java | 233 ++++-- .../api/command/StartContainerCmd.java | 134 +-- .../dockerjava/api/model/HostConfig.java | 34 +- .../github/dockerjava/api/model/Ports.java | 16 + .../core/command/CreateContainerCmdImpl.java | 766 +++++++++++------- .../command/CreateContainerCmdImplTest.java | 192 ++++- .../command/StartContainerCmdImplTest.java | 69 +- 7 files changed, 989 insertions(+), 455 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java index c6a1234c..a2a6dc85 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java @@ -2,111 +2,115 @@ import com.github.dockerjava.api.ConflictException; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Capability; +import com.github.dockerjava.api.model.Device; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.HostConfig; +import com.github.dockerjava.api.model.Link; +import com.github.dockerjava.api.model.LxcConf; +import com.github.dockerjava.api.model.PortBinding; +import com.github.dockerjava.api.model.Ports; +import com.github.dockerjava.api.model.RestartPolicy; import com.github.dockerjava.api.model.Volume; import com.github.dockerjava.api.model.VolumesFrom; public interface CreateContainerCmd extends DockerCmd{ - public CreateContainerCmd withName(String name); - - public String getName(); - - public CreateContainerCmd withExposedPorts(ExposedPort... exposedPorts); - - public ExposedPort[] getExposedPorts(); + public static interface Exec extends DockerCmdExec { + } - public boolean isDisableNetwork(); + /** + * @throws NotFoundException No such container + * @throws ConflictException Named container already exists + */ + @Override + public CreateContainerResponse exec() throws NotFoundException, + ConflictException; - public String getWorkingDir(); + public Bind[] getBinds(); - public CreateContainerCmd withWorkingDir(String workingDir); + public Capability[] getCapAdd(); - public String getHostName(); + public Capability[] getCapDrop(); - public CreateContainerCmd withDisableNetwork(boolean disableNetwork); + public String[] getCmd(); - public CreateContainerCmd withHostName(String hostName); + public String getCpuset(); - public String[] getPortSpecs(); + public int getCpuShares(); - public CreateContainerCmd withPortSpecs(String... portSpecs); + public Device[] getDevices(); - public String getUser(); + public String[] getDns(); + + public String[] getDnsSearch(); - public CreateContainerCmd withUser(String user); + public String[] getEntrypoint(); - public boolean isTty(); + public String[] getEnv(); - public CreateContainerCmd withTty(boolean tty); + public ExposedPort[] getExposedPorts(); + + public String[] getExtraHosts(); - public boolean isStdinOpen(); + public HostConfig getHostConfig(); - public CreateContainerCmd withStdinOpen(boolean stdinOpen); + public String getHostName(); - public boolean isStdInOnce(); + public String getImage(); - public CreateContainerCmd withStdInOnce(boolean stdInOnce); + public Link[] getLinks(); + + public LxcConf[] getLxcConf(); public long getMemoryLimit(); - public CreateContainerCmd withMemoryLimit(long memoryLimit); - public long getMemorySwap(); - public CreateContainerCmd withMemorySwap(long memorySwap); - - public int getCpuShares(); - - public CreateContainerCmd withCpuShares(int cpuShares); - - public String getCpuset(); + public String getName(); + + public String getNetworkMode(); + + public Ports getPortBindings(); - public CreateContainerCmd withCpuset(String cpuset); + public String[] getPortSpecs(); + + public RestartPolicy getRestartPolicy(); - public boolean isAttachStdin(); + public String getUser(); - public CreateContainerCmd withAttachStdin(boolean attachStdin); + public Volume[] getVolumes(); - public boolean isAttachStdout(); + public VolumesFrom[] getVolumesFrom(); - public CreateContainerCmd withAttachStdout(boolean attachStdout); + public String getWorkingDir(); public boolean isAttachStderr(); - public CreateContainerCmd withAttachStderr(boolean attachStderr); - - public String[] getEnv(); - - public CreateContainerCmd withEnv(String... env); - - public String[] getCmd(); - - public CreateContainerCmd withCmd(String... cmd); - - public String[] getDns(); + public boolean isAttachStdin(); - public CreateContainerCmd withDns(String... dns); + public boolean isAttachStdout(); - public String getImage(); + public boolean isDisableNetwork(); + + public Boolean isPrivileged(); + + public Boolean isPublishAllPorts(); - public CreateContainerCmd withImage(String image); + public boolean isStdInOnce(); - public Volume[] getVolumes(); + public boolean isStdinOpen(); - public CreateContainerCmd withVolumes(Volume... volumes); + public boolean isTty(); - public VolumesFrom[] getVolumesFrom(); + public CreateContainerCmd withAttachStderr(boolean attachStderr); - public CreateContainerCmd withVolumesFrom(VolumesFrom... volumesFrom); + public CreateContainerCmd withAttachStdin(boolean attachStdin); - public HostConfig getHostConfig(); + public CreateContainerCmd withAttachStdout(boolean attachStdout); - public CreateContainerCmd withHostConfig(HostConfig hostConfig); - - public Capability[] getCapAdd(); + public CreateContainerCmd withBinds(Bind... binds); /** * Add linux { */ public CreateContainerCmd withCapAdd(Capability... capAdd); - public Capability[] getCapDrop(); - /** * Drop linux kernel @@ -125,21 +127,114 @@ public interface CreateContainerCmd extends DockerCmd{ * prevents the container from changing the owner of any files. */ public CreateContainerCmd withCapDrop(Capability... capDrop); + + public CreateContainerCmd withCmd(String... cmd); + + public CreateContainerCmd withCpuset(String cpuset); + public CreateContainerCmd withCpuShares(int cpuShares); - public String[] getEntrypoint(); + /** + * Add host devices to the container + */ + public CreateContainerCmd withDevices(Device... devices); + + public CreateContainerCmd withDisableNetwork(boolean disableNetwork); + + /** + * Set custom DNS servers + */ + public CreateContainerCmd withDns(String... dns); + /** + * Set custom DNS search domains + */ + public CreateContainerCmd withDnsSearch(String... dnsSearch); + public CreateContainerCmd withEntrypoint(String... entrypoint); + + public CreateContainerCmd withEnv(String... env); + + public CreateContainerCmd withExposedPorts(ExposedPort... exposedPorts); /** - * @throws NotFoundException No such container - * @throws ConflictException Named container already exists + * Add hostnames to /etc/hosts in the container */ - @Override - public CreateContainerResponse exec() throws NotFoundException, - ConflictException; + public CreateContainerCmd withExtraHosts(String... extraHosts); - public static interface Exec extends DockerCmdExec { - } + public CreateContainerCmd withHostConfig(HostConfig hostConfig); + + public CreateContainerCmd withHostName(String hostName); + + public CreateContainerCmd withImage(String image); + + /** + * Add link to another container. + */ + public CreateContainerCmd withLinks(Link... links); + + public CreateContainerCmd withLxcConf(LxcConf... lxcConf); + + public CreateContainerCmd withMemoryLimit(long memoryLimit); + + public CreateContainerCmd withMemorySwap(long memorySwap); + + public CreateContainerCmd withName(String name); + + + /** + * Set the Network mode for the container + *
    + *
  • 'bridge': creates a new network stack for the container on the docker + * bridge
  • + *
  • 'none': no networking for this container
  • + *
  • 'container:': reuses another container network stack
  • + *
  • 'host': use the host network stack inside the container. Note: the + * host mode gives the container full access to local system services such + * as D-bus and is therefore considered insecure.
  • + *
+ */ + public CreateContainerCmd withNetworkMode(String networkMode); + + /** + * Add one or more {@link PortBinding}s. + * This corresponds to the --publish (-p) + * option of the docker run CLI command. + */ + public CreateContainerCmd withPortBindings(PortBinding... portBindings); + + /** + * Add the port bindings that are contained in the given {@link Ports} + * object. + * + * @see #withPortBindings(PortBinding...) + */ + public CreateContainerCmd withPortBindings(Ports portBindings); + + public CreateContainerCmd withPortSpecs(String... portSpecs); + + public CreateContainerCmd withPrivileged(boolean privileged); + + public CreateContainerCmd withPublishAllPorts(boolean publishAllPorts); + + /** + * Set custom {@link RestartPolicy} for the container. Defaults to + * {@link RestartPolicy#noRestart()} + */ + public CreateContainerCmd withRestartPolicy(RestartPolicy restartPolicy); + + public CreateContainerCmd withStdInOnce(boolean stdInOnce); + + public CreateContainerCmd withStdinOpen(boolean stdinOpen); + + public CreateContainerCmd withTty(boolean tty); + + public CreateContainerCmd withUser(String user); + + public CreateContainerCmd withVolumes(Volume... volumes); + + public CreateContainerCmd withVolumesFrom(VolumesFrom... volumesFrom); + + public CreateContainerCmd withWorkingDir(String workingDir); } diff --git a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java index de70b97c..e76598e3 100644 --- a/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/StartContainerCmd.java @@ -18,72 +18,79 @@ */ public interface StartContainerCmd extends DockerCmd { - public Bind[] getBinds(); + public static interface Exec extends DockerCmdExec { + } - public Link[] getLinks(); + /** + * @throws NotFoundException + * No such container + * @throws NotModifiedException + * Container already started + */ + @Override + public Void exec() throws NotFoundException, NotModifiedException; - public LxcConf[] getLxcConf(); + public Bind[] getBinds(); - public Ports getPortBindings(); + public Capability[] getCapAdd(); - public Boolean isPublishAllPorts(); + public Capability[] getCapDrop(); - public Boolean isPrivileged(); + public String getContainerId(); + + public Device[] getDevices(); public String[] getDns(); public String[] getDnsSearch(); - public String getVolumesFrom(); + public String[] getExtraHosts(); - public String getContainerId(); + public Link[] getLinks(); - public String getNetworkMode(); + public LxcConf[] getLxcConf(); - public Device[] getDevices(); + public String getNetworkMode(); - public String[] getExtraHosts(); + public Ports getPortBindings(); public RestartPolicy getRestartPolicy(); - public Capability[] getCapAdd(); - - public Capability[] getCapDrop(); + public String getVolumesFrom(); - @Deprecated - public StartContainerCmd withBinds(Bind... binds); + public Boolean isPrivileged(); - /** - * Add link to another container. - */ - @Deprecated - public StartContainerCmd withLinks(Link... links); + public Boolean isPublishAllPorts(); @Deprecated - public StartContainerCmd withLxcConf(LxcConf... lxcConf); + public StartContainerCmd withBinds(Bind... binds); /** - * Add the port bindings that are contained in the given {@link Ports} - * object. - * - * @see #withPortBindings(PortBinding...) + * Add linux
kernel + * capability to the container. For example: adding {@link Capability#MKNOD} + * allows the container to create special files using the 'mknod' command. */ @Deprecated - public StartContainerCmd withPortBindings(Ports portBindings); + public StartContainerCmd withCapAdd(Capability... capAdd); /** - * Add one or more {@link PortBinding}s. - * This corresponds to the --publish (-p) - * option of the docker run CLI command. + * Drop linux kernel + * capability from the container. For example: dropping {@link Capability#CHOWN} + * prevents the container from changing the owner of any files. */ @Deprecated - public StartContainerCmd withPortBindings(PortBinding... portBindings); + public StartContainerCmd withCapDrop(Capability... capDrop); @Deprecated - public StartContainerCmd withPrivileged(Boolean privileged); + public StartContainerCmd withContainerId(String containerId); + /** + * Add host devices to the container + */ @Deprecated - public StartContainerCmd withPublishAllPorts(Boolean publishAllPorts); + public StartContainerCmd withDevices(Device... devices); /** * Set custom DNS servers @@ -97,11 +104,20 @@ public interface StartContainerCmd extends DockerCmd { @Deprecated public StartContainerCmd withDnsSearch(String... dnsSearch); + /** + * Add hostnames to /etc/hosts in the container + */ @Deprecated - public StartContainerCmd withVolumesFrom(String volumesFrom); + public StartContainerCmd withExtraHosts(String... extraHosts); + /** + * Add link to another container. + */ @Deprecated - public StartContainerCmd withContainerId(String containerId); + public StartContainerCmd withLinks(Link... links); + + @Deprecated + public StartContainerCmd withLxcConf(LxcConf... lxcConf); /** * Set the Network mode for the container @@ -119,52 +135,36 @@ public interface StartContainerCmd extends DockerCmd { public StartContainerCmd withNetworkMode(String networkMode); /** - * Add host devices to the container + * Add one or more {@link PortBinding}s. + * This corresponds to the --publish (-p) + * option of the docker run CLI command. */ @Deprecated - public StartContainerCmd withDevices(Device... devices); + public StartContainerCmd withPortBindings(PortBinding... portBindings); /** - * Add hostnames to /etc/hosts in the container + * Add the port bindings that are contained in the given {@link Ports} + * object. + * + * @see #withPortBindings(PortBinding...) */ @Deprecated - public StartContainerCmd withExtraHosts(String... extraHosts); + public StartContainerCmd withPortBindings(Ports portBindings); - /** - * Set custom {@link RestartPolicy} for the container. Defaults to - * {@link RestartPolicy#noRestart()} - */ @Deprecated - public StartContainerCmd withRestartPolicy(RestartPolicy restartPolicy); + public StartContainerCmd withPrivileged(Boolean privileged); - /** - * Add linux kernel - * capability to the container. For example: adding {@link Capability#MKNOD} - * allows the container to create special files using the 'mknod' command. - */ @Deprecated - public StartContainerCmd withCapAdd(Capability... capAdd); + public StartContainerCmd withPublishAllPorts(Boolean publishAllPorts); /** - * Drop linux kernel - * capability from the container. For example: dropping {@link Capability#CHOWN} - * prevents the container from changing the owner of any files. + * Set custom {@link RestartPolicy} for the container. Defaults to + * {@link RestartPolicy#noRestart()} */ @Deprecated - public StartContainerCmd withCapDrop(Capability... capDrop); - - /** - * @throws NotFoundException - * No such container - * @throws NotModifiedException - * Container already started - */ - @Override - public Void exec() throws NotFoundException, NotModifiedException; + public StartContainerCmd withRestartPolicy(RestartPolicy restartPolicy); - public static interface Exec extends DockerCmdExec { - } + @Deprecated + public StartContainerCmd withVolumesFrom(String volumesFrom); } diff --git a/src/main/java/com/github/dockerjava/api/model/HostConfig.java b/src/main/java/com/github/dockerjava/api/model/HostConfig.java index c72d078b..18fd3407 100644 --- a/src/main/java/com/github/dockerjava/api/model/HostConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/HostConfig.java @@ -1,7 +1,10 @@ package com.github.dockerjava.api.model; +import java.util.Map; + import org.apache.commons.lang.builder.ToStringBuilder; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @@ -9,7 +12,7 @@ public class HostConfig { @JsonProperty("Binds") - private String[] binds; + private Binds binds; @JsonProperty("Links") private Links links; @@ -59,12 +62,12 @@ public class HostConfig { public HostConfig() { } - public HostConfig(String[] binds, Links links, LxcConf[] lxcConf, Ports portBindings, boolean publishAllPorts, + public HostConfig(Bind[] binds, Link[] links, LxcConf[] lxcConf, Ports portBindings, boolean publishAllPorts, boolean privileged, String[] dns, String[] dnsSearch, VolumesFrom[] volumesFrom, String containerIDFile, Capability[] capAdd, Capability[] capDrop, RestartPolicy restartPolicy, String networkMode, Device[] devices, String[] extraHosts) { - this.binds = binds; - this.links = links; + this.binds = new Binds(binds); + this.links = new Links(links); this.lxcConf = lxcConf; this.portBindings = portBindings; this.publishAllPorts = publishAllPorts; @@ -81,14 +84,16 @@ public HostConfig(String[] binds, Links links, LxcConf[] lxcConf, Ports portBind this.extraHosts = extraHosts; } - public String[] getBinds() { - return binds; + + @JsonIgnore + public Bind[] getBinds() { + return (binds == null) ? new Bind[0] : binds.getBinds(); } public LxcConf[] getLxcConf() { return lxcConf; } - + public Ports getPortBindings() { return portBindings; } @@ -117,8 +122,9 @@ public String[] getDnsSearch() { return dnsSearch; } - public Links getLinks() { - return links; + @JsonIgnore + public Link[] getLinks() { + return (links == null) ? new Link[0] : links.getLinks(); } public String getNetworkMode() { @@ -145,12 +151,14 @@ public Capability[] getCapDrop() { return capDrop; } - public void setBinds(String[] binds) { - this.binds = binds; + @JsonIgnore + public void setBinds(Bind... binds) { + this.binds = new Binds(binds); } - public void setLinks(Links links) { - this.links = links; + @JsonIgnore + public void setLinks(Link... links) { + this.links = new Links(links); } public void setLxcConf(LxcConf[] lxcConf) { diff --git a/src/main/java/com/github/dockerjava/api/model/Ports.java b/src/main/java/com/github/dockerjava/api/model/Ports.java index e0f3c080..d7c8a324 100644 --- a/src/main/java/com/github/dockerjava/api/model/Ports.java +++ b/src/main/java/com/github/dockerjava/api/model/Ports.java @@ -3,8 +3,10 @@ import static org.apache.commons.lang.StringUtils.isEmpty; import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -59,6 +61,10 @@ public Ports() { } public Ports(ExposedPort exposedPort, Binding host) { bind(exposedPort, host); } + + public Ports(PortBinding... portBindings) { + add(portBindings); + } /** * Adds a new {@link PortBinding} for the specified {@link ExposedPort} and @@ -97,6 +103,16 @@ public String toString(){ public Map getBindings(){ return ports; } + +// public PortBinding[] getBindingsAsArray() { +// List bindings = new ArrayList<>(); +// for(Map.Entry entry: ports.entrySet()) { +// for(Ports.Binding binding : entry.getValue()) { +// bindings.add(new PortBinding(binding, entry.getKey())); +// } +// } +// return bindings.toArray(new PortBinding[bindings.size()]); +// } /** * Creates a {@link Binding} for the given IP address and port number. diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index ac32960a..5afd0dbb 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -10,370 +10,546 @@ import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Capability; +import com.github.dockerjava.api.model.Device; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.ExposedPorts; import com.github.dockerjava.api.model.HostConfig; +import com.github.dockerjava.api.model.Link; +import com.github.dockerjava.api.model.LxcConf; +import com.github.dockerjava.api.model.PortBinding; +import com.github.dockerjava.api.model.Ports; +import com.github.dockerjava.api.model.RestartPolicy; import com.github.dockerjava.api.model.Volume; import com.github.dockerjava.api.model.VolumesFrom; import com.github.dockerjava.api.model.Volumes; /** - * + * * Creates a new container. - * + * */ -public class CreateContainerCmdImpl extends AbstrDockerCmd implements CreateContainerCmd { +public class CreateContainerCmdImpl extends + AbstrDockerCmd implements + CreateContainerCmd { private String name; - - @JsonProperty("Hostname") private String hostName = ""; - @JsonProperty("User") private String user = ""; - @JsonProperty("Memory") private long memoryLimit = 0; - @JsonProperty("MemorySwap") private long memorySwap = 0; - @JsonProperty("CpuShares") private int cpuShares = 0; - @JsonProperty("Cpuset") private String cpuset; - @JsonProperty("AttachStdin") private boolean attachStdin = false; - @JsonProperty("AttachStdout") private boolean attachStdout = false; - @JsonProperty("AttachStderr") private boolean attachStderr = false; - @JsonProperty("PortSpecs") private String[] portSpecs; - @JsonProperty("Tty") private boolean tty = false; - @JsonProperty("OpenStdin") private boolean stdinOpen = false; - @JsonProperty("StdinOnce") private boolean stdInOnce = false; - @JsonProperty("Env") private String[] env; - @JsonProperty("Cmd") private String[] cmd; - @JsonProperty("Entrypoint") private String[] entrypoint; - @JsonProperty("Image") private String image; - @JsonProperty("Volumes") private Volumes volumes = new Volumes(); - @JsonProperty("WorkingDir") private String workingDir = ""; - @JsonProperty("DisableNetwork") private boolean disableNetwork = false; - @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts = new ExposedPorts(); - @JsonProperty("HostConfig") private HostConfig hostConfig = new HostConfig(); - + + @JsonProperty("Hostname") + private String hostName = ""; + @JsonProperty("User") + private String user = ""; + @JsonProperty("Memory") + private long memoryLimit = 0; + @JsonProperty("MemorySwap") + private long memorySwap = 0; + @JsonProperty("CpuShares") + private int cpuShares = 0; + @JsonProperty("Cpuset") + private String cpuset; + @JsonProperty("AttachStdin") + private boolean attachStdin = false; + @JsonProperty("AttachStdout") + private boolean attachStdout = false; + @JsonProperty("AttachStderr") + private boolean attachStderr = false; + @JsonProperty("PortSpecs") + private String[] portSpecs; + @JsonProperty("Tty") + private boolean tty = false; + @JsonProperty("OpenStdin") + private boolean stdinOpen = false; + @JsonProperty("StdinOnce") + private boolean stdInOnce = false; + @JsonProperty("Env") + private String[] env; + @JsonProperty("Cmd") + private String[] cmd; + @JsonProperty("Entrypoint") + private String[] entrypoint; + @JsonProperty("Image") + private String image; + @JsonProperty("Volumes") + private Volumes volumes = new Volumes(); + @JsonProperty("WorkingDir") + private String workingDir = ""; + @JsonProperty("DisableNetwork") + private boolean disableNetwork = false; + @JsonProperty("ExposedPorts") + private ExposedPorts exposedPorts = new ExposedPorts(); + @JsonProperty("HostConfig") + private HostConfig hostConfig = new HostConfig(); + public CreateContainerCmdImpl(CreateContainerCmd.Exec exec, String image) { super(exec); checkNotNull(image, "image was not specified"); withImage(image); } + /** + * @throws NotFoundException + * No such container + * @throws ConflictException + * Named container already exists + */ @Override - public CreateContainerCmdImpl withName(String name) { - checkNotNull(name, "name was not specified"); - this.name = name; - return this; - } + public CreateContainerResponse exec() throws NotFoundException, + ConflictException { + return super.exec(); + } - @Override - public String getName() { - return name; - } + @Override + @JsonIgnore + public Bind[] getBinds() { + return hostConfig.getBinds(); + } - @Override - public CreateContainerCmdImpl withExposedPorts(ExposedPort... exposedPorts) { - this.exposedPorts = new ExposedPorts(exposedPorts); - return this; - } + @Override + public Capability[] getCapAdd() { + return hostConfig.getCapAdd(); + } + + @Override + public Capability[] getCapDrop() { + return hostConfig.getCapDrop(); + } + + @Override + public String[] getCmd() { + return cmd; + } + + @Override + public String getCpuset() { + return cpuset; + } + + @Override + public int getCpuShares() { + return cpuShares; + } - @Override + @Override @JsonIgnore - public ExposedPort[] getExposedPorts() { - return exposedPorts.getExposedPorts(); - } + public Device[] getDevices() { + return hostConfig.getDevices(); + } + @Override + @JsonIgnore + public String[] getDns() { + return hostConfig.getDns(); + } - @Override - public boolean isDisableNetwork() { - return disableNetwork; - } + @Override + @JsonIgnore + public String[] getDnsSearch() { + return hostConfig.getDnsSearch(); + } - @Override - public String getWorkingDir() { - return workingDir; - } + @Override + public String[] getEntrypoint() { + return entrypoint; + } - @Override - public CreateContainerCmdImpl withWorkingDir(String workingDir) { - this.workingDir = workingDir; - return this; - } + @Override + public String[] getEnv() { + return env; + } + + @Override + @JsonIgnore + public ExposedPort[] getExposedPorts() { + return exposedPorts.getExposedPorts(); + } + @Override + @JsonIgnore + public String[] getExtraHosts() { + return hostConfig.getExtraHosts(); + } + + @Override + public HostConfig getHostConfig() { + return hostConfig; + } - @Override + @Override public String getHostName() { - return hostName; - } + return hostName; + } - @Override - public CreateContainerCmdImpl withDisableNetwork(boolean disableNetwork) { - this.disableNetwork = disableNetwork; - return this; - } + @Override + public String getImage() { + return image; + } - @Override - public CreateContainerCmdImpl withHostName(String hostName) { - this.hostName = hostName; - return this; - } + @Override + @JsonIgnore + public Link[] getLinks() { + return hostConfig.getLinks(); + } + + @Override + @JsonIgnore + public LxcConf[] getLxcConf() { + return hostConfig.getLxcConf(); + } + + @Override + public long getMemoryLimit() { + return memoryLimit; + } + + @Override + public long getMemorySwap() { + return memorySwap; + } + + @Override + public String getName() { + return name; + } - @Override + @Override + @JsonIgnore + public String getNetworkMode() { + return hostConfig.getNetworkMode(); + } + + @Override + @JsonIgnore + public Ports getPortBindings() { + return hostConfig.getPortBindings(); + } + + @Override public String[] getPortSpecs() { - return portSpecs; - } + return portSpecs; + } - @Override - public CreateContainerCmdImpl withPortSpecs(String... portSpecs) { - this.portSpecs = portSpecs; - return this; - } + @Override + @JsonIgnore + public RestartPolicy getRestartPolicy() { + return hostConfig.getRestartPolicy(); + } - @Override + @Override public String getUser() { - return user; - } + return user; + } - @Override - public CreateContainerCmdImpl withUser(String user) { - this.user = user; - return this; - } + @Override + @JsonIgnore + public Volume[] getVolumes() { + return volumes.getVolumes(); + } - @Override - public boolean isTty() { - return tty; - } + @Override + @JsonIgnore + public VolumesFrom[] getVolumesFrom() { + return hostConfig.getVolumesFrom(); + } - @Override - public CreateContainerCmdImpl withTty(boolean tty) { - this.tty = tty; - return this; - } + @Override + public String getWorkingDir() { + return workingDir; + } - @Override - public boolean isStdinOpen() { - return stdinOpen; - } + @Override + public boolean isAttachStderr() { + return attachStderr; + } - @Override - public CreateContainerCmdImpl withStdinOpen(boolean stdinOpen) { - this.stdinOpen = stdinOpen; - return this; - } + @Override + public boolean isAttachStdin() { + return attachStdin; + } - @Override + @Override + public boolean isAttachStdout() { + return attachStdout; + } + + @Override + public boolean isDisableNetwork() { + return disableNetwork; + } + + @Override + @JsonIgnore + public Boolean isPrivileged() { + return hostConfig.isPrivileged(); + } + + @Override + @JsonIgnore + public Boolean isPublishAllPorts() { + return hostConfig.isPublishAllPorts(); + } + + @Override public boolean isStdInOnce() { - return stdInOnce; - } + return stdInOnce; + } - @Override - public CreateContainerCmdImpl withStdInOnce(boolean stdInOnce) { - this.stdInOnce = stdInOnce; - return this; - } + @Override + public boolean isStdinOpen() { + return stdinOpen; + } - @Override - public long getMemoryLimit() { - return memoryLimit; - } + @Override + public boolean isTty() { + return tty; + } - @Override - public CreateContainerCmdImpl withMemoryLimit(long memoryLimit) { - this.memoryLimit = memoryLimit; - return this; - } + @Override + public String toString() { + return new ToStringBuilder(this).append("create container ") + .append(name != null ? "name=" + name + " " : "").append(this) + .toString(); + } - @Override - public long getMemorySwap() { - return memorySwap; - } + @Override + public CreateContainerCmdImpl withAttachStderr(boolean attachStderr) { + this.attachStderr = attachStderr; + return this; + } - @Override - public CreateContainerCmdImpl withMemorySwap(long memorySwap) { - this.memorySwap = memorySwap; - return this; - } + @Override + public CreateContainerCmdImpl withAttachStdin(boolean attachStdin) { + this.attachStdin = attachStdin; + return this; + } - @Override - public int getCpuShares() { - return cpuShares; - } + @Override + public CreateContainerCmdImpl withAttachStdout(boolean attachStdout) { + this.attachStdout = attachStdout; + return this; + } - @Override - public CreateContainerCmdImpl withCpuShares(int cpuShares) { - this.cpuShares = cpuShares; - return this; - } + @Override + public CreateContainerCmd withBinds(Bind... binds) { + hostConfig.setBinds(binds); + return this; + } - @Override - public String getCpuset() { - return cpuset; - } + @Override + public CreateContainerCmd withCapAdd(Capability... capAdd) { + hostConfig.setCapAdd(capAdd); + return this; + } - @Override - public CreateContainerCmdImpl withCpuset(String cpuset) { - this.cpuset = cpuset; - return this; - } + @Override + public CreateContainerCmd withCapDrop(Capability... capDrop) { + hostConfig.setCapDrop(capDrop); + return this; + } - @Override - public boolean isAttachStdin() { - return attachStdin; - } + @Override + public CreateContainerCmdImpl withCmd(String... cmd) { + this.cmd = cmd; + return this; + } - @Override - public CreateContainerCmdImpl withAttachStdin(boolean attachStdin) { - this.attachStdin = attachStdin; - return this; - } + @Override + public CreateContainerCmdImpl withCpuset(String cpuset) { + this.cpuset = cpuset; + return this; + } - @Override - public boolean isAttachStdout() { - return attachStdout; - } + @Override + public CreateContainerCmdImpl withCpuShares(int cpuShares) { + this.cpuShares = cpuShares; + return this; + } - @Override - public CreateContainerCmdImpl withAttachStdout(boolean attachStdout) { - this.attachStdout = attachStdout; - return this; - } + @Override + public CreateContainerCmd withDevices(Device... devices) { + this.hostConfig.setDevices(devices); + return this; + } - @Override - public boolean isAttachStderr() { - return attachStderr; - } + @Override + public CreateContainerCmdImpl withDisableNetwork(boolean disableNetwork) { + this.disableNetwork = disableNetwork; + return this; + } - @Override - public CreateContainerCmdImpl withAttachStderr(boolean attachStderr) { - this.attachStderr = attachStderr; - return this; - } + @Override + public CreateContainerCmdImpl withDns(String... dns) { + this.hostConfig.setDns(dns); + return this; + } - @Override - public String[] getEnv() { - return env; - } + @Override + public CreateContainerCmd withDnsSearch(String... dnsSearch) { + this.hostConfig.setDnsSearch(dnsSearch); + return this; + } - @Override + @Override + public CreateContainerCmdImpl withEntrypoint(String... entrypoint) { + this.entrypoint = entrypoint; + return this; + } + + @Override public CreateContainerCmdImpl withEnv(String... env) { - this.env = env; - return this; - } + this.env = env; + return this; + } - @Override - public String[] getCmd() { - return cmd; - } + @Override + public CreateContainerCmdImpl withExposedPorts(ExposedPort... exposedPorts) { + this.exposedPorts = new ExposedPorts(exposedPorts); + return this; + } - @Override - public CreateContainerCmdImpl withCmd(String... cmd) { - this.cmd = cmd; - return this; - } - - @Override - public String[] getEntrypoint() { - return entrypoint; - } - - @Override - public CreateContainerCmdImpl withEntrypoint(String... entrypoint) { - this.entrypoint = entrypoint; - return this; - } - - @Override - public String[] getDns() { - return hostConfig.getDns(); - } - - @Override - public CreateContainerCmdImpl withDns(String... dns) { - hostConfig.setDns(dns); - return this; - } - - @Override - public String getImage() { - return image; - } + @Override + public CreateContainerCmd withExtraHosts(String... extraHosts) { + this.hostConfig.setExtraHosts(extraHosts); + return this; + } + + @Override + public CreateContainerCmd withHostConfig(HostConfig hostConfig) { + checkNotNull(hostConfig, "no host config was specified"); + this.hostConfig = hostConfig; + return this; + } + + @Override + public CreateContainerCmdImpl withHostName(String hostName) { + this.hostName = hostName; + return this; + } - @Override + @Override public CreateContainerCmdImpl withImage(String image) { - this.image = image; - return this; - } + this.image = image; + return this; + } - @Override - @JsonIgnore - public Volume[] getVolumes() { - return volumes.getVolumes(); - } + @Override + public CreateContainerCmdImpl withLinks(Link... links) { + checkNotNull(links, "links was not specified"); + this.hostConfig.setLinks(links); + return this; + } - @Override - public CreateContainerCmdImpl withVolumes(Volume... volumes) { - this.volumes = new Volumes(volumes); - return this; - } + @Override + public CreateContainerCmd withLxcConf(LxcConf... lxcConf) { + checkNotNull(lxcConf, "lxcConf was not specified"); + this.hostConfig.setLxcConf(lxcConf); + return this; + } - @Override - public VolumesFrom[] getVolumesFrom() { - return hostConfig.getVolumesFrom(); - } + @Override + public CreateContainerCmdImpl withMemoryLimit(long memoryLimit) { + this.memoryLimit = memoryLimit; + return this; + } + + @Override + public CreateContainerCmdImpl withMemorySwap(long memorySwap) { + this.memorySwap = memorySwap; + return this; + } + + @Override + public CreateContainerCmdImpl withName(String name) { + checkNotNull(name, "name was not specified"); + this.name = name; + return this; + } + + @Override + public CreateContainerCmd withNetworkMode(String networkMode) { + checkNotNull(networkMode, "networkMode was not specified"); + this.hostConfig.setNetworkMode(networkMode); + return this; + } + + @Override + public CreateContainerCmd withPortBindings(PortBinding... portBindings) { + checkNotNull(portBindings, "portBindings was not specified"); + this.hostConfig.setPortBindings(new Ports(portBindings)); + return this; + } + + @Override + public CreateContainerCmd withPortBindings(Ports portBindings) { + checkNotNull(portBindings, "portBindings was not specified"); + this.hostConfig.setPortBindings(portBindings); + return this; + } + + @Override + public CreateContainerCmdImpl withPortSpecs(String... portSpecs) { + this.portSpecs = portSpecs; + return this; + } + + @Override + public CreateContainerCmd withPrivileged(boolean privileged) { + this.hostConfig.setPrivileged(privileged); + return this; + } + + @Override + public CreateContainerCmd withPublishAllPorts(boolean publishAllPorts) { + this.hostConfig.setPublishAllPorts(publishAllPorts); + return this; + } + + @Override + public CreateContainerCmd withRestartPolicy(RestartPolicy restartPolicy) { + this.hostConfig.setRestartPolicy(restartPolicy); + return this; + } + + @Override + public CreateContainerCmdImpl withStdInOnce(boolean stdInOnce) { + this.stdInOnce = stdInOnce; + return this; + } - @Override + @Override + public CreateContainerCmdImpl withStdinOpen(boolean stdinOpen) { + this.stdinOpen = stdinOpen; + return this; + } + + @Override + public CreateContainerCmdImpl withTty(boolean tty) { + this.tty = tty; + return this; + } + + @Override + public CreateContainerCmdImpl withUser(String user) { + this.user = user; + return this; + } + + @Override + public CreateContainerCmdImpl withVolumes(Volume... volumes) { + this.volumes = new Volumes(volumes); + return this; + } + + @Override public CreateContainerCmdImpl withVolumesFrom(VolumesFrom... volumesFrom) { - this.hostConfig.setVolumesFrom(volumesFrom); - return this; - } - - @Override - public HostConfig getHostConfig() { - return hostConfig; - } - - @Override - public CreateContainerCmd withHostConfig(HostConfig hostConfig) { - checkNotNull(hostConfig, "no host config was specified"); - this.hostConfig = hostConfig; - return this; - } - - @Override - public Capability[] getCapAdd() { - return hostConfig.getCapAdd(); - } - - @Override - public CreateContainerCmd withCapAdd(Capability... capAdd) { - hostConfig.setCapAdd(capAdd); - return this; - } - - @Override - public Capability[] getCapDrop() { - return hostConfig.getCapDrop(); - } - - @Override - public CreateContainerCmd withCapDrop(Capability... capDrop) { - hostConfig.setCapDrop(capDrop); - return this; - } - - @Override - public String toString() { - return new ToStringBuilder(this).append("create container ") - .append(name != null ? "name=" + name + " " : "") - .append(this) - .toString(); - } - - /** - * @throws NotFoundException No such container - * @throws ConflictException Named container already exists - */ - @Override - public CreateContainerResponse exec() throws NotFoundException, ConflictException { - return super.exec(); - } - -} + this.hostConfig.setVolumesFrom(volumesFrom); + return this; + } + + @Override + public CreateContainerCmdImpl withWorkingDir(String workingDir) { + this.workingDir = workingDir; + return this; + } + +} diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index ba05b268..f652c570 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -1,6 +1,7 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.api.model.Capability.*; +import static com.github.dockerjava.api.model.Capability.MKNOD; +import static com.github.dockerjava.api.model.Capability.NET_ADMIN; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -10,6 +11,8 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; import java.lang.reflect.Method; import java.security.SecureRandom; @@ -28,9 +31,12 @@ import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.model.Bind; +import com.github.dockerjava.api.model.Device; +import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Link; -import com.github.dockerjava.api.model.Links; +import com.github.dockerjava.api.model.Ports; +import com.github.dockerjava.api.model.RestartPolicy; import com.github.dockerjava.api.model.Volume; import com.github.dockerjava.api.model.VolumesFrom; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -99,7 +105,7 @@ public void createContainerWithVolume() throws DockerException { assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), contains("/var/log")); } - + @Test public void createContainerWithVolumesFrom() throws DockerException { @@ -111,11 +117,12 @@ public void createContainerWithVolumesFrom() throws DockerException { // create a running container with bind mounts CreateContainerResponse container1 = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999") - .withName(container1Name).exec(); + .withName(container1Name) + .withBinds(new Bind("/src/webapp1", volume1), new Bind("/src/webapp2", volume2)) + .exec(); LOG.info("Created container1 {}", container1.toString()); - dockerClient.startContainerCmd(container1.getId()).withBinds( - new Bind("/src/webapp1", volume1), new Bind("/src/webapp2", volume2)).exec(); + dockerClient.startContainerCmd(container1.getId()).exec(); LOG.info("Started container1 {}", container1.toString()); InspectContainerResponse inspectContainerResponse1 = dockerClient.inspectContainerCmd( @@ -238,7 +245,7 @@ public void createContainerWithLink() throws DockerException { assertThat(inspectContainerResponse1.getState().isRunning(), is(true)); HostConfig hostConfig = new HostConfig(); - hostConfig.setLinks(new Links(new Link("container1", "container1Link"))); + hostConfig.setLinks(new Link("container1", "container1Link")); CreateContainerResponse container2 = dockerClient .createContainerCmd("busybox").withName("container2").withHostConfig(hostConfig) .withCmd("env").exec(); @@ -247,7 +254,7 @@ public void createContainerWithLink() throws DockerException { InspectContainerResponse inspectContainerResponse2 = dockerClient .inspectContainerCmd(container2.getId()).exec(); - assertThat(inspectContainerResponse2.getHostConfig().getLinks().getLinks(), equalTo(new Link[] {new Link("container1","container1Link")})); + assertThat(inspectContainerResponse2.getHostConfig().getLinks(), equalTo(new Link[] {new Link("container1","container1Link")})); } @Test @@ -333,5 +340,174 @@ public void createContainerWithExtraHosts() throws DockerException { assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getExtraHosts()), containsInAnyOrder("dockerhost:127.0.0.1", "otherhost:10.0.0.1")); } + + @Test + public void createContainerWithDevices() throws DockerException { + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999") + .withDevices(new Device("rwm", "/dev/nulo", "/dev/zero")) + .exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + assertThat(Arrays.asList(inspectContainerResponse.getHostConfig() + .getDevices()), contains(new Device("rwm", "/dev/nulo", + "/dev/zero"))); + } + + @Test + public void createContainerWithPortBindings() throws DockerException { + + ExposedPort tcp22 = ExposedPort.tcp(22); + ExposedPort tcp23 = ExposedPort.tcp(23); + + Ports portBindings = new Ports(); + portBindings.bind(tcp22, Ports.Binding(11022)); + portBindings.bind(tcp23, Ports.Binding(11023)); + portBindings.bind(tcp23, Ports.Binding(11024)); + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("true") + .withExposedPorts(tcp22, tcp23) + .withPortBindings(portBindings) + .exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + assertThat(Arrays.asList(inspectContainerResponse.getConfig() + .getExposedPorts()), contains(tcp22, tcp23)); + + assertThat(inspectContainerResponse.getHostConfig().getPortBindings() + .getBindings().get(tcp22)[0], is(equalTo(Ports.Binding(11022)))); + + assertThat(inspectContainerResponse.getHostConfig().getPortBindings() + .getBindings().get(tcp23)[0], is(equalTo(Ports.Binding(11023)))); + + assertThat(inspectContainerResponse.getHostConfig().getPortBindings() + .getBindings().get(tcp23)[1], is(equalTo(Ports.Binding(11024)))); + + } + + @Test + public void createContainerWithLinking() throws DockerException { + + CreateContainerResponse container1 = dockerClient + .createContainerCmd("busybox") + .withCmd("sleep", "9999") + .withName("container1").exec(); + + LOG.info("Created container1 {}", container1.toString()); + assertThat(container1.getId(), not(isEmptyString())); + + dockerClient.startContainerCmd(container1.getId()).exec(); + + InspectContainerResponse inspectContainerResponse1 = dockerClient + .inspectContainerCmd(container1.getId()).exec(); + LOG.info("Container1 Inspect: {}", inspectContainerResponse1.toString()); + + assertThat(inspectContainerResponse1.getConfig(), is(notNullValue())); + assertThat(inspectContainerResponse1.getId(), not(isEmptyString())); + assertThat(inspectContainerResponse1.getId(), + startsWith(container1.getId())); + assertThat(inspectContainerResponse1.getName(), equalTo("/container1")); + assertThat(inspectContainerResponse1.getImageId(), not(isEmptyString())); + assertThat(inspectContainerResponse1.getState(), is(notNullValue())); + assertThat(inspectContainerResponse1.getState().isRunning(), is(true)); + + if (!inspectContainerResponse1.getState().isRunning()) { + assertThat(inspectContainerResponse1.getState().getExitCode(), + is(equalTo(0))); + } + + CreateContainerResponse container2 = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999") + .withName("container2") + .withLinks(new Link("container1", "container1Link")) + .exec(); + + LOG.info("Created container2 {}", container2.toString()); + assertThat(container2.getId(), not(isEmptyString())); + + InspectContainerResponse inspectContainerResponse2 = dockerClient + .inspectContainerCmd(container2.getId()).exec(); + LOG.info("Container2 Inspect: {}", inspectContainerResponse2.toString()); + + assertThat(inspectContainerResponse2.getConfig(), is(notNullValue())); + assertThat(inspectContainerResponse2.getId(), not(isEmptyString())); + assertThat(inspectContainerResponse2.getHostConfig(), + is(notNullValue())); + assertThat(inspectContainerResponse2.getHostConfig().getLinks(), + is(notNullValue())); + assertThat(inspectContainerResponse2.getHostConfig().getLinks(), equalTo(new Link[] { new Link("container1", + "container1Link") })); + assertThat(inspectContainerResponse2.getId(), + startsWith(container2.getId())); + assertThat(inspectContainerResponse2.getName(), equalTo("/container2")); + assertThat(inspectContainerResponse2.getImageId(), not(isEmptyString())); + + + } + + @Test + public void createContainerWithRestartPolicy() throws DockerException { + + RestartPolicy restartPolicy = RestartPolicy.onFailureRestart(5); + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox") + .withCmd("sleep", "9999") + .withRestartPolicy(restartPolicy) + .exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + assertThat(inspectContainerResponse.getHostConfig().getRestartPolicy(), + is(equalTo(restartPolicy))); + } + + /** + * This tests support for --net option for the docker run command: + * --net="bridge" Set the Network mode for the container 'bridge': creates a + * new network stack for the container on the docker bridge 'none': no + * networking for this container 'container:': reuses another container + * network stack 'host': use the host network stack inside the container. + * Note: the host mode gives the container full access to local system + * services such as D-bus and is therefore considered insecure. + */ + @Test + public void createContainerWithNetworkMode() throws DockerException { + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox") + .withCmd("true") + .withNetworkMode("host") + .exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + assertThat(inspectContainerResponse.getHostConfig().getNetworkMode(), + is(equalTo("host"))); + } + } diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index 37d805aa..f7cbe20c 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -253,7 +253,7 @@ public void startContainerWithConflictingPortBindings() } @Test - public void startContainerWithLinking() throws DockerException { + public void startContainerWithLinkingDeprecated() throws DockerException { CreateContainerResponse container1 = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999") @@ -302,8 +302,71 @@ public void startContainerWithLinking() throws DockerException { is(notNullValue())); assertThat(inspectContainerResponse2.getHostConfig().getLinks(), is(notNullValue())); - assertThat(inspectContainerResponse2.getHostConfig().getLinks() - .getLinks(), equalTo(new Link[] { new Link("container1", + assertThat(inspectContainerResponse2.getHostConfig().getLinks(), equalTo(new Link[] { new Link("container1", + "container1Link") })); + assertThat(inspectContainerResponse2.getId(), + startsWith(container2.getId())); + assertThat(inspectContainerResponse2.getName(), equalTo("/container2")); + assertThat(inspectContainerResponse2.getImageId(), not(isEmptyString())); + assertThat(inspectContainerResponse2.getState(), is(notNullValue())); + assertThat(inspectContainerResponse2.getState().isRunning(), is(true)); + + } + + + @Test + public void startContainerWithLinking() throws DockerException { + + CreateContainerResponse container1 = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999") + .withName("container1").exec(); + + LOG.info("Created container1 {}", container1.toString()); + assertThat(container1.getId(), not(isEmptyString())); + + dockerClient.startContainerCmd(container1.getId()).exec(); + + InspectContainerResponse inspectContainerResponse1 = dockerClient + .inspectContainerCmd(container1.getId()).exec(); + LOG.info("Container1 Inspect: {}", inspectContainerResponse1.toString()); + + assertThat(inspectContainerResponse1.getConfig(), is(notNullValue())); + assertThat(inspectContainerResponse1.getId(), not(isEmptyString())); + assertThat(inspectContainerResponse1.getId(), + startsWith(container1.getId())); + assertThat(inspectContainerResponse1.getName(), equalTo("/container1")); + assertThat(inspectContainerResponse1.getImageId(), not(isEmptyString())); + assertThat(inspectContainerResponse1.getState(), is(notNullValue())); + assertThat(inspectContainerResponse1.getState().isRunning(), is(true)); + + if (!inspectContainerResponse1.getState().isRunning()) { + assertThat(inspectContainerResponse1.getState().getExitCode(), + is(equalTo(0))); + } + + CreateContainerResponse container2 = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999") + .withName("container2") + .withLinks(new Link("container1", "container1Link")) + .exec(); + + LOG.info("Created container2 {}", container2.toString()); + assertThat(container2.getId(), not(isEmptyString())); + + dockerClient.startContainerCmd(container2.getId()) + .exec(); + + InspectContainerResponse inspectContainerResponse2 = dockerClient + .inspectContainerCmd(container2.getId()).exec(); + LOG.info("Container2 Inspect: {}", inspectContainerResponse2.toString()); + + assertThat(inspectContainerResponse2.getConfig(), is(notNullValue())); + assertThat(inspectContainerResponse2.getId(), not(isEmptyString())); + assertThat(inspectContainerResponse2.getHostConfig(), + is(notNullValue())); + assertThat(inspectContainerResponse2.getHostConfig().getLinks(), + is(notNullValue())); + assertThat(inspectContainerResponse2.getHostConfig().getLinks(), equalTo(new Link[] { new Link("container1", "container1Link") })); assertThat(inspectContainerResponse2.getId(), startsWith(container2.getId())); From d26024ca1a3a907b56b01425ba4cae9e13086ff7 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Tue, 7 Apr 2015 21:25:13 +0200 Subject: [PATCH 382/452] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c1b319a7..9be899ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ Change Log === Latest SNAPSHOT --- - +* [#193](https://github.com/docker-java/docker-java/pull/193) Add HostConfig related methods from start command to create command * [#192](https://github.com/docker-java/docker-java/pull/192) Added a Links constructor accepting a List object v1.1.0 From 2549f57afad7282691c3abad9df4baf449ba18c6 Mon Sep 17 00:00:00 2001 From: Emir Dizdarevic Date: Tue, 7 Apr 2015 22:50:50 +0200 Subject: [PATCH 383/452] * Fixed remove intermediate containers bug on build goal - it was always set to true --- .../java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index f67b1f9d..b5ea85ed 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -46,8 +46,8 @@ protected ResponseImpl execute(BuildImageCmd command) { if (command.hasNoCacheEnabled()) { webResource = webResource.queryParam("nocache", "true"); } - if (command.hasRemoveEnabled()) { - webResource = webResource.queryParam("rm", "true"); + if (!command.hasRemoveEnabled()) { + webResource = webResource.queryParam("rm", "false"); } if (command.isQuiet()) { webResource = webResource.queryParam("q", "true"); From 0f847c929535dfe73349e31c75a8604f39bc3eeb Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 8 Apr 2015 19:58:37 +0200 Subject: [PATCH 384/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9be899ac..b38c17d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ Change Log === Latest SNAPSHOT --- +* [#194](https://github.com/docker-java/docker-java/pull/194) Fixed remove intermediate containers bug on build goal * [#193](https://github.com/docker-java/docker-java/pull/193) Add HostConfig related methods from start command to create command * [#192](https://github.com/docker-java/docker-java/pull/192) Added a Links constructor accepting a List object From 6ab93b4337e9e489d92abc9cd25f782d0b17c870 Mon Sep 17 00:00:00 2001 From: Chun Chen Date: Mon, 13 Apr 2015 12:58:55 +0800 Subject: [PATCH 385/452] Allow for null bindings --- .../github/dockerjava/api/model/Ports.java | 40 ++++++++++++------- .../api/model/Ports_SerializingTest.java | 17 ++++++++ .../api/model/Ports_addBindingsTest.java | 9 +++++ 3 files changed, 52 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/model/Ports.java b/src/main/java/com/github/dockerjava/api/model/Ports.java index d7c8a324..0c2df94a 100644 --- a/src/main/java/com/github/dockerjava/api/model/Ports.java +++ b/src/main/java/com/github/dockerjava/api/model/Ports.java @@ -75,7 +75,11 @@ public void bind(ExposedPort exposedPort, Binding binding) { Binding[] bindings = ports.get(exposedPort); ports.put(exposedPort, (Binding[]) ArrayUtils.add(bindings, binding)); } else { - ports.put(exposedPort, new Binding[]{binding}); + if (binding == null) { + ports.put(exposedPort, null); + } else { + ports.put(exposedPort, new Binding[]{binding}); + } } } @@ -282,12 +286,16 @@ public Ports deserialize(JsonParser jsonParser, DeserializationContext deseriali Map.Entry portNode = it.next(); JsonNode bindingsArray = portNode.getValue(); - for (int i = 0; i < bindingsArray.size(); i++) { - JsonNode bindingNode = bindingsArray.get(i); - if (!bindingNode.equals(NullNode.getInstance())) { - String hostIp = bindingNode.get("HostIp").textValue(); - int hostPort = bindingNode.get("HostPort").asInt(); - out.bind(ExposedPort.parse(portNode.getKey()), new Binding(hostIp, hostPort)); + if (bindingsArray.equals(NullNode.getInstance())) { + out.bind(ExposedPort.parse(portNode.getKey()), null); + } else { + for (int i = 0; i < bindingsArray.size(); i++) { + JsonNode bindingNode = bindingsArray.get(i); + if (!bindingNode.equals(NullNode.getInstance())) { + String hostIp = bindingNode.get("HostIp").textValue(); + int hostPort = bindingNode.get("HostPort").asInt(); + out.bind(ExposedPort.parse(portNode.getKey()), new Binding(hostIp, hostPort)); + } } } } @@ -304,14 +312,18 @@ public void serialize(Ports portBindings, JsonGenerator jsonGen, jsonGen.writeStartObject(); for(Entry entry : portBindings.getBindings().entrySet()){ jsonGen.writeFieldName(entry.getKey().toString()); - jsonGen.writeStartArray(); - for (Binding binding : entry.getValue()) { - jsonGen.writeStartObject(); - jsonGen.writeStringField("HostIp", binding.getHostIp() == null ? "" : binding.getHostIp()); - jsonGen.writeStringField("HostPort", binding.getHostPort() == null ? "" : binding.getHostPort().toString()); - jsonGen.writeEndObject(); + if (entry.getValue() != null) { + jsonGen.writeStartArray(); + for (Binding binding : entry.getValue()) { + jsonGen.writeStartObject(); + jsonGen.writeStringField("HostIp", binding.getHostIp() == null ? "" : binding.getHostIp()); + jsonGen.writeStringField("HostPort", binding.getHostPort() == null ? "" : binding.getHostPort().toString()); + jsonGen.writeEndObject(); + } + jsonGen.writeEndArray(); + } else { + jsonGen.writeNull(); } - jsonGen.writeEndArray(); } jsonGen.writeEndObject(); } diff --git a/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java b/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java index 25931069..9190eefd 100644 --- a/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java +++ b/src/test/java/com/github/dockerjava/api/model/Ports_SerializingTest.java @@ -13,6 +13,7 @@ public class Ports_SerializingTest { private final ObjectMapper objectMapper = new ObjectMapper(); private final String jsonWithDoubleBindingForOnePort = "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"},{\"HostIp\":\"10.0.0.2\",\"HostPort\":\"80\"}]}"; + private final String jsonWithNullBindingForOnePort = "{\"80/tcp\":null}"; @Test public void deserializingPortWithMultipleBindings() throws Exception { @@ -39,4 +40,20 @@ public void serializingEmptyBinding() throws Exception { Ports ports = new Ports(ExposedPort.tcp(80), new Binding(null, null)); assertEquals(objectMapper.writeValueAsString(ports), "{\"80/tcp\":[{\"HostIp\":\"\",\"HostPort\":\"\"}]}"); } + + @Test + public void deserializingPortWithNullBindings() throws Exception { + Ports ports = objectMapper.readValue(jsonWithNullBindingForOnePort, Ports.class); + Map map = ports.getBindings(); + assertEquals(map.size(), 1); + + assertEquals(map.get(ExposedPort.tcp(80)), null); + } + + @Test + public void serializingWithNullBindings() throws Exception { + Ports ports = new Ports(); + ports.bind(ExposedPort.tcp(80), null); + assertEquals(objectMapper.writeValueAsString(ports), jsonWithNullBindingForOnePort); + } } diff --git a/src/test/java/com/github/dockerjava/api/model/Ports_addBindingsTest.java b/src/test/java/com/github/dockerjava/api/model/Ports_addBindingsTest.java index 20e47df9..18c7f0f0 100644 --- a/src/test/java/com/github/dockerjava/api/model/Ports_addBindingsTest.java +++ b/src/test/java/com/github/dockerjava/api/model/Ports_addBindingsTest.java @@ -1,6 +1,7 @@ package com.github.dockerjava.api.model; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; import java.util.Map; @@ -54,4 +55,12 @@ public void addTwoBindingsForSameExposedPort() { assertEquals(bindings.get(TCP_80), new Binding[] { BINDING_8080, BINDING_9090 }); } + @Test + public void addNullBindings() { + ports.add(new PortBinding(null, TCP_80)); + Map bindings = ports.getBindings(); + // one key with two values + assertEquals(bindings.size(), 1); + assertEquals(bindings.get(TCP_80), null); + } } From 80093ca8e74503d5e34c393d138da9c97c47f540 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 14 Apr 2015 21:42:33 +0200 Subject: [PATCH 386/452] Set to version 1.2.0-SNAPSHOT --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 957c157c..1dae4be5 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 1.1.1-SNAPSHOT + 1.2.0-SNAPSHOT docker-java https://github.com/docker-java/docker-java From 8e2f6b3842209580a8f38592c80bde32f599821e Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 14 Apr 2015 21:44:14 +0200 Subject: [PATCH 387/452] [maven-release-plugin] prepare release docker-java-1.2.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1dae4be5..95938ea6 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 1.2.0-SNAPSHOT + 1.2.0 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-1.2.0 From 33b0ff5a5fec004c3392326383de8e03ed6e69cf Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 14 Apr 2015 21:44:20 +0200 Subject: [PATCH 388/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 95938ea6..1279f9c1 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 1.2.0 + 1.2.1-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-1.2.0 + HEAD From 065cd78ca16173657830ea8b72d6c13d6defdb5b Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Tue, 14 Apr 2015 21:52:18 +0200 Subject: [PATCH 389/452] Update CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b38c17d1..b7a38646 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ Change Log === Latest SNAPSHOT --- + +v1.2.0 +--- * [#194](https://github.com/docker-java/docker-java/pull/194) Fixed remove intermediate containers bug on build goal * [#193](https://github.com/docker-java/docker-java/pull/193) Add HostConfig related methods from start command to create command * [#192](https://github.com/docker-java/docker-java/pull/192) Added a Links constructor accepting a List object From bcdfd46c5728b0a51686727725236eb2d1c31720 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sat, 25 Apr 2015 12:51:21 +0100 Subject: [PATCH 390/452] Created FrameReader to assist reading frames from attach commands. --- .../github/dockerjava/api/model/Frame.java | 47 ++++++++++++++ .../dockerjava/api/model/StreamType.java | 7 +++ .../dockerjava/core/command/FrameReader.java | 62 +++++++++++++++++++ .../core/command/FrameReaderTest.java | 57 +++++++++++++++++ 4 files changed, 173 insertions(+) create mode 100644 src/main/java/com/github/dockerjava/api/model/Frame.java create mode 100644 src/main/java/com/github/dockerjava/api/model/StreamType.java create mode 100644 src/main/java/com/github/dockerjava/core/command/FrameReader.java create mode 100644 src/test/java/com/github/dockerjava/core/command/FrameReaderTest.java diff --git a/src/main/java/com/github/dockerjava/api/model/Frame.java b/src/main/java/com/github/dockerjava/api/model/Frame.java new file mode 100644 index 00000000..bf77a133 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/Frame.java @@ -0,0 +1,47 @@ +package com.github.dockerjava.api.model; + +import java.util.Arrays; + +/** + * Represents a logging frame. + */ +public class Frame { + private final StreamType streamType; + private final byte[] payload; + + public Frame(StreamType streamType, byte[] payload) { + this.streamType = streamType; + this.payload = payload; + } + + public StreamType getStreamType() { + return streamType; + } + + public byte[] getPayload() { + return payload; + } + + @Override + public String toString() { + return String.format("%s %s", streamType, new String(payload)); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Frame frame = (Frame) o; + + return Arrays.equals(payload, frame.payload) && streamType == frame.streamType; + + } + + @Override + public int hashCode() { + int result = streamType.hashCode(); + result = 31 * result + Arrays.hashCode(payload); + return result; + } +} diff --git a/src/main/java/com/github/dockerjava/api/model/StreamType.java b/src/main/java/com/github/dockerjava/api/model/StreamType.java new file mode 100644 index 00000000..eb11c553 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/StreamType.java @@ -0,0 +1,7 @@ +package com.github.dockerjava.api.model; + +public enum StreamType { + STDIN, + STDOUT, + STDERR +} diff --git a/src/main/java/com/github/dockerjava/core/command/FrameReader.java b/src/main/java/com/github/dockerjava/core/command/FrameReader.java new file mode 100644 index 00000000..22a76de1 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/FrameReader.java @@ -0,0 +1,62 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.StreamType; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Breaks the input into frame. Similar to how a buffered reader would readLies. + *

+ * See: {@link }http://docs.docker.com/v1.6/reference/api/docker_remote_api_v1.13/#attach-to-a-container} + */ +public class FrameReader { + + private static final int HEADER_SIZE = 8; + private final InputStream inputStream; + + public FrameReader(InputStream inputStream) { + this.inputStream = inputStream; + } + + private static StreamType streamType(byte streamType) { + switch (streamType) { + case 0: + return StreamType.STDIN; + case 1: + return StreamType.STDOUT; + case 2: + return StreamType.STDERR; + default: + throw new IllegalArgumentException("invalid streamType"); + } + } + + /** + * @return A frame, or null if no more frames. + */ + public Frame readFrame() throws IOException { + byte[] header = new byte[HEADER_SIZE]; + int headerSize = inputStream.read(header); + + if (headerSize == -1) { + return null; + } + + if (headerSize != HEADER_SIZE) { + throw new IOException(String.format("header must be %d bytes long, but was %d", HEADER_SIZE, headerSize)); + } + + int frameSize = (header[4] << 24) + (header[5] << 16) + (header[6] << HEADER_SIZE) + header[7]; + int payloadSize = frameSize - header.length; + + byte[] payload = new byte[payloadSize]; + int actualPayloadSize = inputStream.read(payload); + if (actualPayloadSize != payloadSize) { + throw new IOException(String.format("payload must be %d bytes long, but was %d", payloadSize, actualPayloadSize)); + } + + return new Frame(streamType(header[0]), payload); + } +} diff --git a/src/test/java/com/github/dockerjava/core/command/FrameReaderTest.java b/src/test/java/com/github/dockerjava/core/command/FrameReaderTest.java new file mode 100644 index 00000000..dc2d4c8f --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/command/FrameReaderTest.java @@ -0,0 +1,57 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.StreamType; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + +public class FrameReaderTest { + public static final int HEADER_SIZE = 8; + private final List bytes = new ArrayList<>(); + private final InputStream inputStream = new InputStream() { + @Override + public int read() throws IOException { + return bytes.isEmpty() ? -1 : bytes.remove(0); + } + }; + private final FrameReader frameReader = new FrameReader(inputStream); + + @Test + public void endOfStreamReturnsNull() throws Exception { + assertNull(nextFrame()); + } + + @Test + public void stdInBytesFrameReturnsFrame() throws Exception { + assertEquals(nextFrame(0, 0, 0, 0, 0, 0, 0, HEADER_SIZE), new Frame(StreamType.STDIN, new byte[0])); + } + + private Frame nextFrame(int... bytes) throws IOException { + setBytes(bytes); + return frameReader.readFrame(); + } + + @Test + public void stdOutBytesFrameReturnsFrame() throws Exception { + assertEquals(nextFrame(1, 0, 0, 0, 0, 0, 0, HEADER_SIZE), new Frame(StreamType.STDOUT, new byte[0])); + } + + @Test + public void stdErrBytesFrameReturnsFrame() throws Exception { + assertEquals(nextFrame(2, 0, 0, 0, 0, 0, 0, HEADER_SIZE), new Frame(StreamType.STDERR, new byte[0])); + } + + private void setBytes(int... bytes) { + this.bytes.clear(); + for (int aByte : bytes) { + this.bytes.add(aByte); + } + } +} \ No newline at end of file From 2b4d5ff0026b3e4739f94a9ca57c4a620c21c709 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sat, 25 Apr 2015 13:11:56 +0100 Subject: [PATCH 391/452] Created FrameReader to assist reading frames from attach commands. --- .../github/dockerjava/api/command/LogContainerCmd.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java index 74512b39..05e10855 100644 --- a/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java @@ -1,9 +1,9 @@ package com.github.dockerjava.api.command; -import java.io.InputStream; - import com.github.dockerjava.api.NotFoundException; +import java.io.InputStream; + /** * Get container logs * @@ -18,6 +18,10 @@ * Defaults to false. * @param tail * - `all` or ``, Output specified number of lines at the end of logs + * + * Consider wrapping any input stream you get with a frame reader to make reading frame easier. + * + * @see com.github.dockerjava.core.command.FrameReader */ public interface LogContainerCmd extends DockerCmd{ From 83943eb420b51c26802e05f386f7937249be908d Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sat, 25 Apr 2015 13:25:41 +0100 Subject: [PATCH 392/452] Make FrameReader Closable. --- .../com/github/dockerjava/core/command/FrameReader.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/command/FrameReader.java b/src/main/java/com/github/dockerjava/core/command/FrameReader.java index 22a76de1..3dae2dd5 100644 --- a/src/main/java/com/github/dockerjava/core/command/FrameReader.java +++ b/src/main/java/com/github/dockerjava/core/command/FrameReader.java @@ -11,7 +11,7 @@ *

* See: {@link }http://docs.docker.com/v1.6/reference/api/docker_remote_api_v1.13/#attach-to-a-container} */ -public class FrameReader { +public class FrameReader implements AutoCloseable { private static final int HEADER_SIZE = 8; private final InputStream inputStream; @@ -48,7 +48,7 @@ public Frame readFrame() throws IOException { throw new IOException(String.format("header must be %d bytes long, but was %d", HEADER_SIZE, headerSize)); } - int frameSize = (header[4] << 24) + (header[5] << 16) + (header[6] << HEADER_SIZE) + header[7]; + int frameSize = (header[4] << 24) + (header[5] << 16) + (header[6] << 8) + header[7]; int payloadSize = frameSize - header.length; byte[] payload = new byte[payloadSize]; @@ -59,4 +59,9 @@ public Frame readFrame() throws IOException { return new Frame(streamType(header[0]), payload); } + + @Override + public void close() throws Exception { + inputStream.close(); + } } From 538d465d4bdf65997907a73c4825f83eded7d005 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sat, 25 Apr 2015 13:37:18 +0100 Subject: [PATCH 393/452] Made exception more specifi --- .../java/com/github/dockerjava/core/command/FrameReader.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/core/command/FrameReader.java b/src/main/java/com/github/dockerjava/core/command/FrameReader.java index 3dae2dd5..ac356da3 100644 --- a/src/main/java/com/github/dockerjava/core/command/FrameReader.java +++ b/src/main/java/com/github/dockerjava/core/command/FrameReader.java @@ -61,7 +61,7 @@ public Frame readFrame() throws IOException { } @Override - public void close() throws Exception { + public void close() throws IOException { inputStream.close(); } } From 42514449ba9f343282125368fe3466109bed9601 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sat, 25 Apr 2015 23:56:59 +0100 Subject: [PATCH 394/452] Trim toString. --- src/main/java/com/github/dockerjava/api/model/Frame.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/api/model/Frame.java b/src/main/java/com/github/dockerjava/api/model/Frame.java index bf77a133..3860a5db 100644 --- a/src/main/java/com/github/dockerjava/api/model/Frame.java +++ b/src/main/java/com/github/dockerjava/api/model/Frame.java @@ -24,7 +24,7 @@ public byte[] getPayload() { @Override public String toString() { - return String.format("%s %s", streamType, new String(payload)); + return String.format("%s: %s", streamType, new String(payload).trim()); } @Override From 559e6c18d1051e2a4329f1e2b1d43bb965ced43f Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sat, 25 Apr 2015 23:57:53 +0100 Subject: [PATCH 395/452] Fixed bug in header. --- .../java/com/github/dockerjava/core/command/FrameReader.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/command/FrameReader.java b/src/main/java/com/github/dockerjava/core/command/FrameReader.java index ac356da3..c3979146 100644 --- a/src/main/java/com/github/dockerjava/core/command/FrameReader.java +++ b/src/main/java/com/github/dockerjava/core/command/FrameReader.java @@ -48,8 +48,7 @@ public Frame readFrame() throws IOException { throw new IOException(String.format("header must be %d bytes long, but was %d", HEADER_SIZE, headerSize)); } - int frameSize = (header[4] << 24) + (header[5] << 16) + (header[6] << 8) + header[7]; - int payloadSize = frameSize - header.length; + int payloadSize = ((header[4] & 0xff) << 24) + ((header[5] & 0xff) << 16) + ((header[6] & 0xff) << 8) + (header[7] & 0xff); byte[] payload = new byte[payloadSize]; int actualPayloadSize = inputStream.read(payload); From 1e1e7e87b249ee524e9d22cb28d67739089ba1ca Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 26 Apr 2015 00:02:14 +0100 Subject: [PATCH 396/452] Updated FrameReaderTest. --- .../com/github/dockerjava/core/command/FrameReaderTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/FrameReaderTest.java b/src/test/java/com/github/dockerjava/core/command/FrameReaderTest.java index dc2d4c8f..2b5e2b64 100644 --- a/src/test/java/com/github/dockerjava/core/command/FrameReaderTest.java +++ b/src/test/java/com/github/dockerjava/core/command/FrameReaderTest.java @@ -30,7 +30,7 @@ public void endOfStreamReturnsNull() throws Exception { @Test public void stdInBytesFrameReturnsFrame() throws Exception { - assertEquals(nextFrame(0, 0, 0, 0, 0, 0, 0, HEADER_SIZE), new Frame(StreamType.STDIN, new byte[0])); + assertEquals(nextFrame(0, 0, 0, 0, 0, 0, 0, 0), new Frame(StreamType.STDIN, new byte[0])); } private Frame nextFrame(int... bytes) throws IOException { @@ -40,12 +40,12 @@ private Frame nextFrame(int... bytes) throws IOException { @Test public void stdOutBytesFrameReturnsFrame() throws Exception { - assertEquals(nextFrame(1, 0, 0, 0, 0, 0, 0, HEADER_SIZE), new Frame(StreamType.STDOUT, new byte[0])); + assertEquals(nextFrame(1, 0, 0, 0, 0, 0, 0, 0), new Frame(StreamType.STDOUT, new byte[0])); } @Test public void stdErrBytesFrameReturnsFrame() throws Exception { - assertEquals(nextFrame(2, 0, 0, 0, 0, 0, 0, HEADER_SIZE), new Frame(StreamType.STDERR, new byte[0])); + assertEquals(nextFrame(2, 0, 0, 0, 0, 0, 0, 0), new Frame(StreamType.STDERR, new byte[0])); } private void setBytes(int... bytes) { From 15b388ea15255d9d69baea83093fd8f83acf59d6 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 27 Apr 2015 21:29:56 +0200 Subject: [PATCH 397/452] Added 'MacAddress' option to create command --- .../api/command/CreateContainerCmd.java | 9 +++++-- .../core/command/CreateContainerCmdImpl.java | 24 ++++++++++++++----- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java index a2a6dc85..708e3139 100644 --- a/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/CreateContainerCmd.java @@ -14,6 +14,7 @@ import com.github.dockerjava.api.model.RestartPolicy; import com.github.dockerjava.api.model.Volume; import com.github.dockerjava.api.model.VolumesFrom; +import com.github.dockerjava.core.command.CreateContainerCmdImpl; public interface CreateContainerCmd extends DockerCmd{ @@ -63,6 +64,8 @@ public CreateContainerResponse exec() throws NotFoundException, public Link[] getLinks(); public LxcConf[] getLxcConf(); + + public String getMacAddress(); public long getMemoryLimit(); @@ -92,7 +95,7 @@ public CreateContainerResponse exec() throws NotFoundException, public boolean isAttachStdout(); - public boolean isDisableNetwork(); + public boolean isNetworkDisabled(); public Boolean isPrivileged(); @@ -139,7 +142,7 @@ public CreateContainerResponse exec() throws NotFoundException, */ public CreateContainerCmd withDevices(Device... devices); - public CreateContainerCmd withDisableNetwork(boolean disableNetwork); + public CreateContainerCmd withNetworkDisabled(boolean disableNetwork); /** * Set custom DNS servers @@ -237,4 +240,6 @@ public CreateContainerResponse exec() throws NotFoundException, public CreateContainerCmd withWorkingDir(String workingDir); + public CreateContainerCmd withMacAddress(String macAddress); + } diff --git a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java index 5afd0dbb..18b089d4 100644 --- a/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java @@ -74,8 +74,10 @@ public class CreateContainerCmdImpl extends private Volumes volumes = new Volumes(); @JsonProperty("WorkingDir") private String workingDir = ""; - @JsonProperty("DisableNetwork") - private boolean disableNetwork = false; + @JsonProperty("MacAddress") + private String macAddress; + @JsonProperty("NetworkDisabled") + private boolean networkDisabled = false; @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts = new ExposedPorts(); @JsonProperty("HostConfig") @@ -196,6 +198,10 @@ public Link[] getLinks() { public LxcConf[] getLxcConf() { return hostConfig.getLxcConf(); } + + public String getMacAddress() { + return macAddress; + } @Override public long getMemoryLimit() { @@ -273,8 +279,8 @@ public boolean isAttachStdout() { } @Override - public boolean isDisableNetwork() { - return disableNetwork; + public boolean isNetworkDisabled() { + return networkDisabled; } @Override @@ -372,8 +378,8 @@ public CreateContainerCmd withDevices(Device... devices) { } @Override - public CreateContainerCmdImpl withDisableNetwork(boolean disableNetwork) { - this.disableNetwork = disableNetwork; + public CreateContainerCmdImpl withNetworkDisabled(boolean disableNetwork) { + this.networkDisabled = disableNetwork; return this; } @@ -445,6 +451,12 @@ public CreateContainerCmd withLxcConf(LxcConf... lxcConf) { this.hostConfig.setLxcConf(lxcConf); return this; } + + @Override + public CreateContainerCmdImpl withMacAddress(String macAddress) { + this.macAddress = macAddress; + return this; + } @Override public CreateContainerCmdImpl withMemoryLimit(long memoryLimit) { From e3e6ce87ff59616347008398a6daa8b8beeae063 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Mon, 27 Apr 2015 21:42:02 +0200 Subject: [PATCH 398/452] Added 'MacAddress' to inspect container response. --- .../dockerjava/api/model/ContainerConfig.java | 7 +++++++ .../command/CreateContainerCmdImplTest.java | 20 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/main/java/com/github/dockerjava/api/model/ContainerConfig.java b/src/main/java/com/github/dockerjava/api/model/ContainerConfig.java index b15d5ca8..dcb1256b 100644 --- a/src/main/java/com/github/dockerjava/api/model/ContainerConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/ContainerConfig.java @@ -51,6 +51,9 @@ public class ContainerConfig { @JsonProperty("Image") private String image; + @JsonProperty("MacAddress") + private String macAddress; + @JsonProperty("Memory") private long memoryLimit = 0; @@ -124,6 +127,10 @@ public boolean isStdinOpen() { public boolean isStdInOnce() { return stdInOnce; } + + public String getMacAddress() { + return macAddress; + } public long getMemoryLimit() { return memoryLimit; diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index f652c570..53337129 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -510,4 +510,24 @@ public void createContainerWithNetworkMode() throws DockerException { is(equalTo("host"))); } + @Test + public void createContainerWithMacAddress() throws DockerException { + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox") + .withMacAddress("00:80:41:ae:fd:7e") + .withCmd("true") + .exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + assertEquals(inspectContainerResponse.getConfig().getMacAddress(), + "00:80:41:ae:fd:7e"); + } + } From 8534b78f68653196f441c9c756df5bb3c47e8b4e Mon Sep 17 00:00:00 2001 From: Emir Dizdarevic Date: Tue, 28 Apr 2015 13:55:02 +0200 Subject: [PATCH 399/452] * Added support to use Auth for mutiple repos during build --- .../dockerjava/core/AuthConfigFile.java | 10 +++++++ .../dockerjava/core/DockerClientConfig.java | 19 +++++++++++++ .../dockerjava/core/DockerClientImpl.java | 28 +++++++++++++------ 3 files changed, 48 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/AuthConfigFile.java b/src/main/java/com/github/dockerjava/core/AuthConfigFile.java index 24c7aa5c..862259a8 100644 --- a/src/main/java/com/github/dockerjava/core/AuthConfigFile.java +++ b/src/main/java/com/github/dockerjava/core/AuthConfigFile.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Map; +import com.github.dockerjava.api.model.AuthConfigurations; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; @@ -50,6 +51,15 @@ public AuthConfig resolveAuthConfig(String hostname) { return null; } + public AuthConfigurations getAuthConfigurations() { + final AuthConfigurations authConfigurations = new AuthConfigurations(); + for(Map.Entry authConfigEntry : authConfigMap.entrySet()) { + authConfigurations.addConfig(authConfigEntry.getValue()); + } + + return authConfigurations; + } + @Override public int hashCode() { final int prime = 31; diff --git a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java index 05491ec6..7e0b57b0 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientConfig.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientConfig.java @@ -14,6 +14,7 @@ import com.github.dockerjava.api.DockerClientException; import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.AuthConfigurations; import com.github.dockerjava.core.NameParser.HostnameReposName; import com.github.dockerjava.core.NameParser.ReposTag; @@ -310,6 +311,24 @@ public AuthConfig effectiveAuthConfig(String imageName) { return authConfig; } + public AuthConfigurations getAuthConfigurations() { + String dockerCfgFile = getDockerCfgPath(); + if (dockerCfgFile != null) { + AuthConfigFile authConfigFile; + try { + authConfigFile = AuthConfigFile.loadConfig(new File( + dockerCfgFile)); + } catch (IOException e) { + throw new DockerClientException( + "Failed to parse dockerCfgFile", e); + } + + return authConfigFile.getAuthConfigurations(); + } + + return new AuthConfigurations(); + } + @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 534c58eb..7e96225f 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -10,12 +10,13 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.*; import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.AuthConfigurations; import com.github.dockerjava.api.model.Identifier; import com.github.dockerjava.core.command.*; /** * @author Konstantin Pelykh (kpelykh@gmail.com) - * + * * @see "https://github.com/docker/docker/blob/master/api/client/commands.go" */ public class DockerClientImpl implements Closeable, DockerClient { @@ -291,20 +292,29 @@ public CommitCmd commitCmd(String containerId) { @Override public BuildImageCmd buildImageCmd() { - return new BuildImageCmdImpl(getDockerCmdExecFactory() - .createBuildImageCmdExec()); + return augmentBuildImageCmd(new BuildImageCmdImpl(getDockerCmdExecFactory() + .createBuildImageCmdExec())); } @Override public BuildImageCmd buildImageCmd(File dockerFileOrFolder) { - return new BuildImageCmdImpl(getDockerCmdExecFactory() - .createBuildImageCmdExec(), dockerFileOrFolder); + return augmentBuildImageCmd(new BuildImageCmdImpl(getDockerCmdExecFactory() + .createBuildImageCmdExec(), dockerFileOrFolder)); } - @Override - public BuildImageCmd buildImageCmd(InputStream tarInputStream) { - return new BuildImageCmdImpl(getDockerCmdExecFactory() - .createBuildImageCmdExec(), tarInputStream); + @Override + public BuildImageCmd buildImageCmd(InputStream tarInputStream) { + return augmentBuildImageCmd(new BuildImageCmdImpl(getDockerCmdExecFactory() + .createBuildImageCmdExec(), tarInputStream)); + } + + private BuildImageCmd augmentBuildImageCmd(BuildImageCmd buildImageCmd) { + final AuthConfigurations authConfigurations = dockerClientConfig.getAuthConfigurations(); + if (!authConfigurations.getConfigs().isEmpty()) { + buildImageCmd.withBuildAuthConfigs(authConfigurations); + } + + return buildImageCmd; } @Override From 2bc290dd962e32c0c3c1222248311f134ec5a1b9 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 28 Apr 2015 17:36:45 +0200 Subject: [PATCH 400/452] Fix createContainerWithEnv test --- .../dockerjava/core/command/CreateContainerCmdImplTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index 53337129..752f0aef 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -172,8 +172,7 @@ public void createContainerWithEnv() throws DockerException { assertThat( Arrays.asList(inspectContainerResponse.getConfig().getEnv()), - containsInAnyOrder("VARIABLE=success", - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")); + containsInAnyOrder("VARIABLE=success")); dockerClient.startContainerCmd(container.getId()).exec(); From 0d9e8a44a67bf59c4359af81528b2c7262aef4ac Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Tue, 28 Apr 2015 17:40:29 +0200 Subject: [PATCH 401/452] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7a38646..6ee13f6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ Change Log === Latest SNAPSHOT --- +* [#203](https://github.com/docker-java/docker-java/issues/203) Missing 'MacAddress' option in create container command +* [#197](https://github.com/docker-java/docker-java/pull/197) Allow for null bindings v1.2.0 --- From db7040fd0d549771afe550d3a61fafd2714fb8d3 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Tue, 28 Apr 2015 21:43:11 +0200 Subject: [PATCH 402/452] Fix issue #202 --- .../java/com/github/dockerjava/core/DockerClientBuilder.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java b/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java index 155b36be..4aa7d5ac 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientBuilder.java @@ -36,6 +36,9 @@ public static DockerClientBuilder getInstance(String serverUrl) { } public static DockerCmdExecFactory getDefaultDockerCmdExecFactory() { + // clearing the cache is needed because otherwise we will get + // the same DockerCmdExecFactory instance each time + serviceLoader.reload(); if(!serviceLoader.iterator().hasNext()) { throw new RuntimeException("Fatal: Can't find any implementation of '" + DockerCmdExecFactory.class.getName() + "' in the current classpath."); } From fdb9e77ef0c1aee95293f9f17a896a59747b380c Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sat, 2 May 2015 00:33:14 +0200 Subject: [PATCH 403/452] Fix issue #205 --- .../api/command/InspectContainerResponse.java | 6 +- .../dockerjava/api/model/AccessMode.java | 8 ++ .../com/github/dockerjava/api/model/Bind.java | 6 +- .../github/dockerjava/api/model/Volume.java | 62 +--------- .../github/dockerjava/api/model/VolumeRW.java | 115 ++++++++++++++++++ .../github/dockerjava/api/model/Volumes.java | 7 +- .../dockerjava/api/model/VolumesRW.java | 57 +++++++++ .../dockerjava/api/model/VolumeTest.java | 4 +- .../command/CreateContainerCmdImplTest.java | 38 +++++- .../command/StartContainerCmdImplTest.java | 5 +- 10 files changed, 235 insertions(+), 73 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/VolumeRW.java create mode 100644 src/main/java/com/github/dockerjava/api/model/VolumesRW.java diff --git a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java index c86e13c5..f9565689 100644 --- a/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java +++ b/src/main/java/com/github/dockerjava/api/command/InspectContainerResponse.java @@ -77,7 +77,7 @@ public class InspectContainerResponse { private VolumeBinds volumes; @JsonProperty("VolumesRW") - private Volumes volumesRW; + private VolumesRW volumesRW; public String getId() { return id; @@ -125,8 +125,8 @@ public VolumeBind[] getVolumes() { } @JsonIgnore - public Volume[] getVolumesRW() { - return volumesRW.getVolumes(); + public VolumeRW[] getVolumesRW() { + return volumesRW.getVolumesRW(); } public String getHostnamePath() { diff --git a/src/main/java/com/github/dockerjava/api/model/AccessMode.java b/src/main/java/com/github/dockerjava/api/model/AccessMode.java index a1f53f57..a893e7f3 100644 --- a/src/main/java/com/github/dockerjava/api/model/AccessMode.java +++ b/src/main/java/com/github/dockerjava/api/model/AccessMode.java @@ -15,6 +15,14 @@ public enum AccessMode { * The default {@link AccessMode}: {@link #rw} */ public static final AccessMode DEFAULT = rw; + + public static final AccessMode fromBoolean(boolean accessMode) { + return accessMode ? rw : ro; + } + + public final boolean toBoolean() { + return this.equals(AccessMode.rw) ? true: false; + } } diff --git a/src/main/java/com/github/dockerjava/api/model/Bind.java b/src/main/java/com/github/dockerjava/api/model/Bind.java index eb0b8fd4..0071bff9 100644 --- a/src/main/java/com/github/dockerjava/api/model/Bind.java +++ b/src/main/java/com/github/dockerjava/api/model/Bind.java @@ -53,11 +53,11 @@ public static Bind parse(String serialized) { String[] parts = serialized.split(":"); switch (parts.length) { case 2: { - return new Bind(parts[0], Volume.parse(parts[1])); + return new Bind(parts[0], new Volume(parts[1])); } case 3: { AccessMode accessMode = AccessMode.valueOf(parts[2].toLowerCase()); - return new Bind(parts[0], Volume.parse(parts[1]), accessMode); + return new Bind(parts[0], new Volume(parts[1]), accessMode); } default: { throw new IllegalArgumentException(); @@ -96,7 +96,7 @@ public int hashCode() { */ @Override public String toString() { - return path + ":" + volume.toString() + ":" + accessMode.toString(); + return path + ":" + volume.getPath() + ":" + accessMode.toString(); } } diff --git a/src/main/java/com/github/dockerjava/api/model/Volume.java b/src/main/java/com/github/dockerjava/api/model/Volume.java index 3ec5e24c..131a9a56 100644 --- a/src/main/java/com/github/dockerjava/api/model/Volume.java +++ b/src/main/java/com/github/dockerjava/api/model/Volume.java @@ -24,42 +24,18 @@ * * @see Bind */ -@JsonDeserialize(using = Volume.Deserializer.class) -@JsonSerialize(using = Volume.Serializer.class) public class Volume { private String path; - private AccessMode accessMode = AccessMode.rw; - public Volume(String path) { this.path = path; } - - public Volume(String path, AccessMode accessMode) { - this.path = path; - this.accessMode = accessMode; - } public String getPath() { return path; } - - public AccessMode getAccessMode() { - return accessMode; - } - public static Volume parse(String serialized) { - return new Volume(serialized); - } - - /** - * Returns a string representation of this {@link Volume} suitable - * for inclusion in a JSON message. - * The returned String is simply the container path, {@link #getPath()}. - * - * @return a string representation of this {@link Volume} - */ @Override public String toString() { return getPath(); @@ -69,48 +45,14 @@ public String toString() { public boolean equals(Object obj) { if (obj instanceof Volume) { Volume other = (Volume) obj; - return new EqualsBuilder().append(path, other.getPath()).append(accessMode, other.getAccessMode()) - .isEquals(); + return new EqualsBuilder().append(path, other.getPath()).isEquals(); } else return super.equals(obj); } @Override public int hashCode() { - return new HashCodeBuilder().append(path).append(accessMode).toHashCode(); + return new HashCodeBuilder().append(path).toHashCode(); } - - public static class Serializer extends JsonSerializer { - - @Override - public void serialize(Volume volume, JsonGenerator jsonGen, - SerializerProvider serProvider) throws IOException, - JsonProcessingException { - - jsonGen.writeStartObject(); - jsonGen.writeFieldName(volume.getPath()); - jsonGen.writeString(Boolean.toString(volume.getAccessMode().equals(AccessMode.rw) ? true: false)); - jsonGen.writeEndObject(); - } - - } - - public static class Deserializer extends JsonDeserializer { - @Override - public Volume deserialize(JsonParser jsonParser, - DeserializationContext deserializationContext) - throws IOException, JsonProcessingException { - ObjectCodec oc = jsonParser.getCodec(); - JsonNode node = oc.readTree(jsonParser); - if (!node.equals(NullNode.getInstance())) { - Entry field = node.fields().next(); - return Volume.parse(field.getKey()); - } else { - return null; - } - } - } - - } diff --git a/src/main/java/com/github/dockerjava/api/model/VolumeRW.java b/src/main/java/com/github/dockerjava/api/model/VolumeRW.java new file mode 100644 index 00000000..717385d9 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/VolumeRW.java @@ -0,0 +1,115 @@ +package com.github.dockerjava.api.model; + +import java.io.IOException; +import java.util.Map.Entry; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +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.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.node.NullNode; + +/** + * Represents a bind mounted volume in a Docker container. + * + * @see Bind + */ +@JsonDeserialize(using = VolumeRW.Deserializer.class) +@JsonSerialize(using = VolumeRW.Serializer.class) +public class VolumeRW { + + private Volume volume; + + private AccessMode accessMode = AccessMode.rw; + + public VolumeRW(Volume volume) { + this.volume = volume; + } + + public VolumeRW(Volume volume, AccessMode accessMode) { + this.volume = volume; + this.accessMode = accessMode; + } + + public Volume getVolume() { + return volume; + } + + public AccessMode getAccessMode() { + return accessMode; + } + + + /** + * Returns a string representation of this {@link VolumeRW} suitable + * for inclusion in a JSON message. + * The returned String is simply the container path, {@link #getPath()}. + * + * @return a string representation of this {@link VolumeRW} + */ + @Override + public String toString() { + return getVolume() + ":" + getAccessMode(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof VolumeRW) { + VolumeRW other = (VolumeRW) obj; + return new EqualsBuilder().append(getVolume(), other.getVolume()).append(accessMode, other.getAccessMode()) + .isEquals(); + } else + return super.equals(obj); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(getVolume()).append(getAccessMode()).toHashCode(); + } + + public static class Serializer extends JsonSerializer { + + @Override + public void serialize(VolumeRW volumeRW, JsonGenerator jsonGen, + SerializerProvider serProvider) throws IOException, + JsonProcessingException { + + jsonGen.writeStartObject(); + jsonGen.writeFieldName(volumeRW.getVolume().getPath()); + jsonGen.writeString(Boolean.toString(volumeRW.getAccessMode().toBoolean())); + jsonGen.writeEndObject(); + } + + } + + public static class Deserializer extends JsonDeserializer { + @Override + public VolumeRW deserialize(JsonParser jsonParser, + DeserializationContext deserializationContext) + throws IOException, JsonProcessingException { + ObjectCodec oc = jsonParser.getCodec(); + JsonNode node = oc.readTree(jsonParser); + if (!node.equals(NullNode.getInstance())) { + Entry field = node.fields().next(); + String volume = field.getKey(); + AccessMode accessMode = AccessMode.fromBoolean(field.getValue().asBoolean()); + return new VolumeRW(new Volume(volume), accessMode); + } else { + return null; + } + } + } + + + +} diff --git a/src/main/java/com/github/dockerjava/api/model/Volumes.java b/src/main/java/com/github/dockerjava/api/model/Volumes.java index 69753d6a..b85536e1 100644 --- a/src/main/java/com/github/dockerjava/api/model/Volumes.java +++ b/src/main/java/com/github/dockerjava/api/model/Volumes.java @@ -48,7 +48,9 @@ public void serialize(Volumes volumes, JsonGenerator jsonGen, jsonGen.writeStartObject(); for (Volume volume : volumes.getVolumes()) { jsonGen.writeFieldName(volume.getPath()); - jsonGen.writeString(Boolean.toString(volume.getAccessMode().equals(AccessMode.rw) ? true: false)); + jsonGen.writeStartObject(); + jsonGen.writeEndObject(); + //jsonGen.writeString(Boolean.toString(volume.getAccessMode().equals(AccessMode.rw) ? true: false)); } jsonGen.writeEndObject(); } @@ -66,7 +68,8 @@ public Volumes deserialize(JsonParser jsonParser, DeserializationContext deseria Map.Entry field = it.next(); if (!field.getValue().equals(NullNode.getInstance())) { - Volume volume = Volume.parse(field.getKey()); + String path = field.getKey(); + Volume volume = new Volume(path); volumes.add(volume); } } diff --git a/src/main/java/com/github/dockerjava/api/model/VolumesRW.java b/src/main/java/com/github/dockerjava/api/model/VolumesRW.java new file mode 100644 index 00000000..223f518c --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/VolumesRW.java @@ -0,0 +1,57 @@ +package com.github.dockerjava.api.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.node.NullNode; + +// This is not going to be serialized +@JsonDeserialize(using = VolumesRW.Deserializer.class) +public class VolumesRW { + private final VolumeRW[] volumesRW; + + public VolumesRW(VolumeRW... binds) { + this.volumesRW = binds; + } + + public VolumeRW[] getVolumesRW() { + return volumesRW; + } + + public static final class Deserializer extends JsonDeserializer { + @Override + public VolumesRW deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { + + List volumesRW = new ArrayList(); + ObjectCodec oc = jsonParser.getCodec(); + JsonNode node = oc.readTree(jsonParser); + + + for (Iterator> it = node.fields(); it.hasNext();) { + Map.Entry field = it.next(); + JsonNode value = field.getValue(); + + if (!value.equals(NullNode.getInstance())) { + if (!value.isBoolean()){ + throw deserializationContext.mappingException("Expected access mode for '"+field.getKey()+"' in host but got '"+ value+"'."); + } + + VolumeRW bind = new VolumeRW(new Volume(field.getKey()), AccessMode.fromBoolean(value.asBoolean())); + volumesRW.add(bind); + } + } + return new VolumesRW(volumesRW.toArray(new VolumeRW[volumesRW.size()])); + } + } + +} diff --git a/src/test/java/com/github/dockerjava/api/model/VolumeTest.java b/src/test/java/com/github/dockerjava/api/model/VolumeTest.java index 8fdf1997..7419e5dc 100644 --- a/src/test/java/com/github/dockerjava/api/model/VolumeTest.java +++ b/src/test/java/com/github/dockerjava/api/model/VolumeTest.java @@ -6,7 +6,7 @@ public class VolumeTest { @Test - public void stringify() { - assertEquals(Volume.parse("/path").toString(), "/path"); + public void getPath() { + assertEquals(new Volume("/path").getPath(), "/path"); } } diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index 752f0aef..4feadc6b 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -30,6 +30,7 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.model.AccessMode; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Device; import com.github.dockerjava.api.model.ExposedPort; @@ -38,6 +39,8 @@ import com.github.dockerjava.api.model.Ports; import com.github.dockerjava.api.model.RestartPolicy; import com.github.dockerjava.api.model.Volume; +import com.github.dockerjava.api.model.VolumeRW; +import com.github.dockerjava.api.model.Volumes; import com.github.dockerjava.api.model.VolumesFrom; import com.github.dockerjava.client.AbstractDockerClientTest; @@ -88,9 +91,11 @@ public void createContainerWithExistingName() throws DockerException { @Test public void createContainerWithVolume() throws DockerException { + Volume volume = new Volume("/var/log"); + CreateContainerResponse container = dockerClient .createContainerCmd("busybox") - .withVolumes(new Volume("/var/log")).withCmd("true").exec(); + .withVolumes(volume).withCmd("true").exec(); LOG.info("Created container {}", container.toString()); @@ -104,6 +109,37 @@ public void createContainerWithVolume() throws DockerException { assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), contains("/var/log")); + + assertThat(inspectContainerResponse.getVolumesRW(), + hasItemInArray(new VolumeRW(volume, AccessMode.rw))); + } + + @Test + public void createContainerWithReadOnlyVolume() throws DockerException { + + Volume volume = new Volume("/srv/test"); + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox") + .withVolumes(volume) + .withCmd("true") + .exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + LOG.info("Inspect container {}", inspectContainerResponse.getConfig() + .getVolumes()); + + assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(), + contains("/srv/test")); + + assertThat(Arrays.asList(inspectContainerResponse.getVolumesRW()), + contains(new VolumeRW(volume))); } @Test diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index f7cbe20c..9a307165 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -65,7 +65,8 @@ public void startContainerWithVolumes() throws DockerException { Volume volume2 = new Volume("/opt/webapp2"); CreateContainerResponse container = dockerClient - .createContainerCmd("busybox").withVolumes(volume1, volume2) + .createContainerCmd("busybox") + .withVolumes(volume1, volume2) .withCmd("true").exec(); LOG.info("Created container {}", container.toString()); @@ -91,7 +92,7 @@ public void startContainerWithVolumes() throws DockerException { assertContainerHasVolumes(inspectContainerResponse, volume1, volume2); assertThat(Arrays.asList(inspectContainerResponse.getVolumesRW()), - contains(volume1, volume2)); + contains(new VolumeRW(volume1, AccessMode.ro), new VolumeRW(volume2))); } From 6cd5f46e266e4351098679877bc477840281062c Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sat, 2 May 2015 00:34:58 +0200 Subject: [PATCH 404/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ee13f6a..ea8bdf04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ Change Log === Latest SNAPSHOT --- +* [#205](https://github.com/docker-java/docker-java/issues/205) Access mode of VolumesRW incorrectly deserialized * [#203](https://github.com/docker-java/docker-java/issues/203) Missing 'MacAddress' option in create container command * [#197](https://github.com/docker-java/docker-java/pull/197) Allow for null bindings From cfc3a9a1df239f401b0554f7f2a15cad514f9c30 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sat, 2 May 2015 00:44:41 +0200 Subject: [PATCH 405/452] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea8bdf04..33607c66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,9 @@ Change Log === Latest SNAPSHOT --- + * [#205](https://github.com/docker-java/docker-java/issues/205) Access mode of VolumesRW incorrectly deserialized +* [#204] (https://github.com/docker-java/docker-java/pull/204) Added support to use the credentials from .dockercfg during build * [#203](https://github.com/docker-java/docker-java/issues/203) Missing 'MacAddress' option in create container command * [#197](https://github.com/docker-java/docker-java/pull/197) Allow for null bindings From 7675400a68af3e77f32179947471279fb36f2324 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sat, 2 May 2015 00:47:12 +0200 Subject: [PATCH 406/452] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b7e9c621..bbafd8a6 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Java API client for [Docker](http://docs.docker.io/ "Docker") -Supports a subset of the Docker Client API v1.16, Docker Server version 1.4.1 +Supports a subset of the Docker Client API v1.17, Docker Server version 1.5.0 The current implementation is based on Jersey 2.x and therefore classpath incompatible with older Jersey 1.x dependent libraries! @@ -64,7 +64,7 @@ Run build without integration tests: com.github.docker-java docker-java - 1.0.0 + 1.2.0 ### Latest SNAPSHOT version @@ -74,7 +74,7 @@ You can find the latest SNAPSHOT version including javadoc and source files on [ com.github.docker-java docker-java - 1.0.1-SNAPSHOT + 1.2.1-SNAPSHOT ## Documentation From 42c1892b07f216dca2882bdfb6f7d86eb405964f Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 08:57:41 +0100 Subject: [PATCH 407/452] Updated to jersey 2.17. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1279f9c1..010165a8 100644 --- a/pom.xml +++ b/pom.xml @@ -47,7 +47,7 @@ 1.7 1.7 - 2.11 + 2.17 2.1.2 4.3.1 1.5 From 92b2002224425235707228dd51657f172693b5cb Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 09:01:13 +0100 Subject: [PATCH 408/452] Flipped expressions for minor perf issue. --- src/main/java/com/github/dockerjava/api/model/Frame.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/api/model/Frame.java b/src/main/java/com/github/dockerjava/api/model/Frame.java index 3860a5db..175b5683 100644 --- a/src/main/java/com/github/dockerjava/api/model/Frame.java +++ b/src/main/java/com/github/dockerjava/api/model/Frame.java @@ -34,7 +34,7 @@ public boolean equals(Object o) { Frame frame = (Frame) o; - return Arrays.equals(payload, frame.payload) && streamType == frame.streamType; + return streamType == frame.streamType && Arrays.equals(payload, frame.payload); } From 9dc9b3c2d26aa25536a60db815934dd7a6c69982 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 09:41:42 +0100 Subject: [PATCH 409/452] Reverted jersey 2.11 -> 2.17 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 010165a8..1279f9c1 100644 --- a/pom.xml +++ b/pom.xml @@ -47,7 +47,7 @@ 1.7 1.7 - 2.17 + 2.11 2.1.2 4.3.1 1.5 From ebaba3588bd6545bb698a529d553d25d5fe9aec8 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 09:43:24 +0100 Subject: [PATCH 410/452] Created integration test for FrameReader. --- .../core/command/DockerfileFixture.java | 63 +++++++++++++++++++ .../core/command/FrameReaderITest.java | 58 +++++++++++++++++ .../frameReaderDockerfile/Dockerfile | 10 +++ 3 files changed, 131 insertions(+) create mode 100644 src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java create mode 100644 src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java create mode 100644 src/test/resources/frameReaderDockerfile/Dockerfile diff --git a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java new file mode 100644 index 00000000..d6a034f6 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java @@ -0,0 +1,63 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.DockerClient; + +import java.io.File; + +/** + * Start and stop a single container for testing. + */ +public class DockerfileFixture implements AutoCloseable { + + private final DockerClient dockerClient; + private String directory; + private String repository; + private String containerId; + + public DockerfileFixture(DockerClient dockerClient, String directory) { + this.dockerClient = dockerClient; + this.directory = directory; + } + + public void open() throws Exception { + + dockerClient + .buildImageCmd(new File("src/test/resources", directory)) + .withNoCache() // remove alternatives, cause problems + .exec() + .close(); + + repository = dockerClient + .listImagesCmd() + .exec() + .get(0) + .getRepoTags()[0]; + + containerId = dockerClient + .createContainerCmd(repository) + .exec() + .getId(); + + dockerClient + .startContainerCmd(containerId) + .exec(); + } + + @Override + public void close() throws Exception { + + dockerClient + .removeContainerCmd(containerId) + .withForce() // stop too + .exec(); + + dockerClient + .removeImageCmd(repository) + .withForce() + .exec(); + } + + public String getContainerId() { + return containerId; + } +} diff --git a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java new file mode 100644 index 00000000..61a5fb88 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java @@ -0,0 +1,58 @@ +package com.github.dockerjava.core.command; + + +import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.StreamType; +import com.github.dockerjava.client.AbstractDockerClientTest; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.InputStream; + +@Test(groups = "integration") +public class FrameReaderITest extends AbstractDockerClientTest { + + private DockerfileFixture dockerfileFixture; + + @BeforeMethod + @Override + public void beforeTest() { + super.beforeTest(); + dockerfileFixture = new DockerfileFixture(dockerClient, "frameReaderDockerfile"); + } + + @BeforeMethod + public void createAndStartDockerContainer() throws Exception { + dockerfileFixture.open(); + } + + @AfterMethod + public void deleteDockerContainerImage() throws Exception { + dockerfileFixture.close(); + } + + @AfterMethod + @Override + public void afterTest() { + super.afterTest(); + } + + @Test + public void canCloseFrameReaderAndReadExpectedLinens() throws Exception { + + InputStream log = dockerClient + .logContainerCmd(dockerfileFixture.getContainerId()) + .withStdOut() + .withStdErr() + .withFollowStream() + .withTailAll() + .exec(); + + try (FrameReader reader = new FrameReader(log)) { + assertEquals(reader.readFrame(), new Frame(StreamType.STDOUT, String.format("to stdout%n").getBytes())); + assertEquals(reader.readFrame(), new Frame(StreamType.STDERR, String.format("to stderr%n").getBytes())); + assertNull(reader.readFrame()); + } + } +} \ No newline at end of file diff --git a/src/test/resources/frameReaderDockerfile/Dockerfile b/src/test/resources/frameReaderDockerfile/Dockerfile new file mode 100644 index 00000000..c4d74fc5 --- /dev/null +++ b/src/test/resources/frameReaderDockerfile/Dockerfile @@ -0,0 +1,10 @@ +FROM busybox:latest + +# log to stdout and stderr so we can make sure logging with FrameReader works + +RUN echo '#! /bin/sh' > cmd.sh +RUN echo 'echo "to stdout"' >> cmd.sh +RUN echo 'echo "to stderr" > /dev/stderr' >> cmd.sh +RUN chmod +x cmd.sh + +CMD ["./cmd.sh"] \ No newline at end of file From 6a7f1d268db292a058b9425b117de02031db8cd0 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 09:46:13 +0100 Subject: [PATCH 411/452] Created integration test for FrameReader. --- .../github/dockerjava/core/command/FrameReaderITest.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java index 61a5fb88..936cd8b4 100644 --- a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java +++ b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java @@ -5,7 +5,9 @@ import com.github.dockerjava.api.model.StreamType; import com.github.dockerjava.client.AbstractDockerClientTest; 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 java.io.InputStream; @@ -15,7 +17,7 @@ public class FrameReaderITest extends AbstractDockerClientTest { private DockerfileFixture dockerfileFixture; - @BeforeMethod + @BeforeTest @Override public void beforeTest() { super.beforeTest(); @@ -32,7 +34,7 @@ public void deleteDockerContainerImage() throws Exception { dockerfileFixture.close(); } - @AfterMethod + @AfterTest @Override public void afterTest() { super.afterTest(); From 5e8cfc606c25e61dcefd793090effb8a7a6a2855 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 10:28:26 +0100 Subject: [PATCH 412/452] Mad Dockerfile more robust. --- .../core/command/DockerfileFixture.java | 32 ++++++++++++++----- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java index d6a034f6..599c8848 100644 --- a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java +++ b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java @@ -1,6 +1,8 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.DockerClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; @@ -9,6 +11,7 @@ */ public class DockerfileFixture implements AutoCloseable { + private static final Logger LOGGER = LoggerFactory.getLogger(DockerfileFixture.class); private final DockerClient dockerClient; private String directory; private String repository; @@ -21,6 +24,7 @@ public DockerfileFixture(DockerClient dockerClient, String directory) { public void open() throws Exception { + LOGGER.info("building {}", directory); dockerClient .buildImageCmd(new File("src/test/resources", directory)) .withNoCache() // remove alternatives, cause problems @@ -33,11 +37,15 @@ public void open() throws Exception { .get(0) .getRepoTags()[0]; + LOGGER.info("created {}", repository); + containerId = dockerClient .createContainerCmd(repository) .exec() .getId(); + LOGGER.info("starting {}", containerId); + dockerClient .startContainerCmd(containerId) .exec(); @@ -46,15 +54,23 @@ public void open() throws Exception { @Override public void close() throws Exception { - dockerClient - .removeContainerCmd(containerId) - .withForce() // stop too - .exec(); + if (containerId != null) { + LOGGER.info("removing container {}", containerId); + dockerClient + .removeContainerCmd(containerId) + .withForce() // stop too + .exec(); + containerId = null; + } - dockerClient - .removeImageCmd(repository) - .withForce() - .exec(); + if (repository != null) { + LOGGER.info("removing repostiory {}", repository); + dockerClient + .removeImageCmd(repository) + .withForce() + .exec(); + repository = null; + } } public String getContainerId() { From e29e7da45b8453c22a625f4ef4a09699240ee42f Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 10:35:02 +0100 Subject: [PATCH 413/452] Ignore container removal error. --- .../core/command/DockerfileFixture.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java index 599c8848..4970a293 100644 --- a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java +++ b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java @@ -1,6 +1,7 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.NotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -56,15 +57,19 @@ public void close() throws Exception { if (containerId != null) { LOGGER.info("removing container {}", containerId); - dockerClient - .removeContainerCmd(containerId) - .withForce() // stop too - .exec(); + try { + dockerClient + .removeContainerCmd(containerId) + .withForce() // stop too + .exec(); + } catch (NotFoundException ignored) { + LOGGER.info("ignoring {}", ignored.getMessage()); + } containerId = null; } if (repository != null) { - LOGGER.info("removing repostiory {}", repository); + LOGGER.info("removing repository {}", repository); dockerClient .removeImageCmd(repository) .withForce() From 09220689a83cf06f90d866acac329463b811d952 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 11:44:18 +0100 Subject: [PATCH 414/452] Fixed connection leak. --- .../dockerjava/jaxrs/BuildImageCmdExec.java | 36 ++++++++++--------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java index b5ea85ed..3bdfb006 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/BuildImageCmdExec.java @@ -1,21 +1,5 @@ package com.github.dockerjava.jaxrs; -import static javax.ws.rs.client.Entity.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Iterator; - -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.glassfish.jersey.client.ClientProperties; -import org.glassfish.jersey.client.RequestEntityProcessing; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.github.dockerjava.api.command.BuildImageCmd; @@ -23,6 +7,20 @@ import com.github.dockerjava.api.model.EventStreamItem; import com.github.dockerjava.jaxrs.util.WrappedResponseInputStream; import com.google.common.collect.ImmutableList; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.client.RequestEntityProcessing; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.io.InputStream; +import java.util.Iterator; + +import static javax.ws.rs.client.Entity.entity; public class BuildImageCmdExec extends AbstrDockerCmdExec implements @@ -112,5 +110,11 @@ public Iterable getItems() throws IOException { public int read() throws IOException { return proxy.read(); } + + @Override + public void close() throws IOException { + proxy.close(); + super.close(); + } } } From 92aa1bbfe6b416c160dc4dc1eef66f9a40d015e1 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 11:50:06 +0100 Subject: [PATCH 415/452] Updated test. --- .../core/command/DockerfileFixture.java | 11 +++-- .../core/command/FrameReaderITest.java | 47 ++++++++++++++++--- .../resources/busyboxDockerfile/Dockerfile | 3 ++ .../frameReaderDockerfile/Dockerfile | 3 ++ 4 files changed, 53 insertions(+), 11 deletions(-) create mode 100644 src/test/resources/busyboxDockerfile/Dockerfile diff --git a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java index 4970a293..b3bdf4ea 100644 --- a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java +++ b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java @@ -2,6 +2,7 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.NotFoundException; +import com.github.dockerjava.api.model.Image; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,16 +33,18 @@ public void open() throws Exception { .exec() .close(); - repository = dockerClient + Image lastCreatedImage = dockerClient .listImagesCmd() .exec() - .get(0) + .get(0); + + repository = lastCreatedImage .getRepoTags()[0]; - LOGGER.info("created {}", repository); + LOGGER.info("created {} {}", lastCreatedImage.getId(), repository); containerId = dockerClient - .createContainerCmd(repository) + .createContainerCmd(lastCreatedImage.getId()) .exec() .getId(); diff --git a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java index 936cd8b4..4654d83d 100644 --- a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java +++ b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java @@ -10,6 +10,7 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import java.io.IOException; import java.io.InputStream; @Test(groups = "integration") @@ -41,20 +42,52 @@ public void afterTest() { } @Test - public void canCloseFrameReaderAndReadExpectedLinens() throws Exception { + public void canCloseFrameReaderAndReadExpectedLines() throws Exception { - InputStream log = dockerClient + try (FrameReader reader = new FrameReader(getLoggerStream())) { + assertEquals(reader.readFrame(), new Frame(StreamType.STDOUT, String.format("to stdout%n").getBytes())); + assertEquals(reader.readFrame(), new Frame(StreamType.STDERR, String.format("to stderr%n").getBytes())); + assertNull(reader.readFrame()); + } + } + + private InputStream getLoggerStream() { + return dockerClient .logContainerCmd(dockerfileFixture.getContainerId()) .withStdOut() .withStdErr() - .withFollowStream() .withTailAll() + .withTail(10) + .withFollowStream() .exec(); + } - try (FrameReader reader = new FrameReader(log)) { - assertEquals(reader.readFrame(), new Frame(StreamType.STDOUT, String.format("to stdout%n").getBytes())); - assertEquals(reader.readFrame(), new Frame(StreamType.STDERR, String.format("to stderr%n").getBytes())); - assertNull(reader.readFrame()); + @Test + public void canLogInOneThreadAndExecuteCommandsInAnother() throws Exception { + + Thread thread = new Thread(new Runnable() { + @Override + public void run() { + try { + try (FrameReader reader = new FrameReader(getLoggerStream())) { + //noinspection StatementWithEmptyBody + while (reader.readFrame() != null) { + // nop + } + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + }); + + thread.start(); + + try (DockerfileFixture busyboxDockerfile = new DockerfileFixture(dockerClient, "busyboxDockerfile")) { + busyboxDockerfile.open(); } + + thread.join(); + } } \ No newline at end of file diff --git a/src/test/resources/busyboxDockerfile/Dockerfile b/src/test/resources/busyboxDockerfile/Dockerfile new file mode 100644 index 00000000..5377ac8a --- /dev/null +++ b/src/test/resources/busyboxDockerfile/Dockerfile @@ -0,0 +1,3 @@ +FROM busybox:latest + +CMD ["cat"] \ No newline at end of file diff --git a/src/test/resources/frameReaderDockerfile/Dockerfile b/src/test/resources/frameReaderDockerfile/Dockerfile index c4d74fc5..8d9b553e 100644 --- a/src/test/resources/frameReaderDockerfile/Dockerfile +++ b/src/test/resources/frameReaderDockerfile/Dockerfile @@ -3,8 +3,11 @@ FROM busybox:latest # log to stdout and stderr so we can make sure logging with FrameReader works RUN echo '#! /bin/sh' > cmd.sh +RUN echo 'sleep 1' >> cmd.sh RUN echo 'echo "to stdout"' >> cmd.sh RUN echo 'echo "to stderr" > /dev/stderr' >> cmd.sh +# block for ever +RUN echo 'cat' >> cmd.sh RUN chmod +x cmd.sh CMD ["./cmd.sh"] \ No newline at end of file From 6942c4fc9fe085915d4e791758a1ce27ca1179ca Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 12:02:41 +0100 Subject: [PATCH 416/452] Ignore error when removing image (e.g. due to brtfs on CircleCI). --- .../dockerjava/core/command/DockerfileFixture.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java index b3bdf4ea..500a6263 100644 --- a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java +++ b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java @@ -1,6 +1,7 @@ package com.github.dockerjava.core.command; import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.InternalServerErrorException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.model.Image; import org.slf4j.Logger; @@ -73,10 +74,14 @@ public void close() throws Exception { if (repository != null) { LOGGER.info("removing repository {}", repository); - dockerClient - .removeImageCmd(repository) - .withForce() - .exec(); + try { + dockerClient + .removeImageCmd(repository) + .withForce() + .exec(); + } catch (InternalServerErrorException e) { + LOGGER.info("ignoring {}", e.getMessage()); + } repository = null; } } From 33d66dab953956e8af2102853d4599256b08b7ce Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 12:33:31 +0100 Subject: [PATCH 417/452] Ignore error when removing image (e.g. due to brtfs on CircleCI). --- .../com/github/dockerjava/core/command/DockerfileFixture.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java index 500a6263..2d7ca7c8 100644 --- a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java +++ b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java @@ -66,7 +66,7 @@ public void close() throws Exception { .removeContainerCmd(containerId) .withForce() // stop too .exec(); - } catch (NotFoundException ignored) { + } catch (NotFoundException | InternalServerErrorException ignored) { LOGGER.info("ignoring {}", ignored.getMessage()); } containerId = null; From f05294d51ec3448552e79712058ed4f5ef6c9db9 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 13:25:37 +0100 Subject: [PATCH 418/452] Added PullEventStreamItem and EventStreamReader to stream the reading of events. --- .../dockerjava/api/command/BuildImageCmd.java | 9 ++- .../dockerjava/api/command/PullImageCmd.java | 3 + .../dockerjava/api/command/PushImageCmd.java | 10 ++- .../api/model/PullEventStreamItem.java | 59 +++++++++++++++ .../core/command/EventStreamReader.java | 35 +++++++++ .../core/command/EventStreamReaderITest.java | 72 +++++++++++++++++++ .../core/command/FrameReaderITest.java | 28 +++----- .../eventStreamReaderDockerfile/Dockerfile | 5 ++ 8 files changed, 197 insertions(+), 24 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/PullEventStreamItem.java create mode 100644 src/main/java/com/github/dockerjava/core/command/EventStreamReader.java create mode 100644 src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java create mode 100644 src/test/resources/eventStreamReaderDockerfile/Dockerfile diff --git a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java index ec013d42..925946db 100644 --- a/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/BuildImageCmd.java @@ -1,12 +1,12 @@ package com.github.dockerjava.api.command; +import com.github.dockerjava.api.model.AuthConfigurations; +import com.github.dockerjava.api.model.EventStreamItem; + import java.io.File; import java.io.IOException; import java.io.InputStream; -import com.github.dockerjava.api.model.AuthConfigurations; -import com.github.dockerjava.api.model.EventStreamItem; - /** * * Build an image from Dockerfile. @@ -61,6 +61,9 @@ public interface BuildImageCmd extends DockerCmd{ public static interface Exec extends DockerCmdExec { } + /** + * @see {@link com.github.dockerjava.core.command.EventStreamReader} + */ public static abstract class Response extends InputStream { public abstract Iterable getItems() throws IOException; } diff --git a/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java b/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java index c39617dd..4b5fc4c3 100644 --- a/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/PullImageCmd.java @@ -1,6 +1,7 @@ package com.github.dockerjava.api.command; import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.core.command.EventStreamReader; import java.io.InputStream; @@ -33,6 +34,8 @@ public static interface Exec extends DockerCmdExec { /** * Its the responsibility of the caller to consume and/or close the {@link InputStream} to prevent * connection leaks. + * + * @see {@link EventStreamReader} */ @Override public InputStream exec(); diff --git a/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java b/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java index 80e16c6d..9ed38beb 100644 --- a/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/PushImageCmd.java @@ -1,11 +1,12 @@ package com.github.dockerjava.api.command; -import java.io.IOException; -import java.io.InputStream; - import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.model.AuthConfig; import com.github.dockerjava.api.model.PushEventStreamItem; +import com.github.dockerjava.core.command.EventStreamReader; + +import java.io.IOException; +import java.io.InputStream; /** * Push the latest image to the repository. @@ -40,6 +41,9 @@ public interface PushImageCmd extends DockerCmd{ public static interface Exec extends DockerCmdExec { } + /** + * @see {@link EventStreamReader} + */ public static abstract class Response extends InputStream { public abstract Iterable getItems() throws IOException; } diff --git a/src/main/java/com/github/dockerjava/api/model/PullEventStreamItem.java b/src/main/java/com/github/dockerjava/api/model/PullEventStreamItem.java new file mode 100644 index 00000000..4a3a0b50 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/PullEventStreamItem.java @@ -0,0 +1,59 @@ +package com.github.dockerjava.api.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.common.base.Objects; + +import java.io.Serializable; + +/** + * Represents an item returned from pull + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class PullEventStreamItem implements Serializable { + + private static final long serialVersionUID = -5187169652557467828L; + + @JsonProperty("status") + private String status; + + @JsonProperty("progress") + private String progress; + + @JsonProperty("progressDetail") + private ProgressDetail progressDetail; + + + public String getStatus() { + return status; + } + + public String getProgress() { + return progress; + } + + public ProgressDetail getProgressDetail() { + return progressDetail; + } + + @JsonIgnoreProperties(ignoreUnknown=true) + public static class ProgressDetail implements Serializable { + @JsonProperty("current") + int current; + + + @Override + public String toString() { + return "current " + current; + } + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("status", status) + .add("progress", progress) + .add("progressDetail", progressDetail) + .toString(); + } +} diff --git a/src/main/java/com/github/dockerjava/core/command/EventStreamReader.java b/src/main/java/com/github/dockerjava/core/command/EventStreamReader.java new file mode 100644 index 00000000..b8975224 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/command/EventStreamReader.java @@ -0,0 +1,35 @@ +package com.github.dockerjava.core.command; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.io.InputStream; + +public class EventStreamReader implements AutoCloseable { + + private final ObjectMapper objectMapper = new ObjectMapper(); + private final Class type; + private final InputStream inputStream; + + public EventStreamReader(InputStream inputStream, Class type) { + this.inputStream = inputStream; + this.type = type; + } + + public I readItem() throws IOException { + try { + return objectMapper.readValue(inputStream, type); + } catch (IOException e) { + // dirty, but works + if (e.getMessage().equals("Stream closed")) { + return null; + } + throw e; + } + } + + @Override + public void close() throws IOException { + inputStream.close(); + } +} diff --git a/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java b/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java new file mode 100644 index 00000000..dfc330d9 --- /dev/null +++ b/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java @@ -0,0 +1,72 @@ +package com.github.dockerjava.core.command; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.model.EventStreamItem; +import com.github.dockerjava.api.model.PullEventStreamItem; +import com.github.dockerjava.core.DockerClientBuilder; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import java.io.File; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; +import static org.hamcrest.core.AllOf.allOf; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.nullValue; +import static org.testng.AssertJUnit.assertNull; + + +@Test(groups = "integration") +public class EventStreamReaderITest { + + private DockerClient dockerClient; + + @BeforeTest + public void setUp() throws Exception { + dockerClient = DockerClientBuilder.getInstance().build(); + } + + @AfterTest + public void tearDown() throws Exception { + dockerClient.close(); + } + + @Test + public void pullCanBeStreamed() throws Exception { + + try (EventStreamReader reader = new EventStreamReader<>( + dockerClient.pullImageCmd("busybox:latest").exec(), + PullEventStreamItem.class) + ) {; + assertThat(reader.readItem(), + allOf( + hasProperty("status", equalTo("Pulling repository busybox")), + hasProperty("progress", nullValue()), + hasProperty("progressDetail", nullValue()) + ) + ); + assertNull(reader.readItem()); + } + } + + @Test + public void buildCanBeStreamed() throws Exception { + + try (EventStreamReader reader = new EventStreamReader<>( + dockerClient.buildImageCmd(new File("src/test/resources/eventStreamReaderDockerfile")).exec(), + EventStreamItem.class) + ) { + assertThat(reader.readItem(), + allOf( + hasProperty("stream", equalTo("Step 0 : FROM busybox:latest\n")), + hasProperty("error", nullValue()), + hasProperty("errorDetail", nullValue()) + ) + ); + assertNull(reader.readItem()); + + } + } +} \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java index 4654d83d..3aee3cb4 100644 --- a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java +++ b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java @@ -1,44 +1,36 @@ package com.github.dockerjava.core.command; +import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.model.Frame; import com.github.dockerjava.api.model.StreamType; -import com.github.dockerjava.client.AbstractDockerClientTest; -import org.testng.annotations.AfterMethod; +import com.github.dockerjava.core.DockerClientBuilder; import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.IOException; import java.io.InputStream; +import static org.testng.Assert.assertEquals; +import static org.testng.AssertJUnit.assertNull; + @Test(groups = "integration") -public class FrameReaderITest extends AbstractDockerClientTest { +public class FrameReaderITest { + private DockerClient dockerClient; private DockerfileFixture dockerfileFixture; @BeforeTest - @Override public void beforeTest() { - super.beforeTest(); + dockerClient = DockerClientBuilder.getInstance().build(); dockerfileFixture = new DockerfileFixture(dockerClient, "frameReaderDockerfile"); } - @BeforeMethod - public void createAndStartDockerContainer() throws Exception { - dockerfileFixture.open(); - } - - @AfterMethod + @AfterTest public void deleteDockerContainerImage() throws Exception { dockerfileFixture.close(); - } - - @AfterTest - @Override - public void afterTest() { - super.afterTest(); + dockerClient.close(); } @Test diff --git a/src/test/resources/eventStreamReaderDockerfile/Dockerfile b/src/test/resources/eventStreamReaderDockerfile/Dockerfile new file mode 100644 index 00000000..cdd3bba7 --- /dev/null +++ b/src/test/resources/eventStreamReaderDockerfile/Dockerfile @@ -0,0 +1,5 @@ +FROM busybox:latest + +RUN true + +CMD ["true"] \ No newline at end of file From 8a35bd692ba9fe5090bbb6db789279befa929b5f Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 16:49:55 +0100 Subject: [PATCH 419/452] Corrected bug in test. --- .../com/github/dockerjava/core/command/FrameReaderITest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java index 3aee3cb4..e8e6bcc6 100644 --- a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java +++ b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java @@ -25,6 +25,7 @@ public class FrameReaderITest { public void beforeTest() { dockerClient = DockerClientBuilder.getInstance().build(); dockerfileFixture = new DockerfileFixture(dockerClient, "frameReaderDockerfile"); + dockerfileFixture.open(); } @AfterTest From 86c9f0aa93cb3aa2a64747c303e6756828f5e0e3 Mon Sep 17 00:00:00 2001 From: Alex Collins Date: Sun, 3 May 2015 16:51:54 +0100 Subject: [PATCH 420/452] Added PullEventStreamItem and EventStreamReader to stream the reading of events. --- .../github/dockerjava/core/command/DockerfileFixture.java | 5 +++-- .../com/github/dockerjava/core/command/FrameReaderITest.java | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java index 2d7ca7c8..840f63da 100644 --- a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java +++ b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java @@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory; import java.io.File; +import java.io.IOException; /** * Start and stop a single container for testing. @@ -25,7 +26,7 @@ public DockerfileFixture(DockerClient dockerClient, String directory) { this.directory = directory; } - public void open() throws Exception { + public void open() throws IOException { LOGGER.info("building {}", directory); dockerClient @@ -79,7 +80,7 @@ public void close() throws Exception { .removeImageCmd(repository) .withForce() .exec(); - } catch (InternalServerErrorException e) { + } catch (NotFoundException | InternalServerErrorException e) { LOGGER.info("ignoring {}", e.getMessage()); } repository = null; diff --git a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java index e8e6bcc6..0cf08e95 100644 --- a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java +++ b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java @@ -22,7 +22,7 @@ public class FrameReaderITest { private DockerfileFixture dockerfileFixture; @BeforeTest - public void beforeTest() { + public void beforeTest() throws Exception { dockerClient = DockerClientBuilder.getInstance().build(); dockerfileFixture = new DockerfileFixture(dockerClient, "frameReaderDockerfile"); dockerfileFixture.open(); From c577bf9cb77b523a2ebbdc14f6edd9d661bda250 Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Wed, 6 May 2015 00:42:19 +0300 Subject: [PATCH 421/452] Add public constructor and Javadoc to api.model.Event --- .../github/dockerjava/api/model/Event.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/main/java/com/github/dockerjava/api/model/Event.java b/src/main/java/com/github/dockerjava/api/model/Event.java index 674cb66d..cb961f97 100644 --- a/src/main/java/com/github/dockerjava/api/model/Event.java +++ b/src/main/java/com/github/dockerjava/api/model/Event.java @@ -14,18 +14,59 @@ public class Event { private long time; + /** + * Default constructor for the deserialization. + */ + public Event() { + } + + /** + * Constructor. + * @param id Container ID + * @param status Status string. + * List of statuses is available in Docker API v.1.16 + * @param from Image, from which the container has been created + * @param time Event time + * The time is specified in milliseconds since January 1, 1970, 00:00:00 GMT + * @since TODO + */ + public Event(String status, String id, String from, long time) { + this.status = status; + this.id = id; + this.from = from; + this.time = time; + } + + /** + * Status of docker image or container. + * List of statuses is available in Docker API v.1.16 + * @return Status string + */ public String getStatus() { return status; } + /** + * Get ID of docker container. + * @return Container ID + */ public String getId() { return id; } + /** + * Get source image of the container. + * @return Name of the parent container + */ public String getFrom() { return from; } + /** + * Get the event time. + * The time is specified in milliseconds since January 1, 1970, 00:00:00 GMT + * @return Event time in the specified format. + */ public long getTime() { return time; } From 8042fc9ea04359600519d2877ab176e447da5a57 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Wed, 6 May 2015 23:05:46 +0200 Subject: [PATCH 422/452] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 33607c66..e6fca225 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ Change Log === Latest SNAPSHOT --- - +* [#208](https://github.com/docker-java/docker-java/pull/208) Added PullEventStreamItem and EventStreamReader to stream the reading of events * [#205](https://github.com/docker-java/docker-java/issues/205) Access mode of VolumesRW incorrectly deserialized * [#204] (https://github.com/docker-java/docker-java/pull/204) Added support to use the credentials from .dockercfg during build * [#203](https://github.com/docker-java/docker-java/issues/203) Missing 'MacAddress' option in create container command From 5697c60bc4581eff46cc79f735f26b8c658ab2d5 Mon Sep 17 00:00:00 2001 From: "alex.collins" Date: Wed, 6 May 2015 22:57:07 +0100 Subject: [PATCH 423/452] Quietly catch IndexOutOfBoundsException. --- .../github/dockerjava/core/command/EventStreamReaderITest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java b/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java index dfc330d9..b7d86de0 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java @@ -39,7 +39,7 @@ public void pullCanBeStreamed() throws Exception { try (EventStreamReader reader = new EventStreamReader<>( dockerClient.pullImageCmd("busybox:latest").exec(), PullEventStreamItem.class) - ) {; + ) { assertThat(reader.readItem(), allOf( hasProperty("status", equalTo("Pulling repository busybox")), From f4d5a4dd2cb51934e61dff5d7df213b0130e8532 Mon Sep 17 00:00:00 2001 From: "alex.collins" Date: Wed, 6 May 2015 23:04:29 +0100 Subject: [PATCH 424/452] Revert "Quietly catch IndexOutOfBoundsException." This reverts commit 5697c60bc4581eff46cc79f735f26b8c658ab2d5. --- .../github/dockerjava/core/command/EventStreamReaderITest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java b/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java index b7d86de0..dfc330d9 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java @@ -39,7 +39,7 @@ public void pullCanBeStreamed() throws Exception { try (EventStreamReader reader = new EventStreamReader<>( dockerClient.pullImageCmd("busybox:latest").exec(), PullEventStreamItem.class) - ) { + ) {; assertThat(reader.readItem(), allOf( hasProperty("status", equalTo("Pulling repository busybox")), From 6fa074ba40cf54e9043dc6a80db142c76968bb9b Mon Sep 17 00:00:00 2001 From: Vangie Du Date: Thu, 7 May 2015 15:51:01 +0800 Subject: [PATCH 425/452] Add ulimit support --- .../dockerjava/api/model/HostConfig.java | 20 +++-- .../github/dockerjava/api/model/Ulimit.java | 64 ++++++++++++++++ .../command/CreateContainerCmdImplTest.java | 73 +++++++++---------- 3 files changed, 115 insertions(+), 42 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/model/Ulimit.java diff --git a/src/main/java/com/github/dockerjava/api/model/HostConfig.java b/src/main/java/com/github/dockerjava/api/model/HostConfig.java index 18fd3407..9973e625 100644 --- a/src/main/java/com/github/dockerjava/api/model/HostConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/HostConfig.java @@ -1,12 +1,10 @@ package com.github.dockerjava.api.model; -import java.util.Map; - -import org.apache.commons.lang.builder.ToStringBuilder; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.ToStringBuilder; + @JsonIgnoreProperties(ignoreUnknown = true) public class HostConfig { @@ -59,13 +57,16 @@ public class HostConfig { @JsonProperty("ExtraHosts") private String[] extraHosts; + @JsonProperty("Ulimits") + private Ulimit[] ulimits; + public HostConfig() { } public HostConfig(Bind[] binds, Link[] links, LxcConf[] lxcConf, Ports portBindings, boolean publishAllPorts, boolean privileged, String[] dns, String[] dnsSearch, VolumesFrom[] volumesFrom, String containerIDFile, Capability[] capAdd, Capability[] capDrop, RestartPolicy restartPolicy, String networkMode, Device[] devices, - String[] extraHosts) { + String[] extraHosts, Ulimit[] ulimits) { this.binds = new Binds(binds); this.links = new Links(links); this.lxcConf = lxcConf; @@ -82,6 +83,7 @@ public HostConfig(Bind[] binds, Link[] links, LxcConf[] lxcConf, Ports portBindi this.networkMode = networkMode; this.devices = devices; this.extraHosts = extraHosts; + this.ulimits = ulimits; } @@ -151,6 +153,10 @@ public Capability[] getCapDrop() { return capDrop; } + public Ulimit[] getUlimits() { + return ulimits; + } + @JsonIgnore public void setBinds(Bind... binds) { this.binds = new Binds(binds); @@ -217,6 +223,10 @@ public void setExtraHosts(String[] extraHosts) { this.extraHosts = extraHosts; } + public void setUlimits(Ulimit[] ulimits) { + this.ulimits = ulimits; + } + @Override public String toString() { return ToStringBuilder.reflectionToString(this); diff --git a/src/main/java/com/github/dockerjava/api/model/Ulimit.java b/src/main/java/com/github/dockerjava/api/model/Ulimit.java new file mode 100644 index 00000000..d5fac09c --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/Ulimit.java @@ -0,0 +1,64 @@ +package com.github.dockerjava.api.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * @author Vangie Du (duwan@live.com) + */ +public class Ulimit { + + @JsonProperty("Name") + private String name ; + + @JsonProperty("Soft") + private int soft; + + @JsonProperty("Hard") + private int hard; + + public Ulimit() { + + } + + public Ulimit(String name, int soft, int hard) { + checkNotNull(name, "Name is null"); + + this.name = name; + this.soft = soft; + this.hard = hard; + } + + public String getName() { + return name; + } + + public int getSoft() { + return soft; + } + + public int getHard() { + return hard; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Ulimit) { + Ulimit other = (Ulimit) obj; + return new EqualsBuilder() + .append(name, other.getName()) + .append(soft, other.getSoft()) + .append(hard, other.getHard()).isEquals(); + } else + return super.equals(obj); + + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(name).append(soft).append(hard).toHashCode(); + } +} diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index 4feadc6b..c37f4848 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -1,48 +1,23 @@ package com.github.dockerjava.core.command; -import static com.github.dockerjava.api.model.Capability.MKNOD; -import static com.github.dockerjava.api.model.Capability.NET_ADMIN; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItemInArray; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isEmptyString; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.startsWith; +import com.github.dockerjava.api.ConflictException; +import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.model.*; +import com.github.dockerjava.client.AbstractDockerClientTest; +import org.testng.ITestResult; +import org.testng.annotations.*; import java.lang.reflect.Method; import java.security.SecureRandom; import java.util.Arrays; import java.util.UUID; -import org.testng.ITestResult; -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 com.github.dockerjava.api.ConflictException; -import com.github.dockerjava.api.DockerException; -import com.github.dockerjava.api.command.CreateContainerResponse; -import com.github.dockerjava.api.command.InspectContainerResponse; -import com.github.dockerjava.api.model.AccessMode; -import com.github.dockerjava.api.model.Bind; -import com.github.dockerjava.api.model.Device; -import com.github.dockerjava.api.model.ExposedPort; -import com.github.dockerjava.api.model.HostConfig; -import com.github.dockerjava.api.model.Link; -import com.github.dockerjava.api.model.Ports; -import com.github.dockerjava.api.model.RestartPolicy; -import com.github.dockerjava.api.model.Volume; -import com.github.dockerjava.api.model.VolumeRW; -import com.github.dockerjava.api.model.Volumes; -import com.github.dockerjava.api.model.VolumesFrom; -import com.github.dockerjava.client.AbstractDockerClientTest; +import static com.github.dockerjava.api.model.Capability.MKNOD; +import static com.github.dockerjava.api.model.Capability.NET_ADMIN; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; @Test(groups = "integration") public class CreateContainerCmdImplTest extends AbstractDockerClientTest { @@ -564,5 +539,29 @@ public void createContainerWithMacAddress() throws DockerException { assertEquals(inspectContainerResponse.getConfig().getMacAddress(), "00:80:41:ae:fd:7e"); } + + @Test + public void createContainerWithULimits() throws DockerException { + + Ulimit[] ulimits = {new Ulimit("nproc", 709, 1026), new Ulimit("nofile", 1024, 4096)}; + + HostConfig hostConfig = new HostConfig(); + hostConfig.setUlimits(ulimits); + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withName("container") + .withHostConfig(hostConfig).exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getUlimits()), + containsInAnyOrder(new Ulimit("nproc", 709, 1026), new Ulimit("nofile", 1024, 4096))); + + } } From bdbdd7521b39945c64c3c75535f16aa18e0cc4ea Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Thu, 7 May 2015 11:53:12 +0300 Subject: [PATCH 426/452] Added framework classes for JSON serialization-deserialization tests --- .../test/serdes/AbstractJSONResourceRef.java | 31 +++++ .../test/serdes/JSONResourceRef.java | 37 ++++++ .../test/serdes/JSONTestHelper.java | 110 ++++++++++++++++++ 3 files changed, 178 insertions(+) create mode 100644 src/test/java/com/github/dockerjava/test/serdes/AbstractJSONResourceRef.java create mode 100644 src/test/java/com/github/dockerjava/test/serdes/JSONResourceRef.java create mode 100644 src/test/java/com/github/dockerjava/test/serdes/JSONTestHelper.java diff --git a/src/test/java/com/github/dockerjava/test/serdes/AbstractJSONResourceRef.java b/src/test/java/com/github/dockerjava/test/serdes/AbstractJSONResourceRef.java new file mode 100644 index 00000000..882b3b01 --- /dev/null +++ b/src/test/java/com/github/dockerjava/test/serdes/AbstractJSONResourceRef.java @@ -0,0 +1,31 @@ +/* + * Copyright 2015 CloudBees Inc., Oleg Nenashev. + * + * Licensed 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.github.dockerjava.test.serdes; + +/** + * Default implementation of the Resource reference. + * @author Oleg Nenashev + */ +public abstract class AbstractJSONResourceRef implements JSONResourceRef { + /** + * Gets a class which stores resources. + * @return Reference class by default. + */ + @Override + public Class getResourceClass() { + return this.getClass(); + } +} diff --git a/src/test/java/com/github/dockerjava/test/serdes/JSONResourceRef.java b/src/test/java/com/github/dockerjava/test/serdes/JSONResourceRef.java new file mode 100644 index 00000000..96e5df72 --- /dev/null +++ b/src/test/java/com/github/dockerjava/test/serdes/JSONResourceRef.java @@ -0,0 +1,37 @@ +/* + * Copyright 2015 Oleg Nenashev. + * + * Licensed 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.github.dockerjava.test.serdes; + +import java.io.IOException; + +/** + * References JSON resources, which + * @author Oleg Nenashev + */ +public interface JSONResourceRef { + + /** + * Gets the resource file name under the class. + * @return File name, which is stored under the resource class + */ + String getFileName(); + + /** + * Gets a class which stores resources. + * @return Class to be used as a resource source + */ + Class getResourceClass(); +} diff --git a/src/test/java/com/github/dockerjava/test/serdes/JSONTestHelper.java b/src/test/java/com/github/dockerjava/test/serdes/JSONTestHelper.java new file mode 100644 index 00000000..b465b2aa --- /dev/null +++ b/src/test/java/com/github/dockerjava/test/serdes/JSONTestHelper.java @@ -0,0 +1,110 @@ +/* + * Copyright 2015 Oleg Nenashev. + * + * Licensed 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.github.dockerjava.test.serdes; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.command.CommandJSONSamples; +import java.io.IOException; +import java.io.InputStream; +import org.apache.commons.io.IOUtils; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +/** + * Provides helper methods for serialization-deserialization tests + * @author Oleg Nenashev + * @since TODO + */ +public class JSONTestHelper { + + /** + * Reads JSON String from the specified resource + * @param resource JSON File + * @return JSON String + * @throws IOException JSON Conversion error + */ + public static String readString(JSONResourceRef resource) throws IOException { + InputStream istream = CommandJSONSamples.class.getResourceAsStream(resource.getFileName()); + if (istream == null) { + throw new IOException("Cannot retrieve resource " + resource.getFileName()); + } + return IOUtils.toString(istream, "UTF-8"); + } + + /** + * Reads item from the resource. + * @param Data class to be read + * @param resource Resource reference + * @param tclass Class entry + * @return Item + * @throws IOException JSON conversion error + */ + public static TClass readObject(JSONResourceRef resource, Class tclass) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + String str = readString(resource); + return mapper.readValue(str, tclass); + } + + /** + * Basic serialization-deserialization consistency test for the resource. + * @param Data class + * @param resource Resource reference + * @param tclass Class entry + * @throws IOException JSON conversion error + * @throws AssertionError Validation error + * @return Deserialized object after the roundtrip + */ + public static TClass testRoundTrip(JSONResourceRef resource, Class tclass) + throws IOException, AssertionError { + TClass item = readObject(resource, tclass); + assertNotNull(item); + return testRoundTrip(item, tclass); + } + + /** + * Performs roundtrip test for the specified class. + * @param Item class + * @param item Item to be checked + * @return Deserialized object after the roundtrip + * @throws IOException JSON Conversion error + * @throws AssertionError Validation error + */ + @SuppressWarnings("unchecked") + public static TClass testRoundTrip(TClass item) + throws IOException, AssertionError { + return testRoundTrip(item, (Class)item.getClass()); + } + + /** + * Performs roundtrip test for the specified class. + * @param Item class + * @param item Item to be checked + * @param asclass Class to be used during conversions + * @return Deserialized object after the roundtrip + * @throws IOException JSON Conversion error + * @throws AssertionError Validation error + */ + public static TClass testRoundTrip(TClass item, Class asclass) + throws IOException, AssertionError { + ObjectMapper mapper = new ObjectMapper(); + + String inputItemString = mapper.writeValueAsString(item); + TClass convertedItem = mapper.readValue(inputItemString, asclass); + String convertedItemString = mapper.writeValueAsString(convertedItem); + assertEquals(convertedItemString, inputItemString, "JSONs must be equal after the second roundtrip"); + return convertedItem; + } +} From a221a94edb8018321b5c49160a5c51df23a9541d Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Thu, 7 May 2015 11:53:50 +0300 Subject: [PATCH 427/452] Direct unit tests for https://github.com/docker-java/docker-java/issues/211 --- .../api/command/CommandJSONSamples.java | 45 ++++++ .../command/InspectContainerResponseTest.java | 51 ++++++ .../inspectContainerResponse_empty.json | 115 +++++++++++++ .../inspectContainerResponse_full.json | 153 ++++++++++++++++++ 4 files changed, 364 insertions(+) create mode 100644 src/test/java/com/github/dockerjava/api/command/CommandJSONSamples.java create mode 100644 src/test/java/com/github/dockerjava/api/command/InspectContainerResponseTest.java create mode 100644 src/test/resources/com/github/dockerjava/api/command/inspectContainerResponse_empty.json create mode 100644 src/test/resources/com/github/dockerjava/api/command/inspectContainerResponse_full.json diff --git a/src/test/java/com/github/dockerjava/api/command/CommandJSONSamples.java b/src/test/java/com/github/dockerjava/api/command/CommandJSONSamples.java new file mode 100644 index 00000000..500919fd --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/command/CommandJSONSamples.java @@ -0,0 +1,45 @@ +/* + * Copyright 2015 CloudBees Inc., Oleg Nenashev. + * + * Licensed 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.github.dockerjava.api.command; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.test.serdes.AbstractJSONResourceRef; +import com.github.dockerjava.test.serdes.JSONResourceRef; +import java.io.IOException; +import java.io.InputStream; +import org.apache.commons.io.IOUtils; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +/** + * References test resources and provides basic tests functionality. + * @author Oleg Nenashev + */ +public enum CommandJSONSamples implements JSONResourceRef { + + inspectContainerResponse_full, + inspectContainerResponse_empty; + + @Override + public String getFileName() { + return this + ".json"; + } + + @Override + public Class getResourceClass() { + return CommandJSONSamples.class; + } +} diff --git a/src/test/java/com/github/dockerjava/api/command/InspectContainerResponseTest.java b/src/test/java/com/github/dockerjava/api/command/InspectContainerResponseTest.java new file mode 100644 index 00000000..2e294b14 --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/command/InspectContainerResponseTest.java @@ -0,0 +1,51 @@ +/* + * Copyright 2015 CloudBees Inc., Oleg Nenashev. + * + * Licensed 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.github.dockerjava.api.command; + +import static com.github.dockerjava.test.serdes.JSONTestHelper.testRoundTrip; +import java.io.IOException; +import static org.testng.Assert.*; +import org.testng.annotations.Test; + +/** + * Tests for {@link InspectContainerResponse}. + * @author Oleg Nenashev + */ +public class InspectContainerResponseTest { + + @Test + public void roundTrip_full() throws IOException { + InspectContainerResponse[] responses = testRoundTrip( + CommandJSONSamples.inspectContainerResponse_full, + InspectContainerResponse[].class); + assertEquals(1, responses.length); + final InspectContainerResponse response = responses[0]; + + // Check volumes: https://github.com/docker-java/docker-java/issues/211 + assertEquals(response.getVolumes().length, 2); + assertEquals(response.getVolumesRW().length, 2); + assertEquals(response.getVolumes()[1].getContainerPath(), "/bar/foo/myvol2"); + assertEquals(response.getVolumes()[1].getHostPath(), "/path2"); + assertEquals(response.getVolumesRW()[1].getVolume().getPath(), "/bar/foo/myvol2"); + assertFalse(response.getVolumesRW()[1].getAccessMode().toBoolean()); + assertTrue(response.getVolumesRW()[0].getAccessMode().toBoolean()); + } + + @Test + public void roundTrip_empty() throws IOException { + testRoundTrip(CommandJSONSamples.inspectContainerResponse_empty, InspectContainerResponse[].class); + } +} diff --git a/src/test/resources/com/github/dockerjava/api/command/inspectContainerResponse_empty.json b/src/test/resources/com/github/dockerjava/api/command/inspectContainerResponse_empty.json new file mode 100644 index 00000000..ea31d6f3 --- /dev/null +++ b/src/test/resources/com/github/dockerjava/api/command/inspectContainerResponse_empty.json @@ -0,0 +1,115 @@ +[{ + "AppArmorProfile": "", + "Args": [ ], + "Config": { + "AttachStderr": true, + "AttachStdin": true, + "AttachStdout": true, + "Cmd": [ ], + "CpuShares": 0, + "Cpuset": "", + "Domainname": "", + "Entrypoint": null, + "Env": [ ], + "ExposedPorts": { }, + "Hostname": "469e5edd8d5b", + "Image": "jenkinsci/workflow-demo", + "Labels": {}, + "MacAddress": "", + "Memory": 0, + "MemorySwap": 0, + "NetworkDisabled": false, + "OnBuild": null, + "OpenStdin": true, + "PortSpecs": null, + "StdinOnce": true, + "Tty": true, + "User": "", + "Volumes": null, + "WorkingDir": "/var/lib/jenkins/workflow-plugin-pipeline-demo" + }, + "Created": "2015-04-29T11:55:42.968262967Z", + "Driver": "aufs", + "ExecDriver": "native-0.2", + "ExecIDs": null, + "HostConfig": { + "Binds": null, + "CapAdd": null, + "CapDrop": null, + "CgroupParent": "", + "ContainerIDFile": "", + "CpuShares": 0, + "CpusetCpus": "", + "Devices": [], + "Dns": null, + "DnsSearch": null, + "ExtraHosts": null, + "IpcMode": "", + "Links": null, + "LogConfig": { + "Config": null, + "Type": "json-file" + }, + "LxcConf": [], + "Memory": 0, + "MemorySwap": 0, + "NetworkMode": "bridge", + "PidMode": "", + "PortBindings": { + "8080/tcp": [ ] + }, + "Privileged": false, + "PublishAllPorts": false, + "ReadonlyRootfs": false, + "RestartPolicy": { + "MaximumRetryCount": 0, + "Name": "" + }, + "SecurityOpt": null, + "Ulimits": null, + "VolumesFrom": null + }, + "HostnamePath": "/mnt/sda1/var/lib/docker/containers/469e5edd8d5b33e3c905a7ffc97360ec6ee211d6782815fbcd144568045819e1/hostname", + "HostsPath": "/mnt/sda1/var/lib/docker/containers/469e5edd8d5b33e3c905a7ffc97360ec6ee211d6782815fbcd144568045819e1/hosts", + "Id": "469e5edd8d5b33e3c905a7ffc97360ec6ee211d6782815fbcd144568045819e1", + "Image": "4300417211ebb75b48b06ed5640d641778f312072d24b37978682345cbb362b1", + "LogPath": "/mnt/sda1/var/lib/docker/containers/469e5edd8d5b33e3c905a7ffc97360ec6ee211d6782815fbcd144568045819e1/469e5edd8d5b33e3c905a7ffc97360ec6ee211d6782815fbcd144568045819e1-json.log", + "MountLabel": "", + "Name": "/desperate_babbage", + "NetworkSettings": { + "Bridge": "docker0", + "Gateway": "172.17.42.1", + "GlobalIPv6Address": "", + "GlobalIPv6PrefixLen": 0, + "IPAddress": "172.17.0.2", + "IPPrefixLen": 16, + "IPv6Gateway": "", + "LinkLocalIPv6Address": "fe80::42:acff:fe11:2", + "LinkLocalIPv6PrefixLen": 64, + "MacAddress": "02:42:ac:11:00:02", + "PortMapping": null, + "Ports": { + "22/tcp": null, + "8080/tcp": [ ] + } + }, + "Path": "/bin/sh", + "ProcessLabel": "", + "ResolvConfPath": "/mnt/sda1/var/lib/docker/containers/469e5edd8d5b33e3c905a7ffc97360ec6ee211d6782815fbcd144568045819e1/resolv.conf", + "RestartCount": 0, + "State": { + "Dead": false, + "Error": "", + "ExitCode": 0, + "FinishedAt": "0001-01-01T00:00:00Z", + "OOMKilled": false, + "Paused": false, + "Pid": 898, + "Restarting": false, + "Running": true, + "StartedAt": "2015-04-29T11:55:43.464717907Z" + }, + "Volumes": {}, + "VolumesRW": {} +} +] diff --git a/src/test/resources/com/github/dockerjava/api/command/inspectContainerResponse_full.json b/src/test/resources/com/github/dockerjava/api/command/inspectContainerResponse_full.json new file mode 100644 index 00000000..c4383ef1 --- /dev/null +++ b/src/test/resources/com/github/dockerjava/api/command/inspectContainerResponse_full.json @@ -0,0 +1,153 @@ +[{ + "AppArmorProfile": "", + "Args": [ + "-c", + "/var/lib/jenkins/run.sh" + ], + "Config": { + "AttachStderr": true, + "AttachStdin": true, + "AttachStdout": true, + "Cmd": [ + "/bin/sh", + "-c", + "/var/lib/jenkins/run.sh" + ], + "CpuShares": 0, + "Cpuset": "", + "Domainname": "", + "Entrypoint": null, + "Env": [ + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "MAVEN_VERSION=3.3.1", + "JETTY_VERSION=9.2.9.v20150224", + "REV=107ea141f5c7581056c6eb53d2ccd222cdf0d58c" + ], + "ExposedPorts": { + "22/tcp": {}, + "8080/tcp": {}, + "8081/tcp": {} + }, + "Hostname": "469e5edd8d5b", + "Image": "jenkinsci/workflow-demo", + "Labels": {}, + "MacAddress": "", + "Memory": 0, + "MemorySwap": 0, + "NetworkDisabled": false, + "OnBuild": null, + "OpenStdin": true, + "PortSpecs": null, + "StdinOnce": true, + "Tty": true, + "User": "", + "Volumes": null, + "WorkingDir": "/var/lib/jenkins/workflow-plugin-pipeline-demo" + }, + "Created": "2015-04-29T11:55:42.968262967Z", + "Driver": "aufs", + "ExecDriver": "native-0.2", + "ExecIDs": null, + "HostConfig": { + "Binds": null, + "CapAdd": null, + "CapDrop": null, + "CgroupParent": "", + "ContainerIDFile": "", + "CpuShares": 0, + "CpusetCpus": "", + "Devices": [], + "Dns": null, + "DnsSearch": null, + "ExtraHosts": null, + "IpcMode": "", + "Links": null, + "LogConfig": { + "Config": null, + "Type": "json-file" + }, + "LxcConf": [], + "Memory": 0, + "MemorySwap": 0, + "NetworkMode": "bridge", + "PidMode": "", + "PortBindings": { + "8080/tcp": [ + { + "HostIp": "", + "HostPort": "8080" + } + ], + "8081/tcp": [ + { + "HostIp": "", + "HostPort": "8081" + } + ] + }, + "Privileged": false, + "PublishAllPorts": false, + "ReadonlyRootfs": false, + "RestartPolicy": { + "MaximumRetryCount": 0, + "Name": "" + }, + "SecurityOpt": null, + "Ulimits": null, + "VolumesFrom": null + }, + "HostnamePath": "/mnt/sda1/var/lib/docker/containers/469e5edd8d5b33e3c905a7ffc97360ec6ee211d6782815fbcd144568045819e1/hostname", + "HostsPath": "/mnt/sda1/var/lib/docker/containers/469e5edd8d5b33e3c905a7ffc97360ec6ee211d6782815fbcd144568045819e1/hosts", + "Id": "469e5edd8d5b33e3c905a7ffc97360ec6ee211d6782815fbcd144568045819e1", + "Image": "4300417211ebb75b48b06ed5640d641778f312072d24b37978682345cbb362b1", + "LogPath": "/mnt/sda1/var/lib/docker/containers/469e5edd8d5b33e3c905a7ffc97360ec6ee211d6782815fbcd144568045819e1/469e5edd8d5b33e3c905a7ffc97360ec6ee211d6782815fbcd144568045819e1-json.log", + "MountLabel": "", + "Name": "/desperate_babbage", + "NetworkSettings": { + "Bridge": "docker0", + "Gateway": "172.17.42.1", + "GlobalIPv6Address": "", + "GlobalIPv6PrefixLen": 0, + "IPAddress": "172.17.0.2", + "IPPrefixLen": 16, + "IPv6Gateway": "", + "LinkLocalIPv6Address": "fe80::42:acff:fe11:2", + "LinkLocalIPv6PrefixLen": 64, + "MacAddress": "02:42:ac:11:00:02", + "PortMapping": null, + "Ports": { + "22/tcp": null, + "8080/tcp": [ + { + "HostIp": "0.0.0.0", + "HostPort": "8080" + } + ], + "8081/tcp": [ + { + "HostIp": "0.0.0.0", + "HostPort": "8081" + } + ] + } + }, + "Path": "/bin/sh", + "ProcessLabel": "", + "ResolvConfPath": "/mnt/sda1/var/lib/docker/containers/469e5edd8d5b33e3c905a7ffc97360ec6ee211d6782815fbcd144568045819e1/resolv.conf", + "RestartCount": 0, + "State": { + "Dead": false, + "Error": "", + "ExitCode": 0, + "FinishedAt": "0001-01-01T00:00:00Z", + "OOMKilled": false, + "Paused": false, + "Pid": 898, + "Restarting": false, + "Running": true, + "StartedAt": "2015-04-29T11:55:43.464717907Z" + }, + "Volumes": { "/foo/bar/myvol":"/path1", "/bar/foo/myvol2":"/path2" }, + "VolumesRW": { "/foo/bar/myvol": true, "/bar/foo/myvol2": false } +} +] From c31c4aceba8a883bb5d11a9e8a78c0f15f87fd65 Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Thu, 7 May 2015 11:54:20 +0300 Subject: [PATCH 428/452] Add missing serializers to resolve https://github.com/docker-java/docker-java/issues/211 Resolves #211 --- .../dockerjava/api/model/VolumeBinds.java | 17 +++++++++++++++++ .../github/dockerjava/api/model/VolumesRW.java | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java b/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java index 62ebc118..e23ddc9e 100644 --- a/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java +++ b/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java @@ -1,5 +1,6 @@ package com.github.dockerjava.api.model; +import com.fasterxml.jackson.core.JsonGenerator; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; @@ -12,11 +13,15 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.node.NullNode; // This is not going to be serialized @JsonDeserialize(using = VolumeBinds.Deserializer.class) +@JsonSerialize(using = VolumeBinds.Serializer.class) public class VolumeBinds { private final VolumeBind[] binds; @@ -28,6 +33,18 @@ public VolumeBind[] getBinds() { return binds; } + public static final class Serializer extends JsonSerializer { + + @Override + public void serialize(VolumeBinds value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeStartObject(); + for (final VolumeBind bind : value.binds) { + jgen.writeStringField(bind.getContainerPath(), bind.getHostPath()); + } + jgen.writeEndObject(); + } + } + public static final class Deserializer extends JsonDeserializer { @Override public VolumeBinds deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { diff --git a/src/main/java/com/github/dockerjava/api/model/VolumesRW.java b/src/main/java/com/github/dockerjava/api/model/VolumesRW.java index 223f518c..a898ed57 100644 --- a/src/main/java/com/github/dockerjava/api/model/VolumesRW.java +++ b/src/main/java/com/github/dockerjava/api/model/VolumesRW.java @@ -1,5 +1,6 @@ package com.github.dockerjava.api.model; +import com.fasterxml.jackson.core.JsonGenerator; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; @@ -12,10 +13,14 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.node.NullNode; // This is not going to be serialized +@JsonSerialize(using = VolumesRW.Serializer.class) @JsonDeserialize(using = VolumesRW.Deserializer.class) public class VolumesRW { private final VolumeRW[] volumesRW; @@ -28,6 +33,19 @@ public VolumeRW[] getVolumesRW() { return volumesRW; } + public static final class Serializer extends JsonSerializer { + + @Override + public void serialize(VolumesRW value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeStartObject(); + for (final VolumeRW volumeRW : value.volumesRW) { + jgen.writeBooleanField(volumeRW.getVolume().getPath(), volumeRW.getAccessMode().toBoolean()); + } + jgen.writeEndObject(); + } + + } + public static final class Deserializer extends JsonDeserializer { @Override public VolumesRW deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { From d6e8be31202830302b1ab5d00b20a6f7e8d73872 Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Thu, 7 May 2015 12:00:45 +0300 Subject: [PATCH 429/452] Add roundtrip spotcheck to InspectExecCmdImplTest --- .../dockerjava/core/command/InspectExecCmdImplTest.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/github/dockerjava/core/command/InspectExecCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/InspectExecCmdImplTest.java index 2deddca0..f1270f4e 100644 --- a/src/test/java/com/github/dockerjava/core/command/InspectExecCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/InspectExecCmdImplTest.java @@ -3,8 +3,11 @@ import com.github.dockerjava.api.DockerException; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.ExecCreateCmdResponse; +import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.command.InspectExecResponse; import com.github.dockerjava.client.AbstractDockerClientTest; +import com.github.dockerjava.test.serdes.JSONTestHelper; +import java.io.IOException; import org.testng.ITestResult; import org.testng.annotations.*; @@ -41,7 +44,7 @@ public void afterMethod(ITestResult result) { } @Test(groups = "ignoreInCircleCi") - public void inspectExecTest() { + public void inspectExecTest() throws IOException { String containerName = "generated_" + new SecureRandom().nextInt(); CreateContainerResponse container = dockerClient @@ -93,5 +96,9 @@ public void inspectExecTest() { InspectExecResponse third = dockerClient.inspectExecCmd(checkFileCmdCreateResponse.getId()).exec(); assertThat(third.getExitCode(), is(0)); + // Get container info and check its roundtrip to ensure the consistency + InspectContainerResponse containerInfo = dockerClient.inspectContainerCmd(container.getId()).exec(); + assertEquals(containerInfo.getId(), container.getId()); + JSONTestHelper.testRoundTrip(containerInfo); } } From 390b2f9442eee2014fd1b48df8876582dfef4856 Mon Sep 17 00:00:00 2001 From: Xavier Fournet Date: Sat, 9 May 2015 00:35:59 +0200 Subject: [PATCH 430/452] Use a common path relativize method to fix testDockerIgnore and testNonstandard2 * testDockerIgnore was failing if your source checkout directory contains a 'b' char. stripStart function was misused here * testNonstandard2 was failing on Windows * other usage of relativize has been changed to this relativize method (extract from CompressArchiveUtil) --- .../dockerjava/core/CompressArchiveUtil.java | 9 +++---- .../github/dockerjava/core/FilePathUtil.java | 24 +++++++++++++++++++ .../core/GoLangMatchFileFilter.java | 5 +--- .../core/command/BuildImageCmdImpl.java | 5 ++-- .../core/dockerfile/Dockerfile.java | 5 ++-- 5 files changed, 32 insertions(+), 16 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/core/FilePathUtil.java diff --git a/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java b/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java index f07fa1b2..297adc76 100644 --- a/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java +++ b/src/main/java/com/github/dockerjava/core/CompressArchiveUtil.java @@ -6,6 +6,8 @@ import java.io.*; +import static com.github.dockerjava.core.FilePathUtil.relativize; + public class CompressArchiveUtil { public static File archiveTARFiles(File base, Iterable files, String archiveNameWithOutExtension) throws IOException { @@ -15,7 +17,7 @@ public static File archiveTARFiles(File base, Iterable files, String archi tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); for (File file : files) { TarArchiveEntry tarEntry = new TarArchiveEntry(file); - tarEntry.setName(relativize(base.getCanonicalFile(), file.getCanonicalFile())); + tarEntry.setName(relativize(base, file)); if (!file.isDirectory()) { if (file.canExecute()) { @@ -36,9 +38,4 @@ public static File archiveTARFiles(File base, Iterable files, String archi return tarFile; } - - public static String relativize(File base, File absolute) { - String relative = base.toURI().relativize(absolute.toURI()).getPath(); - return relative; - } } diff --git a/src/main/java/com/github/dockerjava/core/FilePathUtil.java b/src/main/java/com/github/dockerjava/core/FilePathUtil.java new file mode 100644 index 00000000..3fc91021 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/FilePathUtil.java @@ -0,0 +1,24 @@ +package com.github.dockerjava.core; + +import java.io.*; +import com.github.dockerjava.api.DockerClientException; + +public class FilePathUtil { + + /** + * Return the relative path. Path elements are separated with / char. + * @param baseDir a parent directory of {@code file} + * @param file the file to get the relative path + * @return the relative path + */ + public static String relativize(File baseDir, File file) { + try { + baseDir = baseDir.getCanonicalFile(); + file = file.getCanonicalFile(); + + return baseDir.toURI().relativize(file.toURI()).getPath(); + } catch (IOException e) { + throw new DockerClientException(e.getMessage(), e); + } + } +} diff --git a/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java b/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java index aa88287b..33e0f2a4 100644 --- a/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java +++ b/src/main/java/com/github/dockerjava/core/GoLangMatchFileFilter.java @@ -3,8 +3,6 @@ */ package com.github.dockerjava.core; -import static org.apache.commons.lang.StringUtils.stripStart; - import java.io.File; import java.util.List; @@ -25,8 +23,7 @@ public GoLangMatchFileFilter(File base, List patterns) { @Override public boolean accept(File file) { - String basePath = base.getAbsolutePath() + File.separatorChar; - String relativePath = stripStart(file.getAbsolutePath(), basePath); + String relativePath = FilePathUtil.relativize(base, file); boolean match = GoLangFileMatch.match(patterns, relativePath); return !match; diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index 046565d3..dbccda5f 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -8,8 +8,8 @@ import com.github.dockerjava.api.command.BuildImageCmd; import com.github.dockerjava.api.model.AuthConfigurations; +import com.github.dockerjava.core.FilePathUtil; import com.github.dockerjava.core.dockerfile.Dockerfile; -import com.google.common.base.Optional; /** * @@ -125,8 +125,7 @@ public boolean hasPullEnabled() { @Override public String getPathToDockerfile() { - int baseLen = baseDirectory.getAbsolutePath().length(); - return dockerFile.getAbsolutePath().substring(baseLen+1); + return FilePathUtil.relativize(baseDirectory, dockerFile); } @Override diff --git a/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java b/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java index 21d938ff..f5b25f2b 100644 --- a/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java +++ b/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java @@ -2,6 +2,7 @@ import com.github.dockerjava.api.DockerClientException; import com.github.dockerjava.core.CompressArchiveUtil; +import com.github.dockerjava.core.FilePathUtil; import com.github.dockerjava.core.GoLangFileMatch; import com.github.dockerjava.core.GoLangFileMatchException; import com.github.dockerjava.core.GoLangMatchFileFilter; @@ -23,7 +24,6 @@ import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Optional; -import com.google.common.base.Predicate; import com.google.common.collect.Collections2; /** @@ -209,8 +209,7 @@ private void processAddStatement(DockerfileStatement.Add add) throws IOException } else if (!src.exists()) { filesToAdd.addAll(resolveWildcards(src, ignores)); } else if (!GoLangFileMatch.match(ignores, - CompressArchiveUtil.relativize(dockerFolder, - src))) { + FilePathUtil.relativize(dockerFolder, src))) { filesToAdd.add(src); } else { throw new DockerClientException( From 3bdb89994e7fe35b532ef26efd16ff9f00faac0a Mon Sep 17 00:00:00 2001 From: Xavier Fournet Date: Sat, 9 May 2015 01:18:44 +0200 Subject: [PATCH 431/452] Fix testDockerBuilderAddFilesViaWildcard on Windows However i'm quite skeptical on the Dockerfile.resolveWildcards method --- .../core/dockerfile/Dockerfile.java | 32 +++++++------------ 1 file changed, 12 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java b/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java index f5b25f2b..802299a7 100644 --- a/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java +++ b/src/main/java/com/github/dockerjava/core/dockerfile/Dockerfile.java @@ -189,33 +189,25 @@ private void processAddStatement(DockerfileStatement.Add add) throws IOException File src = new File(resource); if (!src.isAbsolute()) { - src = new File(dockerFolder, resource) - .getCanonicalFile(); + src = new File(dockerFolder, resource); } else { throw new DockerClientException(String.format( "Source file %s must be relative to %s", src, dockerFolder)); } - // if (!src.exists()) { - // throw new DockerClientException(String.format( - // "Source file %s doesn't exist", src)); - // } - if (src.isDirectory()) { - Collection files = FileUtils.listFiles(src, - new GoLangMatchFileFilter(src, ignores), - TrueFileFilter.INSTANCE); - filesToAdd.addAll(files); - } else if (!src.exists()) { - filesToAdd.addAll(resolveWildcards(src, ignores)); - } else if (!GoLangFileMatch.match(ignores, - FilePathUtil.relativize(dockerFolder, src))) { - filesToAdd.add(src); + if (src.exists()) { + src = src.getCanonicalFile(); + if (src.isDirectory()) { + Collection files = FileUtils.listFiles(src, new GoLangMatchFileFilter(src, ignores), TrueFileFilter.INSTANCE); + filesToAdd.addAll(files); + } else if (!GoLangFileMatch.match(ignores, FilePathUtil.relativize(dockerFolder, src))) { + filesToAdd.add(src); + } else { + throw new DockerClientException(String.format("Source file %s is excluded by .dockerignore file", src)); + } } else { - throw new DockerClientException( - String.format( - "Source file %s is excluded by .dockerignore file", - src)); + filesToAdd.addAll(resolveWildcards(src, ignores)); } } } From 0e52d21471f82368b1ad950e6e49916fc133c8b3 Mon Sep 17 00:00:00 2001 From: Xavier Fournet Date: Sat, 9 May 2015 01:27:44 +0200 Subject: [PATCH 432/452] Fix canCloseFrameReaderAndReadExpectedLines test on Windows --- .../github/dockerjava/core/command/FrameReaderITest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java index 0cf08e95..0c22fc08 100644 --- a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java +++ b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java @@ -38,8 +38,8 @@ public void deleteDockerContainerImage() throws Exception { public void canCloseFrameReaderAndReadExpectedLines() throws Exception { try (FrameReader reader = new FrameReader(getLoggerStream())) { - assertEquals(reader.readFrame(), new Frame(StreamType.STDOUT, String.format("to stdout%n").getBytes())); - assertEquals(reader.readFrame(), new Frame(StreamType.STDERR, String.format("to stderr%n").getBytes())); + assertEquals(reader.readFrame(), new Frame(StreamType.STDOUT, "to stdout\n".getBytes())); + assertEquals(reader.readFrame(), new Frame(StreamType.STDERR, "to stderr\n".getBytes())); assertNull(reader.readFrame()); } } @@ -83,4 +83,4 @@ public void run() { thread.join(); } -} \ No newline at end of file +} From d61b7c4af08cfcc9bbdc59e450345673dada35dc Mon Sep 17 00:00:00 2001 From: Xavier Fournet Date: Sat, 9 May 2015 12:54:10 +0200 Subject: [PATCH 433/452] Fix regression when building an image from a TAR input stream --- .../core/command/BuildImageCmdImpl.java | 6 +- .../core/command/BuildImageCmdImplTest.java | 63 ++++++++++++------- 2 files changed, 45 insertions(+), 24 deletions(-) diff --git a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java index dbccda5f..ef024285 100644 --- a/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java +++ b/src/main/java/com/github/dockerjava/core/command/BuildImageCmdImpl.java @@ -125,7 +125,11 @@ public boolean hasPullEnabled() { @Override public String getPathToDockerfile() { - return FilePathUtil.relativize(baseDirectory, dockerFile); + if (baseDirectory != null && dockerFile != null) { + return FilePathUtil.relativize(baseDirectory, dockerFile); + } else { + return null; + } } @Override diff --git a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java index bd8a56d2..c9bd51b9 100644 --- a/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/BuildImageCmdImplTest.java @@ -9,10 +9,15 @@ import static org.hamcrest.Matchers.nullValue; import java.io.File; +import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; +import java.util.Collection; +import java.util.UUID; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.filefilter.TrueFileFilter; import org.apache.commons.lang.StringUtils; import org.testng.ITestResult; @@ -24,12 +29,13 @@ import com.github.dockerjava.api.DockerClientException; import com.github.dockerjava.api.DockerException; +import com.github.dockerjava.api.command.BuildImageCmd; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.api.model.EventStreamItem; import com.github.dockerjava.client.AbstractDockerClientTest; - +import com.github.dockerjava.core.CompressArchiveUtil; @Test(groups = "integration") public class BuildImageCmdImplTest extends AbstractDockerClientTest { @@ -105,7 +111,16 @@ public void testNonstandard2() { assertThat(fullLog, containsString("Successfully built")); } - @Test + @Test + public void testDockerBuilderFromTar() throws IOException { + File baseDir = new File(Thread.currentThread().getContextClassLoader().getResource("testAddFile").getFile()); + Collection files = FileUtils.listFiles(baseDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); + File tarFile = CompressArchiveUtil.archiveTARFiles(baseDir, files, UUID.randomUUID().toString()); + String response = dockerfileBuild(new FileInputStream(tarFile)); + assertThat(response, containsString("Successfully executed testrun.sh")); + } + + @Test public void testDockerBuilderAddUrl() { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("testAddUrl").getFile()); @@ -150,37 +165,39 @@ public void testDockerBuilderEnv() throws DockerException, assertThat(response, containsString("Successfully executed testrun.sh")); } + private String dockerfileBuild(InputStream tarInputStream) { + return execBuild(dockerClient.buildImageCmd().withTarInputStream(tarInputStream)); + } - private String dockerfileBuild(File baseDir) { - - // Build image - InputStream response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); + private String dockerfileBuild(File baseDir) { + return execBuild(dockerClient.buildImageCmd(baseDir)); + } - String fullLog = asString(response); - assertThat(fullLog, containsString("Successfully built")); + private String execBuild(BuildImageCmd buildImageCmd) { + // Build image + InputStream response = buildImageCmd.withNoCache().exec(); - String imageId = StringUtils.substringBetween(fullLog, - "Successfully built ", "\\n\"}").trim(); + String fullLog = asString(response); + assertThat(fullLog, containsString("Successfully built")); - // Create container based on image - CreateContainerResponse container = dockerClient.createContainerCmd( - imageId).exec(); + String imageId = StringUtils.substringBetween(fullLog, "Successfully built ", "\\n\"}").trim(); - LOG.info("Created container: {}", container.toString()); - assertThat(container.getId(), not(isEmptyString())); + // Create container based on image + CreateContainerResponse container = dockerClient.createContainerCmd(imageId).exec(); - dockerClient.startContainerCmd(container.getId()).exec(); - dockerClient.waitContainerCmd(container.getId()).exec(); + LOG.info("Created container: {}", container.toString()); + assertThat(container.getId(), not(isEmptyString())); - // Log container - InputStream logResponse = logContainer(container - .getId()); + dockerClient.startContainerCmd(container.getId()).exec(); + dockerClient.waitContainerCmd(container.getId()).exec(); - //assertThat(asString(logResponse), containsString(expectedText)); + // Log container + InputStream logResponse = logContainer(container.getId()); - return asString(logResponse); - } + //assertThat(asString(logResponse), containsString(expectedText)); + return asString(logResponse); + } private InputStream logContainer(String containerId) { return dockerClient.logContainerCmd(containerId).withStdErr().withStdOut().exec(); From 5ee09ba4ae06a90761c7027477cef433a4ca45ce Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 10 May 2015 18:33:03 +0200 Subject: [PATCH 434/452] Fix issue #201 --- .../java/com/github/dockerjava/jaxrs/EventsCmdExec.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java index 78d26fea..32ab45f2 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -70,7 +70,11 @@ public Void call() throws Exception { InputStream inputStream = new WrappedResponseInputStream(response); JsonParser jp = JSON_FACTORY.createParser(inputStream); while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed() && eventCallback.isReceiving()) { - eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); + try { + eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); + } catch(Exception e) { + eventCallback.onException(e); + } numEvents++; } } From 72a61dd7834367e99524e5a91a47397d8970b0d7 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 10 May 2015 18:33:29 +0200 Subject: [PATCH 435/452] Fix test expectation --- .../github/dockerjava/core/command/EventStreamReaderITest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java b/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java index dfc330d9..7d4f9d4e 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java @@ -42,7 +42,7 @@ public void pullCanBeStreamed() throws Exception { ) {; assertThat(reader.readItem(), allOf( - hasProperty("status", equalTo("Pulling repository busybox")), + hasProperty("status", equalTo("Pulling from busybox")), hasProperty("progress", nullValue()), hasProperty("progressDetail", nullValue()) ) From 355e649b66b5792bb8401fabf2b6743040ebf99d Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 10 May 2015 18:37:33 +0200 Subject: [PATCH 436/452] Call onCompletetion callback before close because of https://github.com/docker-java/docker-java/issues/196 --- .../dockerjava/jaxrs/EventsCmdExec.java | 148 ++++++++++-------- 1 file changed, 80 insertions(+), 68 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java index 32ab45f2..924fdaed 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -22,72 +22,84 @@ import com.github.dockerjava.api.model.Event; import com.github.dockerjava.jaxrs.util.WrappedResponseInputStream; -public class EventsCmdExec extends AbstrDockerCmdExec implements EventsCmd.Exec { - private static final Logger LOGGER = LoggerFactory.getLogger(EventsCmdExec.class); - - public EventsCmdExec(WebTarget baseResource) { - super(baseResource); - } - - @Override - protected ExecutorService execute(EventsCmd command) { - ExecutorService executorService = Executors.newSingleThreadExecutor(); - - WebTarget webResource = getBaseResource().path("/events") - .queryParam("since", command.getSince()) - .queryParam("until", command.getUntil()); - - LOGGER.trace("GET: {}", webResource); - EventNotifier eventNotifier = EventNotifier.create(command.getEventCallback(), webResource); - executorService.submit(eventNotifier); - return executorService; - } - - private static class EventNotifier implements Callable { - private static final JsonFactory JSON_FACTORY = new JsonFactory(); - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - private final EventCallback eventCallback; - private final WebTarget webTarget; - - private EventNotifier(EventCallback eventCallback, WebTarget webTarget) { - this.eventCallback = eventCallback; - this.webTarget = webTarget; - } - - public static EventNotifier create(EventCallback eventCallback, WebTarget webTarget) { - checkNotNull(eventCallback, "An EventCallback must be provided"); - checkNotNull(webTarget, "An WebTarget must be provided"); - return new EventNotifier(eventCallback, webTarget); - } - - @Override - public Void call() throws Exception { - int numEvents=0; - Response response = null; - try { - response = webTarget.request().get(Response.class); - InputStream inputStream = new WrappedResponseInputStream(response); - JsonParser jp = JSON_FACTORY.createParser(inputStream); - while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed() && eventCallback.isReceiving()) { - try { - eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); - } catch(Exception e) { - eventCallback.onException(e); - } - numEvents++; - } - } - catch(Exception e) { - eventCallback.onException(e); - } - finally { - if (response != null) { - response.close(); - } - } - eventCallback.onCompletion(numEvents); - return null; - } - } +public class EventsCmdExec extends + AbstrDockerCmdExec implements + EventsCmd.Exec { + private static final Logger LOGGER = LoggerFactory + .getLogger(EventsCmdExec.class); + + public EventsCmdExec(WebTarget baseResource) { + super(baseResource); + } + + @Override + protected ExecutorService execute(EventsCmd command) { + ExecutorService executorService = Executors.newSingleThreadExecutor(); + + WebTarget webResource = getBaseResource().path("/events") + .queryParam("since", command.getSince()) + .queryParam("until", command.getUntil()); + + LOGGER.trace("GET: {}", webResource); + EventNotifier eventNotifier = EventNotifier.create( + command.getEventCallback(), webResource); + executorService.submit(eventNotifier); + return executorService; + } + + private static class EventNotifier implements Callable { + private static final JsonFactory JSON_FACTORY = new JsonFactory(); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private final EventCallback eventCallback; + private final WebTarget webTarget; + + private EventNotifier(EventCallback eventCallback, WebTarget webTarget) { + this.eventCallback = eventCallback; + this.webTarget = webTarget; + } + + public static EventNotifier create(EventCallback eventCallback, + WebTarget webTarget) { + checkNotNull(eventCallback, "An EventCallback must be provided"); + checkNotNull(webTarget, "An WebTarget must be provided"); + return new EventNotifier(eventCallback, webTarget); + } + + @Override + public Void call() throws Exception { + int numEvents = 0; + Response response = null; + try { + response = webTarget.request().get(Response.class); + InputStream inputStream = new WrappedResponseInputStream( + response); + JsonParser jp = JSON_FACTORY.createParser(inputStream); + while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed() + && eventCallback.isReceiving()) { + try { + eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, + Event.class)); + } catch (Exception e) { + eventCallback.onException(e); + } + numEvents++; + } + } catch (Exception e) { + eventCallback.onException(e); + } finally { + // call onCompletion before close because of https://github.com/docker-java/docker-java/issues/196 + try { + eventCallback.onCompletion(numEvents); + } catch (Exception e) { + eventCallback.onException(e); + } + if (response != null) { + response.close(); + } + } + + return null; + } + } } From 1d52a47266e78db5769b61bcd6e3612c655b8869 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 10 May 2015 19:21:05 +0200 Subject: [PATCH 437/452] Fix issue #214 --- .../java/com/github/dockerjava/api/model/ContainerConfig.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/model/ContainerConfig.java b/src/main/java/com/github/dockerjava/api/model/ContainerConfig.java index dcb1256b..ce8c6b88 100644 --- a/src/main/java/com/github/dockerjava/api/model/ContainerConfig.java +++ b/src/main/java/com/github/dockerjava/api/model/ContainerConfig.java @@ -64,7 +64,7 @@ public class ContainerConfig { private boolean networkDisabled = false; @JsonProperty("OnBuild") - private int[] onBuild; + private String[] onBuild; @JsonProperty("OpenStdin") private boolean stdinOpen = false; @@ -180,7 +180,7 @@ public String[] getEntrypoint() { return entrypoint; } - public int[] getOnBuild() { + public String[] getOnBuild() { return onBuild; } From 8652329036eeb5ac583584b27a04c4261aca7b8e Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sun, 10 May 2015 19:22:32 +0200 Subject: [PATCH 438/452] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e6fca225..3d3cb24d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ Change Log === Latest SNAPSHOT --- +* [#213](https://github.com/docker-java/docker-java/pull/213) Add ulimit support * [#208](https://github.com/docker-java/docker-java/pull/208) Added PullEventStreamItem and EventStreamReader to stream the reading of events * [#205](https://github.com/docker-java/docker-java/issues/205) Access mode of VolumesRW incorrectly deserialized * [#204] (https://github.com/docker-java/docker-java/pull/204) Added support to use the credentials from .dockercfg during build From 5e268e50343dfebf461b1e71dec8600881c9c3de Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sun, 10 May 2015 19:23:04 +0200 Subject: [PATCH 439/452] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bbafd8a6..6516793d 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Java API client for [Docker](http://docs.docker.io/ "Docker") -Supports a subset of the Docker Client API v1.17, Docker Server version 1.5.0 +Supports a subset of the Docker Client API v1.18, Docker Server version 1.6.0 The current implementation is based on Jersey 2.x and therefore classpath incompatible with older Jersey 1.x dependent libraries! From 9954713fbbae4828bc0aea3e154ca8a8b7dec810 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 10 May 2015 20:07:36 +0200 Subject: [PATCH 440/452] Exclude from CircleCI integration tests --- .../dockerjava/core/command/CreateContainerCmdImplTest.java | 3 ++- .../github/dockerjava/core/command/EventStreamReaderITest.java | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java index c37f4848..c652f51d 100644 --- a/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/CreateContainerCmdImplTest.java @@ -6,6 +6,7 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.model.*; import com.github.dockerjava.client.AbstractDockerClientTest; + import org.testng.ITestResult; import org.testng.annotations.*; @@ -540,7 +541,7 @@ public void createContainerWithMacAddress() throws DockerException { "00:80:41:ae:fd:7e"); } - @Test + @Test(groups = "ignoreInCircleCi") public void createContainerWithULimits() throws DockerException { Ulimit[] ulimits = {new Ulimit("nproc", 709, 1026), new Ulimit("nofile", 1024, 4096)}; diff --git a/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java b/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java index 7d4f9d4e..07bca25b 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventStreamReaderITest.java @@ -33,7 +33,7 @@ public void tearDown() throws Exception { dockerClient.close(); } - @Test + @Test(groups = "ignoreInCircleCi") public void pullCanBeStreamed() throws Exception { try (EventStreamReader reader = new EventStreamReader<>( From ebcb85c15ba72278b3dae6c425e0804374767e9b Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 10 May 2015 20:09:54 +0200 Subject: [PATCH 441/452] Set new semver version --- README.md | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6516793d..9584fdcb 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ You can find the latest SNAPSHOT version including javadoc and source files on [ com.github.docker-java docker-java - 1.2.1-SNAPSHOT + 1.3.0-SNAPSHOT ## Documentation diff --git a/pom.xml b/pom.xml index 1279f9c1..d9aa194d 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 1.2.1-SNAPSHOT + 1.3.0-SNAPSHOT docker-java https://github.com/docker-java/docker-java From 3a0e734148b6786c1fde4021fe1db6b3ba5cb8fe Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 10 May 2015 20:52:29 +0200 Subject: [PATCH 442/452] [maven-release-plugin] prepare release docker-java-1.3.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index d9aa194d..0b28d5dd 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 1.3.0-SNAPSHOT + 1.3.0 docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - HEAD + docker-java-1.3.0 From f4f8b5616c28688dbb97fa494df47b91b4738525 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Sun, 10 May 2015 20:52:32 +0200 Subject: [PATCH 443/452] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 0b28d5dd..f8eb34ce 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ com.github.docker-java docker-java jar - 1.3.0 + 1.3.1-SNAPSHOT docker-java https://github.com/docker-java/docker-java @@ -28,7 +28,7 @@ scm:git:git@github.com:docker-java/docker-java.git git@github.com:docker-java/docker-java.git scm:git:git@github.com:docker-java/docker-java.git - docker-java-1.3.0 + HEAD From 9daa3733233c2733fce2599ff884c1e091cb4993 Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sun, 10 May 2015 20:56:21 +0200 Subject: [PATCH 444/452] Update CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d3cb24d..ea311817 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ Change Log === Latest SNAPSHOT --- + +v1.3.0 +--- * [#213](https://github.com/docker-java/docker-java/pull/213) Add ulimit support * [#208](https://github.com/docker-java/docker-java/pull/208) Added PullEventStreamItem and EventStreamReader to stream the reading of events * [#205](https://github.com/docker-java/docker-java/issues/205) Access mode of VolumesRW incorrectly deserialized From c5ba01b72951096a4c8088a96eedc1a4697da7cb Mon Sep 17 00:00:00 2001 From: marcuslinke Date: Sun, 10 May 2015 20:56:47 +0200 Subject: [PATCH 445/452] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9584fdcb..4c77e896 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ Run build without integration tests: com.github.docker-java docker-java - 1.2.0 + 1.3.0 ### Latest SNAPSHOT version @@ -74,7 +74,7 @@ You can find the latest SNAPSHOT version including javadoc and source files on [ com.github.docker-java docker-java - 1.3.0-SNAPSHOT + 1.3.1-SNAPSHOT ## Documentation From e34638a9b38a29eca8242e0aaa910b09d9f019ec Mon Sep 17 00:00:00 2001 From: James Nord Date: Wed, 13 May 2015 10:52:45 +0100 Subject: [PATCH 446/452] Do not wait for another event before exiting. It the callback decideds it is no longer interested in receiving events whilst it handles either an event or an exception then it should not have to wait until the next event from Docker is received to exit the loop. This adds a check before the event is received and leaves the check after the event has received as the event may take a long time to come and the callback may have decided during that time that it wants to shutdown. --- .../java/com/github/dockerjava/jaxrs/EventsCmdExec.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java index 924fdaed..db14ab21 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java +++ b/src/main/java/com/github/dockerjava/jaxrs/EventsCmdExec.java @@ -75,8 +75,13 @@ public Void call() throws Exception { InputStream inputStream = new WrappedResponseInputStream( response); JsonParser jp = JSON_FACTORY.createParser(inputStream); - while (jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed() - && eventCallback.isReceiving()) { + // The following condition looks strange but jp.nextToken() will block until there is an + // event from the docker server or the connection is terminated. + // therefore we want to check before getting an event (to prevent a blocking operation + // and after the event to make sure that the eventCallback is still interested in getting notified. + while (eventCallback.isReceiving() && + jp.nextToken() != JsonToken.END_OBJECT && !jp.isClosed() && + eventCallback.isReceiving()) { try { eventCallback.onEvent(OBJECT_MAPPER.readValue(jp, Event.class)); From a9b92e383c600cafc03d24b811b7176cb7982ff3 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 14 May 2015 19:57:01 +0200 Subject: [PATCH 447/452] Fix roundtrip test --- .../dockerjava/test/serdes/JSONTestHelper.java | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/test/java/com/github/dockerjava/test/serdes/JSONTestHelper.java b/src/test/java/com/github/dockerjava/test/serdes/JSONTestHelper.java index b465b2aa..b6a33b72 100644 --- a/src/test/java/com/github/dockerjava/test/serdes/JSONTestHelper.java +++ b/src/test/java/com/github/dockerjava/test/serdes/JSONTestHelper.java @@ -15,11 +15,15 @@ */ package com.github.dockerjava.test.serdes; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.dockerjava.api.command.CommandJSONSamples; + import java.io.IOException; import java.io.InputStream; + import org.apache.commons.io.IOUtils; + import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; @@ -101,10 +105,14 @@ public static TClass testRoundTrip(TClass item, Class asclass) throws IOException, AssertionError { ObjectMapper mapper = new ObjectMapper(); - String inputItemString = mapper.writeValueAsString(item); - TClass convertedItem = mapper.readValue(inputItemString, asclass); - String convertedItemString = mapper.writeValueAsString(convertedItem); - assertEquals(convertedItemString, inputItemString, "JSONs must be equal after the second roundtrip"); - return convertedItem; + String serialized1 = mapper.writeValueAsString(item); + JsonNode json1 = mapper.readTree(serialized1); + TClass deserialized1 = mapper.readValue(serialized1, asclass); + String serialized2 = mapper.writeValueAsString(deserialized1); + JsonNode json2 = mapper.readTree(serialized2); + TClass deserialized2 = mapper.readValue(serialized2, asclass); + + assertEquals(json2, json1, "JSONs must be equal after the second roundtrip"); + return deserialized2; } } From a072d62104d03d53cf2f9a41b95fd527fb6acbb9 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Thu, 14 May 2015 20:58:49 +0200 Subject: [PATCH 448/452] Workaround for issue #196 --- .../jaxrs/DockerCmdExecFactoryImpl.java | 5 +- .../jaxrs/connector/ApacheConnector.java | 698 ++++++++++++++++++ .../ApacheConnectorClientResponse.java | 52 ++ .../connector/ApacheConnectorProvider.java | 151 ++++ .../dockerjava/jaxrs/connector/README.txt | 3 + .../core/command/EventsCmdImplTest.java | 34 +- 6 files changed, 939 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/jaxrs/connector/ApacheConnector.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/connector/ApacheConnectorClientResponse.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/connector/ApacheConnectorProvider.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/connector/README.txt diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index bc3afeca..3636bfd0 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -22,7 +22,9 @@ import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.glassfish.jersey.CommonProperties; import org.glassfish.jersey.apache.connector.ApacheClientProperties; -import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; +//import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; +// see https://github.com/docker-java/docker-java/issues/196 +import com.github.dockerjava.jaxrs.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; @@ -34,6 +36,7 @@ import com.github.dockerjava.core.util.ResponseStatusExceptionFilter; import com.github.dockerjava.core.util.SelectiveLoggingFilter; + public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { private static final Logger LOGGER = LoggerFactory diff --git a/src/main/java/com/github/dockerjava/jaxrs/connector/ApacheConnector.java b/src/main/java/com/github/dockerjava/jaxrs/connector/ApacheConnector.java new file mode 100644 index 00000000..651db983 --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/connector/ApacheConnector.java @@ -0,0 +1,698 @@ +package com.github.dockerjava.jaxrs.connector; + +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2010-2014 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * http://glassfish.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicLong; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.ws.rs.ProcessingException; +import javax.ws.rs.core.Configuration; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; + +import org.glassfish.jersey.SslConfigurator; +import org.glassfish.jersey.apache.connector.ApacheClientProperties; +import org.glassfish.jersey.apache.connector.LocalizationMessages; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.client.ClientRequest; +import org.glassfish.jersey.client.ClientResponse; +import org.glassfish.jersey.client.RequestEntityProcessing; +import org.glassfish.jersey.client.spi.AsyncConnectorCallback; +import org.glassfish.jersey.client.spi.Connector; +import org.glassfish.jersey.internal.util.PropertiesHelper; +import org.glassfish.jersey.message.internal.HeaderUtils; +import org.glassfish.jersey.message.internal.OutboundMessageContext; +import org.glassfish.jersey.message.internal.ReaderWriter; +import org.glassfish.jersey.message.internal.Statuses; +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.AuthCache; +import org.apache.http.client.CookieStore; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.methods.RequestBuilder; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.config.ConnectionConfig; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.HttpClientConnectionManager; +import org.apache.http.conn.ManagedHttpClientConnection; +import org.apache.http.conn.routing.HttpRoute; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.LayeredConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContexts; +import org.apache.http.conn.ssl.X509HostnameVerifier; +import org.apache.http.entity.AbstractHttpEntity; +import org.apache.http.entity.BufferedHttpEntity; +import org.apache.http.entity.ContentLengthStrategy; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.DefaultManagedHttpClientConnection; +import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.impl.io.ChunkedOutputStream; +import org.apache.http.io.SessionOutputBuffer; +import org.apache.http.util.TextUtils; +import org.apache.http.util.VersionInfo; + +import jersey.repackaged.com.google.common.util.concurrent.MoreExecutors; + +/** + * A {@link Connector} that utilizes the Apache HTTP Client to send and receive + * HTTP request and responses. + *

+ * The following properties are only supported at construction of this class: + *

    + *
  • {@link ApacheClientProperties#CONNECTION_MANAGER}
  • + *
  • {@link ApacheClientProperties#REQUEST_CONFIG}
  • + *
  • {@link ApacheClientProperties#CREDENTIALS_PROVIDER}
  • + *
  • {@link ApacheClientProperties#DISABLE_COOKIES}
  • + *
  • {@link ClientProperties#PROXY_URI}
  • + *
  • {@link ClientProperties#PROXY_USERNAME}
  • + *
  • {@link ClientProperties#PROXY_PASSWORD}
  • + *
  • {@link ClientProperties#REQUEST_ENTITY_PROCESSING} - default value is {@link RequestEntityProcessing#CHUNKED}
  • + *
  • {@link ApacheClientProperties#PREEMPTIVE_BASIC_AUTHENTICATION}
  • + *
  • {@link ApacheClientProperties#SSL_CONFIG}
  • + *
+ *

+ * This connector uses {@link RequestEntityProcessing#CHUNKED chunked encoding} as a default setting. This can + * be overridden by the {@link ClientProperties#REQUEST_ENTITY_PROCESSING}. By default the + * {@link ClientProperties#CHUNKED_ENCODING_SIZE} property is only supported by using default connection manager. If custom + * connection manager needs to be used then chunked encoding size can be set by providing a custom + * {@link org.apache.http.HttpClientConnection} (via custom {@link org.apache.http.impl.conn.ManagedHttpClientConnectionFactory}) + * and overriding {@code createOutputStream} method. + *

+ *

+ * Using of authorization is dependent on the chunk encoding setting. If the entity + * buffering is enabled, the entity is buffered and authorization can be performed + * automatically in response to a 401 by sending the request again. When entity buffering + * is disabled (chunked encoding is used) then the property + * {@link org.glassfish.jersey.apache.connector.ApacheClientProperties#PREEMPTIVE_BASIC_AUTHENTICATION} must + * be set to {@code true}. + *

+ *

+ * If a {@link org.glassfish.jersey.client.ClientResponse} is obtained and an + * entity is not read from the response then + * {@link org.glassfish.jersey.client.ClientResponse#close()} MUST be called + * after processing the response to release connection-based resources. + *

+ *

+ * Client operations are thread safe, the HTTP connection may + * be shared between different threads. + *

+ *

+ * If a response entity is obtained that is an instance of {@link Closeable} + * then the instance MUST be closed after processing the entity to release + * connection-based resources. + *

+ *

+ * The following methods are currently supported: HEAD, GET, POST, PUT, DELETE, OPTIONS, PATCH and TRACE. + *

+ * + * @author jorgeluisw@mac.com + * @author Paul Sandoz (paul.sandoz at oracle.com) + * @author Pavel Bucek (pavel.bucek at oracle.com) + * @author Arul Dhesiaseelan (aruld at acm.org) + * @see ApacheClientProperties#CONNECTION_MANAGER + */ +@SuppressWarnings("deprecation") +class ApacheConnector implements Connector { + + private final static Logger LOGGER = Logger.getLogger(ApacheConnector.class.getName()); + + private static final VersionInfo vi; + private static final String release; + + static { + vi = VersionInfo.loadVersionInfo("org.apache.http.client", HttpClientBuilder.class.getClassLoader()); + release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; + } + + private final CloseableHttpClient client; + private final CookieStore cookieStore; + private final boolean preemptiveBasicAuth; + private final RequestConfig requestConfig; + + /** + * Create the new Apache HTTP Client connector. + * + * @param config client configuration. + */ + ApacheConnector(Configuration config) { + Object reqConfig = null; + + if (config != null) { + final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER); + + if (connectionManager != null) { + if (!(connectionManager instanceof HttpClientConnectionManager)) { + LOGGER.log( + Level.WARNING, + LocalizationMessages.IGNORING_VALUE_OF_PROPERTY( + ApacheClientProperties.CONNECTION_MANAGER, + connectionManager.getClass().getName(), + HttpClientConnectionManager.class.getName()) + ); + } + } + + reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG); + if (reqConfig != null) { + if (!(reqConfig instanceof RequestConfig)) { + LOGGER.log( + Level.WARNING, + LocalizationMessages.IGNORING_VALUE_OF_PROPERTY( + ApacheClientProperties.REQUEST_CONFIG, + reqConfig.getClass().getName(), + RequestConfig.class.getName()) + ); + reqConfig = null; + } + } + } + + final SSLContext sslContext = getSslContext(config); + final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); + + clientBuilder.setConnectionManager(getConnectionManager(config, sslContext)); + clientBuilder.setSslcontext(sslContext); + + final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); + + int connectTimeout = 0; + int socketTimeout = 0; + boolean ignoreCookies = false; + if (config != null) { + connectTimeout = ClientProperties.getValue(config.getProperties(), ClientProperties.CONNECT_TIMEOUT, 0); + socketTimeout = ClientProperties.getValue(config.getProperties(), ClientProperties.READ_TIMEOUT, 0); + ignoreCookies = PropertiesHelper.isProperty(config.getProperties(), ApacheClientProperties.DISABLE_COOKIES); + + final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER); + if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) { + clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider); + } + + Object proxyUri; + proxyUri = config.getProperty(ClientProperties.PROXY_URI); + if (proxyUri != null) { + final URI u = getProxyUri(proxyUri); + final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme()); + String userName; + userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME, String.class); + if (userName != null) { + String password; + password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class); + + if (password != null) { + final CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials( + new AuthScope(u.getHost(), u.getPort()), + new UsernamePasswordCredentials(userName, password) + ); + clientBuilder.setDefaultCredentialsProvider(credsProvider); + } + } + clientBuilder.setProxy(proxy); + } + + final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties() + .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION); + this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false; + } else { + this.preemptiveBasicAuth = false; + } + + + if (reqConfig != null) { + RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig); + if (connectTimeout > 0) { + reqConfigBuilder.setConnectTimeout(connectTimeout); + } + if (socketTimeout > 0) { + reqConfigBuilder.setSocketTimeout(socketTimeout); + } + if (ignoreCookies) { + reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES); + } + requestConfig = reqConfigBuilder.build(); + } else { + requestConfigBuilder.setConnectTimeout(connectTimeout); + requestConfigBuilder.setSocketTimeout(socketTimeout); + if (ignoreCookies) { + requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES); + } + requestConfig = requestConfigBuilder.build(); + } + + if (requestConfig.getCookieSpec() == null || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) { + this.cookieStore = new BasicCookieStore(); + clientBuilder.setDefaultCookieStore(cookieStore); + } else { + this.cookieStore = null; + } + clientBuilder.setDefaultRequestConfig(requestConfig); + this.client = clientBuilder.build(); + } + + private SSLContext getSslContext(final Configuration config) { + final SslConfigurator sslConfigurator = ApacheClientProperties.getValue( + config.getProperties(), + ApacheClientProperties.SSL_CONFIG, + SslConfigurator.class); + + return sslConfigurator != null ? sslConfigurator.createSSLContext() : null; + } + + HttpClientConnectionManager getConnectionManager(final Configuration config, final SSLContext sslContext) { + final Object cmObject = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER); + + // Connection manager from configuration. + if (cmObject != null) { + if (cmObject instanceof HttpClientConnectionManager) { + return (HttpClientConnectionManager) cmObject; + } else { + LOGGER.log( + Level.WARNING, + LocalizationMessages.IGNORING_VALUE_OF_PROPERTY( + ApacheClientProperties.CONNECTION_MANAGER, + cmObject.getClass().getName(), + HttpClientConnectionManager.class.getName()) + ); + } + } + + // Create custom connection manager. + return createConnectionManager( + config, + sslContext, + null, + false); + } + + private HttpClientConnectionManager createConnectionManager( + final Configuration config, + final SSLContext sslContext, + X509HostnameVerifier hostnameVerifier, + final boolean useSystemProperties) { + + final String[] supportedProtocols = useSystemProperties ? split( + System.getProperty("https.protocols")) : null; + final String[] supportedCipherSuites = useSystemProperties ? split( + System.getProperty("https.cipherSuites")) : null; + + if (hostnameVerifier == null) { + hostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; + } + + final LayeredConnectionSocketFactory sslSocketFactory; + if (sslContext != null) { + sslSocketFactory = new SSLConnectionSocketFactory( + sslContext, supportedProtocols, supportedCipherSuites, hostnameVerifier); + } else { + if (useSystemProperties) { + sslSocketFactory = new SSLConnectionSocketFactory( + (SSLSocketFactory) SSLSocketFactory.getDefault(), + supportedProtocols, supportedCipherSuites, hostnameVerifier); + } else { + sslSocketFactory = new SSLConnectionSocketFactory( + SSLContexts.createDefault(), + hostnameVerifier); + } + } + + final Registry registry = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.getSocketFactory()) + .register("https", sslSocketFactory) + .build(); + + final Integer chunkSize = ClientProperties.getValue(config.getProperties(), + ClientProperties.CHUNKED_ENCODING_SIZE, 4096, Integer.class); + + final PoolingHttpClientConnectionManager connectionManager = + new PoolingHttpClientConnectionManager(registry, new ConnectionFactory(chunkSize)); + + if (useSystemProperties) { + String s = System.getProperty("http.keepAlive", "true"); + if ("true".equalsIgnoreCase(s)) { + s = System.getProperty("http.maxConnections", "5"); + final int max = Integer.parseInt(s); + connectionManager.setDefaultMaxPerRoute(max); + connectionManager.setMaxTotal(2 * max); + } + } + + return connectionManager; + } + + private static String[] split(final String s) { + if (TextUtils.isBlank(s)) { + return null; + } + return s.split(" *, *"); + } + + /** + * Get the {@link HttpClient}. + * + * @return the {@link HttpClient}. + */ + @SuppressWarnings("UnusedDeclaration") + public HttpClient getHttpClient() { + return client; + } + + /** + * Get the {@link CookieStore}. + * + * @return the {@link CookieStore} instance or {@code null} when {@value ApacheClientProperties#DISABLE_COOKIES} set to + * {@code true}. + */ + public CookieStore getCookieStore() { + return cookieStore; + } + + private static URI getProxyUri(final Object proxy) { + if (proxy instanceof URI) { + return (URI) proxy; + } else if (proxy instanceof String) { + return URI.create((String) proxy); + } else { + throw new ProcessingException(LocalizationMessages.WRONG_PROXY_URI_TYPE(ClientProperties.PROXY_URI)); + } + } + + @Override + public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException { + final HttpUriRequest request = getUriHttpRequest(clientRequest); + final Map clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request); + + try { + final CloseableHttpResponse response; + final HttpClientContext context = HttpClientContext.create(); + if (preemptiveBasicAuth) { + final AuthCache authCache = new BasicAuthCache(); + final BasicScheme basicScheme = new BasicScheme(); + authCache.put(getHost(request), basicScheme); + context.setAuthCache(authCache); + } + response = client.execute(getHost(request), request, context); + HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), + this.getClass().getName()); + + final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null ? + Statuses.from(response.getStatusLine().getStatusCode()) : + Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); + + final ClientResponse responseContext = new ApacheConnectorClientResponse(status, clientRequest, response); + final List redirectLocations = context.getRedirectLocations(); + if (redirectLocations != null && !redirectLocations.isEmpty()) { + responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1)); + } + + final Header[] respHeaders = response.getAllHeaders(); + final MultivaluedMap headers = responseContext.getHeaders(); + for (final Header header : respHeaders) { + final String headerName = header.getName(); + List list = headers.get(headerName); + if (list == null) { + list = new ArrayList(); + } + list.add(header.getValue()); + headers.put(headerName, list); + } + + final HttpEntity entity = response.getEntity(); + + if (entity != null) { + if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) { + headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength())); + } + + final Header contentEncoding = entity.getContentEncoding(); + if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) { + headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue()); + } + } + + + try { + responseContext.setEntityStream(new HttpClientResponseInputStream(response)); + } catch (final IOException e) { + LOGGER.log(Level.SEVERE, null, e); + } + + return responseContext; + } catch (final Exception e) { + throw new ProcessingException(e); + } + } + + @Override + public Future apply(final ClientRequest request, final AsyncConnectorCallback callback) { + return MoreExecutors.sameThreadExecutor().submit(new Runnable() { + @Override + public void run() { + try { + callback.response(apply(request)); + } catch (final ProcessingException ex) { + callback.failure(ex); + } catch (final Throwable t) { + callback.failure(t); + } + } + }); + } + + @Override + public String getName() { + return "Apache HttpClient " + release; + } + + @Override + public void close() { + try { + client.close(); + } catch (final IOException e) { + throw new ProcessingException(LocalizationMessages.FAILED_TO_STOP_CLIENT(), e); + } + } + + private HttpHost getHost(final HttpUriRequest request) { + return new HttpHost(request.getURI().getHost(), request.getURI().getPort(), request.getURI().getScheme()); + } + + private HttpUriRequest getUriHttpRequest(final ClientRequest clientRequest) { + final Boolean redirectsEnabled = + clientRequest.resolveProperty(ClientProperties.FOLLOW_REDIRECTS, requestConfig.isRedirectsEnabled()); + final RequestConfig config = RequestConfig.copy(requestConfig).setRedirectsEnabled(redirectsEnabled).build(); + + final Boolean bufferingEnabled = clientRequest.resolveProperty(ClientProperties.REQUEST_ENTITY_PROCESSING, + RequestEntityProcessing.class) == RequestEntityProcessing.BUFFERED; + final HttpEntity entity = getHttpEntity(clientRequest, bufferingEnabled); + + return RequestBuilder + .create(clientRequest.getMethod()) + .setUri(clientRequest.getUri()) + .setConfig(config) + .setEntity(entity) + .build(); + } + + + private HttpEntity getHttpEntity(final ClientRequest clientRequest, final boolean bufferingEnabled) { + final Object entity = clientRequest.getEntity(); + + if (entity == null) { + return null; + } + + final AbstractHttpEntity httpEntity = new AbstractHttpEntity() { + @Override + public boolean isRepeatable() { + return false; + } + + @Override + public long getContentLength() { + return -1; + } + + @Override + public InputStream getContent() throws IOException, IllegalStateException { + if (bufferingEnabled) { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(512); + writeTo(buffer); + return new ByteArrayInputStream(buffer.toByteArray()); + } else { + return null; + } + } + + @Override + public void writeTo(final OutputStream outputStream) throws IOException { + clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() { + @Override + public OutputStream getOutputStream(final int contentLength) throws IOException { + return outputStream; + } + }); + clientRequest.writeEntity(); + } + + @Override + public boolean isStreaming() { + return false; + } + }; + + if (bufferingEnabled) { + try { + return new BufferedHttpEntity(httpEntity); + } catch (final IOException e) { + throw new ProcessingException(LocalizationMessages.ERROR_BUFFERING_ENTITY(), e); + } + } else { + return httpEntity; + } + } + + private static Map writeOutBoundHeaders(final MultivaluedMap headers, final HttpUriRequest request) { + Map stringHeaders = HeaderUtils.asStringHeadersSingleValue(headers); + + for (Map.Entry e : stringHeaders.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + return stringHeaders; + } + + private static final class HttpClientResponseInputStream extends FilterInputStream { + + HttpClientResponseInputStream(final CloseableHttpResponse response) throws IOException { + super(getInputStream(response)); + } + + @Override + public void close() throws IOException { + super.close(); + } + } + + private static InputStream getInputStream(final CloseableHttpResponse response) throws IOException { + + if (response.getEntity() == null) { + return new ByteArrayInputStream(new byte[0]); + } else { + final InputStream i = response.getEntity().getContent(); + if (i.markSupported()) { + return i; + } + return new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE); + } + } + + private static class ConnectionFactory extends ManagedHttpClientConnectionFactory { + + private static final AtomicLong COUNTER = new AtomicLong(); + + private final int chunkSize; + + private ConnectionFactory(final int chunkSize) { + this.chunkSize = chunkSize; + } + + @Override + public ManagedHttpClientConnection create(final HttpRoute route, final ConnectionConfig config) { + final String id = "http-outgoing-" + Long.toString(COUNTER.getAndIncrement()); + + return new HttpClientConnection(id, config.getBufferSize(), chunkSize); + } + } + + private static class HttpClientConnection extends DefaultManagedHttpClientConnection { + + private final int chunkSize; + + private HttpClientConnection(final String id, final int buffersize, final int chunkSize) { + super(id, buffersize); + + this.chunkSize = chunkSize; + } + + @Override + protected OutputStream createOutputStream(final long len, final SessionOutputBuffer outbuffer) { + if (len == ContentLengthStrategy.CHUNKED) { + return new ChunkedOutputStream(chunkSize, outbuffer); + } + return super.createOutputStream(len, outbuffer); + } + } +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/connector/ApacheConnectorClientResponse.java b/src/main/java/com/github/dockerjava/jaxrs/connector/ApacheConnectorClientResponse.java new file mode 100644 index 00000000..7ba9d8ab --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/connector/ApacheConnectorClientResponse.java @@ -0,0 +1,52 @@ +package com.github.dockerjava.jaxrs.connector; + +import java.io.IOException; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.StatusType; + +import org.apache.http.client.methods.CloseableHttpResponse; +import org.glassfish.jersey.client.ClientRequest; +import org.glassfish.jersey.client.ClientResponse; + +/** + * Fix for https://github.com/docker-java/docker-java/issues/196 + * + * https://java.net/jira/browse/JERSEY-2852 + * + * @author marcus + * + */ +public class ApacheConnectorClientResponse extends ClientResponse { + + private CloseableHttpResponse closeableHttpResponse; + + public ApacheConnectorClientResponse(ClientRequest requestContext, + Response response) { + super(requestContext, response); + } + + public ApacheConnectorClientResponse(StatusType status, + ClientRequest requestContext, CloseableHttpResponse closeableHttpResponse) { + super(status, requestContext); + this.closeableHttpResponse = closeableHttpResponse; + } + + public ApacheConnectorClientResponse(StatusType status, + ClientRequest requestContext) { + super(status, requestContext); + } + + @Override + public void close() { + try { + closeableHttpResponse.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + super.close(); + } + + + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/connector/ApacheConnectorProvider.java b/src/main/java/com/github/dockerjava/jaxrs/connector/ApacheConnectorProvider.java new file mode 100644 index 00000000..fbde136f --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/connector/ApacheConnectorProvider.java @@ -0,0 +1,151 @@ +package com.github.dockerjava.jaxrs.connector; + +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2013-2014 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * http://glassfish.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ +import javax.ws.rs.client.Client; +import javax.ws.rs.core.Configurable; +import javax.ws.rs.core.Configuration; + +import org.glassfish.jersey.apache.connector.LocalizationMessages; +import org.glassfish.jersey.client.Initializable; +import org.glassfish.jersey.client.spi.Connector; +import org.glassfish.jersey.client.spi.ConnectorProvider; +import org.apache.http.client.HttpClient; + +/** + * Connector provider for Jersey {@link Connector connectors} that utilize + * Apache HTTP Client to send and receive HTTP request and responses. + *

+ * The following connector configuration properties are supported: + *

    + *
  • {@link ApacheClientProperties#CONNECTION_MANAGER}
  • + *
  • {@link ApacheClientProperties#REQUEST_CONFIG}
  • + *
  • {@link ApacheClientProperties#CREDENTIALS_PROVIDER}
  • + *
  • {@link ApacheClientProperties#DISABLE_COOKIES}
  • + *
  • {@link org.glassfish.jersey.client.ClientProperties#PROXY_URI}
  • + *
  • {@link org.glassfish.jersey.client.ClientProperties#PROXY_USERNAME}
  • + *
  • {@link org.glassfish.jersey.client.ClientProperties#PROXY_PASSWORD}
  • + *
  • {@link org.glassfish.jersey.client.ClientProperties#REQUEST_ENTITY_PROCESSING} + * - default value is {@link org.glassfish.jersey.client.RequestEntityProcessing#CHUNKED}
  • + *
  • {@link ApacheClientProperties#PREEMPTIVE_BASIC_AUTHENTICATION}
  • + *
  • {@link ApacheClientProperties#SSL_CONFIG}
  • + *
+ *

+ *

+ * Connector instances created via this connector provider use + * {@link org.glassfish.jersey.client.RequestEntityProcessing#CHUNKED chunked encoding} as a default setting. + * This can be overridden by the {@link org.glassfish.jersey.client.ClientProperties#REQUEST_ENTITY_PROCESSING}. + * By default the {@link org.glassfish.jersey.client.ClientProperties#CHUNKED_ENCODING_SIZE} property is only supported + * when using the default {@code org.apache.http.conn.HttpClientConnectionManager} instance. If custom + * connection manager is used, then chunked encoding size can be set by providing a custom + * {@code org.apache.http.HttpClientConnection} (via custom {@code org.apache.http.impl.conn.ManagedHttpClientConnectionFactory}) + * and overriding it's {@code createOutputStream} method. + *

+ *

+ * Use of authorization by the AHC-based connectors is dependent on the chunk encoding setting. + * If the entity buffering is enabled, the entity is buffered and authorization can be performed + * automatically in response to a 401 by sending the request again. When entity buffering + * is disabled (chunked encoding is used) then the property + * {@link org.glassfish.jersey.apache.connector.ApacheClientProperties#PREEMPTIVE_BASIC_AUTHENTICATION} must + * be set to {@code true}. + *

+ *

+ * If a {@link org.glassfish.jersey.client.ClientResponse} is obtained and an entity is not read from the response then + * {@link org.glassfish.jersey.client.ClientResponse#close()} MUST be called after processing the response to release + * connection-based resources. + *

+ *

+ * If a response entity is obtained that is an instance of {@link java.io.Closeable} + * then the instance MUST be closed after processing the entity to release + * connection-based resources. + *

+ *

+ * The following methods are currently supported: HEAD, GET, POST, PUT, DELETE, OPTIONS, PATCH and TRACE. + *

+ * + * @author Pavel Bucek (pavel.bucek at oracle.com) + * @author Arul Dhesiaseelan (aruld at acm.org) + * @author jorgeluisw at mac.com + * @author Marek Potociar (marek.potociar at oracle.com) + * @author Paul Sandoz (paul.sandoz at oracle.com) + * @since 2.5 + */ +public class ApacheConnectorProvider implements ConnectorProvider { + + @Override + public Connector getConnector(Client client, Configuration runtimeConfig) { + return new ApacheConnector(runtimeConfig); + } + + /** + * Retrieve the underlying Apache {@link HttpClient} instance from + * {@link org.glassfish.jersey.client.JerseyClient} or {@link org.glassfish.jersey.client.JerseyWebTarget} + * configured to use {@code ApacheConnectorProvider}. + * + * @param component {@code JerseyClient} or {@code JerseyWebTarget} instance that is configured to use + * {@code ApacheConnectorProvider}. + * @return underlying Apache {@code HttpClient} instance. + * + * @throws java.lang.IllegalArgumentException in case the {@code component} is neither {@code JerseyClient} + * nor {@code JerseyWebTarget} instance or in case the component + * is not configured to use a {@code ApacheConnectorProvider}. + * @since 2.8 + */ + public static HttpClient getHttpClient(Configurable component) { + if (!(component instanceof Initializable)) { + throw new IllegalArgumentException( + LocalizationMessages.INVALID_CONFIGURABLE_COMPONENT_TYPE(component.getClass().getName())); + } + + final Initializable initializable = (Initializable) component; + Connector connector = initializable.getConfiguration().getConnector(); + if (connector == null) { + initializable.preInitialize(); + connector = initializable.getConfiguration().getConnector(); + } + + if (connector instanceof ApacheConnector) { + return ((ApacheConnector) connector).getHttpClient(); + } + + throw new IllegalArgumentException(LocalizationMessages.EXPECTED_CONNECTOR_PROVIDER_NOT_USED()); + } +} + diff --git a/src/main/java/com/github/dockerjava/jaxrs/connector/README.txt b/src/main/java/com/github/dockerjava/jaxrs/connector/README.txt new file mode 100644 index 00000000..c3c1415f --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/connector/README.txt @@ -0,0 +1,3 @@ +This package exists as a workaround to https://java.net/jira/browse/JERSEY-2852. +It introduces ApacheConnectorClientResponse which extends ClientResponse and closes +the underlying CloseableHttpResponse when close() is called. \ No newline at end of file diff --git a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java index f9294929..569283ce 100644 --- a/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/EventsCmdImplTest.java @@ -16,6 +16,8 @@ import java.io.IOException; import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; @@ -66,17 +68,37 @@ public void testEventStreamTimeBound() throws InterruptedException, EventsCmd eventsCmd = dockerClient.eventsCmd(eventCallback) .withSince(startTime).withUntil(endTime); ExecutorService executorService = eventsCmd.exec(); - + boolean zeroCount = countDownLatch.await(5, TimeUnit.SECONDS); - + executorService.shutdown(); eventCallback.close(); + assertTrue(zeroCount, "" + eventCallback.getEvents()); + } + + @Test + public void testEventStreaming1() throws InterruptedException, IOException { + // Don't include other tests events + TimeUnit.SECONDS.sleep(1); + + CountDownLatch countDownLatch = new CountDownLatch(KNOWN_NUM_EVENTS); + EventCallbackTest eventCallback = new EventCallbackTest(countDownLatch); + + EventsCmd eventsCmd = dockerClient.eventsCmd(eventCallback).withSince( + getEpochTime()); + ExecutorService executorService = eventsCmd.exec(); + + generateEvents(); + + boolean zeroCount = countDownLatch.await(5, TimeUnit.SECONDS); + executorService.shutdown(); + eventCallback.close(); assertTrue(zeroCount, "Expected 4 events, [create, start, die, stop]"); } @Test - public void testEventStreaming() throws InterruptedException, IOException { + public void testEventStreaming2() throws InterruptedException, IOException { // Don't include other tests events TimeUnit.SECONDS.sleep(1); @@ -111,6 +133,7 @@ private int generateEvents() { private class EventCallbackTest implements EventCallback { private final CountDownLatch countDownLatch; private final AtomicBoolean isReceiving = new AtomicBoolean(true); + private final List events = new ArrayList(); public EventCallbackTest(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; @@ -124,6 +147,7 @@ public void close() { public void onEvent(Event event) { LOG.info("Received event #{}: {}", countDownLatch.getCount(), event); countDownLatch.countDown(); + events.add(event); } @Override @@ -140,5 +164,9 @@ public void onCompletion(int numEvents) { public boolean isReceiving() { return isReceiving.get(); } + + public List getEvents() { + return new ArrayList(events); + } } } From 1ed6fbfe5ae6fd1ddd27e80375a3e94b56436de3 Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 15 May 2015 15:30:20 +0200 Subject: [PATCH 449/452] Warning comment on 'followStream' --- .../api/command/AttachContainerCmd.java | 26 ++++++++---- .../api/command/LogContainerCmd.java | 41 ++++++++++++------- 2 files changed, 46 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java index abdec8f5..0fb72d45 100644 --- a/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/AttachContainerCmd.java @@ -2,6 +2,7 @@ import java.io.InputStream; +import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.NotFoundException; /** @@ -20,7 +21,7 @@ * - true or false, if true, print timestamps for every log line. * Defaults to false. */ -public interface AttachContainerCmd extends DockerCmd{ +public interface AttachContainerCmd extends DockerCmd { public String getContainerId(); @@ -36,8 +37,17 @@ public interface AttachContainerCmd extends DockerCmd{ public AttachContainerCmd withContainerId(String containerId); + /** + * See {@link #withFollowStream(boolean)} + */ public AttachContainerCmd withFollowStream(); + /** + * Following the stream means the resulting {@link InputStream} returned by + * {@link #exec()} reads infinitely. So a {@link InputStream#read()} MAY + * BLOCK FOREVER as long as no data is streamed from the docker host to + * {@link DockerClient}! + */ public AttachContainerCmd withFollowStream(boolean followStream); public AttachContainerCmd withTimestamps(boolean timestamps); @@ -51,19 +61,21 @@ public interface AttachContainerCmd extends DockerCmd{ public AttachContainerCmd withStdErr(boolean stderr); public AttachContainerCmd withLogs(boolean logs); - + public AttachContainerCmd withLogs(); /** - * Its the responsibility of the caller to consume and/or close the {@link InputStream} to prevent - * connection leaks. + * Its the responsibility of the caller to consume and/or close the + * {@link InputStream} to prevent connection leaks. * - * @throws NotFoundException No such container + * @throws NotFoundException + * No such container */ @Override public InputStream exec() throws NotFoundException; - - public static interface Exec extends DockerCmdExec { + + public static interface Exec extends + DockerCmdExec { } } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java b/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java index 05e10855..c966ef95 100644 --- a/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java +++ b/src/main/java/com/github/dockerjava/api/command/LogContainerCmd.java @@ -1,12 +1,13 @@ package com.github.dockerjava.api.command; +import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.NotFoundException; import java.io.InputStream; /** * Get container logs - * + * * @param followStream * - true or false, return stream. Defaults to false. * @param stdout @@ -17,13 +18,15 @@ * - true or false, if true, print timestamps for every log line. * Defaults to false. * @param tail - * - `all` or ``, Output specified number of lines at the end of logs - * - * Consider wrapping any input stream you get with a frame reader to make reading frame easier. - * + * - `all` or ``, Output specified number of lines at the end + * of logs + * + * Consider wrapping any input stream you get with a frame reader to + * make reading frame easier. + * * @see com.github.dockerjava.core.command.FrameReader */ -public interface LogContainerCmd extends DockerCmd{ +public interface LogContainerCmd extends DockerCmd { public String getContainerId(); @@ -39,12 +42,21 @@ public interface LogContainerCmd extends DockerCmd{ public LogContainerCmd withContainerId(String containerId); + /** + * See {@link #withFollowStream(boolean)} + */ public LogContainerCmd withFollowStream(); + /** + * Following the stream means the resulting {@link InputStream} returned by + * {@link #exec()} reads infinitely. So a {@link InputStream#read()} MAY + * BLOCK FOREVER as long as no data is streamed from the docker host to + * {@link DockerClient}! + */ public LogContainerCmd withFollowStream(boolean followStream); public LogContainerCmd withTimestamps(); - + public LogContainerCmd withTimestamps(boolean timestamps); public LogContainerCmd withStdOut(); @@ -60,16 +72,17 @@ public interface LogContainerCmd extends DockerCmd{ public LogContainerCmd withTail(int tail); /** - * Its the responsibility of the caller to consume and/or close the {@link InputStream} to prevent - * connection leaks. - * - * @throws NotFoundException No such container + * Its the responsibility of the caller to consume and/or close the + * {@link InputStream} to prevent connection leaks. + * + * @throws NotFoundException + * No such container */ @Override public InputStream exec() throws NotFoundException; - - public static interface Exec extends DockerCmdExec { - } + public static interface Exec extends + DockerCmdExec { + } } \ No newline at end of file From 2df09cdca8bd41cb5be0b28e00fbd72632d4f33c Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 15 May 2015 15:30:48 +0200 Subject: [PATCH 450/452] Make FrameReaderITest work again --- .../client/AbstractDockerClientTest.java | 8 +- .../core/command/DockerfileFixture.java | 15 +- .../core/command/FrameReaderITest.java | 163 ++++++++++-------- .../frameReaderDockerfile/Dockerfile | 4 +- 4 files changed, 106 insertions(+), 84 deletions(-) diff --git a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java index 1e61b9a7..802166a0 100644 --- a/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java +++ b/src/test/java/com/github/dockerjava/client/AbstractDockerClientTest.java @@ -104,8 +104,12 @@ public void afterMethod(ITestResult result) { "################################## END OF {} ##################################\n", result.getName()); } + + protected String asString(InputStream response) { + return consumeAsString(response); + } - protected String asString(InputStream response) { + public static String consumeAsString(InputStream response) { StringWriter logwriter = new StringWriter(); @@ -116,7 +120,7 @@ protected String asString(InputStream response) { while (itr.hasNext()) { String line = itr.next(); logwriter.write(line + (itr.hasNext() ? "\n" : "")); - //LOG.info("line: "+line); + LOG.info("line: "+line); } response.close(); diff --git a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java index 840f63da..53131c61 100644 --- a/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java +++ b/src/test/java/com/github/dockerjava/core/command/DockerfileFixture.java @@ -1,14 +1,20 @@ package com.github.dockerjava.core.command; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; + import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.InternalServerErrorException; import com.github.dockerjava.api.NotFoundException; import com.github.dockerjava.api.model.Image; +import com.github.dockerjava.client.AbstractDockerClientTest; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; +import java.io.InputStream; /** * Start and stop a single container for testing. @@ -29,11 +35,14 @@ public DockerfileFixture(DockerClient dockerClient, String directory) { public void open() throws IOException { LOGGER.info("building {}", directory); - dockerClient + InputStream response = dockerClient .buildImageCmd(new File("src/test/resources", directory)) .withNoCache() // remove alternatives, cause problems - .exec() - .close(); + .exec(); + + String log = AbstractDockerClientTest.consumeAsString(response); + + assertThat(log, containsString("Successfully built")); Image lastCreatedImage = dockerClient .listImagesCmd() diff --git a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java index 0c22fc08..24c83355 100644 --- a/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java +++ b/src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java @@ -1,86 +1,97 @@ package com.github.dockerjava.core.command; +import static org.testng.Assert.assertEquals; +import static org.testng.AssertJUnit.assertNull; + +import java.io.IOException; +import java.io.InputStream; -import com.github.dockerjava.api.DockerClient; -import com.github.dockerjava.api.model.Frame; -import com.github.dockerjava.api.model.StreamType; -import com.github.dockerjava.core.DockerClientBuilder; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; -import java.io.IOException; -import java.io.InputStream; - -import static org.testng.Assert.assertEquals; -import static org.testng.AssertJUnit.assertNull; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.StreamType; +import com.github.dockerjava.core.DockerClientBuilder; @Test(groups = "integration") -public class FrameReaderITest { - - private DockerClient dockerClient; - private DockerfileFixture dockerfileFixture; - - @BeforeTest - public void beforeTest() throws Exception { - dockerClient = DockerClientBuilder.getInstance().build(); - dockerfileFixture = new DockerfileFixture(dockerClient, "frameReaderDockerfile"); - dockerfileFixture.open(); - } - - @AfterTest - public void deleteDockerContainerImage() throws Exception { - dockerfileFixture.close(); - dockerClient.close(); - } - - @Test - public void canCloseFrameReaderAndReadExpectedLines() throws Exception { - - try (FrameReader reader = new FrameReader(getLoggerStream())) { - assertEquals(reader.readFrame(), new Frame(StreamType.STDOUT, "to stdout\n".getBytes())); - assertEquals(reader.readFrame(), new Frame(StreamType.STDERR, "to stderr\n".getBytes())); - assertNull(reader.readFrame()); - } - } - - private InputStream getLoggerStream() { - return dockerClient - .logContainerCmd(dockerfileFixture.getContainerId()) - .withStdOut() - .withStdErr() - .withTailAll() - .withTail(10) - .withFollowStream() - .exec(); - } - - @Test - public void canLogInOneThreadAndExecuteCommandsInAnother() throws Exception { - - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - try (FrameReader reader = new FrameReader(getLoggerStream())) { - //noinspection StatementWithEmptyBody - while (reader.readFrame() != null) { - // nop - } - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - }); - - thread.start(); - - try (DockerfileFixture busyboxDockerfile = new DockerfileFixture(dockerClient, "busyboxDockerfile")) { - busyboxDockerfile.open(); - } - - thread.join(); - - } +public class FrameReaderITest { + + private DockerClient dockerClient; + private DockerfileFixture dockerfileFixture; + + @BeforeTest + public void beforeTest() throws Exception { + dockerClient = DockerClientBuilder.getInstance().build(); + dockerfileFixture = new DockerfileFixture(dockerClient, + "frameReaderDockerfile"); + dockerfileFixture.open(); + } + + @AfterTest + public void deleteDockerContainerImage() throws Exception { + dockerfileFixture.close(); + dockerClient.close(); + } + + @Test + public void canCloseFrameReaderAndReadExpectedLines() throws Exception { + + // wait for the container to be successfully executed + int exitCode = dockerClient.waitContainerCmd( + dockerfileFixture.getContainerId()).exec(); + assertEquals(0, exitCode); + + InputStream response = getLoggerStream(); + + try (FrameReader reader = new FrameReader(response)) { + assertEquals(reader.readFrame(), new Frame(StreamType.STDOUT, + "to stdout\n".getBytes())); + assertEquals(reader.readFrame(), new Frame(StreamType.STDERR, + "to stderr\n".getBytes())); + assertNull(reader.readFrame()); + } + } + + private InputStream getLoggerStream() { + + return dockerClient.logContainerCmd(dockerfileFixture.getContainerId()) + .withStdOut() + .withStdErr() + .withTailAll() + // we can't follow stream here as it blocks reading from resulting InputStream infinitely + //.withFollowStream() + .exec(); + } + + @Test + public void canLogInOneThreadAndExecuteCommandsInAnother() throws Exception { + + Thread thread = new Thread(new Runnable() { + @Override + public void run() { + try { + try (FrameReader reader = new FrameReader(getLoggerStream())) { + // noinspection StatementWithEmptyBody + while (reader.readFrame() != null) { + // nop + } + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + }); + + thread.start(); + + try (DockerfileFixture busyboxDockerfile = new DockerfileFixture( + dockerClient, "busyboxDockerfile")) { + busyboxDockerfile.open(); + } + + thread.join(); + + } } diff --git a/src/test/resources/frameReaderDockerfile/Dockerfile b/src/test/resources/frameReaderDockerfile/Dockerfile index 8d9b553e..9aa6b984 100644 --- a/src/test/resources/frameReaderDockerfile/Dockerfile +++ b/src/test/resources/frameReaderDockerfile/Dockerfile @@ -3,11 +3,9 @@ FROM busybox:latest # log to stdout and stderr so we can make sure logging with FrameReader works RUN echo '#! /bin/sh' > cmd.sh -RUN echo 'sleep 1' >> cmd.sh RUN echo 'echo "to stdout"' >> cmd.sh RUN echo 'echo "to stderr" > /dev/stderr' >> cmd.sh -# block for ever -RUN echo 'cat' >> cmd.sh +RUN echo 'sleep 1' >> cmd.sh RUN chmod +x cmd.sh CMD ["./cmd.sh"] \ No newline at end of file From bff4291ebb6ce99e1132199876af77208956c60d Mon Sep 17 00:00:00 2001 From: Marcus Linke Date: Fri, 22 May 2015 23:29:43 +0200 Subject: [PATCH 451/452] Added test for starting container with auto assigned port binding --- .../command/StartContainerCmdImplTest.java | 66 ++++++++++++++----- 1 file changed, 50 insertions(+), 16 deletions(-) diff --git a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java index 9a307165..045c008e 100644 --- a/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java +++ b/src/test/java/com/github/dockerjava/core/command/StartContainerCmdImplTest.java @@ -65,8 +65,7 @@ public void startContainerWithVolumes() throws DockerException { Volume volume2 = new Volume("/opt/webapp2"); CreateContainerResponse container = dockerClient - .createContainerCmd("busybox") - .withVolumes(volume1, volume2) + .createContainerCmd("busybox").withVolumes(volume1, volume2) .withCmd("true").exec(); LOG.info("Created container {}", container.toString()); @@ -91,8 +90,10 @@ public void startContainerWithVolumes() throws DockerException { assertContainerHasVolumes(inspectContainerResponse, volume1, volume2); - assertThat(Arrays.asList(inspectContainerResponse.getVolumesRW()), - contains(new VolumeRW(volume1, AccessMode.ro), new VolumeRW(volume2))); + assertThat( + Arrays.asList(inspectContainerResponse.getVolumesRW()), + contains(new VolumeRW(volume1, AccessMode.ro), new VolumeRW( + volume2))); } @@ -224,6 +225,41 @@ public void startContainerWithPortBindings() throws DockerException { } + @Test + public void startContainerWithRandomPortBindings() throws DockerException { + + ExposedPort tcp22 = ExposedPort.tcp(22); + ExposedPort tcp23 = ExposedPort.tcp(23); + + Ports portBindings = new Ports(); + portBindings.bind(tcp22, Ports.Binding(null)); + portBindings.bind(tcp23, Ports.Binding(null)); + + CreateContainerResponse container = dockerClient + .createContainerCmd("busybox").withCmd("sleep", "9999") + .withExposedPorts(tcp22, tcp23).withPortBindings(portBindings) + .withPublishAllPorts(true).exec(); + + LOG.info("Created container {}", container.toString()); + + assertThat(container.getId(), not(isEmptyString())); + + dockerClient.startContainerCmd(container.getId()).exec(); + + InspectContainerResponse inspectContainerResponse = dockerClient + .inspectContainerCmd(container.getId()).exec(); + + assertThat(Arrays.asList(inspectContainerResponse.getConfig() + .getExposedPorts()), contains(tcp22, tcp23)); + + assertThat(inspectContainerResponse.getNetworkSettings().getPorts() + .getBindings().get(tcp22)[0].getHostPort(), is(notNullValue())); + + assertThat(inspectContainerResponse.getNetworkSettings().getPorts() + .getBindings().get(tcp23)[0], is(notNullValue())); + + } + @Test public void startContainerWithConflictingPortBindings() throws DockerException { @@ -303,8 +339,9 @@ public void startContainerWithLinkingDeprecated() throws DockerException { is(notNullValue())); assertThat(inspectContainerResponse2.getHostConfig().getLinks(), is(notNullValue())); - assertThat(inspectContainerResponse2.getHostConfig().getLinks(), equalTo(new Link[] { new Link("container1", - "container1Link") })); + assertThat( + inspectContainerResponse2.getHostConfig().getLinks(), + equalTo(new Link[] { new Link("container1", "container1Link") })); assertThat(inspectContainerResponse2.getId(), startsWith(container2.getId())); assertThat(inspectContainerResponse2.getName(), equalTo("/container2")); @@ -313,8 +350,7 @@ public void startContainerWithLinkingDeprecated() throws DockerException { assertThat(inspectContainerResponse2.getState().isRunning(), is(true)); } - - + @Test public void startContainerWithLinking() throws DockerException { @@ -348,14 +384,12 @@ public void startContainerWithLinking() throws DockerException { CreateContainerResponse container2 = dockerClient .createContainerCmd("busybox").withCmd("sleep", "9999") .withName("container2") - .withLinks(new Link("container1", "container1Link")) - .exec(); + .withLinks(new Link("container1", "container1Link")).exec(); LOG.info("Created container2 {}", container2.toString()); assertThat(container2.getId(), not(isEmptyString())); - dockerClient.startContainerCmd(container2.getId()) - .exec(); + dockerClient.startContainerCmd(container2.getId()).exec(); InspectContainerResponse inspectContainerResponse2 = dockerClient .inspectContainerCmd(container2.getId()).exec(); @@ -367,8 +401,9 @@ public void startContainerWithLinking() throws DockerException { is(notNullValue())); assertThat(inspectContainerResponse2.getHostConfig().getLinks(), is(notNullValue())); - assertThat(inspectContainerResponse2.getHostConfig().getLinks(), equalTo(new Link[] { new Link("container1", - "container1Link") })); + assertThat( + inspectContainerResponse2.getHostConfig().getLinks(), + equalTo(new Link[] { new Link("container1", "container1Link") })); assertThat(inspectContainerResponse2.getId(), startsWith(container2.getId())); assertThat(inspectContainerResponse2.getName(), equalTo("/container2")); @@ -512,8 +547,7 @@ public void startContainerWithExtraHosts() throws DockerException { assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()) - .withExtraHosts("dockerhost:127.0.0.1") - .exec(); + .withExtraHosts("dockerhost:127.0.0.1").exec(); InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); From 60ee0cedd17a2648e6badb9aea1106c2f663c21b Mon Sep 17 00:00:00 2001 From: net613 Date: Mon, 25 May 2015 01:06:31 +0800 Subject: [PATCH 452/452] Add docker stats support --- .../github/dockerjava/api/DockerClient.java | 6 +- .../api/command/DockerCmdExecFactory.java | 4 +- .../dockerjava/api/command/StatsCmd.java | 15 +++ .../github/dockerjava/api/model/Stats.java | 40 +++++++ .../dockerjava/core/DockerClientImpl.java | 54 +++------- .../github/dockerjava/core/StatsCmdImpl.java | 33 ++++++ .../jaxrs/DockerCmdExecFactoryImpl.java | 102 ++++++++++-------- .../github/dockerjava/jaxrs/StatsCmdExec.java | 45 ++++++++ .../dockerjava/api/command/StatsCmdTest.java | 67 ++++++++++++ .../core/TestDockerCmdExecFactory.java | 46 +------- 10 files changed, 278 insertions(+), 134 deletions(-) create mode 100644 src/main/java/com/github/dockerjava/api/command/StatsCmd.java create mode 100644 src/main/java/com/github/dockerjava/api/model/Stats.java create mode 100644 src/main/java/com/github/dockerjava/core/StatsCmdImpl.java create mode 100644 src/main/java/com/github/dockerjava/jaxrs/StatsCmdExec.java create mode 100644 src/test/java/com/github/dockerjava/api/command/StatsCmdTest.java diff --git a/src/main/java/com/github/dockerjava/api/DockerClient.java b/src/main/java/com/github/dockerjava/api/DockerClient.java index 9e275eb3..0e141176 100644 --- a/src/main/java/com/github/dockerjava/api/DockerClient.java +++ b/src/main/java/com/github/dockerjava/api/DockerClient.java @@ -21,7 +21,7 @@ public interface DockerClient extends Closeable { public PingCmd pingCmd(); public VersionCmd versionCmd(); - + /** * * IMAGE API * */ @@ -96,6 +96,8 @@ public CopyFileFromContainerCmd copyFileFromContainerCmd( public RestartContainerCmd restartContainerCmd(String containerId); + public StatsCmd statsCmd(String containerId); + public CommitCmd commitCmd(String containerId); public BuildImageCmd buildImageCmd(); @@ -114,7 +116,7 @@ public CopyFileFromContainerCmd copyFileFromContainerCmd( public EventsCmd eventsCmd(EventCallback eventCallback); - @Override public void close() throws IOException; + } diff --git a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java index 8b988074..8d54a394 100644 --- a/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java +++ b/src/main/java/com/github/dockerjava/api/command/DockerCmdExecFactory.java @@ -79,7 +79,9 @@ public interface DockerCmdExecFactory extends Closeable { public EventsCmd.Exec createEventsCmdExec(); - @Override public void close() throws IOException; + // add + public StatsCmd.Exec createStatsCmdExec(); + } \ No newline at end of file diff --git a/src/main/java/com/github/dockerjava/api/command/StatsCmd.java b/src/main/java/com/github/dockerjava/api/command/StatsCmd.java new file mode 100644 index 00000000..dc57196e --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/command/StatsCmd.java @@ -0,0 +1,15 @@ +package com.github.dockerjava.api.command; + +import com.github.dockerjava.api.model.Stats; + +/** + * @author Heng WU(wuheng09@otcaix.iscas.ac.cn) + * + */ +public interface StatsCmd extends DockerCmd { + + public static interface Exec extends DockerCmdExec { + } + + public String getContainerId(); +} diff --git a/src/main/java/com/github/dockerjava/api/model/Stats.java b/src/main/java/com/github/dockerjava/api/model/Stats.java new file mode 100644 index 00000000..8c47c3d3 --- /dev/null +++ b/src/main/java/com/github/dockerjava/api/model/Stats.java @@ -0,0 +1,40 @@ +package com.github.dockerjava.api.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Heng WU(wuheng09@otcaix.iscas.ac.cn) + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Stats { + + @JsonProperty("read") + private String read; + + @JsonProperty("network") + private Object network; + + @JsonProperty("cpu_stats") + private Object cpu_stats; + + @JsonProperty("memory_stats") + private Object memory_stats; + + public String getRead() { + return read; + } + + public Object getNetwork() { + return network; + } + + public Object getCpu_stats() { + return cpu_stats; + } + + public Object getMemory_stats() { + return memory_stats; + } +} diff --git a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java index 7e96225f..c4b8aef1 100644 --- a/src/main/java/com/github/dockerjava/core/DockerClientImpl.java +++ b/src/main/java/com/github/dockerjava/core/DockerClientImpl.java @@ -72,7 +72,6 @@ private DockerCmdExecFactory getDockerCmdExecFactory() { return dockerCmdExecFactory; } - @Override public AuthConfig authConfig() { checkNotNull(dockerClientConfig.getUsername(), "Configured username is null."); @@ -95,23 +94,21 @@ public AuthConfig authConfig() { /** * Authenticate with the server, useful for checking authentication. */ - @Override public AuthCmd authCmd() { return new AuthCmdImpl(getDockerCmdExecFactory().createAuthCmdExec(), authConfig()); } - @Override public InfoCmd infoCmd() { return new InfoCmdImpl(getDockerCmdExecFactory().createInfoCmdExec()); } - @Override + + public PingCmd pingCmd() { return new PingCmdImpl(getDockerCmdExecFactory().createPingCmdExec()); } - @Override public VersionCmd versionCmd() { return new VersionCmdImpl(getDockerCmdExecFactory() .createVersionCmdExec()); @@ -120,13 +117,11 @@ public VersionCmd versionCmd() { /** * * IMAGE API * */ - @Override public PullImageCmd pullImageCmd(String repository) { return new PullImageCmdImpl(getDockerCmdExecFactory() .createPullImageCmdExec(), dockerClientConfig.effectiveAuthConfig(repository), repository); } - @Override public PushImageCmd pushImageCmd(String name) { PushImageCmd cmd = new PushImageCmdImpl(getDockerCmdExecFactory() .createPushImageCmdExec(), name); @@ -137,7 +132,6 @@ public PushImageCmd pushImageCmd(String name) { return cmd; } - @Override public PushImageCmd pushImageCmd(Identifier identifier) { PushImageCmd cmd = pushImageCmd(identifier.repository.name); if( identifier.tag.isPresent() ) @@ -150,37 +144,31 @@ public PushImageCmd pushImageCmd(Identifier identifier) { return cmd; } - @Override public SaveImageCmd saveImageCmd(String name) { return new SaveImageCmdImpl(getDockerCmdExecFactory().createSaveImageCmdExec(), name); } - @Override public CreateImageCmd createImageCmd(String repository, InputStream imageStream) { return new CreateImageCmdImpl(getDockerCmdExecFactory() .createCreateImageCmdExec(), repository, imageStream); } - @Override public SearchImagesCmd searchImagesCmd(String term) { return new SearchImagesCmdImpl(getDockerCmdExecFactory() .createSearchImagesCmdExec(), term); } - @Override public RemoveImageCmd removeImageCmd(String imageId) { return new RemoveImageCmdImpl(getDockerCmdExecFactory() .createRemoveImageCmdExec(), imageId); } - @Override public ListImagesCmd listImagesCmd() { return new ListImagesCmdImpl(getDockerCmdExecFactory() .createListImagesCmdExec()); } - @Override public InspectImageCmd inspectImageCmd(String imageId) { return new InspectImageCmdImpl(getDockerCmdExecFactory() .createInspectImageCmdExec(), imageId); @@ -189,120 +177,101 @@ public InspectImageCmd inspectImageCmd(String imageId) { /** * * CONTAINER API * */ - - @Override public ListContainersCmd listContainersCmd() { return new ListContainersCmdImpl(getDockerCmdExecFactory() .createListContainersCmdExec()); } - @Override public CreateContainerCmd createContainerCmd(String image) { return new CreateContainerCmdImpl(getDockerCmdExecFactory() .createCreateContainerCmdExec(), image); } - @Override public StartContainerCmd startContainerCmd(String containerId) { return new StartContainerCmdImpl(getDockerCmdExecFactory() .createStartContainerCmdExec(), containerId); } - @Override public InspectContainerCmd inspectContainerCmd(String containerId) { return new InspectContainerCmdImpl(getDockerCmdExecFactory() .createInspectContainerCmdExec(), containerId); } - @Override public ExecCreateCmd execCreateCmd(String containerId) { return new ExecCreateCmdImpl(getDockerCmdExecFactory().createExecCmdExec(), containerId); } - @Override public RemoveContainerCmd removeContainerCmd(String containerId) { return new RemoveContainerCmdImpl(getDockerCmdExecFactory() .createRemoveContainerCmdExec(), containerId); } - @Override public WaitContainerCmd waitContainerCmd(String containerId) { return new WaitContainerCmdImpl(getDockerCmdExecFactory() .createWaitContainerCmdExec(), containerId); } - @Override public AttachContainerCmd attachContainerCmd(String containerId) { return new AttachContainerCmdImpl(getDockerCmdExecFactory() .createAttachContainerCmdExec(), containerId); } - @Override public ExecStartCmd execStartCmd(String containerId) { return new ExecStartCmdImpl(getDockerCmdExecFactory().createExecStartCmdExec(), containerId); } - @Override public InspectExecCmd inspectExecCmd(String execId) { return new InspectExecCmdImpl(getDockerCmdExecFactory().createInspectExecCmdExec(), execId); } - @Override public LogContainerCmd logContainerCmd(String containerId) { return new LogContainerCmdImpl(getDockerCmdExecFactory() .createLogContainerCmdExec(), containerId); } + + - @Override public CopyFileFromContainerCmd copyFileFromContainerCmd( String containerId, String resource) { return new CopyFileFromContainerCmdImpl(getDockerCmdExecFactory() .createCopyFileFromContainerCmdExec(), containerId, resource); } - @Override public ContainerDiffCmd containerDiffCmd(String containerId) { return new ContainerDiffCmdImpl(getDockerCmdExecFactory() .createContainerDiffCmdExec(), containerId); } - @Override public StopContainerCmd stopContainerCmd(String containerId) { return new StopContainerCmdImpl(getDockerCmdExecFactory() .createStopContainerCmdExec(), containerId); } - @Override public KillContainerCmd killContainerCmd(String containerId) { return new KillContainerCmdImpl(getDockerCmdExecFactory() .createKillContainerCmdExec(), containerId); } - @Override public RestartContainerCmd restartContainerCmd(String containerId) { return new RestartContainerCmdImpl(getDockerCmdExecFactory() .createRestartContainerCmdExec(), containerId); } - @Override public CommitCmd commitCmd(String containerId) { return new CommitCmdImpl(getDockerCmdExecFactory() .createCommitCmdExec(), containerId); } - @Override public BuildImageCmd buildImageCmd() { return augmentBuildImageCmd(new BuildImageCmdImpl(getDockerCmdExecFactory() .createBuildImageCmdExec())); } - @Override public BuildImageCmd buildImageCmd(File dockerFileOrFolder) { return augmentBuildImageCmd(new BuildImageCmdImpl(getDockerCmdExecFactory() .createBuildImageCmdExec(), dockerFileOrFolder)); } - @Override public BuildImageCmd buildImageCmd(InputStream tarInputStream) { return augmentBuildImageCmd(new BuildImageCmdImpl(getDockerCmdExecFactory() .createBuildImageCmdExec(), tarInputStream)); @@ -317,39 +286,40 @@ private BuildImageCmd augmentBuildImageCmd(BuildImageCmd buildImageCmd) { return buildImageCmd; } - @Override + public TopContainerCmd topContainerCmd(String containerId) { return new TopContainerCmdImpl(getDockerCmdExecFactory() .createTopContainerCmdExec(), containerId); } - @Override public TagImageCmd tagImageCmd(String imageId, String repository, String tag) { return new TagImageCmdImpl(getDockerCmdExecFactory() .createTagImageCmdExec(), imageId, repository, tag); } - @Override public PauseContainerCmd pauseContainerCmd(String containerId) { return new PauseContainerCmdImpl(getDockerCmdExecFactory() .createPauseContainerCmdExec(), containerId); } - @Override + public UnpauseContainerCmd unpauseContainerCmd(String containerId) { return new UnpauseContainerCmdImpl(getDockerCmdExecFactory() .createUnpauseContainerCmdExec(), containerId); } - @Override + public StatsCmd statsCmd(String containerId) { + return new StatsCmdImpl(getDockerCmdExecFactory() + .createStatsCmdExec(), containerId); + } + public EventsCmd eventsCmd(EventCallback eventCallback) { return new EventsCmdImpl(getDockerCmdExecFactory() .createEventsCmdExec(), eventCallback); } - @Override public void close() throws IOException { getDockerCmdExecFactory().close(); } - + } diff --git a/src/main/java/com/github/dockerjava/core/StatsCmdImpl.java b/src/main/java/com/github/dockerjava/core/StatsCmdImpl.java new file mode 100644 index 00000000..215825e3 --- /dev/null +++ b/src/main/java/com/github/dockerjava/core/StatsCmdImpl.java @@ -0,0 +1,33 @@ +package com.github.dockerjava.core; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.github.dockerjava.api.command.StatsCmd; +import com.github.dockerjava.api.model.Stats; +import com.github.dockerjava.core.command.AbstrDockerCmd; + +/** + * @author Heng WU(wuheng09@otcaix.iscas.ac.cn) + * + */ +public class StatsCmdImpl extends AbstrDockerCmd implements + StatsCmd { + + private String containerId; + + public StatsCmdImpl(StatsCmd.Exec exec, String containerId) { + super(exec); + checkNotNull(containerId, "containerId was not specified"); + this.containerId = containerId; + } + + public String getContainerId() { + return containerId; + } + + @Override + public String toString() { + return "stats"; + } + +} diff --git a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java index 3636bfd0..ccacb1f7 100644 --- a/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java +++ b/src/main/java/com/github/dockerjava/jaxrs/DockerCmdExecFactoryImpl.java @@ -5,11 +5,6 @@ import java.io.IOException; import java.net.URI; -import com.github.dockerjava.api.command.*; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import javax.net.ssl.SSLContext; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; @@ -22,20 +17,59 @@ import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.glassfish.jersey.CommonProperties; import org.glassfish.jersey.apache.connector.ApacheClientProperties; -//import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; -// see https://github.com/docker-java/docker-java/issues/196 -import com.github.dockerjava.jaxrs.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.client.HttpUrlConnectorProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.github.dockerjava.api.DockerClientException; +import com.github.dockerjava.api.command.AttachContainerCmd; +import com.github.dockerjava.api.command.AuthCmd; +import com.github.dockerjava.api.command.BuildImageCmd; +import com.github.dockerjava.api.command.CommitCmd; +import com.github.dockerjava.api.command.ContainerDiffCmd; +import com.github.dockerjava.api.command.CopyFileFromContainerCmd; +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.command.CreateImageCmd; +import com.github.dockerjava.api.command.DockerCmdExecFactory; +import com.github.dockerjava.api.command.EventsCmd; +import com.github.dockerjava.api.command.ExecCreateCmd; +import com.github.dockerjava.api.command.ExecStartCmd; +import com.github.dockerjava.api.command.InfoCmd; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectExecCmd; +import com.github.dockerjava.api.command.InspectImageCmd; +import com.github.dockerjava.api.command.KillContainerCmd; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.command.ListImagesCmd; +import com.github.dockerjava.api.command.LogContainerCmd; +import com.github.dockerjava.api.command.PauseContainerCmd; +import com.github.dockerjava.api.command.PingCmd; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.command.PushImageCmd; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.command.RemoveImageCmd; +import com.github.dockerjava.api.command.RestartContainerCmd; +import com.github.dockerjava.api.command.SaveImageCmd; +import com.github.dockerjava.api.command.SearchImagesCmd; +import com.github.dockerjava.api.command.StartContainerCmd; +import com.github.dockerjava.api.command.StatsCmd.Exec; +import com.github.dockerjava.api.command.StopContainerCmd; +import com.github.dockerjava.api.command.TagImageCmd; +import com.github.dockerjava.api.command.TopContainerCmd; +import com.github.dockerjava.api.command.UnpauseContainerCmd; +import com.github.dockerjava.api.command.VersionCmd; +import com.github.dockerjava.api.command.WaitContainerCmd; import com.github.dockerjava.core.DockerClientConfig; import com.github.dockerjava.core.util.FollowRedirectsFilter; import com.github.dockerjava.core.util.JsonClientFilter; import com.github.dockerjava.core.util.ResponseStatusExceptionFilter; import com.github.dockerjava.core.util.SelectiveLoggingFilter; - +//import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; +// see https://github.com/docker-java/docker-java/issues/196 +import com.github.dockerjava.jaxrs.connector.ApacheConnectorProvider; public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { @@ -44,12 +78,18 @@ public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory { private Client client; private WebTarget baseResource; - @Override public void init(DockerClientConfig dockerClientConfig) { checkNotNull(dockerClientConfig, "config was not specified"); ClientConfig clientConfig = new ClientConfig(); - clientConfig.connectorProvider(new ApacheConnectorProvider()); + // clientConfig.connectorProvider(new ApacheConnectorProvider()); + // see #226 + // StatsCmd could create a live stream for one container. + // Unfortunately, ApacheConnector would perform a ChunkedInputStream call that results in the application blocking. + // The reason is org.apache.http.impl.io.ChunkedInputStream would NEVER closes the underlying stream, even when close + // gets called. Instead, it will read until the "end" of its chunking on close. + // see com.github.dockerjava.api.command.StatsCmdTest + clientConfig.connectorProvider(new HttpUrlConnectorProvider()); clientConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); @@ -141,182 +181,150 @@ protected WebTarget getBaseResource() { return baseResource; } - @Override public AuthCmd.Exec createAuthCmdExec() { return new AuthCmdExec(getBaseResource()); } - @Override public InfoCmd.Exec createInfoCmdExec() { return new InfoCmdExec(getBaseResource()); } - @Override public PingCmd.Exec createPingCmdExec() { return new PingCmdExec(getBaseResource()); } - @Override public VersionCmd.Exec createVersionCmdExec() { return new VersionCmdExec(getBaseResource()); } - @Override public PullImageCmd.Exec createPullImageCmdExec() { return new PullImageCmdExec(getBaseResource()); } - @Override public PushImageCmd.Exec createPushImageCmdExec() { return new PushImageCmdExec(getBaseResource()); } - @Override public SaveImageCmd.Exec createSaveImageCmdExec() { return new SaveImageCmdExec(getBaseResource()); } - @Override public CreateImageCmd.Exec createCreateImageCmdExec() { return new CreateImageCmdExec(getBaseResource()); } - @Override public SearchImagesCmd.Exec createSearchImagesCmdExec() { return new SearchImagesCmdExec(getBaseResource()); } - @Override public RemoveImageCmd.Exec createRemoveImageCmdExec() { return new RemoveImageCmdExec(getBaseResource()); } - @Override public ListImagesCmd.Exec createListImagesCmdExec() { return new ListImagesCmdExec(getBaseResource()); } - @Override public InspectImageCmd.Exec createInspectImageCmdExec() { return new InspectImageCmdExec(getBaseResource()); } - @Override public ListContainersCmd.Exec createListContainersCmdExec() { return new ListContainersCmdExec(getBaseResource()); } - @Override public CreateContainerCmd.Exec createCreateContainerCmdExec() { return new CreateContainerCmdExec(getBaseResource()); } - @Override public StartContainerCmd.Exec createStartContainerCmdExec() { return new StartContainerCmdExec(getBaseResource()); } - @Override public InspectContainerCmd.Exec createInspectContainerCmdExec() { return new InspectContainerCmdExec(getBaseResource()); } - @Override public ExecCreateCmd.Exec createExecCmdExec() { return new ExecCreateCmdExec(getBaseResource()); } - @Override public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { return new RemoveContainerCmdExec(getBaseResource()); } - @Override public WaitContainerCmd.Exec createWaitContainerCmdExec() { return new WaitContainerCmdExec(getBaseResource()); } - @Override public AttachContainerCmd.Exec createAttachContainerCmdExec() { return new AttachContainerCmdExec(getBaseResource()); } - @Override public ExecStartCmd.Exec createExecStartCmdExec() { return new ExecStartCmdExec(getBaseResource()); } - @Override public InspectExecCmd.Exec createInspectExecCmdExec() { return new InspectExecCmdExec(getBaseResource()); } - @Override public LogContainerCmd.Exec createLogContainerCmdExec() { return new LogContainerCmdExec(getBaseResource()); } - @Override public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() { return new CopyFileFromContainerCmdExec(getBaseResource()); } - @Override public StopContainerCmd.Exec createStopContainerCmdExec() { return new StopContainerCmdExec(getBaseResource()); } - @Override public ContainerDiffCmd.Exec createContainerDiffCmdExec() { return new ContainerDiffCmdExec(getBaseResource()); } - @Override public KillContainerCmd.Exec createKillContainerCmdExec() { return new KillContainerCmdExec(getBaseResource()); } - @Override public RestartContainerCmd.Exec createRestartContainerCmdExec() { return new RestartContainerCmdExec(getBaseResource()); } - @Override public CommitCmd.Exec createCommitCmdExec() { return new CommitCmdExec(getBaseResource()); } - @Override public BuildImageCmd.Exec createBuildImageCmdExec() { return new BuildImageCmdExec(getBaseResource()); } - @Override public TopContainerCmd.Exec createTopContainerCmdExec() { return new TopContainerCmdExec(getBaseResource()); } - @Override public TagImageCmd.Exec createTagImageCmdExec() { return new TagImageCmdExec(getBaseResource()); } - @Override public PauseContainerCmd.Exec createPauseContainerCmdExec() { return new PauseContainerCmdExec(getBaseResource()); } - @Override public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { return new UnpauseContainerCmdExec(baseResource); } - @Override public EventsCmd.Exec createEventsCmdExec() { return new EventsCmdExec(getBaseResource()); } - @Override + public Exec createStatsCmdExec() { + return new StatsCmdExec(getBaseResource()); + } + public void close() throws IOException { checkNotNull(client, "Factory not initialized. You probably forgot to call init()!"); diff --git a/src/main/java/com/github/dockerjava/jaxrs/StatsCmdExec.java b/src/main/java/com/github/dockerjava/jaxrs/StatsCmdExec.java new file mode 100644 index 00000000..64bcaced --- /dev/null +++ b/src/main/java/com/github/dockerjava/jaxrs/StatsCmdExec.java @@ -0,0 +1,45 @@ +package com.github.dockerjava.jaxrs; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.client.JerseyInvocation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.dockerjava.api.command.StatsCmd; +import com.github.dockerjava.api.model.Stats; + +/** + * @author Heng WU(wuheng09@otcaix.iscas.ac.cn) + * + */ +public class StatsCmdExec extends AbstrDockerCmdExec implements + StatsCmd.Exec { + + private static final Logger LOGGER = LoggerFactory + .getLogger(StatsCmdExec.class); + + public StatsCmdExec(WebTarget baseResource) { + super(baseResource); + } + + protected Stats execute(StatsCmd command) { + WebTarget webResource = getBaseResource() + .path("/containers/{id}/stats").resolveTemplate("id", + command.getContainerId()); + + LOGGER.trace("GET: {}", webResource); + JerseyInvocation.Builder request = (JerseyInvocation.Builder) webResource.request(); + // see #221 + // This call would results in the application blocking if container is shutdown. + // So we need timeout settings + // see com.github.dockerjava.api.command.StatsCmdTest + request.property(ClientProperties.READ_TIMEOUT, 5000); + return request.accept(MediaType.APPLICATION_JSON) + .get(Stats.class); + } + + +} diff --git a/src/test/java/com/github/dockerjava/api/command/StatsCmdTest.java b/src/test/java/com/github/dockerjava/api/command/StatsCmdTest.java new file mode 100644 index 00000000..d5caeb9a --- /dev/null +++ b/src/test/java/com/github/dockerjava/api/command/StatsCmdTest.java @@ -0,0 +1,67 @@ +package com.github.dockerjava.api.command; + +import java.io.IOException; + +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; + +import org.glassfish.jersey.client.JerseyClient; +import org.glassfish.jersey.client.JerseyClientBuilder; + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.model.Stats; +import com.github.dockerjava.core.DockerClientBuilder; + +/** + * @author Heng WU(wuheng09@otcaix.iscas.ac.cn) + * + * if container is not exist, throws com.github.dockerjava.api.NotFoundException + * if container is shutdown, throws java.net.SocketTimeoutException + * if container is startup, return Object Stats + */ +public class StatsCmdTest { + + final static String DOCKER_SERVER = "http://127.0.0.1:2375"; + + final static String STARTUP_CONTAINER_ID = "4b4fb43779bcc2cb4d5aad954dac99224ff1c2ea623cd95322ef657a5c2f2c36"; + + final static String SHUTDOWN_CONTAINER_ID = "c571b02e26d30e03dfc21829de618df440275c303fbddb384679a5949d0de5d0"; + + final static String NOT_EXIST_CONTAINER_ID = "test1234"; + + /** + * @param args + * @throws IOException + */ + public static void main(String[] args) throws IOException { + noramlStatsImplWithContainer(); +// simpleStatsImplWithContainer(); + } + + + private static void noramlStatsImplWithContainer() throws IOException { + DockerClient client = DockerClientBuilder.getInstance(DOCKER_SERVER) + .build(); + Stats stats = client.statsCmd(SHUTDOWN_CONTAINER_ID).exec(); + System.out.println("Read:" + stats.getRead()); + System.out.println("Cpu_stats:" + stats.getCpu_stats()); + System.out.println("Memory_stats:" + stats.getMemory_stats()); + client.close(); + } + + private static void simpleStatsImplWithContainer() { + JerseyClient jcli = new JerseyClientBuilder().build(); + jcli.register(JacksonJsonProvider.class); + WebTarget baseTar = jcli.target(DOCKER_SERVER); + WebTarget target = baseTar.path("/containers/" + SHUTDOWN_CONTAINER_ID + + "/stats"); + Stats stats = target.request().accept(MediaType.APPLICATION_JSON) + .get(Stats.class); + System.out.println("Read:" + stats.getRead()); + System.out.println("Cpu_stats:" + stats.getCpu_stats()); + System.out.println("Memory_stats:" + stats.getMemory_stats()); + jcli.close(); + } + +} diff --git a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java index 869a12fc..82297cd2 100644 --- a/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java +++ b/src/test/java/com/github/dockerjava/core/TestDockerCmdExecFactory.java @@ -30,20 +30,16 @@ public TestDockerCmdExecFactory(DockerCmdExecFactory delegate) { this.delegate = delegate; } - @Override public void init(DockerClientConfig dockerClientConfig) { delegate.init(dockerClientConfig); } - @Override public void close() throws IOException { delegate.close(); } - @Override public CreateContainerCmd.Exec createCreateContainerCmdExec() { return new CreateContainerCmd.Exec() { - @Override public CreateContainerResponse exec(CreateContainerCmd command) { CreateContainerResponse createContainerResponse = delegate .createCreateContainerCmdExec().exec(command); @@ -53,10 +49,8 @@ public CreateContainerResponse exec(CreateContainerCmd command) { }; } - @Override public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { return new RemoveContainerCmd.Exec() { - @Override public Void exec(RemoveContainerCmd command) { delegate.createRemoveContainerCmdExec().exec(command); containerNames.remove(command.getContainerId()); @@ -65,10 +59,8 @@ public Void exec(RemoveContainerCmd command) { }; } - @Override public CreateImageCmd.Exec createCreateImageCmdExec() { return new CreateImageCmd.Exec() { - @Override public CreateImageResponse exec(CreateImageCmd command) { CreateImageResponse createImageResponse = delegate .createCreateImageCmdExec().exec(command); @@ -78,10 +70,8 @@ public CreateImageResponse exec(CreateImageCmd command) { }; } - @Override public RemoveImageCmd.Exec createRemoveImageCmdExec() { return new RemoveImageCmd.Exec() { - @Override public Void exec(RemoveImageCmd command) { delegate.createRemoveImageCmdExec().exec(command); imageNames.remove(command.getImageId()); @@ -90,10 +80,8 @@ public Void exec(RemoveImageCmd command) { }; } - @Override public BuildImageCmd.Exec createBuildImageCmdExec() { return new BuildImageCmd.Exec() { - @Override public BuildImageCmd.Response exec(BuildImageCmd command) { // can't detect image id here so tagging it String tag = command.getTag(); @@ -109,152 +97,122 @@ public BuildImageCmd.Response exec(BuildImageCmd command) { }; } - @Override public Exec createAuthCmdExec() { return delegate.createAuthCmdExec(); } - @Override public InfoCmd.Exec createInfoCmdExec() { return delegate.createInfoCmdExec(); } - @Override public PingCmd.Exec createPingCmdExec() { return delegate.createPingCmdExec(); } - @Override public ExecCreateCmd.Exec createExecCmdExec() { return delegate.createExecCmdExec(); } - @Override public VersionCmd.Exec createVersionCmdExec() { return delegate.createVersionCmdExec(); } - @Override public PullImageCmd.Exec createPullImageCmdExec() { return delegate.createPullImageCmdExec(); } - @Override public PushImageCmd.Exec createPushImageCmdExec() { return delegate.createPushImageCmdExec(); } - @Override public SaveImageCmd.Exec createSaveImageCmdExec() { return delegate.createSaveImageCmdExec(); } - @Override public SearchImagesCmd.Exec createSearchImagesCmdExec() { return delegate.createSearchImagesCmdExec(); } - @Override public ListImagesCmd.Exec createListImagesCmdExec() { return delegate.createListImagesCmdExec(); } - @Override public InspectImageCmd.Exec createInspectImageCmdExec() { return delegate.createInspectImageCmdExec(); } - @Override public ListContainersCmd.Exec createListContainersCmdExec() { return delegate.createListContainersCmdExec(); } - @Override public StartContainerCmd.Exec createStartContainerCmdExec() { return delegate.createStartContainerCmdExec(); } - @Override public InspectContainerCmd.Exec createInspectContainerCmdExec() { return delegate.createInspectContainerCmdExec(); } - @Override public WaitContainerCmd.Exec createWaitContainerCmdExec() { return delegate.createWaitContainerCmdExec(); } - @Override public AttachContainerCmd.Exec createAttachContainerCmdExec() { return delegate.createAttachContainerCmdExec(); } - @Override public ExecStartCmd.Exec createExecStartCmdExec() { return delegate.createExecStartCmdExec(); } - @Override public InspectExecCmd.Exec createInspectExecCmdExec() { return delegate.createInspectExecCmdExec(); } - @Override public LogContainerCmd.Exec createLogContainerCmdExec() { return delegate.createLogContainerCmdExec(); } - @Override public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() { return delegate.createCopyFileFromContainerCmdExec(); } - @Override public StopContainerCmd.Exec createStopContainerCmdExec() { return delegate.createStopContainerCmdExec(); } - @Override public ContainerDiffCmd.Exec createContainerDiffCmdExec() { return delegate.createContainerDiffCmdExec(); } - @Override public KillContainerCmd.Exec createKillContainerCmdExec() { return delegate.createKillContainerCmdExec(); } - @Override public RestartContainerCmd.Exec createRestartContainerCmdExec() { return delegate.createRestartContainerCmdExec(); } - @Override public CommitCmd.Exec createCommitCmdExec() { return delegate.createCommitCmdExec(); } - @Override public TopContainerCmd.Exec createTopContainerCmdExec() { return delegate.createTopContainerCmdExec(); } - @Override public TagImageCmd.Exec createTagImageCmdExec() { return delegate.createTagImageCmdExec(); } - @Override public PauseContainerCmd.Exec createPauseContainerCmdExec() { return delegate.createPauseContainerCmdExec(); } - @Override public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { return delegate.createUnpauseContainerCmdExec(); } - @Override public EventsCmd.Exec createEventsCmdExec() { return delegate.createEventsCmdExec(); } @@ -267,4 +225,8 @@ public List getImageNames() { return new ArrayList(imageNames); } + public StatsCmd.Exec createStatsCmdExec() { + return delegate.createStatsCmdExec(); + } + }