saltstack adaptor fixes from Sonar
[ccsdk/sli/adaptors.git] / saltstack-adapter / saltstack-adapter-provider / src / main / java / org / onap / ccsdk / sli / adaptors / saltstack / impl / ConnectionBuilder.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 com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import org.apache.commons.io.IOUtils;
30 import org.apache.commons.lang.RandomStringUtils;
31 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResult;
32 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResultCodes;
33
34 import java.io.File;
35 import java.io.FileInputStream;
36 import java.io.FileNotFoundException;
37 import java.io.FileOutputStream;
38 import java.io.IOException;
39 import java.io.OutputStream;
40 import java.io.StringWriter;
41
42 /**
43  * Returns a custom SSH client
44  * - based on options
45  * - can create one with ssl using an X509 certificate that does NOT have a known CA
46  * - create one which trusts ALL SSL certificates
47  * - return default sshclient (which only trusts known CAs from default cacerts file for process) this is the default
48  * option
49  **/
50 //TODO: This class is to be altered completely based on the SALTSTACK server communication.
51 public class ConnectionBuilder {
52
53     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class);
54     SshConnection sshConnection;
55
56     /**
57      * Constructor that initializes an ssh client based on username and password
58      **/
59     public ConnectionBuilder(String host, String port, String userName, String userPasswd) {
60         sshConnection = new SshConnection(host, Integer.parseInt(port), userName, userPasswd);
61     }
62
63     /**
64      * Constructor that initializes an ssh client based on ssh certificate
65      **/
66     public ConnectionBuilder(String host, String port, String certFile) {
67         sshConnection = new SshConnection(host, Integer.parseInt(port), certFile);
68     }
69
70     /**
71      * Constructor that initializes an ssh client based on ssh username password and certificate
72      **/
73     public ConnectionBuilder(String host, String port, String userName, String userPasswd,
74                              String certFile) {
75
76         sshConnection = new SshConnection(host, Integer.parseInt(port), userName, userPasswd, certFile);
77     }
78
79     /**
80      * 1. Connect to SSH server.
81      * 2. Exec remote command over SSH. Return command execution status.
82      * Command output is written to out or err stream.
83      *
84      * @param cmd Commands to execute
85      * @return command execution status
86      */
87     public SaltstackResult connectNExecute(String cmd) throws IOException {
88         return connectNExecute(cmd, -1, -1);
89     }
90
91     /**
92      * 1. Connect to SSH server with retry enabled.
93      * 2. Exec remote command over SSH. Return command execution status.
94      * Command output is written to out or err stream.
95      *
96      * @param cmd        Commands to execute
97      * @param retryDelay delay between retry to make a SSH connection.
98      * @param retryCount number of count retry to make a SSH connection.
99      * @return command execution status
100      */
101     public SaltstackResult connectNExecute(String cmd, int retryCount, int retryDelay)
102                             throws IOException{
103
104         SaltstackResult result = new SaltstackResult();
105         OutputStream out = null;
106         OutputStream errs = null;
107         try {
108             if (retryCount != -1) {
109                 result = sshConnection.connectWithRetry(retryCount, retryDelay);
110             } else {
111                 result = sshConnection.connect();
112             }
113             if (result.getStatusCode() != SaltstackResultCodes.SUCCESS.getValue()) {
114                 return result;
115             }
116             String outFilePath = "/tmp/" + RandomStringUtils.random(5, true, true);
117             String errFilePath = "/tmp/" + RandomStringUtils.random(5, true, true);
118             out = new FileOutputStream(outFilePath);
119             errs = new FileOutputStream(errFilePath);
120             result = sshConnection.execCommand(cmd, out, errs);
121             sshConnection.disconnect();
122             if (result.getSshExitStatus() != 0) {
123                 return sortExitStatus(result.getSshExitStatus(), errFilePath, cmd);
124             }
125             if (result.getStatusCode() != SaltstackResultCodes.SUCCESS.getValue()) {
126                 return result;
127             }
128             result.setStatusMessage("Success");
129             result.setOutputFileName(outFilePath);
130         } catch (Exception io) {
131             logger.error("Caught Exception", io);
132             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
133             result.setStatusMessage(io.getMessage());
134         } finally {
135             if( out != null )
136                 out.close();
137             if( errs != null )
138                 errs.close();
139         }
140         return result;
141     }
142
143     public SaltstackResult sortExitStatus(int exitStatus, String errFilePath, String cmd) {
144         SaltstackResult result = new SaltstackResult();
145         String err = "";
146         StringWriter writer = new StringWriter();
147         try {
148             IOUtils.copy(new FileInputStream(new File(errFilePath)), writer, "UTF-8");
149             err = writer.toString();
150         } catch (FileNotFoundException e){
151             logger.info("Error stream file doesn't exist");
152         } catch (IOException e){
153             logger.info("Error stream file doesn't exist");
154         }
155         if (exitStatus == 255 || exitStatus == 1) {
156             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
157                     + "]. Exit Code " + exitStatus + " and Error message : " +
158                     "Malformed configuration. " + err;
159             logger.error(errMessage);
160             result.setStatusCode(SaltstackResultCodes.INVALID_COMMAND.getValue());
161             result.setStatusMessage(errMessage);
162         } else if (exitStatus == 5 || exitStatus == 65) {
163             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
164                     + "]. Exit Code " + exitStatus + " and Error message : " +
165                     "Host not allowed to connect. " + err;
166             logger.error(errMessage);
167             result.setStatusCode(SaltstackResultCodes.USER_UNAUTHORIZED.getValue());
168             result.setStatusMessage(errMessage);
169         } else if (exitStatus == 67 || exitStatus == 73) {
170             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
171                     + "]. Exit Code " + exitStatus + " and Error message : " +
172                     "Key exchange failed. " + err;
173             logger.error(errMessage);
174             result.setStatusCode(SaltstackResultCodes.CERTIFICATE_ERROR.getValue());
175             result.setStatusMessage(errMessage);
176         } else {
177             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
178                     + "]. Exit Code " + exitStatus + " and Error message : " + err;
179             logger.error(errMessage);
180             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
181             result.setStatusMessage(errMessage);
182         }
183         return result;
184     }
185
186     /**
187      * 1. Connect to SSH server.
188      * 2. Exec remote command over SSH. Return command execution status.
189      * Command output is written to out or err stream.
190      *
191      * @param commands   list of commands to execute
192      * @param payloadSLS has the SLS file location that is to be sent to server
193      * @param retryDelay delay between retry to make a SSH connection.
194      * @param retryCount number of count retry to make a SSH connection.
195      * @return command execution status
196      */
197     public SaltstackResult connectNExecuteSLS(String commands, String payloadSLS, int retryDelay, int retryCount) {
198
199         SaltstackResult result = new SaltstackResult();
200         try {
201             //TODO: to implement SSH connected client to Saltstack Server
202         } catch (Exception io) {
203             logger.error("Caught Exception", io);
204             result.setStatusCode(SaltstackResultCodes.IO_EXCEPTION.getValue());
205             result.setStatusMessage(io.getMessage());
206         }
207         return result;
208     }
209
210     /**
211      * Disconnect from SSH server.
212      */
213     public SaltstackResult disConnect() {
214
215         SaltstackResult result = new SaltstackResult();
216         try {
217             //TODO: to implement SSH connected client to Saltstack Server
218         } catch (Exception io) {
219             logger.error("Caught Exception", io);
220             result.setStatusCode(SaltstackResultCodes.IO_EXCEPTION.getValue());
221             result.setStatusMessage(io.getMessage());
222         }
223         return result;
224     }
225
226     /**
227      * Exec remote command over SSH. Return command execution status.
228      * Command output is written to out or err stream.
229      *
230      * @param cmd command to execute
231      * @return command execution status
232      */
233     public SaltstackResult connectNExecuteLog(String cmd) {
234
235         SaltstackResult result = new SaltstackResult();
236
237         try {
238             //TODO: to implement SSH command execute
239         } catch (Exception io) {
240             result.setStatusCode(SaltstackResultCodes.IO_EXCEPTION.getValue());
241             result.setStatusMessage(io.getMessage());
242             logger.error("Caught IOException", io);
243         }
244         return result;
245     }
246 }