Search in sources :

Example 6 with Image

use of io.fabric8.docker.api.model.Image in project docker-maven-plugin by fabric8io.

the class DockerAccessWithHcClient method removeImage.

@Override
public boolean removeImage(String image, boolean... forceOpt) throws DockerAccessException {
    boolean force = forceOpt != null && forceOpt.length > 0 && forceOpt[0];
    try {
        String url = urlBuilder.deleteImage(image, force);
        HttpBodyAndStatus response = delegate.delete(url, new BodyAndStatusResponseHandler(), HTTP_OK, HTTP_NOT_FOUND);
        if (log.isDebugEnabled()) {
            logRemoveResponse(new JSONArray(response.getBody()));
        }
        return response.getStatusCode() == HTTP_OK;
    } catch (IOException e) {
        throw new DockerAccessException(e, "Unable to remove image [%s]", image);
    }
}
Also used : BodyAndStatusResponseHandler(io.fabric8.maven.docker.access.hc.ApacheHttpClientDelegate.BodyAndStatusResponseHandler) JSONArray(org.json.JSONArray) HttpBodyAndStatus(io.fabric8.maven.docker.access.hc.ApacheHttpClientDelegate.HttpBodyAndStatus)

Example 7 with Image

use of io.fabric8.docker.api.model.Image in project docker-maven-plugin by fabric8io.

the class DockerAssemblyManager method createDockerTarArchive.

/**
 * Create an docker tar archive from the given configuration which can be send to the Docker host for
 * creating the image.
 *
 * @param imageName Name of the image to create (used for creating build directories)
 * @param params Mojos parameters (used for finding the directories)
 * @param buildConfig configuration for how to build the image
 * @param log Logger used to display warning if permissions are to be normalized
 * @param finalCustomizer finalCustomizer to be applied to the tar archive
 * @return file holding the path to the created assembly tar file
 * @throws MojoExecutionException
 */
public File createDockerTarArchive(String imageName, MojoParameters params, final BuildImageConfiguration buildConfig, Logger log, ArchiverCustomizer finalCustomizer) throws MojoExecutionException {
    final BuildDirs buildDirs = createBuildDirs(imageName, params);
    final AssemblyConfiguration assemblyConfig = buildConfig.getAssemblyConfiguration();
    final List<ArchiverCustomizer> archiveCustomizers = new ArrayList<>();
    // Build up assembly. In dockerfile mode this must be added explicitly in the Dockerfile with an ADD
    if (hasAssemblyConfiguration(assemblyConfig)) {
        createAssemblyArchive(assemblyConfig, params, buildDirs);
    }
    try {
        if (buildConfig.isDockerFileMode()) {
            // Use specified docker directory which must include a Dockerfile.
            final File dockerFile = buildConfig.getAbsoluteDockerFilePath(params);
            if (!dockerFile.exists()) {
                throw new MojoExecutionException("Configured Dockerfile \"" + buildConfig.getDockerFile() + "\" (resolved to \"" + dockerFile + "\") doesn't exist");
            }
            FixedStringSearchInterpolator interpolator = DockerFileUtil.createInterpolator(params, buildConfig.getFilter());
            verifyGivenDockerfile(dockerFile, buildConfig, interpolator, log);
            interpolateDockerfile(dockerFile, buildDirs, interpolator);
            // User dedicated Dockerfile from extra directory
            archiveCustomizers.add(new ArchiverCustomizer() {

                @Override
                public TarArchiver customize(TarArchiver archiver) throws IOException {
                    DefaultFileSet fileSet = DefaultFileSet.fileSet(dockerFile.getParentFile());
                    addDockerIgnoreIfPresent(fileSet);
                    // Exclude non-interpolated dockerfile from source tree
                    // Interpolated Dockerfile is already added as it was created into the output directory when
                    // using dir dir mode
                    excludeDockerfile(fileSet, dockerFile);
                    // directly to docker.tar (as the output builddir is not picked up in archive mode)
                    if (isArchive(assemblyConfig)) {
                        String name = dockerFile.getName();
                        archiver.addFile(new File(buildDirs.getOutputDirectory(), name), name);
                    }
                    archiver.addFileSet(fileSet);
                    return archiver;
                }
            });
        } else {
            // Create custom docker file in output dir
            DockerFileBuilder builder = createDockerFileBuilder(buildConfig, assemblyConfig);
            builder.write(buildDirs.getOutputDirectory());
            // Add own Dockerfile
            final File dockerFile = new File(buildDirs.getOutputDirectory(), DOCKERFILE_NAME);
            archiveCustomizers.add(new ArchiverCustomizer() {

                @Override
                public TarArchiver customize(TarArchiver archiver) throws IOException {
                    archiver.addFile(dockerFile, DOCKERFILE_NAME);
                    return archiver;
                }
            });
        }
        // If required make all files in the assembly executable
        if (assemblyConfig != null) {
            AssemblyConfiguration.PermissionMode mode = assemblyConfig.getPermissions();
            if (mode == AssemblyConfiguration.PermissionMode.exec || mode == AssemblyConfiguration.PermissionMode.auto && EnvUtil.isWindows()) {
                archiveCustomizers.add(new AllFilesExecCustomizer(log));
            }
        }
        if (finalCustomizer != null) {
            archiveCustomizers.add(finalCustomizer);
        }
        return createBuildTarBall(buildDirs, archiveCustomizers, assemblyConfig, buildConfig.getCompression());
    } catch (IOException e) {
        throw new MojoExecutionException(String.format("Cannot create %s in %s", DOCKERFILE_NAME, buildDirs.getOutputDirectory()), e);
    }
}
Also used : FixedStringSearchInterpolator(org.codehaus.plexus.interpolation.fixed.FixedStringSearchInterpolator) DefaultFileSet(org.codehaus.plexus.archiver.util.DefaultFileSet) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) TarArchiver(org.codehaus.plexus.archiver.tar.TarArchiver) AssemblyConfiguration(io.fabric8.maven.docker.config.AssemblyConfiguration) File(java.io.File)

Example 8 with Image

use of io.fabric8.docker.api.model.Image in project docker-maven-plugin by fabric8io.

the class BuildService method buildImage.

/**
 * Build an image
 *
 * @param imageConfig the image configuration
 * @param params mojo params for the project
 * @param noCache if not null, dictate the caching behaviour. Otherwise its taken from the build configuration
 * @param buildArgs
 * @throws DockerAccessException
 * @throws MojoExecutionException
 */
protected void buildImage(ImageConfiguration imageConfig, MojoParameters params, boolean noCache, Map<String, String> buildArgs) throws DockerAccessException, MojoExecutionException {
    String imageName = imageConfig.getName();
    ImageName.validate(imageName);
    BuildImageConfiguration buildConfig = imageConfig.getBuildConfiguration();
    String oldImageId = null;
    CleanupMode cleanupMode = buildConfig.cleanupMode();
    if (cleanupMode.isRemove()) {
        oldImageId = queryService.getImageId(imageName);
    }
    long time = System.currentTimeMillis();
    if (buildConfig.getDockerArchive() != null) {
        docker.loadImage(imageName, buildConfig.getAbsoluteDockerTarPath(params));
        log.info("%s: Loaded tarball in %s", buildConfig.getDockerArchive(), EnvUtil.formatDurationTill(time));
        return;
    }
    File dockerArchive = archiveService.createArchive(imageName, buildConfig, params, log);
    log.info("%s: Created %s in %s", imageConfig.getDescription(), dockerArchive.getName(), EnvUtil.formatDurationTill(time));
    Map<String, String> mergedBuildMap = prepareBuildArgs(buildArgs, buildConfig);
    // auto is now supported by docker, consider switching?
    BuildOptions opts = new BuildOptions(buildConfig.getBuildOptions()).dockerfile(getDockerfileName(buildConfig)).forceRemove(cleanupMode.isRemove()).noCache(noCache).buildArgs(mergedBuildMap);
    String newImageId = doBuildImage(imageName, dockerArchive, opts);
    log.info("%s: Built image %s", imageConfig.getDescription(), newImageId);
    if (oldImageId != null && !oldImageId.equals(newImageId)) {
        try {
            docker.removeImage(oldImageId, true);
            log.info("%s: Removed old image %s", imageConfig.getDescription(), oldImageId);
        } catch (DockerAccessException exp) {
            if (cleanupMode == CleanupMode.TRY_TO_REMOVE) {
                log.warn("%s: %s (old image)%s", imageConfig.getDescription(), exp.getMessage(), (exp.getCause() != null ? " [" + exp.getCause().getMessage() + "]" : ""));
            } else {
                throw exp;
            }
        }
    }
}
Also used : BuildOptions(io.fabric8.maven.docker.access.BuildOptions) DockerAccessException(io.fabric8.maven.docker.access.DockerAccessException) CleanupMode(io.fabric8.maven.docker.config.CleanupMode) File(java.io.File) BuildImageConfiguration(io.fabric8.maven.docker.config.BuildImageConfiguration)

Example 9 with Image

use of io.fabric8.docker.api.model.Image in project docker-maven-plugin by fabric8io.

the class QueryService method getLatestContainerForImage.

/**
 * Get the id of the latest container started for an image
 *
 * @param image for which its container are looked up
 * @return container or <code>null</code> if no container has been started for this image.
 * @throws DockerAccessException if the request fails
 */
public Container getLatestContainerForImage(String image) throws DockerAccessException {
    long newest = 0;
    Container result = null;
    for (Container container : getContainersForImage(image)) {
        long timestamp = container.getCreated();
        if (timestamp < newest) {
            continue;
        }
        newest = timestamp;
        result = container;
    }
    return result;
}
Also used : Container(io.fabric8.maven.docker.model.Container)

Example 10 with Image

use of io.fabric8.docker.api.model.Image in project docker-maven-plugin by fabric8io.

the class RegistryService method pullImageWithPolicy.

/**
 * Check an image, and, if <code>autoPull</code> is set to true, fetch it. Otherwise if the image
 * is not existent, throw an error
 * @param registryConfig registry configuration
 *
 * @throws DockerAccessException
 * @throws MojoExecutionException
 */
public void pullImageWithPolicy(String image, ImagePullManager pullManager, RegistryConfig registryConfig, boolean hasImage) throws DockerAccessException, MojoExecutionException {
    // Already pulled, so we don't need to take care
    if (pullManager.hasAlreadyPulled(image)) {
        return;
    }
    // Check if a pull is required
    if (!imageRequiresPull(hasImage, pullManager.getImagePullPolicy(), image)) {
        return;
    }
    ImageName imageName = new ImageName(image);
    long time = System.currentTimeMillis();
    String actualRegistry = EnvUtil.fistRegistryOf(imageName.getRegistry(), registryConfig.getRegistry());
    docker.pullImage(imageName.getFullName(), createAuthConfig(false, null, actualRegistry, registryConfig), actualRegistry);
    log.info("Pulled %s in %s", imageName.getFullName(), EnvUtil.formatDurationTill(time));
    pullManager.pulled(image);
    if (actualRegistry != null && !imageName.hasRegistry()) {
        // If coming from a registry which was not contained in the original name, add a tag from the
        // full name with the registry to the short name with no-registry.
        docker.tag(imageName.getFullName(actualRegistry), image, false);
    }
}
Also used : ImageName(io.fabric8.maven.docker.util.ImageName)

Aggregations

Test (org.junit.Test)35 BuildImageConfiguration (io.fabric8.maven.docker.config.BuildImageConfiguration)28 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)20 IOException (java.io.IOException)16 AbstractConfigHandlerTest (io.fabric8.maven.docker.config.handler.AbstractConfigHandlerTest)15 File (java.io.File)13 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)12 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)12 ImageStream (io.fabric8.openshift.api.model.ImageStream)10 Arguments (io.fabric8.maven.docker.config.Arguments)8 Service (io.fabric8.kubernetes.api.model.Service)7 Fabric8ServiceException (io.fabric8.maven.core.service.Fabric8ServiceException)7 Deployment (io.fabric8.kubernetes.api.model.extensions.Deployment)6 BuildService (io.fabric8.maven.core.service.BuildService)6 BuildConfig (io.fabric8.openshift.api.model.BuildConfig)6 HashMap (java.util.HashMap)6 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)5 DockerAccessException (io.fabric8.maven.docker.access.DockerAccessException)5 ImageName (io.fabric8.maven.docker.util.ImageName)5 ImageStreamTag (io.fabric8.openshift.api.model.ImageStreamTag)5