Search in sources :

Example 11 with KubernetesInfrastructureException

use of org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException in project devspaces-images by redhat-developer.

the class KubernetesServices method create.

/**
 * Creates specified service.
 *
 * @param service service to create
 * @return created service
 * @throws InfrastructureException when any exception occurs
 */
public Service create(Service service) throws InfrastructureException {
    putLabel(service, CHE_WORKSPACE_ID_LABEL, workspaceId);
    putSelector(service, CHE_WORKSPACE_ID_LABEL, workspaceId);
    try {
        return clientFactory.create(workspaceId).services().inNamespace(namespace).create(service);
    } catch (KubernetesClientException e) {
        throw new KubernetesInfrastructureException(e);
    }
}
Also used : KubernetesInfrastructureException(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 12 with KubernetesInfrastructureException

use of org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException in project che-server by eclipse-che.

the class KubernetesDeploymentsTest method testDeletePodThrowingKubernetesClientExceptionShouldCloseWatch.

@Test
public void testDeletePodThrowingKubernetesClientExceptionShouldCloseWatch() throws Exception {
    final String POD_NAME = "nonExistingPod";
    doReturn(podResource).when(podResource).withPropagationPolicy(eq(BACKGROUND));
    doThrow(KubernetesClientException.class).when(podResource).delete();
    Watch watch = mock(Watch.class);
    doReturn(watch).when(podResource).watch(any());
    try {
        new KubernetesDeployments("", "", clientFactory, executor).doDeletePod(POD_NAME).get(5, TimeUnit.SECONDS);
    } catch (KubernetesInfrastructureException e) {
        assertTrue(e.getCause() instanceof KubernetesClientException);
        verify(watch).close();
        return;
    }
    fail("The exception should have been rethrown");
}
Also used : Watch(io.fabric8.kubernetes.client.Watch) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) KubernetesInfrastructureException(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) Test(org.testng.annotations.Test)

Example 13 with KubernetesInfrastructureException

use of org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException in project che-server by eclipse-che.

the class KubernetesDeployments method watchEvents.

/**
 * Registers a specified handler for handling events about changes in pods containers. Registering
 * several handlers doesn't create multiple websocket connections, so it is efficient to call this
 * method several times instead of using composite handler to combine other handlers.
 *
 * @param handler pod container events handler
 * @throws InfrastructureException if any error occurs while watcher starting
 */
public void watchEvents(PodEventHandler handler) throws InfrastructureException {
    if (containerWatch == null) {
        final Watcher<Event> watcher = new Watcher<>() {

            @Override
            public void eventReceived(Action action, Event event) {
                ObjectReference involvedObject = event.getInvolvedObject();
                if (POD_OBJECT_KIND.equals(involvedObject.getKind()) || REPLICASET_OBJECT_KIND.equals(involvedObject.getKind()) || DEPLOYMENT_OBJECT_KIND.equals(involvedObject.getKind())) {
                    String podName = involvedObject.getName();
                    String lastTimestamp = event.getLastTimestamp();
                    if (lastTimestamp == null) {
                        String firstTimestamp = event.getFirstTimestamp();
                        if (firstTimestamp != null) {
                            // Done in the same way like it made in
                            // https://github.com/kubernetes/kubernetes/pull/86557
                            lastTimestamp = firstTimestamp;
                        } else {
                            LOG.debug("lastTimestamp and firstTimestamp are undefined. Event: {}.  Fallback to the current time.", event);
                            lastTimestamp = PodEvents.convertDateToEventTimestamp(new Date());
                        }
                    }
                    PodEvent podEvent = new PodEvent(podName, getContainerName(involvedObject.getFieldPath()), event.getReason(), event.getMessage(), event.getMetadata().getCreationTimestamp(), lastTimestamp);
                    try {
                        if (happenedAfterWatcherInitialization(podEvent)) {
                            containerEventsHandlers.forEach(h -> h.handle(podEvent));
                        }
                    } catch (ParseException e) {
                        LOG.error("Failed to parse last timestamp of the event. Cause: {}. Event: {}", e.getMessage(), podEvent, e);
                    }
                }
            }

            @Override
            public void onClose(WatcherException ignored) {
            }

            /**
             * Returns the container name if the event is related to container. When the event is
             * related to container `fieldPath` field contain information in the following format:
             * `spec.container{web}`, where `web` is container name
             */
            private String getContainerName(String fieldPath) {
                String containerName = null;
                if (fieldPath != null) {
                    Matcher containerFieldMatcher = CONTAINER_FIELD_PATH_PATTERN.matcher(fieldPath);
                    if (containerFieldMatcher.matches()) {
                        containerName = containerFieldMatcher.group(CONTAINER_NAME_GROUP);
                    }
                }
                return containerName;
            }

            /**
             * Returns true if 'lastTimestamp' of the event is *after* the time of the watcher
             * initialization
             */
            private boolean happenedAfterWatcherInitialization(PodEvent event) throws ParseException {
                String eventLastTimestamp = event.getLastTimestamp();
                Date eventLastTimestampDate = PodEvents.convertEventTimestampToDate(eventLastTimestamp);
                return eventLastTimestampDate.after(watcherInitializationDate);
            }
        };
        try {
            watcherInitializationDate = new Date();
            containerWatch = clientFactory.create(workspaceId).v1().events().inNamespace(namespace).watch(watcher);
        } catch (KubernetesClientException ex) {
            throw new KubernetesInfrastructureException(ex);
        }
    }
    containerEventsHandlers.add(handler);
}
Also used : Matcher(java.util.regex.Matcher) Watcher(io.fabric8.kubernetes.client.Watcher) LogWatcher(org.eclipse.che.workspace.infrastructure.kubernetes.namespace.log.LogWatcher) PodEvent(org.eclipse.che.workspace.infrastructure.kubernetes.namespace.event.PodEvent) KubernetesInfrastructureException(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException) Date(java.util.Date) WatcherException(io.fabric8.kubernetes.client.WatcherException) LocalObjectReference(io.fabric8.kubernetes.api.model.LocalObjectReference) ObjectReference(io.fabric8.kubernetes.api.model.ObjectReference) Event(io.fabric8.kubernetes.api.model.Event) PodEvent(org.eclipse.che.workspace.infrastructure.kubernetes.namespace.event.PodEvent) ParseException(java.text.ParseException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 14 with KubernetesInfrastructureException

use of org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException in project che-server by eclipse-che.

the class KubernetesDeployments method delete.

/**
 * Deletes all existing pods and the Deployments that control them.
 *
 * <p>Note that this method will mark Kubernetes pods as interrupted and then will wait until all
 * pods will be killed.
 *
 * @throws InfrastructureException when {@link Thread} is interrupted while command executing
 * @throws InfrastructureException when pods removal timeout is reached
 * @throws InfrastructureException when any other exception occurs
 */
public void delete() throws InfrastructureException {
    try {
        final List<CompletableFuture<Void>> deleteFutures = new ArrayList<>();
        // We first delete all deployments, then clean up any bare Pods.
        List<Deployment> deployments = clientFactory.create(workspaceId).apps().deployments().inNamespace(namespace).withLabel(CHE_WORKSPACE_ID_LABEL, workspaceId).list().getItems();
        for (Deployment deployment : deployments) {
            deleteFutures.add(doDeleteDeployment(deployment.getMetadata().getName()));
        }
        // We have to be careful to not include pods that are controlled by a deployment
        List<Pod> pods = clientFactory.create(workspaceId).pods().inNamespace(namespace).withLabel(CHE_WORKSPACE_ID_LABEL, workspaceId).withoutLabel(CHE_DEPLOYMENT_NAME_LABEL).list().getItems();
        for (Pod pod : pods) {
            List<OwnerReference> ownerReferences = pod.getMetadata().getOwnerReferences();
            if (ownerReferences == null || ownerReferences.isEmpty()) {
                deleteFutures.add(doDeletePod(pod.getMetadata().getName()));
            }
        }
        final CompletableFuture<Void> removed = allOf(deleteFutures.toArray(new CompletableFuture[deleteFutures.size()]));
        try {
            removed.get(POD_REMOVAL_TIMEOUT_MIN, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new InfrastructureException("Interrupted while waiting for pod removal. " + e.getMessage());
        } catch (ExecutionException e) {
            throw new InfrastructureException("Error occurred while waiting for pod removing. " + e.getMessage());
        } catch (TimeoutException ex) {
            throw new InfrastructureException("Pods removal timeout reached " + ex.getMessage());
        }
    } catch (KubernetesClientException e) {
        throw new KubernetesInfrastructureException(e);
    }
}
Also used : Pod(io.fabric8.kubernetes.api.model.Pod) ArrayList(java.util.ArrayList) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) KubernetesInfrastructureException(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException) CompletableFuture(java.util.concurrent.CompletableFuture) OwnerReference(io.fabric8.kubernetes.api.model.OwnerReference) ExecutionException(java.util.concurrent.ExecutionException) KubernetesInfrastructureException(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) TimeoutException(java.util.concurrent.TimeoutException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 15 with KubernetesInfrastructureException

use of org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException in project che-server by eclipse-che.

the class KubernetesDeployments method exec.

/**
 * Executes command in specified container.
 *
 * @param name pod name (or name of deployment containing pod) where command will be executed
 * @param containerName container name where command will be executed
 * @param timeoutMin timeout to wait until process will be done
 * @param command command to execute
 * @throws InfrastructureException when specified timeout is reached
 * @throws InfrastructureException when {@link Thread} is interrupted while command executing
 * @throws InfrastructureException when any other exception occurs
 */
public void exec(String name, String containerName, int timeoutMin, String[] command) throws InfrastructureException {
    final String podName = getPodName(name);
    final ExecWatchdog watchdog = new ExecWatchdog();
    try (ExecWatch watch = clientFactory.create(workspaceId).pods().inNamespace(namespace).withName(podName).inContainer(containerName).redirectingError().usingListener(watchdog).exec(encode(command))) {
        try {
            watchdog.wait(timeoutMin, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new InfrastructureException(e.getMessage(), e);
        }
    } catch (KubernetesClientException e) {
        throw new KubernetesInfrastructureException(e);
    }
}
Also used : ExecWatch(io.fabric8.kubernetes.client.dsl.ExecWatch) KubernetesInfrastructureException(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException) KubernetesInfrastructureException(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Aggregations

KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)36 KubernetesInfrastructureException (org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException)36 InfrastructureException (org.eclipse.che.api.workspace.server.spi.InfrastructureException)26 Watch (io.fabric8.kubernetes.client.Watch)22 CompletableFuture (java.util.concurrent.CompletableFuture)20 ExecutionException (java.util.concurrent.ExecutionException)18 TimeoutException (java.util.concurrent.TimeoutException)18 WatcherException (io.fabric8.kubernetes.client.WatcherException)16 ExecWatch (io.fabric8.kubernetes.client.dsl.ExecWatch)12 Pod (io.fabric8.kubernetes.api.model.Pod)10 Watcher (io.fabric8.kubernetes.client.Watcher)6 ParseException (java.text.ParseException)6 InternalInfrastructureException (org.eclipse.che.api.workspace.server.spi.InternalInfrastructureException)6 Deployment (io.fabric8.kubernetes.api.model.apps.Deployment)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)4 Test (org.testng.annotations.Test)4 Event (io.fabric8.kubernetes.api.model.Event)2 LocalObjectReference (io.fabric8.kubernetes.api.model.LocalObjectReference)2 Namespace (io.fabric8.kubernetes.api.model.Namespace)2