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.onap.appc.adapter.ssh.Constants;
27 import org.onap.appc.adapter.ssh.SshConnection;
28 import org.onap.appc.adapter.ssh.SshException;
29 import org.onap.appc.encryption.EncryptionTool;
30 import org.onap.appc.configuration.Configuration;
31 import org.onap.appc.configuration.ConfigurationFactory;
32 import org.apache.sshd.ClientChannel;
33 import org.apache.sshd.ClientSession;
34 import org.apache.sshd.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.KeyPairProvider;
39 import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
41 import com.att.eelf.configuration.EELFLogger;
42 import com.att.eelf.configuration.EELFManager;
44 import java.io.OutputStream;
45 import java.security.KeyPair;
48 * Implementation of SshConnection interface based on Apache MINA SSHD library.
50 class SshConnectionSshd implements SshConnection {
52 private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
54 private static final long AUTH_TIMEOUT = 60000;
55 private static final long EXEC_TIMEOUT = 120000;
59 private String username;
60 private String password;
61 private long timeout = EXEC_TIMEOUT;
62 private String keyFile;
63 private SshClient sshClient;
64 private ClientSession clientSession;
65 private static final Configuration configuration = ConfigurationFactory.getConfiguration();
67 public SshConnectionSshd(String host, int port, String username, String password, String keyFile) {
70 this.username = username;
71 this.password = password;
72 this.keyFile = keyFile;
75 public SshConnectionSshd(String host, int port, String username, String password) {
76 this(host, port, username, password, null);
79 public SshConnectionSshd(String host, int port, String keyFile) {
80 this(host, port, null, null, keyFile);
84 public void connect() {
85 sshClient = SshClient.setUpDefaultClient();
89 sshClient.connect(EncryptionTool.getInstance().decrypt(username), host, port).await().getSession();
90 if (password != null) {
91 clientSession.addPasswordIdentity(EncryptionTool.getInstance().decrypt(password));
93 if (keyFile != null) {
94 KeyPairProvider keyPairProvider = new FileKeyPairProvider(new String[] {
97 KeyPair keyPair = keyPairProvider.loadKeys().iterator().next();
98 clientSession.addPublicKeyIdentity(keyPair);
100 AuthFuture authFuture = clientSession.auth();
101 authFuture.await(AUTH_TIMEOUT);
102 if (!authFuture.isSuccess()) {
103 throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port
104 + "]. Authentication failed.");
106 } catch (RuntimeException e) {
108 } catch (Exception e) {
109 throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port + "].",
112 if (logger.isDebugEnabled()) {
113 logger.debug("SSH: connected to [" + toString() + "]");
118 public void connectWithRetry() {
122 retryCount = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_COUNT,
123 Constants.DEFAULT_CONNECTION_RETRY_COUNT);
124 retryDelay = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_DELAY,
125 Constants.DEFAULT_CONNECTION_RETRY_DELAY);
126 retriesLeft = retryCount + 1;
131 } catch (RuntimeException e) {
132 if (retriesLeft > 1) {
133 logger.debug("SSH Connection failed. Waiting for change in server's state.");
134 waitForConnection(retryDelay);
136 logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
137 + "] out of [" + retryCount + "]");
142 } while (retriesLeft > 0);
146 public void disconnect() {
148 if (logger.isDebugEnabled()) {
149 logger.debug("SSH: disconnecting from [" + toString() + "]");
151 clientSession.close(false);
153 if (sshClient != null) {
160 public void setExecTimeout(long timeout) {
161 this.timeout = timeout;
165 public int execCommand(String cmd, OutputStream out, OutputStream err) {
166 return execCommand(cmd, out, err, false);
170 public int execCommandWithPty(String cmd, OutputStream out) {
171 return execCommand(cmd, out, out, true);
174 private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) {
176 if (logger.isDebugEnabled()) {
177 logger.debug("SSH: executing command");
179 ChannelExec client = clientSession.createExecChannel(cmd);
180 client.setUsePty(usePty); // use pseudo-tty?
183 OpenFuture openFuture = client.open();
186 client.waitFor(ClientChannel.CLOSED, timeout);
188 Integer exitStatusI = client.getExitStatus();
189 if (exitStatusI == null) {
190 throw new SshException("Error executing command [" + cmd + "] over SSH [" + username + "@" + host
191 + ":" + port + "]. Operation timed out.");
193 exitStatus = exitStatusI;
198 } catch (RuntimeException e) {
200 } catch (Exception e1) {
201 throw new SshException(
202 "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", e1);
206 private void waitForConnection(int retryDelay) {
207 long time = retryDelay * 1000L;
208 long future = System.currentTimeMillis() + time;
210 while (System.currentTimeMillis() < future && time > 0) {
213 } catch (InterruptedException e) {
215 * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
216 * case, the thread is resumed before the delay time has actually expired, so re-calculate the
217 * amount of delay time needed and reenter the sleep until we get to the future time.
219 time = future - System.currentTimeMillis();
226 public String toString() {
227 String address = host;
228 if (username != null) {
229 address = username + '@' + address;