Search in sources :

Example 1 with SSHLauncher

use of org.glassfish.cluster.ssh.launcher.SSHLauncher in project Payara by payara.

the class NativeRemoteCommandsBase method expandPasswordAlias.

/**
 * Obtains the real password from the domain specific keystore given an alias
 * @param host host that we are connecting to
 * @param alias password alias of form ${ALIAS=xxx}
 * @return real password of ssh user, null if not found
 */
String expandPasswordAlias(String host, String alias, boolean verifyConn) {
    String expandedPassword = null;
    boolean connStatus = false;
    try {
        File domainsDirFile = DomainDirs.getDefaultDomainsDir();
        // get the list of domains
        File[] files = domainsDirFile.listFiles(new FileFilter() {

            @Override
            public boolean accept(File f) {
                return f.isDirectory();
            }
        });
        for (File f : files) {
            // the following property is required for initializing the password helper
            System.setProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY, f.getAbsolutePath());
            try {
                final PasswordAdapter pa = new PasswordAdapter(null);
                final boolean exists = pa.aliasExists(alias);
                if (exists) {
                    String mPass = getMasterPassword(f.getName());
                    expandedPassword = new PasswordAdapter(mPass.toCharArray()).getPasswordForAlias(alias);
                }
            } catch (Exception e) {
                if (logger.isLoggable(Level.FINER)) {
                    logger.finer(StringUtils.cat(": ", alias, e.getMessage()));
                }
                logger.warning(Strings.get("GetPasswordFailure", f.getName()));
                continue;
            }
            if (expandedPassword != null) {
                SSHLauncher sshL = new SSHLauncher();
                if (host != null) {
                    sshpassword = expandedPassword;
                    sshL.init(getRemoteUser(), host, getRemotePort(), sshpassword, null, null, logger);
                    connStatus = sshL.checkPasswordAuth();
                    if (!connStatus) {
                        logger.warning(Strings.get("PasswordAuthFailure", f.getName()));
                    }
                } else {
                    sshkeypassphrase = expandedPassword;
                    if (verifyConn) {
                        sshL.init(getRemoteUser(), hosts[0], getRemotePort(), sshpassword, getSshKeyFile(), sshkeypassphrase, logger);
                        connStatus = sshL.checkConnection();
                        if (!connStatus) {
                            logger.warning(Strings.get("PasswordAuthFailure", f.getName()));
                        }
                    }
                }
                if (connStatus) {
                    break;
                }
            }
        }
    } catch (IOException ioe) {
        if (logger.isLoggable(Level.FINER)) {
            logger.finer(ioe.getMessage());
        }
    }
    return expandedPassword;
}
Also used : SSHLauncher(org.glassfish.cluster.ssh.launcher.SSHLauncher) PasswordAdapter(com.sun.enterprise.security.store.PasswordAdapter)

Example 2 with SSHLauncher

use of org.glassfish.cluster.ssh.launcher.SSHLauncher in project Payara by payara.

the class SetupSshKey method executeCommand.

@Override
protected int executeCommand() throws CommandException {
    SSHLauncher sshL = habitat.getService(SSHLauncher.class);
    String previousPassword = null;
    boolean status = false;
    for (String node : hosts) {
        sshL.init(getRemoteUser(), node, getRemotePort(), sshpassword, sshkeyfile, sshkeypassphrase, logger);
        if (generatekey || promptPass) {
            // prompt for password iff required
            if (sshkeyfile != null || SSHUtil.getExistingKeyFile() != null) {
                if (sshL.checkConnection()) {
                    logger.info(Strings.get("SSHAlreadySetup", getRemoteUser(), node));
                    continue;
                }
            }
            if (previousPassword != null) {
                status = sshL.checkPasswordAuth();
            }
            if (!status) {
                sshpassword = getSSHPassword(node);
                previousPassword = sshpassword;
            }
        }
        try {
            sshL.setupKey(node, sshpublickeyfile, generatekey, sshpassword);
        } catch (IOException ce) {
            throw new CommandException(Strings.get("KeySetupFailed", ce.getMessage()));
        } catch (Exception e) {
            // handle KeyStoreException
            if (logger.isLoggable(Level.FINER)) {
                logger.log(Level.FINER, "Keystore error: ", e);
            }
        }
        if (!sshL.checkConnection()) {
            throw new CommandException(Strings.get("ConnFailed"));
        }
    }
    return SUCCESS;
}
Also used : SSHLauncher(org.glassfish.cluster.ssh.launcher.SSHLauncher) IOException(java.io.IOException) CommandException(org.glassfish.api.admin.CommandException) IOException(java.io.IOException) EndOfFileException(org.jline.reader.EndOfFileException) UserInterruptException(org.jline.reader.UserInterruptException) CommandException(org.glassfish.api.admin.CommandException)

Example 3 with SSHLauncher

use of org.glassfish.cluster.ssh.launcher.SSHLauncher in project Payara by payara.

the class LogFilterForInstance method downloadGivenInstanceLogFile.

public File downloadGivenInstanceLogFile(ServiceLocator habitat, Server targetServer, Domain domain, Logger logger, String instanceName, String domainRoot, String logFileName, String instanceLogFileName) throws IOException {
    File instanceLogFile = null;
    // method is used from logviewer back end code logfilter.
    // for Instance it's going through this loop. This will use ssh utility to get file from instance machine(remote machine) and
    // store in domains/domain1/logs/<instance name> which is used to get LogFile object.
    // Right now user needs to go through this URL to setup and configure ssh http://wikis.sun.com/display/GlassFish/3.1SSHSetup
    SSHLauncher sshL = getSSHL(habitat);
    String sNode = targetServer.getNodeRef();
    Nodes nodes = domain.getNodes();
    Node node = nodes.getNode(sNode);
    if (node.getType().equals("SSH")) {
        sshL.init(node, logger);
        SFTPClient sftpClient = sshL.getSFTPClient();
        File logFileDirectoryOnServer = makingDirectory(domainRoot + File.separator + "logs" + File.separator + instanceName);
        boolean noFileFound = true;
        String loggingDir = getLoggingDirectoryForNode(instanceLogFileName, node, sNode, instanceName);
        try {
            List instanceLogFileNames = sftpClient.ls(loggingDir);
            for (int i = 0; i < instanceLogFileNames.size(); i++) {
                SFTPv3DirectoryEntry file = (SFTPv3DirectoryEntry) instanceLogFileNames.get(i);
                String fileName = file.filename;
                // code to remove . and .. file which is return from sftpclient ls method
                if (!file.attributes.isDirectory() && !fileName.equals(".") && !fileName.equals("..") && fileName.contains(".log") && !fileName.contains(".log.")) {
                    noFileFound = false;
                    break;
                }
            }
        } catch (Exception e) {
            // if directory doesn't present or missing on remote machine. It happens due to bug 16451
            noFileFound = true;
        }
        if (noFileFound) {
            // this loop is used when user has changed value for server.log but not restarted the server.
            loggingDir = getLoggingDirectoryForNodeWhenNoFilesFound(instanceLogFileName, node, sNode, instanceName);
        }
        String loggingFile = loggingDir + File.separator + logFileName;
        if (!sftpClient.exists(loggingFile)) {
            loggingFile = loggingDir + File.separator + "server.log";
        } else if (!sftpClient.exists(loggingFile)) {
            loggingFile = instanceLogFileName;
        }
        // creating local file name on DAS
        long instanceLogFileSize = 0;
        instanceLogFile = new File(logFileDirectoryOnServer.getAbsolutePath() + File.separator + loggingFile.substring(loggingFile.lastIndexOf(File.separator), loggingFile.length()));
        // getting size of the file on DAS
        if (instanceLogFile.exists()) {
            instanceLogFileSize = instanceLogFile.length();
        }
        SFTPv3FileAttributes sftPv3FileAttributes = sftpClient._stat(loggingFile);
        // getting size of the file on instance machine
        long fileSizeOnNode = sftPv3FileAttributes.size;
        // if differ both size then downloading
        if (instanceLogFileSize != fileSizeOnNode) {
            try (BufferedInputStream in = new BufferedInputStream(sftpClient.read(loggingFile));
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(instanceLogFile))) {
                int i;
                while ((i = in.read()) != -1) {
                    out.write(i);
                }
                out.flush();
            }
        }
        sftpClient.close();
    } else if (node.getType().equals("DCOM")) {
        File logFileDirectoryOnServer = makingDirectory(domainRoot + File.separator + "logs" + File.separator + instanceName);
        String loggingDir = getLoggingDirectoryForNode(instanceLogFileName, node, sNode, instanceName);
        try {
            DcomInfo info = new DcomInfo(node);
            WindowsRemoteFileSystem wrfs = new WindowsRemoteFileSystem(info.getHost(), info.getUser(), info.getPassword());
            if (logFileName == null || logFileName.equals("")) {
                logFileName = "server.log";
            }
            WindowsRemoteFile wrf = new WindowsRemoteFile(wrfs, loggingDir + File.separator + logFileName);
            instanceLogFile = new File(logFileDirectoryOnServer + File.separator + logFileName);
            wrf.copyTo(instanceLogFile);
        } catch (WindowsException ex) {
            throw new IOException("Unable to download instance log file from DCOM Instance Node");
        }
    }
    return instanceLogFile;
}
Also used : SSHLauncher(org.glassfish.cluster.ssh.launcher.SSHLauncher) Node(com.sun.enterprise.config.serverbeans.Node) SFTPClient(org.glassfish.cluster.ssh.sftp.SFTPClient) IOException(java.io.IOException) WindowsException(com.sun.enterprise.util.cluster.windows.process.WindowsException) Nodes(com.sun.enterprise.config.serverbeans.Nodes) IOException(java.io.IOException) WindowsException(com.sun.enterprise.util.cluster.windows.process.WindowsException) DcomInfo(org.glassfish.cluster.ssh.util.DcomInfo) SFTPv3DirectoryEntry(com.trilead.ssh2.SFTPv3DirectoryEntry) WindowsRemoteFile(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFile) BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) WindowsRemoteFileSystem(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFileSystem) ArrayList(java.util.ArrayList) List(java.util.List) SFTPv3FileAttributes(com.trilead.ssh2.SFTPv3FileAttributes) WindowsRemoteFile(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFile) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 4 with SSHLauncher

use of org.glassfish.cluster.ssh.launcher.SSHLauncher in project Payara by payara.

the class StopInstanceCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    report = context.getActionReport();
    logger = context.getLogger();
    SSHLauncher launcher;
    if (env.isDas()) {
        if (kill) {
            errorMessage = killInstance(context);
        } else {
            errorMessage = callInstance();
        }
    } else {
        errorMessage = Strings.get("stop.instance.notDas", env.getRuntimeType().toString());
    }
    if (errorMessage == null && !kill) {
        errorMessage = pollForDeath();
    }
    if (errorMessage != null) {
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage(errorMessage);
        return;
    }
    String nodeName = instance.getNodeRef();
    Node node = nodes.getNode(nodeName);
    if (node.getType().equals("DOCKER")) {
        stopDockerContainer(nodeName, instanceName, context);
    }
    if (node.getType().equals("TEMP")) {
        deleteTempInstance(instanceName, context);
    }
    // If we've got any sub-command failures, log a warning
    if (context.getActionReport().hasFailures()) {
        report.setActionExitCode(ActionReport.ExitCode.WARNING);
        report.setMessage(Strings.get("stop.instance.warning", instanceName));
    } else {
        report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
        report.setMessage(Strings.get("stop.instance.success", instanceName));
    }
    if (kill) {
        // If we killed then stop-local-instance already waited for death
        return;
    }
    // we think the instance is down but it might not be completely down so do further checking
    // get the node name and then the node
    // if localhost check if files exists
    // else if SSH check if file exists  on remote system
    // else can't check anything else.
    InstanceDirUtils insDU = new InstanceDirUtils(node, serverContext);
    // this should be replaced with method from Node config bean.
    if (node.isLocal()) {
        try {
            pidFile = new File(insDU.getLocalInstanceDir(instance.getName()), "config/pid");
        } catch (java.io.IOException eio) {
            // could not get the file name so can't see if it still exists.  Need to exit
            return;
        }
        if (pidFile.exists()) {
            // server still not down completely, do we poll?
            errorMessage = pollForRealDeath("local");
        }
    } else if (node.getType().equals("SSH")) {
        try {
            pidFile = new File(insDU.getLocalInstanceDir(instance.getName()), "config/pid");
        } catch (java.io.IOException eio) {
            // could not get the file name so can't see if it still exists.  Need to exit
            return;
        }
        // use SFTPClient to see if file exists.
        launcher = habitat.getService(SSHLauncher.class);
        launcher.init(node, logger);
        try {
            ftpClient = launcher.getSFTPClient();
            if (ftpClient.exists(pidFile.toString())) {
                // server still not down, do we poll?
                errorMessage = pollForRealDeath("SSH");
            }
        } catch (IOException ex) {
        // could not get to other host
        } finally {
            if (ftpClient != null) {
                ftpClient.close();
            }
        }
    } else if (node.getType().equals("DCOM")) {
        DcomInfo info;
        try {
            info = new DcomInfo(node);
            String path = info.getRemoteNodeRootDirectory() + "\\config\\pid";
            wrf = new WindowsRemoteFile(info.getCredentials(), path);
            if (wrf.exists())
                errorMessage = pollForRealDeath("DCOM");
        } catch (WindowsException ex) {
        // could not get to other host
        }
    }
    if (errorMessage != null) {
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage(errorMessage);
    }
}
Also used : WindowsRemoteFile(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFile) SSHLauncher(org.glassfish.cluster.ssh.launcher.SSHLauncher) IOException(java.io.IOException) IOException(java.io.IOException) WindowsRemoteFile(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFile) File(java.io.File) WindowsException(com.sun.enterprise.util.cluster.windows.process.WindowsException) DcomInfo(org.glassfish.cluster.ssh.util.DcomInfo)

Example 5 with SSHLauncher

use of org.glassfish.cluster.ssh.launcher.SSHLauncher in project Payara by payara.

the class LogFilterForInstance method getInstanceLogFileNames.

public List<String> getInstanceLogFileNames(ServiceLocator habitat, Server targetServer, Domain domain, Logger logger, String instanceName, String instanceLogFileDetails) throws IOException {
    // helper method to get all log file names for given instance
    String sNode = targetServer.getNodeRef();
    Node node = domain.getNodes().getNode(sNode);
    List instanceLogFileNames = null;
    List<String> instanceLogFileNamesAsString = new ArrayList<>();
    // this code is used when DAS and instances are running on the same machine
    if (node.isLocal()) {
        String loggingDir = getLoggingDirectoryForNode(instanceLogFileDetails, node, sNode, instanceName);
        File logsDir = new File(loggingDir);
        File[] allLogFileNames = logsDir.listFiles();
        boolean noFileFound = true;
        if (allLogFileNames != null) {
            // This check for,  if directory doesn't present or missing on machine. It happens due to bug 16451
            for (File file : allLogFileNames) {
                String fileName = file.getName();
                // code to remove . and .. file which is return
                if (file.isFile() && !fileName.equals(".") && !fileName.equals("..") && fileName.contains(".log") && !fileName.contains(".log.")) {
                    instanceLogFileNamesAsString.add(fileName);
                    noFileFound = false;
                }
            }
        }
        if (noFileFound) {
            // this loop is used when user has changed value for server.log but not restarted the server.
            loggingDir = getLoggingDirectoryForNodeWhenNoFilesFound(instanceLogFileDetails, node, sNode, instanceName);
            logsDir = new File(loggingDir);
            allLogFileNames = logsDir.listFiles();
            if (allLogFileNames != null) {
                for (File file : allLogFileNames) {
                    String fileName = file.getName();
                    // code to remove . and .. file which is return
                    if (file.isFile() && !fileName.equals(".") && !fileName.equals("..") && fileName.contains(".log") && !fileName.contains(".log.")) {
                        instanceLogFileNamesAsString.add(fileName);
                    }
                }
            }
        }
    } else if (node.getType().equals("SSH")) {
        // this code is used if DAS and instance are running on different machine
        SSHLauncher sshL = getSSHL(habitat);
        sshL.init(node, logger);
        SFTPClient sftpClient = sshL.getSFTPClient();
        boolean noFileFound = true;
        String loggingDir = getLoggingDirectoryForNode(instanceLogFileDetails, node, sNode, instanceName);
        try {
            instanceLogFileNames = sftpClient.ls(loggingDir);
            for (int i = 0; i < instanceLogFileNames.size(); i++) {
                SFTPv3DirectoryEntry file = (SFTPv3DirectoryEntry) instanceLogFileNames.get(i);
                String fileName = file.filename;
                // code to remove . and .. file which is return from sftpclient ls method
                if (!file.attributes.isDirectory() && !fileName.equals(".") && !fileName.equals("..") && fileName.contains(".log") && !fileName.contains(".log.")) {
                    instanceLogFileNamesAsString.add(fileName);
                    noFileFound = false;
                }
            }
        } catch (Exception ex) {
            // if directory doesn't present or missing on remote machine. It happens due to bug 16451
            noFileFound = true;
        }
        if (noFileFound) {
            // this loop is used when user has changed value for server.log but not restarted the server.
            loggingDir = getLoggingDirectoryForNodeWhenNoFilesFound(instanceLogFileDetails, node, sNode, instanceName);
            instanceLogFileNames = sftpClient.ls(loggingDir);
            for (int i = 0; i < instanceLogFileNames.size(); i++) {
                SFTPv3DirectoryEntry file = (SFTPv3DirectoryEntry) instanceLogFileNames.get(i);
                String fileName = file.filename;
                // code to remove . and .. file which is return from sftpclient ls method
                if (!file.attributes.isDirectory() && !fileName.equals(".") && !fileName.equals("..") && fileName.contains(".log") && !fileName.contains(".log.")) {
                    instanceLogFileNamesAsString.add(fileName);
                }
            }
        }
        sftpClient.close();
    } else if (node.getType().equals("DCOM")) {
        String loggingDir = getLoggingDirectoryForNode(instanceLogFileDetails, node, sNode, instanceName);
        try {
            DcomInfo info = new DcomInfo(node);
            WindowsRemoteFileSystem wrfs = new WindowsRemoteFileSystem(info.getHost(), info.getUser(), info.getPassword());
            WindowsRemoteFile wrf = new WindowsRemoteFile(wrfs, loggingDir);
            String[] allLogFileNames = wrf.list();
            for (String allLogFileName : allLogFileNames) {
                File file = new File(allLogFileName);
                String fileName = file.getName();
                // code to remove . and .. file which is return
                if (!fileName.equals(".") && !fileName.equals("..") && fileName.contains(".log") && !fileName.contains(".log.")) {
                    instanceLogFileNamesAsString.add(fileName);
                }
            }
        } catch (WindowsException ex) {
            throw new IOException("Unable to get instance log file names from DCOM Instance Node");
        }
    }
    return instanceLogFileNamesAsString;
}
Also used : SSHLauncher(org.glassfish.cluster.ssh.launcher.SSHLauncher) Node(com.sun.enterprise.config.serverbeans.Node) ArrayList(java.util.ArrayList) SFTPClient(org.glassfish.cluster.ssh.sftp.SFTPClient) IOException(java.io.IOException) WindowsException(com.sun.enterprise.util.cluster.windows.process.WindowsException) IOException(java.io.IOException) WindowsException(com.sun.enterprise.util.cluster.windows.process.WindowsException) DcomInfo(org.glassfish.cluster.ssh.util.DcomInfo) SFTPv3DirectoryEntry(com.trilead.ssh2.SFTPv3DirectoryEntry) WindowsRemoteFile(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFile) WindowsRemoteFileSystem(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFileSystem) ArrayList(java.util.ArrayList) List(java.util.List) WindowsRemoteFile(com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFile) File(java.io.File)

Aggregations

SSHLauncher (org.glassfish.cluster.ssh.launcher.SSHLauncher)6 IOException (java.io.IOException)5 WindowsRemoteFile (com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFile)4 WindowsException (com.sun.enterprise.util.cluster.windows.process.WindowsException)4 File (java.io.File)4 DcomInfo (org.glassfish.cluster.ssh.util.DcomInfo)4 Node (com.sun.enterprise.config.serverbeans.Node)3 WindowsRemoteFileSystem (com.sun.enterprise.util.cluster.windows.io.WindowsRemoteFileSystem)3 SFTPv3DirectoryEntry (com.trilead.ssh2.SFTPv3DirectoryEntry)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 SFTPClient (org.glassfish.cluster.ssh.sftp.SFTPClient)3 Nodes (com.sun.enterprise.config.serverbeans.Nodes)2 PasswordAdapter (com.sun.enterprise.security.store.PasswordAdapter)1 SCPClient (com.trilead.ssh2.SCPClient)1 SFTPv3FileAttributes (com.trilead.ssh2.SFTPv3FileAttributes)1 BufferedInputStream (java.io.BufferedInputStream)1 BufferedOutputStream (java.io.BufferedOutputStream)1 FileOutputStream (java.io.FileOutputStream)1 CommandException (org.glassfish.api.admin.CommandException)1