Search in sources :

Example 71 with ApiException

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

the class PortForward method forward.

/**
 * PortForward to a container.
 *
 * @param namespace The namespace of the Pod
 * @param name The name of the Pod
 * @param ports The ports to forward
 * @return The result of the Port Forward request.
 */
public PortForwardResult forward(String namespace, String name, List<Integer> ports) throws ApiException, IOException {
    String path = makePath(namespace, name);
    WebSocketStreamHandler handler = new WebSocketStreamHandler();
    PortForwardResult result = new PortForwardResult(handler, ports);
    List<Pair> queryParams = new ArrayList<>(ports.size());
    for (Integer port : ports) {
        queryParams.add(new Pair("ports", port.toString()));
    }
    WebSockets.stream(path, "GET", queryParams, apiClient, handler);
    try {
        handler.waitForInitialized();
    } catch (InterruptedException ex) {
        throw new ApiException(ex);
    }
    Throwable err = handler.getError();
    if (err != null) {
        throw new ApiException(err);
    }
    // Wait for streams to start.
    result.init();
    return result;
}
Also used : WebSocketStreamHandler(io.kubernetes.client.util.WebSocketStreamHandler) ArrayList(java.util.ArrayList) Pair(io.kubernetes.client.openapi.Pair) ApiException(io.kubernetes.client.openapi.ApiException)

Example 72 with ApiException

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

the class PodLogs method streamNamespacedPodLog.

// Important note. You must close this stream or else you can leak connections.
public InputStream streamNamespacedPodLog(String namespace, String name, String container, Integer sinceSeconds, Integer tailLines, boolean timestamps) throws ApiException, IOException {
    Call call = coreClient.readNamespacedPodLogCall(name, namespace, container, true, null, null, "false", false, sinceSeconds, tailLines, timestamps, null);
    Response response = call.execute();
    if (!response.isSuccessful()) {
        throw new ApiException(response.code(), "Logs request failed: " + response.code());
    }
    return response.body().byteStream();
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) ApiException(io.kubernetes.client.openapi.ApiException)

Example 73 with ApiException

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

the class KubernetesKubectlCreateProcessor method postProcessAfterInitialization.

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (!(bean instanceof KubernetesObject)) {
        // no-op
        return bean;
    }
    KubectlCreate create = beanFactory.findAnnotationOnBean(beanName, KubectlCreate.class);
    if (create == null) {
        return bean;
    }
    Class<? extends KubernetesObject> apiTypeClass = (Class<? extends KubernetesObject>) bean.getClass();
    try {
        log.info("@KubectlCreate ensuring resource upon bean {}", beanName);
        return create(apiTypeClass, bean);
    } catch (KubectlException e) {
        if (e.getCause() instanceof ApiException) {
            ApiException apiException = (ApiException) e.getCause();
            if (HttpURLConnection.HTTP_CONFLICT == apiException.getCode()) {
                // already exists
                log.info("Skipped processing {} @KubectlCreate resource already exists", beanName);
                return bean;
            }
        }
        log.error("Failed ensuring resource from @KubectlCreate", e);
        throw new BeanCreationException("Failed ensuring resource from @KubectlCreate", e);
    }
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) KubernetesObject(io.kubernetes.client.common.KubernetesObject) KubectlException(io.kubernetes.client.extended.kubectl.exception.KubectlException) KubectlCreate(io.kubernetes.client.spring.extended.manifests.annotation.KubectlCreate) ApiException(io.kubernetes.client.openapi.ApiException)

Example 74 with ApiException

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

the class CSRUtils method waitUntilCertificateSigned.

/**
 * Wait until the CertificateSigningRequest is approved within a timeout of 30 minutes.
 *
 * @param apiClient the api client
 * @param csrObjectName the csr object name
 * @param retryInterval the retry interval
 * @param timeout the timeout
 * @return the byte [ ]
 * @throws CSRNotApprovedException the csr not approved exception
 */
public static byte[] waitUntilCertificateSigned(ApiClient apiClient, String csrObjectName, Duration retryInterval, Duration timeout) throws CSRNotApprovedException {
    CertificatesV1Api api = new CertificatesV1Api(apiClient);
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    try {
        AtomicReference<byte[]> certRef = new AtomicReference<>();
        boolean certificateSigned = Wait.poll(retryInterval, timeout, () -> {
            try {
                V1CertificateSigningRequest current = api.readCertificateSigningRequest(csrObjectName, null);
                CSRUtils.getCertificate(current).ifPresent(cert -> certRef.set(cert));
                return true;
            } catch (ApiException e) {
                LOG.info("Failed acquiring latest state of CertificateSigningRequest resource {} from the cluster", csrObjectName);
                return false;
            }
        });
        if (!certificateSigned) {
            LOG.error("Timeout exceed but the CertificateSigningRequest {} is not approved", csrObjectName);
            throw new CSRNotApprovedException("Timeout - CertificateSigningRequest not approved: " + csrObjectName);
        }
        LOG.info("Successfully acquired certificate from CertificateSigningRequest {}", csrObjectName);
        return certRef.get();
    } finally {
        service.shutdown();
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) CSRNotApprovedException(io.kubernetes.client.util.exception.CSRNotApprovedException) AtomicReference(java.util.concurrent.atomic.AtomicReference) V1CertificateSigningRequest(io.kubernetes.client.openapi.models.V1CertificateSigningRequest) CertificatesV1Api(io.kubernetes.client.openapi.apis.CertificatesV1Api) ApiException(io.kubernetes.client.openapi.ApiException)

Example 75 with ApiException

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

the class ReflectorRunnable method run.

/**
 * run first lists all items and get the resource version at the moment of call, and then use the
 * resource version to watch.
 */
public void run() {
    log.info("{}#Start listing and watching...", apiTypeClass);
    try {
        ApiListType list = listerWatcher.list(new CallGeneratorParams(Boolean.FALSE, getRelistResourceVersion(), null));
        V1ListMeta listMeta = list.getMetadata();
        String resourceVersion = listMeta.getResourceVersion();
        List<? extends KubernetesObject> items = list.getItems();
        if (log.isDebugEnabled()) {
            log.debug("{}#Extract resourceVersion {} list meta", apiTypeClass, resourceVersion);
        }
        this.syncWith(items, resourceVersion);
        this.lastSyncResourceVersion = resourceVersion;
        this.isLastSyncResourceVersionUnavailable = false;
        if (log.isDebugEnabled()) {
            log.debug("{}#Start watching with {}...", apiTypeClass, lastSyncResourceVersion);
        }
        while (true) {
            if (!isActive.get()) {
                closeWatch();
                return;
            }
            try {
                if (log.isDebugEnabled()) {
                    log.debug("{}#Start watch with resource version {}", apiTypeClass, lastSyncResourceVersion);
                }
                long jitteredWatchTimeoutSeconds = Double.valueOf(REFLECTOR_WATCH_CLIENTSIDE_TIMEOUT.getSeconds() * (1 + Math.random())).longValue();
                Watchable<ApiType> newWatch = listerWatcher.watch(new CallGeneratorParams(Boolean.TRUE, lastSyncResourceVersion, Long.valueOf(jitteredWatchTimeoutSeconds).intValue()));
                synchronized (this) {
                    if (!isActive.get()) {
                        newWatch.close();
                        continue;
                    }
                    watch = newWatch;
                }
                watchHandler(newWatch);
            } catch (WatchExpiredException e) {
                // Watch calls were failed due to expired resource-version. Returning
                // to unwind the list-watch loops so that we can respawn a new round
                // of list-watching.
                log.info("{}#Watch expired, will re-list-watch soon", this.apiTypeClass);
                return;
            } catch (Throwable t) {
                if (isConnectException(t)) {
                    // If this is "connection refused" error, it means that most likely
                    // apiserver is not responsive. It doesn't make sense to re-list all
                    // objects because most likely we will be able to restart watch where
                    // we ended. If that's the case wait and resend watch request.
                    log.info("{}#Watch get connect exception, retry watch", this.apiTypeClass);
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                    // no-op
                    }
                    continue;
                }
                if ((t instanceof RuntimeException) && t.getMessage() != null && t.getMessage().contains("IO Exception during hasNext")) {
                    log.info("{}#Read timeout retry list and watch", this.apiTypeClass);
                    // IO timeout should be taken as a normal case
                    return;
                }
                this.exceptionHandler.accept(apiTypeClass, t);
                return;
            } finally {
                closeWatch();
            }
        }
    } catch (ApiException e) {
        if (e.getCode() == HttpURLConnection.HTTP_GONE) {
            log.info("ResourceVersion {} expired, will retry w/o resourceVersion at the next time", getRelistResourceVersion());
            isLastSyncResourceVersionUnavailable = true;
        } else {
            this.exceptionHandler.accept(apiTypeClass, e);
        }
    } catch (Throwable t) {
        this.exceptionHandler.accept(apiTypeClass, t);
    }
}
Also used : CallGeneratorParams(io.kubernetes.client.util.CallGeneratorParams) V1ListMeta(io.kubernetes.client.openapi.models.V1ListMeta) WatchExpiredException(io.kubernetes.client.informer.exception.WatchExpiredException) 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