Package net.schmizz.sshj.connection.channel.direct

Examples of net.schmizz.sshj.connection.channel.direct.Session


    }

    public void makeDirectory(InvocationContext context) throws ProviderException {
        ApplicationDeploymentDescriptionType app = context.getExecutionDescription().getApp().getType();

        Session session = null;
        try {
            session = getSession(context);

            StringBuilder commandString = new StringBuilder();

            commandString.append("mkdir -p ");
            commandString.append(app.getScratchWorkingDirectory());
            commandString.append(" ; ");
            commandString.append("mkdir -p ");
            commandString.append(app.getStaticWorkingDirectory());
            commandString.append(" ; ");
            commandString.append("mkdir -p ");
            commandString.append(app.getInputDataDirectory());
            commandString.append(" ; ");
            commandString.append("mkdir -p ");
            commandString.append(app.getOutputDataDirectory());

            Command cmd = session.exec(commandString.toString());
            cmd.join(COMMAND_EXECUTION_TIMEOUT, TimeUnit.SECONDS);
        } catch (ConnectionException e) {
            throw new ProviderException(e.getMessage(), e);
        } catch (TransportException e) {
            throw new ProviderException(e.getMessage(), e);
View Full Code Here


    }

    public void executeApplication(InvocationContext context) throws ProviderException {
        ApplicationDeploymentDescriptionType app = context.getExecutionDescription().getApp().getType();

        Session session = null;
        try {
            session = getSession(context);

            /*
             * Going to working Directory
             */
            session.exec("cd " + app.getStaticWorkingDirectory());

            // get the env of the host and the application
            NameValuePairType[] env = app.getApplicationEnvironmentArray();

            Map<String, String> nv = new HashMap<String, String>();
            if (env != null) {
                for (int i = 0; i < env.length; i++) {
                    String key = env[i].getName();
                    String value = env[i].getValue();
                    nv.put(key, value);
                }
            }
            // extra env's
            nv.put(GFacConstants.INPUT_DATA_DIR_VAR_NAME, app.getInputDataDirectory());
            nv.put(GFacConstants.OUTPUT_DATA_DIR_VAR_NAME, app.getOutputDataDirectory());

            /*
             * Set environment
             */
            log.info("Command = " + command);
            for (Entry<String, String> entry : nv.entrySet()) {
                log.info("Env[" + entry.getKey() + "] = " + entry.getValue());
                session.setEnvVar(entry.getKey(), entry.getValue());
            }

            /*
             * Execute
             */
            Command cmd = session.exec(command);
            log.info("stdout=" + GfacUtils.readFromStream(session.getInputStream()));
            cmd.join(COMMAND_EXECUTION_TIMEOUT, TimeUnit.SECONDS);

            /*
             * check return value. usually not very helpful to draw conclusions based on return values so don't bother.
             * just provide warning in the log messages
View Full Code Here

    @Test
    public void testConnectToLocalhostAndCollectOutput() throws IOException {
        SSHClient client = Ssh.newClient(localhost, adminAccess, 1000);
        try {
            Session session = client.startSession();
            try {
                final Session.Command command = session.exec("echo 'stdout' && echo 'stderr' 1>&2");

                String stdout = CharStreams.toString(new InputStreamReader(command.getInputStream()));
                String stderr = CharStreams.toString(new InputStreamReader(command.getErrorStream()));

                command.join();
                assertThat(command.getExitStatus()).isEqualTo(0);
                assertThat(command.getExitErrorMessage()).isNull();

                assertThat(stdout).contains("stdout");
                assertThat(stderr).contains("stderr");

            } finally {
                session.close();
            }
        } finally {
            client.close();
        }
    }
View Full Code Here

    @Test
    public void testConnectStreamLoggerToCommand() throws IOException, InterruptedException {
        SSHClient client = Ssh.newClient(localhost, adminAccess, 1000);
        try {
            Session session = client.startSession();
            try {
                final Session.Command command = session.exec("echo 'line1' && echo && echo 'line2'");
                final List<String> lines = Lists.newCopyOnWriteArrayList();

                StreamLogger logger = new StreamLogger(command.getInputStream(), LOG, MarkerFactory.getMarker("live")) {
                    @Override
                    protected void log(Logger logger, Marker marker, String line) {
                        logger.info(marker, line)/* just for visual inspection */
                        lines.add(line);
                    }
                };
                logger.start();

                command.join();
                logger.join();

                assertThat(lines).hasSize(2).contains("line1", "line2");

            } finally {
                session.close();
            }
        } finally {
            client.close();
        }
    }
View Full Code Here

            String content = UUID.randomUUID().toString();

            Ssh.createFile(client, content, 0600, destination);

            /* Check the file exists and has the expected content */
            Session session = client.startSession();
            try {
                final Session.Command command = session.exec("set +x +e && cat " + destination);

                String output = CharStreams.toString(new InputStreamReader(command.getInputStream()));
                command.join();

                assertThat(command.getExitStatus()).isEqualTo(0);
                assertThat(output).contains(content);

            } finally {
                session.close();
            }
        } finally {
            client.close();
        }

View Full Code Here

            }

            final String destination = "/tmp/" + remoteFileName + ".pp";
            Ssh.createFile(client, createPuppetScript(pool, machine), 0600, destination);

            Session session = client.startSession();
            try {
                session.allocateDefaultPTY();

                // TODO: extract this loop outside of this activity (probably using a business process error)
                final String runScriptWithWaitCommand = "while ! which puppet &> /dev/null ; " +
                    "do echo 'Puppet command not found. Waiting for userdata.sh script to finish (10s)' " +
                    "&& sleep 10; " +
                    "done " +
                    "&& sudo puppet apply --detailed-exitcodes --debug --verbose " + destination;
                Session.Command command = session.exec(runScriptWithWaitCommand);

                Ssh.logCommandOutput(LOG, machine.getExternalId(), command);
                command.join();

                final Integer exitStatus = command.getExitStatus();
                if (exitStatus != PUPPET_FINISHED_WITH_NO_FAILURES && exitStatus != 0) {
                    throw new RuntimeException(String.format("Failed to execute puppet. " +
                        "Exit code: %d. Exit message: %s", exitStatus, command.getExitErrorMessage()));

                } else {
                    LOG.info("<< Command completed successfully with exit code 0");
                }


            } finally {
                session.close();
            }
        } finally {
            client.close();
        }
    }
View Full Code Here

    private void assertSshCommand(Machine machine, AdminAccess adminAccess, String bashCommand) throws IOException {
        LOG.info("Checking return code for command '{}' on machine {}", bashCommand, machine.getExternalId());
        SSHClient client = Ssh.newClient(machine, adminAccess);
        try {
            Session session = client.startSession();
            try {
                session.allocateDefaultPTY();
                Session.Command command = session.exec(bashCommand);

                command.join();
                assertTrue("Exit code was " + command.getExitStatus() + " for command " + bashCommand,
                    command.getExitStatus() == 0);
            } finally {
                session.close();
            }
        } finally {
            client.close();
        }
    }
View Full Code Here

    ssh.loadKnownHosts();
    ssh.addHostKeyVerifier(new NullHostKeyVerifier());
    ssh.connect(vmName);
    ssh.authPassword(vmUser, vmPwd);

    final Session session = ssh.startSession();
    try {
      final Command cmd = session.exec(command);
      System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
      cmd.join(10, TimeUnit.SECONDS);
      System.out
          .println("\n** exit status: " + cmd.getExitStatus() + " for the cmd " + command + " on " + vmName);
      if (cmd.getExitStatus() != 0) {
View Full Code Here

    }

    public void execute(JobExecutionContext jobExecutionContext) throws GFacProviderException {
        if (gsiSshProvider == null) {
            ApplicationDeploymentDescriptionType app = jobExecutionContext.getApplicationContext().getApplicationDeploymentDescription().getType();
            Session session = null;
            try {
                session = securityContext.getSession(jobExecutionContext.getApplicationContext().getHostDescription().getType().getHostAddress());
                /*
                 * Execute
                 */
                String execuable = app.getStaticWorkingDirectory() + File.separatorChar + Constants.EXECUTABLE_NAME;
                GFacUtils.updateApplicationJobStatus(jobExecutionContext, jobID, ApplicationJobStatus.SUBMITTED);
                Command cmd = session.exec("/bin/chmod 755 " + execuable + "; " + execuable);
                GFacUtils.updateApplicationJobStatus(jobExecutionContext, jobID, ApplicationJobStatus.RESULTS_RETRIEVE);
                log.info("stdout=" + GFacUtils.readFromStream(session.getInputStream()));
                cmd.join(Constants.COMMAND_EXECUTION_TIMEOUT, TimeUnit.SECONDS);

                /*
                 * check return value. usually not very helpful to draw conclusions
                 * based on return values so don't bother. just provide warning in
View Full Code Here

            public abstract void act(Session session, Session.Shell shell) throws Exception;
        }

        public void withSession(WithLowLevelSession withSession) {
            try {
                final Session s = getSession();
//                final Session.Shell shell = s.startShell();
                withSession.act(s, null);

                if (!reuseSession) {
                    s.close();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
View Full Code Here

TOP

Related Classes of net.schmizz.sshj.connection.channel.direct.Session

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.