Search in sources :

Example 66 with KubernetesClient

use of io.fabric8.kubernetes.client.KubernetesClient in project strimzi by strimzi.

the class KafkaClusterTest method testZookeeperScaleUpScaleDown.

@Test
@KafkaCluster(name = "my-cluster", kafkaNodes = 1, zkNodes = 1)
public void testZookeeperScaleUpScaleDown() {
    // kafka cluster already deployed via annotation
    String clusterName = "my-cluster";
    LOGGER.info("Running zookeeperScaleUpScaleDown with cluster {}", clusterName);
    // kubeClient.waitForStatefulSet(zookeeperStatefulSetName(clusterName), 1);
    KubernetesClient client = new DefaultKubernetesClient();
    final int initialReplicas = client.apps().statefulSets().inNamespace(NAMESPACE).withName(zookeeperStatefulSetName(clusterName)).get().getStatus().getReplicas();
    assertEquals(1, initialReplicas);
    // scale up
    final int scaleTo = initialReplicas + 2;
    final int[] newPodIds = { initialReplicas, initialReplicas + 1 };
    final String[] newPodName = { zookeeperPodName(clusterName, newPodIds[0]), zookeeperPodName(clusterName, newPodIds[1]) };
    final String firstPodName = zookeeperPodName(clusterName, 0);
    LOGGER.info("Scaling zookeeper up to {}", scaleTo);
    replaceCm(clusterName, "zookeeper-nodes", String.valueOf(scaleTo));
    kubeClient.waitForPod(newPodName[0]);
    kubeClient.waitForPod(newPodName[1]);
    // check the new node is either in leader or follower state
    waitForZkMntr(firstPodName, Pattern.compile("zk_server_state\\s+(leader|follower)"));
    waitForZkMntr(newPodName[0], Pattern.compile("zk_server_state\\s+(leader|follower)"));
    waitForZkMntr(newPodName[1], Pattern.compile("zk_server_state\\s+(leader|follower)"));
    // TODO Check for k8s events, logs for errors
    // scale down
    LOGGER.info("Scaling down");
    replaceCm(clusterName, "zookeeper-nodes", String.valueOf(1));
    kubeClient.waitForResourceDeletion("po", zookeeperPodName(clusterName, 1));
    // Wait for the one remaining node to enter standalone mode
    waitForZkMntr(firstPodName, Pattern.compile("zk_server_state\\s+standalone"));
// TODO Check for k8s events, logs for errors
}
Also used : DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KafkaCluster(io.strimzi.test.KafkaCluster) Test(org.junit.Test)

Example 67 with KubernetesClient

use of io.fabric8.kubernetes.client.KubernetesClient in project fabric8-maven-plugin by fabric8io.

the class ApplyMojo method applyEntities.

protected void applyEntities(Controller controller, KubernetesClient kubernetes, String namespace, String fileName, Set<HasMetadata> entities) throws Exception {
    // Apply all items
    for (HasMetadata entity : entities) {
        if (entity instanceof Pod) {
            Pod pod = (Pod) entity;
            controller.applyPod(pod, fileName);
        } else if (entity instanceof Service) {
            Service service = (Service) entity;
            controller.applyService(service, fileName);
        } else if (entity instanceof ReplicationController) {
            ReplicationController replicationController = (ReplicationController) entity;
            controller.applyReplicationController(replicationController, fileName);
        } else if (entity != null) {
            controller.apply(entity, fileName);
        }
    }
    String command = clusterAccess.isOpenShiftImageStream(log) ? "oc" : "kubectl";
    log.info("[[B]]HINT:[[B]] Use the command `%s get pods -w` to watch your pods start up", command);
    Logger serviceLogger = createExternalProcessLogger("[[G]][SVC][[G]] ");
    long serviceUrlWaitTimeSeconds = this.serviceUrlWaitTimeSeconds;
    for (HasMetadata entity : entities) {
        if (entity instanceof Service) {
            Service service = (Service) entity;
            String name = getName(service);
            Resource<Service, DoneableService> serviceResource = kubernetes.services().inNamespace(namespace).withName(name);
            String url = null;
            // lets wait a little while until there is a service URL in case the exposecontroller is running slow
            for (int i = 0; i < serviceUrlWaitTimeSeconds; i++) {
                if (i > 0) {
                    Thread.sleep(1000);
                }
                Service s = serviceResource.get();
                if (s != null) {
                    url = getExternalServiceURL(s);
                    if (Strings.isNotBlank(url)) {
                        break;
                    }
                }
                if (!isExposeService(service)) {
                    break;
                }
            }
            // lets not wait for other services
            serviceUrlWaitTimeSeconds = 1;
            if (Strings.isNotBlank(url) && url.startsWith("http")) {
                serviceLogger.info("" + name + ": " + url);
            }
        }
    }
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Pod(io.fabric8.kubernetes.api.model.Pod) DoneableService(io.fabric8.kubernetes.api.model.DoneableService) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController) DoneableService(io.fabric8.kubernetes.api.model.DoneableService) Service(io.fabric8.kubernetes.api.model.Service) KubernetesHelper.createIntOrString(io.fabric8.kubernetes.api.KubernetesHelper.createIntOrString) Logger(io.fabric8.maven.docker.util.Logger)

Example 68 with KubernetesClient

use of io.fabric8.kubernetes.client.KubernetesClient in project fabric8-maven-plugin by fabric8io.

the class ApplyMojo method createIngress.

protected void createIngress(Controller controller, KubernetesClient kubernetesClient, Collection<HasMetadata> collection) {
    String routeDomainPostfix = this.routeDomain;
    Log log = getLog();
    String namespace = clusterAccess.getNamespace();
    List<Ingress> ingressList = null;
    // lets get the routes first to see if we should bother
    try {
        IngressList ingresses = kubernetesClient.extensions().ingresses().inNamespace(namespace).list();
        if (ingresses != null) {
            ingressList = ingresses.getItems();
        }
    } catch (Exception e) {
        log.warn("Cannot load Ingress instances. Must be an older version of Kubernetes? Error: " + e, e);
        return;
    }
    List<Ingress> ingresses = new ArrayList<>();
    for (Object object : collection) {
        if (object instanceof Service) {
            Service service = (Service) object;
            if (!serviceHasIngressRule(ingressList, service)) {
                Ingress ingress = createIngressForService(routeDomainPostfix, namespace, service);
                if (ingress != null) {
                    ingresses.add(ingress);
                    log.info("Created ingress for " + namespace + ":" + KubernetesHelper.getName(service));
                } else {
                    log.debug("No ingress required for " + namespace + ":" + KubernetesHelper.getName(service));
                }
            } else {
                log.info("Already has ingress for service " + namespace + ":" + KubernetesHelper.getName(service));
            }
        }
    }
    collection.addAll(ingresses);
}
Also used : Log(org.apache.maven.plugin.logging.Log) ArrayList(java.util.ArrayList) Ingress(io.fabric8.kubernetes.api.model.extensions.Ingress) DoneableService(io.fabric8.kubernetes.api.model.DoneableService) Service(io.fabric8.kubernetes.api.model.Service) KubernetesHelper.createIntOrString(io.fabric8.kubernetes.api.KubernetesHelper.createIntOrString) IngressList(io.fabric8.kubernetes.api.model.extensions.IngressList) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException)

Example 69 with KubernetesClient

use of io.fabric8.kubernetes.client.KubernetesClient in project fabric8-maven-plugin by fabric8io.

the class DebugMojo method waitForRunningPodWithEnvVar.

private String waitForRunningPodWithEnvVar(final KubernetesClient kubernetes, final String namespace, LabelSelector selector, final Map<String, String> envVars) throws MojoExecutionException {
    // wait for the newest pod to be ready with the given env var
    FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> pods = withSelector(kubernetes.pods().inNamespace(namespace), selector, log);
    log.info("Waiting for debug pod with selector " + selector + " and environment variables " + envVars);
    podWaitLog = createExternalProcessLogger("[[Y]][W][[Y]] ");
    PodList list = pods.list();
    if (list != null) {
        Pod latestPod = KubernetesResourceUtil.getNewestPod(list.getItems());
        if (latestPod != null && podHasEnvVars(latestPod, envVars)) {
            return getName(latestPod);
        }
    }
    podWatcher = pods.watch(new Watcher<Pod>() {

        @Override
        public void eventReceived(Watcher.Action action, Pod pod) {
            podWaitLog.info(getName(pod) + " status: " + getPodStatusDescription(pod) + getPodStatusMessagePostfix(action));
            if (isAddOrModified(action) && isPodRunning(pod) && isPodReady(pod) && podHasEnvVars(pod, envVars)) {
                foundPod = pod;
                terminateLatch.countDown();
            }
        }

        @Override
        public void onClose(KubernetesClientException e) {
        // ignore
        }
    });
    // now lets wait forever?
    while (terminateLatch.getCount() > 0) {
        try {
            terminateLatch.await();
        } catch (InterruptedException e) {
        // ignore
        }
        if (foundPod != null) {
            return getName(foundPod);
        }
    }
    throw new MojoExecutionException("Could not find a running pod with environment variables " + envVars);
}
Also used : PodList(io.fabric8.kubernetes.api.model.PodList) Pod(io.fabric8.kubernetes.api.model.Pod) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) Watch(io.fabric8.kubernetes.client.Watch) Watcher(io.fabric8.kubernetes.client.Watcher) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 70 with KubernetesClient

use of io.fabric8.kubernetes.client.KubernetesClient in project fabric8-maven-plugin by fabric8io.

the class AbstractFabric8Mojo method getOpenShiftClientOrJenkinsShift.

protected OpenShiftClient getOpenShiftClientOrJenkinsShift(KubernetesClient kubernetes, String namespace) throws MojoExecutionException {
    OpenShiftClient openShiftClient = getOpenShiftClientOrNull(kubernetes);
    if (openShiftClient == null) {
        String jenkinshiftUrl = getJenkinShiftUrl(kubernetes, namespace);
        log.debug("Using jenkinshift URL: " + jenkinshiftUrl);
        if (jenkinshiftUrl == null) {
            throw new MojoExecutionException("Could not find the service `" + ServiceNames.JENKINSHIFT + "` im namespace `" + namespace + "` on this kubernetes cluster " + kubernetes.getMasterUrl());
        }
        return KubernetesHelper.createJenkinshiftOpenShiftClient(jenkinshiftUrl);
    }
    return openShiftClient;
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient)

Aggregations

KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)62 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)40 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)21 HashMap (java.util.HashMap)19 Pod (io.fabric8.kubernetes.api.model.Pod)17 Service (io.fabric8.kubernetes.api.model.Service)16 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)14 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)13 IOException (java.io.IOException)12 ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)10 File (java.io.File)10 ArrayList (java.util.ArrayList)9 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)8 BuildConfig (io.fabric8.openshift.api.model.BuildConfig)8 Test (org.junit.Test)8 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)7 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)7 Map (java.util.Map)7 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)7 Controller (io.fabric8.kubernetes.api.Controller)6