Search in sources :

Example 26 with Session

use of org.neo4j.driver.v1.Session in project nimbus by nimbus-org.

the class SCPClientImpl method mget.

public File[] mget(String remote, String localDir) throws SCPException {
    if (remote == null || remote.length() == 0) {
        throw new SCPException("Path is null.");
    }
    if (localDir == null) {
        localDir = ".";
    }
    File localDirFile = new File(localDir);
    if (homeDir != null && !localDirFile.isAbsolute()) {
        localDirFile = new File(homeDir, localDir);
    }
    List localFiles = new ArrayList();
    Session session = null;
    final String cmd = "scp -f " + remote;
    File localFile = null;
    try {
        session = connection.openSession();
        session.execCommand(cmd);
        byte[] buf = new byte[1024];
        OutputStream os = new BufferedOutputStream(session.getStdin(), 512);
        InputStream is = new BufferedInputStream(session.getStdout(), 40000);
        os.write(0);
        os.flush();
        while (true) {
            int c = checkAck(is);
            if (c == -1) {
                if (localFiles.size() == 0) {
                    throw new IOException("Remote SCP terminated unexpectedly.");
                }
                break;
            }
            if (c != 'C') {
                break;
            }
            is.read(buf, 0, 5);
            long fileSize = 0L;
            while (true) {
                if (is.read(buf, 0, 1) < 0) {
                    throw new SCPException("Unexpected EOF.");
                }
                if (buf[0] == ' ') {
                    break;
                }
                fileSize = fileSize * 10L + (long) (buf[0] - '0');
            }
            String fileName = null;
            for (int i = 0; ; i++) {
                is.read(buf, i, 1);
                if (buf[i] == (byte) 0x0a) {
                    fileName = new String(buf, 0, i);
                    break;
                }
            }
            buf[0] = 0;
            os.write(buf, 0, 1);
            os.flush();
            localFile = new File(localDirFile, fileName);
            localFiles.add(localFile);
            FileOutputStream fos = new FileOutputStream(localFile);
            try {
                int readLen = 0;
                while (true) {
                    if (buf.length < fileSize) {
                        readLen = buf.length;
                    } else {
                        readLen = (int) fileSize;
                    }
                    readLen = is.read(buf, 0, readLen);
                    if (readLen < 0) {
                        throw new SCPException("Unexpected EOF.");
                    }
                    fos.write(buf, 0, readLen);
                    fileSize -= readLen;
                    if (fileSize == 0L) {
                        break;
                    }
                }
            } finally {
                fos.close();
                fos = null;
            }
            checkAck(is);
            localFile = null;
            buf[0] = 0;
            os.write(buf, 0, 1);
            os.flush();
        }
    } catch (IOException e) {
        throw new SCPException("It failed to mget! from=" + remote + ", to=" + (localFile == null ? localDirFile : localFile), e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return (File[]) localFiles.toArray(new File[localFiles.size()]);
}
Also used : BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SCPException(jp.ossc.nimbus.service.scp.SCPException) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FileOutputStream(java.io.FileOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) RecurciveSearchFile(jp.ossc.nimbus.io.RecurciveSearchFile) BufferedOutputStream(java.io.BufferedOutputStream) Session(ch.ethz.ssh2.Session)

Example 27 with Session

use of org.neo4j.driver.v1.Session in project cosmic by MissionCriticalCloud.

the class SshHelperTest method canEndTheSshConnectionTest.

@Test
public void canEndTheSshConnectionTest() throws Exception {
    PowerMockito.spy(SshHelper.class);
    final Session mockedSession = Mockito.mock(Session.class);
    PowerMockito.doReturn(true).when(SshHelper.class, "isChannelConditionEof", Mockito.anyInt());
    Mockito.when(mockedSession.waitForCondition(ChannelCondition.EXIT_STATUS, 1l)).thenReturn(0);
    PowerMockito.doNothing().when(SshHelper.class, "throwSshExceptionIfConditionsTimeout", Mockito.anyInt());
    SshHelper.canEndTheSshConnection(1, mockedSession, 0);
    PowerMockito.verifyStatic();
    SshHelper.isChannelConditionEof(Mockito.anyInt());
    SshHelper.throwSshExceptionIfConditionsTimeout(Mockito.anyInt());
    Mockito.verify(mockedSession).waitForCondition(ChannelCondition.EXIT_STATUS, 1l);
}
Also used : Session(com.trilead.ssh2.Session) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 28 with Session

use of org.neo4j.driver.v1.Session in project cosmic by MissionCriticalCloud.

the class SshHelper method sshExecute.

public static Pair<Boolean, String> sshExecute(final String host, final int port, final String user, final File pemKeyFile, final String password, final String command, final int connectTimeoutInMs, final int kexTimeoutInMs, final int waitResultTimeoutInMs) throws Exception {
    com.trilead.ssh2.Connection conn = null;
    com.trilead.ssh2.Session sess = null;
    try {
        conn = new com.trilead.ssh2.Connection(host, port);
        conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
        if (pemKeyFile == null) {
            if (!conn.authenticateWithPassword(user, password)) {
                final String msg = "Failed to authentication SSH user " + user + " on host " + host;
                s_logger.error(msg);
                throw new Exception(msg);
            }
        } else {
            if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
                final String msg = "Failed to authentication SSH user " + user + " on host " + host;
                s_logger.error(msg);
                throw new Exception(msg);
            }
        }
        sess = openConnectionSession(conn);
        sess.execCommand(command);
        final InputStream stdout = sess.getStdout();
        final InputStream stderr = sess.getStderr();
        final byte[] buffer = new byte[8192];
        final StringBuffer sbResult = new StringBuffer();
        int currentReadBytes = 0;
        while (true) {
            throwSshExceptionIfStdoutOrStdeerIsNull(stdout, stderr);
            if ((stdout.available() == 0) && (stderr.available() == 0)) {
                final int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, waitResultTimeoutInMs);
                throwSshExceptionIfConditionsTimeout(conditions);
                if ((conditions & ChannelCondition.EXIT_STATUS) != 0) {
                    break;
                }
                if (canEndTheSshConnection(waitResultTimeoutInMs, sess, conditions)) {
                    break;
                }
            }
            while (stdout.available() > 0) {
                currentReadBytes = stdout.read(buffer);
                sbResult.append(new String(buffer, 0, currentReadBytes));
            }
            while (stderr.available() > 0) {
                currentReadBytes = stderr.read(buffer);
                sbResult.append(new String(buffer, 0, currentReadBytes));
            }
        }
        final String result = sbResult.toString();
        if (sess.getExitStatus() == null) {
            // Exit status is NOT available. Returning failure result.
            s_logger.error(String.format("SSH execution of command %s has no exit status set. Result output: %s", command, result));
            return new Pair<>(false, result);
        }
        if (sess.getExitStatus() != null && sess.getExitStatus().intValue() != 0) {
            s_logger.error(String.format("SSH execution of command %s has an error status code in return. Result output: %s", command, result));
            return new Pair<>(false, result);
        }
        return new Pair<>(true, result);
    } finally {
        if (sess != null) {
            sess.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}
Also used : Session(com.trilead.ssh2.Session) InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) IOException(java.io.IOException) Pair(com.cloud.utils.Pair)

Example 29 with Session

use of org.neo4j.driver.v1.Session in project cosmic by MissionCriticalCloud.

the class SSHCmdHelper method sshExecuteCmdOneShotWithExitCode.

public static int sshExecuteCmdOneShotWithExitCode(final com.trilead.ssh2.Connection sshConnection, final String cmd) throws SshException {
    s_logger.debug("Executing cmd: " + cmd);
    Session sshSession = null;
    try {
        sshSession = sshConnection.openSession();
        // There is a bug in Trilead library, wait a second before
        // starting a shell and executing commands, from http://spci.st.ewi.tudelft.nl/chiron/xref/nl/tudelft/swerl/util/SSHConnection.html
        Thread.sleep(1000);
        if (sshSession == null) {
            throw new SshException("Cannot open ssh session");
        }
        sshSession.execCommand(cmd);
        final InputStream stdout = sshSession.getStdout();
        final InputStream stderr = sshSession.getStderr();
        final byte[] buffer = new byte[8192];
        final StringBuffer sbResult = new StringBuffer();
        int currentReadBytes = 0;
        while (true) {
            if (stdout == null || stderr == null) {
                throw new SshException("stdout or stderr of ssh session is null");
            }
            if ((stdout.available() == 0) && (stderr.available() == 0)) {
                final int conditions = sshSession.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, 120000);
                if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                    final String msg = "Timed out in waiting SSH execution result";
                    s_logger.error(msg);
                    throw new Exception(msg);
                }
                if ((conditions & ChannelCondition.EXIT_STATUS) != 0) {
                    if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                        break;
                    }
                }
                if ((conditions & ChannelCondition.EOF) != 0) {
                    if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                        break;
                    }
                }
            }
            while (stdout.available() > 0) {
                currentReadBytes = stdout.read(buffer);
                sbResult.append(new String(buffer, 0, currentReadBytes));
            }
            while (stderr.available() > 0) {
                currentReadBytes = stderr.read(buffer);
                sbResult.append(new String(buffer, 0, currentReadBytes));
            }
        }
        final String result = sbResult.toString();
        if (result != null && !result.isEmpty()) {
            s_logger.debug(cmd + " output:" + result);
        }
        // exit status delivery might get delayed
        for (int i = 0; i < 10; i++) {
            final Integer status = sshSession.getExitStatus();
            if (status != null) {
                return status;
            }
            Thread.sleep(100);
        }
        return -1;
    } catch (final Exception e) {
        s_logger.debug("Ssh executed failed", e);
        throw new SshException("Ssh executed failed " + e.getMessage());
    } finally {
        if (sshSession != null) {
            sshSession.close();
        }
    }
}
Also used : InputStream(java.io.InputStream) IOException(java.io.IOException) Session(com.trilead.ssh2.Session)

Example 30 with Session

use of org.neo4j.driver.v1.Session in project wildfly-swarm by wildfly-swarm.

the class BMTStatefulTestBean method twoTransactions.

public String twoTransactions() throws Exception {
    // start the JTA transaction via javax.transaction.UserTransaction
    userTransaction.begin();
    try {
        // obtain session which will be enlisted into the JTA transaction.
        Session session = driver.session();
        if (session != driver.session()) {
            throw new RuntimeException("multiple calls to Driver.session() must return the same session within JTA transaction.");
        }
        // Calls to Session.beginTransaction() in a JTA transaction are expected to throw a RuntimeException
        try {
            Transaction transaction = session.beginTransaction();
            fail("Calling Session.beginTransaction in a JTA transaction should throw a RuntimeException.");
        } catch (RuntimeException expectedException) {
        // success
        }
        session.run("CREATE (a:Person {name:'BMT', title:'King'})");
        // calls to close the session should also be ignored, since the session is also considered to be enlisted into the JTA transaction
        session.close();
        if (session.isOpen() != true) {
            throw new RuntimeException("Session should be open since JTA transaction is still active.");
        }
        // commit the JTA transaction, which also calls org.neo4j.driver.v1.Transaction.success()/close().
        // if the JTA transaction rolls back, org.neo4j.driver.v1.Transaction.failure()/close() would instead be called.
        userTransaction.commit();
        if (session.isOpen() != false) {
            throw new RuntimeException("Session should now be closed since JTA transaction ended.");
        }
        // should be ignored
        session.close();
        // Start another JTA transaction, note that the session has to be obtained again
        userTransaction.begin();
        session = driver.session();
        if (session != driver.session()) {
            throw new RuntimeException("multiple calls to Driver.session() must return the same session within JTA transaction.");
        }
        // Calls to Session.beginTransaction() in a JTA transaction are expected to throw a RuntimeException
        try {
            Transaction transaction = session.beginTransaction();
            fail("Calling Session.beginTransaction in a JTA transaction should throw a RuntimeException.");
        } catch (RuntimeException expectedException) {
        // success
        }
        StatementResult result = session.run("MATCH (a:Person) WHERE a.name = 'BMT' RETURN a.name AS name, a.title AS title");
        Record record = result.next();
        return record.toString();
    } finally {
        if (userTransaction.getStatus() == Status.STATUS_ACTIVE) {
            // second JTA transaction is ended, which also closes the enlisted org.neo4j.driver.v1.Transaction/Session
            userTransaction.commit();
        }
        Session cleanupSession = driver.session();
        cleanupSession.run("MATCH (a:Person) delete a");
        cleanupSession.close();
    }
}
Also used : StatementResult(org.neo4j.driver.v1.StatementResult) UserTransaction(javax.transaction.UserTransaction) Transaction(org.neo4j.driver.v1.Transaction) Record(org.neo4j.driver.v1.Record) Session(org.neo4j.driver.v1.Session)

Aggregations

Session (com.trilead.ssh2.Session)43 Session (org.neo4j.driver.v1.Session)38 Connection (com.trilead.ssh2.Connection)32 IOException (java.io.IOException)30 Test (org.junit.Test)30 Driver (org.neo4j.driver.v1.Driver)29 InputStream (java.io.InputStream)28 StatementResult (org.neo4j.driver.v1.StatementResult)20 Record (org.neo4j.driver.v1.Record)15 Session (iaik.pkcs.pkcs11.Session)10 TokenException (iaik.pkcs.pkcs11.TokenException)10 CoreClusterMember (org.neo4j.causalclustering.discovery.CoreClusterMember)10 P11TokenException (org.xipki.security.exception.P11TokenException)10 RoutingNetworkSession (org.neo4j.driver.internal.RoutingNetworkSession)9 Session (ch.ethz.ssh2.Session)8 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HttpException (org.apache.commons.httpclient.HttpException)8 Transaction (org.neo4j.driver.v1.Transaction)8 SCPClient (com.trilead.ssh2.SCPClient)6