Search in sources :

Example 66 with InfrastructureException

use of org.eclipse.che.api.workspace.server.spi.InfrastructureException in project devspaces-images by redhat-developer.

the class AsyncStoragePodInterceptor method deleteAsyncStoragePod.

private CompletableFuture<Void> deleteAsyncStoragePod(PodResource<Pod> podResource) throws InfrastructureException {
    Watch toCloseOnException = null;
    try {
        final CompletableFuture<Void> deleteFuture = new CompletableFuture<>();
        final Watch watch = podResource.watch(new DeleteWatcher<>(deleteFuture));
        toCloseOnException = watch;
        Boolean deleteSucceeded = podResource.withPropagationPolicy(BACKGROUND).delete();
        if (deleteSucceeded == null || !deleteSucceeded) {
            deleteFuture.complete(null);
        }
        return deleteFuture.whenComplete((v, e) -> {
            if (e != null) {
                LOG.warn("Failed to remove pod {} cause {}", ASYNC_STORAGE, e.getMessage());
            }
            watch.close();
        });
    } catch (KubernetesClientException e) {
        if (toCloseOnException != null) {
            toCloseOnException.close();
        }
        throw new KubernetesInfrastructureException(e);
    } catch (Exception e) {
        if (toCloseOnException != null) {
            toCloseOnException.close();
        }
        throw e;
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Watch(io.fabric8.kubernetes.client.Watch) KubernetesInfrastructureException(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException) TimeoutException(java.util.concurrent.TimeoutException) WatcherException(io.fabric8.kubernetes.client.WatcherException) KubernetesInfrastructureException(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) ExecutionException(java.util.concurrent.ExecutionException) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 67 with InfrastructureException

use of org.eclipse.che.api.workspace.server.spi.InfrastructureException in project devspaces-images by redhat-developer.

the class AsyncStorageProvisioner method provision.

public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException {
    if (!parseBoolean(k8sEnv.getAttributes().get(ASYNC_PERSIST_ATTRIBUTE))) {
        return;
    }
    if (!COMMON_STRATEGY.equals(pvcStrategy)) {
        String message = format("Workspace configuration not valid: Asynchronous storage available only for 'common' PVC strategy, but got %s", pvcStrategy);
        LOG.warn(message);
        k8sEnv.addWarning(new WarningImpl(4200, message));
        throw new InfrastructureException(message);
    }
    if (!isEphemeral(k8sEnv.getAttributes())) {
        String message = format("Workspace configuration not valid: Asynchronous storage available only if '%s' attribute set to false", PERSIST_VOLUMES_ATTRIBUTE);
        LOG.warn(message);
        k8sEnv.addWarning(new WarningImpl(4200, message));
        throw new InfrastructureException(message);
    }
    String namespace = identity.getInfrastructureNamespace();
    String userId = identity.getOwnerId();
    KubernetesClient k8sClient = kubernetesClientFactory.create(identity.getWorkspaceId());
    String configMapName = namespace + ASYNC_STORAGE_CONFIG;
    createPvcIfNotExist(k8sClient, namespace, userId);
    createConfigMapIfNotExist(k8sClient, namespace, configMapName, userId, k8sEnv);
    createAsyncStoragePodIfNotExist(k8sClient, namespace, configMapName, userId);
    createStorageServiceIfNotExist(k8sClient, namespace, userId);
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) WarningImpl(org.eclipse.che.api.workspace.server.model.impl.WarningImpl) IntOrString(io.fabric8.kubernetes.api.model.IntOrString) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException)

Example 68 with InfrastructureException

use of org.eclipse.che.api.workspace.server.spi.InfrastructureException in project devspaces-images by redhat-developer.

the class GatewayTlsProvisioner method useSecureProtocolForGatewayConfigMap.

private void useSecureProtocolForGatewayConfigMap(ConfigMap configMap) throws InfrastructureException {
    Map<String, ServerConfigImpl> servers = Annotations.newDeserializer(configMap.getMetadata().getAnnotations()).servers();
    if (servers.isEmpty()) {
        return;
    }
    if (servers.size() != 1) {
        throw new InfrastructureException("Expected exactly 1 server in Gateway configuration ConfigMap '" + configMap.getMetadata().getName() + "'. This is a bug, please report.");
    }
    Entry<String, ServerConfigImpl> serverConfigEntry = servers.entrySet().iterator().next();
    ServerConfigImpl serverConfig = serverConfigEntry.getValue();
    serverConfig.setProtocol(getSecureProtocol(serverConfig.getProtocol()));
    configMap.getMetadata().getAnnotations().putAll(Annotations.newSerializer().server(serverConfigEntry.getKey(), serverConfig).annotations());
}
Also used : ServerConfigImpl(org.eclipse.che.api.workspace.server.model.impl.ServerConfigImpl) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException)

Example 69 with InfrastructureException

use of org.eclipse.che.api.workspace.server.spi.InfrastructureException in project devspaces-images by redhat-developer.

the class FileSecretApplier method applySecret.

/**
 * Applies secret as file into workspace containers, respecting automount attribute and optional
 * devfile automount property and/or mount path override.
 *
 * @param env kubernetes environment with workspace containers configuration
 * @param runtimeIdentity identity of current runtime
 * @param secret source secret to apply
 * @throws InfrastructureException on misconfigured secrets or other apply error
 */
@Override
public void applySecret(KubernetesEnvironment env, RuntimeIdentity runtimeIdentity, Secret secret) throws InfrastructureException {
    final String secretMountPath = secret.getMetadata().getAnnotations().get(ANNOTATION_MOUNT_PATH);
    boolean secretAutomount = Boolean.parseBoolean(secret.getMetadata().getAnnotations().get(ANNOTATION_AUTOMOUNT));
    if (secretMountPath == null) {
        throw new InfrastructureException(format("Unable to mount secret '%s': It is configured to be mounted as a file but the mount path was not specified. Please define the '%s' annotation on the secret to specify it.", secret.getMetadata().getName(), ANNOTATION_MOUNT_PATH));
    }
    Volume volumeFromSecret = new VolumeBuilder().withName(secret.getMetadata().getName()).withSecret(new SecretVolumeSourceBuilder().withSecretName(secret.getMetadata().getName()).build()).build();
    for (PodData podData : env.getPodsData().values()) {
        if (!podData.getRole().equals(PodRole.DEPLOYMENT)) {
            continue;
        }
        if (podData.getSpec().getVolumes().stream().anyMatch(v -> v.getName().equals(volumeFromSecret.getName()))) {
            volumeFromSecret.setName(volumeFromSecret.getName() + "_" + NameGenerator.generate("", 6));
        }
        podData.getSpec().getVolumes().add(volumeFromSecret);
        for (Container container : podData.getSpec().getContainers()) {
            Optional<ComponentImpl> component = getComponent(env, container.getName());
            // skip components that explicitly disable automount
            if (component.isPresent() && isComponentAutomountFalse(component.get())) {
                continue;
            }
            // if automount disabled globally and not overridden in component
            if (!secretAutomount && (!component.isPresent() || !isComponentAutomountTrue(component.get()))) {
                continue;
            }
            // find path override if any
            Optional<String> overridePathOptional = Optional.empty();
            if (component.isPresent()) {
                overridePathOptional = getOverridenComponentPath(component.get(), secret.getMetadata().getName());
            }
            final String componentMountPath = overridePathOptional.orElse(secretMountPath);
            // remove the existing mount here to replace it with new one.
            if (k8sVersion.olderThan(1, 13)) {
                LOG.debug("Unable to mount multiple VolumeMounts on same path on this k8s version. Removing conflicting volumes in favor of secret mounts.");
                container.getVolumeMounts().removeIf(vm -> Paths.get(vm.getMountPath()).equals(Paths.get(componentMountPath)));
            }
            container.getVolumeMounts().addAll(secret.getData().keySet().stream().map(secretFile -> buildVolumeMount(volumeFromSecret, componentMountPath, secretFile)).collect(Collectors.toList()));
        }
    }
}
Also used : PodData(org.eclipse.che.workspace.infrastructure.kubernetes.environment.KubernetesEnvironment.PodData) SecretVolumeSourceBuilder(io.fabric8.kubernetes.api.model.SecretVolumeSourceBuilder) Container(io.fabric8.kubernetes.api.model.Container) Volume(io.fabric8.kubernetes.api.model.Volume) VolumeBuilder(io.fabric8.kubernetes.api.model.VolumeBuilder) ComponentImpl(org.eclipse.che.api.workspace.server.model.impl.devfile.ComponentImpl) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException)

Example 70 with InfrastructureException

use of org.eclipse.che.api.workspace.server.spi.InfrastructureException in project devspaces-images by redhat-developer.

the class GitCredentialStorageFileSecretApplier method applySecret.

@Override
public void applySecret(KubernetesEnvironment env, RuntimeIdentity runtimeIdentity, Secret secret) throws InfrastructureException {
    super.applySecret(env, runtimeIdentity, secret);
    final String secretMountPath = secret.getMetadata().getAnnotations().get(ANNOTATION_MOUNT_PATH);
    Set<String> keys = secret.getData().keySet();
    if (keys.size() != 1) {
        throw new InfrastructureException(format("Invalid git credential secret data. It should contain only 1 data item but it have %d", keys.size()));
    }
    Path gitSecretFilePath = Paths.get(secretMountPath, keys.iterator().next());
    ConfigMap gitConfigMap = env.getConfigMaps().get(GitConfigProvisioner.GIT_CONFIG_MAP_NAME);
    if (gitConfigMap != null) {
        Map<String, String> gitConfigMapData = gitConfigMap.getData();
        String gitConfig = gitConfigMapData.get(GitConfigProvisioner.GIT_CONFIG);
        if (gitConfig != null) {
            if (gitConfig.contains("helper = store --file") && gitConfig.contains("[credential]")) {
                throw new InfrastructureException(format("Multiple git credential secrets for user %s found in namespace %s. That may be caused by reinstalling product without user namespaces cleanup or using multiple instances of product with the same namespace namings template.", secret.getMetadata().getAnnotations().get(ANNOTATION_USER_NAME), secret.getMetadata().getNamespace()));
            }
            HashMap<String, String> newGitConfigMapData = new HashMap<>(gitConfigMapData);
            newGitConfigMapData.put(GitConfigProvisioner.GIT_CONFIG, gitConfig + String.format(GIT_CREDENTIALS_FILE_STORE_PATTERN, gitSecretFilePath.toString()));
            gitConfigMap.setData(newGitConfigMapData);
        }
    }
}
Also used : Path(java.nio.file.Path) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) HashMap(java.util.HashMap) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException)

Aggregations

InfrastructureException (org.eclipse.che.api.workspace.server.spi.InfrastructureException)242 InternalInfrastructureException (org.eclipse.che.api.workspace.server.spi.InternalInfrastructureException)64 Test (org.testng.annotations.Test)56 KubernetesInfrastructureException (org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException)44 RuntimeIdentity (org.eclipse.che.api.core.model.workspace.runtime.RuntimeIdentity)42 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)38 CompletableFuture (java.util.concurrent.CompletableFuture)36 ExecutionException (java.util.concurrent.ExecutionException)36 TimeoutException (java.util.concurrent.TimeoutException)32 ServerException (org.eclipse.che.api.core.ServerException)32 Pod (io.fabric8.kubernetes.api.model.Pod)30 Map (java.util.Map)26 ValidationException (org.eclipse.che.api.core.ValidationException)22 Traced (org.eclipse.che.commons.annotation.Traced)20 Container (io.fabric8.kubernetes.api.model.Container)18 List (java.util.List)18 Set (java.util.Set)18 Inject (javax.inject.Inject)18 RuntimeStartInterruptedException (org.eclipse.che.api.workspace.server.spi.RuntimeStartInterruptedException)18 KubernetesEnvironment (org.eclipse.che.workspace.infrastructure.kubernetes.environment.KubernetesEnvironment)18