2 * ============LICENSE_START=======================================================
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
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
120 * appropriate returns the appropriate url, else an empty string.
122 public String reqUriOutput(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=GetOutput";
133 * Method that validates that the Map has enough information
134 * to query Ansible server for logs. If so, it populates the appropriate
135 * returns the appropriate url, else an empty string.
137 public String reqUriLog(Map<String, String> params) throws APPCException {
139 final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY};
141 for (String mandatoryParam : mandatoryTestParams) {
142 throwIfMissingMandatoryParam(params, mandatoryParam);
144 return params.get(AGENT_URL_KEY) + "?Id=" + params.get(ID_KEY) + "&Type=GetLog";
148 * This method parses response from the Ansible Server when we do a post
149 * and returns an AnsibleResult object.
151 public AnsibleResult parsePostResponse(String input) throws APPCException {
152 AnsibleResult ansibleResult;
154 JSONObject postResponse = new JSONObject(input);
156 int code = postResponse.getInt(STATUS_CODE_KEY);
157 String msg = postResponse.getString(STATUS_MESSAGE_KEY);
159 int initResponseValue = AnsibleResultCodes.INITRESPONSE.getValue();
160 boolean validCode = AnsibleResultCodes.CODE.checkValidCode(initResponseValue, code);
162 throw new APPCException("Invalid InitResponse code = " + code + " received. MUST be one of "
163 + AnsibleResultCodes.CODE.getValidCodes(initResponseValue));
166 ansibleResult = new AnsibleResult(code, msg);
168 } catch (JSONException e) {
169 ansibleResult = new AnsibleResult(600, "Error parsing response = " + input + ". Error = " + e.getMessage());
171 return ansibleResult;
175 * This method parses response from an Ansible server when we do a GET for a result
176 * and returns an AnsibleResult object.
178 public AnsibleResult parseGetResponse(String input) throws APPCException {
180 AnsibleResult ansibleResult = new AnsibleResult();
181 int finalCode = AnsibleResultCodes.FINAL_SUCCESS.getValue();
184 JSONObject postResponse = new JSONObject(input);
186 int codeStatus = postResponse.getInt(STATUS_CODE_KEY);
187 String messageStatus = postResponse.getString(STATUS_MESSAGE_KEY);
190 AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.FINALRESPONSE.getValue(), codeStatus);
193 throw new APPCException("Invalid FinalResponse code = " + codeStatus + " received. MUST be one of "
194 + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.FINALRESPONSE.getValue()));
197 ansibleResult.setStatusCode(codeStatus);
198 ansibleResult.setStatusMessage(messageStatus);
199 LOGGER.info("Received response with code = {}, Message = {}", codeStatus, messageStatus);
201 if (!postResponse.isNull("Results")) {
203 // Results are available. process them
204 // Results is a dictionary of the form
205 // {host :{status:s, group:g, message:m, hostname:h}, ...}
206 LOGGER.info("Processing results in response");
207 JSONObject results = postResponse.getJSONObject("Results");
208 LOGGER.info("Get JSON dictionary from Results ..");
209 Iterator<String> hosts = results.keys();
210 LOGGER.info("Iterating through hosts");
212 while (hosts.hasNext()) {
213 String host = hosts.next();
214 LOGGER.info("Processing host = {}", host);
217 JSONObject hostResponse = results.getJSONObject(host);
218 int subCode = hostResponse.getInt(STATUS_CODE_KEY);
219 String message = hostResponse.getString(STATUS_MESSAGE_KEY);
221 LOGGER.info("Code = {}, Message = {}", subCode, message);
223 if (subCode != 200 || !message.equals("SUCCESS")) {
224 finalCode = AnsibleResultCodes.REQ_FAILURE.getValue();
226 } catch (JSONException e) {
227 ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue());
228 ansibleResult.setStatusMessage(String.format(
229 "Error processing response message = %s from host %s", results.getString(host), host));
234 ansibleResult.setStatusCode(finalCode);
236 // We return entire Results object as message
237 ansibleResult.setResults(results.toString());
240 ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue());
241 ansibleResult.setStatusMessage("Results not found in GET for response");
245 } catch (JSONException e) {
246 ansibleResult = new AnsibleResult(AnsibleResultCodes.INVALID_PAYLOAD.getValue(),
247 "Error parsing response = " + input + ". Error = " + e.getMessage(), "");
251 return ansibleResult;
254 private void parseOptionalParams(Map<String, String> params, String[] optionalTestParams, JSONObject jsonPayload) {
256 Set<String> optionalParamsSet = new HashSet<>();
257 Collections.addAll(optionalParamsSet, optionalTestParams);
262 .filter(entry -> optionalParamsSet.contains(entry.getKey()))
263 .filter(entry -> !Strings.isNullOrEmpty(entry.getValue()))
264 .forEach(entry -> parseOptionalParam(entry, jsonPayload));
268 private void parseOptionalParam(Map.Entry<String, String> params, JSONObject jsonPayload) {
269 String key = params.getKey();
270 String payload = params.getValue();
273 case TIMEOUT_OPT_KEY:
274 int timeout = Integer.parseInt(payload);
276 throw new NumberFormatException(" : specified negative integer for timeout = " + payload);
278 jsonPayload.put(key, payload);
281 case VERSION_OPT_KEY:
282 jsonPayload.put(key, payload);
285 case LOCAL_PARAMETERS_OPT_KEY:
286 case ENV_PARAMETERS_OPT_KEY:
287 JSONObject paramsJson = new JSONObject(payload);
288 jsonPayload.put(key, paramsJson);
291 case NODE_LIST_OPT_KEY:
292 JSONArray paramsArray = new JSONArray(payload);
293 jsonPayload.put(key, paramsArray);
296 case FILE_PARAMETERS_OPT_KEY:
297 jsonPayload.put(key, getFilePayload(payload));
306 * Return payload with escaped newlines
308 private JSONObject getFilePayload(String payload) {
309 String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r");
310 return new JSONObject(formattedPayload);
313 private void throwIfMissingMandatoryParam(Map<String, String> params, String key) throws APPCException {
314 if (!params.containsKey(key)) {
315 throw new APPCException(String.format(
316 "Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !",
319 if (Strings.isNullOrEmpty(params.get(key))) {
320 throw new APPCException(String.format(
321 "Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !",