From 2d5a58d66ca6f87571e74eb457092687b04e46ab Mon Sep 17 00:00:00 2001 From: Anthony Xu Date: Mon, 24 Mar 2014 15:18:50 -0700 Subject: [PATCH] fixed ssh execution log --- .../src/com/cloud/utils/ssh/SSHCmdHelper.java | 33 +++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java b/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java index 10ada37835d..4a440eff4e3 100644 --- a/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java +++ b/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java @@ -110,17 +110,28 @@ public class SSHCmdHelper { 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, 120000); + int conditions = sshSession.waitForCondition(ChannelCondition.STDOUT_DATA + | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, + 120000); if ((conditions & ChannelCondition.TIMEOUT) != 0) { - s_logger.info("Timeout while waiting for data from peer."); - break; + 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) { @@ -131,19 +142,21 @@ public class SSHCmdHelper { } while (stdout.available() > 0) { - stdout.read(buffer); + currentReadBytes = stdout.read(buffer); + sbResult.append(new String(buffer, 0, currentReadBytes)); } while (stderr.available() > 0) { - stderr.read(buffer); + currentReadBytes = stderr.read(buffer); + sbResult.append(new String(buffer, 0, currentReadBytes)); } } - if (buffer[0] != 0) - s_logger.debug(cmd + " output:" + new String(buffer)); + String result = sbResult.toString(); + if (result != null && !result.isEmpty()) + s_logger.debug(cmd + " output:" + result); - Thread.sleep(1000); - return sshSession.getExitStatus(); + return sshSession.getExitStatus(); } catch (Exception e) { s_logger.debug("Ssh executed failed", e); throw new SshException("Ssh executed failed " + e.getMessage());