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.ccsdk.sli.adaptors.saltstack.impl;
27 import org.onap.appc.encryption.EncryptionTool;
28 import org.apache.sshd.ClientChannel;
29 import org.apache.sshd.ClientSession;
30 import org.apache.sshd.SshClient;
31 import org.apache.sshd.client.channel.ChannelExec;
32 import org.apache.sshd.client.future.AuthFuture;
33 import org.apache.sshd.client.future.OpenFuture;
34 import org.apache.sshd.common.KeyPairProvider;
35 import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
37 import com.att.eelf.configuration.EELFLogger;
38 import com.att.eelf.configuration.EELFManager;
39 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResult;
40 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResultCodes;
41 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
43 import java.io.OutputStream;
44 import java.security.KeyPair;
47 * Implementation of SshConnection interface based on Apache MINA SSHD library.
51 private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
53 private static final long AUTH_TIMEOUT = 60000;
54 private static final long EXEC_TIMEOUT = 120000;
58 private String username;
59 private String password;
60 private long timeout = EXEC_TIMEOUT;
61 private String keyFile;
62 private SshClient sshClient;
63 private ClientSession clientSession;
65 public static final int DEFAULT_CONNECTION_RETRY_DELAY = 60;
66 public static final int DEFAULT_CONNECTION_RETRY_COUNT = 5;
68 public SshConnection(String host, int port, String username, String password, String keyFile) {
71 this.username = username;
72 this.password = password;
73 this.keyFile = keyFile;
76 public SshConnection(String host, int port, String username, String password) {
77 this(host, port, username, password, null);
80 public SshConnection(String host, int port, String keyFile) {
81 this(host, port, null, null, keyFile);
84 public SaltstackResult connect() {
85 SaltstackResult result = new SaltstackResult();
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 String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port
105 + "]. Authentication failed.";
106 result.setStatusCode(SaltstackResultCodes.USER_UNAUTHORIZED.getValue());
107 result.setStatusMessage(errMessage);
109 } catch (RuntimeException e) {
110 String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port + "]." +
111 "Runtime Exception : "+ e.getMessage();
112 result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
113 result.setStatusMessage(errMessage);
114 } catch (Exception e) {
115 String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port + "]." +
116 "Host Unknown : " + e.getMessage();
117 result.setStatusCode(SaltstackResultCodes.HOST_UNKNOWN.getValue());
118 result.setStatusMessage(errMessage);
120 if (logger.isDebugEnabled()) {
121 logger.debug("SSH: connected to [" + toString() + "]");
123 result.setStatusCode(SaltstackResultCodes.SUCCESS.getValue());
127 public SaltstackResult connectWithRetry(int retryCount, int retryDelay) {
129 SaltstackResult result = new SaltstackResult();
131 retryCount = DEFAULT_CONNECTION_RETRY_COUNT;
133 retryDelay = DEFAULT_CONNECTION_RETRY_DELAY;
134 retriesLeft = retryCount + 1;
137 result = this.connect();
139 } catch (RuntimeException e) {
140 if (retriesLeft > 1) {
141 logger.debug("SSH Connection failed. Waiting for change in server's state.");
142 waitForConnection(retryDelay);
144 logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
145 + "] out of [" + retryCount + "]");
150 } while (retriesLeft > 0);
154 public void disconnect() {
156 if (logger.isDebugEnabled()) {
157 logger.debug("SSH: disconnecting from [" + toString() + "]");
159 clientSession.close(false);
161 if (sshClient != null) {
167 public void setExecTimeout(long timeout) {
168 this.timeout = timeout;
171 public SaltstackResult execCommand(String cmd, OutputStream out, OutputStream err) {
172 return execCommand(cmd, out, err, false);
175 public SaltstackResult execCommandWithPty(String cmd, OutputStream out) {
176 return execCommand(cmd, out, out, true);
179 private SaltstackResult execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) {
180 SaltstackResult result = new SaltstackResult();
182 if (logger.isDebugEnabled()) {
183 logger.debug("SSH: executing command");
185 ChannelExec client = clientSession.createExecChannel(cmd);
186 client.setUsePty(usePty); // use pseudo-tty?
189 OpenFuture openFuture = client.open();
192 client.waitFor(ClientChannel.CLOSED, timeout);
194 Integer exitStatusI = client.getExitStatus();
195 if (exitStatusI == null) {
196 String errMessage = "Error executing command [" + cmd + "] over SSH [" + username + "@" + host
197 + ":" + port + "]. SSH operation timed out.";
198 result.setStatusCode(SaltstackResultCodes.OPERATION_TIMEOUT.getValue());
199 result.setStatusMessage(errMessage);
202 exitStatus = exitStatusI;
206 result.setSshExitStatus(exitStatus);
208 } catch (RuntimeException e) {
209 String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port + "]." +
210 "Runtime Exception : "+ e.getMessage();
211 result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
212 result.setStatusMessage(errMessage);
213 } catch (Exception e1) {
214 String errMessage = "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" +
215 port + "]"+ e1.getMessage();
216 result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
217 result.setStatusMessage(errMessage);
219 result.setStatusCode(SaltstackResultCodes.SUCCESS.getValue());
223 private void waitForConnection(int retryDelay) {
224 long time = retryDelay * 1000L;
225 long future = System.currentTimeMillis() + time;
227 while (System.currentTimeMillis() < future && time > 0) {
230 } catch (InterruptedException e) {
232 * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
233 * case, the thread is resumed before the delay time has actually expired, so re-calculate the
234 * amount of delay time needed and reenter the sleep until we get to the future time.
236 time = future - System.currentTimeMillis();
243 public String toString() {
244 String address = host;
245 if (username != null) {
246 address = username + '@' + address + ':' + port;