io.fabric8.kubernetes.client.dsl.Watchable Java Examples

The following examples show how to use io.fabric8.kubernetes.client.dsl.Watchable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractWatcher.java    From abstract-operator with Apache License 2.0 4 votes vote down vote up
protected CompletableFuture<Watch> createConfigMapWatch() {
    CompletableFuture<Watch> cf = CompletableFuture.supplyAsync(() -> {
        MixedOperation<ConfigMap, ConfigMapList, DoneableConfigMap, Resource<ConfigMap, DoneableConfigMap>> aux = client.configMaps();

        final boolean inAllNs = "*".equals(namespace);
        Watchable<Watch, Watcher<ConfigMap>> watchable = inAllNs ? aux.inAnyNamespace().withLabels(selector) :
                aux.inNamespace(namespace).withLabels(selector);
        Watch watch = watchable.watch(new Watcher<ConfigMap>() {
            @Override
            public void eventReceived(Action action, ConfigMap cm) {
                if (isSupported.test(cm)) {
                    log.info("ConfigMap in namespace {} was {}\nCM:\n{}\n", namespace, action, cm);
                    T entity = convert.apply(cm);
                    if (entity == null) {
                        log.error("something went wrong, unable to parse {} definition", entityName);
                    }
                    if (action.equals(Action.ERROR)) {
                        log.error("Failed ConfigMap {} in namespace{} ", cm, namespace);
                    } else {
                        handleAction(action, entity, inAllNs ? cm.getMetadata().getNamespace() : namespace);
                    }
                } else {
                    log.error("Unknown CM kind: {}", cm.toString());
                }
            }

            @Override
            public void onClose(KubernetesClientException e) {
                if (e != null) {
                    log.error("Watcher closed with exception in namespace {}", namespace, e);
                    recreateWatcher();
                } else {
                    log.info("Watcher closed in namespace {}", namespace);
                }
            }
        });
        return watch;
    }, SDKEntrypoint.getExecutors());
    cf.thenApply(w -> {
        log.info("ConfigMap watcher running for labels {}", selector);
        return w;
    }).exceptionally(e -> {
        log.error("ConfigMap watcher failed to start", e.getCause());
        return null;
    });
    return cf;
}
 
Example #2
Source File: AbstractWatcher.java    From abstract-operator with Apache License 2.0 4 votes vote down vote up
protected CompletableFuture<Watch> createCustomResourceWatch() {
    CompletableFuture<Watch> cf = CompletableFuture.supplyAsync(() -> {
        MixedOperation<InfoClass, InfoList, InfoClassDoneable, Resource<InfoClass, InfoClassDoneable>> aux =
                client.customResources(crd, InfoClass.class, InfoList.class, InfoClassDoneable.class);

        final boolean inAllNs = "*".equals(namespace);
        Watchable<Watch, Watcher<InfoClass>> watchable = inAllNs ? aux.inAnyNamespace() : aux.inNamespace(namespace);
        Watch watch = watchable.watch(new Watcher<InfoClass>() {
            @Override
            public void eventReceived(Action action, InfoClass info) {
                log.info("Custom resource in namespace {} was {}\nCR:\n{}", namespace, action, info);
                T entity = convertCr.apply(info);
                if (entity == null) {
                    log.error("something went wrong, unable to parse {} definition", entityName);
                }
                if (action.equals(Action.ERROR)) {
                    log.error("Failed Custom resource {} in namespace{} ", info, namespace);
                } else {
                    handleAction(action, entity, inAllNs ? info.getMetadata().getNamespace() : namespace);
                }
            }

            @Override
            public void onClose(KubernetesClientException e) {
                if (e != null) {
                    log.error("Watcher closed with exception in namespace {}", namespace, e);
                    recreateWatcher();
                } else {
                    log.info("Watcher closed in namespace {}", namespace);
                }
            }
        });
        AbstractWatcher.this.watch = watch;
        return watch;
    }, SDKEntrypoint.getExecutors());
    cf.thenApply(w -> {
        log.info("CustomResource watcher running for kinds {}", entityName);
        return w;
    }).exceptionally(e -> {
        log.error("CustomResource watcher failed to start", e.getCause());
        return null;
    });
    return cf;
}
 
Example #3
Source File: ResourceSupport.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * Watches the given {@code watchable} using the given
 * {@code watchFn},
 * returning a Future which completes when {@code watchFn} returns non-null
 * to some event on the watchable, or after a timeout.
 *
 * The given {@code watchFn} will be invoked on a worked thread when the
 * Kubernetes resources changes, so may block.
 * When the {@code watchFn} returns non-null the watch will be closed and then
 * the future returned from this method will be completed on the context thread.
 * @param watchable The watchable.
 * @param watchFn The function to determine
 * @param timeoutMs The timeout in milliseconds.
 * @param <T> The type of watched resource.
 * @param <U> The result type of the {@code watchFn}.
 *
 * @return A Futures which completes when the {@code watchFn} returns non-null
 * in response to some Kubenetes even on the watched resource(s).
 */
public <T, U> Future<U> selfClosingWatch(Watchable<Watch, Watcher<T>> watchable,
                                         BiFunction<Watcher.Action, T, U> watchFn,
                                         long timeoutMs) {

    return new Watcher<T>() {
        private final Promise<Watch> watchPromise;
        private final Promise<U> donePromise;
        private final Promise<U> resultPromise;
        private final long timerId;

        /* init */
        {
            this.watchPromise = Promise.promise();
            this.donePromise = Promise.promise();
            this.resultPromise = Promise.promise();
            this.timerId = vertx.setTimer(timeoutMs, ignored -> {
                donePromise.tryFail(new TimeoutException());
            });
            CompositeFuture.join(watchPromise.future(), donePromise.future()).onComplete(joinResult -> {
                Future<Void> closeFuture;
                if (watchPromise.future().succeeded()) {
                    closeFuture = closeOnWorkerThread(watchPromise.future().result());
                } else {
                    closeFuture = Future.succeededFuture();
                }
                closeFuture.onComplete(closeResult -> {
                    vertx.runOnContext(ignored2 -> {
                        LOGGER.warn("Completing watch future");
                        if (joinResult.succeeded() && closeResult.succeeded()) {
                            resultPromise.complete(joinResult.result().resultAt(1));
                        } else {
                            resultPromise.fail(collectCauses(joinResult, closeResult));
                        }
                    });
                });
            });
            Watch watch = watchable.watch(this);
            LOGGER.debug("Opened watch {}", watch);
            watchPromise.complete(watch);
        }

        @Override
        public void eventReceived(Action action, T resource) {
            vertx.<U>executeBlocking(
                f -> {
                    try {
                        U apply = watchFn.apply(action, resource);
                        if (apply != null) {
                            f.tryComplete(apply);
                            vertx.cancelTimer(timerId);
                        } else {
                            LOGGER.debug("Not yet complete");
                        }
                    } catch (Throwable t) {
                        if (!f.tryFail(t)) {
                            LOGGER.debug("Ignoring exception thrown while " +
                                    "evaluating watch because the future was already completed", t);
                        }
                    }
                },
                true,
                ar -> {
                    donePromise.handle(ar);
                });
        }

        @Override
        public void onClose(KubernetesClientException cause) {

        }

    }.resultPromise.future();
}
 
Example #4
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public Watchable<Watch, Watcher<T>> withResourceVersion(String resourceVersion) {
  return newInstance(context.withResourceVersion(resourceVersion));
}
 
Example #5
Source File: BuildConfigOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public Watchable<Watch, Watcher<BuildConfig>> withResourceVersion(String resourceVersion) {
  return new BuildConfigOperationsImpl(getContext().withResourceVersion(resourceVersion));
}