Search in sources :

Example 11 with CoreV1Api

use of io.kubernetes.client.openapi.apis.CoreV1Api in project java by kubernetes-client.

the class KubeConfigFileClientExample method main.

public static void main(String[] args) throws IOException, ApiException {
    // file path to your KubeConfig
    String kubeConfigPath = System.getenv("HOME") + "/.kube/config";
    // loading the out-of-cluster config, a kubeconfig from file-system
    ApiClient client = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();
    // set the global default api-client to the in-cluster one from above
    Configuration.setDefaultApiClient(client);
    // the CoreV1Api loads default api-client from global configuration.
    CoreV1Api api = new CoreV1Api();
    // invokes the CoreV1Api client
    V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null, null);
    for (V1Pod item : list.getItems()) {
        System.out.println(item.getMetadata().getName());
    }
}
Also used : V1PodList(io.kubernetes.client.openapi.models.V1PodList) V1Pod(io.kubernetes.client.openapi.models.V1Pod) FileReader(java.io.FileReader) ApiClient(io.kubernetes.client.openapi.ApiClient) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api)

Example 12 with CoreV1Api

use of io.kubernetes.client.openapi.apis.CoreV1Api in project java by kubernetes-client.

the class PrometheusExample method main.

public static void main(String[] args) throws IOException, ApiException {
    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);
    // Install an HTTP Interceptor that adds metrics
    Monitoring.installMetrics(client);
    // Install a simple HTTP server to serve prometheus metrics. If you already are serving
    // metrics elsewhere, this is unnecessary.
    Monitoring.startMetricsServer("localhost", 8080);
    CoreV1Api api = new CoreV1Api();
    while (true) {
        // A request that should return 200
        V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null, null);
        // A request that should return 404
        try {
            V1Pod pod = api.readNamespacedPod("foo", "bar", null);
        } catch (ApiException ex) {
            if (ex.getCode() != 404) {
                throw ex;
            }
        }
        try {
            Thread.sleep(10000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}
Also used : V1PodList(io.kubernetes.client.openapi.models.V1PodList) V1Pod(io.kubernetes.client.openapi.models.V1Pod) ApiClient(io.kubernetes.client.openapi.ApiClient) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) ApiException(io.kubernetes.client.openapi.ApiException)

Example 13 with CoreV1Api

use of io.kubernetes.client.openapi.apis.CoreV1Api 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 14 with CoreV1Api

use of io.kubernetes.client.openapi.apis.CoreV1Api in project java by kubernetes-client.

the class PagerTest method testPaginationForNamespaceListWithBadTokenFailure.

@Test
public void testPaginationForNamespaceListWithBadTokenFailure() throws IOException {
    String status400Str = new String(Files.readAllBytes(Paths.get(STATUS_BAD_TOKEN_FILE_PATH)));
    CoreV1Api api = new CoreV1Api(client);
    stubFor(get(urlPathEqualTo("/api/v1/namespaces")).withQueryParam("limit", equalTo("1")).willReturn(aResponse().withStatus(400).withHeader("Content-Type", "application/json").withBody(status400Str)));
    Pager<V1Namespace, V1NamespaceList> pager = new Pager<V1Namespace, V1NamespaceList>((Pager.PagerParams param) -> {
        try {
            return api.listNamespaceCall(null, null, param.getContinueToken(), null, null, param.getLimit(), null, null, null, null, null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }, client, 1, V1NamespaceList.class);
    int count = 0;
    try {
        for (V1Namespace namespace : pager) {
            assertEquals("default", namespace.getMetadata().getName());
            count++;
        }
    } catch (Exception e) {
        assertEquals(status400Str, e.getMessage());
    }
    verify(getRequestedFor(urlPathEqualTo("/api/v1/namespaces")).withQueryParam("limit", equalTo("1")));
}
Also used : V1NamespaceList(io.kubernetes.client.openapi.models.V1NamespaceList) V1Namespace(io.kubernetes.client.openapi.models.V1Namespace) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) IOException(java.io.IOException) Test(org.junit.Test)

Example 15 with CoreV1Api

use of io.kubernetes.client.openapi.apis.CoreV1Api 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)

Aggregations

CoreV1Api (io.kubernetes.client.openapi.apis.CoreV1Api)48 V1Pod (io.kubernetes.client.openapi.models.V1Pod)18 ApiClient (io.kubernetes.client.openapi.ApiClient)16 Test (org.junit.Test)16 ApiException (io.kubernetes.client.openapi.ApiException)13 V1PodList (io.kubernetes.client.openapi.models.V1PodList)13 SneakyThrows (lombok.SneakyThrows)12 IOException (java.io.IOException)11 V1Namespace (io.kubernetes.client.openapi.models.V1Namespace)10 V1ObjectMeta (io.kubernetes.client.openapi.models.V1ObjectMeta)10 CallGeneratorParams (io.kubernetes.client.util.CallGeneratorParams)9 Watch (io.kubernetes.client.util.Watch)9 SharedInformerFactory (io.kubernetes.client.informer.SharedInformerFactory)8 JSON (io.kubernetes.client.openapi.JSON)6 V1Status (io.kubernetes.client.openapi.models.V1Status)6 OkHttpClient (okhttp3.OkHttpClient)6 V1Patch (io.kubernetes.client.custom.V1Patch)5 V1ConfigMap (io.kubernetes.client.openapi.models.V1ConfigMap)5 V1ListMeta (io.kubernetes.client.openapi.models.V1ListMeta)5 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5