Search in sources :

Example 51 with ConflictException

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

the class MemoryVirtualFile method unlock.

@Override
public VirtualFile unlock(String lockToken) throws ForbiddenException, ConflictException {
    checkExistence();
    if (isFile()) {
        final LockHolder theLock = lock;
        if (theLock == null) {
            throw new ConflictException("File is not locked");
        } else if (isExpired(theLock)) {
            lock = null;
            throw new ConflictException("File is not locked");
        }
        if (theLock.lockToken.equals(lockToken)) {
            lock = null;
            lastModificationDate = System.currentTimeMillis();
        } else {
            throw new ForbiddenException("Unable remove lock from file. Lock token does not match");
        }
        lastModificationDate = System.currentTimeMillis();
        return this;
    } else {
        throw new ForbiddenException(String.format("Unable unlock '%s'. Locking allowed for files only", getPath()));
    }
}
Also used : ForbiddenException(org.eclipse.che.api.core.ForbiddenException) ConflictException(org.eclipse.che.api.core.ConflictException)

Example 52 with ConflictException

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

the class DockerProcess method start.

@Override
public void start(LineConsumer output) throws ConflictException, MachineException {
    if (started) {
        throw new ConflictException("Process already started.");
    }
    started = true;
    // Trap is invoked when bash session ends. Here we kill all sub-processes of shell and remove pid-file.
    final String trap = format("trap '[ -z \"$(jobs -p)\" ] || kill $(jobs -p); [ -e %1$s ] && rm %1$s' EXIT", pidFilePath);
    // 'echo' saves shell pid in file, then run command
    final String shellCommand = trap + "; echo $$>" + pidFilePath + "; " + commandLine;
    final String[] command = { shellInvoker, "-c", shellCommand };
    Exec exec;
    try {
        exec = docker.createExec(CreateExecParams.create(container, command).withDetach(output == null));
    } catch (IOException e) {
        throw new MachineException(format("Error occurs while initializing command %s in docker container %s: %s", Arrays.toString(command), container, e.getMessage()), e);
    }
    try {
        docker.startExec(StartExecParams.create(exec.getId()), output == null ? null : new LogMessagePrinter(output));
    } catch (IOException e) {
        if (output != null && e instanceof SocketTimeoutException) {
            throw new MachineException(getErrorMessage());
        } else {
            throw new MachineException(format("Error occurs while executing command %s: %s", Arrays.toString(exec.getCommand()), e.getMessage()), e);
        }
    }
}
Also used : Exec(org.eclipse.che.plugin.docker.client.Exec) SocketTimeoutException(java.net.SocketTimeoutException) ConflictException(org.eclipse.che.api.core.ConflictException) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) IOException(java.io.IOException)

Example 53 with ConflictException

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

the class SshMachineExecAgentLauncher method launch.

public void launch(SshMachineInstance machine, Agent agent) throws ServerException {
    if (isNullOrEmpty(agent.getScript())) {
        return;
    }
    try {
        String architecture = detectArchitecture(machine);
        machine.copy(archivePathProvider.getPath(architecture), terminalLocation);
        final AgentImpl agentCopy = new AgentImpl(agent);
        agentCopy.setScript(agent.getScript() + "\n" + terminalRunCommand);
        final SshMachineProcess process = start(machine, agentCopy);
        LOG.debug("Waiting for agent {} is launched. Workspace ID:{}", agentCopy.getId(), machine.getWorkspaceId());
        final long pingStartTimestamp = System.currentTimeMillis();
        SshProcessLaunchedChecker agentLaunchingChecker = new SshProcessLaunchedChecker("che-websocket-terminal");
        while (System.currentTimeMillis() - pingStartTimestamp < agentMaxStartTimeMs) {
            if (agentLaunchingChecker.isLaunched(agentCopy, machine)) {
                return;
            } else {
                Thread.sleep(agentPingDelayMs);
            }
        }
        process.kill();
        final String errMsg = format("Fail launching agent %s. Workspace ID:%s", agent.getName(), machine.getWorkspaceId());
        LOG.error(errMsg);
        throw new ServerException(errMsg);
    } catch (MachineException e) {
        throw new ServerException(e.getServiceError());
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new ServerException(format("Launching agent %s is interrupted", agent.getName()));
    } catch (ConflictException e) {
        // should never happen
        throw new ServerException("Internal server error occurs on terminal launching.");
    }
}
Also used : ServerException(org.eclipse.che.api.core.ServerException) ConflictException(org.eclipse.che.api.core.ConflictException) SshMachineProcess(org.eclipse.che.plugin.machine.ssh.SshMachineProcess) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) AgentImpl(org.eclipse.che.api.agent.shared.model.impl.AgentImpl)

Example 54 with ConflictException

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

the class FactoryBuilder method validateCompatibility.

/**
     * Validate compatibility of factory parameters.
     *
     * @param object
     *         - object to validate factory parameters
     * @param parent
     *         - parent object
     * @param methodsProvider
     *         - class that provides methods with {@link org.eclipse.che.api.core.factory.FactoryParameter}
     *         annotations
     * @param allowedMethodsProvider
     *         - class that provides allowed methods
     * @param version
     *         - version of factory
     * @param parentName
     *         - parent parameter queryParameterName
     * @throws org.eclipse.che.api.core.ConflictException
     */
void validateCompatibility(Object object, Object parent, Class methodsProvider, Class allowedMethodsProvider, Version version, String parentName, boolean isUpdate) throws ConflictException {
    // validate source
    if (SourceStorageDto.class.equals(methodsProvider) && !hasSubprojectInPath(parent)) {
        sourceStorageParametersValidator.validate((SourceStorage) object, version);
    }
    // get all methods recursively
    for (Method method : methodsProvider.getMethods()) {
        FactoryParameter factoryParameter = method.getAnnotation(FactoryParameter.class);
        if (factoryParameter == null) {
            continue;
        }
        String fullName = (parentName.isEmpty() ? "" : (parentName + ".")) + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, method.getName().startsWith("is") ? method.getName().substring(2) : method.getName().substring(3).toLowerCase());
        // check that field is set
        Object parameterValue;
        try {
            parameterValue = method.invoke(object);
        } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
            // should never happen
            LOG.error(e.getLocalizedMessage(), e);
            throw new ConflictException(FactoryConstants.INVALID_PARAMETER_MESSAGE);
        }
        // if value is null or empty collection or default value for primitives
        if (ValueHelper.isEmpty(parameterValue)) {
            // field must not be a mandatory, unless it's ignored or deprecated or doesn't suit to the version
            if (Obligation.MANDATORY.equals(factoryParameter.obligation()) && factoryParameter.deprecatedSince().compareTo(version) > 0 && factoryParameter.ignoredSince().compareTo(version) > 0 && method.getDeclaringClass().isAssignableFrom(allowedMethodsProvider)) {
                throw new ConflictException(String.format(FactoryConstants.MISSING_MANDATORY_MESSAGE, method.getName()));
            }
        } else if (!method.getDeclaringClass().isAssignableFrom(allowedMethodsProvider)) {
            throw new ConflictException(String.format(FactoryConstants.PARAMETRIZED_INVALID_PARAMETER_MESSAGE, fullName, version));
        } else {
            // is parameter deprecated
            if (factoryParameter.deprecatedSince().compareTo(version) <= 0 || (!isUpdate && factoryParameter.setByServer())) {
                throw new ConflictException(String.format(FactoryConstants.PARAMETRIZED_INVALID_PARAMETER_MESSAGE, fullName, version));
            }
            // use recursion if parameter is DTO object
            if (method.getReturnType().isAnnotationPresent(DTO.class)) {
                // validate inner objects such Git ot ProjectAttributes
                validateCompatibility(parameterValue, object, method.getReturnType(), method.getReturnType(), version, fullName, isUpdate);
            } else if (Map.class.isAssignableFrom(method.getReturnType())) {
                Type tp = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[1];
                Class secMapParamClass = (tp instanceof ParameterizedType) ? (Class) ((ParameterizedType) tp).getRawType() : (Class) tp;
                if (!String.class.equals(secMapParamClass) && !List.class.equals(secMapParamClass)) {
                    if (secMapParamClass.isAnnotationPresent(DTO.class)) {
                        Map<Object, Object> map = (Map) parameterValue;
                        for (Map.Entry<Object, Object> entry : map.entrySet()) {
                            validateCompatibility(entry.getValue(), object, secMapParamClass, secMapParamClass, version, fullName + "." + entry.getKey(), isUpdate);
                        }
                    } else {
                        throw new RuntimeException("This type of fields is not supported by factory.");
                    }
                }
            } else if (List.class.isAssignableFrom(method.getReturnType())) {
                Type tp = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0];
                Class secListParamClass = (tp instanceof ParameterizedType) ? (Class) ((ParameterizedType) tp).getRawType() : (Class) tp;
                if (!String.class.equals(secListParamClass) && !List.class.equals(secListParamClass)) {
                    if (secListParamClass.isAnnotationPresent(DTO.class)) {
                        List<Object> list = (List) parameterValue;
                        for (Object entry : list) {
                            validateCompatibility(entry, object, secListParamClass, secListParamClass, version, fullName, isUpdate);
                        }
                    } else {
                        throw new RuntimeException("This type of fields is not supported by factory.");
                    }
                }
            }
        }
    }
}
Also used : ConflictException(org.eclipse.che.api.core.ConflictException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) FactoryParameter(org.eclipse.che.api.core.factory.FactoryParameter) ParameterizedType(java.lang.reflect.ParameterizedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) SourceStorageDto(org.eclipse.che.api.workspace.shared.dto.SourceStorageDto) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) DTO(org.eclipse.che.dto.shared.DTO)

Example 55 with ConflictException

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

the class FactoryBuilder method checkValid.

/**
     * Validate factory compatibility.
     *
     * @param factory
     *         - factory object to validate
     * @param isUpdate
     *         - indicates is validation performed on update time.
     *           Set-by-server variables are allowed during update.
     * @throws ConflictException
     */
public void checkValid(FactoryDto factory, boolean isUpdate) throws ConflictException {
    if (null == factory) {
        throw new ConflictException(FactoryConstants.UNPARSABLE_FACTORY_MESSAGE);
    }
    if (factory.getV() == null) {
        throw new ConflictException(FactoryConstants.INVALID_VERSION_MESSAGE);
    }
    Version v;
    try {
        v = Version.fromString(factory.getV());
    } catch (IllegalArgumentException e) {
        throw new ConflictException(FactoryConstants.INVALID_VERSION_MESSAGE);
    }
    Class usedFactoryVersionMethodProvider;
    switch(v) {
        case V4_0:
            usedFactoryVersionMethodProvider = FactoryDto.class;
            break;
        default:
            throw new ConflictException(FactoryConstants.INVALID_VERSION_MESSAGE);
    }
    validateCompatibility(factory, null, FactoryDto.class, usedFactoryVersionMethodProvider, v, "", isUpdate);
}
Also used : ConflictException(org.eclipse.che.api.core.ConflictException) Version(org.eclipse.che.api.core.factory.FactoryParameter.Version)

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