From 11510b43c277b8e1dd7e58d79785544810118c8e Mon Sep 17 00:00:00 2001 From: Jessica Wagantall Date: Tue, 1 Dec 2020 11:26:31 -0800 Subject: Migrate sli-adaptor files Migrate sli-adaptor repo files into a new "adaptors" directory. Signed-off-by: Jessica Wagantall --- adaptors/ansible-adapter/.pydevproject | 5 + .../ansible-adapter-bundle/.gitignore | 25 ++ .../ansible-adapter/ansible-adapter-bundle/pom.xml | 131 ++++++ .../ccsdk/sli/adaptors/ansible/AnsibleAdapter.java | 55 +++ .../ansible/AnsibleAdapterPropertiesProvider.java | 28 ++ .../adaptors/ansible/impl/AnsibleAdapterImpl.java | 460 +++++++++++++++++++++ .../impl/AnsibleAdapterPropertiesProviderImpl.java | 191 +++++++++ .../adaptors/ansible/impl/ConnectionBuilder.java | 205 +++++++++ .../ansible/model/AnsibleMessageParser.java | 332 +++++++++++++++ .../sli/adaptors/ansible/model/AnsibleResult.java | 81 ++++ .../adaptors/ansible/model/AnsibleResultCodes.java | 93 +++++ .../ansible/model/AnsibleServerEmulator.java | 137 ++++++ .../blueprint/ansible-adapter-blueprint.xml | 39 ++ .../src/main/resources/ansible-adapter.properties | 48 +++ .../blueprint/ansible-adapter-blueprint.xml | 39 ++ .../ansible/impl/TestAnsibleAdapterImpl.java | 147 +++++++ .../TestAnsibleAdapterPropertiesProviderImpl.java | 53 +++ .../ansible/impl/TestConnectionBuilder.java | 155 +++++++ .../adapter/ansible/model/TestAnsibleAdapter.java | 81 ++++ .../java/org/onap/ccsdk/test/ExecutorHarness.java | 181 ++++++++ .../java/org/onap/ccsdk/test/InterceptLogger.java | 454 ++++++++++++++++++++ .../ansible-adapter-bundle/src/test/resources/cert | 125 ++++++ .../resources/org/onap/ccsdk/default.properties | 111 +++++ .../ansible-adapter-installer/pom.xml | 151 +++++++ .../src/assembly/assemble_installer_zip.xml | 62 +++ .../src/assembly/assemble_mvnrepo_zip.xml | 50 +++ .../src/main/resources/scripts/install-feature.sh | 42 ++ adaptors/ansible-adapter/pom.xml | 191 +++++++++ 28 files changed, 3672 insertions(+) create mode 100644 adaptors/ansible-adapter/.pydevproject create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/.gitignore create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/pom.xml create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/AnsibleAdapter.java create mode 100755 adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/AnsibleAdapterPropertiesProvider.java create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/impl/AnsibleAdapterImpl.java create mode 100755 adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/impl/AnsibleAdapterPropertiesProviderImpl.java create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/impl/ConnectionBuilder.java create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleMessageParser.java create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleResult.java create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleResultCodes.java create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleServerEmulator.java create mode 100755 adaptors/ansible-adapter/ansible-adapter-bundle/src/main/resources/OSGI-INF/blueprint/ansible-adapter-blueprint.xml create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/main/resources/ansible-adapter.properties create mode 100755 adaptors/ansible-adapter/ansible-adapter-bundle/src/main/resources/org/opendaylight/blueprint/ansible-adapter-blueprint.xml create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterImpl.java create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterPropertiesProviderImpl.java create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestConnectionBuilder.java create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleAdapter.java create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/ExecutorHarness.java create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/InterceptLogger.java create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/test/resources/cert create mode 100644 adaptors/ansible-adapter/ansible-adapter-bundle/src/test/resources/org/onap/ccsdk/default.properties create mode 100644 adaptors/ansible-adapter/ansible-adapter-installer/pom.xml create mode 100644 adaptors/ansible-adapter/ansible-adapter-installer/src/assembly/assemble_installer_zip.xml create mode 100644 adaptors/ansible-adapter/ansible-adapter-installer/src/assembly/assemble_mvnrepo_zip.xml create mode 100644 adaptors/ansible-adapter/ansible-adapter-installer/src/main/resources/scripts/install-feature.sh create mode 100644 adaptors/ansible-adapter/pom.xml (limited to 'adaptors/ansible-adapter') diff --git a/adaptors/ansible-adapter/.pydevproject b/adaptors/ansible-adapter/.pydevproject new file mode 100644 index 000000000..d001f0aea --- /dev/null +++ b/adaptors/ansible-adapter/.pydevproject @@ -0,0 +1,5 @@ + + +Default +python interpreter + diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/.gitignore b/adaptors/ansible-adapter/ansible-adapter-bundle/.gitignore new file mode 100644 index 000000000..255b54097 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/.gitignore @@ -0,0 +1,25 @@ +# ============LICENSE_START========================================== +# ONAP : APPC +# =================================================================== +# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. +# =================================================================== +# +# Unless otherwise specified, all software contained herein is licensed +# under the Apache License, Version 2.0 (the License); +# you may not use this software except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END============================================ +/bin/ +/target/ +/target-ide/ +/.settings/ diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/pom.xml b/adaptors/ansible-adapter/ansible-adapter-bundle/pom.xml new file mode 100644 index 000000000..605c64421 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/pom.xml @@ -0,0 +1,131 @@ + + + + + 4.0.0 + + + org.onap.ccsdk.parent + binding-parent + 2.1.0 + + + + org.onap.ccsdk.sli.adaptors + ansible-adapter-bundle + 1.1.1-SNAPSHOT + bundle + + ccsdk-sli-adaptors :: ansible-adapter :: ${project.artifactId} + + + ${project.version} + + + + + + org.onap.ccsdk.sli.core + sli-core-artifacts + ${ccsdk.sli.core.version} + pom + import + + + + + + com.att.eelf + eelf-core + + + commons-codec + commons-codec + + + commons-logging + commons-logging + + + + org.apache.httpcomponents + httpclient + + + + + + org.glassfish.jersey.core + jersey-common + test + + + + org.codehaus.jackson + jackson-jaxrs + test + + + + junit + junit + test + + + org.mockito + mockito-core + test + + + org.onap.ccsdk.sli.core + sli-common + provided + + + + org.onap.ccsdk.sli.core + sli-provider + provided + + + + org.osgi + org.osgi.core + provided + + + org.slf4j + slf4j-api + + + + org.slf4j + jcl-over-slf4j + + + + org.json + json + + + + + com.google.guava + guava + + + + + diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/AnsibleAdapter.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/AnsibleAdapter.java new file mode 100644 index 000000000..e43d3e3c3 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/AnsibleAdapter.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ansible; + +import java.util.Map; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +/** + * This interface defines the operations that the Ansible adapter exposes. + * + */ +public interface AnsibleAdapter extends SvcLogicJavaPlugin { + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + */ + String getAdapterName(); + + /* Method to post request for execution of Playbook */ + void reqExec(Map params, SvcLogicContext ctx) throws SvcLogicException; + + /* Method to get result of a playbook execution request */ + void reqExecResult(Map params, SvcLogicContext ctx) throws SvcLogicException; + + /* Method to get log of a playbook execution request */ + void reqExecLog(Map params, SvcLogicContext ctx) throws SvcLogicException; + + /* Method to get output of a playbook execution request */ + void reqExecOutput(Map params, SvcLogicContext ctx) throws SvcLogicException; +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/AnsibleAdapterPropertiesProvider.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/AnsibleAdapterPropertiesProvider.java new file mode 100755 index 000000000..6d9f4f12c --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/AnsibleAdapterPropertiesProvider.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * onap + * ================================================================================ + * Copyright (C) 2016 - 2017 ONAP + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ansible; + +import java.util.Properties; + +public interface AnsibleAdapterPropertiesProvider { + + public Properties getProperties(); +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/impl/AnsibleAdapterImpl.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/impl/AnsibleAdapterImpl.java new file mode 100644 index 000000000..2361feebd --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/impl/AnsibleAdapterImpl.java @@ -0,0 +1,460 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ansible.impl; + +import java.util.Map; +import java.util.Properties; +import org.apache.commons.lang.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.ccsdk.sli.adaptors.ansible.AnsibleAdapter; +import org.onap.ccsdk.sli.adaptors.ansible.AnsibleAdapterPropertiesProvider; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleMessageParser; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResultCodes; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleServerEmulator; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** + * This class implements the {@link AnsibleAdapter} interface. This interface defines the behaviors + * that our service provides. + */ +public class AnsibleAdapterImpl implements AnsibleAdapter { + + + /** + * The constant used to define the service name in the mapped diagnostic context + */ + @SuppressWarnings("nls") + public static final String MDC_SERVICE = "service"; + + /** + * The constant for the status code for a failed outcome + */ + @SuppressWarnings("nls") + public static final String OUTCOME_FAILURE = "failure"; + + /** + * The constant for the status code for a successful outcome + */ + @SuppressWarnings("nls") + public static final String OUTCOME_SUCCESS = "success"; + + /** + * Adapter Name + */ + private static final String ADAPTER_NAME = "Ansible Adapter"; + private static final String APPC_EXCEPTION_CAUGHT = "APPCException caught"; + + private static final String RESULT_CODE_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.result.code"; + private static final String MESSAGE_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.message"; + private static final String RESULTS_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.results"; + private static final String ID_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.Id"; + private static final String LOG_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.log"; + private static final String OUTPUT_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.output"; + + private static final String CLIENT_TYPE_PROPERTY_NAME = "org.onap.appc.adapter.ansible.clientType"; + private static final String TRUSTSTORE_PROPERTY_NAME = "org.onap.appc.adapter.ansible.trustStore"; + private static final String TRUSTPASSD_PROPERTY_NAME = "org.onap.appc.adapter.ansible.trustStore.trustPasswd"; + + private static final String PASSD = "Password"; + + /** + * The logger to be used + */ + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AnsibleAdapterImpl.class); + + + /** + * Connection object + **/ + private ConnectionBuilder httpClient; + + /** + * Ansible API Message Handlers + **/ + private AnsibleMessageParser messageProcessor; + + /** + * indicator whether in test mode + **/ + private boolean testMode = false; + + /** + * server emulator object to be used if in test mode + **/ + private AnsibleServerEmulator testServer; + + /** + * This default constructor is used as a work around because the activator wasn't getting called + */ + public AnsibleAdapterImpl() { + initialize(new AnsibleAdapterPropertiesProviderImpl()); + } + public AnsibleAdapterImpl(AnsibleAdapterPropertiesProvider propProvider) { + initialize(propProvider); + } + + /** + * Used for jUnit test and testing interface + */ + public AnsibleAdapterImpl(boolean mode) { + testMode = mode; + testServer = new AnsibleServerEmulator(); + messageProcessor = new AnsibleMessageParser(); + } + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + * @see org.onap.appc.adapter.rest.AnsibleAdapter#getAdapterName() + */ + @Override + public String getAdapterName() { + return ADAPTER_NAME; + } + + /** + * @param rc Method posts info to Context memory in case of an error and throws a + * SvcLogicException causing SLI to register this as a failure + */ + @SuppressWarnings("static-method") + private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException { + + svcLogic.setStatus(OUTCOME_FAILURE); + svcLogic.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code)); + svcLogic.setAttribute(MESSAGE_ATTRIBUTE_NAME, message); + + throw new SvcLogicException("Ansible Adapter Error = " + message); + } + + /** + * initialize the Ansible adapter based on default and over-ride configuration data + */ + private void initialize(AnsibleAdapterPropertiesProvider propProvider) { + + + Properties props = propProvider.getProperties(); + + // Create the message processor instance + messageProcessor = new AnsibleMessageParser(); + + // Create the http client instance + // type of client is extracted from the property file parameter + // org.onap.appc.adapter.ansible.clientType + // It can be : + // 1. TRUST_ALL (trust all SSL certs). To be used ONLY in dev + // 2. TRUST_CERT (trust only those whose certificates have been stored in the trustStore file) + // 3. DEFAULT (trust only well known certificates). This is standard behavior to which it will + // revert. To be used in PROD + + try { + String clientType = props.getProperty(CLIENT_TYPE_PROPERTY_NAME); + logger.info("Ansible http client type set to " + clientType); + + if ("TRUST_ALL".equals(clientType)) { + logger.info( + "Creating http client to trust ALL ssl certificates. WARNING. This should be done only in dev environments"); + httpClient = new ConnectionBuilder(1); + } else if ("TRUST_CERT".equals(clientType)) { + // set path to keystore file + String trustStoreFile = props.getProperty(TRUSTSTORE_PROPERTY_NAME); + String key = props.getProperty(TRUSTPASSD_PROPERTY_NAME); + char[] trustStorePasswd = key.toCharArray(); + logger.info("Creating http client with trustmanager from " + trustStoreFile); + httpClient = new ConnectionBuilder(trustStoreFile, trustStorePasswd); + } else { + logger.info("Creating http client with default behaviour"); + httpClient = new ConnectionBuilder(0); + } + } catch (Exception e) { + logger.error("Error Initializing Ansible Adapter due to Unknown Exception", e); + } + + logger.info("Initialized Ansible Adapter"); + } + + // Public Method to post request to execute playbook. Posts the following back + // to Svc context memory + // org.onap.appc.adapter.ansible.req.code : 100 if successful + // org.onap.appc.adapter.ansible.req.messge : any message + // org.onap.appc.adapter.ansible.req.Id : a unique uuid to reference the request + @Override + public void reqExec(Map params, SvcLogicContext ctx) throws SvcLogicException { + + String playbookName = StringUtils.EMPTY; + String payload = StringUtils.EMPTY; + String agentUrl = StringUtils.EMPTY; + String user = StringUtils.EMPTY; + String password = StringUtils.EMPTY; + String id = StringUtils.EMPTY; + + JSONObject jsonPayload; + + try { + // create json object to send request + jsonPayload = messageProcessor.reqMessage(params); + + agentUrl = (String) jsonPayload.remove("AgentUrl"); + user = (String) jsonPayload.remove("User"); + password = (String) jsonPayload.remove(PASSD); + id = jsonPayload.getString("Id"); + payload = jsonPayload.toString(); + logger.info("Updated Payload = " + payload); + } catch (SvcLogicException e) { + logger.error(APPC_EXCEPTION_CAUGHT, e); + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), + "Error constructing request for execution of playbook due to missing mandatory parameters. Reason = " + + e.getMessage()); + } catch (JSONException e) { + logger.error("JSONException caught", e); + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), + "Error constructing request for execution of playbook due to invalid JSON block. Reason = " + + e.getMessage()); + } catch (NumberFormatException e) { + logger.error("NumberFormatException caught", e); + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), + "Error constructing request for execution of playbook due to invalid parameter values. Reason = " + + e.getMessage()); + } + + int code = -1; + String message = StringUtils.EMPTY; + + try { + // post the test request + logger.info("Posting request = " + payload + " to url = " + agentUrl); + AnsibleResult testResult = postExecRequest(agentUrl, payload, user, password); + + // Process if HTTP was successful + if (testResult.getStatusCode() == 200) { + testResult = messageProcessor.parsePostResponse(testResult.getStatusMessage()); + } else { + doFailure(ctx, testResult.getStatusCode(), + "Error posting request. Reason = " + testResult.getStatusMessage()); + } + + code = testResult.getStatusCode(); + message = testResult.getStatusMessage(); + + // Check status of test request returned by Agent + if (code == AnsibleResultCodes.PENDING.getValue()) { + logger.info(String.format("Submission of Test %s successful.", playbookName)); + // test request accepted. We are in asynchronous case + } else { + doFailure(ctx, code, "Request for execution of playbook rejected. Reason = " + message); + } + } catch (SvcLogicException e) { + logger.error(APPC_EXCEPTION_CAUGHT, e); + doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), + "Exception encountered when posting request for execution of playbook. Reason = " + e.getMessage()); + } + + ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code)); + ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, message); + ctx.setAttribute(ID_ATTRIBUTE_NAME, id); + } + + /** + * Public method to query status of a specific request It blocks till the Ansible Server + * responds or the session times out (non-Javadoc) + * + * @see org.onap.ccsdk.sli.adaptors.ansible.AnsibleAdapter#reqExecResult(java.util.Map, + * org.onap.ccsdk.sli.core.sli.SvcLogicContext) + */ + @Override + public void reqExecResult(Map params, SvcLogicContext ctx) throws SvcLogicException { + + // Get URI + String reqUri = StringUtils.EMPTY; + + try { + reqUri = messageProcessor.reqUriResult(params); + logger.info("Got uri ", reqUri ); + } catch (SvcLogicException e) { + logger.error(APPC_EXCEPTION_CAUGHT, e); + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), + "Error constructing request to retrieve result due to missing parameters. Reason = " + + e.getMessage()); + return; + } catch (NumberFormatException e) { + logger.error("NumberFormatException caught", e); + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), + "Error constructing request to retrieve result due to invalid parameters value. Reason = " + + e.getMessage()); + return; + } + + int code = -1; + String message = StringUtils.EMPTY; + String results = StringUtils.EMPTY; + + try { + // Try to retrieve the test results (modify the URL for that) + AnsibleResult testResult = queryServer(reqUri, params.get("User"), params.get(PASSD)); + code = testResult.getStatusCode(); + message = testResult.getStatusMessage(); + + if (code == 200) { + logger.info("Parsing response from Server = " + message); + // Valid HTTP. process the Ansible message + testResult = messageProcessor.parseGetResponse(message); + code = testResult.getStatusCode(); + message = testResult.getStatusMessage(); + results = testResult.getResults(); + } + + logger.info("Request response = " + message); + } catch (SvcLogicException e) { + logger.error(APPC_EXCEPTION_CAUGHT, e); + doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), + "Exception encountered retrieving result : " + e.getMessage()); + return; + } + + // We were able to get and process the results. Determine if playbook succeeded + + if (code == AnsibleResultCodes.FINAL_SUCCESS.getValue()) { + message = String.format("Ansible Request %s finished with Result = %s, Message = %s", params.get("Id"), + OUTCOME_SUCCESS, message); + logger.info(message); + } else { + logger.info(String.format("Ansible Request %s finished with Result %s, Message = %s", params.get("Id"), + OUTCOME_FAILURE, message)); + ctx.setAttribute(RESULTS_ATTRIBUTE_NAME, results); + doFailure(ctx, code, message); + return; + } + + ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(400)); + ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, message); + ctx.setAttribute(RESULTS_ATTRIBUTE_NAME, results); + ctx.setStatus(OUTCOME_SUCCESS); + } + + /** + * Public method to get logs from playbook execution for a specific request + * + * It blocks till the Ansible Server responds or the session times out very similar to + * reqExecResult logs are returned in the DG context variable org.onap.appc.adapter.ansible.log + */ + @Override + public void reqExecLog(Map params, SvcLogicContext ctx) throws SvcLogicException { + + String reqUri = StringUtils.EMPTY; + try { + reqUri = messageProcessor.reqUriLog(params); + logger.info("Retrieving results from " + reqUri); + } catch (Exception e) { + logger.error("Exception caught", e); + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), e.getMessage()); + } + + String message = StringUtils.EMPTY; + try { + // Try to retrieve the test results (modify the url for that) + AnsibleResult testResult = queryServer(reqUri, params.get("User"), params.get(PASSD)); + message = testResult.getStatusMessage(); + logger.info("Request output = " + message); + ctx.setAttribute(LOG_ATTRIBUTE_NAME, message); + ctx.setStatus(OUTCOME_SUCCESS); + } catch (Exception e) { + logger.error("Exception caught", e); + doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), + "Exception encountered retreiving output : " + e.getMessage()); + } + } + + /** + * Public method to get output from playbook execution for a specific request + * + * It blocks till the Ansible Server responds or the session times out very similar to + * reqExecResult and output is returned in the DG context variable org.onap.appc.adapter.ansible.output + */ + @Override + public void reqExecOutput(Map params, SvcLogicContext ctx) throws SvcLogicException { + + String reqUri = StringUtils.EMPTY; + try { + reqUri = messageProcessor.reqUriOutput(params); + logger.info("Retrieving results from " + reqUri); + } catch (Exception e) { + logger.error("Exception caught", e); + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), e.getMessage()); + } + + String message = StringUtils.EMPTY; + try { + // Try to retrieve the test results (modify the url for that) + AnsibleResult testResult = queryServer(reqUri, params.get("User"), params.get(PASSD)); + message = testResult.getStatusMessage(); + logger.info("Request output = " + message); + ctx.setAttribute(OUTPUT_ATTRIBUTE_NAME, message); + ctx.setStatus(OUTCOME_SUCCESS); + } catch (Exception e) { + logger.error("Exception caught", e); + doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), + "Exception encountered retreiving output : " + e.getMessage()); + } + } + + /** + * Method that posts the request + */ + private AnsibleResult postExecRequest(String agentUrl, String payload, String user, String password) { + + AnsibleResult testResult; + + if (!testMode) { + httpClient.setHttpContext(user, password); + testResult = httpClient.post(agentUrl, payload); + } else { + testResult = testServer.Post(agentUrl, payload); + } + return testResult; + } + + /** + * Method to query Ansible server + */ + private AnsibleResult queryServer(String agentUrl, String user, String password) { + + AnsibleResult testResult; + + logger.info("Querying url = " + agentUrl); + + if (!testMode) { + testResult = httpClient.get(agentUrl); + } else { + testResult = testServer.Get(agentUrl); + } + + return testResult; + } +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/impl/AnsibleAdapterPropertiesProviderImpl.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/impl/AnsibleAdapterPropertiesProviderImpl.java new file mode 100755 index 000000000..482aaf8e5 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/impl/AnsibleAdapterPropertiesProviderImpl.java @@ -0,0 +1,191 @@ +/*- + * ============LICENSE_START======================================================= + * onap + * ================================================================================ + * Copyright (C) 2016 - 2017 ONAP + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ansible.impl; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Optional; +import java.util.Properties; +import java.util.Vector; +import org.onap.ccsdk.sli.adaptors.ansible.AnsibleAdapterPropertiesProvider; +import org.onap.ccsdk.sli.core.sli.ConfigurationException; +import org.onap.ccsdk.sli.core.utils.JREFileResolver; +import org.onap.ccsdk.sli.core.utils.KarafRootFileResolver; +import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; +import org.onap.ccsdk.sli.core.utils.common.CoreDefaultFileResolver; +import org.onap.ccsdk.sli.core.utils.common.SdncConfigEnvVarFileResolver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Responsible for determining the properties file to use and instantiating the + * SqlResource Service. The priority for properties file + * resolution is as follows: + * + *
    + *
  1. A directory identified by the system environment variable + * SDNC_CONFIG_DIR
  2. + *
  3. The default directory DEFAULT_DBLIB_PROP_DIR
  4. + *
  5. A directory identified by the JRE argument + * sql-resource.properties
  6. + *
  7. A sql-resource.properties file located in the karaf root + * directory
  8. + *
+ */ +public class AnsibleAdapterPropertiesProviderImpl implements AnsibleAdapterPropertiesProvider { + + private static final Logger LOG = LoggerFactory.getLogger(AnsibleAdapterPropertiesProviderImpl.class); + + /** + * The name of the properties file for database configuration + */ + private static final String ANSIBLEADAPTER_PROP_FILE_NAME = "ansible-adapter.properties"; + + /** + * A prioritized list of strategies for resolving sql-resource properties files. + */ + private Vector ansibleAdapterPropertiesFileResolvers = new Vector<>(); + + /** + * The configuration properties for the db connection. + */ + private Properties properties; + + /** + * Set up the prioritized list of strategies for resolving dblib properties + * files. + */ + public AnsibleAdapterPropertiesProviderImpl() { + ansibleAdapterPropertiesFileResolvers + .add(new SdncConfigEnvVarFileResolver("Using property file (1) from environment variable")); + ansibleAdapterPropertiesFileResolvers.add(new CoreDefaultFileResolver("Using property file (2) from default directory")); + + ansibleAdapterPropertiesFileResolvers.add( + new JREFileResolver("Using property file (3) from JRE argument", AnsibleAdapterPropertiesProviderImpl.class)); + ansibleAdapterPropertiesFileResolvers.add(new KarafRootFileResolver("Using property file (4) from karaf root", this)); + + // determines properties file as according to the priority described in the + // class header comment + final File propertiesFile = determinePropertiesFile(this); + if (propertiesFile != null) { + try (FileInputStream fileInputStream = new FileInputStream(propertiesFile)) { + properties = new Properties(); + properties.load(fileInputStream); + } catch (final IOException e) { + LOG.error("Failed to load properties for file: {}", propertiesFile.toString(), + new ConfigurationException("Failed to load properties for file: " + propertiesFile.toString(), + e)); + } + } else { + // Try to read properties as resource + + InputStream propStr = getClass().getResourceAsStream("/" + ANSIBLEADAPTER_PROP_FILE_NAME); + if (propStr != null) { + properties = new Properties(); + try { + properties.load(propStr); + propStr.close(); + } catch (IOException e) { + properties = null; + } + } + + } + + if (properties == null) { + reportFailure("Missing configuration properties resource(3)", new ConfigurationException( + "Missing configuration properties resource(3): " + ANSIBLEADAPTER_PROP_FILE_NAME)); + + LOG.info("Defaulting org.onap.appc.adapter.ansible.clientType to TRUST_ALL"); + + properties = new Properties(); + properties.setProperty("org.onap.appc.adapter.ansible.clientType", "TRUST_ALL"); + } + } + + /** + * Extract svclogic config properties. + * + * @return the svclogic config properties + */ + public Properties getProperties() { + return properties; + } + + /** + * Reports the method chosen for properties resolution to the + * Logger. + * + * @param message + * Some user friendly message + * @param fileOptional + * The file location of the chosen properties file + * @return the file location of the chosen properties file + */ + private static File reportSuccess(final String message, final Optional fileOptional) { + if (fileOptional.isPresent()) { + final File file = fileOptional.get(); + LOG.info("{} {}", message, file.getPath()); + return file; + } + return null; + } + + /** + * Reports fatal errors. This is the case in which no properties file could be + * found. + * + * @param message + * An appropriate fatal error message + * @param configurationException + * An exception describing what went wrong during resolution + */ + private static void reportFailure(final String message, final ConfigurationException configurationException) { + + LOG.error("{}", message, configurationException); + } + + /** + * Determines the sql-resource properties file to use based on the following priority: + *
    + *
  1. A directory identified by the system environment variable + * SDNC_CONFIG_DIR
  2. + *
  3. The default directory DEFAULT_DBLIB_PROP_DIR
  4. + *
  5. A directory identified by the JRE argument + * sql-resource.properties
  6. + *
  7. A sql-resource.properties file located in the karaf root + * directory
  8. + *
+ */ + File determinePropertiesFile(final AnsibleAdapterPropertiesProviderImpl resourceProvider) { + + for (final PropertiesFileResolver sliPropertiesFileResolver : ansibleAdapterPropertiesFileResolvers) { + final Optional fileOptional = sliPropertiesFileResolver.resolveFile(ANSIBLEADAPTER_PROP_FILE_NAME); + if (fileOptional.isPresent()) { + return reportSuccess(sliPropertiesFileResolver.getSuccessfulResolutionMessage(), fileOptional); + } + } + + return null; + } +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/impl/ConnectionBuilder.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/impl/ConnectionBuilder.java new file mode 100644 index 000000000..672e0df67 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/impl/ConnectionBuilder.java @@ -0,0 +1,205 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright © 2018 IBM. + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ansible.impl; + +import java.io.FileInputStream; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import javax.net.ssl.SSLContext; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContexts; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResultCodes; +import org.onap.ccsdk.sli.core.utils.PathValidator; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** + * Returns a custom http client + * - based on options + * - can create one with ssl using an X509 certificate that does NOT have a known CA + * - create one which trusts ALL SSL certificates + * - return default httpclient (which only trusts known CAs from default cacerts file for process) this is the default + * option + **/ + +public class ConnectionBuilder { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class); + + private CloseableHttpClient httpClient = null; + private HttpClientContext httpContext = new HttpClientContext(); + + /** + * Constructor that initializes an http client based on certificate + **/ + public ConnectionBuilder(String certFile) throws KeyStoreException, CertificateException, IOException, + KeyManagementException, NoSuchAlgorithmException { + + /* Point to the certificate */ + try(FileInputStream fs = new FileInputStream(certFile)){ + /* Generate a certificate from the X509 */ + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + X509Certificate cert = (X509Certificate) cf.generateCertificate(fs); + + /* Create a keystore object and load the certificate there */ + KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); + keystore.load(null, null); + keystore.setCertificateEntry("cacert", cert); + + SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build(); + SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, + SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); + + httpClient = HttpClients.custom().setSSLSocketFactory(factory).build(); + } + } + + /** + * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS + * file) + **/ + public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException, + KeyManagementException, NoSuchAlgorithmException, CertificateException { + + if (!PathValidator.isValidFilePath(trustStoreFile)) { + throw new IOException("Invalid trust store file path"); + } + + /* Load the specified trustStore */ + KeyStore keystore = KeyStore.getInstance("JKS"); + FileInputStream readStream = new FileInputStream(trustStoreFile); + keystore.load(readStream, trustStorePasswd); + + SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build(); + SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, + SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); + + httpClient = HttpClients.custom().setSSLSocketFactory(factory).build(); + } + + /** + * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1 or + * Default if Mode == 0 + */ + public ConnectionBuilder(int mode) + throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { + if (mode == 1) { + SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); + SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, + SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); + + httpClient = HttpClients.custom().setSSLSocketFactory(factory).build(); + } else { + httpClient = HttpClients.createDefault(); + } + } + + // Use to create an http context with auth headers + public void setHttpContext(String user, String myPassword) { + + // Are credential provided ? If so, set the context to be used + if (user != null && !user.isEmpty() && myPassword != null && !myPassword.isEmpty()) { + UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, myPassword); + AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); + BasicCredentialsProvider credsprovider = new BasicCredentialsProvider(); + credsprovider.setCredentials(authscope, credentials); + httpContext.setCredentialsProvider(credsprovider); + } + } + + // Method posts to the ansible server and writes out response to + // Ansible result object + public AnsibleResult post(String agentUrl, String payload) { + + AnsibleResult result = new AnsibleResult(); + try { + + HttpPost postObj = new HttpPost(agentUrl); + StringEntity bodyParams = new StringEntity(payload, "UTF-8"); + postObj.setEntity(bodyParams); + postObj.addHeader("Content-type", "application/json"); + + HttpResponse response = httpClient.execute(postObj, httpContext); + + HttpEntity entity = response.getEntity(); + String responseOutput = entity != null ? EntityUtils.toString(entity) : null; + int responseCode = response.getStatusLine().getStatusCode(); + result.setStatusCode(responseCode); + result.setStatusMessage(responseOutput); + } catch (IOException io) { + logger.error("Caught IOException", io); + result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue()); + result.setStatusMessage(io.getMessage()); + } + return result; + } + + // Method gets information from an Ansible server and writes out response to + // Ansible result object + + public AnsibleResult get(String agentUrl) { + + AnsibleResult result = new AnsibleResult(); + + try { + HttpGet getObj = new HttpGet(agentUrl); + HttpResponse response = httpClient.execute(getObj, httpContext); + + HttpEntity entity = response.getEntity(); + String responseOutput = entity != null ? EntityUtils.toString(entity) : null; + int responseCode = response.getStatusLine().getStatusCode(); + result.setStatusCode(responseCode); + result.setStatusMessage(responseOutput); + } catch (IOException io) { + result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue()); + result.setStatusMessage(io.getMessage()); + logger.error("Caught IOException", io); + } + return result; + } +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleMessageParser.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleMessageParser.java new file mode 100644 index 000000000..5f6342d94 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleMessageParser.java @@ -0,0 +1,332 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Modifications Copyright (C) 2018 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ansible.model; + +/** + * This module implements the APP-C/Ansible Server interface + * based on the REST API specifications + */ +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.google.common.base.Strings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Class that validates and constructs requests sent/received from + * Ansible Server + */ +public class AnsibleMessageParser { + + private static final String STATUS_MESSAGE_KEY = "StatusMessage"; + private static final String STATUS_CODE_KEY = "StatusCode"; + + private static final String PLAYBOOK_NAME_KEY = "PlaybookName"; + private static final String AGENT_URL_KEY = "AgentUrl"; + private static final String PASS_KEY = "Password"; + private static final String USER_KEY = "User"; + private static final String ID_KEY = "Id"; + + private static final String LOCAL_PARAMETERS_OPT_KEY = "LocalParameters"; + private static final String FILE_PARAMETERS_OPT_KEY = "FileParameters"; + private static final String ENV_PARAMETERS_OPT_KEY = "EnvParameters"; + private static final String NODE_LIST_OPT_KEY = "NodeList"; + private static final String TIMEOUT_OPT_KEY = "Timeout"; + private static final String VERSION_OPT_KEY = "Version"; + private static final String ACTION_OPT_KEY = "Action"; + + private String jsonException = "JSON exception"; + private static final Logger LOGGER = LoggerFactory.getLogger(AnsibleMessageParser.class); + + /** + * Accepts a map of strings and + * a) validates if all parameters are appropriate (else, throws an exception) and + * b) if correct returns a JSON object with appropriate key-value pairs to send to the server. + * + * Mandatory parameters, that must be in the supplied information to the Ansible Adapter + * 1. URL to connect to + * 2. credentials for URL (assume username password for now) + * 3. Playbook name + * + */ + public JSONObject reqMessage(Map params) throws SvcLogicException { + final String[] mandatoryTestParams = {AGENT_URL_KEY, PLAYBOOK_NAME_KEY, USER_KEY, PASS_KEY}; + final String[] optionalTestParams = {ENV_PARAMETERS_OPT_KEY, NODE_LIST_OPT_KEY, LOCAL_PARAMETERS_OPT_KEY, + TIMEOUT_OPT_KEY, VERSION_OPT_KEY, FILE_PARAMETERS_OPT_KEY, ACTION_OPT_KEY}; + + JSONObject jsonPayload = new JSONObject(); + + for (String key : mandatoryTestParams) { + throwIfMissingMandatoryParam(params, key); + jsonPayload.put(key, params.get(key)); + } + + parseOptionalParams(params, optionalTestParams, jsonPayload); + + // Generate a unique uuid for the test + String reqId = UUID.randomUUID().toString(); + jsonPayload.put(ID_KEY, reqId); + + return jsonPayload; + } + + /** + * Method that validates that the Map has enough information + * to query Ansible server for a result. If so, it returns + * the appropriate url, else an empty string. + */ + public String reqUriResult(Map params) throws SvcLogicException { + + final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY}; + + for (String key : mandatoryTestParams) { + throwIfMissingMandatoryParam(params, key); + } + return params.get(AGENT_URL_KEY) + "?Id=" + params.get(ID_KEY) + "&Type=GetResult"; + } + + /** + * Method that validates that the Map has enough information + * to query Ansible server for logs. If so, it populates the appropriate + * returns the appropriate url, else an empty string. + */ + public String reqUriLog(Map params) throws SvcLogicException { + + final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY}; + + for (String mandatoryParam : mandatoryTestParams) { + throwIfMissingMandatoryParam(params, mandatoryParam); + } + return params.get(AGENT_URL_KEY) + "?Id=" + params.get(ID_KEY) + "&Type=GetLog"; + } + + /** + * Method that validates that the Map has enough information + * to query Ansible server for an output. If so, it returns + * the appropriate url, else an empty string. + */ + public String reqUriOutput(Map params) throws SvcLogicException { + + final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY}; + + for (String mandatoryParam : mandatoryTestParams) { + throwIfMissingMandatoryParam(params, mandatoryParam); + } + return params.get(AGENT_URL_KEY) + "?Id=" + params.get(ID_KEY) + "&Type=GetOutput"; + } + + /** + * This method parses response from the Ansible Server when we do a post + * and returns an AnsibleResult object. + */ + public AnsibleResult parsePostResponse(String input) throws SvcLogicException { + AnsibleResult ansibleResult; + try { + JSONObject postResponse = new JSONObject(input); + + int code = postResponse.getInt(STATUS_CODE_KEY); + String msg = postResponse.getString(STATUS_MESSAGE_KEY); + + int initResponseValue = AnsibleResultCodes.INITRESPONSE.getValue(); + boolean validCode = AnsibleResultCodes.CODE.checkValidCode(initResponseValue, code); + if (!validCode) { + throw new SvcLogicException("Invalid InitResponse code = " + code + " received. MUST be one of " + + AnsibleResultCodes.CODE.getValidCodes(initResponseValue)); + } + + ansibleResult = new AnsibleResult(code, msg); + + } catch (JSONException e) { + LOGGER.error(jsonException, e); + ansibleResult = new AnsibleResult(600, "Error parsing response = " + input + ". Error = " + e.getMessage()); + } + return ansibleResult; + } + + /** + * This method parses response from an Ansible server when we do a GET for a result + * and returns an AnsibleResult object. + **/ + public AnsibleResult parseGetResponse(String input) throws SvcLogicException { + + AnsibleResult ansibleResult = new AnsibleResult(); + + try { + JSONObject postResponse = new JSONObject(input); + ansibleResult = parseGetResponseNested(ansibleResult, postResponse); + } catch (JSONException e) { + LOGGER.error(jsonException, e); + ansibleResult = new AnsibleResult(AnsibleResultCodes.INVALID_PAYLOAD.getValue(), + "Error parsing response = " + input + ". Error = " + e.getMessage(), ""); + } + return ansibleResult; + } + + private AnsibleResult parseGetResponseNested(AnsibleResult ansibleResult, JSONObject postRsp) throws SvcLogicException { + + int codeStatus = postRsp.getInt(STATUS_CODE_KEY); + String messageStatus = postRsp.getString(STATUS_MESSAGE_KEY); + int finalCode = AnsibleResultCodes.FINAL_SUCCESS.getValue(); + + boolean valCode = + AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.FINALRESPONSE.getValue(), codeStatus); + + if (!valCode) { + throw new SvcLogicException("Invalid FinalResponse code = " + codeStatus + " received. MUST be one of " + + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.FINALRESPONSE.getValue())); + } + + ansibleResult.setStatusCode(codeStatus); + ansibleResult.setStatusMessage(messageStatus); + LOGGER.info("Received response with code = {}, Message = {}", codeStatus, messageStatus); + + if (!postRsp.isNull("Results")) { + + // Results are available. process them + // Results is a dictionary of the form + + LOGGER.info("Processing results in response"); + JSONObject results = postRsp.getJSONObject("Results"); + LOGGER.info("Get JSON dictionary from Results .."); + Iterator hosts = results.keys(); + LOGGER.info("Iterating through hosts"); + + while (hosts.hasNext()) { + String host = hosts.next(); + LOGGER.info("Processing host = {}", host); + + try { + JSONObject hostResponse = results.getJSONObject(host); + int subCode = hostResponse.getInt(STATUS_CODE_KEY); + String message = hostResponse.getString(STATUS_MESSAGE_KEY); + + LOGGER.info("Code = {}, Message = {}", subCode, message); + + if (subCode != 200 || !("SUCCESS").equals(message)) { + finalCode = AnsibleResultCodes.REQ_FAILURE.getValue(); + } + } catch (JSONException e) { + LOGGER.error(jsonException, e); + ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue()); + ansibleResult.setStatusMessage(String.format( + "Error processing response message = %s from host %s", results.getString(host), host)); + break; + } + } + + ansibleResult.setStatusCode(finalCode); + + // We return entire Results object as message + ansibleResult.setResults(results.toString()); + + } else { + ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue()); + ansibleResult.setStatusMessage("Results not found in GET for response"); + } + return ansibleResult; + } + + private void parseOptionalParams(Map params, String[] optionalTestParams, JSONObject jsonPayload) { + + Set optionalParamsSet = new HashSet<>(); + Collections.addAll(optionalParamsSet, optionalTestParams); + + //@formatter:off + params.entrySet() + .stream() + .filter(entry -> optionalParamsSet.contains(entry.getKey())) + .filter(entry -> !Strings.isNullOrEmpty(entry.getValue())) + .forEach(entry -> parseOptionalParam(entry, jsonPayload)); + //@formatter:on + } + + private void parseOptionalParam(Map.Entry params, JSONObject jsonPayload) { + String key = params.getKey(); + String payload = params.getValue(); + + switch (key) { + case TIMEOUT_OPT_KEY: + int timeout = Integer.parseInt(payload); + if (timeout < 0) { + throw new NumberFormatException(" : specified negative integer for timeout = " + payload); + } + jsonPayload.put(key, payload); + break; + + case VERSION_OPT_KEY: + jsonPayload.put(key, payload); + break; + + case LOCAL_PARAMETERS_OPT_KEY: + case ENV_PARAMETERS_OPT_KEY: + JSONObject paramsJson = new JSONObject(payload); + jsonPayload.put(key, paramsJson); + break; + + case NODE_LIST_OPT_KEY: + JSONArray paramsArray = new JSONArray(payload); + jsonPayload.put(key, paramsArray); + break; + + case FILE_PARAMETERS_OPT_KEY: + jsonPayload.put(key, getFilePayload(payload)); + break; + + default: + break; + } + } + + /** + * Return payload with escaped newlines + */ + private JSONObject getFilePayload(String payload) { + String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r"); + return new JSONObject(formattedPayload); + } + + private void throwIfMissingMandatoryParam(Map params, String key) throws SvcLogicException { + if (!params.containsKey(key)) { + throw new SvcLogicException(String.format( + "Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", + key)); + } + if (Strings.isNullOrEmpty(params.get(key))) { + throw new SvcLogicException(String.format( + "Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", + key)); + } + } +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleResult.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleResult.java new file mode 100644 index 000000000..3d1b3cfab --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleResult.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ansible.model; + +/** + * Simple class to store code and message returned by POST/GET to an Ansible Server + */ +public class AnsibleResult { + + private static final String EMPTY_VALUE = "UNKNOWN"; + + private int statusCode; + private String statusMessage; + private String results; + + public AnsibleResult() { + this(-1, EMPTY_VALUE, EMPTY_VALUE); + } + + public AnsibleResult(int code, String message) { + this(code, message, EMPTY_VALUE); + } + + public AnsibleResult(int code, String message, String result) { + statusCode = code; + statusMessage = message; + results = result; + } + + public void setStatusCode(int code) { + this.statusCode = code; + } + + public void setStatusMessage(String message) { + this.statusMessage = message; + } + + public void setResults(String results) { + this.results = results; + } + + void set(int code, String message, String results) { + this.statusCode = code; + this.statusMessage = message; + this.results = results; + } + + public int getStatusCode() { + return this.statusCode; + } + + public String getStatusMessage() { + return this.statusMessage; + } + + public String getResults() { + return this.results; + } +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleResultCodes.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleResultCodes.java new file mode 100644 index 000000000..a529e4a0c --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleResultCodes.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ansible.model; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * enum of the various codes that APP-C uses to resolve different + * status of response from Ansible Server + **/ + +public enum AnsibleResultCodes { + + // @formatter:off + SUCCESS(400), + KEYSTORE_EXCEPTION(622), + CERTIFICATE_ERROR(610), + IO_EXCEPTION(611), + HOST_UNKNOWN(625), + USER_UNAUTHORIZED(613), + UNKNOWN_EXCEPTION(699), + SSL_EXCEPTION(697), + INVALID_PAYLOAD(698), + INVALID_RESPONSE(601), + PENDING(100), + REJECTED(101), + FINAL_SUCCESS(200), + REQ_FAILURE(401), + MESSAGE(1), + CODE(0), + INITRESPONSE(0), + FINALRESPONSE(1); + // @formatter:on + + private final Set initCodes = new HashSet<>(Arrays.asList(100, 101)); + private final Set finalCodes = new HashSet<>(Arrays.asList(200, 500)); + private final ArrayList> codeSets = new ArrayList<>(Arrays.asList(initCodes, finalCodes)); + private final Set messageSet = new HashSet<>(Arrays.asList("PENDING", "FINISHED", "TERMINATED")); + private final int value; + + AnsibleResultCodes(int value) { + this.value = value; + }; + + public int getValue() { + return value; + } + + public boolean checkValidCode(int type, int code) { + return codeSets.get(type).contains(code); + } + + public String getValidCodes(int type) { + StringBuilder sb = new StringBuilder("[ "); + codeSets.get(type).stream().forEach(s -> sb.append(s).append(",")); + return sb.append("]").toString(); + } + + public boolean checkValidMessage(String message) { + return messageSet.contains(message); + } + + public String getValidMessages() { + StringBuilder sb = new StringBuilder("[ "); + messageSet.stream().forEach(s -> sb.append(s).append(",")); + return sb.append("]").toString(); + } +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleServerEmulator.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleServerEmulator.java new file mode 100644 index 000000000..993c70062 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/ansible/model/AnsibleServerEmulator.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +/* + * Class to emulate responses from the Ansible Server that is compliant with the APP-C Ansible Server + * Interface. Used for jUnit tests to verify code is working. In tests it can be used + * as a replacement for methods from ConnectionBuilder class + */ + +package org.onap.ccsdk.sli.adaptors.ansible.model; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.apache.commons.lang.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class AnsibleServerEmulator { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(AnsibleServerEmulator.class); + + private static final String PLAYBOOK_NAME = "PlaybookName"; + private static final String STATUS_CODE = "StatusCode"; + private static final String STATUS_MESSAGE = "StatusMessage"; + + private String playbookName = "test_playbook.yaml"; + + /** + * Method that emulates the response from an Ansible Server + * when presented with a request to execute a playbook + * Returns an ansible object result. The response code is always the http code 200 (i.e connection successful) + * payload is json string as would be sent back by Ansible Server + **/ + public AnsibleResult Post(String agentUrl, String payload) { + AnsibleResult result = new AnsibleResult(); + + try { + // Request must be a JSON object + + JSONObject message = new JSONObject(payload); + if (message.isNull("Id")) { + rejectRequest(result, "Must provide a valid Id"); + } else if (message.isNull(PLAYBOOK_NAME)) { + rejectRequest(result, "Must provide a playbook Name"); + } else if (!message.getString(PLAYBOOK_NAME).equals(playbookName)) { + rejectRequest(result, "Playbook " + message.getString(PLAYBOOK_NAME) + " not found in catalog"); + } else { + acceptRequest(result); + } + } catch (JSONException e) { + logger.error("JSONException caught", e); + rejectRequest(result, e.getMessage()); + } + return result; + } + + /** + * Method to emulate response from an Ansible + * Server when presented with a GET request + * Returns an ansibl object result. The response code is always the http code 200 (i.e connection successful) + * payload is json string as would be sent back by Ansible Server + * + **/ + public AnsibleResult Get(String agentUrl) { + + Pattern pattern = Pattern.compile(".*?\\?Id=(.*?)&Type.*"); + Matcher matcher = pattern.matcher(agentUrl); + String id = StringUtils.EMPTY; + String vmAddress = "192.168.1.10"; + + if (matcher.find()) { + id = matcher.group(1); + } + + AnsibleResult getResult = new AnsibleResult(); + + JSONObject response = new JSONObject(); + response.put(STATUS_CODE, 200); + response.put(STATUS_MESSAGE, "FINISHED"); + + JSONObject results = new JSONObject(); + + JSONObject vmResults = new JSONObject(); + vmResults.put(STATUS_CODE, 200); + vmResults.put(STATUS_MESSAGE, "SUCCESS"); + vmResults.put("Id", id); + results.put(vmAddress, vmResults); + + response.put("Results", results); + + getResult.setStatusCode(200); + getResult.setStatusMessage(response.toString()); + + return getResult; + } + + private void rejectRequest(AnsibleResult result, String Message) { + result.setStatusCode(200); + JSONObject response = new JSONObject(); + response.put(STATUS_CODE, AnsibleResultCodes.REJECTED.getValue()); + response.put(STATUS_MESSAGE, Message); + result.setStatusMessage(response.toString()); + } + + private void acceptRequest(AnsibleResult result) { + result.setStatusCode(200); + JSONObject response = new JSONObject(); + response.put(STATUS_CODE, AnsibleResultCodes.PENDING.getValue()); + response.put(STATUS_MESSAGE, "PENDING"); + result.setStatusMessage(response.toString()); + } +} \ No newline at end of file diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/resources/OSGI-INF/blueprint/ansible-adapter-blueprint.xml b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/resources/OSGI-INF/blueprint/ansible-adapter-blueprint.xml new file mode 100755 index 000000000..d7be01e9d --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/resources/OSGI-INF/blueprint/ansible-adapter-blueprint.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + org.onap.ccsdk.sli.adaptors.ansible.AnsibleAdapter + + + + diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/resources/ansible-adapter.properties b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/resources/ansible-adapter.properties new file mode 100644 index 000000000..761758bbb --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/resources/ansible-adapter.properties @@ -0,0 +1,48 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# +# Default properties for the APP-C TestService Adapter +# +# ------------------------------------------------------------------------------------------------- +# +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded +# to supply configuration options +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=${user.home},/opt/opendaylight/current/properties + +appc.application.name=APPC + +# +# Define the message resource bundle name to be loaded +org.onap.appc.resources=org.onap/appc/i18n/MessageResources +# +# The name of the adapter. +org.onap.appc.provider.adaptor.name=org.onap.appc.appc_ansible_adapter + + +# Default truststore path and password +org.onap.appc.adapter.ansible.trustStore=/opt/opendaylight/tls-client/mykeystore.js +org.onap.appc.adapter.ansible.trustStore.trustPasswd=changeit +org.onap.appc.adapter.ansible.clientType=TRUST_ALL diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/resources/org/opendaylight/blueprint/ansible-adapter-blueprint.xml b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/resources/org/opendaylight/blueprint/ansible-adapter-blueprint.xml new file mode 100755 index 000000000..d7be01e9d --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/main/resources/org/opendaylight/blueprint/ansible-adapter-blueprint.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + org.onap.ccsdk.sli.adaptors.ansible.AnsibleAdapter + + + + diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterImpl.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterImpl.java new file mode 100644 index 000000000..4636d2450 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterImpl.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.adapter.ansible.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.adaptors.ansible.impl.AnsibleAdapterImpl; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + + +public class TestAnsibleAdapterImpl { + + private final String PENDING = "100"; + private final String SUCCESS = "400"; + private String message = "{\"Results\":{\"192.168.1.10\":{\"Id\":\"101\",\"StatusCode\":200,\"StatusMessage\":\"SUCCESS\"}},\"StatusCode\":200,\"StatusMessage\":\"FINISHED\"}"; + + private AnsibleAdapterImpl adapter; + private String TestId; + private boolean testMode = true; + private Map params; + private SvcLogicContext svcContext; + + + @Before + public void setup() throws IllegalArgumentException { + testMode = true; + svcContext = new SvcLogicContext(); + adapter = new AnsibleAdapterImpl(testMode); + + params = new HashMap<>(); + params.put("AgentUrl", "https://192.168.1.1"); + params.put("User", "test"); + params.put("Password", "test"); + } + + @After + public void tearDown() { + testMode = false; + adapter = null; + params = null; + svcContext = null; + } + + @Test + public void reqExec_shouldSetPending() throws IllegalStateException, IllegalArgumentException { + + params.put("PlaybookName", "test_playbook.yaml"); + + try { + adapter.reqExec(params, svcContext); + String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); + TestId = svcContext.getAttribute("org.onap.appc.adapter.ansible.result.Id"); + System.out.println("Comparing " + PENDING + " and " + status); + assertEquals(PENDING, status); + } catch (SvcLogicException e) { + String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); + fail(e.getMessage() + " Code = " + status); + } catch (Exception e) { + fail(e.getMessage() + " Unknown exception encountered "); + } + } + + @Test + public void reqExecResult_shouldSetSuccess() throws IllegalStateException, IllegalArgumentException { + + params.put("Id", "100"); + + for (String ukey : params.keySet()) { + System.out.println(String.format("Ansible Parameter %s = %s", ukey, params.get(ukey))); + } + + try { + adapter.reqExecResult(params, svcContext); + String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); + assertEquals(SUCCESS, status); + } catch (SvcLogicException e) { + String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); + fail(e.getMessage() + " Code = " + status); + } catch (Exception e) { + fail(e.getMessage() + " Unknown exception encountered "); + } + } + + @Test + public void reqExecLog_shouldSetMessage() throws IllegalStateException, IllegalArgumentException { + + params.put("Id", "101"); + + try { + adapter.reqExecLog(params, svcContext); + String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.log"); + assertEquals(message, status); + } catch (SvcLogicException e) { + String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.log"); + fail(e.getMessage() + " Code = " + status); + } catch (Exception e) { + fail(e.getMessage() + " Unknown exception encountered "); + } + } + + @Test + public void reqExecOutput_shouldSetMessage() throws IllegalStateException, IllegalArgumentException { + + params.put("Id", "101"); + + try { + adapter.reqExecOutput(params, svcContext); + String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.output"); + assertEquals(message, status); + } catch (SvcLogicException e) { + String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.output"); + fail(e.getMessage() + " Code = " + status); + } catch (Exception e) { + fail(e.getMessage() + " Unknown exception encountered "); + } + } +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterPropertiesProviderImpl.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterPropertiesProviderImpl.java new file mode 100644 index 000000000..b3c01e9bd --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterPropertiesProviderImpl.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * onap + * ================================================================================ + * Copyright (C) 2018 Samsung + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.adapter.ansible.impl; + +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.adaptors.ansible.impl.AnsibleAdapterPropertiesProviderImpl; + +import java.util.Properties; + +import static org.junit.Assert.assertEquals; + +public class TestAnsibleAdapterPropertiesProviderImpl { + AnsibleAdapterPropertiesProviderImpl adaptor; + @Before + public void setup() throws IllegalArgumentException { + adaptor = new AnsibleAdapterPropertiesProviderImpl(); + } + + + @Test + public void testGetProperties() throws IllegalStateException, IllegalArgumentException { + Properties prop = adaptor.getProperties(); + + System.out.println("All Property params : " + prop); + assertEquals("TRUST_ALL", prop.getProperty("org.onap.appc.adapter.ansible.clientType")); + assertEquals("org.onap.appc.appc_ansible_adapter", prop.getProperty("org.onap.appc.provider.adaptor.name")); + assertEquals("changeit", prop.getProperty("org.onap.appc.adapter.ansible.trustStore.trustPasswd")); + assertEquals("${user.home},/opt/opendaylight/current/properties", prop.getProperty("org.onap.appc.bootstrap.path")); + assertEquals("APPC", prop.getProperty("appc.application.name")); + assertEquals("appc.properties", prop.getProperty("org.onap.appc.bootstrap.file")); + assertEquals("org.onap/appc/i18n/MessageResources", prop.getProperty("org.onap.appc.resources")); + assertEquals("/opt/opendaylight/tls-client/mykeystore.js", prop.getProperty("org.onap.appc.adapter.ansible.trustStore")); + } +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestConnectionBuilder.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestConnectionBuilder.java new file mode 100644 index 000000000..c94655f56 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestConnectionBuilder.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * onap + * ================================================================================ + * Copyright (C) 2018 Samsung + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.adapter.ansible.impl; + +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.adaptors.ansible.impl.ConnectionBuilder; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +import javax.net.ssl.SSLException; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; + +import static org.junit.Assert.assertEquals; + +public class TestConnectionBuilder { + ConnectionBuilder builder; + @Before + public void setup() + throws SSLException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { + builder = new ConnectionBuilder(1); + } + + + @Test + public void testSetHttpContext() throws IllegalStateException, IllegalArgumentException { + String user = "testUser"; + String pass = "testPassword"; + + builder.setHttpContext(user, pass); + } + + @Test + public void testPost() throws IllegalStateException, IllegalArgumentException { + String user = "testUser"; + String pass = "testPassword"; + String agentUrl = "test/server.com"; + String payload = "testPayload"; + + builder.setHttpContext(user, pass); + AnsibleResult result = builder.post(agentUrl, payload); + + assertEquals(611, result.getStatusCode()); + assertEquals(null, result.getStatusMessage()); + assertEquals("UNKNOWN", result.getResults()); + } + + @Test + public void testGet() throws IllegalStateException, IllegalArgumentException { + String user = "testUser"; + String pass = "testPassword"; + String agentUrl = "test/server.com"; + + builder.setHttpContext(user, pass); + AnsibleResult result = builder.get(agentUrl); + + assertEquals(611, result.getStatusCode()); + assertEquals(null, result.getStatusMessage()); + assertEquals("UNKNOWN", result.getResults()); + } + + @Test + public void testGetMode() + throws SSLException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { + String user = "testUser"; + String pass = "testPassword"; + String agentUrl = "test/server.com"; + + builder = new ConnectionBuilder(2); + builder.setHttpContext(user, pass); + AnsibleResult result = builder.get(agentUrl); + + assertEquals(611, result.getStatusCode()); + assertEquals(null, result.getStatusMessage()); + assertEquals("UNKNOWN", result.getResults()); + } + + @Test (expected = FileNotFoundException.class) + public void testGetModeNoCert() + throws KeyStoreException, CertificateException, IOException, + KeyManagementException, NoSuchAlgorithmException, SvcLogicException { + String user = "testUser"; + String pass = "testPassword"; + String agentUrl = "test/server.com"; + String certFile = "testCert"; + + builder = new ConnectionBuilder(certFile); + builder.setHttpContext(user, pass); + AnsibleResult result = builder.get(agentUrl); + + assertEquals(611, result.getStatusCode()); + assertEquals(null, result.getStatusMessage()); + assertEquals("UNKNOWN", result.getResults()); + } + + @Test + public void testGetModeCert() + throws KeyStoreException, CertificateException, IOException, + KeyManagementException, NoSuchAlgorithmException, SvcLogicException { + String user = "testUser"; + String pass = "testPassword"; + String agentUrl = "test/server.com"; + String certFile = "src/test/resources/cert"; + + builder = new ConnectionBuilder(certFile); + builder.setHttpContext(user, pass); + AnsibleResult result = builder.get(agentUrl); + + assertEquals(611, result.getStatusCode()); + assertEquals(null, result.getStatusMessage()); + assertEquals("UNKNOWN", result.getResults()); + } + + @Test (expected = IOException.class) + public void testGetModeStore() + throws KeyStoreException, CertificateException, IOException, + KeyManagementException, NoSuchAlgorithmException, SvcLogicException { + String user = "testUser"; + String pass = "testPassword"; + String agentUrl = "test/server.com"; + String store = "src/test/resources/cert"; + + builder = new ConnectionBuilder(store, new char['t'] ); + builder.setHttpContext(user, pass); + AnsibleResult result = builder.get(agentUrl); + + assertEquals(611, result.getStatusCode()); + assertEquals(null, result.getStatusMessage()); + assertEquals("UNKNOWN", result.getResults()); + } + +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleAdapter.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleAdapter.java new file mode 100644 index 000000000..6fc90d012 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleAdapter.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ +package org.onap.ccsdk.adapter.ansible.model; + +import static org.junit.Assert.assertNotNull; + +import java.util.HashMap; +import java.util.Map; +import java.lang.reflect.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleMessageParser; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleServerEmulator; + +public class TestAnsibleAdapter { + + private Class[] parameterTypes; + private AnsibleMessageParser ansibleMessageParser; + private Method m; + private String name; + + @Test + public void callPrivateConstructorsMethodsForCodeCoverage() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { + + /* test constructors */ + Class[] classesOne = {AnsibleMessageParser.class}; + for(Class clazz : classesOne) { + Constructor constructor = clazz.getDeclaredConstructor(); + name = constructor.getName(); + constructor.setAccessible(true); + assertNotNull(constructor.newInstance()); + } + Class[] classesTwo = {AnsibleServerEmulator.class}; + for(Class clazz : classesTwo) { + Constructor constructor = clazz.getDeclaredConstructor(); + name = constructor.getName(); + constructor.setAccessible(true); + assertNotNull(constructor.newInstance()); + } + Class[] classesThree = {AnsibleResult.class}; + for(Class clazz : classesThree) { + Constructor constructor = clazz.getDeclaredConstructor(); + name = constructor.getName(); + constructor.setAccessible(true); + assertNotNull(constructor.newInstance()); + } + + /* test methods */ + ansibleMessageParser = new AnsibleMessageParser(); + parameterTypes = new Class[1]; + parameterTypes[0] = java.lang.String.class; + + m = ansibleMessageParser.getClass().getDeclaredMethod("getFilePayload", parameterTypes); + m.setAccessible(true); + assertNotNull(m.invoke(ansibleMessageParser,"{\"test\": test}")); + + } +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/ExecutorHarness.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/ExecutorHarness.java new file mode 100644 index 000000000..3555d7dfe --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/ExecutorHarness.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.ccsdk.test; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +/** + * This class is used as a test harness to wrap the call to an executor node. + */ + +public class ExecutorHarness { + + /** + * The executor to be tested + */ + private SvcLogicJavaPlugin executor; + + /** + * The collection of all exec methods found on the class + */ + private Map methods; + + /** + * The field of the class being tested that contains the reference to the logger to be used. This is modified to + * point to our interception logger for the test. + */ + private Field contextLogger; + + /** + * The interception logger that buffers all messages logged and allows us to look at them as part of the test case. + */ + private InterceptLogger logger; + + /** + * Create the harness and initialize it + * + * @throws SecurityException + * If a security manager, s, is present and any of the following conditions is met: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • + *
  • the caller's class loader is not the same as or an ancestor of the class loader for the current + * class and invocation of s.checkPackageAccess() denies access to the package of this class
  • + *
+ * @throws NoSuchFieldException + * if a field with the specified name is not found. + * @throws IllegalAccessException + * if this Field object is enforcing Java language access control and the underlying field is either + * inaccessible or final. + * @throws IllegalArgumentException + * if the specified object is not an instance of the class or interface declaring the underlying field + * (or a subclass or implementor thereof), or if an unwrapping conversion fails. + */ + @SuppressWarnings("nls") + public ExecutorHarness() throws NoSuchFieldException, SecurityException, IllegalArgumentException, + IllegalAccessException { + methods = new HashMap<>(); + new SvcLogicContext(); + + Class contextClass = SvcLogicContext.class; + contextLogger = contextClass.getDeclaredField("LOG"); + contextLogger.setAccessible(true); + logger = new InterceptLogger(); + contextLogger.set(null, logger); + } + + /** + * Convenience constructor + * + * @param executor + * The executor to be tested by the harness + * @throws SecurityException + * If a security manager, s, is present and any of the following conditions is met: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • + *
  • the caller's class loader is not the same as or an ancestor of the class loader for the current + * class and invocation of s.checkPackageAccess() denies access to the package of this class
  • + *
+ * @throws NoSuchFieldException + * if a field with the specified name is not found. + * @throws IllegalAccessException + * if this Field object is enforcing Java language access control and the underlying field is either + * inaccessible or final. + * @throws IllegalArgumentException + * if the specified object is not an instance of the class or interface declaring the underlying field + * (or a subclass or implementor thereof), or if an unwrapping conversion fails. + */ + public ExecutorHarness(SvcLogicJavaPlugin executor) throws NoSuchFieldException, SecurityException, + IllegalArgumentException, IllegalAccessException { + this(); + setExecutor(executor); + } + + /** + * @param executor + * The java plugin class to be executed + */ + public void setExecutor(SvcLogicJavaPlugin executor) { + this.executor = executor; + scanExecutor(); + } + + /** + * @return The java plugin class to be executed + */ + public SvcLogicJavaPlugin getExecutor() { + return executor; + } + + /** + * @return The set of all methods that meet the signature requirements + */ + public List getExecMethodNames() { + List names = new ArrayList<>(); + names.addAll(methods.keySet()); + return names; + } + + /** + * Returns an indication if the named method is a valid executor method that could be called from a DG execute node + * + * @param methodName + * The method name to be validated + * @return True if the method name meets the signature requirements, false if the method either does not exist or + * does not meet the requirements. + */ + public boolean isExecMethod(String methodName) { + return methods.containsKey(methodName); + } + + /** + * This method scans the executor class hierarchy to locate all methods that match the required signature of the + * executor and records these methods in a map. + */ + private void scanExecutor() { + methods.clear(); + Class executorClass = executor.getClass(); + Method[] publicMethods = executorClass.getMethods(); + for (Method method : publicMethods) { + if (method.getReturnType().equals(Void.class)) { + Class[] paramTypes = method.getParameterTypes(); + if (paramTypes.length == 2) { + if (Map.class.isAssignableFrom(paramTypes[0]) + && SvcLogicContext.class.isAssignableFrom(paramTypes[1])) { + methods.put(method.getName(), method); + } + } + } + } + } +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/InterceptLogger.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/InterceptLogger.java new file mode 100644 index 000000000..92235cb39 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/InterceptLogger.java @@ -0,0 +1,454 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.ccsdk.test; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Marker; + +import ch.qos.logback.classic.Level; + +/** + * This class is used as an intercept logger that can be used in testing to intercept and record all messages that are + * logged, thus allowing a junit test case to examine the log output and make assertions. + */ +public class InterceptLogger implements org.slf4j.Logger { + + /** + * This inner class represents an intercepted log event + */ + public class LogRecord { + private Level level; + private String message; + private long timestamp; + private Throwable t; + + public LogRecord(Level level, String message) { + setLevel(level); + setTimestamp(System.currentTimeMillis()); + setMessage(message); + } + + public LogRecord(Level level, String message, Throwable t) { + this(level, message); + setThrowable(t); + } + + /** + * @return the value of level + */ + public Level getLevel() { + return level; + } + + /** + * @return the value of message + */ + public String getMessage() { + return message; + } + + /** + * @return the value of timestamp + */ + public long getTimestamp() { + return timestamp; + } + + /** + * @param level + * the value for level + */ + public void setLevel(Level level) { + this.level = level; + } + + /** + * @param message + * the value for message + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * @param timestamp + * the value for timestamp + */ + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + /** + * @return the value of t + */ + public Throwable getThrowable() { + return t; + } + + /** + * @param t + * the value for t + */ + public void setThrowable(Throwable t) { + this.t = t; + } + + } + + /** + * The list of all intercepted log events + */ + private List events; + + /** + * Create the intercept logger + */ + public InterceptLogger() { + events = new ArrayList(1000); + } + + /** + * @return Returns all intercepted log events + */ + public List getLogRecords() { + return events; + } + + /** + * Clears all log events + */ + public void clear() { + events.clear(); + } + + @Override + public void debug(Marker marker, String msg) { + debug(msg); + } + + @Override + public void debug(Marker marker, String format, Object arg) { + debug(MessageFormat.format(format, arg)); + } + + @Override + public void debug(Marker marker, String format, Object... arguments) { + debug(MessageFormat.format(format, arguments)); + } + + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) { + debug(MessageFormat.format(format, arg1, arg2)); + } + + @Override + public void debug(Marker marker, String msg, Throwable t) { + debug(msg, t); + } + + @Override + public void debug(String msg) { + events.add(new LogRecord(Level.DEBUG, msg)); + } + + @Override + public void debug(String format, Object arg) { + events.add(new LogRecord(Level.DEBUG, MessageFormat.format(format, arg))); + } + + @Override + public void debug(String format, Object... arguments) { + events.add(new LogRecord(Level.DEBUG, MessageFormat.format(format, arguments))); + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + events.add(new LogRecord(Level.DEBUG, MessageFormat.format(format, arg1, arg2))); + } + + @Override + public void debug(String msg, Throwable t) { + events.add(new LogRecord(Level.DEBUG, msg, t)); + } + + @Override + public void error(Marker marker, String msg) { + error(msg); + } + + @Override + public void error(Marker marker, String format, Object arg) { + error(format, arg); + } + + @Override + public void error(Marker marker, String format, Object... arguments) { + error(format, arguments); + } + + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) { + error(format, arg1, arg2); + } + + @Override + public void error(Marker marker, String msg, Throwable t) { + events.add(new LogRecord(Level.ERROR, msg, t)); + } + + @Override + public void error(String msg) { + events.add(new LogRecord(Level.ERROR, msg)); + } + + @Override + public void error(String format, Object arg) { + events.add(new LogRecord(Level.ERROR, MessageFormat.format(format, arg))); + } + + @Override + public void error(String format, Object... arguments) { + events.add(new LogRecord(Level.ERROR, MessageFormat.format(format, arguments))); + } + + @Override + public void error(String format, Object arg1, Object arg2) { + events.add(new LogRecord(Level.ERROR, MessageFormat.format(format, arg1, arg2))); + } + + @Override + public void error(String msg, Throwable t) { + events.add(new LogRecord(Level.ERROR, msg, t)); + } + + @Override + public String getName() { + return null; + } + + @Override + public void info(Marker marker, String msg) { + info(msg); + } + + @Override + public void info(Marker marker, String format, Object arg) { + info(format, arg); + } + + @Override + public void info(Marker marker, String format, Object... arguments) { + info(format, arguments); + } + + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) { + info(format, arg1, arg2); + } + + @Override + public void info(Marker marker, String msg, Throwable t) { + events.add(new LogRecord(Level.INFO, msg, t)); + } + + @Override + public void info(String msg) { + events.add(new LogRecord(Level.INFO, msg)); + } + + @Override + public void info(String format, Object arg) { + events.add(new LogRecord(Level.INFO, MessageFormat.format(format, arg))); + } + + @Override + public void info(String format, Object... arguments) { + events.add(new LogRecord(Level.INFO, MessageFormat.format(format, arguments))); + } + + @Override + public void info(String format, Object arg1, Object arg2) { + events.add(new LogRecord(Level.INFO, MessageFormat.format(format, arg1, arg2))); + } + + @Override + public void info(String msg, Throwable t) { + events.add(new LogRecord(Level.INFO, msg, t)); + } + + @Override + public boolean isDebugEnabled() { + return true; + } + + @Override + public boolean isDebugEnabled(Marker marker) { + return true; + } + + @Override + public boolean isErrorEnabled() { + return true; + } + + @Override + public boolean isErrorEnabled(Marker marker) { + return true; + } + + @Override + public boolean isInfoEnabled() { + return true; + } + + @Override + public boolean isInfoEnabled(Marker marker) { + return true; + } + + @Override + public boolean isTraceEnabled() { + return true; + } + + @Override + public boolean isTraceEnabled(Marker marker) { + return true; + } + + @Override + public boolean isWarnEnabled() { + return true; + } + + @Override + public boolean isWarnEnabled(Marker marker) { + return true; + } + + @Override + public void trace(Marker marker, String msg) { + trace(msg); + } + + @Override + public void trace(Marker marker, String format, Object arg) { + trace(format, arg); + } + + @Override + public void trace(Marker marker, String format, Object... argArray) { + trace(format, argArray); + } + + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) { + trace(format, arg1, arg2); + } + + @Override + public void trace(Marker marker, String msg, Throwable t) { + trace(msg, t); + } + + @Override + public void trace(String msg) { + events.add(new LogRecord(Level.TRACE, msg)); + } + + @Override + public void trace(String format, Object arg) { + events.add(new LogRecord(Level.TRACE, MessageFormat.format(format, arg))); + } + + @Override + public void trace(String format, Object... arguments) { + events.add(new LogRecord(Level.TRACE, MessageFormat.format(format, arguments))); + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + events.add(new LogRecord(Level.TRACE, MessageFormat.format(format, arg1, arg2))); + } + + @Override + public void trace(String msg, Throwable t) { + events.add(new LogRecord(Level.TRACE, msg, t)); + } + + @Override + public void warn(Marker marker, String msg) { + warn(msg); + } + + @Override + public void warn(Marker marker, String format, Object arg) { + warn(format, arg); + } + + @Override + public void warn(Marker marker, String format, Object... arguments) { + warn(format, arguments); + } + + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) { + warn(format, arg1, arg2); + } + + @Override + public void warn(Marker marker, String msg, Throwable t) { + events.add(new LogRecord(Level.WARN, msg, t)); + } + + @Override + public void warn(String msg) { + events.add(new LogRecord(Level.WARN, msg)); + } + + @Override + public void warn(String format, Object arg) { + events.add(new LogRecord(Level.WARN, MessageFormat.format(format, arg))); + } + + @Override + public void warn(String format, Object... arguments) { + events.add(new LogRecord(Level.WARN, MessageFormat.format(format, arguments))); + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + events.add(new LogRecord(Level.WARN, MessageFormat.format(format, arg1, arg2))); + } + + @Override + public void warn(String msg, Throwable t) { + events.add(new LogRecord(Level.WARN, msg, t)); + } +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/resources/cert b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/resources/cert new file mode 100644 index 000000000..cc2921c4b --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/resources/cert @@ -0,0 +1,125 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 1 (0x1) + Signature Algorithm: sha1WithRSAEncryption + Issuer: C=FR, ST=Alsace, L=Strasbourg, O=www.freelan.org, OU=freelan, CN=Freelan Sample Certificate Authority/emailAddress=contact@freelan.org + Validity + Not Before: Apr 27 10:31:18 2012 GMT + Not After : Apr 25 10:31:18 2022 GMT + Subject: C=FR, ST=Alsace, O=www.freelan.org, OU=freelan, CN=alice/emailAddress=contact@freelan.org + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (4096 bit) + Modulus: + 00:dd:6d:bd:f8:80:fa:d7:de:1b:1f:a7:a3:2e:b2: + 02:e2:16:f6:52:0a:3c:bf:a6:42:f8:ca:dc:93:67: + 4d:60:c3:4f:8d:c3:8a:00:1b:f1:c4:4b:41:6a:69: + d2:69:e5:3f:21:8e:c5:0b:f8:22:37:ad:b6:2c:4b: + 55:ff:7a:03:72:bb:9a:d3:ec:96:b9:56:9f:cb:19: + 99:c9:32:94:6f:8f:c6:52:06:9f:45:03:df:fd:e8: + 97:f6:ea:d6:ba:bb:48:2b:b5:e0:34:61:4d:52:36: + 0f:ab:87:52:25:03:cf:87:00:87:13:f2:ca:03:29: + 16:9d:90:57:46:b5:f4:0e:ae:17:c8:0a:4d:92:ed: + 08:a6:32:23:11:71:fe:f2:2c:44:d7:6c:07:f3:0b: + 7b:0c:4b:dd:3b:b4:f7:37:70:9f:51:b6:88:4e:5d: + 6a:05:7f:8d:9b:66:7a:ab:80:20:fe:ee:6b:97:c3: + 49:7d:78:3b:d5:99:97:03:75:ce:8f:bc:c5:be:9c: + 9a:a5:12:19:70:f9:a4:bd:96:27:ed:23:02:a7:c7: + 57:c9:71:cf:76:94:a2:21:62:f6:b8:1d:ca:88:ee: + 09:ad:46:2f:b7:61:b3:2c:15:13:86:9f:a5:35:26: + 5a:67:f4:37:c8:e6:80:01:49:0e:c7:ed:61:d3:cd: + bc:e4:f8:be:3f:c9:4e:f8:7d:97:89:ce:12:bc:ca: + b5:c6:d2:e0:d9:b3:68:3c:2e:4a:9d:b4:5f:b8:53: + ee:50:3d:bf:dd:d4:a2:8a:b6:a0:27:ab:98:0c:b3: + b2:58:90:e2:bc:a1:ad:ff:bd:8e:55:31:0f:00:bf: + 68:e9:3d:a9:19:9a:f0:6d:0b:a2:14:6a:c6:4c:c6: + 4e:bd:63:12:a5:0b:4d:97:eb:42:09:79:53:e2:65: + aa:24:34:70:b8:c1:ab:23:80:e7:9c:6c:ed:dc:82: + aa:37:04:b8:43:2a:3d:2a:a8:cc:20:fc:27:5d:90: + 26:58:f9:b7:14:e2:9e:e2:c1:70:73:97:e9:6b:02: + 8e:d3:52:59:7b:00:ec:61:30:f1:56:3f:9c:c1:7c: + 05:c5:b1:36:c8:18:85:cf:61:40:1f:07:e8:a7:06: + 87:df:9a:77:0b:a9:64:72:03:f6:93:fc:e0:02:59: + c1:96:ec:c0:09:42:3e:30:a2:7f:1b:48:2f:fe:e0: + 21:8f:53:87:25:0d:cb:ea:49:f5:4a:9b:d0:e3:5f: + ee:78:18:e5:ba:71:31:a9:04:98:0f:b1:ad:67:52: + a0:f2:e3:9c:ab:6a:fe:58:84:84:dd:07:3d:32:94: + 05:16:45:15:96:59:a0:58:6c:18:0e:e3:77:66:c7: + b3:f7:99 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: + CA:FALSE + Netscape Comment: + OpenSSL Generated Certificate + X509v3 Subject Key Identifier: + 59:5F:C9:13:BA:1B:CC:B9:A8:41:4A:8A:49:79:6A:36:F6:7D:3E:D7 + X509v3 Authority Key Identifier: + keyid:23:6C:2D:3D:3E:29:5D:78:B8:6C:3E:AA:E2:BB:2E:1E:6C:87:F2:53 + + Signature Algorithm: sha1WithRSAEncryption + 13:e7:02:45:3e:a7:ab:bd:b8:da:e7:ef:74:88:ac:62:d5:dd: + 10:56:d5:46:07:ec:fa:6a:80:0c:b9:62:be:aa:08:b4:be:0b: + eb:9a:ef:68:b7:69:6f:4d:20:92:9d:18:63:7a:23:f4:48:87: + 6a:14:c3:91:98:1b:4e:08:59:3f:91:80:e9:f4:cf:fd:d5:bf: + af:4b:e4:bd:78:09:71:ac:d0:81:e5:53:9f:3e:ac:44:3e:9f: + f0:bf:5a:c1:70:4e:06:04:ef:dc:e8:77:05:a2:7d:c5:fa:80: + 58:0a:c5:10:6d:90:ca:49:26:71:84:39:b7:9a:3e:e9:6f:ae: + c5:35:b6:5b:24:8c:c9:ef:41:c3:b1:17:b6:3b:4e:28:89:3c: + 7e:87:a8:3a:a5:6d:dc:39:03:20:20:0b:c5:80:a3:79:13:1e: + f6:ec:ae:36:df:40:74:34:87:46:93:3b:a3:e0:a4:8c:2f:43: + 4c:b2:54:80:71:76:78:d4:ea:12:28:d8:f2:e3:80:55:11:9b: + f4:65:dc:53:0e:b4:4c:e0:4c:09:b4:dc:a0:80:5c:e6:b5:3b: + 95:d3:69:e4:52:3d:5b:61:86:02:e5:fd:0b:00:3a:fa:b3:45: + cc:c9:a3:64:f2:dc:25:59:89:58:0d:9e:6e:28:3a:55:45:50: + 5f:88:67:2a:d2:e2:48:cc:8b:de:9a:1b:93:ae:87:e1:f2:90: + 50:40:d9:0f:44:31:53:46:ad:62:4e:8d:48:86:19:77:fc:59: + 75:91:79:35:59:1d:e3:4e:33:5b:e2:31:d7:ee:52:28:5f:0a: + 70:a7:be:bb:1c:03:ca:1a:18:d0:f5:c1:5b:9c:73:04:b6:4a: + e8:46:52:58:76:d4:6a:e6:67:1c:0e:dc:13:d0:61:72:a0:92: + cb:05:97:47:1c:c1:c9:cf:41:7d:1f:b1:4d:93:6b:53:41:03: + 21:2b:93:15:63:08:3e:2c:86:9e:7b:9f:3a:09:05:6a:7d:bb: + 1c:a7:b7:af:96:08:cb:5b:df:07:fb:9c:f2:95:11:c0:82:81: + f6:1b:bf:5a:1e:58:cd:28:ca:7d:04:eb:aa:e9:29:c4:82:51: + 2c:89:61:95:b6:ed:a5:86:7c:7c:48:1d:ec:54:96:47:79:ea: + fc:7f:f5:10:43:0a:9b:00:ef:8a:77:2e:f4:36:66:d2:6a:a6: + 95:b6:9f:23:3b:12:e2:89:d5:a4:c1:2c:91:4e:cb:94:e8:3f: + 22:0e:21:f9:b8:4a:81:5c:4c:63:ae:3d:05:b2:5c:5c:54:a7: + 55:8f:98:25:55:c4:a6:90:bc:19:29:b1:14:d4:e2:b0:95:e4: + ff:89:71:61:be:8a:16:85 +-----BEGIN CERTIFICATE----- +MIIGJzCCBA+gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBsjELMAkGA1UEBhMCRlIx +DzANBgNVBAgMBkFsc2FjZTETMBEGA1UEBwwKU3RyYXNib3VyZzEYMBYGA1UECgwP +d3d3LmZyZWVsYW4ub3JnMRAwDgYDVQQLDAdmcmVlbGFuMS0wKwYDVQQDDCRGcmVl +bGFuIFNhbXBsZSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkxIjAgBgkqhkiG9w0BCQEW +E2NvbnRhY3RAZnJlZWxhbi5vcmcwHhcNMTIwNDI3MTAzMTE4WhcNMjIwNDI1MTAz +MTE4WjB+MQswCQYDVQQGEwJGUjEPMA0GA1UECAwGQWxzYWNlMRgwFgYDVQQKDA93 +d3cuZnJlZWxhbi5vcmcxEDAOBgNVBAsMB2ZyZWVsYW4xDjAMBgNVBAMMBWFsaWNl +MSIwIAYJKoZIhvcNAQkBFhNjb250YWN0QGZyZWVsYW4ub3JnMIICIjANBgkqhkiG +9w0BAQEFAAOCAg8AMIICCgKCAgEA3W29+ID6194bH6ejLrIC4hb2Ugo8v6ZC+Mrc +k2dNYMNPjcOKABvxxEtBamnSaeU/IY7FC/giN622LEtV/3oDcrua0+yWuVafyxmZ +yTKUb4/GUgafRQPf/eiX9urWurtIK7XgNGFNUjYPq4dSJQPPhwCHE/LKAykWnZBX +RrX0Dq4XyApNku0IpjIjEXH+8ixE12wH8wt7DEvdO7T3N3CfUbaITl1qBX+Nm2Z6 +q4Ag/u5rl8NJfXg71ZmXA3XOj7zFvpyapRIZcPmkvZYn7SMCp8dXyXHPdpSiIWL2 +uB3KiO4JrUYvt2GzLBUThp+lNSZaZ/Q3yOaAAUkOx+1h08285Pi+P8lO+H2Xic4S +vMq1xtLg2bNoPC5KnbRfuFPuUD2/3dSiiragJ6uYDLOyWJDivKGt/72OVTEPAL9o +6T2pGZrwbQuiFGrGTMZOvWMSpQtNl+tCCXlT4mWqJDRwuMGrI4DnnGzt3IKqNwS4 +Qyo9KqjMIPwnXZAmWPm3FOKe4sFwc5fpawKO01JZewDsYTDxVj+cwXwFxbE2yBiF +z2FAHwfopwaH35p3C6lkcgP2k/zgAlnBluzACUI+MKJ/G0gv/uAhj1OHJQ3L6kn1 +SpvQ41/ueBjlunExqQSYD7GtZ1Kg8uOcq2r+WISE3Qc9MpQFFkUVllmgWGwYDuN3 +Zsez95kCAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT +TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFFlfyRO6G8y5qEFKikl5 +ajb2fT7XMB8GA1UdIwQYMBaAFCNsLT0+KV14uGw+quK7Lh5sh/JTMA0GCSqGSIb3 +DQEBBQUAA4ICAQAT5wJFPqervbja5+90iKxi1d0QVtVGB+z6aoAMuWK+qgi0vgvr +mu9ot2lvTSCSnRhjeiP0SIdqFMORmBtOCFk/kYDp9M/91b+vS+S9eAlxrNCB5VOf +PqxEPp/wv1rBcE4GBO/c6HcFon3F+oBYCsUQbZDKSSZxhDm3mj7pb67FNbZbJIzJ +70HDsRe2O04oiTx+h6g6pW3cOQMgIAvFgKN5Ex727K4230B0NIdGkzuj4KSML0NM +slSAcXZ41OoSKNjy44BVEZv0ZdxTDrRM4EwJtNyggFzmtTuV02nkUj1bYYYC5f0L +ADr6s0XMyaNk8twlWYlYDZ5uKDpVRVBfiGcq0uJIzIvemhuTrofh8pBQQNkPRDFT +Rq1iTo1Ihhl3/Fl1kXk1WR3jTjNb4jHX7lIoXwpwp767HAPKGhjQ9cFbnHMEtkro +RlJYdtRq5mccDtwT0GFyoJLLBZdHHMHJz0F9H7FNk2tTQQMhK5MVYwg+LIaee586 +CQVqfbscp7evlgjLW98H+5zylRHAgoH2G79aHljNKMp9BOuq6SnEglEsiWGVtu2l +hnx8SB3sVJZHeer8f/UQQwqbAO+Kdy70NmbSaqaVtp8jOxLiidWkwSyRTsuU6D8i +DiH5uEqBXExjrj0FslxcVKdVj5glVcSmkLwZKbEU1OKwleT/iXFhvooWhQ== +-----END CERTIFICATE----- diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/resources/org/onap/ccsdk/default.properties b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/resources/org/onap/ccsdk/default.properties new file mode 100644 index 000000000..2f8fb4585 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/resources/org/onap/ccsdk/default.properties @@ -0,0 +1,111 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# +# Default properties for the APP-C Provider Adapter +# +# ------------------------------------------------------------------------------------------------- +# +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded +# to supply configuration options +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/onap/appc/data/properties,${user.home},. + +appc.application.name=APPC + +# +# Define the message resource bundle name to be loaded +org.onap.appc.resources=org/onap/appc/i18n/MessageResources +# +# The name of the adapter. +org.onap.appc.provider.adaptor.name=org.onap.appc.appc_provider_adapter +# +# Set up the logging environment +# +org.onap.appc.logging.file=org/onap/appc/logback.xml +org.onap.appc.logging.path=${user.home};etc;../etc +org.onap.appc.logger=org.onap.appc +org.onap.appc.security.logger=org.onap.appc.security +# +# The minimum and maximum provider/tenant context pool sizes. Min=1 means that as soon +# as the provider/tenant is referenced a Context is opened and added to the pool. Max=0 +# means that the upper bound on the pool is unbounded. +org.onap.appc.provider.min.pool=1 +org.onap.appc.provider.max.pool=0 + +# +# The following properties are used to configure the retry logic for connection to the +# IaaS provider(s). The retry delay property is the amount of time, in seconds, the +# application waits between retry attempts. The retry limit is the number of retries +# that are allowed before the request is failed. +org.onap.appc.provider.retry.delay = 30 +org.onap.appc.provider.retry.limit = 10 + +# +# The trusted hosts list for SSL access when a certificate is not provided. +# +provider.trusted.hosts=* +# +# The amount of time, in seconds, to wait for a server state change (start->stop, stop->start, etc). +# If the server does not change state to a valid state within the alloted time, the operation +# fails. +org.onap.appc.server.state.change.timeout=300 +# +# The amount of time to wait, in seconds, between subsequent polls to the OpenStack provider +# to refresh the status of a resource we are waiting on. +# +org.onap.appc.openstack.poll.interval=20 +# +# The connection information to connect to the provider we are using. These properties +# are "structured" properties, in that the name is a compound name, where the nodes +# of the name can be ordered (1, 2, 3, ...). All of the properties with the same ordinal +# position are defining the same entity. For example, provider1.type and provider1.name +# are defining the same provider, whereas provider2.name and provider2.type are defining +# the values for a different provider. Any number of providers can be defined in this +# way. +# + +# Don't change these 2 right now since they are hard coded in the DG +#provider1.type=appc +#provider1.name=appc + +#These you can change +#provider1.identity=appc +#provider1.tenant1.name=appc +#provider1.tenant1.userid=appc +#provider1.tenant1.password=appc + +# After a change to the provider make sure to recheck these values with an api call to provider1.identity/tokens +test.expected-regions=1 +test.expected-endpoints=1 + +#Your OpenStack IP +#test.ip=192.168.1.2 +# Your OpenStack Platform's Keystone Port (default is 5000) +#test.port=5000 +#test.tenantid=abcde12345fghijk6789lmnopq123rst +#test.vmid=abc12345-1234-5678-890a-abcdefg12345 +# Port 8774 below is default port for OpenStack's Nova API Service +#test.url=http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345 + diff --git a/adaptors/ansible-adapter/ansible-adapter-installer/pom.xml b/adaptors/ansible-adapter/ansible-adapter-installer/pom.xml new file mode 100644 index 000000000..af02a8c5c --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-installer/pom.xml @@ -0,0 +1,151 @@ + + + + + 4.0.0 + + + org.onap.ccsdk.parent + odlparent-lite + 2.1.0 + + + + org.onap.ccsdk.sli.adaptors + ansible-adapter-installer + 1.1.1-SNAPSHOT + pom + + ccsdk-sli-adaptors :: ansible-adapter :: ${project.artifactId} + + + ccsdk-ansible-adapter + ${application.name} + mvn:org.onap.ccsdk.sli.adaptors/${features.boot}/${project.version}/xml/features + false + + + + + + org.onap.ccsdk.sli.adaptors + ansible-adapter-bundle + ${project.version} + + + + + + + + + maven-assembly-plugin + + + maven-repo-zip + + single + + package + + true + true + stage/${application.name}-${project.version} + + src/assembly/assemble_mvnrepo_zip.xml + + + + + installer-zip + + single + + package + + false + true + ${application.name}-${project.version} + + src/assembly/assemble_installer_zip.xml + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + + copy-dependencies + + prepare-package + + false + ${project.build.directory}/assembly/system + false + true + true + true + false + false + org.onap.ccsdk.sli.adaptors + + provided + + + + + + maven-resources-plugin + + + copy-version + + copy-resources + + + validate + + ${basedir}/target/stage + + + src/main/resources/scripts + + install-feature.sh + + true + + + + + + + + + diff --git a/adaptors/ansible-adapter/ansible-adapter-installer/src/assembly/assemble_installer_zip.xml b/adaptors/ansible-adapter/ansible-adapter-installer/src/assembly/assemble_installer_zip.xml new file mode 100644 index 000000000..322fa76eb --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-installer/src/assembly/assemble_installer_zip.xml @@ -0,0 +1,62 @@ + + + + + + adapter + + zip + + + + false + + + + target/stage/ + ${application.name} + 755 + + *.sh + + + + target/stage/ + ${application.name} + 644 + + *.sh + + + + + + + diff --git a/adaptors/ansible-adapter/ansible-adapter-installer/src/assembly/assemble_mvnrepo_zip.xml b/adaptors/ansible-adapter/ansible-adapter-installer/src/assembly/assemble_mvnrepo_zip.xml new file mode 100644 index 000000000..ec65e79e1 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-installer/src/assembly/assemble_mvnrepo_zip.xml @@ -0,0 +1,50 @@ + + + + + + repo + + zip + + + + false + + + + target/assembly/ + . + + + + + + diff --git a/adaptors/ansible-adapter/ansible-adapter-installer/src/main/resources/scripts/install-feature.sh b/adaptors/ansible-adapter/ansible-adapter-installer/src/main/resources/scripts/install-feature.sh new file mode 100644 index 000000000..c8214c520 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-installer/src/main/resources/scripts/install-feature.sh @@ -0,0 +1,42 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +#!/bin/bash + +ODL_HOME=${ODL_HOME:-/opt/opendaylight/current} +ODL_KARAF_CLIENT=${ODL_KARAF_CLIENT:-${ODL_HOME}/bin/client} +INSTALLERDIR=$(dirname $0) + +REPOZIP=${INSTALLERDIR}/${features.boot}-${project.version}.zip + +if [ -f ${REPOZIP} ] +then + unzip -n -d ${ODL_HOME} ${REPOZIP} +else + echo "ERROR : repo zip ($REPOZIP) not found" + exit 1 +fi + +${ODL_KARAF_CLIENT} feature:repo-add ${features.repositories} +${ODL_KARAF_CLIENT} feature:install ${features.boot} diff --git a/adaptors/ansible-adapter/pom.xml b/adaptors/ansible-adapter/pom.xml new file mode 100644 index 000000000..3414e7cf3 --- /dev/null +++ b/adaptors/ansible-adapter/pom.xml @@ -0,0 +1,191 @@ + + + + + 4.0.0 + + + org.onap.ccsdk.parent + odlparent-lite + 2.1.0 + + + + org.onap.ccsdk.sli.adaptors + ansible-adaptor + 1.1.1-SNAPSHOT + pom + + ccsdk-sli-adaptors :: ansible-adapter + Abstractions to interact with Ansible server via REST + + + ansible-adapter-bundle + ansible-adapter-installer + + + + + + + org.onap.appc + ansible-adapter-features + ${project.version} + xml + features + + + + org.onap.appc + ansible-adapter-provider + ${project.version} + + + + + + + + + + + + JCenter + JCenter Repository + http://jcenter.bintray.com + + + + + + + + + + + + + + + + maven-javadoc-plugin + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.antlr + antlr4 + ${antlr.version} + + + org.antlr + antlr4-runtime + 4.3 + + + + + + + javadoc-no-fork + test-javadoc-no-fork + + + + aggregate + + aggregate + test-aggregate + + + + + + org.apache.maven.plugins + maven-jxr-plugin + 2.3 + + + aggregate + + aggregate + test-aggregate + + + + + + + maven-surefire-plugin + + + + org.apache.maven.plugins + maven-changelog-plugin + 2.3 + + + dual-report + + range + 30 + + + changelog + file-activity + + + + + + + org.codehaus.mojo + taglist-maven-plugin + 2.4 + + + + + -- cgit 1.2.3-korg