Search in sources :

Example 21 with Connection

use of com.trilead.ssh2.Connection in project cloudstack by apache.

the class CitrixResourceBase method setupServer.

/* return : if setup is needed */
public boolean setupServer(final Connection conn, final Host host) {
    final String packageVersion = CitrixResourceBase.class.getPackage().getImplementationVersion();
    final String version = this.getClass().getName() + "-" + (packageVersion == null ? Long.toString(System.currentTimeMillis()) : packageVersion);
    try {
        /* push patches to XenServer */
        final Host.Record hr = host.getRecord(conn);
        final Iterator<String> it = hr.tags.iterator();
        while (it.hasNext()) {
            final String tag = it.next();
            if (tag.startsWith("vmops-version-")) {
                if (tag.contains(version)) {
                    s_logger.info(logX(host, "Host " + hr.address + " is already setup."));
                    return false;
                } else {
                    it.remove();
                }
            }
        }
        final com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(hr.address, 22);
        try {
            sshConnection.connect(null, 60000, 60000);
            if (!sshConnection.authenticateWithPassword(_username, _password.peek())) {
                throw new CloudRuntimeException("Unable to authenticate");
            }
            final String cmd = "mkdir -p /opt/cloud/bin /var/log/cloud";
            if (!SSHCmdHelper.sshExecuteCmd(sshConnection, cmd)) {
                throw new CloudRuntimeException("Cannot create directory /opt/cloud/bin on XenServer hosts");
            }
            final SCPClient scp = new SCPClient(sshConnection);
            final List<File> files = getPatchFiles();
            if (files == null || files.isEmpty()) {
                throw new CloudRuntimeException("Can not find patch file");
            }
            for (final File file : files) {
                final String path = file.getParentFile().getAbsolutePath() + "/";
                final Properties props = PropertiesUtil.loadFromFile(file);
                for (final Map.Entry<Object, Object> entry : props.entrySet()) {
                    final String k = (String) entry.getKey();
                    final String v = (String) entry.getValue();
                    assert k != null && k.length() > 0 && v != null && v.length() > 0 : "Problems with " + k + "=" + v;
                    final String[] tokens = v.split(",");
                    String f = null;
                    if (tokens.length == 3 && tokens[0].length() > 0) {
                        if (tokens[0].startsWith("/")) {
                            f = tokens[0];
                        } else if (tokens[0].startsWith("~")) {
                            final String homedir = System.getenv("HOME");
                            f = homedir + tokens[0].substring(1) + k;
                        } else {
                            f = path + tokens[0] + '/' + k;
                        }
                    } else {
                        f = path + k;
                    }
                    final String directoryPath = tokens[tokens.length - 1];
                    f = f.replace('/', File.separatorChar);
                    String permissions = "0755";
                    if (tokens.length == 3) {
                        permissions = tokens[1];
                    } else if (tokens.length == 2) {
                        permissions = tokens[0];
                    }
                    if (!new File(f).exists()) {
                        s_logger.warn("We cannot locate " + f);
                        continue;
                    }
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("Copying " + f + " to " + directoryPath + " on " + hr.address + " with permission " + permissions);
                    }
                    if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "mkdir -m 700 -p " + directoryPath)) {
                        s_logger.debug("Unable to create destination path: " + directoryPath + " on " + hr.address + ".");
                    }
                    try {
                        scp.put(f, directoryPath, permissions);
                    } catch (final IOException e) {
                        final String msg = "Unable to copy file " + f + " to path " + directoryPath + " with permissions  " + permissions;
                        s_logger.debug(msg);
                        throw new CloudRuntimeException("Unable to setup the server: " + msg, e);
                    }
                }
            }
        } catch (final IOException e) {
            throw new CloudRuntimeException("Unable to setup the server correctly", e);
        } finally {
            sshConnection.close();
        }
        hr.tags.add("vmops-version-" + version);
        host.setTags(conn, hr.tags);
        return true;
    } catch (final XenAPIException e) {
        final String msg = "XenServer setup failed due to " + e.toString();
        s_logger.warn(msg, e);
        throw new CloudRuntimeException("Unable to get host information " + e.toString(), e);
    } catch (final XmlRpcException e) {
        final String msg = "XenServer setup failed due to " + e.getMessage();
        s_logger.warn(msg, e);
        throw new CloudRuntimeException("Unable to get host information ", e);
    }
}
Also used : SCPClient(com.trilead.ssh2.SCPClient) Connection(com.xensource.xenapi.Connection) URLConnection(java.net.URLConnection) XenAPIException(com.xensource.xenapi.Types.XenAPIException) Host(com.xensource.xenapi.Host) IOException(java.io.IOException) Properties(java.util.Properties) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) XenAPIObject(com.xensource.xenapi.XenAPIObject) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) XmlRpcException(org.apache.xmlrpc.XmlRpcException)

Example 22 with Connection

use of com.trilead.ssh2.Connection in project cloudstack by apache.

the class TestClientWithAPI method sshTest.

private static String sshTest(String host, String password, String snapshotTest) {
    int i = 0;
    if (host == null) {
        s_logger.info("Did not receive a host back from test, ignoring ssh test");
        return null;
    }
    if (password == null) {
        s_logger.info("Did not receive a password back from test, ignoring ssh test");
        return null;
    }
    // We will retry 5 times before quitting
    String result = null;
    int retry = 0;
    while (true) {
        try {
            if (retry > 0) {
                s_logger.info("Retry attempt : " + retry + " ...sleeping 120 seconds before next attempt. Account is " + s_account.get());
                Thread.sleep(120000);
            }
            s_logger.info("Attempting to SSH into linux host " + host + " with retry attempt: " + retry + ". Account is " + s_account.get());
            Connection conn = new Connection(host);
            conn.connect(null, 60000, 60000);
            s_logger.info("User + " + s_account.get() + " ssHed successfully into linux host " + host);
            boolean isAuthenticated = conn.authenticateWithPassword("root", password);
            if (isAuthenticated == false) {
                s_logger.info("Authentication failed for root with password" + password);
                return "Authentication failed";
            }
            boolean success = false;
            String linuxCommand = null;
            if (i % 10 == 0)
                linuxCommand = "rm -rf *; wget http://" + downloadUrl + " && ls -al dump.bin";
            else
                linuxCommand = "wget http://" + downloadUrl + " && ls -al dump.bin";
            Session sess = conn.openSession();
            s_logger.info("User " + s_account.get() + " executing : " + linuxCommand);
            sess.execCommand(linuxCommand);
            InputStream stdout = sess.getStdout();
            InputStream stderr = sess.getStderr();
            byte[] buffer = new byte[8192];
            while (true) {
                if ((stdout.available() == 0) && (stderr.available() == 0)) {
                    int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 120000);
                    if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                        s_logger.info("Timeout while waiting for data from peer.");
                        return null;
                    }
                    if ((conditions & ChannelCondition.EOF) != 0) {
                        if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                            break;
                        }
                    }
                }
                while (stdout.available() > 0) {
                    success = true;
                    int len = stdout.read(buffer);
                    if (// this check is somewhat paranoid
                    len > 0)
                        s_logger.info(new String(buffer, 0, len));
                }
                while (stderr.available() > 0) {
                    /* int len = */
                    stderr.read(buffer);
                }
            }
            sess.close();
            conn.close();
            if (!success) {
                retry++;
                if (retry == MAX_RETRY_LINUX) {
                    result = "SSH Linux Network test fail";
                }
            }
            if (snapshotTest.equals("no"))
                return result;
            else {
                Long sleep = 300000L;
                s_logger.info("Sleeping for " + sleep / 1000 / 60 + "minutes before executing next ssh test");
                Thread.sleep(sleep);
            }
        } catch (Exception e) {
            retry++;
            s_logger.error("SSH Linux Network test fail with error");
            if ((retry == MAX_RETRY_LINUX) && (snapshotTest.equals("no"))) {
                return "SSH Linux Network test fail with error " + e.getMessage();
            }
        }
        i++;
    }
}
Also used : InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Session(com.trilead.ssh2.Session)

Example 23 with Connection

use of com.trilead.ssh2.Connection in project cloudstack by apache.

the class StressTestDirectAttach method sshTest.

private static String sshTest(String host, String password) {
    int i = 0;
    if (host == null) {
        s_logger.info("Did not receive a host back from test, ignoring ssh test");
        return null;
    }
    if (password == null) {
        s_logger.info("Did not receive a password back from test, ignoring ssh test");
        return null;
    }
    // We will retry 5 times before quitting
    String result = null;
    int retry = 0;
    while (true) {
        try {
            if (retry > 0) {
                s_logger.info("Retry attempt : " + retry + " ...sleeping 120 seconds before next attempt. Account is " + s_account.get());
                Thread.sleep(120000);
            }
            s_logger.info("Attempting to SSH into linux host " + host + " with retry attempt: " + retry + ". Account is " + s_account.get());
            Connection conn = new Connection(host);
            conn.connect(null, 60000, 60000);
            s_logger.info("User + " + s_account.get() + " ssHed successfully into linux host " + host);
            boolean isAuthenticated = conn.authenticateWithPassword("root", password);
            if (isAuthenticated == false) {
                s_logger.info("Authentication failed for root with password" + password);
                return "Authentication failed";
            }
            boolean success = false;
            String linuxCommand = null;
            if (i % 10 == 0)
                linuxCommand = "rm -rf *; wget http://192.168.1.250/dump.bin && ls -al dump.bin";
            else
                linuxCommand = "wget http://192.168.1.250/dump.bin && ls -al dump.bin";
            Session sess = conn.openSession();
            s_logger.info("User " + s_account.get() + " executing : " + linuxCommand);
            sess.execCommand(linuxCommand);
            InputStream stdout = sess.getStdout();
            InputStream stderr = sess.getStderr();
            byte[] buffer = new byte[8192];
            while (true) {
                if ((stdout.available() == 0) && (stderr.available() == 0)) {
                    int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 120000);
                    if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                        s_logger.info("Timeout while waiting for data from peer.");
                        return null;
                    }
                    if ((conditions & ChannelCondition.EOF) != 0) {
                        if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                            break;
                        }
                    }
                }
                while (stdout.available() > 0) {
                    success = true;
                    int len = stdout.read(buffer);
                    if (// this check is somewhat paranoid
                    len > 0)
                        s_logger.info(new String(buffer, 0, len));
                }
                while (stderr.available() > 0) {
                    /* int len = */
                    stderr.read(buffer);
                }
            }
            sess.close();
            conn.close();
            if (!success) {
                retry++;
                if (retry == MAX_RETRY_LINUX) {
                    result = "SSH Linux Network test fail";
                }
            }
            return result;
        } catch (Exception e) {
            retry++;
            s_logger.error("SSH Linux Network test fail with error");
            if (retry == MAX_RETRY_LINUX) {
                return "SSH Linux Network test fail with error " + e.getMessage();
            }
        }
        i++;
    }
}
Also used : InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Session(com.trilead.ssh2.Session)

Example 24 with Connection

use of com.trilead.ssh2.Connection in project cloudstack by apache.

the class SshTest method main.

public static void main(String[] args) {
    // Parameters
    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    while (iter.hasNext()) {
        String arg = iter.next();
        if (arg.equals("-h")) {
            host = iter.next();
        }
        if (arg.equals("-p")) {
            password = iter.next();
        }
        if (arg.equals("-u")) {
            url = iter.next();
        }
    }
    if (host == null || host.equals("")) {
        s_logger.info("Did not receive a host back from test, ignoring ssh test");
        System.exit(2);
    }
    if (password == null) {
        s_logger.info("Did not receive a password back from test, ignoring ssh test");
        System.exit(2);
    }
    try {
        s_logger.info("Attempting to SSH into host " + host);
        Connection conn = new Connection(host);
        conn.connect(null, 60000, 60000);
        s_logger.info("User + ssHed successfully into host " + host);
        boolean isAuthenticated = conn.authenticateWithPassword("root", password);
        if (isAuthenticated == false) {
            s_logger.info("Authentication failed for root with password" + password);
            System.exit(2);
        }
        String linuxCommand = "wget " + url;
        Session sess = conn.openSession();
        sess.execCommand(linuxCommand);
        sess.close();
        conn.close();
    } catch (Exception e) {
        s_logger.error("SSH test fail with error", e);
        System.exit(2);
    }
}
Also used : Connection(com.trilead.ssh2.Connection) Session(com.trilead.ssh2.Session)

Example 25 with Connection

use of com.trilead.ssh2.Connection in project cloudstack by apache.

the class SSHCmdHelper method sshExecuteCmdOneShotWithExitCode.

public static int sshExecuteCmdOneShotWithExitCode(com.trilead.ssh2.Connection sshConnection, 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);
        InputStream stdout = sshSession.getStdout();
        InputStream stderr = sshSession.getStderr();
        byte[] buffer = new byte[8192];
        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)) {
                int conditions = sshSession.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, 120000);
                if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                    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));
            }
        }
        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++) {
            Integer status = sshSession.getExitStatus();
            if (status != null) {
                return status;
            }
            Thread.sleep(100);
        }
        return -1;
    } catch (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)

Aggregations

Connection (com.trilead.ssh2.Connection)36 Session (com.trilead.ssh2.Session)34 IOException (java.io.IOException)31 InputStream (java.io.InputStream)22 SCPClient (com.trilead.ssh2.SCPClient)15 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)14 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HttpException (org.apache.commons.httpclient.HttpException)8 ConfigurationException (javax.naming.ConfigurationException)6 Connection (org.jboss.remoting3.Connection)6 StreamGobbler (com.trilead.ssh2.StreamGobbler)5 File (java.io.File)4 Principal (java.security.Principal)4 HashMap (java.util.HashMap)4 Connection (okhttp3.Connection)4 SecurityIdentity (org.wildfly.security.auth.server.SecurityIdentity)4 BufferedReader (java.io.BufferedReader)3 InputStreamReader (java.io.InputStreamReader)3 Charset (java.nio.charset.Charset)3 TimeoutException (java.util.concurrent.TimeoutException)3