saltstack reqExecSls implemented as adaptor
[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) {
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
103         SaltstackResult result = new SaltstackResult();
104         try {
105             if (retryCount != -1) {
106                 result = sshConnection.connectWithRetry(retryCount, retryDelay);
107             } else {
108                 result = sshConnection.connect();
109             }
110             if (result.getStatusCode() != SaltstackResultCodes.SUCCESS.getValue()) {
111                 return result;
112             }
113             String outFilePath = "/tmp/" + RandomStringUtils.random(5, true, true);
114             String errFilePath = "/tmp/" + RandomStringUtils.random(5, true, true);
115             OutputStream out = new FileOutputStream(outFilePath);
116             OutputStream errs = new FileOutputStream(errFilePath);
117             result = sshConnection.execCommand(cmd, out, errs);
118             sshConnection.disconnect();
119             out.close();
120             errs.close();
121             if (result.getSshExitStatus() != 0) {
122                 return sortExitStatus(result.getSshExitStatus(), errFilePath, cmd);
123             }
124             if (result.getStatusCode() != SaltstackResultCodes.SUCCESS.getValue()) {
125                 return result;
126             }
127             result.setStatusMessage("Success");
128             result.setOutputFileName(outFilePath);
129         } catch (Exception io) {
130             logger.error("Caught Exception", io);
131             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
132             result.setStatusMessage(io.getMessage());
133         }
134         return result;
135     }
136
137     public SaltstackResult sortExitStatus(int exitStatus, String errFilePath, String cmd) {
138         SaltstackResult result = new SaltstackResult();
139         String err = "";
140         StringWriter writer = new StringWriter();
141         try {
142             IOUtils.copy(new FileInputStream(new File(errFilePath)), writer, "UTF-8");
143             err = writer.toString();
144         } catch (FileNotFoundException e){
145             logger.info("Error stream file doesn't exist");
146         } catch (IOException e){
147             logger.info("Error stream file doesn't exist");
148         }
149         if (exitStatus == 255 || exitStatus == 1) {
150             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
151                     + "]. Exit Code " + exitStatus + " and Error message : " +
152                     "Malformed configuration. " + err;
153             logger.error(errMessage);
154             result.setStatusCode(SaltstackResultCodes.INVALID_COMMAND.getValue());
155             result.setStatusMessage(errMessage);
156         } else if (exitStatus == 5 || exitStatus == 65) {
157             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
158                     + "]. Exit Code " + exitStatus + " and Error message : " +
159                     "Host not allowed to connect. " + err;
160             logger.error(errMessage);
161             result.setStatusCode(SaltstackResultCodes.USER_UNAUTHORIZED.getValue());
162             result.setStatusMessage(errMessage);
163         } else if (exitStatus == 67 || exitStatus == 73) {
164             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
165                     + "]. Exit Code " + exitStatus + " and Error message : " +
166                     "Key exchange failed. " + err;
167             logger.error(errMessage);
168             result.setStatusCode(SaltstackResultCodes.CERTIFICATE_ERROR.getValue());
169             result.setStatusMessage(errMessage);
170         } else {
171             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
172                     + "]. Exit Code " + exitStatus + " and Error message : " + err;
173             logger.error(errMessage);
174             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
175             result.setStatusMessage(errMessage);
176         }
177         return result;
178     }
179
180     /**
181      * 1. Connect to SSH server.
182      * 2. Exec remote command over SSH. Return command execution status.
183      * Command output is written to out or err stream.
184      *
185      * @param commands   list of commands to execute
186      * @param payloadSLS has the SLS file location that is to be sent to server
187      * @param retryDelay delay between retry to make a SSH connection.
188      * @param retryCount number of count retry to make a SSH connection.
189      * @return command execution status
190      */
191     public SaltstackResult connectNExecuteSLS(String commands, String payloadSLS, int retryDelay, int retryCount) {
192
193         SaltstackResult result = new SaltstackResult();
194         try {
195             //TODO: to implement SSH connected client to Saltstack Server
196         } catch (Exception io) {
197             logger.error("Caught Exception", io);
198             result.setStatusCode(SaltstackResultCodes.IO_EXCEPTION.getValue());
199             result.setStatusMessage(io.getMessage());
200         }
201         return result;
202     }
203
204     /**
205      * Disconnect from SSH server.
206      */
207     public SaltstackResult disConnect() {
208
209         SaltstackResult result = new SaltstackResult();
210         try {
211             //TODO: to implement SSH connected client to Saltstack Server
212         } catch (Exception io) {
213             logger.error("Caught Exception", io);
214             result.setStatusCode(SaltstackResultCodes.IO_EXCEPTION.getValue());
215             result.setStatusMessage(io.getMessage());
216         }
217         return result;
218     }
219
220     /**
221      * Exec remote command over SSH. Return command execution status.
222      * Command output is written to out or err stream.
223      *
224      * @param cmd command to execute
225      * @return command execution status
226      */
227     public SaltstackResult connectNExecuteLog(String cmd) {
228
229         SaltstackResult result = new SaltstackResult();
230
231         try {
232             //TODO: to implement SSH command execute
233         } catch (Exception io) {
234             result.setStatusCode(SaltstackResultCodes.IO_EXCEPTION.getValue());
235             result.setStatusMessage(io.getMessage());
236             logger.error("Caught IOException", io);
237         }
238         return result;
239     }
240 }