Search in sources :

Example 31 with MachineException

use of org.eclipse.che.api.machine.server.exception.MachineException 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 32 with MachineException

use of org.eclipse.che.api.machine.server.exception.MachineException in project che by eclipse.

the class JschSshClient method copyRecursively.

private void copyRecursively(String sourceFolder, String targetFolder) throws MachineException {
    // create target dir
    try {
        int execCode = execAndGetCode("mkdir -p " + targetFolder);
        if (execCode != 0) {
            throw new MachineException(format("Creation of folder %s failed. Exit code is %s", targetFolder, execCode));
        }
    } catch (JSchException | IOException e) {
        throw new MachineException(format("Creation of folder %s failed. Error: %s", targetFolder, e.getLocalizedMessage()));
    }
    // not normalized paths don't work
    final String targetAbsolutePath = getAbsolutePath(targetFolder);
    // copy files
    ChannelSftp sftp = null;
    try {
        sftp = (ChannelSftp) session.openChannel("sftp");
        sftp.connect(connectionTimeout);
        final ChannelSftp finalSftp = sftp;
        Files.walkFileTree(Paths.get(sourceFolder), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                try {
                    if (!attrs.isDirectory()) {
                        copyFile(file.toString(), Paths.get(targetAbsolutePath, file.getFileName().toString()).toString(), finalSftp);
                    } else {
                        finalSftp.mkdir(file.normalize().toString());
                    }
                } catch (MachineException | SftpException e) {
                    throw new IOException(format("Sftp copying of file %s failed. Error: %s", file, e.getLocalizedMessage()));
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (JSchException | IOException e) {
        throw new MachineException("Copying failed. Error: " + e.getLocalizedMessage());
    } finally {
        if (sftp != null) {
            sftp.disconnect();
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) Path(java.nio.file.Path) ChannelSftp(com.jcraft.jsch.ChannelSftp) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 33 with MachineException

use of org.eclipse.che.api.machine.server.exception.MachineException in project che by eclipse.

the class JschSshClient method execAndGetOutput.

private String execAndGetOutput(String command) throws JSchException, MachineException, IOException {
    ChannelExec exec = (ChannelExec) session.openChannel("exec");
    exec.setCommand(command);
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
        InputStream erStream = exec.getErrStream()) {
        exec.connect(connectionTimeout);
        ListLineConsumer listLineConsumer = new ListLineConsumer();
        String line;
        while ((line = reader.readLine()) != null) {
            listLineConsumer.writeLine(line);
        }
        // read stream to wait until command finishes its work
        IoUtil.readStream(erStream);
        if (exec.getExitStatus() != 0) {
            throw new MachineException(format("Error code: %s. Error: %s", exec.getExitStatus(), IoUtil.readAndCloseQuietly(exec.getErrStream())));
        }
        return listLineConsumer.getText();
    } finally {
        exec.disconnect();
    }
}
Also used : ListLineConsumer(org.eclipse.che.api.core.util.ListLineConsumer) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) BufferedReader(java.io.BufferedReader) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 34 with MachineException

use of org.eclipse.che.api.machine.server.exception.MachineException in project che by eclipse.

the class RecipeDownloader method getRecipe.

/**
     * Downloads recipe by location.
     *
     * @param location
     *         location of recipe
     * @return recipe with set content and type
     * @throws ServerException
     *         if any error occurs
     */
public String getRecipe(String location) throws ServerException {
    URL recipeUrl;
    File file = null;
    try {
        UriBuilder targetUriBuilder = UriBuilder.fromUri(location);
        // add user token to be able to download user's private recipe
        final URI recipeUri = targetUriBuilder.build();
        if (!recipeUri.isAbsolute() && recipeUri.getHost() == null) {
            targetUriBuilder.scheme(apiEndpoint.getScheme()).host(apiEndpoint.getHost()).port(apiEndpoint.getPort()).replacePath(apiEndpoint.getPath() + location);
            if (EnvironmentContext.getCurrent().getSubject().getToken() != null) {
                targetUriBuilder.queryParam("token", EnvironmentContext.getCurrent().getSubject().getToken());
            }
        }
        recipeUrl = targetUriBuilder.build().toURL();
        file = IoUtil.downloadFileWithRedirect(null, "recipe", null, recipeUrl);
        return IoUtil.readAndCloseQuietly(new FileInputStream(file));
    } catch (IOException | IllegalArgumentException | UriBuilderException e) {
        throw new MachineException(format("Failed to download recipe %s. Error: %s", location, e.getLocalizedMessage()));
    } finally {
        if (file != null && !file.delete()) {
            LOG.error(String.format("Removal of recipe file %s failed.", file.getAbsolutePath()));
        }
    }
}
Also used : MachineException(org.eclipse.che.api.machine.server.exception.MachineException) IOException(java.io.IOException) UriBuilderException(javax.ws.rs.core.UriBuilderException) UriBuilder(javax.ws.rs.core.UriBuilder) File(java.io.File) URI(java.net.URI) URL(java.net.URL) FileInputStream(java.io.FileInputStream)

Example 35 with MachineException

use of org.eclipse.che.api.machine.server.exception.MachineException in project che by eclipse.

the class RecipeDownloader method getRecipe.

/**
     * Downloads recipe by location from {@link MachineSource#getLocation()}.
     *
     * @param machineConfig
     *         config used to get recipe location
     * @return recipe with set content and type
     * @throws MachineException
     *         if any error occurs
     */
public RecipeImpl getRecipe(MachineConfig machineConfig) throws MachineException {
    URL recipeUrl;
    File file = null;
    final String location = machineConfig.getSource().getLocation();
    try {
        UriBuilder targetUriBuilder = UriBuilder.fromUri(location);
        // add user token to be able to download user's private recipe
        final URI recipeUri = targetUriBuilder.build();
        if (!recipeUri.isAbsolute() && recipeUri.getHost() == null) {
            targetUriBuilder.scheme(apiEndpoint.getScheme()).host(apiEndpoint.getHost()).port(apiEndpoint.getPort()).replacePath(apiEndpoint.getPath() + location);
            if (EnvironmentContext.getCurrent().getSubject().getToken() != null) {
                targetUriBuilder.queryParam("token", EnvironmentContext.getCurrent().getSubject().getToken());
            }
        }
        recipeUrl = targetUriBuilder.build().toURL();
        file = IoUtil.downloadFileWithRedirect(null, "recipe", null, recipeUrl);
        return new RecipeImpl().withType(machineConfig.getSource().getType()).withScript(IoUtil.readAndCloseQuietly(new FileInputStream(file)));
    } catch (IOException | IllegalArgumentException e) {
        throw new MachineException(format("Failed to download recipe for machine %s. Recipe url %s. Error: %s", machineConfig.getName(), location, e.getLocalizedMessage()));
    } finally {
        if (file != null && !file.delete()) {
            LOG.error(String.format("Removal of recipe file %s failed.", file.getAbsolutePath()));
        }
    }
}
Also used : RecipeImpl(org.eclipse.che.api.machine.server.recipe.RecipeImpl) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) IOException(java.io.IOException) UriBuilder(javax.ws.rs.core.UriBuilder) File(java.io.File) URI(java.net.URI) URL(java.net.URL) FileInputStream(java.io.FileInputStream)

Aggregations

MachineException (org.eclipse.che.api.machine.server.exception.MachineException)35 IOException (java.io.IOException)17 ListLineConsumer (org.eclipse.che.api.core.util.ListLineConsumer)7 ConflictException (org.eclipse.che.api.core.ConflictException)6 ServerException (org.eclipse.che.api.core.ServerException)6 InstanceProcess (org.eclipse.che.api.machine.server.spi.InstanceProcess)6 JSchException (com.jcraft.jsch.JSchException)5 File (java.io.File)5 LineConsumer (org.eclipse.che.api.core.util.LineConsumer)5 Instance (org.eclipse.che.api.machine.server.spi.Instance)5 Test (org.testng.annotations.Test)5 Agent (org.eclipse.che.api.agent.shared.model.Agent)4 Command (org.eclipse.che.api.core.model.machine.Command)4 CommandImpl (org.eclipse.che.api.machine.server.model.impl.CommandImpl)4 Exec (org.eclipse.che.plugin.docker.client.Exec)4 URL (java.net.URL)3 NotFoundException (org.eclipse.che.api.core.NotFoundException)3 AbstractLineConsumer (org.eclipse.che.api.core.util.AbstractLineConsumer)3 ChannelExec (com.jcraft.jsch.ChannelExec)2 ChannelSftp (com.jcraft.jsch.ChannelSftp)2