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.appc.adapter.ansible.model;
28 * This module implements the APP-C/Ansible Server interface
29 * based on the REST API specifications
31 import java.util.Collections;
32 import java.util.HashSet;
33 import java.util.Iterator;
36 import java.util.UUID;
37 import org.json.JSONArray;
38 import org.json.JSONException;
39 import org.json.JSONObject;
40 import org.onap.appc.exceptions.APPCException;
41 import com.google.common.base.Strings;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * Class that validates and constructs requests sent/received from
49 public class AnsibleMessageParser {
51 private static final String STATUS_MESSAGE_KEY = "StatusMessage";
52 private static final String STATUS_CODE_KEY = "StatusCode";
54 private static final String PLAYBOOK_NAME_KEY = "PlaybookName";
55 private static final String AGENT_URL_KEY = "AgentUrl";
56 private static final String PASS_KEY = "Password";
57 private static final String USER_KEY = "User";
58 private static final String ID_KEY = "Id";
60 private static final String LOCAL_PARAMETERS_OPT_KEY = "LocalParameters";
61 private static final String FILE_PARAMETERS_OPT_KEY = "FileParameters";
62 private static final String ENV_PARAMETERS_OPT_KEY = "EnvParameters";
63 private static final String NODE_LIST_OPT_KEY = "NodeList";
64 private static final String TIMEOUT_OPT_KEY = "Timeout";
65 private static final String VERSION_OPT_KEY = "Version";
66 private static final String ACTION_OPT_KEY = "Action";
68 private static final Logger LOGGER = LoggerFactory.getLogger(AnsibleMessageParser.class);
71 * Accepts a map of strings and
72 * a) validates if all parameters are appropriate (else, throws an exception) and
73 * b) if correct returns a JSON object with appropriate key-value pairs to send to the server.
75 * Mandatory parameters, that must be in the supplied information to the Ansible Adapter
76 * 1. URL to connect to
77 * 2. credentials for URL (assume username password for now)
81 public JSONObject reqMessage(Map<String, String> params) throws APPCException {
82 final String[] mandatoryTestParams = {AGENT_URL_KEY, PLAYBOOK_NAME_KEY, USER_KEY, PASS_KEY};
83 final String[] optionalTestParams = {ENV_PARAMETERS_OPT_KEY, NODE_LIST_OPT_KEY, LOCAL_PARAMETERS_OPT_KEY,
84 TIMEOUT_OPT_KEY, VERSION_OPT_KEY, FILE_PARAMETERS_OPT_KEY, ACTION_OPT_KEY};
86 JSONObject jsonPayload = new JSONObject();
88 for (String key : mandatoryTestParams) {
89 throwIfMissingMandatoryParam(params, key);
90 jsonPayload.put(key, params.get(key));
93 parseOptionalParams(params, optionalTestParams, jsonPayload);
95 // Generate a unique uuid for the test
96 String reqId = UUID.randomUUID().toString();
97 jsonPayload.put(ID_KEY, reqId);
103 * Method that validates that the Map has enough information
104 * to query Ansible server for a result. If so, it returns
105 * the appropriate url, else an empty string.
107 public String reqUriResult(Map<String, String> params) throws APPCException {
109 final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY};
111 for (String key : mandatoryTestParams) {
112 throwIfMissingMandatoryParam(params, key);
114 return params.get(AGENT_URL_KEY) + "?Id=" + params.get(ID_KEY) + "&Type=GetResult";
118 * Method that validates that the Map has enough information
119 * to query Ansible server for logs. If so, it populates the appropriate
120 * returns the appropriate url, else an empty string.
122 public String reqUriLog(Map<String, String> params) throws APPCException {
124 final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY};
126 for (String mandatoryParam : mandatoryTestParams) {
127 throwIfMissingMandatoryParam(params, mandatoryParam);
129 return params.get(AGENT_URL_KEY) + "?Id=" + params.get(ID_KEY) + "&Type=GetLog";
133 * This method parses response from the Ansible Server when we do a post
134 * and returns an AnsibleResult object.
136 public AnsibleResult parsePostResponse(String input) throws APPCException {
137 AnsibleResult ansibleResult;
139 JSONObject postResponse = new JSONObject(input);
141 int code = postResponse.getInt(STATUS_CODE_KEY);
142 String msg = postResponse.getString(STATUS_MESSAGE_KEY);
144 int initResponseValue = AnsibleResultCodes.INITRESPONSE.getValue();
145 boolean validCode = AnsibleResultCodes.CODE.checkValidCode(initResponseValue, code);
147 throw new APPCException("Invalid InitResponse code = " + code + " received. MUST be one of "
148 + AnsibleResultCodes.CODE.getValidCodes(initResponseValue));
151 ansibleResult = new AnsibleResult(code, msg);
153 } catch (JSONException e) {
154 ansibleResult = new AnsibleResult(600, "Error parsing response = " + input + ". Error = " + e.getMessage());
156 return ansibleResult;
160 * This method parses response from an Ansible server when we do a GET for a result
161 * and returns an AnsibleResult object.
163 public AnsibleResult parseGetResponse(String input) throws APPCException {
165 AnsibleResult ansibleResult = new AnsibleResult();
168 JSONObject postResponse = new JSONObject(input);
169 ansibleResult = parseGetResponseNested(ansibleResult, postResponse);
170 } catch (JSONException e) {
171 ansibleResult = new AnsibleResult(AnsibleResultCodes.INVALID_PAYLOAD.getValue(),
172 "Error parsing response = " + input + ". Error = " + e.getMessage(), "");
174 return ansibleResult;
177 private AnsibleResult parseGetResponseNested(AnsibleResult ansibleResult, JSONObject postRsp) throws APPCException {
179 int codeStatus = postRsp.getInt(STATUS_CODE_KEY);
180 String messageStatus = postRsp.getString(STATUS_MESSAGE_KEY);
181 int finalCode = AnsibleResultCodes.FINAL_SUCCESS.getValue();
184 AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.FINALRESPONSE.getValue(), codeStatus);
187 throw new APPCException("Invalid FinalResponse code = " + codeStatus + " received. MUST be one of "
188 + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.FINALRESPONSE.getValue()));
191 ansibleResult.setStatusCode(codeStatus);
192 ansibleResult.setStatusMessage(messageStatus);
193 LOGGER.info("Received response with code = {}, Message = {}", codeStatus, messageStatus);
195 if (!postRsp.isNull("Results")) {
197 // Results are available. process them
198 // Results is a dictionary of the form
199 // {host :{status:s, group:g, message:m, hostname:h}, ...}
200 LOGGER.info("Processing results in response");
201 JSONObject results = postRsp.getJSONObject("Results");
202 LOGGER.info("Get JSON dictionary from Results ..");
203 Iterator<String> hosts = results.keys();
204 LOGGER.info("Iterating through hosts");
206 while (hosts.hasNext()) {
207 String host = hosts.next();
208 LOGGER.info("Processing host = {}", host);
211 JSONObject hostResponse = results.getJSONObject(host);
212 int subCode = hostResponse.getInt(STATUS_CODE_KEY);
213 String message = hostResponse.getString(STATUS_MESSAGE_KEY);
215 LOGGER.info("Code = {}, Message = {}", subCode, message);
217 if (subCode != 200 || !message.equals("SUCCESS")) {
218 finalCode = AnsibleResultCodes.REQ_FAILURE.getValue();
220 } catch (JSONException e) {
221 ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue());
222 ansibleResult.setStatusMessage(String.format(
223 "Error processing response message = %s from host %s", results.getString(host), host));
228 ansibleResult.setStatusCode(finalCode);
230 // We return entire Results object as message
231 ansibleResult.setResults(results.toString());
234 ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue());
235 ansibleResult.setStatusMessage("Results not found in GET for response");
237 return ansibleResult;
240 private void parseOptionalParams(Map<String, String> params, String[] optionalTestParams, JSONObject jsonPayload) {
242 Set<String> optionalParamsSet = new HashSet<>();
243 Collections.addAll(optionalParamsSet, optionalTestParams);
248 .filter(entry -> optionalParamsSet.contains(entry.getKey()))
249 .filter(entry -> !Strings.isNullOrEmpty(entry.getValue()))
250 .forEach(entry -> parseOptionalParam(entry, jsonPayload));
254 private void parseOptionalParam(Map.Entry<String, String> params, JSONObject jsonPayload) {
255 String key = params.getKey();
256 String payload = params.getValue();
259 case TIMEOUT_OPT_KEY:
260 int timeout = Integer.parseInt(payload);
262 throw new NumberFormatException(" : specified negative integer for timeout = " + payload);
264 jsonPayload.put(key, payload);
267 case VERSION_OPT_KEY:
268 jsonPayload.put(key, payload);
271 case LOCAL_PARAMETERS_OPT_KEY:
272 case ENV_PARAMETERS_OPT_KEY:
273 JSONObject paramsJson = new JSONObject(payload);
274 jsonPayload.put(key, paramsJson);
277 case NODE_LIST_OPT_KEY:
278 JSONArray paramsArray = new JSONArray(payload);
279 jsonPayload.put(key, paramsArray);
282 case FILE_PARAMETERS_OPT_KEY:
283 jsonPayload.put(key, getFilePayload(payload));
292 * Return payload with escaped newlines
294 private JSONObject getFilePayload(String payload) {
295 String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r");
296 return new JSONObject(formattedPayload);
299 private void throwIfMissingMandatoryParam(Map<String, String> params, String key) throws APPCException {
300 if (!params.containsKey(key)) {
301 throw new APPCException(String.format(
302 "Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !",
305 if (Strings.isNullOrEmpty(params.get(key))) {
306 throw new APPCException(String.format(
307 "Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !",