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;
}
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()));
}
}
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();
}
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;
}
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;
});
}
Aggregations