2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.onap.ccsdk.sli.adaptors.saltstack.model;
28 * This module implements the APP-C/Saltstack Server interface
29 * based on the REST API specifications
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;
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;
49 import java.util.Properties;
51 import java.util.UUID;
54 * Class that validates and constructs requests sent/received from
57 //TODO: This class is to be altered completely based on the SALTSTACK server communicaiton.
58 public class SaltstackMessageParser {
60 private static final String STATUS_MESSAGE_KEY = "StatusMessage";
61 private static final String STATUS_CODE_KEY = "StatusCode";
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";
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";
83 private static final Logger LOGGER = LoggerFactory.getLogger(SaltstackMessageParser.class);
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.
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)
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};
100 JSONObject jsonPayload = new JSONObject();
102 for (String key : mandatoryTestParams) {
103 throwIfMissingMandatoryParam(params, key);
104 jsonPayload.put(key, params.get(key));
107 parseOptionalParams(params, optionalTestParams, jsonPayload);
109 // Generate a unique uuid for the test
110 String reqId = UUID.randomUUID().toString();
111 jsonPayload.put(SS_AGENT_HOSTNAME_KEY, reqId);
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.
121 public String reqPortResult(Map<String, String> params) throws SvcLogicException {
123 final String[] mandatoryTestParams = {SS_AGENT_HOSTNAME_KEY, SS_AGENT_PORT_KEY, USER_KEY,
126 for (String key : mandatoryTestParams) {
127 throwIfMissingMandatoryParam(params, key);
129 return params.get(SS_AGENT_PORT_KEY);
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.
137 public String reqHostNameResult(Map<String, String> params) throws SvcLogicException {
139 final String[] mandatoryTestParams = {SS_AGENT_HOSTNAME_KEY, SS_AGENT_PORT_KEY, USER_KEY,
142 for (String key : mandatoryTestParams) {
143 throwIfMissingMandatoryParam(params, key);
145 return params.get(SS_AGENT_HOSTNAME_KEY);
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.
153 public String reqId(Map<String, String> params) {
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();
160 return params.get(SaltstackMessageParser.SS_REQ_ID);
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.
168 public String reqCmd(Map<String, String> params) throws SvcLogicException {
170 final String[] mandatoryTestParams = {CMD_EXEC, IS_SLS_EXEC};
172 for (String key : mandatoryTestParams) {
173 throwIfMissingMandatoryParam(params, key);
176 return params.get(SaltstackMessageParser.CMD_EXEC);
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.
184 public String reqSlsFile(Map<String, String> params) throws SvcLogicException {
186 final String[] mandatoryTestParams = {SLS_FILE_LOCATION};
188 for (String key : mandatoryTestParams) {
189 throwIfMissingMandatoryParam(params, key);
192 return params.get(SaltstackMessageParser.SLS_FILE_LOCATION);
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.
200 public String reqSlsName(Map<String, String> params) throws SvcLogicException {
202 final String[] mandatoryTestParams = {SLS_NAME};
204 for (String key : mandatoryTestParams) {
205 throwIfMissingMandatoryParam(params, key);
207 String slsName = params.get(SaltstackMessageParser.SLS_NAME);
208 if(slsName.substring(slsName.lastIndexOf("."), slsName.length()).equalsIgnoreCase(".sls"))
209 return stripExtension(slsName);
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);
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.
225 public String reqApplyToDevices(Map<String, String> params) {
227 if (params.get(SaltstackMessageParser.MINION_TO_APPLY) == null) {
229 } else if (params.get(SaltstackMessageParser.MINION_TO_APPLY).equalsIgnoreCase("")) {
232 return params.get(SaltstackMessageParser.MINION_TO_APPLY);
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.
240 public boolean reqIsSLSExec(Map<String, String> params) throws SvcLogicException {
242 final String[] mandatoryTestParams = {CMD_EXEC, IS_SLS_EXEC};
244 for (String key : mandatoryTestParams) {
245 throwIfMissingMandatoryParam(params, key);
248 return params.get(SaltstackMessageParser.IS_SLS_EXEC).equalsIgnoreCase("true");
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.
256 public String reqUserNameResult(Map<String, String> params) throws SvcLogicException {
258 final String[] mandatoryTestParams = {SS_AGENT_HOSTNAME_KEY, SS_AGENT_PORT_KEY, USER_KEY,
261 for (String key : mandatoryTestParams) {
262 throwIfMissingMandatoryParam(params, key);
264 return params.get(USER_KEY);
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.
272 public String reqPasswordResult(Map<String, String> params) throws SvcLogicException {
274 final String[] mandatoryTestParams = {SS_AGENT_HOSTNAME_KEY, SS_AGENT_PORT_KEY, USER_KEY,
277 for (String key : mandatoryTestParams) {
278 throwIfMissingMandatoryParam(params, key);
280 return params.get(PASS_KEY);
284 * This method parses response from the Saltstack Server when we do a post
285 * and returns an SaltstackResult object.
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;
295 File file = new File(saltstackResult.getOutputFileName());
296 InputStream in = new FileInputStream(file);
297 byte[] data = new byte[(int) file.length()];
299 String str = new String(data, "UTF-8");
301 Map<String, String> mm = JsonParser.convertToProperties(str);
303 for (Map.Entry<String, String> entry : mm.entrySet()) {
304 if (entry.getKey().contains("retcode")) {
306 if (!entry.getValue().equalsIgnoreCase("0")) {
307 executionStatus = false;
310 ctx.setAttribute(pfx + "." + entry.getKey(), entry.getValue());
311 LOGGER.info("+++ " + pfx + "." + entry.getKey() + ": [" + entry.getValue() + "]");
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());
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");
332 saltstackResult.setStatusCode(SaltstackResultCodes.FINAL_SUCCESS.getValue());
333 return saltstackResult;
336 public SaltstackResult putToProperties(SvcLogicContext ctx, String pfx, SaltstackResult saltstackResult) {
338 File file = new File(saltstackResult.getOutputFileName());
339 InputStream in = new FileInputStream(file);
340 Properties prop = new Properties();
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 + "]");
351 } catch (Exception e) {
352 saltstackResult = new SaltstackResult(SaltstackResultCodes.INVALID_RESPONSE_FILE.getValue(), "Error parsing response file = "
353 + saltstackResult.getOutputFileName() + ". Error = " + e.getMessage());
355 saltstackResult.setStatusCode(SaltstackResultCodes.FINAL_SUCCESS.getValue());
356 return saltstackResult;
360 * This method parses response from an Saltstack server when we do a GET for a result
361 * and returns an SaltstackResult object.
363 public SaltstackResult parseGetResponse(String input) throws SvcLogicException {
365 SaltstackResult saltstackResult = new SaltstackResult();
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);
374 return saltstackResult;
377 private SaltstackResult parseGetResponseNested(SaltstackResult saltstackResult, JSONObject postRsp) throws SvcLogicException {
379 int codeStatus = postRsp.getInt(STATUS_CODE_KEY);
380 String messageStatus = postRsp.getString(STATUS_MESSAGE_KEY);
381 int finalCode = SaltstackResultCodes.FINAL_SUCCESS.getValue();
384 SaltstackResultCodes.CODE.checkValidCode(SaltstackResultCodes.FINALRESPONSE.getValue(), codeStatus);
387 throw new SvcLogicException("Invalid FinalResponse code = " + codeStatus + " received. MUST be one of "
388 + SaltstackResultCodes.CODE.getValidCodes(SaltstackResultCodes.FINALRESPONSE.getValue()));
391 saltstackResult.setStatusCode(codeStatus);
392 saltstackResult.setStatusMessage(messageStatus);
393 LOGGER.info("Received response with code = {}, Message = {}", codeStatus, messageStatus);
395 if (!postRsp.isNull("Results")) {
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");
406 while (hosts.hasNext()) {
407 String host = hosts.next();
408 LOGGER.info("Processing host = {}", host);
411 JSONObject hostResponse = results.getJSONObject(host);
412 int subCode = hostResponse.getInt(STATUS_CODE_KEY);
413 String message = hostResponse.getString(STATUS_MESSAGE_KEY);
415 LOGGER.info("Code = {}, Message = {}", subCode, message);
417 if (subCode != 200 || !message.equals("SUCCESS")) {
418 finalCode = SaltstackResultCodes.REQ_FAILURE.getValue();
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));
428 saltstackResult.setStatusCode(finalCode);
430 // We return entire Results object as message
431 saltstackResult.setResults(results.toString());
434 saltstackResult.setStatusCode(SaltstackResultCodes.INVALID_RESPONSE.getValue());
435 saltstackResult.setStatusMessage("Results not found in GET for response");
437 return saltstackResult;
440 private void parseOptionalParams(Map<String, String> params, String[] optionalTestParams, JSONObject jsonPayload) {
442 Set<String> optionalParamsSet = new HashSet<>();
443 Collections.addAll(optionalParamsSet, optionalTestParams);
448 .filter(entry -> optionalParamsSet.contains(entry.getKey()))
449 .filter(entry -> !Strings.isNullOrEmpty(entry.getValue()))
450 .forEach(entry -> parseOptionalParam(entry, jsonPayload));
454 private void parseOptionalParam(Map.Entry<String, String> params, JSONObject jsonPayload) {
455 String key = params.getKey();
456 String payload = params.getValue();
459 case TIMEOUT_OPT_KEY:
460 int timeout = Integer.parseInt(payload);
462 throw new NumberFormatException(" : specified negative integer for timeout = " + payload);
464 jsonPayload.put(key, payload);
467 case VERSION_OPT_KEY:
468 jsonPayload.put(key, payload);
471 case LOCAL_PARAMETERS_OPT_KEY:
472 case ENV_PARAMETERS_OPT_KEY:
473 JSONObject paramsJson = new JSONObject(payload);
474 jsonPayload.put(key, paramsJson);
477 case NODE_LIST_OPT_KEY:
478 JSONArray paramsArray = new JSONArray(payload);
479 jsonPayload.put(key, paramsArray);
482 case FILE_PARAMETERS_OPT_KEY:
483 jsonPayload.put(key, getFilePayload(payload));
492 * Return payload with escaped newlines
494 private JSONObject getFilePayload(String payload) {
495 String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r");
496 return new JSONObject(formattedPayload);
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 !",
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 !",