Search in sources :

Example 16 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 17 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 18 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)

Example 19 with ImageName

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

the class DockerImageWatcher method updateImageName.

private void updateImageName(KubernetesClient kubernetes, String namespace, HasMetadata entity, String imagePrefix, String imageName) {
    String name = KubernetesHelper.getName(entity);
    if (entity instanceof Deployment) {
        Deployment resource = (Deployment) entity;
        DeploymentSpec spec = resource.getSpec();
        if (spec != null) {
            if (updateImageName(entity, spec.getTemplate(), imagePrefix, imageName)) {
                kubernetes.extensions().deployments().inNamespace(namespace).withName(name).replace(resource);
            }
        }
    } else if (entity instanceof ReplicaSet) {
        ReplicaSet resource = (ReplicaSet) entity;
        ReplicaSetSpec spec = resource.getSpec();
        if (spec != null) {
            if (updateImageName(entity, spec.getTemplate(), imagePrefix, imageName)) {
                kubernetes.extensions().replicaSets().inNamespace(namespace).withName(name).replace(resource);
            }
        }
    } else if (entity instanceof ReplicationController) {
        ReplicationController resource = (ReplicationController) entity;
        ReplicationControllerSpec spec = resource.getSpec();
        if (spec != null) {
            if (updateImageName(entity, spec.getTemplate(), imagePrefix, imageName)) {
                kubernetes.replicationControllers().inNamespace(namespace).withName(name).replace(resource);
            }
        }
    } else if (entity instanceof DeploymentConfig) {
        DeploymentConfig resource = (DeploymentConfig) entity;
        DeploymentConfigSpec spec = resource.getSpec();
        if (spec != null) {
            if (updateImageName(entity, spec.getTemplate(), imagePrefix, imageName)) {
                OpenShiftClient openshiftClient = new Controller(kubernetes).getOpenShiftClientOrNull();
                if (openshiftClient == null) {
                    log.warn("Ignoring DeploymentConfig %s as not connected to an OpenShift cluster", name);
                }
                openshiftClient.deploymentConfigs().inNamespace(namespace).withName(name).replace(resource);
            }
        }
    }
}
Also used : DeploymentSpec(io.fabric8.kubernetes.api.model.extensions.DeploymentSpec) ReplicaSetSpec(io.fabric8.kubernetes.api.model.extensions.ReplicaSetSpec) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) DeploymentConfigSpec(io.fabric8.openshift.api.model.DeploymentConfigSpec) Controller(io.fabric8.kubernetes.api.Controller) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController) ReplicaSet(io.fabric8.kubernetes.api.model.extensions.ReplicaSet) ReplicationControllerSpec(io.fabric8.kubernetes.api.model.ReplicationControllerSpec)

Example 20 with ImageName

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

the class SessionListener method hasRegistry.

/**
 * Checks to see if there's a registry name already provided in the image name
 *
 * Code influenced from <a href="https://github.com/rhuss/docker-maven-plugin/blob/master/src/main/java/org/jolokia/docker/maven/util/ImageName.java">docker-maven-plugin</a>
 * @param imageName
 * @return true if the image name contains a registry
 */
public static boolean hasRegistry(String imageName) {
    if (imageName == null) {
        throw new NullPointerException("Image name must not be null");
    }
    Pattern tagPattern = Pattern.compile("^(.+?)(?::([^:/]+))?$");
    Matcher matcher = tagPattern.matcher(imageName);
    if (!matcher.matches()) {
        throw new IllegalArgumentException(imageName + " is not a proper image name ([registry/][repo][:port]");
    }
    String rest = matcher.group(1);
    String[] parts = rest.split("\\s*/\\s*");
    String part = parts[0];
    return part.contains(".") || part.contains(":");
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Util.readAsString(io.fabric8.arquillian.utils.Util.readAsString)

Aggregations

ImageName (io.fabric8.maven.docker.util.ImageName)13 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)5 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)5 Test (org.junit.Test)5 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)4 BuildImageConfiguration (io.fabric8.maven.docker.config.BuildImageConfiguration)4 File (java.io.File)4 DockerClient (io.fabric8.docker.client.DockerClient)3 Container (io.fabric8.kubernetes.api.model.Container)3 PodSpec (io.fabric8.kubernetes.api.model.PodSpec)3 DockerAccessException (io.fabric8.maven.docker.access.DockerAccessException)3 UrlBuilder (io.fabric8.maven.docker.access.UrlBuilder)3 IOException (java.io.IOException)3 Controller (io.fabric8.kubernetes.api.Controller)2 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)2 ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)2 Deployment (io.fabric8.kubernetes.api.model.extensions.Deployment)2 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2