Search in sources :

Example 6 with Connection

use of org.openmuc.j60870.Connection in project CloudStack-archive by CloudStack-extras.

the class ConfigTest method executeTest.

public boolean executeTest() {
    int error = 0;
    Element rootElement = this.getInputFile().get(0).getDocumentElement();
    NodeList commandLst = rootElement.getElementsByTagName("command");
    //Analyze each command, send request and build the array list of api commands
    for (int i = 0; i < commandLst.getLength(); i++) {
        Node fstNode = commandLst.item(i);
        Element fstElmnt = (Element) fstNode;
        //new command
        ApiCommand api = new ApiCommand(fstElmnt, this.getParam(), this.getCommands());
        if (api.getName().equals("rebootManagementServer")) {
            s_logger.info("Attempting to SSH into management server " + this.getParam().get("hostip"));
            try {
                Connection conn = new Connection(this.getParam().get("hostip"));
                conn.connect(null, 60000, 60000);
                s_logger.info("SSHed successfully into management server " + this.getParam().get("hostip"));
                boolean isAuthenticated = conn.authenticateWithPassword("root", "password");
                if (isAuthenticated == false) {
                    s_logger.info("Authentication failed for root with password");
                    return false;
                }
                String restartCommand = "service cloud-management restart; service cloud-usage restart";
                Session sess = conn.openSession();
                s_logger.info("Executing : " + restartCommand);
                sess.execCommand(restartCommand);
                Thread.sleep(120000);
                sess.close();
                conn.close();
            } catch (Exception ex) {
                s_logger.error(ex);
                return false;
            }
        } else {
            //send a command
            api.sendCommand(this.getClient(), null);
            //verify the response of the command
            if ((api.getResponseType() == ResponseType.ERROR) && (api.getResponseCode() == 200) && (api.getTestCaseInfo() != null)) {
                s_logger.error("Test case " + api.getTestCaseInfo() + "failed. Command that was supposed to fail, passed. The command was sent with the following url " + api.getUrl());
                error++;
            } else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() == 200)) {
                //set parameters for the future use
                if (api.setParam(this.getParam()) == false) {
                    s_logger.error("Exiting the test...Command " + api.getName() + " didn't return parameters needed for the future use. The command was sent with url " + api.getUrl());
                    return false;
                } else {
                    //verify parameters
                    if (api.verifyParam() == false) {
                        s_logger.error("Command " + api.getName() + " failed. Verification for returned parameters failed. Command was sent with url " + api.getUrl());
                        error++;
                    } else if (api.getTestCaseInfo() != null) {
                        s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command was sent with the url " + api.getUrl());
                    }
                }
            } else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() != 200)) {
                s_logger.error("Command " + api.getName() + " failed with an error code " + api.getResponseCode() + " . Command was sent with url  " + api.getUrl() + " Required: " + api.getRequired());
                if (api.getRequired() == true) {
                    s_logger.info("The command is required for the future use, so exiging");
                    return false;
                }
                error++;
            } else if (api.getTestCaseInfo() != null) {
                s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command that was supposed to fail, failed - test passed. Command was sent with url " + api.getUrl());
            }
        }
    }
    if (error != 0)
        return false;
    else
        return true;
}
Also used : Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Connection(com.trilead.ssh2.Connection) Session(com.trilead.ssh2.Session)

Example 7 with Connection

use of org.openmuc.j60870.Connection in project CloudStack-archive by CloudStack-extras.

the class EventsApiTest method executeTest.

public boolean executeTest() {
    int error = 0;
    Element rootElement = this.getInputFile().get(0).getDocumentElement();
    NodeList commandLst = rootElement.getElementsByTagName("command");
    //Analyze each command, send request and build the array list of api commands
    for (int i = 0; i < commandLst.getLength(); i++) {
        Node fstNode = commandLst.item(i);
        Element fstElmnt = (Element) fstNode;
        //!!!check if we need to execute mySql command
        NodeList commandName = fstElmnt.getElementsByTagName("name");
        Element commandElmnt = (Element) commandName.item(0);
        NodeList commandNm = commandElmnt.getChildNodes();
        if (((Node) commandNm.item(0)).getNodeValue().equals("mysqlupdate")) {
            //establish connection to mysql server and execute an update command
            NodeList mysqlList = fstElmnt.getElementsByTagName("mysqlcommand");
            for (int j = 0; j < mysqlList.getLength(); j++) {
                Element itemVariableElement = (Element) mysqlList.item(j);
                s_logger.info("Executing mysql command " + itemVariableElement.getTextContent());
                try {
                    Statement st = this.getConn().createStatement();
                    st.executeUpdate(itemVariableElement.getTextContent());
                } catch (Exception ex) {
                    s_logger.error(ex);
                    return false;
                }
            }
        } else if (((Node) commandNm.item(0)).getNodeValue().equals("agentcommand")) {
            //connect to all the agents and execute agent command
            NodeList commandList = fstElmnt.getElementsByTagName("commandname");
            Element commandElement = (Element) commandList.item(0);
            NodeList ipList = fstElmnt.getElementsByTagName("ip");
            for (int j = 0; j < ipList.getLength(); j++) {
                Element itemVariableElement = (Element) ipList.item(j);
                s_logger.info("Attempting to SSH into agent " + itemVariableElement.getTextContent());
                try {
                    Connection conn = new Connection(itemVariableElement.getTextContent());
                    conn.connect(null, 60000, 60000);
                    s_logger.info("SSHed successfully into agent " + itemVariableElement.getTextContent());
                    boolean isAuthenticated = conn.authenticateWithPassword("root", "password");
                    if (isAuthenticated == false) {
                        s_logger.info("Authentication failed for root with password");
                        return false;
                    }
                    Session sess = conn.openSession();
                    s_logger.info("Executing : " + commandElement.getTextContent());
                    sess.execCommand(commandElement.getTextContent());
                    Thread.sleep(60000);
                    sess.close();
                    conn.close();
                } catch (Exception ex) {
                    s_logger.error(ex);
                    return false;
                }
            }
        } else {
            //new command
            ApiCommand api = new ApiCommand(fstElmnt, this.getParam(), this.getCommands());
            //send a command
            api.sendCommand(this.getClient(), null);
            //verify the response of the command
            if ((api.getResponseType() == ResponseType.ERROR) && (api.getResponseCode() == 200)) {
                s_logger.error("Test case " + api.getTestCaseInfo() + " failed. Command that was supposed to fail, passed. The command was sent with the following url " + api.getUrl());
                error++;
            } else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() == 200)) {
                //verify if response is suppposed to be empty
                if (api.getResponseType() == ResponseType.EMPTY) {
                    if (api.isEmpty() == true) {
                        s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Empty response was returned as expected. Command was sent with url " + api.getUrl());
                    } else {
                        s_logger.error("Test case " + api.getTestCaseInfo() + " failed. Empty response was expected. Command was sent with url " + api.getUrl());
                    }
                } else {
                    if (api.isEmpty() != false)
                        s_logger.error("Test case " + api.getTestCaseInfo() + " failed. Non-empty response was expected. Command was sent with url " + api.getUrl());
                    else {
                        //set parameters for the future use
                        if (api.setParam(this.getParam()) == false) {
                            s_logger.error("Exiting the test...Command " + api.getName() + " didn't return parameters needed for the future use. The command was sent with url " + api.getUrl());
                            return false;
                        } else if (api.getTestCaseInfo() != null) {
                            s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command was sent with the url " + api.getUrl());
                        }
                    }
                }
            } else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() != 200)) {
                s_logger.error("Command " + api.getName() + " failed with an error code " + api.getResponseCode() + " . Command was sent with url  " + api.getUrl());
                if (api.getRequired() == true) {
                    s_logger.info("The command is required for the future use, so exiging");
                    return false;
                }
                error++;
            } else if (api.getTestCaseInfo() != null) {
                s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command that was supposed to fail, failed. Command was sent with url " + api.getUrl());
            }
        }
    }
    //verify events with userid parameter - test case 97
    HashMap<String, Integer> expectedEvents = new HashMap<String, Integer>();
    expectedEvents.put("VM.START", 1);
    boolean eventResult = ApiCommand.verifyEvents(expectedEvents, "INFO", "http://" + this.getParam().get("hostip") + ":8096", "userid=" + this.getParam().get("userid1") + "&type=VM.START");
    s_logger.info("Test case 97 - listEvent command verification result is  " + eventResult);
    //verify error events
    eventResult = ApiCommand.verifyEvents("../metadata/error_events.properties", "ERROR", "http://" + this.getParam().get("hostip") + ":8096", this.getParam().get("erroruseraccount"));
    s_logger.info("listEvent command verification result is  " + eventResult);
    if (error != 0)
        return false;
    else
        return true;
}
Also used : HashMap(java.util.HashMap) Statement(java.sql.Statement) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Connection(com.trilead.ssh2.Connection) Session(com.trilead.ssh2.Session)

Example 8 with Connection

use of org.openmuc.j60870.Connection in project ACS by ACS-Community.

the class Executor method remotePortable.

/**
    * @return false - if this failed gracefully
    * @throws IOException - if this failed severely
    */
private static boolean remotePortable(String username, String password, String command, String endMark, NativeCommand.Listener listener, String host) throws IOException {
    if (listener == null) {
        // normalization: use a do-nothing implementation
        listener = new NativeCommand.ListenerAdapter();
    }
    try {
        remoteFlow.reset(null);
        // connect
        // --------
        Connection conn = new Connection(host);
        connections.add(conn);
        conn.connect();
        remoteFlow.success(RemoteFlow.CONNECT);
        // login
        // ------
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        if (isAuthenticated == false)
            throw new IOException("Authentication failed");
        remoteFlow.success(RemoteFlow.LOG_IN);
        // send command
        // -------------
        Session sess = conn.openSession();
        sessions.add(sess);
        /* msc 2008-11:
          * We're passing the command as an argument to ssh, just like typing
          * > ssh 127.0.0.1 "env" 
          * on the commandline. This opens a non-login shell on the remote host
          * which (thank you bash) won't parse the .bash_profile but only the .bashrc!
          * Now unfortunately the usual setup for accounts on Alma machines is to
          * have the ACS settings defined in .bash_profile. The optimal way around
          * this would be to run a real login shell here by allocating a terminal,
          * and then deal with all the input output/stuff ourselves. I'm trying here
          * to get away with something cheaper: Explicitly source the .bash_profile
          * before running the command.
          */
        command = ". ~/.bash_profile ; " + command;
        log.info("Now sending: '" + command + "'");
        sess.execCommand(command);
        remoteFlow.success(RemoteFlow.SEND_COMMAND);
        // read output, scan for endmark
        // ----------------------------
        SearchBuffer searchStdout = null;
        SearchBuffer searchStderr = null;
        if (endMark != null) {
            searchStdout = new SearchBuffer(endMark);
            searchStderr = new SearchBuffer(endMark);
        }
        InputStream stdout = sess.getStdout();
        InputStream stderr = sess.getStderr();
        byte[] buffer = new byte[8192];
        while (true) {
            if (stdout.available() == 0 && stderr.available() == 0) {
                /* Even though currently there is no data available, it may be that new data arrives
					 * and the session's underlying channel is closed before we call waitForCondition().
					 * This means that EOF and STDOUT_DATA (or STDERR_DATA, or both) may be set together. */
                int conditions = sess.waitForCondition(//
                ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, // allow several seconds
                10 * 1000);
                if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                    throw new IOException("Timeout while waiting for data from peer");
                }
                if ((conditions & ChannelCondition.EOF) != 0) {
                    /* The remote side won't send us further data ... */
                    if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                        /* ... and we have consumed all data in the local arrival window. */
                        break;
                    }
                }
            /* At this point, either STDOUT_DATA or STDERR_DATA, (or both) is set. */
            }
            /* If you below use "if" instead of "while", then the way the output appears on the local
				 * stdout and stder streams is more "balanced". Addtionally reducing the buffer size
				 * will also improve the interleaving, but performance will slightly suffer.
				 * OKOK, that all matters only if you get HUGE amounts of stdout and stderr data =)
				 */
            if (stdout.available() > 0) {
                int len = stdout.read(buffer);
                listener.stdoutWritten(null, new String(buffer, 0, len));
                if (searchStdout != null)
                    if (searchStdout.add(buffer, 0, len)) {
                        remoteFlow.success(RemoteFlow.COMPLETE);
                        break;
                    }
            }
            if (stderr.available() > 0) {
                int len = stderr.read(buffer);
                // msc 2008-11: porting to a different ssh library. this should of course
                // call stderrWritten() but i don't want to change the original behavior.
                listener.stdoutWritten(null, new String(buffer, 0, len));
                if (searchStderr != null)
                    if (searchStderr.add(buffer, 0, len)) {
                        remoteFlow.success(RemoteFlow.COMPLETE);
                        break;
                    }
            }
        }
        return true;
    } catch (IOException exc) {
        remoteFlow.failure(exc);
        /* throw exc; */
        return false;
    }
}
Also used : InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) IOException(java.io.IOException) PreparedString(alma.acs.commandcenter.util.PreparedString) Session(com.trilead.ssh2.Session)

Example 9 with Connection

use of org.openmuc.j60870.Connection in project intellij-community by JetBrains.

the class SshConnectionUtils method openConnection.

// we need project here since it could occur that the same repository/proxy would be used from different projects with different credentials
// though it is unlikely
public static Connection openConnection(final ConnectionSettings connectionSettings, final SshAuthentication authentication) throws AuthenticationException, IOException {
    final int port = connectionSettings.getPort() == -1 ? SSH_DEFAULT_PORT : connectionSettings.getPort();
    final Connection connection = new Connection(connectionSettings.getHostName(), port);
    final ProxyData proxy = SshProxyFactory.createAndRegister(connectionSettings);
    if (proxy != null) {
        connection.setProxyData(proxy);
    }
    connection.connect(null, connectionSettings.getConnectionTimeout(), connectionSettings.getConnectionTimeout());
    authentication.authenticate(connection);
    //HTTPProxyException
    return connection;
}
Also used : ProxyData(com.trilead.ssh2.ProxyData) Connection(com.trilead.ssh2.Connection)

Example 10 with Connection

use of org.openmuc.j60870.Connection in project intellij-community by JetBrains.

the class BasicWithHTTPProxy method main.

public static void main(String[] args) {
    String hostname = "my-ssh-server";
    String username = "joe";
    String password = "joespass";
    String proxyHost = "192.168.1.1";
    // default port used by squid
    int proxyPort = 3128;
    try {
        /* Create a connection instance */
        Connection conn = new Connection(hostname);
        /* We want to connect through a HTTP proxy */
        conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort));
        // if the proxy requires basic authentication:
        // conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort, "username", "secret"));
        /* Now connect (through the proxy) */
        conn.connect();
        /* Authenticate.
			 * If you get an IOException saying something like
			 * "Authentication method password not supported by the server at this stage."
			 * then please check the FAQ.
			 */
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        if (isAuthenticated == false)
            throw new IOException("Authentication failed.");
        /* Create a session */
        Session sess = conn.openSession();
        sess.execCommand("uname -a && date && uptime && who");
        System.out.println("Here is some information about the remote host:");
        /* 
			 * This basic example does not handle stderr, which is sometimes dangerous
			 * (please read the FAQ).
			 */
        InputStream stdout = new StreamGobbler(sess.getStdout());
        BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
        while (true) {
            String line = br.readLine();
            if (line == null)
                break;
            System.out.println(line);
        }
        /* Show exit status, if available (otherwise "null") */
        System.out.println("ExitCode: " + sess.getExitStatus());
        /* Close this session */
        sess.close();
        /* Close the connection */
        conn.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(2);
    }
}
Also used : StreamGobbler(com.trilead.ssh2.StreamGobbler) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) HTTPProxyData(com.trilead.ssh2.HTTPProxyData) Session(com.trilead.ssh2.Session)

Aggregations

Connection (org.ovirt.engine.sdk4.Connection)64 Connection (com.trilead.ssh2.Connection)55 IOException (java.io.IOException)43 Session (com.trilead.ssh2.Session)32 VmsService (org.ovirt.engine.sdk4.services.VmsService)30 Vm (org.ovirt.engine.sdk4.types.Vm)30 InputStream (java.io.InputStream)25 VmService (org.ovirt.engine.sdk4.services.VmService)18 Connection (okhttp3.Connection)15 Connection (ch.ethz.ssh2.Connection)13 Request (okhttp3.Request)13 SystemService (org.ovirt.engine.sdk4.services.SystemService)13 Response (okhttp3.Response)12 StorageDomainsService (org.ovirt.engine.sdk4.services.StorageDomainsService)12 StorageDomain (org.ovirt.engine.sdk4.types.StorageDomain)12 MediaType (okhttp3.MediaType)11 ResponseBody (okhttp3.ResponseBody)11 RequestBody (okhttp3.RequestBody)10 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)9 Charset (java.nio.charset.Charset)9