Search in sources :

Example 16 with ReplicaSet

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

the class EnricherManagerTest method enrichSimple.

@Test
public void enrichSimple() {
    new Expectations() {

        {
            context.getConfiguration();
            result = new Configuration.Builder().processorConfig(new ProcessorConfig(Arrays.asList("fmp-metadata", "fmp-project-label"), null, new HashMap<>())).build();
        }
    };
    EnricherManager manager = new EnricherManager(null, context, Optional.empty());
    KubernetesListBuilder builder = new KubernetesListBuilder();
    builder.addToItems(new ReplicaSetBuilder().withNewSpec().withNewTemplate().withNewSpec().addNewContainer().withName("test").withImage("busybox").endContainer().endSpec().endTemplate().endSpec().build());
    manager.enrich(PlatformMode.kubernetes, builder);
    KubernetesList list = builder.build();
    assertEquals(1, list.getItems().size());
    ReplicaSet pod = (ReplicaSet) list.getItems().get(0);
    ObjectMeta metadata = pod.getMetadata();
    assertNotNull(metadata);
    Map<String, String> labels = metadata.getLabels();
    assertNotNull(labels);
    assertEquals("fabric8", labels.get("provider"));
}
Also used : Expectations(mockit.Expectations) KubernetesListBuilder(io.fabric8.kubernetes.api.model.KubernetesListBuilder) ReplicaSetBuilder(io.fabric8.kubernetes.api.model.apps.ReplicaSetBuilder) ObjectMeta(io.fabric8.kubernetes.api.model.ObjectMeta) ImageConfiguration(io.fabric8.maven.docker.config.ImageConfiguration) Configuration(io.fabric8.maven.core.model.Configuration) HashMap(java.util.HashMap) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList) ProcessorConfig(io.fabric8.maven.core.config.ProcessorConfig) ReplicaSet(io.fabric8.kubernetes.api.model.apps.ReplicaSet) Test(org.junit.Test)

Example 17 with ReplicaSet

use of io.fabric8.kubernetes.api.model.apps.ReplicaSet 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 = OpenshiftHelper.asOpenShiftClient(kubernetes);
                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.apps.DeploymentSpec) ReplicaSetSpec(io.fabric8.kubernetes.api.model.apps.ReplicaSetSpec) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) DeploymentConfigSpec(io.fabric8.openshift.api.model.DeploymentConfigSpec) ReplicaSet(io.fabric8.kubernetes.api.model.apps.ReplicaSet) ReplicationControllerSpec(io.fabric8.kubernetes.api.model.ReplicationControllerSpec)

Example 18 with ReplicaSet

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

the class DefaultControllerEnricher method create.

@Override
public void create(PlatformMode platformMode, KubernetesListBuilder builder) {
    final String name = getConfig(Config.name, MavenUtil.createDefaultResourceName(getContext().getGav().getSanitizedArtifactId()));
    ResourceConfig xmlResourceConfig = getConfiguration().getResource().orElse(null);
    ResourceConfig config = new ResourceConfig.Builder(xmlResourceConfig).controllerName(name).imagePullPolicy(getImagePullPolicy(xmlResourceConfig, getConfig(Config.pullPolicy))).withReplicas(getReplicaCount(builder, xmlResourceConfig, Configs.asInt(getConfig(Config.replicaCount)))).build();
    final List<ImageConfiguration> images = getImages().orElse(Collections.emptyList());
    // Check if at least a replica set is added. If not add a default one
    if (!KubernetesResourceUtil.checkForKind(builder, POD_CONTROLLER_KINDS)) {
        // At least one image must be present, otherwise the resulting config will be invalid
        if (!images.isEmpty()) {
            String type = getConfig(Config.type);
            if ("deployment".equalsIgnoreCase(type) || "deploymentConfig".equalsIgnoreCase(type)) {
                if (platformMode == PlatformMode.kubernetes || (platformMode == PlatformMode.openshift && useDeploymentforOpenShift())) {
                    log.info("Adding a default Deployment");
                    Deployment deployment = deployHandler.getDeployment(config, images);
                    builder.addToItems(deployment);
                    setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(deployment.getSpec().getTemplate()));
                } else {
                    log.info("Adding a default DeploymentConfig");
                    DeploymentConfig deploymentConfig = deployConfigHandler.getDeploymentConfig(config, images, getOpenshiftDeployTimeoutInSeconds(3600L), getValueFromConfig(IMAGE_CHANGE_TRIGGERS, true), getValueFromConfig(OPENSHIFT_ENABLE_AUTOMATIC_TRIGGER, true), isOpenShiftMode(), getProcessingInstructionViaKey(FABRIC8_GENERATED_CONTAINERS));
                    builder.addToItems(deploymentConfig);
                    setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(deploymentConfig.getSpec().getTemplate()));
                }
            } else if ("statefulSet".equalsIgnoreCase(type)) {
                log.info("Adding a default StatefulSet");
                StatefulSet statefulSet = statefulSetHandler.getStatefulSet(config, images);
                builder.addToItems(statefulSet);
                setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(statefulSet.getSpec().getTemplate()));
            } else if ("daemonSet".equalsIgnoreCase(type)) {
                log.info("Adding a default DaemonSet");
                DaemonSet daemonSet = daemonSetHandler.getDaemonSet(config, images);
                builder.addToItems(daemonSet);
                setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(daemonSet.getSpec().getTemplate()));
            } else if ("replicaSet".equalsIgnoreCase(type)) {
                log.info("Adding a default ReplicaSet");
                ReplicaSet replicaSet = rsHandler.getReplicaSet(config, images);
                builder.addToItems(replicaSet);
                setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(replicaSet.getSpec().getTemplate()));
            } else if ("replicationController".equalsIgnoreCase(type)) {
                log.info("Adding a default ReplicationController");
                ReplicationController replicationController = rcHandler.getReplicationController(config, images);
                builder.addToReplicationControllerItems(replicationController);
                setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(replicationController.getSpec().getTemplate()));
            } else if ("job".equalsIgnoreCase(type)) {
                log.info("Adding a default Job");
                Job job = jobHandler.getJob(config, images);
                builder.addToItems(job);
                setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(job.getSpec().getTemplate()));
            }
        }
    }
}
Also used : ImageConfiguration(io.fabric8.maven.docker.config.ImageConfiguration) KubernetesListBuilder(io.fabric8.kubernetes.api.model.KubernetesListBuilder) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) DaemonSet(io.fabric8.kubernetes.api.model.apps.DaemonSet) ResourceConfig(io.fabric8.maven.core.config.ResourceConfig) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) StatefulSet(io.fabric8.kubernetes.api.model.apps.StatefulSet) Job(io.fabric8.kubernetes.api.model.batch.Job) ReplicaSet(io.fabric8.kubernetes.api.model.apps.ReplicaSet)

Example 19 with ReplicaSet

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

the class SessionListener method applyConfiguration.

private boolean applyConfiguration(KubernetesClient client, Controller controller, Configuration configuration, Session session, List<KubernetesList> kubeConfigs) throws Exception {
    Logger log = session.getLogger();
    Map<Integer, Callable<Boolean>> conditions = new TreeMap<>();
    Callable<Boolean> sessionPodsReady = new SessionPodsAreReady(client, session);
    Callable<Boolean> servicesReady = new SessionServicesAreReady(client, session, configuration);
    Set<HasMetadata> entities = new TreeSet<>(new HasMetadataComparator());
    for (KubernetesList c : kubeConfigs) {
        entities.addAll(enhance(session, configuration, c).getItems());
    }
    if (containsImageStreamResources(entities)) {
    // no need to use a local image registry
    // as we are using OpenShift and
    } else {
        String registry = getLocalDockerRegistry();
        if (Strings.isNotBlank(registry)) {
            log.status("Adapting resources to pull images from registry: " + registry);
            addRegistryToImageNameIfNotPresent(entities, registry);
        } else {
            log.status("No local fabric8 docker registry found");
        }
    }
    List<Object> items = new ArrayList<>();
    items.addAll(entities);
    // Ensure services are processed first.
    Collections.sort(items, new Comparator<Object>() {

        @Override
        public int compare(Object left, Object right) {
            if (left instanceof Service) {
                return -1;
            } else if (right instanceof Service) {
                return 1;
            } else {
                return 0;
            }
        }
    });
    boolean isOpenshift = client.isAdaptable(OpenShiftClient.class);
    String namespace = session.getNamespace();
    String routeDomain = null;
    if (Strings.isNotBlank(configuration.getKubernetesDomain())) {
        routeDomain = configuration.getKubernetesDomain();
    }
    preprocessEnvironment(client, controller, configuration, session);
    Set<HasMetadata> extraEntities = new TreeSet<>(new HasMetadataComparator());
    for (Object entity : items) {
        if (entity instanceof Pod) {
            Pod pod = (Pod) entity;
            log.status("Applying pod:" + getName(pod));
            Set<Secret> secrets = generateSecrets(client, session, pod.getMetadata());
            String serviceAccountName = pod.getSpec().getServiceAccountName();
            if (Strings.isNotBlank(serviceAccountName)) {
                generateServiceAccount(client, session, secrets, serviceAccountName);
            }
            controller.applyPod(pod, session.getId());
            conditions.put(1, sessionPodsReady);
        } else if (entity instanceof Service) {
            Service service = (Service) entity;
            String serviceName = getName(service);
            log.status("Applying service:" + serviceName);
            controller.applyService(service, session.getId());
            conditions.put(2, servicesReady);
            if (isOpenshift) {
                Route route = Routes.createRouteForService(routeDomain, namespace, service, log);
                if (route != null) {
                    log.status("Applying route for:" + serviceName);
                    controller.applyRoute(route, "route for " + serviceName);
                    extraEntities.add(route);
                }
            }
        } else if (entity instanceof ReplicationController) {
            ReplicationController replicationController = (ReplicationController) entity;
            log.status("Applying replication controller:" + getName(replicationController));
            Set<Secret> secrets = generateSecrets(client, session, replicationController.getSpec().getTemplate().getMetadata());
            String serviceAccountName = replicationController.getSpec().getTemplate().getSpec().getServiceAccountName();
            if (Strings.isNotBlank(serviceAccountName)) {
                generateServiceAccount(client, session, secrets, serviceAccountName);
            }
            controller.applyReplicationController(replicationController, session.getId());
            conditions.put(1, sessionPodsReady);
        } else if (entity instanceof ReplicaSet || entity instanceof Deployment || entity instanceof DeploymentConfig) {
            log.status("Applying " + entity.getClass().getSimpleName() + ".");
            controller.apply(entity, session.getId());
            conditions.put(1, sessionPodsReady);
        } else if (entity instanceof OAuthClient) {
            OAuthClient oc = (OAuthClient) entity;
            // these are global so lets create a custom one for the new namespace
            ObjectMeta metadata = KubernetesHelper.getOrCreateMetadata(oc);
            String name = metadata.getName();
            if (isOpenshift) {
                OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class);
                OAuthClient current = openShiftClient.oAuthClients().withName(name).get();
                boolean create = false;
                if (current == null) {
                    current = oc;
                    create = true;
                }
                boolean updated = false;
                // lets add a new redirect entry
                List<String> redirectURIs = current.getRedirectURIs();
                String namespaceSuffix = "-" + namespace;
                String redirectUri = "http://" + name + namespaceSuffix;
                if (Strings.isNotBlank(routeDomain)) {
                    redirectUri += "." + Strings.stripPrefix(routeDomain, ".");
                }
                if (!redirectURIs.contains(redirectUri)) {
                    redirectURIs.add(redirectUri);
                    updated = true;
                }
                current.setRedirectURIs(redirectURIs);
                log.status("Applying OAuthClient:" + name);
                controller.setSupportOAuthClients(true);
                if (create) {
                    openShiftClient.oAuthClients().create(current);
                } else {
                    if (updated) {
                        // TODO this should work!
                        // openShiftClient.oAuthClients().withName(name).replace(current);
                        openShiftClient.oAuthClients().withName(name).delete();
                        current.getMetadata().setResourceVersion(null);
                        openShiftClient.oAuthClients().create(current);
                    }
                }
            }
        } else if (entity instanceof HasMetadata) {
            log.status("Applying " + entity.getClass().getSimpleName() + ":" + KubernetesHelper.getName((HasMetadata) entity));
            controller.apply(entity, session.getId());
        } else if (entity != null) {
            log.status("Applying " + entity.getClass().getSimpleName() + ".");
            controller.apply(entity, session.getId());
        }
    }
    entities.addAll(extraEntities);
    // Wait until conditions are meet.
    if (!conditions.isEmpty()) {
        Callable<Boolean> compositeCondition = new CompositeCondition(conditions.values());
        WaitStrategy waitStrategy = new WaitStrategy(compositeCondition, configuration.getWaitTimeout(), configuration.getWaitPollInterval());
        if (!waitStrategy.await()) {
            log.error("Timed out waiting for pods/services!");
            return false;
        } else {
            log.status("All pods/services are currently 'running'!");
        }
    } else {
        log.warn("No pods/services/replication controllers defined in the configuration!");
    }
    return true;
}
Also used : SessionPodsAreReady(io.fabric8.arquillian.kubernetes.await.SessionPodsAreReady) OAuthClient(io.fabric8.openshift.api.model.OAuthClient) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) Util.readAsString(io.fabric8.arquillian.utils.Util.readAsString) Logger(io.fabric8.arquillian.kubernetes.log.Logger) Callable(java.util.concurrent.Callable) HasMetadataComparator(io.fabric8.kubernetes.internal.HasMetadataComparator) ReplicaSet(io.fabric8.kubernetes.api.model.extensions.ReplicaSet) Route(io.fabric8.openshift.api.model.Route) SessionServicesAreReady(io.fabric8.arquillian.kubernetes.await.SessionServicesAreReady) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) WaitStrategy(io.fabric8.arquillian.kubernetes.await.WaitStrategy) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) CompositeCondition(io.fabric8.arquillian.kubernetes.await.CompositeCondition)

Example 20 with ReplicaSet

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

the class ReplicaSetPodsAssert method pods.

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

Aggregations

ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)17 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)14 ReplicaSet (io.fabric8.kubernetes.api.model.extensions.ReplicaSet)12 ReplicaSet (io.fabric8.kubernetes.api.model.apps.ReplicaSet)10 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)10 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)8 Deployment (io.fabric8.kubernetes.api.model.extensions.Deployment)8 LabelSelector (io.fabric8.kubernetes.api.model.LabelSelector)7 Deployment (io.fabric8.kubernetes.api.model.apps.Deployment)7 ReplicationControllerSpec (io.fabric8.kubernetes.api.model.ReplicationControllerSpec)6 DeploymentConfigSpec (io.fabric8.openshift.api.model.DeploymentConfigSpec)6 KubernetesListBuilder (io.fabric8.kubernetes.api.model.KubernetesListBuilder)5 ReplicaSetSpec (io.fabric8.kubernetes.api.model.extensions.ReplicaSetSpec)5 IOException (java.io.IOException)5 Controller (io.fabric8.kubernetes.api.Controller)4 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)4 PersistentVolumeClaim (io.fabric8.kubernetes.api.model.PersistentVolumeClaim)4 Pod (io.fabric8.kubernetes.api.model.Pod)4 Secret (io.fabric8.kubernetes.api.model.Secret)4 Service (io.fabric8.kubernetes.api.model.Service)4