saltstack reqExecSls implemented as adaptor
[ccsdk/sli/adaptors.git] / saltstack-adapter / saltstack-adapter-provider / src / main / java / org / onap / ccsdk / sli / adaptors / saltstack / model / SaltstackMessageParser.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 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.model;
26
27 /**
28  * This module implements the APP-C/Saltstack Server interface
29  * based on the REST API specifications
30  */
31
32 import com.google.common.base.Strings;
33 import org.json.JSONArray;
34 import org.codehaus.jettison.json.JSONException;
35 import org.json.JSONObject;
36 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
37 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 import java.io.File;
42 import java.io.FileInputStream;
43 import java.io.FileNotFoundException;
44 import java.io.InputStream;
45 import java.util.Collections;
46 import java.util.HashSet;
47 import java.util.Iterator;
48 import java.util.Map;
49 import java.util.Properties;
50 import java.util.Set;
51 import java.util.UUID;
52
53 /**
54  * Class that validates and constructs requests sent/received from
55  * Saltstack Server
56  */
57 //TODO: This class is to be altered completely based on the SALTSTACK server communicaiton.
58 public class SaltstackMessageParser {
59
60     private static final String STATUS_MESSAGE_KEY = "StatusMessage";
61     private static final String STATUS_CODE_KEY = "StatusCode";
62
63     private static final String SALTSTATE_NAME_KEY = "SaltStateName";
64     private static final String SS_AGENT_HOSTNAME_KEY = "HostName";
65     private static final String SS_AGENT_PORT_KEY = "Port";
66     private static final String PASS_KEY = "Password";
67     private static final String USER_KEY = "User";
68     private static final String CMD_EXEC = "cmd";
69     private static final String IS_SLS_EXEC = "slsExec";
70     private static final String SS_REQ_ID = "Id";
71     private static final String SLS_FILE_LOCATION = "slsFile";
72     private static final String SLS_NAME = "slsName";
73     private static final String MINION_TO_APPLY = "applyTo";
74
75     private static final String LOCAL_PARAMETERS_OPT_KEY = "LocalParameters";
76     private static final String FILE_PARAMETERS_OPT_KEY = "FileParameters";
77     private static final String ENV_PARAMETERS_OPT_KEY = "EnvParameters";
78     private static final String NODE_LIST_OPT_KEY = "NodeList";
79     private static final String TIMEOUT_OPT_KEY = "Timeout";
80     private static final String VERSION_OPT_KEY = "Version";
81     private static final String ACTION_OPT_KEY = "Action";
82
83     private static final Logger LOGGER = LoggerFactory.getLogger(SaltstackMessageParser.class);
84
85     /**
86      * Accepts a map of strings and
87      * a) validates if all parameters are appropriate (else, throws an exception) and
88      * b) if correct returns a JSON object with appropriate key-value pairs to send to the server.
89      * <p>
90      * Mandatory parameters, that must be in the supplied information to the Saltstack Adapter
91      * 1. URL to connect to
92      * 2. credentials for URL (assume username password for now)
93      * 3. SaltState name
94      */
95     public JSONObject reqMessage(Map<String, String> params) throws SvcLogicException {
96         final String[] mandatoryTestParams = {SS_AGENT_HOSTNAME_KEY, SALTSTATE_NAME_KEY, USER_KEY, PASS_KEY};
97         final String[] optionalTestParams = {ENV_PARAMETERS_OPT_KEY, NODE_LIST_OPT_KEY, LOCAL_PARAMETERS_OPT_KEY,
98                 TIMEOUT_OPT_KEY, VERSION_OPT_KEY, FILE_PARAMETERS_OPT_KEY, ACTION_OPT_KEY};
99
100         JSONObject jsonPayload = new JSONObject();
101
102         for (String key : mandatoryTestParams) {
103             throwIfMissingMandatoryParam(params, key);
104             jsonPayload.put(key, params.get(key));
105         }
106
107         parseOptionalParams(params, optionalTestParams, jsonPayload);
108
109         // Generate a unique uuid for the test
110         String reqId = UUID.randomUUID().toString();
111         jsonPayload.put(SS_AGENT_HOSTNAME_KEY, reqId);
112
113         return jsonPayload;
114     }
115
116     /**
117      * Method that validates that the Map has enough information
118      * to query Saltstack server for a result. If so, it returns
119      * the appropriate PORT number.
120      */
121     public String reqPortResult(Map<String, String> params) throws SvcLogicException {
122
123         final String[] mandatoryTestParams = {SS_AGENT_HOSTNAME_KEY, SS_AGENT_PORT_KEY, USER_KEY,
124                 PASS_KEY};
125
126         for (String key : mandatoryTestParams) {
127             throwIfMissingMandatoryParam(params, key);
128         }
129         return params.get(SS_AGENT_PORT_KEY);
130     }
131
132     /**
133      * Method that validates that the Map has enough information
134      * to query Saltstack server for a result. If so, it returns
135      * the appropriate HOST name.
136      */
137     public String reqHostNameResult(Map<String, String> params) throws SvcLogicException {
138
139         final String[] mandatoryTestParams = {SS_AGENT_HOSTNAME_KEY, SS_AGENT_PORT_KEY, USER_KEY,
140                 PASS_KEY};
141
142         for (String key : mandatoryTestParams) {
143             throwIfMissingMandatoryParam(params, key);
144         }
145         return params.get(SS_AGENT_HOSTNAME_KEY);
146     }
147
148     /**
149      * Method that validates that the Map has enough information
150      * to query Saltstack server for a result. If so, it returns
151      * the appropriate request ID.
152      */
153     public String reqId(Map<String, String> params) {
154
155         if (params.get(SaltstackMessageParser.SS_REQ_ID) == null) {
156             return UUID.randomUUID().toString();
157         } else if (params.get(SaltstackMessageParser.SS_REQ_ID).equalsIgnoreCase("")) {
158             return UUID.randomUUID().toString();
159         }
160         return params.get(SaltstackMessageParser.SS_REQ_ID);
161     }
162
163     /**
164      * Method that validates that the Map has enough information
165      * to query Saltstack server for a result. If so, it returns
166      * the appropriate command to execute.
167      */
168     public String reqCmd(Map<String, String> params) throws SvcLogicException {
169
170         final String[] mandatoryTestParams = {CMD_EXEC, IS_SLS_EXEC};
171
172         for (String key : mandatoryTestParams) {
173             throwIfMissingMandatoryParam(params, key);
174         }
175
176         return params.get(SaltstackMessageParser.CMD_EXEC);
177     }
178
179     /**
180      * Method that validates that the Map has enough information
181      * to query Saltstack server for a result. If so, it returns
182      * the appropriate SLS file location to execute.
183      */
184     public String reqSlsFile(Map<String, String> params) throws SvcLogicException {
185
186         final String[] mandatoryTestParams = {SLS_FILE_LOCATION};
187
188         for (String key : mandatoryTestParams) {
189             throwIfMissingMandatoryParam(params, key);
190         }
191
192         return params.get(SaltstackMessageParser.SLS_FILE_LOCATION);
193     }
194
195     /**
196      * Method that validates that the Map has enough information
197      * to query Saltstack server for a result. If so, it returns
198      * the appropriate SLS file location to execute.
199      */
200     public String reqSlsName(Map<String, String> params) throws SvcLogicException {
201
202         final String[] mandatoryTestParams = {SLS_NAME};
203
204         for (String key : mandatoryTestParams) {
205             throwIfMissingMandatoryParam(params, key);
206         }
207         String slsName = params.get(SaltstackMessageParser.SLS_NAME);
208         if(slsName.substring(slsName.lastIndexOf("."), slsName.length()).equalsIgnoreCase(".sls"))
209             return stripExtension(slsName);
210         return slsName;
211     }
212
213     private String stripExtension (String str) {
214         if (str == null) return null;
215         int pos = str.lastIndexOf(".");
216         if (pos == -1) return str;
217         return str.substring(0, pos);
218     }
219
220     /**
221      * Method that validates that the Map has enough information
222      * to query Saltstack server for a result. If so, it returns
223      * the appropriate minions/vnfc to execute the SLS file to.
224      */
225     public String reqApplyToDevices(Map<String, String> params) {
226
227         if (params.get(SaltstackMessageParser.MINION_TO_APPLY) == null) {
228             return "*";
229         } else if (params.get(SaltstackMessageParser.MINION_TO_APPLY).equalsIgnoreCase("")) {
230             return "*";
231         }
232         return params.get(SaltstackMessageParser.MINION_TO_APPLY);
233     }
234
235     /**
236      * Method that validates that the Map has enough information
237      * to query Saltstack server for a result. If so, it returns
238      * the appropriate IsSLSExec true or false.
239      */
240     public boolean reqIsSLSExec(Map<String, String> params) throws SvcLogicException {
241
242         final String[] mandatoryTestParams = {CMD_EXEC, IS_SLS_EXEC};
243
244         for (String key : mandatoryTestParams) {
245             throwIfMissingMandatoryParam(params, key);
246         }
247
248         return params.get(SaltstackMessageParser.IS_SLS_EXEC).equalsIgnoreCase("true");
249     }
250
251     /**
252      * Method that validates that the Map has enough information
253      * to query Saltstack server for a result. If so, it returns
254      * the appropriate Saltstack server login user name.
255      */
256     public String reqUserNameResult(Map<String, String> params) throws SvcLogicException {
257
258         final String[] mandatoryTestParams = {SS_AGENT_HOSTNAME_KEY, SS_AGENT_PORT_KEY, USER_KEY,
259                 PASS_KEY};
260
261         for (String key : mandatoryTestParams) {
262             throwIfMissingMandatoryParam(params, key);
263         }
264         return params.get(USER_KEY);
265     }
266
267     /**
268      * Method that validates that the Map has enough information
269      * to query Saltstack server for a result. If so, it returns
270      * the appropriate Saltstack server login password.
271      */
272     public String reqPasswordResult(Map<String, String> params) throws SvcLogicException {
273
274         final String[] mandatoryTestParams = {SS_AGENT_HOSTNAME_KEY, SS_AGENT_PORT_KEY, USER_KEY,
275                 PASS_KEY};
276
277         for (String key : mandatoryTestParams) {
278             throwIfMissingMandatoryParam(params, key);
279         }
280         return params.get(PASS_KEY);
281     }
282
283     /**
284      * This method parses response from the Saltstack Server when we do a post
285      * and returns an SaltstackResult object.
286      */
287     public SaltstackResult parseResponse(SvcLogicContext ctx, String pfx,
288                                          SaltstackResult saltstackResult, boolean slsExec) {
289         int code = saltstackResult.getStatusCode();
290         boolean executionStatus = true, retCodeFound = false;
291         if (code != SaltstackResultCodes.SUCCESS.getValue()) {
292             return saltstackResult;
293         }
294         try {
295             File file = new File(saltstackResult.getOutputFileName());
296             InputStream in = new FileInputStream(file);
297             byte[] data = new byte[(int) file.length()];
298             in.read(data);
299             String str = new String(data, "UTF-8");
300             in.close();
301             Map<String, String> mm = JsonParser.convertToProperties(str);
302             if (mm != null) {
303                 for (Map.Entry<String, String> entry : mm.entrySet()) {
304                     if (entry.getKey().contains("retcode")) {
305                         retCodeFound = true;
306                         if (!entry.getValue().equalsIgnoreCase("0")) {
307                             executionStatus = false;
308                         }
309                     }
310                     ctx.setAttribute(pfx + "." + entry.getKey(), entry.getValue());
311                     LOGGER.info("+++ " + pfx + "." + entry.getKey() + ": [" + entry.getValue() + "]");
312                 }
313             }
314         } catch (FileNotFoundException e) {
315             return new SaltstackResult(SaltstackResultCodes.INVALID_RESPONSE_FILE.getValue(), "error parsing response file "
316                     + saltstackResult.getOutputFileName() + " : " + e.getMessage());
317         } catch (JSONException e) {
318             LOGGER.info("Output not in JSON format");
319             return putToProperties(ctx, pfx, saltstackResult);
320         } catch (Exception e) {
321             return new SaltstackResult(SaltstackResultCodes.INVALID_RESPONSE_FILE.getValue(), "error parsing response file "
322                     + saltstackResult.getOutputFileName() + " : " + e.getMessage());
323         }
324         if (slsExec) {
325             if (!retCodeFound)
326                 return new SaltstackResult(SaltstackResultCodes.COMMAND_EXEC_FAILED_STATUS.getValue(),
327                                            "error in parsing response Json after SLS file execution in server");
328             if (!executionStatus)
329                 return new SaltstackResult(SaltstackResultCodes.COMMAND_EXEC_FAILED_STATUS.getValue(),
330                                            "error in parsing response Json after SLS file execution in server");
331         }
332         saltstackResult.setStatusCode(SaltstackResultCodes.FINAL_SUCCESS.getValue());
333         return saltstackResult;
334     }
335
336     public SaltstackResult putToProperties(SvcLogicContext ctx, String pfx, SaltstackResult saltstackResult) {
337         try {
338             File file = new File(saltstackResult.getOutputFileName());
339             InputStream in = new FileInputStream(file);
340             Properties prop = new Properties();
341             prop.load(in);
342             ctx.setAttribute(pfx + "completeResult", prop.toString());
343             for (Object key : prop.keySet()) {
344                 String name = (String) key;
345                 String value = prop.getProperty(name);
346                 if (value != null && value.trim().length() > 0) {
347                     ctx.setAttribute(pfx + name, value.trim());
348                     LOGGER.info("+++ " + pfx + name + ": [" + value + "]");
349                 }
350             }
351         } catch (Exception e) {
352             saltstackResult = new SaltstackResult(SaltstackResultCodes.INVALID_RESPONSE_FILE.getValue(), "Error parsing response file = "
353                     + saltstackResult.getOutputFileName() + ". Error = " + e.getMessage());
354         }
355         saltstackResult.setStatusCode(SaltstackResultCodes.FINAL_SUCCESS.getValue());
356         return saltstackResult;
357     }
358
359     /**
360      * This method parses response from an Saltstack server when we do a GET for a result
361      * and returns an SaltstackResult object.
362      **/
363     public SaltstackResult parseGetResponse(String input) throws SvcLogicException {
364
365         SaltstackResult saltstackResult = new SaltstackResult();
366
367         try {
368             JSONObject postResponse = new JSONObject(input);
369             saltstackResult = parseGetResponseNested(saltstackResult, postResponse);
370         } catch (Exception e) {
371             saltstackResult = new SaltstackResult(SaltstackResultCodes.INVALID_COMMAND.getValue(),
372                                                   "Error parsing response = " + input + ". Error = " + e.getMessage(), "", -1);
373         }
374         return saltstackResult;
375     }
376
377     private SaltstackResult parseGetResponseNested(SaltstackResult saltstackResult, JSONObject postRsp) throws SvcLogicException {
378
379         int codeStatus = postRsp.getInt(STATUS_CODE_KEY);
380         String messageStatus = postRsp.getString(STATUS_MESSAGE_KEY);
381         int finalCode = SaltstackResultCodes.FINAL_SUCCESS.getValue();
382
383         boolean valCode =
384                 SaltstackResultCodes.CODE.checkValidCode(SaltstackResultCodes.FINALRESPONSE.getValue(), codeStatus);
385
386         if (!valCode) {
387             throw new SvcLogicException("Invalid FinalResponse code  = " + codeStatus + " received. MUST be one of "
388                                                 + SaltstackResultCodes.CODE.getValidCodes(SaltstackResultCodes.FINALRESPONSE.getValue()));
389         }
390
391         saltstackResult.setStatusCode(codeStatus);
392         saltstackResult.setStatusMessage(messageStatus);
393         LOGGER.info("Received response with code = {}, Message = {}", codeStatus, messageStatus);
394
395         if (!postRsp.isNull("Results")) {
396
397             // Results are available. process them
398             // Results is a dictionary of the form
399             // {host :{status:s, group:g, message:m, hostname:h}, ...}
400             LOGGER.info("Processing results in response");
401             JSONObject results = postRsp.getJSONObject("Results");
402             LOGGER.info("Get JSON dictionary from Results ..");
403             Iterator<String> hosts = results.keys();
404             LOGGER.info("Iterating through hosts");
405
406             while (hosts.hasNext()) {
407                 String host = hosts.next();
408                 LOGGER.info("Processing host = {}", host);
409
410                 try {
411                     JSONObject hostResponse = results.getJSONObject(host);
412                     int subCode = hostResponse.getInt(STATUS_CODE_KEY);
413                     String message = hostResponse.getString(STATUS_MESSAGE_KEY);
414
415                     LOGGER.info("Code = {}, Message = {}", subCode, message);
416
417                     if (subCode != 200 || !message.equals("SUCCESS")) {
418                         finalCode = SaltstackResultCodes.REQ_FAILURE.getValue();
419                     }
420                 } catch (Exception e) {
421                     saltstackResult.setStatusCode(SaltstackResultCodes.INVALID_RESPONSE.getValue());
422                     saltstackResult.setStatusMessage(String.format(
423                             "Error processing response message = %s from host %s", results.getString(host), host));
424                     break;
425                 }
426             }
427
428             saltstackResult.setStatusCode(finalCode);
429
430             // We return entire Results object as message
431             saltstackResult.setResults(results.toString());
432
433         } else {
434             saltstackResult.setStatusCode(SaltstackResultCodes.INVALID_RESPONSE.getValue());
435             saltstackResult.setStatusMessage("Results not found in GET for response");
436         }
437         return saltstackResult;
438     }
439
440     private void parseOptionalParams(Map<String, String> params, String[] optionalTestParams, JSONObject jsonPayload) {
441
442         Set<String> optionalParamsSet = new HashSet<>();
443         Collections.addAll(optionalParamsSet, optionalTestParams);
444
445         //@formatter:off
446         params.entrySet()
447                 .stream()
448                 .filter(entry -> optionalParamsSet.contains(entry.getKey()))
449                 .filter(entry -> !Strings.isNullOrEmpty(entry.getValue()))
450                 .forEach(entry -> parseOptionalParam(entry, jsonPayload));
451         //@formatter:on
452     }
453
454     private void parseOptionalParam(Map.Entry<String, String> params, JSONObject jsonPayload) {
455         String key = params.getKey();
456         String payload = params.getValue();
457
458         switch (key) {
459             case TIMEOUT_OPT_KEY:
460                 int timeout = Integer.parseInt(payload);
461                 if (timeout < 0) {
462                     throw new NumberFormatException(" : specified negative integer for timeout = " + payload);
463                 }
464                 jsonPayload.put(key, payload);
465                 break;
466
467             case VERSION_OPT_KEY:
468                 jsonPayload.put(key, payload);
469                 break;
470
471             case LOCAL_PARAMETERS_OPT_KEY:
472             case ENV_PARAMETERS_OPT_KEY:
473                 JSONObject paramsJson = new JSONObject(payload);
474                 jsonPayload.put(key, paramsJson);
475                 break;
476
477             case NODE_LIST_OPT_KEY:
478                 JSONArray paramsArray = new JSONArray(payload);
479                 jsonPayload.put(key, paramsArray);
480                 break;
481
482             case FILE_PARAMETERS_OPT_KEY:
483                 jsonPayload.put(key, getFilePayload(payload));
484                 break;
485
486             default:
487                 break;
488         }
489     }
490
491     /**
492      * Return payload with escaped newlines
493      */
494     private JSONObject getFilePayload(String payload) {
495         String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r");
496         return new JSONObject(formattedPayload);
497     }
498
499     private void throwIfMissingMandatoryParam(Map<String, String> params, String key) throws SvcLogicException {
500         if (!params.containsKey(key)) {
501             throw new SvcLogicException(String.format(
502                     "Saltstack: Mandatory SaltstackAdapter key %s not found in parameters provided by calling agent !",
503                     key));
504         }
505         if (Strings.isNullOrEmpty(params.get(key))) {
506             throw new SvcLogicException(String.format(
507                     "Saltstack: Mandatory SaltstackAdapter key %s not found in parameters provided by calling agent !",
508                     key));
509         }
510     }
511 }