Search in sources :

Example 26 with Action

use of io.fabric8.kubernetes.client.Watcher.Action in project dubbo-spi-extensions by apache.

the class KubernetesMeshEnvListener method subscribeVs.

private void subscribeVs(String appName) {
    if (vsAppWatch.containsKey(appName)) {
        return;
    }
    try {
        Watch watch = kubernetesClient.customResource(MeshConstant.getVsDefinition()).watch(namespace, appName, null, new ListOptionsBuilder().build(), new Watcher<String>() {

            @Override
            public void eventReceived(Action action, String resource) {
                logger.info("Received VS Rule notification. AppName: " + appName + " Action:" + action + " Resource:" + resource);
                if (action == Action.ADDED || action == Action.MODIFIED) {
                    Map drRuleMap = new Gson().fromJson(resource, Map.class);
                    String vsRule = new Yaml(new SafeConstructor()).dump(drRuleMap);
                    vsAppCache.put(appName, vsRule);
                    if (drAppCache.containsKey(appName)) {
                        notifyListener(vsRule, appName, drAppCache.get(appName));
                    }
                } else {
                    appRuleListenerMap.get(appName).receiveConfigInfo("");
                }
            }

            @Override
            public void onClose(WatcherException cause) {
            // ignore
            }
        });
        vsAppWatch.put(appName, watch);
        try {
            Map<String, Object> vsRule = kubernetesClient.customResource(MeshConstant.getVsDefinition()).get(namespace, appName);
            vsAppCache.put(appName, new Yaml(new SafeConstructor()).dump(vsRule));
        } catch (Throwable ignore) {
        }
    } catch (IOException e) {
        logger.error("Error occurred when listen kubernetes crd.", e);
    }
}
Also used : Gson(com.google.gson.Gson) IOException(java.io.IOException) Yaml(org.yaml.snakeyaml.Yaml) WatcherException(io.fabric8.kubernetes.client.WatcherException) Watch(io.fabric8.kubernetes.client.Watch) SafeConstructor(org.yaml.snakeyaml.constructor.SafeConstructor) ListOptionsBuilder(io.fabric8.kubernetes.api.model.ListOptionsBuilder) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map)

Example 27 with Action

use of io.fabric8.kubernetes.client.Watcher.Action in project dubbo-spi-extensions by apache.

the class KubernetesServiceDiscovery method watchEndpoints.

private void watchEndpoints(ServiceInstancesChangedListener listener, String serviceName) {
    Watch watch = kubernetesClient.endpoints().inNamespace(namespace).withName(serviceName).watch(new Watcher<Endpoints>() {

        @Override
        public void eventReceived(Action action, Endpoints resource) {
            if (logger.isDebugEnabled()) {
                logger.debug("Received Endpoint Event. Event type: " + action.name() + ". Current pod name: " + currentHostname);
            }
            notifyServiceChanged(serviceName, listener);
        }

        @Override
        public void onClose(WatcherException cause) {
        // ignore
        }
    });
    ENDPOINTS_WATCHER.put(serviceName, watch);
}
Also used : Endpoints(io.fabric8.kubernetes.api.model.Endpoints) Watch(io.fabric8.kubernetes.client.Watch) WatcherException(io.fabric8.kubernetes.client.WatcherException)

Example 28 with Action

use of io.fabric8.kubernetes.client.Watcher.Action in project jkube by eclipse.

the class PortForwardService method forwardPortAsync.

/**
 * Forwards a port to the newest pod matching the given selector.
 * If another pod is created, it forwards connections to the new pod once it's ready.
 *
 * @param podSelector Pod label selector
 * @param containerPort port inside Pod container running inside Kubernetes Cluster
 * @param localPort port at remote machine outside Kubernetes Cluster
 * @return {@link Closeable} Closeable
 */
public Closeable forwardPortAsync(final LabelSelector podSelector, String namespace, final int containerPort, final int localPort) {
    final Lock monitor = new ReentrantLock(true);
    final Condition podChanged = monitor.newCondition();
    final Pod[] nextForwardedPod = new Pod[1];
    final Thread forwarderThread = new Thread() {

        @Override
        public void run() {
            Pod currentPod = null;
            Closeable currentPortForward = null;
            try {
                monitor.lock();
                while (true) {
                    if (podEquals(currentPod, nextForwardedPod[0])) {
                        podChanged.await();
                    } else {
                        // may be null
                        Pod nextPod = nextForwardedPod[0];
                        try {
                            monitor.unlock();
                            if (currentPortForward != null) {
                                log.info("Closing port-forward from pod %s", KubernetesHelper.getName(currentPod));
                                currentPortForward.close();
                                currentPortForward = null;
                            }
                            if (nextPod != null) {
                                log.info("Starting port-forward to pod %s", KubernetesHelper.getName(nextPod));
                                currentPortForward = forwardPortAsync(KubernetesHelper.getName(nextPod), KubernetesHelper.getNamespace(nextPod), containerPort, localPort);
                            } else {
                                log.info("Waiting for a pod to become ready before starting port-forward");
                            }
                            currentPod = nextPod;
                        } finally {
                            monitor.lock();
                        }
                    }
                }
            } catch (InterruptedException e) {
                log.debug("Port-forwarding thread interrupted", e);
                Thread.currentThread().interrupt();
            } catch (Exception e) {
                log.warn("Error while port-forwarding to pod", e);
            } finally {
                monitor.unlock();
                if (currentPortForward != null) {
                    try {
                        currentPortForward.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
    };
    // Switching forward to the current pod if present
    Pod newPod = getNewestPod(namespace, podSelector);
    nextForwardedPod[0] = newPod;
    final Watch watch = KubernetesHelper.withSelector(kubernetes.pods().inNamespace(namespace), podSelector, log).watch(new Watcher<Pod>() {

        @Override
        public void eventReceived(Action action, Pod pod) {
            monitor.lock();
            try {
                List<Pod> candidatePods;
                if (nextForwardedPod[0] != null) {
                    candidatePods = new LinkedList<>();
                    candidatePods.add(nextForwardedPod[0]);
                    candidatePods.add(pod);
                } else {
                    candidatePods = Collections.singletonList(pod);
                }
                // may be null
                Pod newPod = getNewestPod(candidatePods);
                if (!podEquals(nextForwardedPod[0], newPod)) {
                    nextForwardedPod[0] = newPod;
                    podChanged.signal();
                }
            } finally {
                monitor.unlock();
            }
        }

        @Override
        public void onClose(WatcherException e) {
        // don't care
        }
    });
    forwarderThread.start();
    final Closeable handle = () -> {
        try {
            watch.close();
        } catch (Exception e) {
        }
        try {
            forwarderThread.interrupt();
            forwarderThread.join(15000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    };
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            try {
                handle.close();
            } catch (Exception e) {
            // suppress
            }
        }
    });
    return handle;
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) Condition(java.util.concurrent.locks.Condition) Pod(io.fabric8.kubernetes.api.model.Pod) Closeable(java.io.Closeable) WatcherException(io.fabric8.kubernetes.client.WatcherException) LinkedList(java.util.LinkedList) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) WatcherException(io.fabric8.kubernetes.client.WatcherException) Watch(io.fabric8.kubernetes.client.Watch) List(java.util.List) PodList(io.fabric8.kubernetes.api.model.PodList) LinkedList(java.util.LinkedList)

Example 29 with Action

use of io.fabric8.kubernetes.client.Watcher.Action in project jkube by eclipse.

the class PodLogService method onPod.

private void onPod(Watcher.Action action, Pod pod, KubernetesClient kubernetes, String namespace, String ctrlCMessage, boolean followLog) {
    String name = KubernetesHelper.getName(pod);
    if (action.equals(Watcher.Action.DELETED)) {
        addedPods.remove(name);
        if (Objects.equals(watchingPodName, name)) {
            watchingPodName = null;
            addedPods.remove(name);
        }
    } else {
        if (action.equals(Watcher.Action.ADDED) || action.equals(Watcher.Action.MODIFIED)) {
            addedPods.put(name, pod);
        }
    }
    Pod watchPod = KubernetesHelper.getNewestPod(addedPods.values());
    String newestPodName = KubernetesHelper.getName(watchPod);
    KitLogger statusLog = Objects.equals(name, newestPodName) ? context.getNewPodLog() : context.getOldPodLog();
    if (!action.equals(Watcher.Action.MODIFIED) || watchingPodName == null || !watchingPodName.equals(name)) {
        statusLog.info("%s status: %s%s", name, getPodStatusDescription(pod), getPodStatusMessagePostfix(action));
    }
    if (watchPod != null && KubernetesHelper.isPodRunning(watchPod)) {
        watchLogOfPodName(kubernetes, namespace, ctrlCMessage, followLog, watchPod, KubernetesHelper.getName(watchPod));
    }
}
Also used : KitLogger(org.eclipse.jkube.kit.common.KitLogger) Pod(io.fabric8.kubernetes.api.model.Pod)

Example 30 with Action

use of io.fabric8.kubernetes.client.Watcher.Action in project jkube by eclipse.

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) {
    final FilterWatchListDeletable<Pod, PodList> pods;
    if (StringUtils.isNotBlank(context.getPodName())) {
        log.info("Watching pod with selector %s, and name %s waiting for a running pod...", selector, context.getPodName());
        pods = kubernetes.pods().inNamespace(namespace).withField("metadata.name", context.getPodName());
    } else {
        log.info("Watching pods with selector %s waiting for a running pod...", selector);
        pods = withSelector(kubernetes.pods().inNamespace(namespace), selector, log);
    }
    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) {
                if (KubernetesHelper.isPodRunning(pod) || KubernetesHelper.isPodWaiting(pod)) {
                    if (latestPod == null || KubernetesHelper.isNewerResource(pod, latestPod)) {
                        if (ignorePodsOlderThan != null) {
                            Date podCreateTime = KubernetesHelper.getCreationTimestamp(pod);
                            if (podCreateTime != null && podCreateTime.compareTo(ignorePodsOlderThan) > 0) {
                                latestPod = pod;
                            }
                        } else {
                            latestPod = pod;
                        }
                    }
                    runningPod = true;
                }
            }
        }
    }
    // 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 && !runningPod) {
        log.warn("No pod is running yet. Are you sure you deployed your app using Eclipse JKube apply/deploy mechanism?");
        log.warn("Or did you undeploy it? If so try running the Eclipse JKube apply/deploy tasks again.");
    }
    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(WatcherException e) {
        // ignore
        }
    });
    if (waitInCurrentThread) {
        while (terminateLatch.getCount() > 0) {
            try {
                terminateLatch.await();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
Also used : PodList(io.fabric8.kubernetes.api.model.PodList) Pod(io.fabric8.kubernetes.api.model.Pod) Watcher(io.fabric8.kubernetes.client.Watcher) Date(java.util.Date) WatcherException(io.fabric8.kubernetes.client.WatcherException)

Aggregations

WatcherException (io.fabric8.kubernetes.client.WatcherException)63 Watch (io.fabric8.kubernetes.client.Watch)48 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)42 Watcher (io.fabric8.kubernetes.client.Watcher)35 Pod (io.fabric8.kubernetes.api.model.Pod)34 CountDownLatch (java.util.concurrent.CountDownLatch)27 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)23 Test (org.junit.jupiter.api.Test)22 Map (java.util.Map)15 List (java.util.List)14 ArrayList (java.util.ArrayList)13 DisplayName (org.junit.jupiter.api.DisplayName)12 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)11 Future (io.vertx.core.Future)11 ReconciliationLogger (io.strimzi.operator.common.ReconciliationLogger)10 GenericKubernetesResource (io.fabric8.kubernetes.api.model.GenericKubernetesResource)9 WatchEvent (io.fabric8.kubernetes.api.model.WatchEvent)9 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)9 Service (io.fabric8.kubernetes.api.model.Service)8 Annotations (io.strimzi.operator.common.Annotations)8