Search in sources :

Example 21 with Action

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

the class WatchTest method testTryWithResourcesConnectsThenReceivesEvent.

@Test
@DisplayName("TryWithResources, connects and receives event then receives GONE, should receive first event and then close")
void testTryWithResourcesConnectsThenReceivesEvent() throws InterruptedException {
    // Given
    server.expect().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&allowWatchBookmarks=true&watch=true").andUpgradeToWebSocket().open().waitFor(EVENT_WAIT_PERIOD_MS).andEmit(new WatchEvent(pod1, "DELETED")).waitFor(EVENT_WAIT_PERIOD_MS).andEmit(outdatedEvent()).done().once();
    final CountDownLatch deleteLatch = new CountDownLatch(1);
    final CountDownLatch closeLatch = new CountDownLatch(1);
    final Watcher<Pod> watcher = new Watcher<Pod>() {

        @Override
        public void eventReceived(Action action, Pod resource) {
            if (action != DELETED) {
                fail();
            }
            deleteLatch.countDown();
        }

        @Override
        public void onClose(WatcherException cause) {
            assertTrue(cause.isHttpGone());
            closeLatch.countDown();
        }
    };
    // When
    try (Watch watch = client.pods().withName("pod1").withResourceVersion("1").watch(watcher)) {
        // Then
        assertNotNull(watch);
        assertTrue(deleteLatch.await(10, TimeUnit.SECONDS));
        assertTrue(closeLatch.await(10, TimeUnit.SECONDS));
    }
}
Also used : Pod(io.fabric8.kubernetes.api.model.Pod) Watch(io.fabric8.kubernetes.client.Watch) Watcher(io.fabric8.kubernetes.client.Watcher) WatchEvent(io.fabric8.kubernetes.api.model.WatchEvent) CountDownLatch(java.util.concurrent.CountDownLatch) WatcherException(io.fabric8.kubernetes.client.WatcherException) Test(org.junit.jupiter.api.Test) DisplayName(org.junit.jupiter.api.DisplayName)

Example 22 with Action

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

the class AuthorizationPolicyTest method testCreate.

@Test
@DisplayName("Should Create a AuthorizationPolicy Entry")
void testCreate() throws InterruptedException {
    AuthorizationPolicy service = new AuthorizationPolicyBuilder().withNewMetadata().withName("httpbin").endMetadata().withNewSpec().withSelector(new WorkloadSelectorBuilder().withMatchLabels(Collections.singletonMap("app", "httpbin")).build()).withAction(AuthorizationPolicyAction.DENY).withRules(new RuleBuilder().withFrom(new RuleFromBuilder().withSource(new SourceBuilder().withPrincipals("cluster.local/ns/default/sa/sleep").build()).build(), new RuleFromBuilder().withSource(new SourceBuilder().withNamespaces("dev").build()).build()).withTo(new RuleToBuilder().withOperation(new OperationBuilder().withMethods("GET").build()).build()).withWhen(new ConditionBuilder().withKey("request.auth.claims[iss]").withValues("https://accounts.google.com").build()).build()).endSpec().build();
    server.expect().post().withPath("/apis/security.istio.io/v1beta1/namespaces/ns2/authorizationpolicies").andReturn(HttpURLConnection.HTTP_OK, service).once();
    service = client.v1beta1().authorizationPolicies().inNamespace("ns2").create(service);
    assertNotNull(service);
    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("{\"apiVersion\":\"security.istio.io/v1beta1\"," + "\"kind\":\"AuthorizationPolicy\"," + "\"metadata\":{\"name\":\"httpbin\"}," + "\"spec\":{" + "\"action\":\"DENY\"," + "\"rules\":[" + "{\"from\":[{\"source\":{\"principals\":[\"cluster.local/ns/default/sa/sleep\"]}}," + "{\"source\":{\"namespaces\":[\"dev\"]}}]," + "\"to\":[{\"operation\":{\"methods\":[\"GET\"]}}]," + "\"when\":[{\"key\":\"request.auth.claims[iss]\",\"values\":[\"https://accounts.google.com\"]}]}]," + "\"selector\":{\"matchLabels\":{\"app\":\"httpbin\"}}}}", recordedRequest.getBody().readUtf8());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) AuthorizationPolicy(io.fabric8.istio.api.security.v1beta1.AuthorizationPolicy) AuthorizationPolicyBuilder(io.fabric8.istio.api.security.v1beta1.AuthorizationPolicyBuilder) OperationBuilder(io.fabric8.istio.api.security.v1beta1.OperationBuilder) ConditionBuilder(io.fabric8.istio.api.security.v1beta1.ConditionBuilder) RuleToBuilder(io.fabric8.istio.api.security.v1beta1.RuleToBuilder) SourceBuilder(io.fabric8.istio.api.security.v1beta1.SourceBuilder) RuleBuilder(io.fabric8.istio.api.security.v1beta1.RuleBuilder) RuleFromBuilder(io.fabric8.istio.api.security.v1beta1.RuleFromBuilder) WorkloadSelectorBuilder(io.fabric8.istio.api.type.v1beta1.WorkloadSelectorBuilder) Test(org.junit.jupiter.api.Test) DisplayName(org.junit.jupiter.api.DisplayName)

Example 23 with Action

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

the class AbstractWatchManager method onMessage.

protected void onMessage(String message) {
    try {
        WatchEvent event = readWatchEvent(message);
        Object object = event.getObject();
        if (object instanceof Status) {
            Status status = (Status) object;
            onStatus(status);
        } else if (object instanceof KubernetesResourceList) {
            // Dirty cast - should always be valid though
            KubernetesResourceList list = (KubernetesResourceList) object;
            updateResourceVersion(list.getMetadata().getResourceVersion());
            Action action = Action.valueOf(event.getType());
            List<HasMetadata> items = list.getItems();
            if (items != null) {
                for (HasMetadata item : items) {
                    eventReceived(action, item);
                }
            }
        } else if (object instanceof HasMetadata) {
            @SuppressWarnings("unchecked") T obj = (T) object;
            updateResourceVersion(obj.getMetadata().getResourceVersion());
            Action action = Action.valueOf(event.getType());
            eventReceived(action, obj);
        } else {
            logger.error("Unknown message received: {}", message);
        }
    } catch (ClassCastException e) {
        logger.error("Received wrong type of object for watch", e);
    } catch (IllegalArgumentException e) {
        logger.error("Invalid event type", e);
    } catch (Exception e) {
        logger.error("Unhandled exception encountered in watcher event handler", e);
    }
}
Also used : Action(io.fabric8.kubernetes.client.Watcher.Action) List(java.util.List) WatcherException(io.fabric8.kubernetes.client.WatcherException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) MalformedURLException(java.net.MalformedURLException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 24 with Action

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

the class GenericKubernetesResourceExample method main.

public static void main(String[] args) throws Exception {
    final ConfigBuilder configBuilder = new ConfigBuilder();
    configBuilder.withWatchReconnectInterval(500);
    configBuilder.withWatchReconnectLimit(5);
    try (KubernetesClient client = new KubernetesClientBuilder().withConfig(configBuilder.build()).build()) {
        String namespace = "default";
        CustomResourceDefinition prometheousRuleCrd = client.apiextensions().v1beta1().customResourceDefinitions().load(GenericKubernetesResourceExample.class.getResourceAsStream("/prometheous-rule-crd.yml")).get();
        client.apiextensions().v1beta1().customResourceDefinitions().createOrReplace(prometheousRuleCrd);
        logger.info("Successfully created Prometheous custom resource definition");
        // Creating Custom Resources Now:
        ResourceDefinitionContext crdContext = CustomResourceDefinitionContext.fromCrd(prometheousRuleCrd);
        client.load(GenericKubernetesResourceExample.class.getResourceAsStream("/prometheous-rule-cr.yml")).inNamespace(namespace).createOrReplace();
        logger.info("Created Custom Resource successfully too");
        // Listing all custom resources in given namespace:
        NonNamespaceOperation<GenericKubernetesResource, GenericKubernetesResourceList, Resource<GenericKubernetesResource>> resourcesInNamespace = client.genericKubernetesResources(crdContext).inNamespace(namespace);
        GenericKubernetesResourceList list = resourcesInNamespace.list();
        List<GenericKubernetesResource> items = list.getItems();
        logger.info("Custom Resources :- ");
        for (GenericKubernetesResource customResource : items) {
            ObjectMeta metadata = customResource.getMetadata();
            final String name = metadata.getName();
            logger.info(name);
        }
        // Watching custom resources now
        logger.info("Watching custom resources now");
        final CountDownLatch closeLatch = new CountDownLatch(1);
        resourcesInNamespace.watch(new Watcher<GenericKubernetesResource>() {

            @Override
            public void eventReceived(Action action, GenericKubernetesResource resource) {
                logger.info("{}: {}", action, resource);
            }

            @Override
            public void onClose(WatcherException e) {
                logger.debug("Watcher onClose");
                closeLatch.countDown();
                if (e != null) {
                    logger.error(e.getMessage(), e);
                }
            }
        });
        closeLatch.await(10, TimeUnit.MINUTES);
        // Cleanup
        logger.info("Deleting custom resources...");
        resourcesInNamespace.withName("prometheus-example-rules").delete();
        client.apiextensions().v1beta1().customResourceDefinitions().withName(prometheousRuleCrd.getMetadata().getName()).delete();
    } catch (KubernetesClientException e) {
        logger.error("Could not create resource: {}", e.getMessage(), e);
    }
}
Also used : ObjectMeta(io.fabric8.kubernetes.api.model.ObjectMeta) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) CustomResourceDefinition(io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) Resource(io.fabric8.kubernetes.client.dsl.Resource) CountDownLatch(java.util.concurrent.CountDownLatch) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) WatcherException(io.fabric8.kubernetes.client.WatcherException) CustomResourceDefinitionContext(io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext) ResourceDefinitionContext(io.fabric8.kubernetes.client.dsl.base.ResourceDefinitionContext) KubernetesClientBuilder(io.fabric8.kubernetes.client.KubernetesClientBuilder) GenericKubernetesResourceList(io.fabric8.kubernetes.api.model.GenericKubernetesResourceList) ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 25 with Action

use of io.fabric8.kubernetes.client.Watcher.Action in project helm-charts by hivemq.

the class HelmChartDeploymentIT method getWaitForClusterToBeReadyLatch.

/**
 * Return a count-down latch that will be decreased when the hivemq cluster is running.
 * The helm chart makes sure it is installed, and the operator makes sure the state is
 * update to running, we listen for this status change.
 *
 * @param kubeConfigYaml k3s yaml configuration for the container that is running and waiting for the Kubernetes artifacts to be ready
 */
private CountDownLatch getWaitForClusterToBeReadyLatch(@NotNull final String kubeConfigYaml) {
    Config config = Config.fromKubeconfig(kubeConfigYaml);
    DefaultKubernetesClient client = new DefaultKubernetesClient(config);
    final CountDownLatch closeLatch = new CountDownLatch(1);
    client.customResources(HiveMQInfo.class).watch(new Watcher<>() {

        @Override
        public void eventReceived(@NotNull Action action, @NotNull HiveMQInfo resource) {
            if (resource.getStatus() != null && resource.getStatus().getState() != null && resource.getStatus().getState() == HivemqClusterStatus.State.RUNNING) {
                closeLatch.countDown();
            }
        }

        @Override
        public void onClose(@NotNull WatcherException cause) {
            System.out.println("onClose");
        }
    });
    return closeLatch;
}
Also used : HiveMQInfo(com.hivemq.crd.hivemq.HiveMQInfo) Config(io.fabric8.kubernetes.client.Config) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) 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