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.openecomp.appc.adapter.ansible.impl;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.List;
32 import java.util.Properties;
34 import java.util.regex.Pattern;
37 import org.openecomp.appc.Constants;
38 import org.openecomp.appc.exceptions.APPCException;
40 import org.openecomp.appc.configuration.Configuration;
41 import org.openecomp.appc.configuration.ConfigurationFactory;
42 import org.openecomp.appc.exceptions.APPCException;
43 import org.openecomp.appc.i18n.Msg;
44 import org.openecomp.appc.pool.Pool;
45 import org.openecomp.appc.pool.PoolExtensionException;
46 import org.openecomp.appc.util.StructuredPropertyHelper;
47 import org.openecomp.appc.util.StructuredPropertyHelper.Node;
49 import org.openecomp.sdnc.sli.SvcLogicContext;
50 import org.openecomp.sdnc.sli.SvcLogicException;
55 import org.json.JSONObject;
56 import org.json.JSONArray;
57 import org.json.JSONException;
60 import com.google.common.base.Strings;
61 //import com.google.gson.Gson;
62 //import com.google.gson.GsonBuilder;
64 import org.openecomp.appc.adapter.ansible.AnsibleAdapter;
66 import org.openecomp.appc.adapter.ansible.model.AnsibleResult;
67 import org.openecomp.appc.adapter.ansible.model.AnsibleMessageParser;
68 import org.openecomp.appc.adapter.ansible.model.AnsibleResultCodes;
69 import org.openecomp.appc.adapter.ansible.model.AnsibleServerEmulator;
71 import com.att.eelf.configuration.EELFLogger;
72 import com.att.eelf.configuration.EELFManager;
73 import com.att.eelf.i18n.EELFResourceManager;
74 import static com.att.eelf.configuration.Configuration.*;
78 * This class implements the {@link AnsibleAdapter} interface. This interface
79 * defines the behaviors that our service provides.
82 public class AnsibleAdapterImpl implements AnsibleAdapter {
85 * The constant used to define the adapter name in the mapped diagnostic
90 @SuppressWarnings("nls")
91 public static final String MDC_ADAPTER = "Ansible Adapter";
94 * The constant used to define the service name in the mapped diagnostic
97 @SuppressWarnings("nls")
98 public static final String MDC_SERVICE = "service";
101 * The constant for the status code for a failed outcome
103 @SuppressWarnings("nls")
104 public static final String OUTCOME_FAILURE = "failure";
107 * The constant for the status code for a successful outcome
109 @SuppressWarnings("nls")
110 public static final String OUTCOME_SUCCESS = "success";
115 private static final String ADAPTER_NAME = "Ansible Adapter";
119 * The logger to be used
121 private static final EELFLogger logger = EELFManager.getInstance().getLogger(AnsibleAdapterImpl.class);
124 * A reference to the adapter configuration object.
126 private Configuration configuration;;
128 /** can Specify a X509 certificate file for use if required ...
129 Must be initialized with setCertFile
131 private String certFile = "";
137 ConnectionBuilder http_client ;
140 * Ansible API Message Handlers
142 private AnsibleMessageParser messageProcessor;
145 indicator whether in test mode
147 private boolean testMode = false;
150 server emulator object to be used if in test mode
152 private AnsibleServerEmulator testServer;
155 * This default constructor is used as a work around because the activator
156 * wasnt getting called
158 public AnsibleAdapterImpl() {
167 public AnsibleAdapterImpl(Properties props) {
174 Used for jUnit test and testing interface
176 public AnsibleAdapterImpl(boolean Mode){
178 testServer = new AnsibleServerEmulator();
179 messageProcessor = new AnsibleMessageParser();
183 * Returns the symbolic name of the adapter
185 * @return The adapter name
186 * @see org.openecomp.appc.adapter.rest.AnsibleAdapter#getAdapterName()
189 public String getAdapterName() {
197 * Method posts info to Context memory in case of an error
198 * and throws a SvcLogicException causing SLI to register this as a failure
200 @SuppressWarnings("static-method")
201 private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
203 svcLogic.setStatus(OUTCOME_FAILURE);
204 svcLogic.setAttribute("org.openecomp.appc.adapter.ansible.result.code",Integer.toString(code));
205 svcLogic.setAttribute("org.openecomp.appc.adapter.ansible.message",message);
207 throw new SvcLogicException("Ansible Adapter Error = " + message );
212 * initialize the Ansible adapter based on default and over-ride configuration data
214 private void initialize() {
216 configuration = ConfigurationFactory.getConfiguration();
217 Properties props = configuration.getProperties();
219 // Create the message processor instance
220 messageProcessor = new AnsibleMessageParser();
222 // Create the http client instance
223 // type of client is extracted from the property file parameter
224 // org.openecomp.appc.adapter.ansible.clientType
226 // 1. TRUST_ALL (trust all SSL certs). To be used ONLY in dev
227 // 2. TRUST_CERT (trust only those whose certificates have been stored in the trustStore file)
228 // 3. DEFAULT (trust only well known certificates). This is standard behaviour to which it will
229 // revert. To be used in PROD
232 String clientType = props.getProperty("org.openecomp.appc.adapter.ansible.clientType");
233 logger.info("Ansible http client type set to " + clientType);
235 if (clientType.equals("TRUST_ALL")){
236 logger.info("Creating http client to trust ALL ssl certificates. WARNING. This should be done only in dev environments");
237 http_client = new ConnectionBuilder(1);
239 else if (clientType.equals("TRUST_CERT")){
240 // set path to keystore file
241 String trustStoreFile = props.getProperty("org.openecomp.appc.adapter.ansible.trustStore");
242 String key = props.getProperty("org.openecomp.appc.adapter.ansible.trustStore.trustPasswd");
243 char [] trustStorePasswd = key.toCharArray();
244 String trustStoreType = "JKS";
245 logger.info("Creating http client with trustmanager from " + trustStoreFile);
246 http_client = new ConnectionBuilder(trustStoreFile, trustStorePasswd);
249 logger.info("Creating http client with default behaviour");
250 http_client = new ConnectionBuilder(0);
254 logger.error("Error Initializing Ansible Adapter due to Unknown Exception: reason = " + e.getMessage());
257 logger.info("Intitialized Ansible Adapter");
262 /** set the certificate file if not a trusted/known CA **/
263 private void setCertFile(String CertFile){
264 this.certFile = CertFile;
269 // Public Method to post request to execute playbook. Posts the following back
270 // to Svc context memory
271 // org.openecomp.appc.adapter.ansible.req.code : 100 if successful
272 // org.openecomp.appc.adapter.ansible.req.messge : any message
273 // org.openecomp.appc.adapter.ansible.req.Id : a unique uuid to reference the request
275 public void reqExec(Map <String, String> params, SvcLogicContext ctx) throws SvcLogicException {
277 String PlaybookName = "";
279 String AgentUrl = "";
281 String Password = "";
284 JSONObject JsonPayload;
287 // create json object to send request
288 JsonPayload = messageProcessor.ReqMessage(params);
290 AgentUrl = (String) JsonPayload.remove("AgentUrl");
291 User = (String) JsonPayload.remove("User");
292 Password = (String) JsonPayload.remove("Password");
293 Id = (String)JsonPayload.getString("Id");
294 payload = JsonPayload.toString();
295 logger.info("Updated Payload = " + payload);
297 catch(APPCException e){
298 doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request for execution of playbook due to missing mandatory parameters. Reason = " + e.getMessage());
300 catch(JSONException e){
301 doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request for execution of playbook due to invalid JSON block. Reason = " + e.getMessage());
303 catch(NumberFormatException e){
304 doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request for execution of playbook due to invalid parameter values. Reason = " + e.getMessage());
314 // post the test request
315 //---------------------------------------
316 logger.info("Posting request = " + payload + " to url = " + AgentUrl );
317 AnsibleResult testresult = postExecRequest(AgentUrl, payload, User, Password);
320 // Process if HTTP was successfull
321 if(testresult.getStatusCode() == 200){
322 testresult = messageProcessor.parsePostResponse(testresult.getStatusMessage());
325 doFailure(ctx, testresult.getStatusCode(), "Error posting request. Reason = " + testresult.getStatusMessage());
329 code = testresult.getStatusCode();
330 message = testresult.getStatusMessage();
333 // Check status of test request returned by Agent
334 //-----------------------------------------------
335 if (code == AnsibleResultCodes.PENDING.getValue()){
336 logger.info(String.format("Submission of Test %s successful.", PlaybookName));
337 // test request accepted. We are in asynchronous case
340 doFailure(ctx, code, "Request for execution of playbook rejected. Reason = " + message);
344 catch(APPCException e){
345 doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), "Exception encountered when posting request for execution of playbook. Reason = " + e.getMessage());
349 ctx.setAttribute("org.openecomp.appc.adapter.ansible.result.code", Integer.toString(code));
350 ctx.setAttribute("org.openecomp.appc.adapter.ansible.message", message );
351 ctx.setAttribute("org.openecomp.appc.adapter.ansible.Id", Id);
356 // Public method to query status of a specific request
357 // It blocks till the Ansible Server responds or the session times out
359 public void reqExecResult(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
366 ReqUri = messageProcessor.ReqUri_Result(params);
367 System.out.println("Got uri = " + ReqUri);
369 catch(APPCException e){
370 doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request to retreive result due to missing parameters. Reason = " + e.getMessage());
373 catch(NumberFormatException e){
374 doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request to retreive result due to invalid parameters value. Reason = " + e.getMessage());
383 // Try to retreive the test results (modify the url for that)
384 AnsibleResult testresult = queryServer(ReqUri, params.get("User"), params.get("Password"));
385 code = testresult.getStatusCode();
386 message = testresult.getStatusMessage();
389 logger.info("Parsing response from Server = " + message);
390 // Valid HTTP. process the Ansible message
391 testresult = messageProcessor.parseGetResponse(message);
392 code = testresult.getStatusCode();
393 message = testresult.getStatusMessage();
394 results = testresult.getResults();
398 logger.info("Request response = " + message);
401 catch (APPCException e){
402 doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), "Exception encountered retreiving result : " + e.getMessage());
406 // We were able to get and process the results. Determine if playbook succeeded
408 if (code == AnsibleResultCodes.FINAL_SUCCESS.getValue()){
409 message = String.format("Ansible Request %s finished with Result = %s, Message = %s", params.get("Id"), OUTCOME_SUCCESS, message);
410 logger.info(message);
413 logger.info(String.format("Ansible Request %s finished with Result %s, Message = %s", params.get("Id"), OUTCOME_FAILURE, message));
414 ctx.setAttribute("org.openecomp.appc.adapter.ansible.results", results);
415 doFailure(ctx, code, message );
420 ctx.setAttribute("org.openecomp.appc.adapter.ansible.result.code", Integer.toString(400));
421 ctx.setAttribute("org.openecomp.appc.adapter.ansible.message",message);
422 ctx.setAttribute("org.openecomp.appc.adapter.ansible.results", results);
423 ctx.setStatus(OUTCOME_SUCCESS);
427 // Public method to get logs from plyabook execution for a specifcic request
428 // It blocks till the Ansible Server responds or the session times out
429 // very similar to reqExecResult
430 // logs are returned in the DG context variable org.openecomp.appc.adapter.ansible.log
432 public void reqExecLog(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException{
438 ReqUri = messageProcessor.ReqUri_Log(params);
439 logger.info("Retreiving results from " + ReqUri);
442 doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), e.getMessage());
450 // Try to retreive the test results (modify the url for that)
451 AnsibleResult testresult = queryServer(ReqUri, params.get("User"), params.get("Password"));
452 code = testresult.getStatusCode();
453 message = testresult.getStatusMessage();
455 logger.info("Request output = " + message);
459 doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), "Exception encountered retreiving output : " + e.getMessage());
462 ctx.setAttribute("org.openecomp.appc.adapter.ansible.log",message);
463 ctx.setStatus(OUTCOME_SUCCESS);
471 * Method that posts the request
474 private AnsibleResult postExecRequest(String AgentUrl, String Payload, String User, String Password) {
476 String reqOutput = "UNKNOWN";
479 AnsibleResult testresult;
482 http_client.setHttpContext(User, Password);
483 testresult = http_client.Post(AgentUrl, Payload);
486 testresult = testServer.Post(AgentUrl, Payload);
494 Method to query Ansible server
497 private AnsibleResult queryServer(String AgentUrl, String User, String Password) {
499 String testOutput = "UNKNOWN";
501 AnsibleResult testresult;
503 logger.info("Querying url = " + AgentUrl);
506 testresult = http_client.Get(AgentUrl);
509 testresult = testServer.Get(AgentUrl);