reqExec API implemented for saltstack
[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 : APPC
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
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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.ccsdk.sli.adaptors.saltstack.impl;
26
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;
36
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;
42
43 import java.io.OutputStream;
44 import java.security.KeyPair;
45
46 /**
47  * Implementation of SshConnection interface based on Apache MINA SSHD library.
48  */
49 class SshConnection {
50
51     private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
52
53     private static final long AUTH_TIMEOUT = 60000;
54     private static final long EXEC_TIMEOUT = 120000;
55
56     private String host;
57     private int port;
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;
64
65     public static final int DEFAULT_CONNECTION_RETRY_DELAY = 60;
66     public static final int DEFAULT_CONNECTION_RETRY_COUNT = 5;
67
68     public SshConnection(String host, int port, String username, String password, String keyFile) {
69         this.host = host;
70         this.port = port;
71         this.username = username;
72         this.password = password;
73         this.keyFile = keyFile;
74     }
75
76     public SshConnection(String host, int port, String username, String password) {
77         this(host, port, username, password, null);
78     }
79
80     public SshConnection(String host, int port, String keyFile) {
81         this(host, port, null, null, keyFile);
82     }
83
84     public SaltstackResult connect() {
85         SaltstackResult result = new SaltstackResult();
86         sshClient = SshClient.setUpDefaultClient();
87         sshClient.start();
88         try {
89             clientSession =
90                 sshClient.connect(EncryptionTool.getInstance().decrypt(username), host, port).await().getSession();
91             if (password != null) {
92                 clientSession.addPasswordIdentity(EncryptionTool.getInstance().decrypt(password));
93             }
94             if (keyFile != null) {
95                 KeyPairProvider keyPairProvider = new FileKeyPairProvider(new String[] {
96                     keyFile
97                 });
98                 KeyPair keyPair = keyPairProvider.loadKeys().iterator().next();
99                 clientSession.addPublicKeyIdentity(keyPair);
100             }
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);
108             }
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);
119         }
120         if (logger.isDebugEnabled()) {
121             logger.debug("SSH: connected to [" + toString() + "]");
122         }
123         result.setStatusCode(SaltstackResultCodes.SUCCESS.getValue());
124         return result;
125     }
126
127     public SaltstackResult connectWithRetry(int retryCount, int retryDelay) {
128         int retriesLeft;
129         SaltstackResult result = new SaltstackResult();
130         if(retryCount == 0)
131         retryCount = DEFAULT_CONNECTION_RETRY_COUNT;
132         if(retryDelay == 0)
133         retryDelay = DEFAULT_CONNECTION_RETRY_DELAY;
134         retriesLeft = retryCount + 1;
135         do {
136             try {
137                 result = this.connect();
138                 break;
139             } catch (RuntimeException e) {
140                 if (retriesLeft > 1) {
141                     logger.debug("SSH Connection failed. Waiting for change in server's state.");
142                     waitForConnection(retryDelay);
143                     retriesLeft--;
144                     logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1)
145                         + "] out of [" + retryCount + "]");
146                 } else {
147                     throw e;
148                 }
149           }
150         } while (retriesLeft > 0);
151         return result;
152     }
153
154     public void disconnect() {
155         try {
156             if (logger.isDebugEnabled()) {
157                 logger.debug("SSH: disconnecting from [" + toString() + "]");
158             }
159             clientSession.close(false);
160         } finally {
161             if (sshClient != null) {
162                 sshClient.stop();
163             }
164         }
165     }
166
167     public void setExecTimeout(long timeout) {
168         this.timeout = timeout;
169     }
170
171     public SaltstackResult execCommand(String cmd, OutputStream out, OutputStream err) {
172         return execCommand(cmd, out, err, false);
173     }
174
175     public SaltstackResult execCommandWithPty(String cmd, OutputStream out) {
176         return execCommand(cmd, out, out, true);
177     }
178
179     private SaltstackResult execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) {
180         SaltstackResult result = new SaltstackResult();
181         try {
182             if (logger.isDebugEnabled()) {
183                 logger.debug("SSH: executing command");
184             }
185             ChannelExec client = clientSession.createExecChannel(cmd);
186             client.setUsePty(usePty); // use pseudo-tty?
187             client.setOut(out);
188             client.setErr(err);
189             OpenFuture openFuture = client.open();
190             int exitStatus;
191             try {
192                 client.waitFor(ClientChannel.CLOSED, timeout);
193                 openFuture.verify();
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);
200                     return result;
201                 }
202                 exitStatus = exitStatusI;
203             } finally {
204                 client.close(false);
205             }
206             result.setSshExitStatus(exitStatus);
207             return result;
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);
218         }
219         result.setStatusCode(SaltstackResultCodes.SUCCESS.getValue());
220         return result;
221     }
222
223     private void waitForConnection(int retryDelay) {
224         long time = retryDelay * 1000L;
225         long future = System.currentTimeMillis() + time;
226         if (time != 0) {
227             while (System.currentTimeMillis() < future && time > 0) {
228                 try {
229                     Thread.sleep(time);
230                 } catch (InterruptedException e) {
231                     /*
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.
235                      */
236                     time = future - System.currentTimeMillis();
237                 }
238             }
239         }
240     }
241
242     @Override
243     public String toString() {
244         String address = host;
245         if (username != null) {
246             address = username + '@' + address + ':' + port;
247         }
248         return address;
249     }
250 }