Search in sources :

Example 31 with ImageName

use of io.fabric8.maven.docker.util.ImageName in project fabric8-maven-plugin by fabric8io.

the class OpenshiftBuildService method updateOrCreateBuildConfig.

private String updateOrCreateBuildConfig(BuildServiceConfig config, OpenShiftClient client, KubernetesListBuilder builder, ImageConfiguration imageConfig) {
    ImageName imageName = new ImageName(imageConfig.getName());
    String buildName = getS2IBuildName(config, imageName);
    String imageStreamName = getImageStreamName(imageName);
    String outputImageStreamTag = imageStreamName + ":" + (imageName.getTag() != null ? imageName.getTag() : "latest");
    BuildStrategy buildStrategyResource = createBuildStrategy(imageConfig, config.getOpenshiftBuildStrategy());
    BuildOutput buildOutput = new BuildOutputBuilder().withNewTo().withKind("ImageStreamTag").withName(outputImageStreamTag).endTo().build();
    // Fetch exsting build config
    BuildConfig buildConfig = client.buildConfigs().withName(buildName).get();
    if (buildConfig != null) {
        // lets verify the BC
        BuildConfigSpec spec = getBuildConfigSpec(buildConfig);
        validateSourceType(buildName, spec);
        if (config.getBuildRecreateMode().isBuildConfig()) {
            // Delete and recreate afresh
            client.buildConfigs().withName(buildName).delete();
            return createBuildConfig(builder, buildName, buildStrategyResource, buildOutput);
        } else {
            // Update & return
            return updateBuildConfig(client, buildName, buildStrategyResource, buildOutput, spec);
        }
    } else {
        // Create afresh
        return createBuildConfig(builder, buildName, buildStrategyResource, buildOutput);
    }
}
Also used : ImageName(io.fabric8.maven.docker.util.ImageName) BuildOutput(io.fabric8.openshift.api.model.BuildOutput) BuildStrategy(io.fabric8.openshift.api.model.BuildStrategy) OpenShiftBuildStrategy(io.fabric8.maven.core.config.OpenShiftBuildStrategy) BuildOutputBuilder(io.fabric8.openshift.api.model.BuildOutputBuilder) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) BuildConfigSpec(io.fabric8.openshift.api.model.BuildConfigSpec)

Example 32 with ImageName

use of io.fabric8.maven.docker.util.ImageName in project fabric8-maven-plugin by fabric8io.

the class OpenshiftBuildService method build.

@Override
public void build(ImageConfiguration imageConfig) throws Fabric8ServiceException {
    try {
        ImageName imageName = new ImageName(imageConfig.getName());
        File dockerTar = createBuildArchive(imageConfig);
        KubernetesListBuilder builder = new KubernetesListBuilder();
        // Check for buildconfig / imagestream and create them if necessary
        String buildName = updateOrCreateBuildConfig(config, client, builder, imageConfig);
        checkOrCreateImageStream(config, client, builder, getImageStreamName(imageName));
        applyResourceObjects(config, client, builder);
        // Start the actual build
        Build build = startBuild(client, dockerTar, buildName);
        // Wait until the build finishes
        waitForOpenShiftBuildToComplete(client, build);
        // Create a file with generated image streams
        addImageStreamToFile(getImageStreamFile(config), imageName, client);
    } catch (Fabric8ServiceException e) {
        throw e;
    } catch (Exception ex) {
        throw new Fabric8ServiceException("Unable to build the image using the OpenShift build service", ex);
    }
}
Also used : ImageName(io.fabric8.maven.docker.util.ImageName) Fabric8ServiceException(io.fabric8.maven.core.service.Fabric8ServiceException) Build(io.fabric8.openshift.api.model.Build) File(java.io.File) Fabric8ServiceException(io.fabric8.maven.core.service.Fabric8ServiceException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException)

Example 33 with ImageName

use of io.fabric8.maven.docker.util.ImageName in project fabric8-maven-plugin by fabric8io.

the class BaseGenerator method addFrom.

/**
 * Add the base image either from configuration or from a given selector
 *
 * @param builder for the build image configuration to add the from to.
 */
protected void addFrom(BuildImageConfiguration.Builder builder) {
    String fromMode = getConfigWithSystemFallbackAndDefault(Config.fromMode, "fabric8.generator.fromMode", getFromModeDefault(context.getMode()));
    String from = getConfigWithSystemFallbackAndDefault(Config.from, "fabric8.generator.from", null);
    if ("docker".equalsIgnoreCase(fromMode)) {
        String fromImage = from;
        if (fromImage == null) {
            fromImage = fromSelector != null ? fromSelector.getFrom() : null;
        }
        builder.from(fromImage);
        log.info("Using Docker image %s as base / builder", fromImage);
    } else if ("istag".equalsIgnoreCase(fromMode)) {
        Map<String, String> fromExt = new HashMap<>();
        if (from != null) {
            ImageName iName = new ImageName(from);
            // user/project is considered to be the namespace
            String tag = iName.getTag();
            if (StringUtils.isBlank(tag)) {
                tag = "latest";
            }
            fromExt.put(OpenShiftBuildStrategy.SourceStrategy.name.key(), iName.getSimpleName() + ":" + tag);
            if (iName.getUser() != null) {
                fromExt.put(OpenShiftBuildStrategy.SourceStrategy.namespace.key(), iName.getUser());
            }
            fromExt.put(OpenShiftBuildStrategy.SourceStrategy.kind.key(), "ImageStreamTag");
        } else {
            fromExt = fromSelector != null ? fromSelector.getImageStreamTagFromExt() : null;
        }
        if (fromExt != null) {
            String namespace = fromExt.get(OpenShiftBuildStrategy.SourceStrategy.namespace.key());
            if (namespace != null) {
                log.info("Using ImageStreamTag '%s' from namespace '%s' as builder image", fromExt.get(OpenShiftBuildStrategy.SourceStrategy.name.key()), namespace);
            } else {
                log.info("Using ImageStreamTag '%s' as builder image", fromExt.get(OpenShiftBuildStrategy.SourceStrategy.name.key()));
            }
            builder.fromExt(fromExt);
        }
    } else {
        throw new IllegalArgumentException(String.format("Invalid 'fromMode' in generator configuration for '%s'", getName()));
    }
}
Also used : ImageName(io.fabric8.maven.docker.util.ImageName) HashMap(java.util.HashMap) Map(java.util.Map)

Example 34 with ImageName

use of io.fabric8.maven.docker.util.ImageName in project fabric8-maven-plugin by fabric8io.

the class DeploymentOpenShiftConverter method convert.

@Override
public HasMetadata convert(HasMetadata item, boolean trimImageInContainerSpec, boolean enableAutomaticTrigger) {
    Deployment resource = (Deployment) item;
    DeploymentConfigBuilder builder = new DeploymentConfigBuilder();
    builder.withMetadata(resource.getMetadata());
    DeploymentSpec spec = resource.getSpec();
    if (spec != null) {
        DeploymentConfigFluent.SpecNested<DeploymentConfigBuilder> specBuilder = builder.withNewSpec();
        Integer replicas = spec.getReplicas();
        if (replicas != null) {
            specBuilder.withReplicas(replicas);
        }
        Integer revisionHistoryLimit = spec.getRevisionHistoryLimit();
        if (revisionHistoryLimit != null) {
            specBuilder.withRevisionHistoryLimit(revisionHistoryLimit);
        }
        LabelSelector selector = spec.getSelector();
        if (selector != null) {
            Map<String, String> matchLabels = selector.getMatchLabels();
            if (matchLabels != null && !matchLabels.isEmpty()) {
                specBuilder.withSelector(matchLabels);
            }
        }
        Map<String, String> containerToImageMap = new HashMap<>();
        PodTemplateSpec template = spec.getTemplate();
        if (template != null) {
            specBuilder.withTemplate(template);
            PodSpec podSpec = template.getSpec();
            notNull(podSpec, "No PodSpec for PodTemplate:" + template);
            List<Container> containers = podSpec.getContainers();
            notNull(podSpec, "No containers for PodTemplate.spec: " + template);
            for (Container container : containers) {
                validateContainer(container);
                containerToImageMap.put(container.getName(), container.getImage());
            }
        }
        DeploymentStrategy strategy = spec.getStrategy();
        String strategyType = null;
        if (strategy != null) {
            strategyType = strategy.getType();
        }
        if (openshiftDeployTimeoutSeconds != null && openshiftDeployTimeoutSeconds > 0) {
            if (Strings.isNullOrBlank(strategyType) || "Rolling".equals(strategyType)) {
                specBuilder.withNewStrategy().withType("Rolling").withNewRollingParams().withTimeoutSeconds(openshiftDeployTimeoutSeconds).endRollingParams().endStrategy();
            } else if ("Recreate".equals(strategyType)) {
                specBuilder.withNewStrategy().withType("Recreate").withNewRecreateParams().withTimeoutSeconds(openshiftDeployTimeoutSeconds).endRecreateParams().endStrategy();
            } else {
                specBuilder.withNewStrategy().withType(strategyType).endStrategy();
            }
        } else if (Strings.isNotBlank(strategyType)) {
            // TODO is there any values we can copy across?
            specBuilder.withNewStrategy().withType(strategyType).endStrategy();
        }
        // lets add a default trigger so that its triggered when we change its config
        if (enableAutomaticTrigger) {
            specBuilder.addNewTrigger().withType("ConfigChange").endTrigger();
        }
        // add a new image change trigger for the build stream
        if (containerToImageMap.size() != 0) {
            if (mode.equals(PlatformMode.openshift)) {
                for (Map.Entry<String, String> entry : containerToImageMap.entrySet()) {
                    String containerName = entry.getKey();
                    ImageName image = new ImageName(entry.getValue());
                    String tag = image.getTag() != null ? image.getTag() : "latest";
                    specBuilder.addNewTrigger().withType("ImageChange").withNewImageChangeParams().withAutomatic(enableAutomaticTrigger).withNewFrom().withKind("ImageStreamTag").withName(image.getSimpleName() + ":" + tag).withNamespace(image.getUser()).endFrom().withContainerNames(containerName).endImageChangeParams().endTrigger();
                }
            }
            if (trimImageInContainerSpec) {
                /*
                         * In Openshift 3.7, update to container image is automatically triggering redeployments
                         * and those subsequent rollouts lead to RC complaining about a missing image reference.
                         *
                         *    See this : https://github.com/openshift/origin/issues/18406#issuecomment-364090247
                         *
                         * this the time it gets fixed. Do this:
                         * Since we're using ImageTrigger here, set container image to " ". If there is any config
                         * change never set to image else than " "; so doing oc apply/rollouts won't be creating
                         * re-deployments again and again.
                         *
                         */
                List<Container> containers = template.getSpec().getContainers();
                for (Integer nIndex = 0; nIndex < containers.size(); nIndex++) {
                    containers.get(nIndex).setImage(" ");
                }
                template.getSpec().setContainers(containers);
                specBuilder.withTemplate(template);
            }
        }
        specBuilder.endSpec();
    }
    return builder.build();
}
Also used : HashMap(java.util.HashMap) PodSpec(io.fabric8.kubernetes.api.model.PodSpec) DeploymentConfigFluent(io.fabric8.openshift.api.model.DeploymentConfigFluent) DeploymentConfigBuilder(io.fabric8.openshift.api.model.DeploymentConfigBuilder) LabelSelector(io.fabric8.kubernetes.api.model.LabelSelector) ImageName(io.fabric8.maven.docker.util.ImageName) PodTemplateSpec(io.fabric8.kubernetes.api.model.PodTemplateSpec) Container(io.fabric8.kubernetes.api.model.Container) HashMap(java.util.HashMap) Map(java.util.Map)

Example 35 with ImageName

use of io.fabric8.maven.docker.util.ImageName in project fabric8-maven-plugin by fabric8io.

the class DockerImageWatcher method buildImage.

protected void buildImage(ImageConfiguration imageConfig) throws DockerAccessException, MojoExecutionException {
    String imageName = imageConfig.getName();
    // lets regenerate the label
    try {
        String imagePrefix = getImagePrefix(imageName);
        imageName = imagePrefix + "%t";
        ImageNameFormatter formatter = new ImageNameFormatter(getContext().getProject(), new Date());
        imageName = formatter.format(imageName);
        imageConfig.setName(imageName);
        log.info("New image name: " + imageConfig.getName());
    } catch (Exception e) {
        log.error("Caught: " + e, e);
    }
}
Also used : ImageNameFormatter(io.fabric8.maven.docker.util.ImageNameFormatter) Date(java.util.Date) DockerAccessException(io.fabric8.maven.docker.access.DockerAccessException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException)

Aggregations

ImageName (io.fabric8.maven.docker.util.ImageName)20 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)11 BuildImageConfiguration (io.fabric8.maven.docker.config.BuildImageConfiguration)10 File (java.io.File)9 IOException (java.io.IOException)7 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)7 DockerAccessException (io.fabric8.maven.docker.access.DockerAccessException)6 Container (io.fabric8.kubernetes.api.model.Container)5 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)4 CopyConfiguration (io.fabric8.maven.docker.config.CopyConfiguration)4 Container (io.fabric8.maven.docker.model.Container)4 Test (org.junit.Test)4 DockerClient (io.fabric8.docker.client.DockerClient)3 PodSpec (io.fabric8.kubernetes.api.model.PodSpec)3 Deployment (io.fabric8.kubernetes.api.model.extensions.Deployment)3 RunImageConfiguration (io.fabric8.maven.docker.config.RunImageConfiguration)3 ArrayList (java.util.ArrayList)3 Matcher (java.util.regex.Matcher)3 Util.readAsString (io.fabric8.arquillian.utils.Util.readAsString)2 Controller (io.fabric8.kubernetes.api.Controller)2