Search in sources :

Example 6 with LabelSelector

use of io.fabric8.kubernetes.api.model.LabelSelector 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 7 with LabelSelector

use of io.fabric8.kubernetes.api.model.LabelSelector 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 8 with LabelSelector

use of io.fabric8.kubernetes.api.model.LabelSelector in project fabric8-maven-plugin by fabric8io.

the class SpringBootWatcher method getPortForwardUrl.

private String getPortForwardUrl(final Set<HasMetadata> resources) throws Exception {
    LabelSelector selector = KubernetesResourceUtil.getPodLabelSelector(resources);
    if (selector == null) {
        log.warn("Unable to determine a selector for application pods");
        return null;
    }
    Properties properties = SpringBootUtil.getSpringBootApplicationProperties(getContext().getProject());
    SpringBootConfigurationHelper propertyHelper = new SpringBootConfigurationHelper(SpringBootUtil.getSpringBootVersion(getContext().getProject()));
    PortForwardService portForwardService = getContext().getFabric8ServiceHub().getPortForwardService();
    int port = IoUtil.getFreeRandomPort();
    int containerPort = findSpringBootWebPort(propertyHelper, properties);
    portForwardService.forwardPortAsync(getContext().getLogger(), selector, containerPort, port);
    return createForwardUrl(propertyHelper, properties, port);
}
Also used : SpringBootConfigurationHelper(io.fabric8.maven.core.util.SpringBootConfigurationHelper) LabelSelector(io.fabric8.kubernetes.api.model.LabelSelector) Properties(java.util.Properties) PortForwardService(io.fabric8.maven.core.service.PortForwardService)

Example 9 with LabelSelector

use of io.fabric8.kubernetes.api.model.LabelSelector in project strimzi by strimzi.

the class Storage method fromJson.

/**
 * Returns a Storage instance from a corresponding JSON representation
 *
 * @param json  storage JSON representation
 * @return  Storage instance
 */
public static Storage fromJson(JsonObject json) {
    String type = json.getString(Storage.TYPE_FIELD);
    if (type == null) {
        throw new IllegalArgumentException("Storage '" + Storage.TYPE_FIELD + "' is mandatory");
    }
    Storage storage = new Storage(StorageType.from(type));
    String size = json.getString(Storage.SIZE_FIELD);
    if (size != null) {
        storage.withSize(new Quantity(size));
    }
    String storageClass = json.getString(Storage.STORAGE_CLASS_FIELD);
    if (storageClass != null) {
        storage.withClass(storageClass);
    }
    if (json.getValue(Storage.DELETE_CLAIM_FIELD) instanceof Boolean) {
        boolean isDeleteClaim = json.getBoolean(Storage.DELETE_CLAIM_FIELD);
        storage.withDeleteClaim(isDeleteClaim);
    }
    JsonObject selector = json.getJsonObject(Storage.SELECTOR_FIELD);
    if (selector != null) {
        JsonObject matchLabelsJson = selector.getJsonObject(Storage.SELECTOR_MATCH_LABELS_FIELD);
        Map<String, String> matchLabels = matchLabelsJson.getMap().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue())));
        // match-expressions doesn't supported yet, so null first argument
        storage.withSelector(new LabelSelector(null, matchLabels));
    }
    return storage;
}
Also used : Quantity(io.fabric8.kubernetes.api.model.Quantity) LabelSelector(io.fabric8.kubernetes.api.model.LabelSelector) Map(java.util.Map) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim) JsonObject(io.vertx.core.json.JsonObject) Collectors(java.util.stream.Collectors) Quantity(io.fabric8.kubernetes.api.model.Quantity) JsonObject(io.vertx.core.json.JsonObject) LabelSelector(io.fabric8.kubernetes.api.model.LabelSelector) Map(java.util.Map)

Example 10 with LabelSelector

use of io.fabric8.kubernetes.api.model.LabelSelector in project fabric8 by fabric8io.

the class ServicePodsAssert method pods.

@Override
public PodSelectionAssert pods() {
    spec().isNotNull().selector().isNotNull();
    ServiceSpec spec = this.actual.getSpec();
    int replicas = 1;
    LabelSelector selector = null;
    Map<String, String> matchLabels = spec.getSelector();
    List<LabelSelectorRequirement> matchExpressions = selector.getMatchExpressions();
    return new PodSelectionAssert(client, replicas, matchLabels, matchExpressions, "Service " + KubernetesHelper.getName(actual));
}
Also used : ServiceSpec(io.fabric8.kubernetes.api.model.ServiceSpec) LabelSelector(io.fabric8.kubernetes.api.model.LabelSelector) LabelSelectorRequirement(io.fabric8.kubernetes.api.model.LabelSelectorRequirement)

Aggregations

LabelSelector (io.fabric8.kubernetes.api.model.LabelSelector)10 Pod (io.fabric8.kubernetes.api.model.Pod)7 PodList (io.fabric8.kubernetes.api.model.PodList)6 Watch (io.fabric8.kubernetes.client.Watch)5 LabelSelectorRequirement (io.fabric8.kubernetes.api.model.LabelSelectorRequirement)4 ReplicaSetSpec (io.fabric8.kubernetes.api.model.extensions.ReplicaSetSpec)4 Watcher (io.fabric8.kubernetes.client.Watcher)4 Test (org.junit.Test)4 DeploymentSpec (io.fabric8.kubernetes.api.model.extensions.DeploymentSpec)3 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)3 KubernetesMockServer (io.fabric8.kubernetes.client.server.mock.KubernetesMockServer)3 Container (io.fabric8.kubernetes.api.model.Container)2 DoneablePod (io.fabric8.kubernetes.api.model.DoneablePod)2 PodBuilder (io.fabric8.kubernetes.api.model.PodBuilder)2 PodListBuilder (io.fabric8.kubernetes.api.model.PodListBuilder)2 PodSpec (io.fabric8.kubernetes.api.model.PodSpec)2 ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)2 ReplicationControllerSpec (io.fabric8.kubernetes.api.model.ReplicationControllerSpec)2 ServiceSpec (io.fabric8.kubernetes.api.model.ServiceSpec)2 WatchEvent (io.fabric8.kubernetes.api.model.WatchEvent)2