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 + "]");
142 } catch (Exception e) {
145 } while (retriesLeft > 0);
149 public void disconnect() {
151 if (logger.isDebugEnabled()) {
152 logger.debug("SSH: disconnecting from [" + toString() + "]");
154 clientSession.close(false);
156 if (sshClient != null) {
163 public void setExecTimeout(long timeout) {
164 this.timeout = timeout;
168 public int execCommand(String cmd, OutputStream out, OutputStream err) {
169 return execCommand(cmd, out, err, false);
173 public int execCommandWithPty(String cmd, OutputStream out) {
174 return execCommand(cmd, out, out, true);
177 private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) {
179 if (logger.isDebugEnabled()) {
180 logger.debug("SSH: executing command");
182 ChannelExec client = clientSession.createExecChannel(cmd);
183 client.setUsePty(usePty); // use pseudo-tty?
186 OpenFuture openFuture = client.open();
189 client.waitFor(ClientChannel.CLOSED, timeout);
191 Integer exitStatusI = client.getExitStatus();
192 if (exitStatusI == null) {
193 throw new SshException("Error executing command [" + cmd + "] over SSH [" + username + "@" + host
194 + ":" + port + "]. Operation timed out.");
196 exitStatus = exitStatusI;
201 } catch (RuntimeException e) {
203 } catch (Exception t) {
204 throw new SshException(
205 "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", t);
209 private void waitForConnection(int retryDelay) {
210 long time = retryDelay * 1000L;
211 long future = System.currentTimeMillis() + time;
213 while (System.currentTimeMillis() < future && time > 0) {
216 } catch (InterruptedException e) {
218 * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
219 * case, the thread is resumed before the delay time has actually expired, so re-calculate the
220 * amount of delay time needed and reenter the sleep until we get to the future time.
222 time = future - System.currentTimeMillis();
229 public String toString() {
230 String address = host;
231 if (username != null) {
232 address = username + '@' + address;