Search in sources :

Example 6 with ValidationException

use of org.eclipse.che.api.core.ValidationException in project che-server by eclipse-che.

the class OpenShiftEnvironmentFactory method doCreate.

@Override
protected OpenShiftEnvironment doCreate(@Nullable InternalRecipe recipe, Map<String, InternalMachineConfig> machines, List<Warning> sourceWarnings) throws InfrastructureException, ValidationException {
    checkNotNull(recipe, "Null recipe is not supported by openshift environment factory");
    List<Warning> warnings = new ArrayList<>();
    if (sourceWarnings != null) {
        warnings.addAll(sourceWarnings);
    }
    final List<HasMetadata> list = k8sObjectsParser.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, Route> routes = new HashMap<>();
    Map<String, Secret> secrets = new HashMap<>();
    for (HasMetadata object : list) {
        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 DeploymentConfig) {
            throw new ValidationException("Supporting of deployment configs is not implemented yet.");
        } else 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 Route) {
            putInto(routes, object.getMetadata().getName(), (Route) object);
        } 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);
    }
    OpenShiftEnvironment osEnv = OpenShiftEnvironment.builder().setInternalRecipe(recipe).setMachines(machines).setWarnings(warnings).setPods(pods).setDeployments(deployments).setServices(services).setPersistentVolumeClaims(pvcs).setSecrets(secrets).setConfigMaps(configMaps).setRoutes(routes).build();
    envValidator.validate(osEnv);
    return osEnv;
}
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) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) Service(io.fabric8.kubernetes.api.model.Service) Secret(io.fabric8.kubernetes.api.model.Secret) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) Route(io.fabric8.openshift.api.model.Route)

Example 7 with ValidationException

use of org.eclipse.che.api.core.ValidationException in project che-server by eclipse-che.

the class WorkspaceRuntimes method recoverOne.

@VisibleForTesting
InternalRuntime<?> recoverOne(RuntimeInfrastructure infra, RuntimeIdentity identity) throws ServerException, ConflictException {
    if (isStartRefused.get()) {
        throw new ConflictException(format("Recovery of the workspace '%s' is rejected by the system, " + "no more workspaces are allowed to start", identity.getWorkspaceId()));
    }
    WorkspaceImpl workspace;
    try {
        workspace = workspaceDao.get(identity.getWorkspaceId());
    } catch (NotFoundException x) {
        throw new ServerException(format("Workspace configuration is missing for the runtime '%s:%s'. Runtime won't be recovered", identity.getWorkspaceId(), identity.getEnvName()));
    }
    Environment environment = null;
    WorkspaceConfigImpl workspaceConfig = workspace.getConfig();
    if (workspaceConfig == null) {
        workspaceConfig = devfileConverter.convert(workspace.getDevfile());
    }
    if (identity.getEnvName() != null) {
        environment = workspaceConfig.getEnvironments().get(identity.getEnvName());
        if (environment == null) {
            throw new ServerException(format("Environment configuration is missing for the runtime '%s:%s'. Runtime won't be recovered", identity.getWorkspaceId(), identity.getEnvName()));
        }
    }
    InternalRuntime runtime;
    try {
        InternalEnvironment internalEnv = createInternalEnvironment(environment, workspaceConfig.getAttributes(), workspaceConfig.getCommands(), workspaceConfig.getDevfile());
        runtime = infra.prepare(identity, internalEnv).getRuntime();
        WorkspaceStatus runtimeStatus = runtime.getStatus();
        try (Unlocker ignored = lockService.writeLock(workspace.getId())) {
            statuses.replace(identity.getWorkspaceId(), runtimeStatus);
            runtimes.putIfAbsent(identity.getWorkspaceId(), runtime);
        }
        LOG.info("Successfully recovered workspace runtime '{}'. Its status is '{}'", identity.getWorkspaceId(), runtimeStatus);
        return runtime;
    } catch (NotFoundException x) {
        LOG.warn("Not able to create internal environment for  '{}'. Reason: '{}'", identity.getWorkspaceId(), x.getMessage());
        try (Unlocker ignored = lockService.writeLock(identity.getWorkspaceId())) {
            runtimes.remove(identity.getWorkspaceId());
            statuses.remove(identity.getWorkspaceId());
        }
        publishWorkspaceStatusEvent(identity.getWorkspaceId(), STOPPED, STOPPING, "Workspace is stopped. Reason: " + x.getMessage(), false);
        throw new ServerException(format("Couldn't recover runtime '%s:%s'. Error: %s", identity.getWorkspaceId(), identity.getEnvName(), x.getMessage()));
    } catch (InfrastructureException | ValidationException x) {
        throw new ServerException(format("Couldn't recover runtime '%s:%s'. Error: %s", identity.getWorkspaceId(), identity.getEnvName(), x.getMessage()));
    }
}
Also used : WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) ServerException(org.eclipse.che.api.core.ServerException) ValidationException(org.eclipse.che.api.core.ValidationException) ConflictException(org.eclipse.che.api.core.ConflictException) NotFoundException(org.eclipse.che.api.core.NotFoundException) InternalRuntime(org.eclipse.che.api.workspace.server.spi.InternalRuntime) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) InternalEnvironment(org.eclipse.che.api.workspace.server.spi.environment.InternalEnvironment) InternalEnvironment(org.eclipse.che.api.workspace.server.spi.environment.InternalEnvironment) Environment(org.eclipse.che.api.core.model.workspace.config.Environment) WorkspaceConfigImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl) WorkspaceStatus(org.eclipse.che.api.core.model.workspace.WorkspaceStatus) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) InternalInfrastructureException(org.eclipse.che.api.workspace.server.spi.InternalInfrastructureException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 8 with ValidationException

use of org.eclipse.che.api.core.ValidationException in project che-server by eclipse-che.

the class WorkspaceService method create.

@Path("/devfile")
@POST
@Consumes({ APPLICATION_JSON, "text/yaml", "text/x-yaml" })
@Produces(APPLICATION_JSON)
@Operation(summary = "Creates a new workspace based on the Devfile.", responses = { @ApiResponse(responseCode = "201", description = "The workspace successfully created", content = @Content(schema = @Schema(implementation = WorkspaceDto.class))), @ApiResponse(responseCode = "400", description = "Missed required parameters, parameters are not valid"), @ApiResponse(responseCode = "403", description = "The user does not have access to create a new workspace"), @ApiResponse(responseCode = "409", description = "Conflict error occurred during the workspace creation" + "(e.g. The workspace with such name already exists)"), @ApiResponse(responseCode = "500", description = "Internal server error occurred") })
public Response create(@Parameter(description = "The devfile of the workspace to create", required = true) DevfileDto devfile, @Parameter(description = "Workspace attribute defined in 'attrName:attrValue' format. " + "The first ':' is considered as attribute name and value separator", examples = @ExampleObject(value = "attrName:value-with:colon")) @QueryParam("attribute") List<String> attrsList, @Parameter(description = "If true then the workspace will be immediately " + "started after it is successfully created") @QueryParam("start-after-create") @DefaultValue("false") Boolean startAfterCreate, @Parameter(description = "Che namespace where workspace should be created") @QueryParam("namespace") String namespace, @HeaderParam(CONTENT_TYPE) MediaType contentType) throws ConflictException, BadRequestException, ForbiddenException, NotFoundException, ServerException {
    requiredNotNull(devfile, "Devfile");
    final Map<String, String> attributes = parseAttrs(attrsList);
    if (namespace == null) {
        namespace = EnvironmentContext.getCurrent().getSubject().getUserName();
    }
    WorkspaceImpl workspace;
    try {
        workspace = workspaceManager.createWorkspace(devfile, namespace, attributes, // referenced file only once per request)
        FileContentProvider.cached(devfileContentProvider));
    } catch (ValidationException x) {
        throw new BadRequestException(x.getMessage());
    }
    if (startAfterCreate) {
        workspaceManager.startWorkspace(workspace.getId(), null, new HashMap<>());
    }
    return Response.status(201).entity(asDtoWithLinksAndToken(workspace)).build();
}
Also used : WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) ValidationException(org.eclipse.che.api.core.ValidationException) BadRequestException(org.eclipse.che.api.core.BadRequestException) Path(jakarta.ws.rs.Path) POST(jakarta.ws.rs.POST) Consumes(jakarta.ws.rs.Consumes) Produces(jakarta.ws.rs.Produces) Operation(io.swagger.v3.oas.annotations.Operation)

Example 9 with ValidationException

use of org.eclipse.che.api.core.ValidationException in project che-server by eclipse-che.

the class WorkspaceManager method createWorkspace.

/**
 * Creates a workspace out of a devfile.
 *
 * <p>The devfile should have been validated using the {@link
 * DevfileIntegrityValidator#validateDevfile(Devfile)}. This method does rest of the validation
 * and actually creates the workspace.
 *
 * @param devfile the devfile describing the workspace
 * @param namespace workspace name is unique in this namespace
 * @param attributes workspace instance attributes
 * @param contentProvider the content provider to use for resolving content references in the
 *     devfile
 * @return new workspace instance
 * @throws NullPointerException when either {@code config} or {@code namespace} is null
 * @throws NotFoundException when account with given id was not found
 * @throws ConflictException when any conflict occurs (e.g Workspace with such name already exists
 *     for {@code owner})
 * @throws ServerException when any other error occurs
 * @throws ValidationException when incoming configuration or attributes are not valid
 */
@Traced
public WorkspaceImpl createWorkspace(Devfile devfile, String namespace, Map<String, String> attributes, FileContentProvider contentProvider) throws ServerException, NotFoundException, ConflictException, ValidationException {
    requireNonNull(devfile, "Required non-null devfile");
    requireNonNull(namespace, "Required non-null namespace");
    validator.validateAttributes(attributes);
    devfile = generateNameIfNeeded(devfile);
    try {
        devfileIntegrityValidator.validateContentReferences(devfile, contentProvider);
    } catch (DevfileFormatException e) {
        throw new ValidationException(e.getMessage(), e);
    }
    WorkspaceImpl workspace = doCreateWorkspace(devfile, accountManager.getByName(namespace), attributes, false);
    TracingTags.WORKSPACE_ID.set(workspace.getId());
    return workspace;
}
Also used : WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) ValidationException(org.eclipse.che.api.core.ValidationException) DevfileFormatException(org.eclipse.che.api.workspace.server.devfile.exception.DevfileFormatException) Traced(org.eclipse.che.commons.annotation.Traced)

Example 10 with ValidationException

use of org.eclipse.che.api.core.ValidationException in project che-server by eclipse-che.

the class WorkspaceManager method startAsync.

/**
 * Asynchronously starts given workspace.
 */
private void startAsync(WorkspaceImpl workspace, @Nullable String envName, Map<String, String> options) throws ConflictException, NotFoundException, ServerException {
    try {
        runtimes.validate(workspace, envName);
    } catch (ValidationException e) {
        throw new ConflictException(e.getMessage(), e);
    }
    // handle the situation where a workspace created by a previous Che version doesn't have a
    // namespace stored for it. We use the legacy-aware method to figure out the namespace to
    // correctly capture the workspaces which have PVCs already in a namespace defined by the legacy
    // configuration variable.
    String targetNamespace = workspace.getAttributes().get(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE);
    if (isNullOrEmpty(targetNamespace)) {
        try {
            targetNamespace = runtimes.evalInfrastructureNamespace(buildResolutionContext(workspace));
            workspace.getAttributes().put(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE, targetNamespace);
        } catch (InfrastructureException e) {
            throw new ServerException(e);
        }
    }
    if (!runtimes.isInfrastructureNamespaceValid(targetNamespace)) {
        try {
            targetNamespace = runtimes.evalInfrastructureNamespace(buildResolutionContext(workspace));
            if (targetNamespace == null || !runtimes.isInfrastructureNamespaceValid(targetNamespace)) {
                throw new ServerException(format("The workspace would be started in a namespace/project" + " '%s', which is not a valid namespace/project name.", targetNamespace));
            }
            workspace.getAttributes().put(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE, targetNamespace);
        } catch (InfrastructureException e) {
            throw new ServerException(e);
        }
    }
    workspace.getAttributes().put(UPDATED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis()));
    workspaceDao.update(workspace);
    runtimes.startAsync(workspace, envName, firstNonNull(options, Collections.emptyMap())).thenAccept(aVoid -> handleStartupSuccess(workspace.getId())).exceptionally(ex -> {
        if (workspace.isTemporary()) {
            removeWorkspaceQuietly(workspace.getId());
        } else {
            handleStartupError(workspace.getId(), ex.getCause());
        }
        return null;
    });
}
Also used : NamespaceResolutionContext(org.eclipse.che.api.workspace.server.spi.NamespaceResolutionContext) WorkspaceConfig(org.eclipse.che.api.core.model.workspace.WorkspaceConfig) STOPPED_ATTRIBUTE_NAME(org.eclipse.che.api.workspace.shared.Constants.STOPPED_ATTRIBUTE_NAME) Arrays(java.util.Arrays) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) WorkspaceConfigImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl) RUNNING(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.RUNNING) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) LAST_ACTIVE_INFRASTRUCTURE_NAMESPACE(org.eclipse.che.api.workspace.shared.Constants.LAST_ACTIVE_INFRASTRUCTURE_NAMESPACE) PreferenceManager(org.eclipse.che.api.user.server.PreferenceManager) WORKSPACE_GENERATE_NAME_CHARS_APPEND(org.eclipse.che.api.workspace.shared.Constants.WORKSPACE_GENERATE_NAME_CHARS_APPEND) Map(java.util.Map) Account(org.eclipse.che.account.shared.model.Account) WorkspaceDao(org.eclipse.che.api.workspace.server.spi.WorkspaceDao) NameGenerator(org.eclipse.che.commons.lang.NameGenerator) EventService(org.eclipse.che.api.core.notification.EventService) Devfile(org.eclipse.che.api.core.model.workspace.devfile.Devfile) Set(java.util.Set) CREATED_ATTRIBUTE_NAME(org.eclipse.che.api.workspace.shared.Constants.CREATED_ATTRIBUTE_NAME) MetadataImpl(org.eclipse.che.api.workspace.server.model.impl.devfile.MetadataImpl) String.format(java.lang.String.format) STOPPED_ABNORMALLY_ATTRIBUTE_NAME(org.eclipse.che.api.workspace.shared.Constants.STOPPED_ABNORMALLY_ATTRIBUTE_NAME) Nullable(org.eclipse.che.commons.annotation.Nullable) STARTING(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.STARTING) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) TracingTags(org.eclipse.che.commons.tracing.TracingTags) WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE(org.eclipse.che.api.workspace.shared.Constants.WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE) Optional(java.util.Optional) WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) STOPPED(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.STOPPED) Workspace(org.eclipse.che.api.core.model.workspace.Workspace) Instant.now(java.time.Instant.now) System.currentTimeMillis(java.lang.System.currentTimeMillis) Page(org.eclipse.che.api.core.Page) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) Singleton(javax.inject.Singleton) Traced(org.eclipse.che.commons.annotation.Traced) ValidationException(org.eclipse.che.api.core.ValidationException) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) ERROR_MESSAGE_ATTRIBUTE_NAME(org.eclipse.che.api.workspace.shared.Constants.ERROR_MESSAGE_ATTRIBUTE_NAME) Subject(org.eclipse.che.commons.subject.Subject) Objects.requireNonNull(java.util.Objects.requireNonNull) REMOVE_WORKSPACE_AFTER_STOP(org.eclipse.che.api.workspace.shared.Constants.REMOVE_WORKSPACE_AFTER_STOP) ConflictException(org.eclipse.che.api.core.ConflictException) DevfileImpl(org.eclipse.che.api.workspace.server.model.impl.devfile.DevfileImpl) DevfileIntegrityValidator(org.eclipse.che.api.workspace.server.devfile.validator.DevfileIntegrityValidator) Logger(org.slf4j.Logger) Constants(org.eclipse.che.api.workspace.shared.Constants) WorkspaceStatus(org.eclipse.che.api.core.model.workspace.WorkspaceStatus) LAST_ACTIVITY_TIME(org.eclipse.che.api.workspace.shared.Constants.LAST_ACTIVITY_TIME) NotFoundException(org.eclipse.che.api.core.NotFoundException) FileContentProvider(org.eclipse.che.api.workspace.server.devfile.FileContentProvider) Boolean.parseBoolean(java.lang.Boolean.parseBoolean) UPDATED_ATTRIBUTE_NAME(org.eclipse.che.api.workspace.shared.Constants.UPDATED_ATTRIBUTE_NAME) ServerException(org.eclipse.che.api.core.ServerException) WorkspaceCreatedEvent(org.eclipse.che.api.workspace.shared.event.WorkspaceCreatedEvent) AccountManager(org.eclipse.che.account.api.AccountManager) Collections(java.util.Collections) DevfileFormatException(org.eclipse.che.api.workspace.server.devfile.exception.DevfileFormatException) ValidationException(org.eclipse.che.api.core.ValidationException) ServerException(org.eclipse.che.api.core.ServerException) ConflictException(org.eclipse.che.api.core.ConflictException) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException)

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