2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.onap.appc.adapter.ssh.sshd;
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.ClientChannel;
34 import org.apache.sshd.ClientSession;
35 import org.apache.sshd.SshClient;
36 import org.apache.sshd.client.channel.ChannelExec;
37 import org.apache.sshd.client.future.AuthFuture;
38 import org.apache.sshd.client.future.OpenFuture;
39 import org.apache.sshd.common.KeyPairProvider;
40 import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
42 import com.att.eelf.configuration.EELFLogger;
43 import com.att.eelf.configuration.EELFManager;
45 import java.io.OutputStream;
46 import java.security.KeyPair;
49 * Implementation of SshConnection interface based on Apache MINA SSHD library.
51 class SshConnectionSshd implements SshConnection {
53 private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
55 private static final long AUTH_TIMEOUT = 60000;
56 private static final long EXEC_TIMEOUT = 120000;
60 private String username;
61 private String password;
62 private long timeout = EXEC_TIMEOUT;
63 private String keyFile;
64 private SshClient sshClient;
65 private ClientSession clientSession;
66 private static final Configuration configuration = ConfigurationFactory.getConfiguration();
68 public SshConnectionSshd(String host, int port, String username, String password, String keyFile) {
71 this.username = username;
72 this.password = password;
73 this.keyFile = keyFile;
76 public SshConnectionSshd(String host, int port, String username, String password) {
77 this(host, port, username, password, null);
80 public SshConnectionSshd(String host, int port, String keyFile) {
81 this(host, port, null, null, keyFile);
85 public void connect() {
86 sshClient = SshClient.setUpDefaultClient();
90 sshClient.connect(EncryptionTool.getInstance().decrypt(username), host, port).await().getSession();
91 if (password != null) {
92 clientSession.addPasswordIdentity(EncryptionTool.getInstance().decrypt(password));
94 if (keyFile != null) {
95 KeyPairProvider keyPairProvider = new FileKeyPairProvider(new String[] {
98 KeyPair keyPair = keyPairProvider.loadKeys().iterator().next();
99 clientSession.addPublicKeyIdentity(keyPair);
101 AuthFuture authFuture = clientSession.auth();
102 authFuture.await(AUTH_TIMEOUT);
103 if (!authFuture.isSuccess()) {
104 throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port
105 + "]. Authentication failed.");
107 } catch (RuntimeException e) {
109 } catch (Exception e) {
110 throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port + "].",
113 if (logger.isDebugEnabled()) {
114 logger.debug("SSH: connected to [" + toString() + "]");
119 public void connectWithRetry() {
123 retryCount = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_COUNT,
124 Constants.DEFAULT_CONNECTION_RETRY_COUNT);
125 retryDelay = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_DELAY,
126 Constants.DEFAULT_CONNECTION_RETRY_DELAY);
127 retriesLeft = retryCount + 1;
132 } catch (RuntimeException e) {
133 if (retriesLeft > 1) {
134 logger.debug("SSH Connection failed. Waiting for change in server's state.");
135 waitForConnection(retryDelay);
137 logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
138 + "] out of [" + retryCount + "]");
143 } while (retriesLeft > 0);
147 public void disconnect() {
149 if (logger.isDebugEnabled()) {
150 logger.debug("SSH: disconnecting from [" + toString() + "]");
152 clientSession.close(false);
154 if (sshClient != null) {
161 public void setExecTimeout(long timeout) {
162 this.timeout = timeout;
166 public int execCommand(String cmd, OutputStream out, OutputStream err) {
167 return execCommand(cmd, out, err, false);
171 public int execCommandWithPty(String cmd, OutputStream out) {
172 return execCommand(cmd, out, out, true);
175 private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) {
177 if (logger.isDebugEnabled()) {
178 logger.debug("SSH: executing command");
180 ChannelExec client = clientSession.createExecChannel(cmd);
181 client.setUsePty(usePty); // use pseudo-tty?
184 OpenFuture openFuture = client.open();
187 client.waitFor(ClientChannel.CLOSED, timeout);
189 Integer exitStatusI = client.getExitStatus();
190 if (exitStatusI == null) {
191 throw new SshException("Error executing command [" + cmd + "] over SSH [" + username + "@" + host
192 + ":" + port + "]. Operation timed out.");
194 exitStatus = exitStatusI;
199 } catch (RuntimeException e) {
201 } catch (Exception e1) {
202 throw new SshException(
203 "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", e1);
207 private void waitForConnection(int retryDelay) {
208 long time = retryDelay * 1000L;
209 long future = System.currentTimeMillis() + time;
211 while (System.currentTimeMillis() < future && time > 0) {
214 } catch (InterruptedException e) {
216 * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
217 * case, the thread is resumed before the delay time has actually expired, so re-calculate the
218 * amount of delay time needed and reenter the sleep until we get to the future time.
220 time = future - System.currentTimeMillis();
227 public String toString() {
228 String address = host;
229 if (username != null) {
230 address = username + '@' + address;