Search in sources :

Example 1 with CallGeneratorParams

use of io.kubernetes.client.util.CallGeneratorParams in project java by kubernetes-client.

the class InformerExample method main.

public static void main(String[] args) throws Exception {
    CoreV1Api coreV1Api = new CoreV1Api();
    ApiClient apiClient = coreV1Api.getApiClient();
    OkHttpClient httpClient = apiClient.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
    apiClient.setHttpClient(httpClient);
    SharedInformerFactory factory = new SharedInformerFactory(apiClient);
    // Node informer
    SharedIndexInformer<V1Node> nodeInformer = factory.sharedIndexInformerFor(// the informer-factory.
    (CallGeneratorParams params) -> {
        return coreV1Api.listNodeCall(null, null, null, null, null, null, params.resourceVersion, null, params.timeoutSeconds, params.watch, null);
    }, V1Node.class, V1NodeList.class);
    nodeInformer.addEventHandler(new ResourceEventHandler<V1Node>() {

        @Override
        public void onAdd(V1Node node) {
            System.out.printf("%s node added!\n", node.getMetadata().getName());
        }

        @Override
        public void onUpdate(V1Node oldNode, V1Node newNode) {
            System.out.printf("%s => %s node updated!\n", oldNode.getMetadata().getName(), newNode.getMetadata().getName());
        }

        @Override
        public void onDelete(V1Node node, boolean deletedFinalStateUnknown) {
            System.out.printf("%s node deleted!\n", node.getMetadata().getName());
        }
    });
    factory.startAllRegisteredInformers();
    V1Node nodeToCreate = new V1Node();
    V1ObjectMeta metadata = new V1ObjectMeta();
    metadata.setName("noxu");
    nodeToCreate.setMetadata(metadata);
    V1Node createdNode = coreV1Api.createNode(nodeToCreate, null, null, null, null);
    Thread.sleep(3000);
    Lister<V1Node> nodeLister = new Lister<V1Node>(nodeInformer.getIndexer());
    V1Node node = nodeLister.get("noxu");
    System.out.printf("noxu created! %s\n", node.getMetadata().getCreationTimestamp());
    factory.stopAllRegisteredInformers();
    Thread.sleep(3000);
    System.out.println("informer stopped..");
}
Also used : OkHttpClient(okhttp3.OkHttpClient) V1Node(io.kubernetes.client.openapi.models.V1Node) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) Lister(io.kubernetes.client.informer.cache.Lister) ApiClient(io.kubernetes.client.openapi.ApiClient) CallGeneratorParams(io.kubernetes.client.util.CallGeneratorParams) SharedInformerFactory(io.kubernetes.client.informer.SharedInformerFactory) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api)

Example 2 with CallGeneratorParams

use of io.kubernetes.client.util.CallGeneratorParams in project java by kubernetes-client.

the class DefaultControllerBuilderTest method testBuildWatchShouldWorkIfInformerPresent.

@Test
public void testBuildWatchShouldWorkIfInformerPresent() {
    CoreV1Api api = new CoreV1Api();
    informerFactory.sharedIndexInformerFor((CallGeneratorParams params) -> {
        return api.listPodForAllNamespacesCall(null, null, null, null, null, null, params.resourceVersion, null, params.timeoutSeconds, params.watch, null);
    }, V1Pod.class, V1PodList.class);
    ControllerBuilder.defaultBuilder(informerFactory).watch((workQueue) -> ControllerBuilder.controllerWatchBuilder(V1Pod.class, workQueue).build()).withReconciler(new Reconciler() {

        @Override
        public Result reconcile(Request request) {
            return new Result(false);
        }
    }).build();
}
Also used : Reconciler(io.kubernetes.client.extended.controller.reconciler.Reconciler) Request(io.kubernetes.client.extended.controller.reconciler.Request) CallGeneratorParams(io.kubernetes.client.util.CallGeneratorParams) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) Result(io.kubernetes.client.extended.controller.reconciler.Result) Test(org.junit.Test)

Example 3 with CallGeneratorParams

use of io.kubernetes.client.util.CallGeneratorParams in project java by kubernetes-client.

the class ReflectorRunnableTest method testReflectorRelistShouldHonorLastSyncResourceVersion.

@Test
public void testReflectorRelistShouldHonorLastSyncResourceVersion() {
    String expectedResourceVersion = "999";
    AtomicReference<String> requestedResourceVersion = new AtomicReference<>();
    ReflectorRunnable<V1Pod, V1PodList> reflectorRunnable = new ReflectorRunnable<>(V1Pod.class, new ListerWatcher<V1Pod, V1PodList>() {

        @Override
        public V1PodList list(CallGeneratorParams params) throws ApiException {
            requestedResourceVersion.set(params.resourceVersion);
            return new V1PodList().metadata(new V1ListMeta().resourceVersion(expectedResourceVersion));
        }

        @Override
        public Watchable<V1Pod> watch(CallGeneratorParams params) throws ApiException {
            throw new ApiException("HTTP GONE");
        }
    }, deltaFIFO);
    // first run
    try {
        Thread thread = new Thread(reflectorRunnable::run);
        thread.setDaemon(true);
        thread.start();
        Awaitility.await().atMost(Duration.ofSeconds(1)).pollInterval(Duration.ofMillis(100)).until(() -> expectedResourceVersion.equals(reflectorRunnable.getLastSyncResourceVersion()));
    } finally {
        reflectorRunnable.stop();
    }
    // second run
    try {
        Thread thread = new Thread(reflectorRunnable::run);
        thread.setDaemon(true);
        thread.start();
        Awaitility.await().atMost(Duration.ofSeconds(1)).pollInterval(Duration.ofMillis(100)).untilAtomic(requestedResourceVersion, new IsEqual<>(expectedResourceVersion));
    } finally {
        reflectorRunnable.stop();
    }
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) CallGeneratorParams(io.kubernetes.client.util.CallGeneratorParams) V1ListMeta(io.kubernetes.client.openapi.models.V1ListMeta) V1PodList(io.kubernetes.client.openapi.models.V1PodList) Watchable(io.kubernetes.client.util.Watchable) V1Pod(io.kubernetes.client.openapi.models.V1Pod) ApiException(io.kubernetes.client.openapi.ApiException) Test(org.junit.Test)

Example 4 with CallGeneratorParams

use of io.kubernetes.client.util.CallGeneratorParams in project java by kubernetes-client.

the class DefaultSharedIndexInformerWireMockTest method testAllNamespacedPodInformerNormalBehavior.

@Test
public void testAllNamespacedPodInformerNormalBehavior() throws InterruptedException {
    CoreV1Api coreV1Api = new CoreV1Api(client);
    String startRV = "1000";
    String endRV = "1001";
    V1PodList podList = new V1PodList().metadata(new V1ListMeta().resourceVersion(startRV)).items(Arrays.asList());
    stubFor(get(urlPathEqualTo("/api/v1/pods")).withQueryParam("watch", equalTo("false")).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(new JSON().serialize(podList))));
    Watch.Response<V1Pod> watchResponse = new Watch.Response<>(EventType.ADDED.name(), new V1Pod().metadata(new V1ObjectMeta().namespace(namespace).name(podName).resourceVersion(endRV).labels(Collections.singletonMap("foo", "bar")).annotations(Collections.singletonMap("foo", "bar"))));
    stubFor(get(urlPathEqualTo("/api/v1/pods")).withQueryParam("watch", equalTo("true")).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(new JSON().serialize(watchResponse))));
    SharedInformerFactory factory = new SharedInformerFactory();
    SharedIndexInformer<V1Pod> podInformer = factory.sharedIndexInformerFor((CallGeneratorParams params) -> {
        try {
            return coreV1Api.listPodForAllNamespacesCall(null, null, null, null, null, null, params.resourceVersion, null, params.timeoutSeconds, params.watch, null);
        } catch (ApiException e) {
            throw new RuntimeException(e);
        }
    }, V1Pod.class, V1PodList.class);
    podInformer.setTransform((obj) -> {
        // deepcopy
        String json = new JSON().serialize(obj);
        V1Pod pod = new JSON().deserialize(json, V1Pod.class);
        // remove pod annotations
        pod.getMetadata().setAnnotations(null);
        return pod;
    });
    AtomicBoolean foundExistingPod = new AtomicBoolean(false);
    AtomicBoolean transformed = new AtomicBoolean(false);
    AtomicBoolean setTransformAfterStarted = new AtomicBoolean(false);
    podInformer.addEventHandler(new ResourceEventHandler<V1Pod>() {

        @Override
        public void onAdd(V1Pod obj) {
            if (podName.equals(obj.getMetadata().getName()) && namespace.equals(obj.getMetadata().getNamespace())) {
                foundExistingPod.set(true);
            }
            V1ObjectMeta metadata = obj.getMetadata();
            // check if the object was transformed
            if (metadata.getLabels().get("foo").equals("bar") && metadata.getAnnotations() == null) {
                transformed.set(true);
            }
        }

        @Override
        public void onUpdate(V1Pod oldObj, V1Pod newObj) {
        }

        @Override
        public void onDelete(V1Pod obj, boolean deletedFinalStateUnknown) {
        }
    });
    factory.startAllRegisteredInformers();
    Thread.sleep(1000);
    // can not set transform func if the informer has started
    try {
        podInformer.setTransform((obj) -> new V1Pod());
        setTransformAfterStarted.set(true);
    } catch (IllegalStateException e) {
    }
    assertTrue(foundExistingPod.get());
    assertTrue(transformed.get());
    assertFalse(setTransformAfterStarted.get());
    assertEquals(endRV, podInformer.lastSyncResourceVersion());
    verify(1, getRequestedFor(urlPathEqualTo("/api/v1/pods")).withQueryParam("watch", equalTo("false")));
    verify(moreThan(1), getRequestedFor(urlPathEqualTo("/api/v1/pods")).withQueryParam("watch", equalTo("true")));
    factory.stopAllRegisteredInformers();
}
Also used : V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) JSON(io.kubernetes.client.openapi.JSON) CallGeneratorParams(io.kubernetes.client.util.CallGeneratorParams) V1ListMeta(io.kubernetes.client.openapi.models.V1ListMeta) V1PodList(io.kubernetes.client.openapi.models.V1PodList) WireMock.aResponse(com.github.tomakehurst.wiremock.client.WireMock.aResponse) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SharedInformerFactory(io.kubernetes.client.informer.SharedInformerFactory) Watch(io.kubernetes.client.util.Watch) V1Pod(io.kubernetes.client.openapi.models.V1Pod) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) ApiException(io.kubernetes.client.openapi.ApiException) Test(org.junit.Test)

Example 5 with CallGeneratorParams

use of io.kubernetes.client.util.CallGeneratorParams in project java by kubernetes-client.

the class DefaultSharedIndexInformerWireMockTest method testInformerReListWatchOnWatchConflict.

@Test
public void testInformerReListWatchOnWatchConflict() throws InterruptedException {
    CoreV1Api coreV1Api = new CoreV1Api(client);
    String startRV = "1000";
    V1PodList podList = new V1PodList().metadata(new V1ListMeta().resourceVersion(startRV)).items(Arrays.asList());
    stubFor(get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods")).withQueryParam("watch", equalTo("false")).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(new JSON().serialize(podList))));
    Watch.Response<V1Pod> watchResponse = new Watch.Response<>(EventType.ERROR.name(), new V1Status().apiVersion("v1").kind("Status").code(409));
    stubFor(get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods")).withQueryParam("watch", equalTo("true")).withQueryParam("resourceVersion", equalTo(startRV)).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(new JSON().serialize(watchResponse))));
    SharedInformerFactory factory = new SharedInformerFactory();
    SharedIndexInformer<V1Pod> podInformer = factory.sharedIndexInformerFor((CallGeneratorParams params) -> {
        try {
            return coreV1Api.listNamespacedPodCall(namespace, null, null, null, null, null, null, params.resourceVersion, null, params.timeoutSeconds, params.watch, null);
        } catch (ApiException e) {
            throw new RuntimeException(e);
        }
    }, V1Pod.class, V1PodList.class);
    factory.startAllRegisteredInformers();
    // Sleep mroe than 1s so that informer can perform multiple rounds of list-watch
    Thread.sleep(3000);
    verify(moreThan(1), getRequestedFor(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods")).withQueryParam("watch", equalTo("false")));
    verify(moreThan(1), getRequestedFor(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods")).withQueryParam("watch", equalTo("true")));
    factory.stopAllRegisteredInformers();
}
Also used : V1Status(io.kubernetes.client.openapi.models.V1Status) JSON(io.kubernetes.client.openapi.JSON) CallGeneratorParams(io.kubernetes.client.util.CallGeneratorParams) V1ListMeta(io.kubernetes.client.openapi.models.V1ListMeta) V1PodList(io.kubernetes.client.openapi.models.V1PodList) WireMock.aResponse(com.github.tomakehurst.wiremock.client.WireMock.aResponse) SharedInformerFactory(io.kubernetes.client.informer.SharedInformerFactory) Watch(io.kubernetes.client.util.Watch) V1Pod(io.kubernetes.client.openapi.models.V1Pod) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) ApiException(io.kubernetes.client.openapi.ApiException) Test(org.junit.Test)

Aggregations

CallGeneratorParams (io.kubernetes.client.util.CallGeneratorParams)13 CoreV1Api (io.kubernetes.client.openapi.apis.CoreV1Api)9 Test (org.junit.Test)9 SharedInformerFactory (io.kubernetes.client.informer.SharedInformerFactory)8 ApiException (io.kubernetes.client.openapi.ApiException)8 V1ListMeta (io.kubernetes.client.openapi.models.V1ListMeta)8 V1Pod (io.kubernetes.client.openapi.models.V1Pod)8 V1PodList (io.kubernetes.client.openapi.models.V1PodList)7 JSON (io.kubernetes.client.openapi.JSON)6 Watch (io.kubernetes.client.util.Watch)6 V1ObjectMeta (io.kubernetes.client.openapi.models.V1ObjectMeta)5 WireMock.aResponse (com.github.tomakehurst.wiremock.client.WireMock.aResponse)4 Reconciler (io.kubernetes.client.extended.controller.reconciler.Reconciler)3 Request (io.kubernetes.client.extended.controller.reconciler.Request)3 Result (io.kubernetes.client.extended.controller.reconciler.Result)3 ApiClient (io.kubernetes.client.openapi.ApiClient)3 V1Status (io.kubernetes.client.openapi.models.V1Status)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 Controller (io.kubernetes.client.extended.controller.Controller)2 SharedIndexInformer (io.kubernetes.client.informer.SharedIndexInformer)2