Search in sources :

Example 71 with ChannelSftp

use of com.jcraft.jsch.ChannelSftp in project suite by stupidsing.

the class Ssh method channelSftp.

private <T> T channelSftp(Session session, SshFun<ChannelSftp, T> fun) throws IOException, SftpException, JSchException {
    ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
    channel.connect();
    try {
        return fun.apply(channel);
    } finally {
        channel.disconnect();
    }
}
Also used : ChannelSftp(com.jcraft.jsch.ChannelSftp)

Example 72 with ChannelSftp

use of com.jcraft.jsch.ChannelSftp in project coprhd-controller by CoprHD.

the class CinderCommunicationInterface method scan.

/**
 * Process the cinder.conf file and deduce storage systems from it
 */
@Override
public void scan(AccessProfile accessProfile) throws BaseCollectionException {
    _logger.info("Scanning started for provider: {}", accessProfile.getSystemId());
    StorageProvider storageProvider = _dbClient.queryObject(StorageProvider.class, accessProfile.getSystemId());
    String username = storageProvider.getUserName();
    String password = storageProvider.getPassword();
    String hostName = storageProvider.getIPAddress();
    // map to hold cinder end point info
    StringMap providerKeys = storageProvider.getKeys();
    if (providerKeys == null) {
        providerKeys = new StringMap();
    }
    updateKeyInProvider(providerKeys, CinderConstants.KEY_CINDER_HOST_NAME, hostName);
    Integer portNumber = storageProvider.getPortNumber();
    ArrayList<Section> sections = new ArrayList<Section>();
    String volume_driver = "";
    String auth_strategy = "unknown";
    ChannelSftp sftp = null;
    Session session = null;
    try {
        JSch jsch = new JSch();
        session = jsch.getSession(username, hostName, portNumber);
        session.setPassword(password);
        Hashtable<String, String> config = new Hashtable<String, String>();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect(timeout);
        _logger.debug("Session Connected...");
        Channel channel = session.openChannel("sftp");
        sftp = (ChannelSftp) channel;
        InputStream ins;
        sftp.connect(connectTimeout);
        if (sftp.isConnected()) {
            _logger.debug("SFTP Connected");
            ins = sftp.get(CONFFILE);
            BufferedReader b = new BufferedReader(new InputStreamReader(ins));
            int next_section_index = 0;
            String section_title = "";
            Boolean auth_section = false;
            while (!sftp.isEOF()) {
                String line = b.readLine();
                if (line == null) {
                    _logger.debug("End of buffer -- break");
                    break;
                }
                if (isComment(line)) {
                    // skip comments
                    continue;
                }
                if (isSection(line)) {
                    // start new section
                    section_title = line.substring(line.indexOf('[') + 1, line.indexOf(']'));
                    Section section = new Section();
                    section.index = next_section_index;
                    section.title = section_title;
                    sections.add(section);
                    next_section_index++;
                    _logger.debug("Section {}: Title: {}", section.index, section.title);
                    auth_section = section_title.startsWith(auth_strategy);
                    continue;
                }
                if (!line.contains("=")) {
                    // not a value-parameter pair
                    continue;
                }
                // Now process each line
                String[] splits = line.split("=");
                if (splits.length == 2) {
                    String parameter = splits[0].trim();
                    String value = splits[1].trim();
                    if (auth_section) {
                        if (parameter.equalsIgnoreCase("admin_user") || parameter.equalsIgnoreCase("username")) {
                            updateKeyInProvider(providerKeys, CinderConstants.KEY_CINDER_REST_USER, value);
                            _logger.debug("REST user name = {}", value);
                        } else if (parameter.equalsIgnoreCase("admin_password") || parameter.equalsIgnoreCase("password")) {
                            updateKeyInProvider(providerKeys, CinderConstants.KEY_CINDER_REST_PASSWORD, value);
                            _logger.debug("REST password = {}", value);
                        } else if (parameter.equalsIgnoreCase("admin_tenant_name") || parameter.equalsIgnoreCase("project_name")) {
                            updateKeyInProvider(providerKeys, CinderConstants.KEY_CINDER_TENANT_NAME, value);
                            _logger.debug("Tenant name = {}", value);
                        } else if (parameter.equalsIgnoreCase("auth_uri")) {
                            updateKeyInProvider(providerKeys, CinderConstants.KEY_CINDER_REST_URI_BASE, value);
                            _logger.info("REST uri = {}", value);
                        }
                    } else {
                        // this is a storage section
                        _logger.debug("Storage section: parameter = {},  value = {}", parameter, value);
                        if (parameter.equalsIgnoreCase("auth_strategy")) {
                            auth_strategy = value.trim();
                            _logger.info("Auth strategy = {}", auth_strategy);
                        } else if (parameter.equalsIgnoreCase("volume_driver")) {
                            volume_driver = value.trim();
                            sections.get(next_section_index - 1).volume_driver = volume_driver;
                            _logger.debug("Volume driver = {}", volume_driver);
                        } else if (parameter.equalsIgnoreCase("volume_backend_name")) {
                            String volume_backend_name = value.trim();
                            _logger.debug("Volume backend_name = {}", volume_backend_name);
                            sections.get(next_section_index - 1).volume_backend_name = volume_backend_name;
                        }
                    }
                }
            /* if splits.length */
            }
            /* while not EOF */
            b.close();
        }
        /* if sftp is connected */
        storageProvider.setConnectionStatus(ConnectionStatus.CONNECTED.name());
    }/* try */
     catch (Exception e) {
        // exceptionOccured = true;
        storageProvider.setConnectionStatus(ConnectionStatus.NOTCONNECTED.name());
        _logger.error("Exception occurred while scanning provider {}", accessProfile.getSystemId(), e);
    } finally {
        fillStorageSystemCache(accessProfile, sections);
        if (storageProvider.getKeys() == null) {
            /* first time scan */
            storageProvider.setKeys(providerKeys);
        }
        _dbClient.persistObject(storageProvider);
        if (sftp != null) {
            sftp.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
    _logger.info("Scanning ended for provider: {}", accessProfile.getSystemId());
}
Also used : StringMap(com.emc.storageos.db.client.model.StringMap) InputStreamReader(java.io.InputStreamReader) Hashtable(java.util.Hashtable) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) ArrayList(java.util.ArrayList) StorageProvider(com.emc.storageos.db.client.model.StorageProvider) JSch(com.jcraft.jsch.JSch) AlternateIdConstraint(com.emc.storageos.db.client.constraint.AlternateIdConstraint) ContainmentConstraint(com.emc.storageos.db.client.constraint.ContainmentConstraint) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException) BaseCollectionException(com.emc.storageos.plugins.BaseCollectionException) IOException(java.io.IOException) CinderColletionException(com.emc.storageos.volumecontroller.impl.cinder.CinderColletionException) ChannelSftp(com.jcraft.jsch.ChannelSftp) BufferedReader(java.io.BufferedReader) Session(com.jcraft.jsch.Session)

Example 73 with ChannelSftp

use of com.jcraft.jsch.ChannelSftp in project cdap by caskdata.

the class SFTPFileSystem method getHomeDirectory.

@Override
public Path getHomeDirectory() {
    ChannelSftp channel = null;
    try {
        channel = connect();
        Path homeDir = new Path(channel.pwd());
        return homeDir;
    } catch (Exception ioe) {
        return null;
    } finally {
        try {
            disconnect(channel);
        } catch (IOException ioe) {
            return null;
        }
    }
}
Also used : Path(org.apache.hadoop.fs.Path) ChannelSftp(com.jcraft.jsch.ChannelSftp) IOException(java.io.IOException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SftpException(com.jcraft.jsch.SftpException)

Example 74 with ChannelSftp

use of com.jcraft.jsch.ChannelSftp in project cdap by caskdata.

the class SFTPFileSystem method open.

@Override
public FSDataInputStream open(Path f, int bufferSize) throws IOException {
    ChannelSftp channel = connect();
    Path workDir;
    try {
        workDir = new Path(channel.pwd());
    } catch (SftpException e) {
        throw new IOException(e);
    }
    Path absolute = makeAbsolute(workDir, f);
    FileStatus fileStat = getFileStatus(channel, absolute);
    if (fileStat.isDirectory()) {
        disconnect(channel);
        throw new IOException(String.format(E_PATH_DIR, f));
    }
    InputStream is;
    try {
        // the path could be a symbolic link, so get the real path
        absolute = new Path("/", channel.realpath(absolute.toUri().getPath()));
        is = channel.get(absolute.toUri().getPath());
    } catch (SftpException e) {
        throw new IOException(e);
    }
    FSDataInputStream fis = new FSDataInputStream(new SFTPInputStream(is, channel, statistics));
    return fis;
}
Also used : Path(org.apache.hadoop.fs.Path) ChannelSftp(com.jcraft.jsch.ChannelSftp) FileStatus(org.apache.hadoop.fs.FileStatus) FSDataInputStream(org.apache.hadoop.fs.FSDataInputStream) InputStream(java.io.InputStream) SftpException(com.jcraft.jsch.SftpException) FSDataInputStream(org.apache.hadoop.fs.FSDataInputStream) IOException(java.io.IOException)

Example 75 with ChannelSftp

use of com.jcraft.jsch.ChannelSftp in project cdap by caskdata.

the class SFTPConnectionPool method shutdown.

/**
 * Shutdown the connection pool and close all open connections.
 */
synchronized void shutdown() {
    if (this.con2infoMap == null) {
        // already shutdown in case it is called
        return;
    }
    LOG.info("Inside shutdown, con2infoMap size=" + con2infoMap.size());
    this.maxConnection = 0;
    Set<ChannelSftp> cons = con2infoMap.keySet();
    if (cons != null && cons.size() > 0) {
        // make a copy since we need to modify the underlying Map
        Set<ChannelSftp> copy = new HashSet<ChannelSftp>(cons);
        // Initiate disconnect from all outstanding connections
        for (ChannelSftp con : copy) {
            try {
                disconnect(con);
            } catch (IOException ioe) {
                ConnectionInfo info = con2infoMap.get(con);
                LOG.error("Error encountered while closing connection to " + info.getHost(), ioe);
            }
        }
    }
    // make sure no further connections can be returned.
    this.idleConnections = null;
    this.con2infoMap = null;
}
Also used : ChannelSftp(com.jcraft.jsch.ChannelSftp) IOException(java.io.IOException) HashSet(java.util.HashSet)

Aggregations

ChannelSftp (com.jcraft.jsch.ChannelSftp)99 SftpException (com.jcraft.jsch.SftpException)61 IOException (java.io.IOException)36 JSchException (com.jcraft.jsch.JSchException)28 Session (com.jcraft.jsch.Session)25 JSch (com.jcraft.jsch.JSch)20 Channel (com.jcraft.jsch.Channel)17 LsEntry (com.jcraft.jsch.ChannelSftp.LsEntry)17 File (java.io.File)16 Test (org.junit.Test)14 InputStream (java.io.InputStream)12 SftpATTRS (com.jcraft.jsch.SftpATTRS)11 FileNotFoundException (java.io.FileNotFoundException)9 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)8 FileInputStream (java.io.FileInputStream)7 OutputStream (java.io.OutputStream)7 Path (org.apache.hadoop.fs.Path)7 CoreException (org.eclipse.core.runtime.CoreException)7 IStatus (org.eclipse.core.runtime.IStatus)7 Status (org.eclipse.core.runtime.Status)7