Search in sources :

Example 16 with CoreV1Api

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

Example 17 with CoreV1Api

use of io.kubernetes.client.openapi.apis.CoreV1Api in project twister2 by DSC-SPIDAL.

the class PodWatchUtils method createApiInstances.

private static void createApiInstances() {
    try {
        apiClient = io.kubernetes.client.util.Config.defaultClient();
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Exception when creating ApiClient: ", e);
        throw new RuntimeException(e);
    }
    OkHttpClient httpClient = apiClient.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
    apiClient.setHttpClient(httpClient);
    Configuration.setDefaultApiClient(apiClient);
    coreApi = new CoreV1Api(apiClient);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) IOException(java.io.IOException) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api)

Example 18 with CoreV1Api

use of io.kubernetes.client.openapi.apis.CoreV1Api in project twister2 by DSC-SPIDAL.

the class JobKillWatcher method run.

/**
 * start the watcher
 */
@Override
public void run() {
    String killParam = "KILL_JOB";
    String cmName = jobID;
    String labelSelector = KubernetesUtils.jobLabelSelector(jobID);
    Integer timeoutSeconds = Integer.MAX_VALUE;
    CoreV1Api v1Api = controller.createCoreV1Api();
    try {
        watcher = Watch.createWatch(controller.getApiClient(), v1Api.listNamespacedConfigMapCall(namespace, null, null, null, null, labelSelector, null, null, timeoutSeconds, Boolean.TRUE, null), new TypeToken<Watch.Response<V1ConfigMap>>() {
        }.getType());
    } catch (ApiException e) {
        String logMessage = "Exception when watching the ConfigMap: \n" + "exCode: " + e.getCode() + "\n" + "responseBody: " + e.getResponseBody();
        LOG.log(Level.SEVERE, logMessage, e);
        throw new RuntimeException(e);
    }
    try {
        for (Watch.Response<V1ConfigMap> item : watcher) {
            // it means that the pod is in the process of being deleted
            if (item.object != null && item.object.getData() != null && item.object.getMetadata().getName().equals(cmName) && item.object.getData().get(killParam) != null) {
                LOG.info("Job Kill parameter received. Killing the job");
                jobMaster.endJob(JobAPI.JobState.KILLED);
                return;
            }
        }
    } catch (RuntimeException e) {
        if (stopWatcher) {
            LOG.fine("Watcher is stopped.");
            return;
        } else {
            throw e;
        }
    } finally {
        try {
            watcher.close();
        } catch (IOException e) {
            LOG.warning("IOException when closing ConfigMapWatcher");
        }
    }
}
Also used : Watch(io.kubernetes.client.util.Watch) IOException(java.io.IOException) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) V1ConfigMap(io.kubernetes.client.openapi.models.V1ConfigMap) ApiException(io.kubernetes.client.openapi.ApiException)

Example 19 with CoreV1Api

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

the class K8sClient method createConfigMap.

/**
 * Create ConfigMap.
 * @param namespace The namespace where the ConfigMap should be created.
 * @param binding The cluster ConfigMap.
 * @return A future indicating the status of the ConfigMap operation.
 */
@SneakyThrows(ApiException.class)
public CompletableFuture<V1ConfigMap> createConfigMap(String namespace, V1ConfigMap binding) {
    CoreV1Api api = new CoreV1Api();
    K8AsyncCallback<V1ConfigMap> callback = new K8AsyncCallback<>("createConfigMap-" + binding.getMetadata().getName());
    api.createNamespacedConfigMapAsync(namespace, binding, PRETTY_PRINT, DRY_RUN, FIELD_MANAGER, callback);
    return exceptionallyExpecting(callback.getFuture(), isConflict, null);
}
Also used : CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) V1ConfigMap(io.kubernetes.client.openapi.models.V1ConfigMap) SneakyThrows(lombok.SneakyThrows)

Example 20 with CoreV1Api

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

the class K8sClient method getPodsWithLabels.

/**
 * Method to fetch all pods which match a set of labels.
 * @param namespace Namespace on which the pod(s) reside.
 * @param labels Name of the label.
 * @return Future representing the list of pod status.
 */
@SneakyThrows(ApiException.class)
public CompletableFuture<V1PodList> getPodsWithLabels(String namespace, Map<String, String> labels) {
    CoreV1Api api = new CoreV1Api();
    log.debug("Current number of http interceptors {}", api.getApiClient().getHttpClient().networkInterceptors().size());
    String labelSelector = labels.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining());
    K8AsyncCallback<V1PodList> callback = new K8AsyncCallback<>("listPods-" + labels);
    api.listNamespacedPodAsync(namespace, PRETTY_PRINT, ALLOW_WATCH_BOOKMARKS, null, null, labelSelector, null, null, null, false, callback);
    return callback.getFuture();
}
Also used : PodLogs(io.kubernetes.client.PodLogs) TypeToken(com.google.gson.reflect.TypeToken) SneakyThrows(lombok.SneakyThrows) Retry(io.pravega.common.util.Retry) V1beta1CustomResourceDefinition(io.kubernetes.client.openapi.models.V1beta1CustomResourceDefinition) Cleanup(lombok.Cleanup) V1PodList(io.kubernetes.client.openapi.models.V1PodList) V1PodStatus(io.kubernetes.client.openapi.models.V1PodStatus) TestFrameworkException(io.pravega.test.system.framework.TestFrameworkException) ApiextensionsV1beta1Api(io.kubernetes.client.openapi.apis.ApiextensionsV1beta1Api) Futures.exceptionallyExpecting(io.pravega.common.concurrent.Futures.exceptionallyExpecting) V1beta1ClusterRole(io.kubernetes.client.openapi.models.V1beta1ClusterRole) V1Patch(io.kubernetes.client.custom.V1Patch) Configuration(io.kubernetes.client.openapi.Configuration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) V1beta1ClusterRoleBinding(io.kubernetes.client.openapi.models.V1beta1ClusterRoleBinding) V1ServiceAccount(io.kubernetes.client.openapi.models.V1ServiceAccount) V1DeleteOptions(io.kubernetes.client.openapi.models.V1DeleteOptions) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) V1Secret(io.kubernetes.client.openapi.models.V1Secret) CONFLICT(javax.ws.rs.core.Response.Status.CONFLICT) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) RbacAuthorizationV1beta1Api(io.kubernetes.client.openapi.apis.RbacAuthorizationV1beta1Api) V1Status(io.kubernetes.client.openapi.models.V1Status) Collectors(java.util.stream.Collectors) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Optional(java.util.Optional) ApiCallback(io.kubernetes.client.openapi.ApiCallback) PatchUtils(io.kubernetes.client.util.PatchUtils) Futures(io.pravega.common.concurrent.Futures) V1Deployment(io.kubernetes.client.openapi.models.V1Deployment) Exceptions(io.pravega.common.Exceptions) Watch(io.kubernetes.client.util.Watch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AppsV1Api(io.kubernetes.client.openapi.apis.AppsV1Api) ApiClient(io.kubernetes.client.openapi.ApiClient) ApiException(io.kubernetes.client.openapi.ApiException) V1ConfigMap(io.kubernetes.client.openapi.models.V1ConfigMap) V1ContainerStateTerminated(io.kubernetes.client.openapi.models.V1ContainerStateTerminated) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) V1ContainerStatus(io.kubernetes.client.openapi.models.V1ContainerStatus) V1Namespace(io.kubernetes.client.openapi.models.V1Namespace) V1beta1Role(io.kubernetes.client.openapi.models.V1beta1Role) JsonSyntaxException(com.google.gson.JsonSyntaxException) Files(java.nio.file.Files) CustomObjectsApi(io.kubernetes.client.openapi.apis.CustomObjectsApi) IOException(java.io.IOException) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) Config(io.kubernetes.client.util.Config) TimeUnit(java.util.concurrent.TimeUnit) ConnectionFailed(io.pravega.test.system.framework.TestFrameworkException.Type.ConnectionFailed) Paths(java.nio.file.Paths) V1ContainerState(io.kubernetes.client.openapi.models.V1ContainerState) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) V1beta1RoleBinding(io.kubernetes.client.openapi.models.V1beta1RoleBinding) SECONDS(java.util.concurrent.TimeUnit.SECONDS) V1Pod(io.kubernetes.client.openapi.models.V1Pod) InputStream(java.io.InputStream) V1PodList(io.kubernetes.client.openapi.models.V1PodList) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) SneakyThrows(lombok.SneakyThrows)

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