Search in sources :

Example 66 with ConflictException

use of org.eclipse.che.api.core.ConflictException in project che by eclipse.

the class CheEnvironmentEngine method startMachine.

/**
     * Starts machine in running environment.
     *
     * @param workspaceId
     *         ID of workspace that owns environment in which machine should be started
     * @param machineConfig
     *         configuration of machine that should be started
     * @return running machine
     * @throws EnvironmentNotRunningException
     *         if environment is not running
     * @throws NotFoundException
     *         if provider of machine implementation is not found
     * @throws ConflictException
     *         if machine with the same name already exists in the environment
     * @throws ServerException
     *         if any other error occurs
     */
public Instance startMachine(String workspaceId, MachineConfig machineConfig, List<String> agents) throws ServerException, NotFoundException, ConflictException, EnvironmentException {
    MachineConfig machineConfigCopy = new MachineConfigImpl(machineConfig);
    EnvironmentHolder environmentHolder;
    try (@SuppressWarnings("unused") Unlocker u = stripedLocks.readLock(workspaceId)) {
        environmentHolder = environments.get(workspaceId);
        if (environmentHolder == null || environmentHolder.status != EnvStatus.RUNNING) {
            throw new EnvironmentNotRunningException(format("Environment '%s' is not running", workspaceId));
        }
        for (Instance machine : environmentHolder.machines) {
            if (machine.getConfig().getName().equals(machineConfigCopy.getName())) {
                throw new ConflictException(format("Machine with name '%s' already exists in environment of workspace '%s'", machineConfigCopy.getName(), workspaceId));
            }
        }
    }
    final String creator = EnvironmentContext.getCurrent().getSubject().getUserId();
    final String namespace = EnvironmentContext.getCurrent().getSubject().getUserName();
    MachineImpl machine = MachineImpl.builder().setConfig(machineConfig).setWorkspaceId(workspaceId).setStatus(MachineStatus.CREATING).setEnvName(environmentHolder.name).setOwner(creator).build();
    MachineStarter machineStarter;
    if ("docker".equals(machineConfig.getType())) {
        // needed to reuse startInstance method and
        // create machine instances by different implementation-specific providers
        CheServiceImpl service = machineConfigToService(machineConfig);
        normalize(namespace, workspaceId, machineConfig.getName(), service);
        machine.setId(service.getId());
        machineStarter = (machineLogger, machineSource) -> {
            CheServiceImpl serviceWithNormalizedSource = normalizeServiceSource(service, machineSource);
            normalize(namespace, workspaceId, machineConfig.getName(), serviceWithNormalizedSource);
            infrastructureProvisioner.provision(new ExtendedMachineImpl().withAgents(agents), serviceWithNormalizedSource);
            return machineProvider.startService(namespace, workspaceId, environmentHolder.name, machineConfig.getName(), machineConfig.isDev(), environmentHolder.networkId, serviceWithNormalizedSource, machineLogger);
        };
    } else {
        try {
            InstanceProvider provider = machineInstanceProviders.getProvider(machineConfig.getType());
            machine.setId(generateMachineId());
            addAgentsProvidedServers(machine, agents);
            machineStarter = (machineLogger, machineSource) -> {
                Machine machineWithNormalizedSource = normalizeMachineSource(machine, machineSource);
                return provider.createInstance(machineWithNormalizedSource, machineLogger);
            };
        } catch (NotFoundException e) {
            throw new NotFoundException(format("Provider of machine type '%s' not found", machineConfig.getType()));
        }
    }
    return startInstance(false, environmentHolder.logger, machine, machineStarter);
}
Also used : ExtendedMachineImpl(org.eclipse.che.api.workspace.server.model.impl.ExtendedMachineImpl) MachineImpl(org.eclipse.che.api.machine.server.model.impl.MachineImpl) MachineConfig(org.eclipse.che.api.core.model.machine.MachineConfig) Instance(org.eclipse.che.api.machine.server.spi.Instance) ConflictException(org.eclipse.che.api.core.ConflictException) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) EnvironmentNotRunningException(org.eclipse.che.api.environment.server.exception.EnvironmentNotRunningException) SourceNotFoundException(org.eclipse.che.api.machine.server.exception.SourceNotFoundException) NotFoundException(org.eclipse.che.api.core.NotFoundException) ExtendedMachine(org.eclipse.che.api.core.model.workspace.ExtendedMachine) Machine(org.eclipse.che.api.core.model.machine.Machine) MachineConfigImpl(org.eclipse.che.api.machine.server.model.impl.MachineConfigImpl) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) ExtendedMachineImpl(org.eclipse.che.api.workspace.server.model.impl.ExtendedMachineImpl) InstanceProvider(org.eclipse.che.api.machine.server.spi.InstanceProvider)

Example 67 with ConflictException

use of org.eclipse.che.api.core.ConflictException in project che by eclipse.

the class CheEnvironmentEngine method stopMachine.

/**
     * Stops machine in running environment.
     *
     * @param workspaceId
     *         ID of workspace of environment that owns machine
     * @param machineId
     *         ID of machine that should be stopped
     * @throws NotFoundException
     *         if machine in not found in environment
     * @throws EnvironmentNotRunningException
     *         if environment is not running
     * @throws ConflictException
     *         if stop of dev machine is requested
     * @throws ServerException
     *         if other error occurs
     */
public void stopMachine(String workspaceId, String machineId) throws NotFoundException, ServerException, ConflictException {
    Instance targetMachine = null;
    try (@SuppressWarnings("unused") Unlocker u = stripedLocks.writeLock(workspaceId)) {
        EnvironmentHolder environmentHolder = environments.get(workspaceId);
        if (environmentHolder == null || environmentHolder.status != EnvStatus.RUNNING) {
            throw new EnvironmentNotRunningException(format("Environment '%s' is not running", workspaceId));
        }
        for (Instance machine : environmentHolder.machines) {
            if (machine.getId().equals(machineId)) {
                if (machine.getConfig().isDev()) {
                    throw new ConflictException("Stop of dev machine is not allowed. Please, stop whole environment");
                }
                targetMachine = machine;
                break;
            }
        }
        environmentHolder.machines.remove(targetMachine);
    }
    if (targetMachine == null) {
        throw new NotFoundException(format("Machine with ID '%s' is not found in environment of workspace '%s'", machineId, workspaceId));
    }
    // out of lock to prevent blocking by potentially long-running method
    destroyMachine(targetMachine);
}
Also used : Instance(org.eclipse.che.api.machine.server.spi.Instance) ConflictException(org.eclipse.che.api.core.ConflictException) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) EnvironmentNotRunningException(org.eclipse.che.api.environment.server.exception.EnvironmentNotRunningException) SourceNotFoundException(org.eclipse.che.api.machine.server.exception.SourceNotFoundException) NotFoundException(org.eclipse.che.api.core.NotFoundException)

Example 68 with ConflictException

use of org.eclipse.che.api.core.ConflictException in project che by eclipse.

the class WorkspaceRuntimes method stop.

/**
     * Stops running workspace runtime.
     *
     * <p>Stops environment in an implementation specific way.
     * During the stop of the workspace its runtime is accessible with {@link WorkspaceStatus#STOPPING stopping} status.
     * Workspace may be stopped only if its status is {@link WorkspaceStatus#RUNNING}.
     *
     * @param workspaceId
     *         identifier of workspace which should be stopped
     * @throws NotFoundException
     *         when workspace with specified identifier is not running
     * @throws ServerException
     *         when any error occurs during workspace stopping
     * @throws ConflictException
     *         when running workspace status is different from {@link WorkspaceStatus#RUNNING}
     * @see CheEnvironmentEngine#stop(String)
     * @see WorkspaceStatus#STOPPING
     */
public void stop(String workspaceId) throws NotFoundException, ServerException, ConflictException, EnvironmentException {
    requireNonNull(workspaceId, "Required not-null workspace id");
    RuntimeState prevState;
    try (@SuppressWarnings("unused") Unlocker u = locks.writeLock(workspaceId)) {
        checkIsNotTerminated("stop the workspace");
        RuntimeState state = getExistingState(workspaceId);
        if (state.status != WorkspaceStatus.RUNNING && state.status != WorkspaceStatus.STARTING) {
            throw new ConflictException(format("Couldn't stop the workspace '%s' because its status is '%s'. " + "Workspace can be stopped only if it is 'RUNNING' or 'STARTING'", workspaceId, state.status));
        }
        prevState = new RuntimeState(state);
        state.status = WorkspaceStatus.STOPPING;
    }
    // workspace is running, stop normally
    if (prevState.status == WorkspaceStatus.RUNNING) {
        stopEnvironmentAndPublishEvents(workspaceId, WorkspaceStatus.RUNNING);
        return;
    }
    // interrupt workspace start thread
    prevState.startFuture.cancel(true);
    // if task wasn't called by executor service, then
    // no real machines were started but, the clients still
    // have to be notified about the workspace shut down
    StartTask startTask = prevState.startTask;
    if (startTask.markAsUsed()) {
        removeStateAndPublishStopEvents(workspaceId);
        prevState.startTask.earlyComplete();
        return;
    }
    // otherwise stop will be triggered by the start task, wait for it to finish
    try {
        startTask.await();
    } catch (EnvironmentStartInterruptedException ignored) {
    // environment start successfully interrupted
    } catch (InterruptedException x) {
        Thread.currentThread().interrupt();
        throw new ServerException("Interrupted while waiting for start task cancellation", x);
    }
}
Also used : ServerException(org.eclipse.che.api.core.ServerException) ConflictException(org.eclipse.che.api.core.ConflictException) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) EnvironmentStartInterruptedException(org.eclipse.che.api.environment.server.exception.EnvironmentStartInterruptedException) EnvironmentStartInterruptedException(org.eclipse.che.api.environment.server.exception.EnvironmentStartInterruptedException)

Example 69 with ConflictException

use of org.eclipse.che.api.core.ConflictException in project che by eclipse.

the class WorkspaceRuntimes method startMachine.

/**
     * Starts machine in running workspace.
     *
     * @param workspaceId
     *         ID of workspace that owns machine
     * @param machineConfig
     *         config of machine that should be started
     * @return running machine
     * @throws ConflictException
     *         if environment is not running or conflicting machine already exists in the environment
     * @throws ConflictException
     *         if environment was stopped during start of machine
     * @throws ServerException
     *         if any other error occurs
     */
public Instance startMachine(String workspaceId, MachineConfig machineConfig) throws ServerException, ConflictException, NotFoundException, EnvironmentException {
    try (@SuppressWarnings("unused") Unlocker u = locks.readLock(workspaceId)) {
        getRunningState(workspaceId);
    }
    // Copy constructor makes deep copy of objects graph
    // which means that original values won't affect the values in used further in this class
    MachineConfigImpl machineConfigCopy = new MachineConfigImpl(machineConfig);
    List<String> agents = Collections.singletonList("org.eclipse.che.terminal");
    Instance instance = envEngine.startMachine(workspaceId, machineConfigCopy, agents);
    launchAgents(instance, agents);
    try (@SuppressWarnings("unused") Unlocker u = locks.writeLock(workspaceId)) {
        checkIsNotTerminated("start the machine");
        RuntimeState workspaceState = states.get(workspaceId);
        if (workspaceState == null || workspaceState.status != RUNNING) {
            try {
                envEngine.stopMachine(workspaceId, instance.getId());
            } catch (NotFoundException | ServerException | ConflictException e) {
                LOG.error(e.getLocalizedMessage(), e);
            }
            throw new ConflictException(format("Environment of workspace '%s' was stopped during start of  machine", workspaceId));
        }
    }
    return instance;
}
Also used : MachineConfigImpl(org.eclipse.che.api.machine.server.model.impl.MachineConfigImpl) ServerException(org.eclipse.che.api.core.ServerException) Instance(org.eclipse.che.api.machine.server.spi.Instance) ConflictException(org.eclipse.che.api.core.ConflictException) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) NotFoundException(org.eclipse.che.api.core.NotFoundException)

Example 70 with ConflictException

use of org.eclipse.che.api.core.ConflictException in project che by eclipse.

the class WorkspaceService method updateProject.

@PUT
@Path("/{id}/project/{path:.*}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Update the workspace project by replacing it with a new one", notes = "This operation can be performed only by the workspace owner")
@ApiResponses({ @ApiResponse(code = 200, message = "The project successfully updated"), @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"), @ApiResponse(code = 403, message = "The user does not have access to update the project"), @ApiResponse(code = 404, message = "The workspace or the project not found"), @ApiResponse(code = 500, message = "Internal server error occurred") })
public WorkspaceDto updateProject(@ApiParam("The workspace id") @PathParam("id") String id, @ApiParam("The path to the project") @PathParam("path") String path, @ApiParam(value = "The project update", required = true) ProjectConfigDto update) throws ServerException, BadRequestException, NotFoundException, ConflictException, ForbiddenException {
    requiredNotNull(update, "Project config");
    final WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
    final List<ProjectConfigImpl> projects = workspace.getConfig().getProjects();
    final String normalizedPath = path.startsWith("/") ? path : '/' + path;
    if (!projects.removeIf(project -> project.getPath().equals(normalizedPath))) {
        throw new NotFoundException(format("Workspace '%s' doesn't contain project with path '%s'", id, normalizedPath));
    }
    projects.add(new ProjectConfigImpl(update));
    validator.validateConfig(workspace.getConfig());
    return linksInjector.injectLinks(asDto(workspaceManager.updateWorkspace(id, workspace)), getServiceContext());
}
Also used : EnvironmentImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) ApiParam(io.swagger.annotations.ApiParam) ApiOperation(io.swagger.annotations.ApiOperation) QueryParam(javax.ws.rs.QueryParam) Service(org.eclipse.che.api.core.rest.Service) Consumes(javax.ws.rs.Consumes) Example(io.swagger.annotations.Example) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) WsAgentHealthChecker(org.eclipse.che.api.agent.server.WsAgentHealthChecker) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) ImmutableMap(com.google.common.collect.ImmutableMap) LINK_REL_GET_WORKSPACES(org.eclipse.che.api.workspace.shared.Constants.LINK_REL_GET_WORKSPACES) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) DtoFactory.newDto(org.eclipse.che.dto.server.DtoFactory.newDto) WsAgentHealthStateDto(org.eclipse.che.api.workspace.shared.dto.WsAgentHealthStateDto) LINK_REL_GET_BY_NAMESPACE(org.eclipse.che.api.workspace.shared.Constants.LINK_REL_GET_BY_NAMESPACE) String.format(java.lang.String.format) SnapshotDto(org.eclipse.che.api.machine.shared.dto.SnapshotDto) List(java.util.List) BadRequestException(org.eclipse.che.api.core.BadRequestException) DtoConverter.asDto(org.eclipse.che.api.workspace.server.DtoConverter.asDto) Response(javax.ws.rs.core.Response) EnvironmentRecipeDto(org.eclipse.che.api.workspace.shared.dto.EnvironmentRecipeDto) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) CommandDto(org.eclipse.che.api.machine.shared.dto.CommandDto) PathParam(javax.ws.rs.PathParam) GET(javax.ws.rs.GET) WorkspaceDto(org.eclipse.che.api.workspace.shared.dto.WorkspaceDto) ApiResponses(io.swagger.annotations.ApiResponses) Inject(javax.inject.Inject) EnvironmentDto(org.eclipse.che.api.workspace.shared.dto.EnvironmentDto) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) ConflictException(org.eclipse.che.api.core.ConflictException) Api(io.swagger.annotations.Api) Named(javax.inject.Named) GenerateLink(org.eclipse.che.api.core.rest.annotations.GenerateLink) Collections.emptyMap(java.util.Collections.emptyMap) POST(javax.ws.rs.POST) ProjectConfigDto(org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto) WorkspaceStatus(org.eclipse.che.api.core.model.workspace.WorkspaceStatus) WorkspaceConfigDto(org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto) CHE_WORKSPACE_AUTO_START(org.eclipse.che.api.workspace.shared.Constants.CHE_WORKSPACE_AUTO_START) Maps(com.google.common.collect.Maps) NotFoundException(org.eclipse.che.api.core.NotFoundException) Collectors.toList(java.util.stream.Collectors.toList) MachineImpl(org.eclipse.che.api.machine.server.model.impl.MachineImpl) ServerException(org.eclipse.che.api.core.ServerException) ApiResponse(io.swagger.annotations.ApiResponse) ExampleProperty(io.swagger.annotations.ExampleProperty) CommandImpl(org.eclipse.che.api.machine.server.model.impl.CommandImpl) ForbiddenException(org.eclipse.che.api.core.ForbiddenException) ProjectConfigImpl(org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl) CHE_WORKSPACE_AUTO_SNAPSHOT(org.eclipse.che.api.workspace.shared.Constants.CHE_WORKSPACE_AUTO_SNAPSHOT) PUT(javax.ws.rs.PUT) CHE_WORKSPACE_AUTO_RESTORE(org.eclipse.che.api.workspace.shared.Constants.CHE_WORKSPACE_AUTO_RESTORE) LINK_REL_CREATE_WORKSPACE(org.eclipse.che.api.workspace.shared.Constants.LINK_REL_CREATE_WORKSPACE) WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) NotFoundException(org.eclipse.che.api.core.NotFoundException) ProjectConfigImpl(org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) PUT(javax.ws.rs.PUT) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

ConflictException (org.eclipse.che.api.core.ConflictException)81 VirtualFile (org.eclipse.che.api.vfs.VirtualFile)28 ForbiddenException (org.eclipse.che.api.core.ForbiddenException)25 ServerException (org.eclipse.che.api.core.ServerException)24 Test (org.junit.Test)24 NotFoundException (org.eclipse.che.api.core.NotFoundException)17 Path (org.eclipse.che.api.vfs.Path)12 IOException (java.io.IOException)10 NewProjectConfig (org.eclipse.che.api.core.model.project.NewProjectConfig)8 Unlocker (org.eclipse.che.commons.lang.concurrent.Unlocker)8 ArrayList (java.util.ArrayList)7 BadRequestException (org.eclipse.che.api.core.BadRequestException)7 MachineException (org.eclipse.che.api.machine.server.exception.MachineException)7 File (java.io.File)6 ProjectConfig (org.eclipse.che.api.core.model.project.ProjectConfig)6 CommandImpl (org.eclipse.che.api.machine.server.model.impl.CommandImpl)6 List (java.util.List)5 Map (java.util.Map)5 WorkspaceImpl (org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl)5 String.format (java.lang.String.format)4