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.ccsdk.sli.adaptors.ansible.impl;
28 import java.util.Properties;
29 import org.apache.commons.lang.StringUtils;
30 import org.json.JSONException;
31 import org.json.JSONObject;
32 import org.onap.ccsdk.sli.adaptors.ansible.AnsibleAdapter;
33 import org.onap.ccsdk.sli.adaptors.ansible.AnsibleAdapterPropertiesProvider;
34 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleMessageParser;
35 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult;
36 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResultCodes;
37 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleServerEmulator;
38 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
39 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
40 import com.att.eelf.configuration.EELFLogger;
41 import com.att.eelf.configuration.EELFManager;
44 * This class implements the {@link AnsibleAdapter} interface. This interface defines the behaviors
45 * that our service provides.
47 public class AnsibleAdapterImpl implements AnsibleAdapter {
51 * The constant used to define the service name in the mapped diagnostic context
53 @SuppressWarnings("nls")
54 public static final String MDC_SERVICE = "service";
57 * The constant for the status code for a failed outcome
59 @SuppressWarnings("nls")
60 public static final String OUTCOME_FAILURE = "failure";
63 * The constant for the status code for a successful outcome
65 @SuppressWarnings("nls")
66 public static final String OUTCOME_SUCCESS = "success";
71 private static final String ADAPTER_NAME = "Ansible Adapter";
72 private static final String APPC_EXCEPTION_CAUGHT = "APPCException caught";
74 private static final String RESULT_CODE_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.result.code";
75 private static final String MESSAGE_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.message";
76 private static final String RESULTS_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.results";
77 private static final String ID_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.Id";
78 private static final String LOG_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.log";
80 private static final String CLIENT_TYPE_PROPERTY_NAME = "org.onap.appc.adapter.ansible.clientType";
81 private static final String TRUSTSTORE_PROPERTY_NAME = "org.onap.appc.adapter.ansible.trustStore";
82 private static final String TRUSTPASSD_PROPERTY_NAME = "org.onap.appc.adapter.ansible.trustStore.trustPasswd";
84 private static final String PASSD = "Password";
87 * The logger to be used
89 private static final EELFLogger logger = EELFManager.getInstance().getLogger(AnsibleAdapterImpl.class);
95 private ConnectionBuilder httpClient;
98 * Ansible API Message Handlers
100 private AnsibleMessageParser messageProcessor;
103 * indicator whether in test mode
105 private boolean testMode = false;
108 * server emulator object to be used if in test mode
110 private AnsibleServerEmulator testServer;
113 * This default constructor is used as a work around because the activator wasn't getting called
115 public AnsibleAdapterImpl() {
116 initialize(new AnsibleAdapterPropertiesProviderImpl());
118 public AnsibleAdapterImpl(AnsibleAdapterPropertiesProvider propProvider) {
119 initialize(propProvider);
123 * Used for jUnit test and testing interface
125 public AnsibleAdapterImpl(boolean mode) {
127 testServer = new AnsibleServerEmulator();
128 messageProcessor = new AnsibleMessageParser();
132 * Returns the symbolic name of the adapter
134 * @return The adapter name
135 * @see org.onap.appc.adapter.rest.AnsibleAdapter#getAdapterName()
138 public String getAdapterName() {
143 * @param rc Method posts info to Context memory in case of an error and throws a
144 * SvcLogicException causing SLI to register this as a failure
146 @SuppressWarnings("static-method")
147 private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
149 svcLogic.setStatus(OUTCOME_FAILURE);
150 svcLogic.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code));
151 svcLogic.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
153 throw new SvcLogicException("Ansible Adapter Error = " + message);
157 * initialize the Ansible adapter based on default and over-ride configuration data
159 private void initialize(AnsibleAdapterPropertiesProvider propProvider) {
162 Properties props = propProvider.getProperties();
164 // Create the message processor instance
165 messageProcessor = new AnsibleMessageParser();
167 // Create the http client instance
168 // type of client is extracted from the property file parameter
169 // org.onap.appc.adapter.ansible.clientType
171 // 1. TRUST_ALL (trust all SSL certs). To be used ONLY in dev
172 // 2. TRUST_CERT (trust only those whose certificates have been stored in the trustStore file)
173 // 3. DEFAULT (trust only well known certificates). This is standard behavior to which it will
174 // revert. To be used in PROD
177 String clientType = props.getProperty(CLIENT_TYPE_PROPERTY_NAME);
178 logger.info("Ansible http client type set to " + clientType);
180 if ("TRUST_ALL".equals(clientType)) {
182 "Creating http client to trust ALL ssl certificates. WARNING. This should be done only in dev environments");
183 httpClient = new ConnectionBuilder(1);
184 } else if ("TRUST_CERT".equals(clientType)) {
185 // set path to keystore file
186 String trustStoreFile = props.getProperty(TRUSTSTORE_PROPERTY_NAME);
187 String key = props.getProperty(TRUSTPASSD_PROPERTY_NAME);
188 char[] trustStorePasswd = key.toCharArray();
189 logger.info("Creating http client with trustmanager from " + trustStoreFile);
190 httpClient = new ConnectionBuilder(trustStoreFile, trustStorePasswd);
192 logger.info("Creating http client with default behaviour");
193 httpClient = new ConnectionBuilder(0);
195 } catch (Exception e) {
196 logger.error("Error Initializing Ansible Adapter due to Unknown Exception", e);
199 logger.info("Initialized Ansible Adapter");
202 // Public Method to post request to execute playbook. Posts the following back
203 // to Svc context memory
204 // org.onap.appc.adapter.ansible.req.code : 100 if successful
205 // org.onap.appc.adapter.ansible.req.messge : any message
206 // org.onap.appc.adapter.ansible.req.Id : a unique uuid to reference the request
208 public void reqExec(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
210 String playbookName = StringUtils.EMPTY;
211 String payload = StringUtils.EMPTY;
212 String agentUrl = StringUtils.EMPTY;
213 String user = StringUtils.EMPTY;
214 String password = StringUtils.EMPTY;
215 String id = StringUtils.EMPTY;
217 JSONObject jsonPayload;
220 // create json object to send request
221 jsonPayload = messageProcessor.reqMessage(params);
223 agentUrl = (String) jsonPayload.remove("AgentUrl");
224 user = (String) jsonPayload.remove("User");
225 password = (String) jsonPayload.remove(PASSD);
226 id = jsonPayload.getString("Id");
227 payload = jsonPayload.toString();
228 logger.info("Updated Payload = " + payload);
229 } catch (SvcLogicException e) {
230 logger.error(APPC_EXCEPTION_CAUGHT, e);
231 doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(),
232 "Error constructing request for execution of playbook due to missing mandatory parameters. Reason = "
234 } catch (JSONException e) {
235 logger.error("JSONException caught", e);
236 doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(),
237 "Error constructing request for execution of playbook due to invalid JSON block. Reason = "
239 } catch (NumberFormatException e) {
240 logger.error("NumberFormatException caught", e);
241 doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(),
242 "Error constructing request for execution of playbook due to invalid parameter values. Reason = "
247 String message = StringUtils.EMPTY;
250 // post the test request
251 logger.info("Posting request = " + payload + " to url = " + agentUrl);
252 AnsibleResult testResult = postExecRequest(agentUrl, payload, user, password);
254 // Process if HTTP was successful
255 if (testResult.getStatusCode() == 200) {
256 testResult = messageProcessor.parsePostResponse(testResult.getStatusMessage());
258 doFailure(ctx, testResult.getStatusCode(),
259 "Error posting request. Reason = " + testResult.getStatusMessage());
262 code = testResult.getStatusCode();
263 message = testResult.getStatusMessage();
265 // Check status of test request returned by Agent
266 if (code == AnsibleResultCodes.PENDING.getValue()) {
267 logger.info(String.format("Submission of Test %s successful.", playbookName));
268 // test request accepted. We are in asynchronous case
270 doFailure(ctx, code, "Request for execution of playbook rejected. Reason = " + message);
272 } catch (SvcLogicException e) {
273 logger.error(APPC_EXCEPTION_CAUGHT, e);
274 doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(),
275 "Exception encountered when posting request for execution of playbook. Reason = " + e.getMessage());
278 ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code));
279 ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
280 ctx.setAttribute(ID_ATTRIBUTE_NAME, id);
284 * Public method to query status of a specific request It blocks till the Ansible Server
285 * responds or the session times out (non-Javadoc)
287 * @see org.onap.ccsdk.sli.adaptors.ansible.AnsibleAdapter#reqExecResult(java.util.Map,
288 * org.onap.ccsdk.sli.core.sli.SvcLogicContext)
291 public void reqExecResult(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
294 String reqUri = StringUtils.EMPTY;
297 reqUri = messageProcessor.reqUriResult(params);
298 logger.info("Got uri ", reqUri );
299 } catch (SvcLogicException e) {
300 logger.error(APPC_EXCEPTION_CAUGHT, e);
301 doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(),
302 "Error constructing request to retrieve result due to missing parameters. Reason = "
305 } catch (NumberFormatException e) {
306 logger.error("NumberFormatException caught", e);
307 doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(),
308 "Error constructing request to retrieve result due to invalid parameters value. Reason = "
314 String message = StringUtils.EMPTY;
315 String results = StringUtils.EMPTY;
318 // Try to retrieve the test results (modify the URL for that)
319 AnsibleResult testResult = queryServer(reqUri, params.get("User"), params.get(PASSD));
320 code = testResult.getStatusCode();
321 message = testResult.getStatusMessage();
324 logger.info("Parsing response from Server = " + message);
325 // Valid HTTP. process the Ansible message
326 testResult = messageProcessor.parseGetResponse(message);
327 code = testResult.getStatusCode();
328 message = testResult.getStatusMessage();
329 results = testResult.getResults();
332 logger.info("Request response = " + message);
333 } catch (SvcLogicException e) {
334 logger.error(APPC_EXCEPTION_CAUGHT, e);
335 doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(),
336 "Exception encountered retrieving result : " + e.getMessage());
340 // We were able to get and process the results. Determine if playbook succeeded
342 if (code == AnsibleResultCodes.FINAL_SUCCESS.getValue()) {
343 message = String.format("Ansible Request %s finished with Result = %s, Message = %s", params.get("Id"),
344 OUTCOME_SUCCESS, message);
345 logger.info(message);
347 logger.info(String.format("Ansible Request %s finished with Result %s, Message = %s", params.get("Id"),
348 OUTCOME_FAILURE, message));
349 ctx.setAttribute(RESULTS_ATTRIBUTE_NAME, results);
350 doFailure(ctx, code, message);
354 ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(400));
355 ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
356 ctx.setAttribute(RESULTS_ATTRIBUTE_NAME, results);
357 ctx.setStatus(OUTCOME_SUCCESS);
361 * Public method to get logs from playbook execution for a specific request
363 * It blocks till the Ansible Server responds or the session times out very similar to
364 * reqExecResult logs are returned in the DG context variable org.onap.appc.adapter.ansible.log
367 public void reqExecLog(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
369 String reqUri = StringUtils.EMPTY;
371 reqUri = messageProcessor.reqUriLog(params);
372 logger.info("Retrieving results from " + reqUri);
373 } catch (Exception e) {
374 logger.error("Exception caught", e);
375 doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), e.getMessage());
378 String message = StringUtils.EMPTY;
380 // Try to retrieve the test results (modify the url for that)
381 AnsibleResult testResult = queryServer(reqUri, params.get("User"), params.get(PASSD));
382 message = testResult.getStatusMessage();
383 logger.info("Request output = " + message);
384 ctx.setAttribute(LOG_ATTRIBUTE_NAME, message);
385 ctx.setStatus(OUTCOME_SUCCESS);
386 } catch (Exception e) {
387 logger.error("Exception caught", e);
388 doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(),
389 "Exception encountered retreiving output : " + e.getMessage());
394 * Method that posts the request
396 private AnsibleResult postExecRequest(String agentUrl, String payload, String user, String password) {
398 AnsibleResult testResult;
401 httpClient.setHttpContext(user, password);
402 testResult = httpClient.post(agentUrl, payload);
404 testResult = testServer.Post(agentUrl, payload);
410 * Method to query Ansible server
412 private AnsibleResult queryServer(String agentUrl, String user, String password) {
414 AnsibleResult testResult;
416 logger.info("Querying url = " + agentUrl);
419 testResult = httpClient.get(agentUrl);
421 testResult = testServer.Get(agentUrl);