Search in sources :

Example 71 with KubernetesClient

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

the class PodLogService method tailAppPodsLogs.

public void tailAppPodsLogs(final KubernetesClient kubernetes, final String namespace, final Set<HasMetadata> entities, boolean watchAddedPodsOnly, String onExitOperation, boolean followLog, Date ignorePodsOlderThan, boolean waitInCurrentThread) {
    LabelSelector selector = KubernetesResourceUtil.getPodLabelSelector(entities);
    if (selector != null) {
        String ctrlCMessage = "stop tailing the log";
        if (Strings.isNotBlank(onExitOperation)) {
            final String onExitOperationLower = onExitOperation.toLowerCase().trim();
            if (onExitOperationLower.equals(OPERATION_UNDEPLOY)) {
                ctrlCMessage = "undeploy the app";
            } else if (onExitOperationLower.equals(OPERATION_STOP)) {
                ctrlCMessage = "scale down the app and stop tailing the log";
            } else {
                log.warn("Unknown on-exit command: `%s`", onExitOperationLower);
            }
            resizeApp(kubernetes, namespace, entities, 1, log);
            Runtime.getRuntime().addShutdownHook(new Thread("pod log service shutdown hook") {

                @Override
                public void run() {
                    if (onExitOperationLower.equals(OPERATION_UNDEPLOY)) {
                        log.info("Undeploying the app:");
                        deleteEntities(kubernetes, namespace, entities, context.getS2iBuildNameSuffix(), log);
                    } else if (onExitOperationLower.equals(OPERATION_STOP)) {
                        log.info("Stopping the app:");
                        resizeApp(kubernetes, namespace, entities, 0, log);
                    }
                    if (podWatcher != null) {
                        podWatcher.close();
                    }
                    closeLogWatcher();
                }
            });
        }
        waitAndLogPods(kubernetes, namespace, selector, watchAddedPodsOnly, ctrlCMessage, followLog, ignorePodsOlderThan, waitInCurrentThread);
    } else {
        log.warn("No selector in deployment so cannot watch pods!");
    }
}
Also used : LabelSelector(io.fabric8.kubernetes.api.model.LabelSelector)

Example 72 with KubernetesClient

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

the class PodLogService method watchLogOfPodName.

private void watchLogOfPodName(KubernetesClient kubernetes, String namespace, String ctrlCMessage, boolean followLog, Pod pod, String name) {
    if (watchingPodName == null || !watchingPodName.equals(name)) {
        if (logWatcher != null) {
            log.info("Closing log watcher for %s as now watching %s", watchingPodName, name);
            closeLogWatcher();
        }
        PodResource<Pod, DoneablePod> podResource = kubernetes.pods().inNamespace(namespace).withName(name);
        List<Container> containers = KubernetesHelper.getContainers(pod);
        String containerName = null;
        if (followLog) {
            watchingPodName = name;
            logWatchTerminateLatch = new CountDownLatch(1);
            if (containers.size() < 2) {
                logWatcher = podResource.watchLog();
            } else {
                containerName = getLogContainerName(containers);
                logWatcher = podResource.inContainer(containerName).watchLog();
            }
            watchLog(logWatcher, name, "Failed to read log of pod " + name + ".", ctrlCMessage, containerName);
        } else {
            String logText;
            if (containers.size() < 2) {
                logText = podResource.getLog();
            } else {
                containerName = getLogContainerName(containers);
                logText = podResource.inContainer(containerName).getLog();
            }
            if (logText != null) {
                String[] lines = logText.split("\n");
                log.info("Log of pod: %s%s", name, containerNameMessage(containerName));
                log.info("");
                for (String line : lines) {
                    log.info("[[s]]%s", line);
                }
            }
            terminateLatch.countDown();
        }
    }
}
Also used : Container(io.fabric8.kubernetes.api.model.Container) DoneablePod(io.fabric8.kubernetes.api.model.DoneablePod) Pod(io.fabric8.kubernetes.api.model.Pod) DoneablePod(io.fabric8.kubernetes.api.model.DoneablePod) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 73 with KubernetesClient

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

the class PodLogService method waitAndLogPods.

private void waitAndLogPods(final KubernetesClient kubernetes, final String namespace, LabelSelector selector, final boolean watchAddedPodsOnly, final String ctrlCMessage, final boolean followLog, Date ignorePodsOlderThan, boolean waitInCurrentThread) {
    FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> pods = withSelector(kubernetes.pods().inNamespace(namespace), selector, log);
    if (context.getPodName() != null) {
        log.info("Watching pod with selector %s, and name %s waiting for a running pod...", selector, context.getPodName());
        pods = pods.withField("metadata.name", context.getPodName());
    } else {
        log.info("Watching pods with selector %s waiting for a running pod...", selector);
    }
    Pod latestPod = null;
    boolean runningPod = false;
    PodList list = pods.list();
    if (list != null) {
        List<Pod> items = list.getItems();
        if (items != null) {
            for (Pod pod : items) {
                PodStatusType status = getPodStatus(pod);
                switch(status) {
                    case WAIT:
                    case OK:
                        if (latestPod == null || KubernetesResourceUtil.isNewerResource(pod, latestPod)) {
                            if (ignorePodsOlderThan != null) {
                                Date podCreateTime = KubernetesResourceUtil.getCreationTimestamp(pod);
                                if (podCreateTime != null && podCreateTime.compareTo(ignorePodsOlderThan) > 0) {
                                    latestPod = pod;
                                }
                            } else {
                                latestPod = pod;
                            }
                        }
                        runningPod = true;
                        break;
                    case ERROR:
                    default:
                        continue;
                }
            }
        }
    }
    // we may have missed the ADDED event so lets simulate one
    if (latestPod != null) {
        onPod(Watcher.Action.ADDED, latestPod, kubernetes, namespace, ctrlCMessage, followLog);
    }
    if (!watchAddedPodsOnly) {
        // lets watch the current pods then watch for changes
        if (!runningPod) {
            log.warn("No pod is running yet. Are you sure you deployed your app via `fabric8:deploy`?");
            log.warn("Or did you stop it via `fabric8:stop`? If so try running the `fabric8:start` goal");
        }
    }
    podWatcher = pods.watch(new Watcher<Pod>() {

        @Override
        public void eventReceived(Action action, Pod pod) {
            onPod(action, pod, kubernetes, namespace, ctrlCMessage, followLog);
        }

        @Override
        public void onClose(KubernetesClientException e) {
        // ignore
        }
    });
    if (waitInCurrentThread) {
        while (terminateLatch.getCount() > 0) {
            try {
                terminateLatch.await();
            } catch (InterruptedException e) {
            // ignore
            }
        }
    }
}
Also used : PodList(io.fabric8.kubernetes.api.model.PodList) DoneablePod(io.fabric8.kubernetes.api.model.DoneablePod) Pod(io.fabric8.kubernetes.api.model.Pod) Watcher(io.fabric8.kubernetes.client.Watcher) Date(java.util.Date) Watch(io.fabric8.kubernetes.client.Watch) LogWatch(io.fabric8.kubernetes.client.dsl.LogWatch) PodStatusType(io.fabric8.kubernetes.api.PodStatusType) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 74 with KubernetesClient

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

the class ClusterAccessTest method createClientTestKubernetes.

@Test
public void createClientTestKubernetes() throws Exception {
    RootPaths rootpaths = new RootPaths();
    rootpaths.setPaths(paths);
    mockServer.expect().get().withPath("/").andReturn(200, rootpaths).always();
    ClusterAccess clusterAccess = new ClusterAccess(null, client);
    Client outputClient = clusterAccess.createDefaultClient(logger);
    assertTrue(outputClient instanceof KubernetesClient);
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) RootPaths(io.fabric8.kubernetes.api.model.RootPaths) Client(io.fabric8.kubernetes.client.Client) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Test(org.junit.Test)

Example 75 with KubernetesClient

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

the class AbstractLiveEnricher method getExternalServiceURL.

/**
 * Returns the external access to the given service name
 *
 * @param serviceName name of the service
 * @param protocol URL protocol such as <code>http</code>
 */
protected String getExternalServiceURL(String serviceName, String protocol) {
    if (!isOnline()) {
        getLog().info("Not looking for service " + serviceName + " as we are in offline mode");
        return null;
    } else {
        try {
            KubernetesClient kubernetes = getKubernetes();
            String ns = kubernetes.getNamespace();
            if (Strings.isNullOrBlank(ns)) {
                ns = getNamespace();
            }
            Service service = kubernetes.services().inNamespace(ns).withName(serviceName).get();
            return service != null ? KubernetesHelper.getServiceURL(kubernetes, serviceName, ns, protocol, true) : null;
        } catch (Throwable e) {
            Throwable cause = e;
            boolean notFound = false;
            boolean connectError = false;
            Stack<Throwable> stack = unfoldExceptions(e);
            while (!stack.isEmpty()) {
                Throwable t = stack.pop();
                if (t instanceof ConnectException || "No route to host".equals(t.getMessage())) {
                    getLog().warn("Cannot connect to Kubernetes to find URL for service %s : %s", serviceName, cause.getMessage());
                    return null;
                } else if (t instanceof IllegalArgumentException || t.getMessage() != null && t.getMessage().matches("^No.*found.*$")) {
                    getLog().warn("%s", cause.getMessage());
                    return null;
                }
                ;
            }
            getLog().warn("Cannot find URL for service %s : %s", serviceName, cause.getMessage());
            return null;
        }
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Service(io.fabric8.kubernetes.api.model.Service) Stack(java.util.Stack) ConnectException(java.net.ConnectException)

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