Search in sources :

Example 6 with ApiException

use of io.kubernetes.client.openapi.ApiException in project pravega by pravega.

the class K8sClient method downloadLogs.

/**
 * Download logs of the specified pod.
 *
 * @param fromPod Pod logs to be copied.
 * @param toFile Destination file of the logs.
 * @return A Future which completes once the download operation completes.
 */
public CompletableFuture<Void> downloadLogs(final V1Pod fromPod, final String toFile) {
    final AtomicInteger retryCount = new AtomicInteger(0);
    return Retry.withExpBackoff(LOG_DOWNLOAD_INIT_DELAY_MS, 10, LOG_DOWNLOAD_RETRY_COUNT, RETRY_MAX_DELAY_MS).retryingOn(TestFrameworkException.class).throwingOn(RuntimeException.class).runInExecutor(() -> {
        final String podName = fromPod.getMetadata().getName();
        log.debug("Download logs from pod {}", podName);
        try {
            @Cleanup InputStream logStream = logUtility.streamNamespacedPodLog(fromPod);
            // On every retry this method attempts to download the complete pod logs from from K8s api-server. Due to the
            // amount of logs for a pod and the K8s cluster configuration it can so happen that the K8s api-server can
            // return truncated logs. Hence, every retry attempt does not overwrite the previously downloaded logs for
            // the pod.
            String logFile = toFile + "-" + retryCount.incrementAndGet() + ".log";
            Files.copy(logStream, Paths.get(logFile));
            log.info("Logs downloaded from pod {} to {}", podName, logFile);
        } catch (ApiException | IOException e) {
            log.warn("Retryable error while downloading logs from pod {}. Error message: {} ", podName, e.getMessage());
            throw new TestFrameworkException(TestFrameworkException.Type.RequestFailed, "Error while downloading logs");
        }
    }, executor);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestFrameworkException(io.pravega.test.system.framework.TestFrameworkException) InputStream(java.io.InputStream) IOException(java.io.IOException) Cleanup(lombok.Cleanup) ApiException(io.kubernetes.client.openapi.ApiException)

Example 7 with ApiException

use of io.kubernetes.client.openapi.ApiException in project pravega by pravega.

the class K8sClient method createAndUpdateCustomObject.

/**
 * This is used to update a custom object. This is useful to modify the custom object configuration, number of
 * instances is one type of configuration. If the object does not exist then a new object is created.
 * @param customResourceGroup Custom resource group.
 * @param version version.
 * @param namespace Namespace.
 * @param plural Plural of the CRD.
 * @param request Actual request.
 * @return A Future representing the status of create/update.
 */
@SuppressWarnings("unchecked")
public CompletableFuture<Object> createAndUpdateCustomObject(String customResourceGroup, String version, String namespace, String plural, Map<String, Object> request) {
    CustomObjectsApi api = new CustomObjectsApi();
    // Fetch the name of the custom object.
    String name = ((Map<String, String>) request.get("metadata")).get("name");
    return getCustomObject(customResourceGroup, version, namespace, plural, name).thenCompose(o -> {
        log.info("Instance {} of custom resource {}  exists, update it with the new request", name, customResourceGroup);
        try {
            // patch object
            K8AsyncCallback<Object> cb1 = new K8AsyncCallback<>("patchCustomObject");
            PatchUtils.patch(CustomObjectsApi.class, () -> api.patchNamespacedCustomObjectCall(customResourceGroup, version, namespace, plural, name, request, cb1), V1Patch.PATCH_FORMAT_JSON_MERGE_PATCH);
            return cb1.getFuture();
        } catch (ApiException e) {
            throw Exceptions.sneakyThrow(e);
        }
    }).exceptionally(t -> {
        log.warn("Exception while trying to fetch instance {} of custom resource {}, try to create it. Details: {}", name, customResourceGroup, t.getMessage());
        try {
            // create object
            K8AsyncCallback<Object> cb = new K8AsyncCallback<>("createCustomObject");
            api.createNamespacedCustomObjectAsync(customResourceGroup, version, namespace, plural, request, PRETTY_PRINT, cb);
            return cb.getFuture();
        } catch (ApiException e) {
            throw Exceptions.sneakyThrow(e);
        }
    });
}
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) CustomObjectsApi(io.kubernetes.client.openapi.apis.CustomObjectsApi) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) V1ConfigMap(io.kubernetes.client.openapi.models.V1ConfigMap) ApiException(io.kubernetes.client.openapi.ApiException)

Example 8 with ApiException

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

the class PatchExample method main.

public static void main(String[] args) throws IOException {
    try {
        AppsV1Api api = new AppsV1Api(ClientBuilder.standard().build());
        V1Deployment body = Configuration.getDefaultApiClient().getJSON().deserialize(jsonDeploymentStr, V1Deployment.class);
        // create a deployment
        V1Deployment deploy1 = api.createNamespacedDeployment("default", body, null, null, null, null);
        System.out.println("original deployment" + deploy1);
        // json-patch a deployment
        V1Deployment deploy2 = PatchUtils.patch(V1Deployment.class, () -> api.patchNamespacedDeploymentCall("hello-node", "default", new V1Patch(jsonPatchStr), null, null, null, // field-manager is optional
        null, null, null), V1Patch.PATCH_FORMAT_JSON_PATCH, api.getApiClient());
        System.out.println("json-patched deployment" + deploy2);
        // strategic-merge-patch a deployment
        V1Deployment deploy3 = PatchUtils.patch(V1Deployment.class, () -> api.patchNamespacedDeploymentCall("hello-node", "default", new V1Patch(strategicMergePatchStr), null, null, // field-manager is optional
        null, null, null, null), V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH, api.getApiClient());
        System.out.println("strategic-merge-patched deployment" + deploy3);
        // apply-yaml a deployment, server side apply is available by default after kubernetes v1.16
        // or opt-in by turning on the feature gate for v1.14 or v1.15.
        // https://kubernetes.io/docs/reference/using-api/api-concepts/#server-side-apply
        V1Deployment deploy4 = PatchUtils.patch(V1Deployment.class, () -> api.patchNamespacedDeploymentCall("hello-node", "default", new V1Patch(applyYamlStr), null, null, // field-manager is required for server-side apply
        "example-field-manager", null, true, null), V1Patch.PATCH_FORMAT_APPLY_YAML, api.getApiClient());
        System.out.println("application/apply-patch+yaml deployment" + deploy4);
    } catch (ApiException e) {
        System.out.println(e.getResponseBody());
        e.printStackTrace();
    }
}
Also used : V1Deployment(io.kubernetes.client.openapi.models.V1Deployment) AppsV1Api(io.kubernetes.client.openapi.apis.AppsV1Api) V1Patch(io.kubernetes.client.custom.V1Patch) ApiException(io.kubernetes.client.openapi.ApiException)

Example 9 with ApiException

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

the class KubectlAnnotate method execute.

@Override
public ApiType execute() throws KubectlException {
    verifyArguments();
    refreshDiscovery();
    final ApiType currentObj;
    if (isNamespaced(apiTypeClass)) {
        try {
            currentObj = getGenericApi().get(namespace, name).throwsApiException().getObject();
        } catch (ApiException e) {
            throw new KubectlException(e);
        }
    } else {
        try {
            currentObj = getGenericApi().get(name).throwsApiException().getObject();
        } catch (ApiException e) {
            throw new KubectlException(e);
        }
    }
    Annotations.addAnnotations(currentObj, addingAnnotations);
    final KubernetesApiResponse<ApiType> updateResponse;
    try {
        return getGenericApi().update(currentObj).throwsApiException().getObject();
    } catch (ApiException e) {
        throw new KubectlException(e);
    }
}
Also used : KubectlException(io.kubernetes.client.extended.kubectl.exception.KubectlException) ApiException(io.kubernetes.client.openapi.ApiException)

Example 10 with ApiException

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

the class LeaderElectorTest method deleteConfigMapLockResource.

private void deleteConfigMapLockResource() throws Exception {
    try {
        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
        coreV1Api.deleteNamespacedConfigMap(LOCK_RESOURCE_NAME, NAMESPACE, null, null, null, null, null, null);
    } catch (ApiException ex) {
        if (ex.getCode() != HttpURLConnection.HTTP_NOT_FOUND) {
            throw ex;
        }
    }
}
Also used : CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) ApiException(io.kubernetes.client.openapi.ApiException)

Aggregations

ApiException (io.kubernetes.client.openapi.ApiException)82 V1Pod (io.kubernetes.client.openapi.models.V1Pod)21 IOException (java.io.IOException)21 V1PodList (io.kubernetes.client.openapi.models.V1PodList)18 Test (org.junit.Test)18 CoreV1Api (io.kubernetes.client.openapi.apis.CoreV1Api)17 KubectlException (io.kubernetes.client.extended.kubectl.exception.KubectlException)14 V1ObjectMeta (io.kubernetes.client.openapi.models.V1ObjectMeta)13 ApiClient (io.kubernetes.client.openapi.ApiClient)10 AppsV1Api (io.kubernetes.client.openapi.apis.AppsV1Api)10 V1ConfigMap (io.kubernetes.client.openapi.models.V1ConfigMap)8 V1Deployment (io.kubernetes.client.openapi.models.V1Deployment)8 V1ListMeta (io.kubernetes.client.openapi.models.V1ListMeta)8 V1Status (io.kubernetes.client.openapi.models.V1Status)8 CallGeneratorParams (io.kubernetes.client.util.CallGeneratorParams)8 Watch (io.kubernetes.client.util.Watch)8 List (java.util.List)8 Configuration (io.kubernetes.client.openapi.Configuration)6 HashMap (java.util.HashMap)6 V1Patch (io.kubernetes.client.custom.V1Patch)5