Search in sources :

Example 16 with Watcher

use of io.fabric8.kubernetes.client.Watcher in project fabric8 by jboss-fuse.

the class ZooKeeperUtils method getProperties.

public static Properties getProperties(CuratorFramework curator, String path, Watcher watcher) throws Exception {
    String value = getStringData(curator, path, watcher);
    Properties properties = new Properties();
    if (value != null) {
        try {
            properties.load(new StringReader(value));
        } catch (IOException ignore) {
        }
    }
    return properties;
}
Also used : StringReader(java.io.StringReader) IOException(java.io.IOException) RuntimeProperties(io.fabric8.api.RuntimeProperties) Properties(java.util.Properties)

Example 17 with Watcher

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

the class PodOperatorTest method testCreateReadUpdate.

@Test
public void testCreateReadUpdate(TestContext context) {
    vertx.createSharedWorkerExecutor("kubernetes-ops-pool", 10);
    KubernetesClient client = server.getKubernetesClient();
    PodOperator pr = new PodOperator(vertx, client);
    context.assertEquals(emptyList(), pr.list(NAMESPACE, Labels.EMPTY));
    Async async = context.async(1);
    pr.createOrUpdate(resource()).setHandler(createResult -> {
        context.assertTrue(createResult.succeeded());
        context.assertEquals(singletonList(RESOURCE_NAME), pr.list(NAMESPACE, Labels.EMPTY).stream().map(p -> p.getMetadata().getName()).collect(Collectors.toList()));
        // Pod got = pr.get(NAMESPACE, RESOURCE_NAME);
        // context.assertNotNull(got);
        // context.assertNotNull(got.getMetadata());
        // context.assertEquals(RESOURCE_NAME, got.getMetadata().getName());
        context.assertFalse(pr.isReady(NAMESPACE, RESOURCE_NAME));
        /*pr.watch(NAMESPACE, RESOURCE_NAME, new Watcher<Pod>() {
                @Override
                public void eventReceived(Action action, Pod resource) {
                    if (action == Action.DELETED) {
                        context.assertEquals(RESOURCE_NAME, resource.getMetadata().getName());
                    } else {
                        context.fail();
                    }
                    async.countDown();
                }

                @Override
                public void onClose(KubernetesClientException cause) {

                }
            });*/
        /*Pod modified = resource();
            modified.getSpec().setHostname("bar");
            Async patchAsync = context.async();
            pr.patch(NAMESPACE, RESOURCE_NAME, modified, patchResult -> {
                context.assertTrue(patchResult.succeeded());
                patchAsync.complete();
            });
            patchAsync.await();*/
        pr.reconcile(NAMESPACE, RESOURCE_NAME, null).setHandler(deleteResult -> {
            context.assertTrue(deleteResult.succeeded());
            async.countDown();
        });
    });
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Async(io.vertx.ext.unit.Async) Test(org.junit.Test)

Example 18 with Watcher

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

the class ClusterController method createConfigMapWatch.

private void createConfigMapWatch(Handler<AsyncResult<Watch>> handler) {
    getVertx().executeBlocking(future -> {
        Watch watch = client.configMaps().inNamespace(namespace).withLabels(selector.toMap()).watch(new Watcher<ConfigMap>() {

            @Override
            public void eventReceived(Action action, ConfigMap cm) {
                Labels labels = Labels.fromResource(cm);
                AssemblyType type;
                try {
                    type = labels.type();
                } catch (IllegalArgumentException e) {
                    log.warn("Unknown {} label {} received in Config Map {} in namespace {}", Labels.STRIMZI_TYPE_LABEL, cm.getMetadata().getLabels().get(Labels.STRIMZI_TYPE_LABEL), cm.getMetadata().getName(), namespace);
                    return;
                }
                final AbstractAssemblyOperator cluster;
                if (type == null) {
                    log.warn("Missing label {} in Config Map {} in namespace {}", Labels.STRIMZI_TYPE_LABEL, cm.getMetadata().getName(), namespace);
                    return;
                } else {
                    switch(type) {
                        case KAFKA:
                            cluster = kafkaAssemblyOperator;
                            break;
                        case CONNECT:
                            cluster = kafkaConnectAssemblyOperator;
                            break;
                        case CONNECT_S2I:
                            cluster = kafkaConnectS2IAssemblyOperator;
                            break;
                        default:
                            return;
                    }
                }
                String name = cm.getMetadata().getName();
                switch(action) {
                    case ADDED:
                    case DELETED:
                    case MODIFIED:
                        Reconciliation reconciliation = new Reconciliation("watch", type, namespace, name);
                        log.info("{}: ConfigMap {} in namespace {} was {}", reconciliation, name, namespace, action);
                        cluster.reconcileAssembly(reconciliation, result -> {
                            if (result.succeeded()) {
                                log.info("{}: assembly reconciled", reconciliation);
                            } else {
                                log.error("{}: Failed to reconcile", reconciliation);
                            }
                        });
                        break;
                    case ERROR:
                        log.error("Failed ConfigMap {} in namespace{} ", name, namespace);
                        reconcileAll("watch error");
                        break;
                    default:
                        log.error("Unknown action: {} in namespace {}", name, namespace);
                        reconcileAll("watch unknown");
                }
            }

            @Override
            public void onClose(KubernetesClientException e) {
                if (e != null) {
                    log.error("Watcher closed with exception in namespace {}", namespace, e);
                } else {
                    log.info("Watcher closed in namespace {}", namespace);
                }
                recreateConfigMapWatch();
            }
        });
        future.complete(watch);
    }, res -> {
        if (res.succeeded()) {
            log.info("ConfigMap watcher running for labels {}", selector);
            handler.handle(Future.succeededFuture((Watch) res.result()));
        } else {
            log.info("ConfigMap watcher failed to start", res.cause());
            handler.handle(Future.failedFuture("ConfigMap watcher failed to start"));
        }
    });
}
Also used : KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) AssemblyType(io.strimzi.controller.cluster.model.AssemblyType) KafkaAssemblyOperator(io.strimzi.controller.cluster.operator.assembly.KafkaAssemblyOperator) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) Watcher(io.fabric8.kubernetes.client.Watcher) Watch(io.fabric8.kubernetes.client.Watch) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Labels(io.strimzi.controller.cluster.model.Labels) Future(io.vertx.core.Future) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) TimeUnit(java.util.concurrent.TimeUnit) AbstractVerticle(io.vertx.core.AbstractVerticle) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) AbstractAssemblyOperator(io.strimzi.controller.cluster.operator.assembly.AbstractAssemblyOperator) KafkaConnectS2IAssemblyOperator(io.strimzi.controller.cluster.operator.assembly.KafkaConnectS2IAssemblyOperator) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) KafkaConnectAssemblyOperator(io.strimzi.controller.cluster.operator.assembly.KafkaConnectAssemblyOperator) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) Labels(io.strimzi.controller.cluster.model.Labels) AbstractAssemblyOperator(io.strimzi.controller.cluster.operator.assembly.AbstractAssemblyOperator) AssemblyType(io.strimzi.controller.cluster.model.AssemblyType) Watch(io.fabric8.kubernetes.client.Watch) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 19 with Watcher

use of io.fabric8.kubernetes.client.Watcher 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 20 with Watcher

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

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.
 */
public Closeable forwardPortAsync(final Logger externalProcessLogger, final LabelSelector podSelector, final int remotePort, final int localPort) throws Fabric8ServiceException {
    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(externalProcessLogger, KubernetesHelper.getName(nextPod), remotePort, 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(podSelector);
    nextForwardedPod[0] = newPod;
    final Watch watch = KubernetesClientUtil.withSelector(kubernetes.pods(), 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(KubernetesClientException e) {
        // don't care
        }
    });
    forwarderThread.start();
    final Closeable handle = new Closeable() {

        @Override
        public void close() throws IOException {
            try {
                watch.close();
            } catch (Exception e) {
            }
            try {
                forwarderThread.interrupt();
                forwarderThread.join(15000);
            } catch (Exception e) {
            }
        }
    };
    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) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) IOException(java.io.IOException) LinkedList(java.util.LinkedList) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) Watch(io.fabric8.kubernetes.client.Watch) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) PodList(io.fabric8.kubernetes.api.model.PodList) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Aggregations

Watch (io.fabric8.kubernetes.client.Watch)11 Watcher (io.fabric8.kubernetes.client.Watcher)9 Pod (io.fabric8.kubernetes.api.model.Pod)8 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)8 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)7 PodList (io.fabric8.kubernetes.api.model.PodList)6 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)5 ArrayList (java.util.ArrayList)5 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)5 DoneablePod (io.fabric8.kubernetes.api.model.DoneablePod)4 WatchImageConfiguration (io.fabric8.maven.docker.config.WatchImageConfiguration)4 IOException (java.io.IOException)4 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)3 LogWatch (io.fabric8.kubernetes.client.dsl.LogWatch)3 MixedOperation (io.fabric8.kubernetes.client.dsl.MixedOperation)3 HashMap (java.util.HashMap)3 ConfigMapList (io.fabric8.kubernetes.api.model.ConfigMapList)2 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)2 DoneableStatefulSet (io.fabric8.kubernetes.api.model.extensions.DoneableStatefulSet)2 StatefulSet (io.fabric8.kubernetes.api.model.extensions.StatefulSet)2