Java Code Examples for io.fabric8.kubernetes.client.Watcher#Action

The following examples show how to use io.fabric8.kubernetes.client.Watcher#Action . 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: PodLogService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
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));
    }
}
 
Example 2
Source File: Reaper.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void eventReceived(Watcher.Action action, Pod pod) {
    String ns = pod.getMetadata().getNamespace();
    String name = pod.getMetadata().getName();
    Jenkins jenkins = Jenkins.getInstanceOrNull();
    if (jenkins == null) {
        return;
    }
    Optional<KubernetesSlave> optionalNode = resolveNode(jenkins, ns, name);
    if (!optionalNode.isPresent()) {
        return;
    }
    ExtensionList.lookup(Listener.class).forEach(listener -> {
        try {
            listener.onEvent(action, optionalNode.get(), pod);
        } catch (Exception x) {
            LOGGER.log(Level.WARNING, "Listener " + listener + " failed for " + ns + "/" + name, x);
        }
    });
}
 
Example 3
Source File: EventConsumer.java    From java-operator-sdk with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private boolean processEvent() {
    Watcher.Action action = event.getAction();
    CustomResource resource = event.getResource();
    try {
        eventDispatcher.handleEvent(action, resource);
    } catch (RuntimeException e) {
        log.error("Processing event {} failed.", event, e);
        return false;
    }
    return true;
}
 
Example 4
Source File: EventDispatcher.java    From java-operator-sdk with Apache License 2.0 5 votes vote down vote up
public void handleEvent(Watcher.Action action, CustomResource resource) {
    log.info("Handling event {} for resource {}", action, resource.getMetadata());
    if (Watcher.Action.ERROR == action) {
        log.error("Received error for resource: {}", resource.getMetadata().getName());
        return;
    }
    // Its interesting problem if we should call delete if received event after object is marked for deletion
    // but there is not our finalizer. Since it can happen that there are multiple finalizers, also other events after
    // we called delete and remove finalizers already. But also it can happen that we did not manage to put
    // finalizer into the resource before marked for delete. So for now we will call delete every time, since delete
    // operation should be idempotent too, and this way we cover the corner case.
    if (markedForDeletion(resource) || action == Watcher.Action.DELETED) {
        boolean removeFinalizer = controller.deleteResource(resource);
        if (removeFinalizer && hasDefaultFinalizer(resource)) {
            log.debug("Removing finalizer on {}: {}", resource.getMetadata().getName(), resource.getMetadata());
            removeDefaultFinalizer(resource);
        }
    } else {
        Optional<CustomResource> updateResult = controller.createOrUpdateResource(resource);
        if (updateResult.isPresent()) {
            log.debug("Updating resource: {} with version: {}", resource.getMetadata().getName(),
                    resource.getMetadata().getResourceVersion());
            log.trace("Resource before update: {}", resource);
            CustomResource updatedResource = updateResult.get();
            addFinalizerIfNotPresent(updatedResource);
            replace(updatedResource);
            log.trace("Resource after update: {}", resource);
            // We always add the default finalizer if missing and not marked for deletion.
        } else if (!hasDefaultFinalizer(resource) && !markedForDeletion(resource)) {
            log.debug("Adding finalizer for resource: {} version: {}", resource.getMetadata().getName(),
                    resource.getMetadata().getResourceVersion());
            addFinalizerIfNotPresent(resource);
            replace(resource);
        }
    }
}
 
Example 5
Source File: EventSchedulerTest.java    From java-operator-sdk with Apache License 2.0 5 votes vote down vote up
public EventProcessingDetail(Watcher.Action action, LocalDateTime startTime, LocalDateTime endTime, CustomResource customResource, Exception exception) {
    this.action = action;
    this.startTime = startTime;
    this.endTime = endTime;
    this.customResource = customResource;
    this.exception = exception;
}
 
Example 6
Source File: KubernetesDockerRunner.java    From styx with Apache License 2.0 5 votes vote down vote up
private void logEvent(Watcher.Action action, Pod pod, String resourceVersion,
                      boolean polled) {
  final String podName = pod.getMetadata().getName();
  final String workflowInstance = Optional.ofNullable(pod.getMetadata().getAnnotations())
      .map(annotations -> annotations.get(STYX_WORKFLOW_INSTANCE_ANNOTATION))
      .orElse("N/A");
  final String status = readStatus(pod);

  LOG.info("{}Pod event for {} ({}) at resource version {}, action: {}, workflow instance: {}, status: {}",
           polled ? "Polled: " : "", podName, pod.getMetadata().getUid(), resourceVersion, action, workflowInstance,
           status);
}
 
Example 7
Source File: KubernetesClientUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static String getPodStatusMessagePostfix(Watcher.Action action) {
    String message = "";
    switch (action) {
    case DELETED:
        message = ": Pod Deleted";
        break;
    case ERROR:
        message = ": Error";
        break;
    }
    return message;
}
 
Example 8
Source File: Reaper.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(@NonNull Watcher.Action action, @NonNull KubernetesSlave node, @NonNull Pod pod) throws IOException {
    if (action != Action.DELETED) {
        return;
    }
    String ns = pod.getMetadata().getNamespace();
    String name = pod.getMetadata().getName();
    TaskListener runListener = node.getTemplate().getListener();
    LOGGER.info(() -> ns + "/" + name + " was just deleted, so removing corresponding Jenkins agent");
    runListener.getLogger().printf("Pod %s/%s was just deleted%n", ns, name);
    Jenkins.get().removeNode(node);
}
 
Example 9
Source File: MockTopicOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Void> onResourceEvent(LogContext logContext, KafkaTopic resource, Watcher.Action action) {
    mockOperatorEvents.add(new MockOperatorEvent(action == Watcher.Action.MODIFIED ? MockOperatorEvent.Type.MODIFY :
            action == Watcher.Action.ADDED ? MockOperatorEvent.Type.CREATE :
            MockOperatorEvent.Type.DELETE, resource));
    return resourceAddedResult;
}
 
Example 10
Source File: EventSchedulerTest.java    From java-operator-sdk with Apache License 2.0 4 votes vote down vote up
public EventProcessingDetail setAction(Watcher.Action action) {
    this.action = action;
    return this;
}
 
Example 11
Source File: DebugMojo.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
private boolean isAddOrModified(Watcher.Action action) {
    return action.equals(Watcher.Action.ADDED) || action.equals(Watcher.Action.MODIFIED);
}
 
Example 12
Source File: LogContext.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
static LogContext kubeWatch(Watcher.Action action, KafkaTopic kafkaTopic) {
    LogContext logContext = new LogContext("kube " + action(action) + kafkaTopic.getMetadata().getName());
    logContext.resourceVersion = kafkaTopic.getMetadata().getResourceVersion();
    return logContext;
}
 
Example 13
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 14
Source File: OpenShiftServiceNoOp.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends HasMetadata, L extends KubernetesResourceList<T>, D extends Doneable<T>> Watch watchCR(CustomResourceDefinition crd, Class<T> resourceType, Class<L> resourceListType, Class<D> doneableResourceType, BiConsumer<Watcher.Action, T> watcher) {
    return null;
}
 
Example 15
Source File: EventSchedulerTest.java    From java-operator-sdk with Apache License 2.0 4 votes vote down vote up
public Watcher.Action getAction() {
    return action;
}
 
Example 16
Source File: PredicatedWatcher.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public void maybeFire(CM removed, Watcher.Action action) {
    if (predicate.test(removed)) {
        LOGGER.debug("Firing watcher {} with {} and resource {}", watcher, action, removed);
        watcher.eventReceived(action, removed);
    }
}
 
Example 17
Source File: CustomResourceEvent.java    From java-operator-sdk with Apache License 2.0 4 votes vote down vote up
Watcher.Action getAction() {
    return action;
}
 
Example 18
Source File: CustomResourceEvent.java    From java-operator-sdk with Apache License 2.0 4 votes vote down vote up
CustomResourceEvent(Watcher.Action action, CustomResource resource, Retry retry) {
    this.action = action;
    this.resource = resource;
    this.retryExecution = retry.initExecution();
}
 
Example 19
Source File: OpenShiftService.java    From syndesis with Apache License 2.0 2 votes vote down vote up
/**
 * The entry point to client operations.
 * @param <T>   The Kubernetes resource type.
 * @param <L>   The list variant of the Kubernetes resource type.
 * @param <D>   The doneable variant of the Kubernetes resource type.
 * @param crd the {@link CustomResourceDefinition}
 * @param resourceType the type of T
 * @param resourceListType the type of L
 * @param doneableResourceType the type of D
 * @param watcher a {@code BiConsumer<Watcher.Action,T>} function to be executed for each received Action on T
 * @return the Watch
 */
<T extends HasMetadata, L extends KubernetesResourceList<T>, D extends Doneable<T>> Watch watchCR(CustomResourceDefinition crd, Class<T> resourceType, Class<L> resourceListType, Class<D> doneableResourceType, BiConsumer<Watcher.Action,T> watcher);
 
Example 20
Source File: Observer.java    From strimzi-kafka-operator with Apache License 2.0 votes vote down vote up
void afterWatcherFire(Watcher.Action action, T resource);