Search in sources :

Example 16 with ValidationException

use of org.eclipse.che.api.core.ValidationException in project devspaces-images by redhat-developer.

the class KubernetesInternalRuntime method doStartMachine.

/**
 * Creates Kubernetes pods and resolves servers using the specified serverResolver.
 *
 * @param serverResolver server resolver that provide servers by container
 * @throws InfrastructureException when any error occurs while creating Kubernetes pods
 */
@Traced
protected void doStartMachine(ServerResolver serverResolver) throws InfrastructureException {
    final KubernetesEnvironment environment = getContext().getEnvironment();
    final Map<String, InternalMachineConfig> machineConfigs = environment.getMachines();
    final String workspaceId = getContext().getIdentity().getWorkspaceId();
    LOG.debug("Begin pods creation for workspace '{}'", workspaceId);
    PodMerger podMerger = new PodMerger();
    Map<String, Map<String, Pod>> injectablePods = environment.getInjectablePodsCopy();
    for (Pod toCreate : environment.getPodsCopy().values()) {
        ObjectMeta toCreateMeta = toCreate.getMetadata();
        List<PodData> injectables = getAllInjectablePods(toCreate, injectablePods);
        Pod createdPod;
        if (injectables.isEmpty()) {
            createdPod = namespace.deployments().deploy(toCreate);
        } else {
            try {
                injectables.add(new PodData(toCreate));
                Deployment merged = podMerger.merge(injectables);
                merged.getMetadata().setName(toCreate.getMetadata().getName());
                createdPod = namespace.deployments().deploy(merged);
            } catch (ValidationException e) {
                throw new InfrastructureException(e);
            }
        }
        LOG.debug("Creating pod '{}' in workspace '{}'", toCreateMeta.getName(), workspaceId);
        storeStartingMachine(createdPod, createdPod.getMetadata(), machineConfigs, serverResolver);
    }
    for (Deployment toCreate : environment.getDeploymentsCopy().values()) {
        PodTemplateSpec template = toCreate.getSpec().getTemplate();
        List<PodData> injectables = getAllInjectablePods(template.getMetadata(), template.getSpec().getContainers(), injectablePods);
        Pod createdPod;
        if (injectables.isEmpty()) {
            createdPod = namespace.deployments().deploy(toCreate);
        } else {
            try {
                injectables.add(new PodData(toCreate));
                Deployment deployment = podMerger.merge(injectables);
                deployment.getMetadata().setName(toCreate.getMetadata().getName());
                putAnnotations(deployment.getMetadata(), toCreate.getMetadata().getAnnotations());
                putLabels(deployment.getMetadata(), toCreate.getMetadata().getLabels());
                createdPod = namespace.deployments().deploy(deployment);
            } catch (ValidationException e) {
                throw new InfrastructureException(e);
            }
        }
        LOG.debug("Creating deployment '{}' in workspace '{}'", createdPod.getMetadata().getName(), workspaceId);
        storeStartingMachine(createdPod, createdPod.getMetadata(), machineConfigs, serverResolver);
    }
    LOG.debug("Pods creation finished in workspace '{}'", workspaceId);
}
Also used : PodMerger(org.eclipse.che.workspace.infrastructure.kubernetes.environment.PodMerger) ObjectMeta(io.fabric8.kubernetes.api.model.ObjectMeta) ValidationException(org.eclipse.che.api.core.ValidationException) Pod(io.fabric8.kubernetes.api.model.Pod) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) InternalMachineConfig(org.eclipse.che.api.workspace.server.spi.environment.InternalMachineConfig) PodData(org.eclipse.che.workspace.infrastructure.kubernetes.environment.KubernetesEnvironment.PodData) PodTemplateSpec(io.fabric8.kubernetes.api.model.PodTemplateSpec) KubernetesEnvironment(org.eclipse.che.workspace.infrastructure.kubernetes.environment.KubernetesEnvironment) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) LinkedHashMap(java.util.LinkedHashMap) Collections.emptyMap(java.util.Collections.emptyMap) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) InternalInfrastructureException(org.eclipse.che.api.workspace.server.spi.InternalInfrastructureException) Traced(org.eclipse.che.commons.annotation.Traced)

Example 17 with ValidationException

use of org.eclipse.che.api.core.ValidationException in project devspaces-images by redhat-developer.

the class KubernetesEnvironmentFactory method doCreate.

@Override
protected KubernetesEnvironment doCreate(@Nullable InternalRecipe recipe, Map<String, InternalMachineConfig> machines, List<Warning> sourceWarnings) throws InfrastructureException, ValidationException {
    checkNotNull(recipe, "Null recipe is not supported by kubernetes environment factory");
    List<Warning> warnings = new ArrayList<>();
    if (sourceWarnings != null) {
        warnings.addAll(sourceWarnings);
    }
    final List<HasMetadata> recipeObjects = recipeParser.parse(recipe);
    Map<String, Pod> pods = new HashMap<>();
    Map<String, Deployment> deployments = new HashMap<>();
    Map<String, Service> services = new HashMap<>();
    Map<String, ConfigMap> configMaps = new HashMap<>();
    Map<String, PersistentVolumeClaim> pvcs = new HashMap<>();
    Map<String, Secret> secrets = new HashMap<>();
    boolean isAnyIngressPresent = false;
    for (HasMetadata object : recipeObjects) {
        checkNotNull(object.getKind(), "Environment contains object without specified kind field");
        checkNotNull(object.getMetadata(), "%s metadata must not be null", object.getKind());
        checkNotNull(object.getMetadata().getName(), "%s name must not be null", object.getKind());
        if (object instanceof Pod) {
            putInto(pods, object.getMetadata().getName(), (Pod) object);
        } else if (object instanceof Deployment) {
            putInto(deployments, object.getMetadata().getName(), (Deployment) object);
        } else if (object instanceof Service) {
            putInto(services, object.getMetadata().getName(), (Service) object);
        } else if (object instanceof Ingress) {
            isAnyIngressPresent = true;
        } else if (object instanceof PersistentVolumeClaim) {
            putInto(pvcs, object.getMetadata().getName(), (PersistentVolumeClaim) object);
        } else if (object instanceof Secret) {
            putInto(secrets, object.getMetadata().getName(), (Secret) object);
        } else if (object instanceof ConfigMap) {
            putInto(configMaps, object.getMetadata().getName(), (ConfigMap) object);
        } else {
            throw new ValidationException(format("Found unknown object type in recipe -- name: '%s', kind: '%s'", object.getMetadata().getName(), object.getKind()));
        }
    }
    if (deployments.size() + pods.size() > 1) {
        mergePods(pods, deployments, services);
    }
    if (isAnyIngressPresent) {
        warnings.add(new WarningImpl(Warnings.INGRESSES_IGNORED_WARNING_CODE, Warnings.INGRESSES_IGNORED_WARNING_MESSAGE));
    }
    KubernetesEnvironment k8sEnv = KubernetesEnvironment.builder().setInternalRecipe(recipe).setMachines(machines).setWarnings(warnings).setPods(pods).setDeployments(deployments).setServices(services).setPersistentVolumeClaims(pvcs).setIngresses(new HashMap<>()).setSecrets(secrets).setConfigMaps(configMaps).build();
    envValidator.validate(k8sEnv);
    return k8sEnv;
}
Also used : Warning(org.eclipse.che.api.core.model.workspace.Warning) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) ValidationException(org.eclipse.che.api.core.ValidationException) Pod(io.fabric8.kubernetes.api.model.Pod) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) WarningImpl(org.eclipse.che.api.workspace.server.model.impl.WarningImpl) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) Service(io.fabric8.kubernetes.api.model.Service) Ingress(io.fabric8.kubernetes.api.model.networking.v1.Ingress) Secret(io.fabric8.kubernetes.api.model.Secret) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim)

Example 18 with ValidationException

use of org.eclipse.che.api.core.ValidationException in project devspaces-images by redhat-developer.

the class KubernetesRecipeParser method parse.

/**
 * Parses Kubernetes objects from recipe content.
 *
 * @param recipeContent recipe content that should be parsed
 * @return parsed objects
 * @throws IllegalArgumentException if recipe content is null
 * @throws ValidationException if recipe content has broken format
 * @throws ValidationException if recipe content has unrecognized objects
 * @throws InfrastructureException when exception occurred during kubernetes client creation
 */
public List<HasMetadata> parse(String recipeContent) throws ValidationException, InfrastructureException {
    checkNotNull(recipeContent, "Recipe content type must not be null");
    try {
        // Behavior:
        // - If `content` is a single object like Deployment, load().get() will get the object in that
        // list
        // - If `content` is a Kubernetes List, load().get() will get the objects in that list
        // - If `content` is an OpenShift template, load().get() will get the objects in the template
        // with parameters substituted (e.g. with default values).
        List<HasMetadata> parsed = clientFactory.create().load(new ByteArrayInputStream(recipeContent.getBytes())).get();
        // needed because Che master namespace is set by K8s API during list loading
        parsed.stream().filter(o -> o.getMetadata() != null).forEach(o -> o.getMetadata().setNamespace(null));
        return parsed;
    } catch (KubernetesClientException e) {
        // KubernetesClient wraps the error when a JsonMappingException occurs so we need the cause
        String message = e.getCause() == null ? e.getMessage() : e.getCause().getMessage();
        if (message.contains("\n")) {
            // Clean up message if it comes from JsonMappingException. Format is e.g.
            // `No resource type found for:v1#Route1\n at [...]`
            message = message.split("\\n", 2)[0];
        }
        throw new ValidationException(format("Could not parse Kubernetes recipe: %s", message));
    }
}
Also used : KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) ImmutableSet(com.google.common.collect.ImmutableSet) KubernetesClientFactory(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesClientFactory) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Set(java.util.Set) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) String.format(java.lang.String.format) ValidationException(org.eclipse.che.api.core.ValidationException) Inject(javax.inject.Inject) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) List(java.util.List) InternalRecipe(org.eclipse.che.api.workspace.server.spi.environment.InternalRecipe) ByteArrayInputStream(java.io.ByteArrayInputStream) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) ValidationException(org.eclipse.che.api.core.ValidationException) ByteArrayInputStream(java.io.ByteArrayInputStream) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 19 with ValidationException

use of org.eclipse.che.api.core.ValidationException in project devspaces-images by redhat-developer.

the class KubernetesComponentToWorkspaceApplierTest method shouldThrowExceptionWhenRecipeContentIsNotAValidYaml.

@Test(expectedExceptions = DevfileException.class, expectedExceptionsMessageRegExp = "Error occurred during parsing list from file " + REFERENCE_FILENAME + " for component '" + COMPONENT_NAME + "': .*")
public void shouldThrowExceptionWhenRecipeContentIsNotAValidYaml() throws Exception {
    // given
    doThrow(new ValidationException("non valid")).when(k8sRecipeParser).parse(anyString());
    ComponentImpl component = new ComponentImpl();
    component.setType(KUBERNETES_COMPONENT_TYPE);
    component.setReference(REFERENCE_FILENAME);
    component.setAlias(COMPONENT_NAME);
    // when
    applier.apply(workspaceConfig, component, s -> "some_non_yaml_content");
}
Also used : ValidationException(org.eclipse.che.api.core.ValidationException) ComponentImpl(org.eclipse.che.api.workspace.server.model.impl.devfile.ComponentImpl) Test(org.testng.annotations.Test)

Example 20 with ValidationException

use of org.eclipse.che.api.core.ValidationException in project devspaces-images by redhat-developer.

the class FactoryCreateValidatorImpl method validateOnCreate.

@Override
public void validateOnCreate(FactoryDto factory) throws BadRequestException, ServerException, ForbiddenException, NotFoundException {
    validateProjects(factory);
    validateCurrentTimeAfterSinceUntil(factory);
    validateProjectActions(factory);
    try {
        workspaceConfigValidator.validateConfig(factory.getWorkspace());
    } catch (ValidationException x) {
        throw new BadRequestException(x.getMessage());
    }
}
Also used : ValidationException(org.eclipse.che.api.core.ValidationException) BadRequestException(org.eclipse.che.api.core.BadRequestException)

Aggregations

ValidationException (org.eclipse.che.api.core.ValidationException)42 Test (org.testng.annotations.Test)16 InfrastructureException (org.eclipse.che.api.workspace.server.spi.InfrastructureException)12 Deployment (io.fabric8.kubernetes.api.model.apps.Deployment)10 WorkspaceImpl (org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl)10 PodData (org.eclipse.che.workspace.infrastructure.kubernetes.environment.KubernetesEnvironment.PodData)8 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)6 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)6 ObjectMeta (io.fabric8.kubernetes.api.model.ObjectMeta)6 Pod (io.fabric8.kubernetes.api.model.Pod)6 PodTemplateSpec (io.fabric8.kubernetes.api.model.PodTemplateSpec)6 HashMap (java.util.HashMap)6 Map (java.util.Map)6 ConflictException (org.eclipse.che.api.core.ConflictException)6 ServerException (org.eclipse.che.api.core.ServerException)6 WorkspaceStatus (org.eclipse.che.api.core.model.workspace.WorkspaceStatus)6 RuntimeIdentityImpl (org.eclipse.che.api.workspace.server.model.impl.RuntimeIdentityImpl)6 WorkspaceConfigImpl (org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl)6 InternalInfrastructureException (org.eclipse.che.api.workspace.server.spi.InternalInfrastructureException)6 Traced (org.eclipse.che.commons.annotation.Traced)6