Search in sources :

Example 51 with Resource

use of io.fabric8.support.api.Resource in project fabric8-maven-plugin by fabric8io.

the class ResourceMojo method generateResources.

private KubernetesList generateResources(List<ImageConfiguration> images) throws IOException, MojoExecutionException {
    // Manager for calling enrichers.
    openshiftDependencyResources = new OpenShiftDependencyResources(log);
    loadOpenShiftOverrideResources();
    EnricherContext.Builder ctxBuilder = new EnricherContext.Builder().project(project).session(session).goalFinder(goalFinder).config(extractEnricherConfig()).resources(resources).images(resolvedImages).log(log).useProjectClasspath(useProjectClasspath).openshiftDependencyResources(openshiftDependencyResources);
    if (resources != null) {
        ctxBuilder.namespace(resources.getNamespace());
    }
    EnricherManager enricherManager = new EnricherManager(resources, ctxBuilder.build());
    // Generate all resources from the main resource diretory, configuration and enrich them accordingly
    KubernetesListBuilder builder = generateAppResources(images, enricherManager);
    // Add resources found in subdirectories of resourceDir, with a certain profile
    // applied
    addProfiledResourcesFromSubirectories(builder, resourceDir, enricherManager);
    return builder.build();
}
Also used : EnricherContext(io.fabric8.maven.enricher.api.EnricherContext) EnricherManager(io.fabric8.maven.plugin.enricher.EnricherManager)

Example 52 with Resource

use of io.fabric8.support.api.Resource in project fabric8-maven-plugin by fabric8io.

the class DebugMojo method applyEntities.

@Override
protected void applyEntities(Controller controller, KubernetesClient kubernetes, String namespace, String fileName, Set<HasMetadata> entities) throws Exception {
    LabelSelector firstSelector = null;
    for (HasMetadata entity : entities) {
        String name = getName(entity);
        LabelSelector selector = null;
        if (entity instanceof Deployment) {
            Deployment resource = (Deployment) entity;
            DeploymentSpec spec = resource.getSpec();
            if (spec != null) {
                if (enableDebugging(entity, spec.getTemplate())) {
                    kubernetes.extensions().deployments().inNamespace(namespace).withName(name).replace(resource);
                }
                selector = getPodLabelSelector(entity);
            }
        } else if (entity instanceof ReplicaSet) {
            ReplicaSet resource = (ReplicaSet) entity;
            ReplicaSetSpec spec = resource.getSpec();
            if (spec != null) {
                if (enableDebugging(entity, spec.getTemplate())) {
                    kubernetes.extensions().replicaSets().inNamespace(namespace).withName(name).replace(resource);
                }
                selector = getPodLabelSelector(entity);
            }
        } else if (entity instanceof ReplicationController) {
            ReplicationController resource = (ReplicationController) entity;
            ReplicationControllerSpec spec = resource.getSpec();
            if (spec != null) {
                if (enableDebugging(entity, spec.getTemplate())) {
                    kubernetes.replicationControllers().inNamespace(namespace).withName(name).replace(resource);
                }
                selector = getPodLabelSelector(entity);
            }
        } else if (entity instanceof DeploymentConfig) {
            DeploymentConfig resource = (DeploymentConfig) entity;
            DeploymentConfigSpec spec = resource.getSpec();
            if (spec != null) {
                if (enableDebugging(entity, spec.getTemplate())) {
                    OpenShiftClient openshiftClient = new Controller(kubernetes).getOpenShiftClientOrNull();
                    if (openshiftClient == null) {
                        log.warn("Ignoring DeploymentConfig %s as not connected to an OpenShift cluster", name);
                        continue;
                    }
                    openshiftClient.deploymentConfigs().inNamespace(namespace).withName(name).replace(resource);
                }
                selector = getPodLabelSelector(entity);
            }
        }
        if (selector != null) {
            firstSelector = selector;
        } else {
            controller.apply(entity, fileName);
        }
    }
    if (firstSelector != null) {
        Map<String, String> envVars = new TreeMap<>();
        envVars.put(DebugConstants.ENV_VAR_JAVA_DEBUG, "true");
        envVars.put(DebugConstants.ENV_VAR_JAVA_DEBUG_SUSPEND, String.valueOf(this.debugSuspend));
        if (this.debugSuspendValue != null) {
            envVars.put(DebugConstants.ENV_VAR_JAVA_DEBUG_SESSION, this.debugSuspendValue);
        }
        String podName = waitForRunningPodWithEnvVar(kubernetes, namespace, firstSelector, envVars);
        portForward(controller, podName);
    }
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) ReplicaSetSpec(io.fabric8.kubernetes.api.model.extensions.ReplicaSetSpec) LabelSelector(io.fabric8.kubernetes.api.model.LabelSelector) KubernetesResourceUtil.getPodLabelSelector(io.fabric8.maven.core.util.KubernetesResourceUtil.getPodLabelSelector) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) Controller(io.fabric8.kubernetes.api.Controller) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController) TreeMap(java.util.TreeMap) DeploymentSpec(io.fabric8.kubernetes.api.model.extensions.DeploymentSpec) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) DeploymentConfigSpec(io.fabric8.openshift.api.model.DeploymentConfigSpec) ReplicaSet(io.fabric8.kubernetes.api.model.extensions.ReplicaSet) ReplicationControllerSpec(io.fabric8.kubernetes.api.model.ReplicationControllerSpec)

Example 53 with Resource

use of io.fabric8.support.api.Resource in project fabric8-maven-plugin by fabric8io.

the class AppCatalogMojo method loadYamlResourcesOnClassPath.

protected Map<URL, KubernetesResource> loadYamlResourcesOnClassPath(String resourcePath) throws MojoExecutionException {
    List<URL> resourceList = findResourcesOnClassPath(resourcePath);
    Map<URL, KubernetesResource> resourceMap = new HashMap<>();
    for (URL url : resourceList) {
        try (InputStream is = url.openStream()) {
            if (is != null) {
                KubernetesResource<?> resource;
                try {
                    resource = KubernetesHelper.loadYaml(is, KubernetesResource.class);
                    resourceMap.put(url, resource);
                } catch (IOException e) {
                    log.warn("Ignoring resource %s as it could not be parsed: %s", url, e);
                    continue;
                }
            }
        } catch (IOException e) {
            log.warn("Ignoring resource %s as it could not be opened: %s", url, e);
            continue;
        }
    }
    return resourceMap;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) InputStream(java.io.InputStream) KubernetesResource(io.fabric8.kubernetes.api.model.KubernetesResource) IOException(java.io.IOException) URL(java.net.URL)

Example 54 with Resource

use of io.fabric8.support.api.Resource in project fabric8-maven-plugin by fabric8io.

the class HelmMojo method findIconURL.

private String findIconURL() throws MojoExecutionException {
    String answer = null;
    if (kubernetesManifest != null && kubernetesManifest.isFile()) {
        Object dto = null;
        try {
            dto = KubernetesHelper.loadYaml(kubernetesManifest, KubernetesResource.class);
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to load kubernetes YAML " + kubernetesManifest + ". " + e, e);
        }
        if (dto instanceof HasMetadata) {
            answer = KubernetesHelper.getOrCreateAnnotations((HasMetadata) dto).get(Annotations.Builds.ICON_URL);
        }
        if (Strings.isNullOrBlank(answer) && dto instanceof KubernetesList) {
            KubernetesList list = (KubernetesList) dto;
            List<HasMetadata> items = list.getItems();
            if (items != null) {
                for (HasMetadata item : items) {
                    answer = KubernetesHelper.getOrCreateAnnotations(item).get(Annotations.Builds.ICON_URL);
                    if (Strings.isNotBlank(answer)) {
                        break;
                    }
                }
            }
        }
    } else {
        getLog().warn("No kubernetes manifest file has been generated yet by the fabric8:resource goal at: " + kubernetesManifest);
    }
    return answer;
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) KubernetesResource(io.fabric8.kubernetes.api.model.KubernetesResource) IOException(java.io.IOException) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList)

Example 55 with Resource

use of io.fabric8.support.api.Resource 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)

Aggregations

HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)25 Resource (io.fabric8.kubernetes.client.dsl.Resource)25 Map (java.util.Map)20 Test (org.junit.Test)20 IOException (java.io.IOException)19 HashMap (java.util.HashMap)16 Deployment (io.fabric8.kubernetes.api.model.extensions.Deployment)14 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)14 MixedOperation (io.fabric8.kubernetes.client.dsl.MixedOperation)14 Resource (org.osgi.resource.Resource)14 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)13 NonNamespaceOperation (io.fabric8.kubernetes.client.dsl.NonNamespaceOperation)13 ArrayList (java.util.ArrayList)13 Async (io.vertx.ext.unit.Async)12 File (java.io.File)10 ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)9 Service (io.fabric8.kubernetes.api.model.Service)9 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)9 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)8 Bundle (org.osgi.framework.Bundle)7