2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ============LICENSE_END=========================================================
24 package org.onap.appc.adapter.ssh.sshd;
26 import org.apache.sshd.client.channel.ClientChannelEvent;
27 import org.onap.appc.adapter.ssh.Constants;
28 import org.onap.appc.adapter.ssh.SshConnection;
29 import org.onap.appc.adapter.ssh.SshException;
30 import org.onap.appc.encryption.EncryptionTool;
31 import org.onap.appc.configuration.Configuration;
32 import org.onap.appc.configuration.ConfigurationFactory;
33 import org.apache.sshd.client.session.ClientSession;
34 import org.apache.sshd.client.SshClient;
35 import org.apache.sshd.client.channel.ChannelExec;
36 import org.apache.sshd.client.future.AuthFuture;
37 import org.apache.sshd.client.future.OpenFuture;
38 import org.apache.sshd.common.keyprovider.KeyPairProvider;
39 import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
41 import com.att.eelf.configuration.EELFLogger;
42 import com.att.eelf.configuration.EELFManager;
45 import java.io.OutputStream;
46 import java.security.KeyPair;
47 import java.util.Arrays;
50 * Implementation of SshConnection interface based on Apache MINA SSHD library.
52 class SshConnectionSshd implements SshConnection {
54 private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
56 private static final long AUTH_TIMEOUT = 60000;
57 private static final long EXEC_TIMEOUT = 120000;
61 private String username;
62 private String password;
63 private long timeout = EXEC_TIMEOUT;
64 private String keyFile;
65 private SshClient sshClient;
66 private ClientSession clientSession;
67 private static final Configuration configuration = ConfigurationFactory.getConfiguration();
69 public SshConnectionSshd(String host, int port, String username, String password, String keyFile) {
72 this.username = username;
73 this.password = password;
74 this.keyFile = keyFile;
77 public SshConnectionSshd(String host, int port, String username, String password) {
78 this(host, port, username, password, null);
81 public SshConnectionSshd(String host, int port, String keyFile) {
82 this(host, port, null, null, keyFile);
86 public void connect() {
87 sshClient = SshClient.setUpDefaultClient();
91 sshClient.connect(EncryptionTool.getInstance().decrypt(username), host, port).verify().getSession();
92 if (password != null) {
93 clientSession.addPasswordIdentity(EncryptionTool.getInstance().decrypt(password));
95 if (keyFile != null) {
96 KeyPairProvider keyPairProvider = new FileKeyPairProvider(
97 new File(keyFile).toPath()
99 KeyPair keyPair = keyPairProvider.loadKeys().iterator().next();
100 clientSession.addPublicKeyIdentity(keyPair);
102 AuthFuture authFuture = clientSession.auth();
103 authFuture.await(AUTH_TIMEOUT);
104 if (!authFuture.isSuccess()) {
105 throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port
106 + "]. Authentication failed.");
108 } catch (RuntimeException e) {
110 } catch (Exception e) {
111 throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port + "].",
114 if (logger.isDebugEnabled()) {
115 logger.debug("SSH: connected to [" + toString() + "]");
120 public void connectWithRetry() {
124 retryCount = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_COUNT,
125 Constants.DEFAULT_CONNECTION_RETRY_COUNT);
126 retryDelay = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_DELAY,
127 Constants.DEFAULT_CONNECTION_RETRY_DELAY);
128 retriesLeft = retryCount + 1;
133 } catch (RuntimeException e) {
134 if (retriesLeft > 1) {
135 logger.debug("SSH Connection failed. Waiting for change in server's state.");
136 waitForConnection(retryDelay);
138 logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
139 + "] out of [" + retryCount + "]");
144 } while (retriesLeft > 0);
148 public void disconnect() {
150 if (logger.isDebugEnabled()) {
151 logger.debug("SSH: disconnecting from [" + toString() + "]");
153 clientSession.close(false);
155 if (sshClient != null) {
162 public void setExecTimeout(long timeout) {
163 this.timeout = timeout;
167 public int execCommand(String cmd, OutputStream out, OutputStream err) {
168 return execCommand(cmd, out, err, false);
172 public int execCommandWithPty(String cmd, OutputStream out) {
173 return execCommand(cmd, out, out, true);
176 private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) {
178 if (logger.isDebugEnabled()) {
179 logger.debug("SSH: executing command");
181 ChannelExec client = clientSession.createExecChannel(cmd);
182 client.setUsePty(usePty); // use pseudo-tty?
185 OpenFuture openFuture = client.open();
188 client.waitFor(Arrays.asList(ClientChannelEvent.CLOSED), timeout);
190 Integer exitStatusI = client.getExitStatus();
191 if (exitStatusI == null) {
192 throw new SshException("Error executing command [" + cmd + "] over SSH [" + username + "@" + host
193 + ":" + port + "]. Operation timed out.");
195 exitStatus = exitStatusI;
200 } catch (RuntimeException e) {
202 } catch (Exception e1) {
203 throw new SshException(
204 "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", e1);
208 private void waitForConnection(int retryDelay) {
209 long time = retryDelay * 1000L;
210 long future = System.currentTimeMillis() + time;
212 while (System.currentTimeMillis() < future && time > 0) {
215 } catch (InterruptedException e) {
217 * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
218 * case, the thread is resumed before the delay time has actually expired, so re-calculate the
219 * amount of delay time needed and reenter the sleep until we get to the future time.
221 time = future - System.currentTimeMillis();
228 public String toString() {
229 String address = host;
230 if (username != null) {
231 address = username + '@' + address;