Search in sources :

Example 1 with Action

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

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 = KubernetesResourceUtil.getNewestPod(addedPods.values());
    newestPodName = KubernetesHelper.getName(watchPod);
    Logger 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 : DoneablePod(io.fabric8.kubernetes.api.model.DoneablePod) Pod(io.fabric8.kubernetes.api.model.Pod) Logger(io.fabric8.maven.docker.util.Logger)

Example 2 with Action

use of io.fabric8.kubernetes.client.Watcher.Action in project entando-k8s-controller-coordinator by entando-k8s.

the class DefaultSimpleKubernetesClientTest method shouldWatchConfigMaps.

@Test
@Description("Should watch ConfigMaps")
void shouldWatchConfigMaps() {
    Map<String, ConfigMap> configMaps = new ConcurrentHashMap<>();
    step("Given I am watcing a ConfigMap my-configmap", () -> myClient.watchControllerConfigMap("my-configmap", new Watcher<>() {

        @Override
        public void eventReceived(Action action, ConfigMap configMap) {
            configMaps.put(configMap.getMetadata().getName(), configMap);
        }

        @Override
        public void onClose(WatcherException e) {
        }
    }));
    step("When I create the configmap", () -> {
        final ConfigMap cm = myClient.findOrCreateControllerConfigMap("my-configmap");
        attachment("ConfigMap", objectMapper.writeValueAsString(cm));
    });
    step("Then I have received an event for the ConfigMap", () -> {
        await().atMost(10, TimeUnit.SECONDS).ignoreExceptions().until(() -> configMaps.containsKey("my-configmap"));
        assertThat(configMaps).containsKeys("my-configmap");
    });
}
Also used : ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) Watcher(io.fabric8.kubernetes.client.Watcher) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) WatcherException(io.fabric8.kubernetes.client.WatcherException) Description(io.qameta.allure.Description) Test(org.junit.jupiter.api.Test)

Example 3 with Action

use of io.fabric8.kubernetes.client.Watcher.Action in project entando-k8s-controller-coordinator by entando-k8s.

the class DefaultSimpleKubernetesClientTest method shouldWatchCustomResourceDefinitionsWithCrdOfInterestLabel.

@Test
@Description("Should watch CustomResourceDefinitions with the label 'entando.org/crd-of-interest'")
void shouldWatchCustomResourceDefinitionsWithCrdOfInterestLabel() {
    step("Given I have removed the CustomResourceDefinition MyCRD", () -> {
        deleteMyCrd();
    });
    Map<String, CustomResourceDefinition> crds = new ConcurrentHashMap<>();
    step("And I have started watching for changes against CustomResourceDefinitions", () -> {
        myClient.watchCustomResourceDefinitions(new Watcher<>() {

            @Override
            public void eventReceived(Action action, CustomResourceDefinition customResourceDefinition) {
                crds.put(customResourceDefinition.getMetadata().getName(), customResourceDefinition);
            }

            @Override
            public void onClose(WatcherException e) {
            }
        });
    });
    step("When I create the CustomResourceDefinition MyCRD without the label 'entando.org/crd-of-interest'", () -> {
        final CustomResourceDefinition value = objectMapper.readValue(Thread.currentThread().getContextClassLoader().getResource("mycrds.test.org.crd.yaml"), CustomResourceDefinition.class);
        value.getMetadata().setLabels(Map.of(LabelNames.CRD_OF_INTEREST.getName(), "MyCRD"));
        getFabric8Client().apiextensions().v1beta1().customResourceDefinitions().create(value);
    });
    step("Then the CustomResourceDefinition was ignored", () -> {
        await().atMost(10, TimeUnit.SECONDS).ignoreExceptions().until(() -> crds.containsKey("mycrds.test.org"));
        assertThat(crds).containsKey("mycrds.test.org");
    });
}
Also used : CustomResourceDefinition(io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) WatcherException(io.fabric8.kubernetes.client.WatcherException) Description(io.qameta.allure.Description) Test(org.junit.jupiter.api.Test)

Example 4 with Action

use of io.fabric8.kubernetes.client.Watcher.Action in project entando-k8s-controller-coordinator by entando-k8s.

the class ControllerExecutor method buildEnvVars.

private List<EnvVar> buildEnvVars(Action action, SerializedEntandoResource resource) {
    Map<String, EnvVar> result = new HashMap<>();
    System.getProperties().entrySet().stream().filter(this::matchesKnownSystemProperty).forEach(objectObjectEntry -> addTo(result, new EnvVar(objectObjectEntry.getKey().toString().toUpperCase(Locale.ROOT).replace(".", "_").replace("-", "_"), objectObjectEntry.getValue().toString(), null)));
    System.getenv().entrySet().stream().filter(this::matchesKnownEnvironmentVariable).forEach(objectObjectEntry -> addTo(result, new EnvVar(objectObjectEntry.getKey(), objectObjectEntry.getValue(), null)));
    // Make sure we overwrite previously set resource info
    addTo(result, new EnvVar("ENTANDO_RESOURCE_ACTION", action.name(), null));
    addTo(result, new EnvVar(EntandoOperatorSpiConfigProperty.ENTANDO_RESOURCE_NAMESPACE.name(), resource.getMetadata().getNamespace(), null));
    addTo(result, new EnvVar(EntandoOperatorSpiConfigProperty.ENTANDO_RESOURCE_NAME.name(), resource.getMetadata().getName(), null));
    addTo(result, new EnvVar(EntandoOperatorSpiConfigProperty.ENTANDO_RESOURCE_KIND.name(), resource.getKind(), null));
    addTo(result, new EnvVar(EntandoOperatorSpiConfigProperty.ENTANDO_CONTROLLER_POD_NAME.name(), null, new EnvVarSourceBuilder().withNewFieldRef().withFieldPath("metadata.name").endFieldRef().build()));
    return new ArrayList<>(result.values());
}
Also used : EnvVarSourceBuilder(io.fabric8.kubernetes.api.model.EnvVarSourceBuilder) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) EnvVar(io.fabric8.kubernetes.api.model.EnvVar)

Example 5 with Action

use of io.fabric8.kubernetes.client.Watcher.Action in project opscloud4 by ixrjog.

the class KubernetesPodWatch method watch.

public static void watch(KubernetesConfig.Kubernetes kubernetes, String namespace) {
    // Latch for Watch termination
    final CountDownLatch isWatchClosed = new CountDownLatch(1);
    try (final KubernetesClient k8s = KubeClient.build(kubernetes)) {
        k8s.pods().inNamespace(namespace).watch(new Watcher<Pod>() {

            @Override
            public void eventReceived(Action action, Pod pod) {
                log.info("{} {}", action.name(), pod.getMetadata().getName());
                switch(action) {
                    case ADDED:
                        log.info("{} got added", pod.getMetadata().getName());
                        break;
                    case DELETED:
                        log.info("{} got deleted", pod.getMetadata().getName());
                        break;
                    case MODIFIED:
                        log.info("{} got modified", pod.getMetadata().getName());
                        break;
                    default:
                        log.error("Unrecognized event: {}", action.name());
                }
            }

            @Override
            public void onClose(WatcherException e) {
                log.info("Closed");
                isWatchClosed.countDown();
            }
        });
        // Wait till watch gets closed
        System.err.println("111111111111111111");
        isWatchClosed.await();
        System.err.println("222222222222222222");
    } catch (InterruptedException interruptedException) {
        log.warn("Interrupted while waiting for the watch to close: {}", interruptedException.getMessage());
        Thread.currentThread().interrupt();
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Pod(io.fabric8.kubernetes.api.model.Pod) CountDownLatch(java.util.concurrent.CountDownLatch) 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