use of org.eclipse.che.api.core.ValidationException in project devspaces-images by redhat-developer.
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;
});
}
use of org.eclipse.che.api.core.ValidationException in project devspaces-images by redhat-developer.
the class WorkspaceRuntimes method startAsync.
/**
* Starts all machines from specified workspace environment, creates workspace runtime instance
* based on that environment.
*
* <p>During the start of the workspace its runtime is visible with {@link
* WorkspaceStatus#STARTING} status.
*
* @param workspace workspace which environment should be started
* @param envName optional environment name to run
* @param options whether machines should be recovered(true) or not(false)
* @return completable future of start execution.
* @throws ConflictException when workspace is already running
* @throws ConflictException when start is interrupted
* @throws NotFoundException when any not found exception occurs during environment start
* @throws ServerException other error occurs during environment start
* @see WorkspaceStatus#STARTING
* @see WorkspaceStatus#RUNNING
*/
@Traced
public CompletableFuture<Void> startAsync(WorkspaceImpl workspace, @Nullable String envName, Map<String, String> options) throws ConflictException, NotFoundException, ServerException {
TracingTags.WORKSPACE_ID.set(workspace.getId());
final String workspaceId = workspace.getId();
if (isStartRefused.get()) {
throw new ConflictException(format("Start of the workspace '%s' is rejected by the system, " + "no more workspaces are allowed to start", workspace.getName()));
}
WorkspaceConfigImpl config = workspace.getConfig();
if (config == null) {
config = devfileConverter.convert(workspace.getDevfile());
}
if (envName == null) {
envName = config.getDefaultEnv();
}
String infraNamespace = workspace.getAttributes().get(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE);
if (isNullOrEmpty(infraNamespace)) {
throw new ServerException(String.format("Workspace does not have infrastructure namespace " + "specified. Please set value of '%s' workspace attribute.", WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE));
}
final RuntimeIdentity runtimeId = new RuntimeIdentityImpl(workspaceId, envName, EnvironmentContext.getCurrent().getSubject().getUserId(), infraNamespace);
try {
InternalEnvironment internalEnv = createInternalEnvironment(config.getEnvironments().get(envName), config.getAttributes(), config.getCommands(), config.getDevfile());
RuntimeContext runtimeContext = infrastructure.prepare(runtimeId, internalEnv);
InternalRuntime runtime = runtimeContext.getRuntime();
try (Unlocker ignored = lockService.writeLock(workspaceId)) {
final WorkspaceStatus existingStatus = statuses.putIfAbsent(workspaceId, STARTING);
if (existingStatus != null) {
throw new ConflictException(format("Could not start workspace '%s' because its state is '%s'", workspaceId, existingStatus));
}
setRuntimesId(workspaceId);
runtimes.put(workspaceId, runtime);
}
LOG.info("Starting workspace '{}/{}' with id '{}' by user '{}'", workspace.getNamespace(), workspace.getName(), workspace.getId(), sessionUserNameOr("undefined"));
publishWorkspaceStatusEvent(workspaceId, STARTING, STOPPED, null, true, options);
return CompletableFuture.runAsync(ThreadLocalPropagateContext.wrap(new StartRuntimeTask(workspace, options, runtime)), sharedPool.getExecutor());
} catch (ValidationException e) {
LOG.error(e.getLocalizedMessage(), e);
throw new ConflictException(e.getLocalizedMessage());
} catch (InfrastructureException e) {
LOG.error(e.getLocalizedMessage(), e);
throw new ServerException(e.getLocalizedMessage(), e);
}
}
use of org.eclipse.che.api.core.ValidationException in project devspaces-images by redhat-developer.
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 K8sInfraNamespaceWsAttributeValidatorTest method testWhenNamespaceFactoryThrowsErrorOnCheckingIfNamespaceIsAllowed.
@Test(expectedExceptions = ValidationException.class, expectedExceptionsMessageRegExp = "The specified namespace name is not valid")
public void testWhenNamespaceFactoryThrowsErrorOnCheckingIfNamespaceIsAllowed() throws ValidationException {
doThrow(new ValidationException("The specified namespace name is not valid")).when(namespaceFactory).checkIfNamespaceIsAllowed(anyString());
validator.validate(ImmutableMap.of(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE, "any"));
}
use of org.eclipse.che.api.core.ValidationException in project che-server by eclipse-che.
the class WorkspaceServiceTest method shouldReturnBadRequestOnInvalidDevfile.
@Test
public void shouldReturnBadRequestOnInvalidDevfile() throws Exception {
final DevfileDto devfileDto = createDevfileDto();
final WorkspaceImpl workspace = createWorkspace(devfileDto);
when(wsManager.createWorkspace(any(Devfile.class), anyString(), any(), any())).thenThrow(new ValidationException("boom"));
final Response response = given().auth().basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD).contentType("application/json").body(devfileDto).when().post(SECURE_PATH + "/workspace/devfile" + "?namespace=test" + "&attribute=factoryId:factory123" + "&attribute=custom:custom:value");
assertEquals(response.getStatusCode(), 400);
String error = unwrapError(response);
assertEquals(error, "boom");
}
Aggregations