Unit Test for ansibleActivator
[appc.git] / appc-adapters / appc-ansible-adapter / appc-ansible-adapter-bundle / src / main / java / org / onap / appc / adapter / ansible / model / AnsibleMessageParser.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.appc.adapter.ansible.model;
26
27 /**
28  * This module implements the APP-C/Ansible Server interface
29  * based on the REST API specifications
30  */
31 import java.util.Collections;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.Map;
35 import java.util.Set;
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;
44
45 /**
46  * Class that validates and constructs requests sent/received from
47  * Ansible Server
48  */
49 public class AnsibleMessageParser {
50
51     private static final String STATUS_MESSAGE_KEY = "StatusMessage";
52     private static final String STATUS_CODE_KEY = "StatusCode";
53
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";
59
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";
67
68     private static final Logger LOGGER = LoggerFactory.getLogger(AnsibleMessageParser.class);
69
70     /**
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.
74      *
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)
78      * 3. Playbook name
79      *
80      */
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};
85
86         JSONObject jsonPayload = new JSONObject();
87
88         for (String key : mandatoryTestParams) {
89             throwIfMissingMandatoryParam(params, key);
90             jsonPayload.put(key, params.get(key));
91         }
92
93         parseOptionalParams(params, optionalTestParams, jsonPayload);
94
95         // Generate a unique uuid for the test
96         String reqId = UUID.randomUUID().toString();
97         jsonPayload.put(ID_KEY, reqId);
98
99         return jsonPayload;
100     }
101
102     /**
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.
106      */
107     public String reqUriResult(Map<String, String> params) throws APPCException {
108
109         final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY};
110
111         for (String key : mandatoryTestParams) {
112             throwIfMissingMandatoryParam(params, key);
113         }
114         return params.get(AGENT_URL_KEY) + "?Id=" + params.get(ID_KEY) + "&Type=GetResult";
115     }
116
117     /**
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.
121      */
122     public String reqUriLog(Map<String, String> params) throws APPCException {
123
124         final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY};
125
126         for (String mandatoryParam : mandatoryTestParams) {
127             throwIfMissingMandatoryParam(params, mandatoryParam);
128         }
129         return params.get(AGENT_URL_KEY) + "?Id=" + params.get(ID_KEY) + "&Type=GetLog";
130     }
131
132     /**
133      * This method parses response from the Ansible Server when we do a post
134      * and returns an AnsibleResult object.
135      */
136     public AnsibleResult parsePostResponse(String input) throws APPCException {
137         AnsibleResult ansibleResult;
138         try {
139             JSONObject postResponse = new JSONObject(input);
140
141             int code = postResponse.getInt(STATUS_CODE_KEY);
142             String msg = postResponse.getString(STATUS_MESSAGE_KEY);
143
144             int initResponseValue = AnsibleResultCodes.INITRESPONSE.getValue();
145             boolean validCode = AnsibleResultCodes.CODE.checkValidCode(initResponseValue, code);
146             if (!validCode) {
147                 throw new APPCException("Invalid InitResponse code  = " + code + " received. MUST be one of "
148                         + AnsibleResultCodes.CODE.getValidCodes(initResponseValue));
149             }
150
151             ansibleResult = new AnsibleResult(code, msg);
152
153         } catch (JSONException e) {
154             ansibleResult = new AnsibleResult(600, "Error parsing response = " + input + ". Error = " + e.getMessage());
155         }
156         return ansibleResult;
157     }
158
159     /**
160      * This method parses response from an Ansible server when we do a GET for a result
161      * and returns an AnsibleResult object.
162      **/
163     public AnsibleResult parseGetResponse(String input) throws APPCException {
164
165         AnsibleResult ansibleResult = new AnsibleResult();
166
167         try {
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(), "");
173         }
174         return ansibleResult;
175     }
176
177     private AnsibleResult parseGetResponseNested(AnsibleResult ansibleResult, JSONObject postRsp) throws APPCException  {
178
179         int codeStatus = postRsp.getInt(STATUS_CODE_KEY);
180         String messageStatus = postRsp.getString(STATUS_MESSAGE_KEY);
181         int finalCode = AnsibleResultCodes.FINAL_SUCCESS.getValue();
182
183         boolean valCode =
184                 AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.FINALRESPONSE.getValue(), codeStatus);
185
186         if (!valCode) {
187             throw new APPCException("Invalid FinalResponse code  = " + codeStatus + " received. MUST be one of "
188                     + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.FINALRESPONSE.getValue()));
189         }
190
191         ansibleResult.setStatusCode(codeStatus);
192         ansibleResult.setStatusMessage(messageStatus);
193         LOGGER.info("Received response with code = {}, Message = {}", codeStatus, messageStatus);
194
195         if (!postRsp.isNull("Results")) {
196
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");
205
206             while (hosts.hasNext()) {
207                 String host = hosts.next();
208                 LOGGER.info("Processing host = {}", host);
209
210                 try {
211                     JSONObject hostResponse = results.getJSONObject(host);
212                     int subCode = hostResponse.getInt(STATUS_CODE_KEY);
213                     String message = hostResponse.getString(STATUS_MESSAGE_KEY);
214
215                     LOGGER.info("Code = {}, Message = {}", subCode, message);
216
217                     if (subCode != 200 || !message.equals("SUCCESS")) {
218                         finalCode = AnsibleResultCodes.REQ_FAILURE.getValue();
219                     }
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));
224                     break;
225                 }
226             }
227
228             ansibleResult.setStatusCode(finalCode);
229
230             // We return entire Results object as message
231             ansibleResult.setResults(results.toString());
232
233         } else {
234             ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue());
235             ansibleResult.setStatusMessage("Results not found in GET for response");
236         }
237         return ansibleResult;
238     }
239
240     private void parseOptionalParams(Map<String, String> params, String[] optionalTestParams, JSONObject jsonPayload) {
241
242         Set<String> optionalParamsSet = new HashSet<>();
243         Collections.addAll(optionalParamsSet, optionalTestParams);
244
245         //@formatter:off
246         params.entrySet()
247             .stream()
248             .filter(entry -> optionalParamsSet.contains(entry.getKey()))
249             .filter(entry -> !Strings.isNullOrEmpty(entry.getValue()))
250              .forEach(entry -> parseOptionalParam(entry, jsonPayload));
251         //@formatter:on
252     }
253
254     private void parseOptionalParam(Map.Entry<String, String> params, JSONObject jsonPayload) {
255         String key = params.getKey();
256         String payload = params.getValue();
257
258         switch (key) {
259             case TIMEOUT_OPT_KEY:
260                 int timeout = Integer.parseInt(payload);
261                 if (timeout < 0) {
262                     throw new NumberFormatException(" : specified negative integer for timeout = " + payload);
263                 }
264                 jsonPayload.put(key, payload);
265                 break;
266
267             case VERSION_OPT_KEY:
268                 jsonPayload.put(key, payload);
269                 break;
270
271             case LOCAL_PARAMETERS_OPT_KEY:
272             case ENV_PARAMETERS_OPT_KEY:
273                 JSONObject paramsJson = new JSONObject(payload);
274                 jsonPayload.put(key, paramsJson);
275                 break;
276
277             case NODE_LIST_OPT_KEY:
278                 JSONArray paramsArray = new JSONArray(payload);
279                 jsonPayload.put(key, paramsArray);
280                 break;
281
282             case FILE_PARAMETERS_OPT_KEY:
283                 jsonPayload.put(key, getFilePayload(payload));
284                 break;
285
286             default:
287                 break;
288         }
289     }
290
291     /**
292      * Return payload with escaped newlines
293      */
294     private JSONObject getFilePayload(String payload) {
295         String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r");
296         return new JSONObject(formattedPayload);
297     }
298
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 !",
303                     key));
304         }
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 !",
308                     key));
309         }
310     }
311 }