6e2244ff9fd2f1f725bc2a195a36c1e13e3daaff
[ccsdk/sli/adaptors.git] /
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  * Modifications Copyright (C) 2018 IBM.
10  * ================================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
24  * ============LICENSE_END=========================================================
25  */
26
27 package org.onap.ccsdk.sli.adaptors.ansible.model;
28
29 /**
30  * This module implements the APP-C/Ansible Server interface
31  * based on the REST API specifications
32  */
33 import java.util.Collections;
34 import java.util.HashSet;
35 import java.util.Iterator;
36 import java.util.Map;
37 import java.util.Set;
38 import java.util.UUID;
39 import org.json.JSONArray;
40 import org.json.JSONException;
41 import org.json.JSONObject;
42 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
43 import com.google.common.base.Strings;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Class that validates and constructs requests sent/received from
49  * Ansible Server
50  */
51 public class AnsibleMessageParser {
52
53     private static final String STATUS_MESSAGE_KEY = "StatusMessage";
54     private static final String STATUS_CODE_KEY = "StatusCode";
55
56     private static final String PLAYBOOK_NAME_KEY = "PlaybookName";
57     private static final String AGENT_URL_KEY = "AgentUrl";
58     private static final String PASS_KEY = "Password";
59     private static final String USER_KEY = "User";
60     private static final String ID_KEY = "Id";
61
62     private static final String LOCAL_PARAMETERS_OPT_KEY = "LocalParameters";
63     private static final String FILE_PARAMETERS_OPT_KEY = "FileParameters";
64     private static final String ENV_PARAMETERS_OPT_KEY = "EnvParameters";
65     private static final String NODE_LIST_OPT_KEY = "NodeList";
66     private static final String TIMEOUT_OPT_KEY = "Timeout";
67     private static final String VERSION_OPT_KEY = "Version";
68     private static final String ACTION_OPT_KEY = "Action";
69
70     private static final Logger LOGGER = LoggerFactory.getLogger(AnsibleMessageParser.class);
71
72     /**
73      * Accepts a map of strings and
74      * a) validates if all parameters are appropriate (else, throws an exception) and
75      * b) if correct returns a JSON object with appropriate key-value pairs to send to the server.
76      *
77      * Mandatory parameters, that must be in the supplied information to the Ansible Adapter
78      * 1. URL to connect to
79      * 2. credentials for URL (assume username password for now)
80      * 3. Playbook name
81      *
82      */
83     public JSONObject reqMessage(Map<String, String> params) throws SvcLogicException {
84         final String[] mandatoryTestParams = {AGENT_URL_KEY, PLAYBOOK_NAME_KEY, USER_KEY, PASS_KEY};
85         final String[] optionalTestParams = {ENV_PARAMETERS_OPT_KEY, NODE_LIST_OPT_KEY, LOCAL_PARAMETERS_OPT_KEY,
86                 TIMEOUT_OPT_KEY, VERSION_OPT_KEY, FILE_PARAMETERS_OPT_KEY, ACTION_OPT_KEY};
87
88         JSONObject jsonPayload = new JSONObject();
89
90         for (String key : mandatoryTestParams) {
91             throwIfMissingMandatoryParam(params, key);
92             jsonPayload.put(key, params.get(key));
93         }
94
95         parseOptionalParams(params, optionalTestParams, jsonPayload);
96
97         // Generate a unique uuid for the test
98         String reqId = UUID.randomUUID().toString();
99         jsonPayload.put(ID_KEY, reqId);
100
101         return jsonPayload;
102     }
103
104     /**
105      * Method that validates that the Map has enough information
106      * to query Ansible server for a result. If so, it returns
107      * the appropriate url, else an empty string.
108      */
109     public String reqUriResult(Map<String, String> params) throws SvcLogicException {
110
111         final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY};
112
113         for (String key : mandatoryTestParams) {
114             throwIfMissingMandatoryParam(params, key);
115         }
116         return params.get(AGENT_URL_KEY) + "?Id=" + params.get(ID_KEY) + "&Type=GetResult";
117     }
118
119     /**
120      * Method that validates that the Map has enough information
121      * to query Ansible server for logs. If so, it populates the appropriate
122      * returns the appropriate url, else an empty string.
123      */
124     public String reqUriLog(Map<String, String> params) throws SvcLogicException {
125
126         final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY};
127
128         for (String mandatoryParam : mandatoryTestParams) {
129             throwIfMissingMandatoryParam(params, mandatoryParam);
130         }
131         return params.get(AGENT_URL_KEY) + "?Id=" + params.get(ID_KEY) + "&Type=GetLog";
132     }
133
134     /**
135      * This method parses response from the Ansible Server when we do a post
136      * and returns an AnsibleResult object.
137      */
138     public AnsibleResult parsePostResponse(String input) throws SvcLogicException {
139         AnsibleResult ansibleResult;
140         try {
141             JSONObject postResponse = new JSONObject(input);
142
143             int code = postResponse.getInt(STATUS_CODE_KEY);
144             String msg = postResponse.getString(STATUS_MESSAGE_KEY);
145
146             int initResponseValue = AnsibleResultCodes.INITRESPONSE.getValue();
147             boolean validCode = AnsibleResultCodes.CODE.checkValidCode(initResponseValue, code);
148             if (!validCode) {
149                 throw new SvcLogicException("Invalid InitResponse code  = " + code + " received. MUST be one of "
150                         + AnsibleResultCodes.CODE.getValidCodes(initResponseValue));
151             }
152
153             ansibleResult = new AnsibleResult(code, msg);
154
155         } catch (JSONException e) {
156             LOGGER.error("JSON exception", e);
157             ansibleResult = new AnsibleResult(600, "Error parsing response = " + input + ". Error = " + e.getMessage());
158         }
159         return ansibleResult;
160     }
161
162     /**
163      * This method parses response from an Ansible server when we do a GET for a result
164      * and returns an AnsibleResult object.
165      **/
166     public AnsibleResult parseGetResponse(String input) throws SvcLogicException {
167
168         AnsibleResult ansibleResult = new AnsibleResult();
169
170         try {
171             JSONObject postResponse = new JSONObject(input);
172             ansibleResult = parseGetResponseNested(ansibleResult, postResponse);
173         } catch (JSONException e) {
174             LOGGER.error("JSON exception", e);
175             ansibleResult = new AnsibleResult(AnsibleResultCodes.INVALID_PAYLOAD.getValue(),
176                     "Error parsing response = " + input + ". Error = " + e.getMessage(), "");
177         }
178         return ansibleResult;
179     }
180
181     private AnsibleResult parseGetResponseNested(AnsibleResult ansibleResult, JSONObject postRsp) throws SvcLogicException  {
182
183         int codeStatus = postRsp.getInt(STATUS_CODE_KEY);
184         String messageStatus = postRsp.getString(STATUS_MESSAGE_KEY);
185         int finalCode = AnsibleResultCodes.FINAL_SUCCESS.getValue();
186
187         boolean valCode =
188                 AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.FINALRESPONSE.getValue(), codeStatus);
189
190         if (!valCode) {
191             throw new SvcLogicException("Invalid FinalResponse code  = " + codeStatus + " received. MUST be one of "
192                     + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.FINALRESPONSE.getValue()));
193         }
194
195         ansibleResult.setStatusCode(codeStatus);
196         ansibleResult.setStatusMessage(messageStatus);
197         LOGGER.info("Received response with code = {}, Message = {}", codeStatus, messageStatus);
198
199         if (!postRsp.isNull("Results")) {
200
201             // Results are available. process them
202             // Results is a dictionary of the form
203
204             LOGGER.info("Processing results in response");
205             JSONObject results = postRsp.getJSONObject("Results");
206             LOGGER.info("Get JSON dictionary from Results ..");
207             Iterator<String> hosts = results.keys();
208             LOGGER.info("Iterating through hosts");
209
210             while (hosts.hasNext()) {
211                 String host = hosts.next();
212                 LOGGER.info("Processing host = {}", host);
213
214                 try {
215                     JSONObject hostResponse = results.getJSONObject(host);
216                     int subCode = hostResponse.getInt(STATUS_CODE_KEY);
217                     String message = hostResponse.getString(STATUS_MESSAGE_KEY);
218
219                     LOGGER.info("Code = {}, Message = {}", subCode, message);
220
221                     if (subCode != 200 || !("SUCCESS").equals(message)) {
222                         finalCode = AnsibleResultCodes.REQ_FAILURE.getValue();
223                     }
224                 } catch (JSONException e) {
225                     LOGGER.error("JSON exception", e);
226                     ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue());
227                     ansibleResult.setStatusMessage(String.format(
228                             "Error processing response message = %s from host %s", results.getString(host), host));
229                     break;
230                 }
231             }
232
233             ansibleResult.setStatusCode(finalCode);
234
235             // We return entire Results object as message
236             ansibleResult.setResults(results.toString());
237
238         } else {
239             ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue());
240             ansibleResult.setStatusMessage("Results not found in GET for response");
241         }
242         return ansibleResult;
243     }
244
245     private void parseOptionalParams(Map<String, String> params, String[] optionalTestParams, JSONObject jsonPayload) {
246
247         Set<String> optionalParamsSet = new HashSet<>();
248         Collections.addAll(optionalParamsSet, optionalTestParams);
249
250         //@formatter:off
251         params.entrySet()
252             .stream()
253             .filter(entry -> optionalParamsSet.contains(entry.getKey()))
254             .filter(entry -> !Strings.isNullOrEmpty(entry.getValue()))
255              .forEach(entry -> parseOptionalParam(entry, jsonPayload));
256         //@formatter:on
257     }
258
259     private void parseOptionalParam(Map.Entry<String, String> params, JSONObject jsonPayload) {
260         String key = params.getKey();
261         String payload = params.getValue();
262
263         switch (key) {
264             case TIMEOUT_OPT_KEY:
265                 int timeout = Integer.parseInt(payload);
266                 if (timeout < 0) {
267                     throw new NumberFormatException(" : specified negative integer for timeout = " + payload);
268                 }
269                 jsonPayload.put(key, payload);
270                 break;
271
272             case VERSION_OPT_KEY:
273                 jsonPayload.put(key, payload);
274                 break;
275
276             case LOCAL_PARAMETERS_OPT_KEY:
277             case ENV_PARAMETERS_OPT_KEY:
278                 JSONObject paramsJson = new JSONObject(payload);
279                 jsonPayload.put(key, paramsJson);
280                 break;
281
282             case NODE_LIST_OPT_KEY:
283                 JSONArray paramsArray = new JSONArray(payload);
284                 jsonPayload.put(key, paramsArray);
285                 break;
286
287             case FILE_PARAMETERS_OPT_KEY:
288                 jsonPayload.put(key, getFilePayload(payload));
289                 break;
290
291             default:
292                 break;
293         }
294     }
295
296     /**
297      * Return payload with escaped newlines
298      */
299     private JSONObject getFilePayload(String payload) {
300         String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r");
301         return new JSONObject(formattedPayload);
302     }
303
304     private void throwIfMissingMandatoryParam(Map<String, String> params, String key) throws SvcLogicException {
305         if (!params.containsKey(key)) {
306             throw new SvcLogicException(String.format(
307                     "Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !",
308                     key));
309         }
310         if (Strings.isNullOrEmpty(params.get(key))) {
311             throw new SvcLogicException(String.format(
312                     "Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !",
313                     key));
314         }
315     }
316 }