71ca5cf7cff21e3bb9d5be66d4d80c02a7d03ca0
[ccsdk/sli/adaptors.git] / saltstack-adapter / saltstack-adapter-provider / src / main / java / org / onap / ccsdk / sli / adaptors / saltstack / impl / SshConnection.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : CCSDK
4  * ================================================================================
5  * Copyright (C) 2018 Samsung Electronics. All rights reserved.
6  * ================================================================================
7  *
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
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
21  *
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.ccsdk.sli.adaptors.saltstack.impl;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import org.apache.sshd.ClientChannel;
30 import org.apache.sshd.ClientSession;
31 import org.apache.sshd.SshClient;
32 import org.apache.sshd.client.channel.ChannelExec;
33 import org.apache.sshd.client.future.AuthFuture;
34 import org.apache.sshd.client.future.OpenFuture;
35 import org.apache.sshd.common.KeyPairProvider;
36 import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
37 import org.onap.appc.encryption.EncryptionTool;
38 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResult;
39 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResultCodes;
40
41 import java.io.OutputStream;
42 import java.security.KeyPair;
43
44 /**
45  * Implementation of SshConnection interface based on Apache MINA SSHD library.
46  */
47 class SshConnection {
48
49     public static final int DEFAULT_CONNECTION_RETRY_DELAY = 60;
50     public static final int DEFAULT_CONNECTION_RETRY_COUNT = 5;
51     private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
52     private static final long AUTH_TIMEOUT = 60000;
53     private static final long EXEC_TIMEOUT = 120;
54     private String host;
55     private int port;
56     private String username;
57     private String password;
58     private long timeout = EXEC_TIMEOUT;
59     private String keyFile;
60     private SshClient sshClient;
61     private ClientSession clientSession;
62
63     public SshConnection(String host, int port, String username, String password, String keyFile) {
64         this.host = host;
65         this.port = port;
66         this.username = username;
67         this.password = password;
68         this.keyFile = keyFile;
69     }
70
71     public SshConnection(String host, int port, String username, String password) {
72         this(host, port, username, password, null);
73     }
74
75     public SshConnection(String host, int port, String keyFile) {
76         this(host, port, null, null, keyFile);
77     }
78
79     public SaltstackResult connect() {
80         SaltstackResult result = new SaltstackResult();
81         sshClient = SshClient.setUpDefaultClient();
82         sshClient.start();
83         try {
84             clientSession =
85                     sshClient.connect(EncryptionTool.getInstance().decrypt(username), host, port).await().getSession();
86             if (password != null) {
87                 clientSession.addPasswordIdentity(EncryptionTool.getInstance().decrypt(password));
88             }
89             if (keyFile != null) {
90                 KeyPairProvider keyPairProvider = new FileKeyPairProvider(new String[]{
91                         keyFile
92                 });
93                 KeyPair keyPair = keyPairProvider.loadKeys().iterator().next();
94                 clientSession.addPublicKeyIdentity(keyPair);
95             }
96             AuthFuture authFuture = clientSession.auth();
97             authFuture.await(AUTH_TIMEOUT);
98             if (!authFuture.isSuccess()) {
99                 String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port
100                         + "]. Authentication failed.";
101                 result.setStatusCode(SaltstackResultCodes.USER_UNAUTHORIZED.getValue());
102                 result.setStatusMessage(errMessage);
103             }
104         } catch (RuntimeException e) {
105             String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port + "]." +
106                     "Runtime Exception : " + e.getMessage();
107             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
108             result.setStatusMessage(errMessage);
109         } catch (Exception e) {
110             String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port + "]." +
111                     "Host Unknown : " + e.getMessage();
112             result.setStatusCode(SaltstackResultCodes.HOST_UNKNOWN.getValue());
113             result.setStatusMessage(errMessage);
114         }
115         if (logger.isDebugEnabled()) {
116             logger.debug("SSH: connected to [" + toString() + "]");
117         }
118         result.setStatusCode(SaltstackResultCodes.SUCCESS.getValue());
119         return result;
120     }
121
122     public SaltstackResult connectWithRetry(int retryCount, int retryDelay) {
123         int retriesLeft;
124         SaltstackResult result = new SaltstackResult();
125         if (retryCount == 0) {
126             retryCount = DEFAULT_CONNECTION_RETRY_COUNT;
127         }
128         if (retryDelay == 0) {
129             retryDelay = DEFAULT_CONNECTION_RETRY_DELAY;
130         }
131         retriesLeft = retryCount + 1;
132         do {
133             try {
134                 result = this.connect();
135                 break;
136             } catch (RuntimeException e) {
137                 if (retriesLeft > 1) {
138                     logger.debug("SSH Connection failed. Waiting for change in server's state.");
139                     waitForConnection(retryDelay);
140                     retriesLeft--;
141                     logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
142                                          + "] out of [" + retryCount + "]");
143                 } else {
144                     throw e;
145                 }
146             }
147         } while (retriesLeft > 0);
148         return result;
149     }
150
151     public void disconnect() {
152         try {
153             if (logger.isDebugEnabled()) {
154                 logger.debug("SSH: disconnecting from [" + toString() + "]");
155             }
156             clientSession.close(false);
157         } finally {
158             if (sshClient != null) {
159                 sshClient.stop();
160             }
161         }
162     }
163
164     public void setExecTimeout(long timeout) {
165         //convert seconds to milliseconds
166         this.timeout = timeout * 1000;
167     }
168
169     public SaltstackResult execCommand(String cmd, OutputStream out, OutputStream err, SaltstackResult result) {
170         return execCommand(cmd, out, err, false, result);
171     }
172
173     public SaltstackResult execCommandWithPty(String cmd, OutputStream out, SaltstackResult result) {
174         return execCommand(cmd, out, out, true, result);
175     }
176
177     private SaltstackResult execCommand(String cmd, OutputStream out, OutputStream err,
178                                         boolean usePty, SaltstackResult result) {
179
180         try {
181             if (logger.isDebugEnabled()) {
182                 logger.debug("SSH: executing command");
183             }
184             ChannelExec client = clientSession.createExecChannel(cmd);
185             client.setUsePty(usePty); // use pseudo-tty?
186             client.setOut(out);
187             client.setErr(err);
188             OpenFuture openFuture = client.open();
189             int exitStatus;
190             try {
191                 client.waitFor(ClientChannel.CLOSED, timeout);
192                 openFuture.verify();
193                 Integer exitStatusI = client.getExitStatus();
194                 if (exitStatusI == null) {
195                     String errMessage = "Error executing command [" + cmd + "] over SSH [" + username + "@" + host
196                             + ":" + port + "]. SSH operation timed out.";
197                     result.setStatusCode(SaltstackResultCodes.OPERATION_TIMEOUT.getValue());
198                     result.setStatusMessage(errMessage);
199                     return result;
200                 }
201                 exitStatus = exitStatusI;
202             } finally {
203                 client.close(false);
204             }
205             result.setSshExitStatus(exitStatus);
206             return result;
207         } catch (RuntimeException e) {
208             String errMessage = "Error establishing ssh connection to [" + username + "@" + host + ":" + port + "]." +
209                     "Runtime Exception : " + e.getMessage();
210             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
211             result.setStatusMessage(errMessage);
212         } catch (Exception e1) {
213             String errMessage = "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" +
214                     port + "]" + e1.getMessage();
215             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
216             result.setStatusMessage(errMessage);
217         }
218         result.setStatusCode(SaltstackResultCodes.SUCCESS.getValue());
219         return result;
220     }
221
222     private void waitForConnection(int retryDelay) {
223         long time = retryDelay * 1000L;
224         long future = System.currentTimeMillis() + time;
225         if (time != 0) {
226             while (System.currentTimeMillis() < future && time > 0) {
227                 try {
228                     Thread.sleep(time);
229                 } catch (InterruptedException e) {
230                     /*
231                      * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that
232                      * case, the thread is resumed before the delay time has actually expired, so re-calculate the
233                      * amount of delay time needed and reenter the sleep until we get to the future time.
234                      */
235                     time = future - System.currentTimeMillis();
236                 }
237             }
238         }
239     }
240
241     @Override
242     public String toString() {
243         String address = host;
244         if (username != null) {
245             address = username + '@' + address + ':' + port;
246         }
247         return address;
248     }
249 }