summaryrefslogtreecommitdiffstats
path: root/adapters/mso-adapter-utils/src
diff options
context:
space:
mode:
Diffstat (limited to 'adapters/mso-adapter-utils/src')
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/adapters/vdu/VduPlugin.java202
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/audit/beans/AuditInventory.java96
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfig.java79
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfigIdentityMapper.java6
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java89
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneAuthHolder.java53
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java141
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/ServiceEndpointNotFoundException.java8
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/models/RackspaceAuthentication.java144
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfo.java19
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java36
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentStatus.java6
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoBlueprintAlreadyExists.java15
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyException.java100
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyManagerNotFound.java14
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeout.java64
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java46
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoDeploymentAlreadyExists.java15
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java1846
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/config/beans/PoConfig.java85
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/HeatCacheEntry.java16
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/NeutronCacheEntry.java55
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/VnfRollback.java408
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java399
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java408
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameter.java97
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java129
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java2257
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java400
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java417
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java53
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java559
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java943
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java26
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java48
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java91
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java9
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java9
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java12
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java7
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java15
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java70
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java32
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java147
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java22
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java130
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java14
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java21
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java56
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java34
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java151
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java25
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java55
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java38
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java36
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java36
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java35
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java530
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java22
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java62
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java46
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java55
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java50
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java25
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java123
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java288
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java33
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java58
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java60
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java286
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java298
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java212
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java33
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java120
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java69
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java5
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java135
-rw-r--r--adapters/mso-adapter-utils/src/test/resources/application-test.yaml4
78 files changed, 6361 insertions, 6477 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/adapters/vdu/VduPlugin.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/adapters/vdu/VduPlugin.java
index ff30c0ee70..bc2757b41c 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/adapters/vdu/VduPlugin.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/adapters/vdu/VduPlugin.java
@@ -21,27 +21,22 @@
package org.onap.so.adapters.vdu;
/**
- * This interface defines a common API for template-based cloud deployments.
- * The methods here should be adaptable for Openstack (Heat), Cloudify (TOSCA),
- * Aria (TOSCA), Multi-VIM (TBD), and others (e.g. Azure Resource Manager).
+ * This interface defines a common API for template-based cloud deployments. The methods here should be adaptable for
+ * Openstack (Heat), Cloudify (TOSCA), Aria (TOSCA), Multi-VIM (TBD), and others (e.g. Azure Resource Manager).
*
- * The deployed instances are referred to here as Virtual Deployment Units (VDUs).
- * The package of templates that define a give VDU is referred to as its blueprint.
+ * The deployed instances are referred to here as Virtual Deployment Units (VDUs). The package of templates that define
+ * a give VDU is referred to as its blueprint.
*
- * Template-based orchestrators all follow a similar template/blueprint model.
- * - One main template that is the top level definition
- * - Optional nested templates referenced/included by the main template
- * - Optional files attached to the template package, typically containing
- * configuration files, install scripts, orchestration scripts, etc.
- *
- * The main template also defines the required inputs for creating a new instance,
- * and output values exposed by successfully deployed instances. Inputs and outputs
- * may include simple or complex (JSON) data types.
- *
- * Each implementation of this interface is expected to understand the MSO CloudConfig
- * to obtain the credentials for its sub-orchestrator and the targeted cloud.
- * The sub-orchestrator may have different credentials from the cloud (e.g. an Aria
- * instance in front of an Openstack cloud) or they may be the same (e.g. Heat)
+ * Template-based orchestrators all follow a similar template/blueprint model. - One main template that is the top level
+ * definition - Optional nested templates referenced/included by the main template - Optional files attached to the
+ * template package, typically containing configuration files, install scripts, orchestration scripts, etc.
+ *
+ * The main template also defines the required inputs for creating a new instance, and output values exposed by
+ * successfully deployed instances. Inputs and outputs may include simple or complex (JSON) data types.
+ *
+ * Each implementation of this interface is expected to understand the MSO CloudConfig to obtain the credentials for its
+ * sub-orchestrator and the targeted cloud. The sub-orchestrator may have different credentials from the cloud (e.g. an
+ * Aria instance in front of an Openstack cloud) or they may be the same (e.g. Heat)
*/
import java.util.Map;
@@ -50,137 +45,110 @@ public interface VduPlugin {
/**
* The instantiateVdu interface deploys a new VDU instance from a vdu model package.
*
- * For some VIMs, this may be a single command (e.g. Heat -> create stack) or may
- * require a series of API calls (e.g. Cloudify -> upload blueprint, create deployment,
- * execute install workflow). These details are hidden within the plug-in implementation.
- * The instantiation should be fully completed before returning. On failures, this
+ * For some VIMs, this may be a single command (e.g. Heat -> create stack) or may require a series of API calls
+ * (e.g. Cloudify -> upload blueprint, create deployment, execute install workflow). These details are hidden within
+ * the plug-in implementation. The instantiation should be fully completed before returning. On failures, this
* method is expected to back out the attempt, leaving the cloud in its previous state.
*
- * It is expected that parameters have been validated and contain at minimum the
- * required parameters for the given template with no extra parameters.
+ * It is expected that parameters have been validated and contain at minimum the required parameters for the given
+ * template with no extra parameters.
*
- * The VDU name supplied by the caller will be globally unique, and identify the artifact
- * in A&AI. Inventory is managed by the higher levels invoking this function.
+ * The VDU name supplied by the caller will be globally unique, and identify the artifact in A&AI. Inventory is
+ * managed by the higher levels invoking this function.
*
* @param cloudInfo The target cloud + tenant identifiers for the VDU.
* @param instanceName A unique name for the VDU instance to update.
- * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects.
- * Will completely replace any inputs provided on the original instantiation.
- * @param vduModel Object containing the collection of templates and files that comprise
- * the blueprint for this VDU.
- * @param rollbackOnFailure Flag to preserve or roll back the update on Failure. Should normally
- * be True except in troubleshooting/debug cases. Might not be supported in all plug-ins.
+ * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects. Will completely replace
+ * any inputs provided on the original instantiation.
+ * @param vduModel Object containing the collection of templates and files that comprise the blueprint for this VDU.
+ * @param rollbackOnFailure Flag to preserve or roll back the update on Failure. Should normally be True except in
+ * troubleshooting/debug cases. Might not be supported in all plug-ins.
*
* @return A VduInstance object
- * @throws VduException Thrown if the sub-orchestrator API calls fail or if a timeout occurs.
- * Various subclasses of VduException may be thrown.
+ * @throws VduException Thrown if the sub-orchestrator API calls fail or if a timeout occurs. Various subclasses of
+ * VduException may be thrown.
*/
- public VduInstance instantiateVdu (
- CloudInfo cloudInfo,
- String instanceName,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException;
-
+ public VduInstance instantiateVdu(CloudInfo cloudInfo, String instanceName, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException;
+
/**
- * Query a deployed VDU instance. This call will return a VduInstance object, or null
- * if the deployment does not exist.
+ * Query a deployed VDU instance. This call will return a VduInstance object, or null if the deployment does not
+ * exist.
*
- * Some VIM orchestrators identify deployment instances by string UUIDs, and others
- * by integers. In the latter case, the ID will be passed in as a numeric string.
+ * Some VIM orchestrators identify deployment instances by string UUIDs, and others by integers. In the latter case,
+ * the ID will be passed in as a numeric string.
*
- * The returned VduInstance object contains the input and output parameter maps,
- * as well as other properties of the deployment (name, status, last action, etc.).
+ * The returned VduInstance object contains the input and output parameter maps, as well as other properties of the
+ * deployment (name, status, last action, etc.).
*
* @param cloudInfo The target cloud + tenant identifiers for the VDU.
* @param vduInstanceId The ID of the deployment to query
*
* @return A VduInstance object
- * @throws VduException Thrown if the sub-orchestrator API calls fail or if a timeout occurs.
- * Various subclasses of VduException may be thrown.
+ * @throws VduException Thrown if the sub-orchestrator API calls fail or if a timeout occurs. Various subclasses of
+ * VduException may be thrown.
*/
- public VduInstance queryVdu (
- CloudInfo cloudInfo,
- String vduInstanceId)
- throws VduException;
+ public VduInstance queryVdu(CloudInfo cloudInfo, String vduInstanceId) throws VduException;
+
-
/**
- * Delete a VDU instance by ID. If the VIM sub-orchestrator supports pre-installation
- * of blueprints/models, the blueprint itself may remain installed. This is recommended,
- * since other VDU instances may be using it.
- *
- * Some VIM orchestrators identify deployment instances by string UUIDs, and others
- * by integers. In the latter case, the ID will be passed in as a numeric string.
- *
- * For some VIMs, deletion may be a single command (e.g. Heat -> delete stack) or a
- * series of API calls (e.g. Cloudify -> execute uninstall workflow, delete deployment).
- * These details are hidden within the plug-in implementation. The deletion should be
- * fully completed before returning.
- *
- * The successful return is a VduInstance object which contains the state of the VDU
- * just prior to deletion, with a status of DELETED. If the deployment was not found,
- * the VduInstance object should be empty (with a status of NOTFOUND).
- * There is no rollback from a successful deletion.
- *
- * A deletion failure will result in an undefined deployment state - the components may
- * or may not have been all or partially uninstalled, so the resulting deployment must
- * be considered invalid.
+ * Delete a VDU instance by ID. If the VIM sub-orchestrator supports pre-installation of blueprints/models, the
+ * blueprint itself may remain installed. This is recommended, since other VDU instances may be using it.
+ *
+ * Some VIM orchestrators identify deployment instances by string UUIDs, and others by integers. In the latter case,
+ * the ID will be passed in as a numeric string.
+ *
+ * For some VIMs, deletion may be a single command (e.g. Heat -> delete stack) or a series of API calls (e.g.
+ * Cloudify -> execute uninstall workflow, delete deployment). These details are hidden within the plug-in
+ * implementation. The deletion should be fully completed before returning.
+ *
+ * The successful return is a VduInstance object which contains the state of the VDU just prior to deletion, with a
+ * status of DELETED. If the deployment was not found, the VduInstance object should be empty (with a status of
+ * NOTFOUND). There is no rollback from a successful deletion.
+ *
+ * A deletion failure will result in an undefined deployment state - the components may or may not have been all or
+ * partially uninstalled, so the resulting deployment must be considered invalid.
*
* @param cloudInfo The target cloud + tenant identifiers for the VDU.
* @param instanceId The unique id of the deployment to delete.
- * @param timeoutMinutes Timeout after which the delete action will be cancelled.
- * Consider sending the entire model here, if it may be of use to the plug-in?
+ * @param timeoutMinutes Timeout after which the delete action will be cancelled. Consider sending the entire model
+ * here, if it may be of use to the plug-in?
*
* @return A VduInstance object, representing its state just prior to deletion.
*
- * @throws VduException Thrown if the API calls fail or if a timeout occurs.
- * Various subclasses of VduException may be thrown.
+ * @throws VduException Thrown if the API calls fail or if a timeout occurs. Various subclasses of VduException may
+ * be thrown.
*/
- public VduInstance deleteVdu (
- CloudInfo cloudInfo,
- String instanceId,
- int timeoutMinutes)
- throws VduException;
+ public VduInstance deleteVdu(CloudInfo cloudInfo, String instanceId, int timeoutMinutes) throws VduException;
+
-
/**
- * The updateVdu interface attempts to update a VDU in-place, using either new inputs or
- * a new model definition (i.e. updated templates/blueprints). This depends on the
- * capabilities of the targeted sub-orchestrator, as not all implementations are expected
- * to support this ability. It is primary included initially only for Heat.
- *
- * It is expected that parameters have been validated and contain at minimum the required
- * parameters for the given template with no extra parameters. The VDU instance name cannot
- * be updated.
- *
- * The update should be fully completed before returning. The successful return is a
- * VduInstance object containing the updated VDU state.
- *
- * An update failure will result in an undefined deployment state - the components may
- * or may not have been all or partially modified, deleted, recreated, etc. So the resulting
- * VDU must be considered invalid.
+ * The updateVdu interface attempts to update a VDU in-place, using either new inputs or a new model definition
+ * (i.e. updated templates/blueprints). This depends on the capabilities of the targeted sub-orchestrator, as not
+ * all implementations are expected to support this ability. It is primary included initially only for Heat.
+ *
+ * It is expected that parameters have been validated and contain at minimum the required parameters for the given
+ * template with no extra parameters. The VDU instance name cannot be updated.
+ *
+ * The update should be fully completed before returning. The successful return is a VduInstance object containing
+ * the updated VDU state.
+ *
+ * An update failure will result in an undefined deployment state - the components may or may not have been all or
+ * partially modified, deleted, recreated, etc. So the resulting VDU must be considered invalid.
*
* @param cloudInfo The target cloud + tenant identifiers for the VDU.
* @param instanceId The unique ID for the VDU instance to update.
- * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects.
- * Will completely replace any inputs provided on the original instantiation.
- * @param vduModel Object containing the collection of templates and files that comprise
- * the blueprint for this VDU.
- * @param rollbackOnFailure Flag to preserve or roll back the update on Failure. Should normally
- * be True except in troubleshooting/debug cases. Might not be supported in all plug-ins.
+ * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects. Will completely replace
+ * any inputs provided on the original instantiation.
+ * @param vduModel Object containing the collection of templates and files that comprise the blueprint for this VDU.
+ * @param rollbackOnFailure Flag to preserve or roll back the update on Failure. Should normally be True except in
+ * troubleshooting/debug cases. Might not be supported in all plug-ins.
*
* @return A VduInfo object
- * @throws VduException Thrown if the sub-orchestrator API calls fail or if a timeout occurs.
- * Various subclasses of VduException may be thrown.
+ * @throws VduException Thrown if the sub-orchestrator API calls fail or if a timeout occurs. Various subclasses of
+ * VduException may be thrown.
*/
- public VduInstance updateVdu (
- CloudInfo cloudInfo,
- String instanceId,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException;
+ public VduInstance updateVdu(CloudInfo cloudInfo, String instanceId, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException;
-} \ No newline at end of file
+}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/audit/beans/AuditInventory.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/audit/beans/AuditInventory.java
index 025d40d7c4..7e612b3b41 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/audit/beans/AuditInventory.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/audit/beans/AuditInventory.java
@@ -22,53 +22,53 @@ package org.onap.so.audit.beans;
import java.io.Serializable;
-public class AuditInventory implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = 4937350343452380760L;
-
- private String cloudRegion;
-
- private String cloudOwner;
-
- private String tenantId;
-
- private String heatStackName;
-
- public String getCloudRegion() {
- return cloudRegion;
- }
-
- public void setCloudRegion(String cloudRegion) {
- this.cloudRegion = cloudRegion;
- }
-
- public String getCloudOwner() {
- return cloudOwner;
- }
-
- public void setCloudOwner(String cloudOwner) {
- this.cloudOwner = cloudOwner;
- }
-
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getHeatStackName() {
- return heatStackName;
- }
-
- public void setHeatStackName(String heatStackName) {
- this.heatStackName = heatStackName;
- }
-
-
+public class AuditInventory implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 4937350343452380760L;
+
+ private String cloudRegion;
+
+ private String cloudOwner;
+
+ private String tenantId;
+
+ private String heatStackName;
+
+ public String getCloudRegion() {
+ return cloudRegion;
+ }
+
+ public void setCloudRegion(String cloudRegion) {
+ this.cloudRegion = cloudRegion;
+ }
+
+ public String getCloudOwner() {
+ return cloudOwner;
+ }
+
+ public void setCloudOwner(String cloudOwner) {
+ this.cloudOwner = cloudOwner;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getHeatStackName() {
+ return heatStackName;
+ }
+
+ public void setHeatStackName(String heatStackName) {
+ this.heatStackName = heatStackName;
+ }
+
+
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfig.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfig.java
index b32ca1833f..fbf7741b4a 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfig.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfig.java
@@ -21,9 +21,7 @@
package org.onap.so.cloud;
import java.util.Optional;
-
import com.fasterxml.jackson.annotation.JsonRootName;
-
import org.onap.so.db.catalog.beans.CloudSite;
import org.onap.so.db.catalog.beans.CloudifyManager;
import org.onap.so.db.catalog.client.CatalogDbClient;
@@ -31,24 +29,21 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
- * JavaBean JSON class for a CloudConfig. This bean maps a JSON-format cloud
- * configuration file to Java. The CloudConfig contains information about
- * Openstack cloud configurations. It includes:
- * - CloudIdentity objects,representing DCP nodes (Openstack Identity Service)
- * - CloudSite objects, representing LCP nodes (Openstack Compute & other services)
+ * JavaBean JSON class for a CloudConfig. This bean maps a JSON-format cloud configuration file to Java. The CloudConfig
+ * contains information about Openstack cloud configurations. It includes: - CloudIdentity objects,representing DCP
+ * nodes (Openstack Identity Service) - CloudSite objects, representing LCP nodes (Openstack Compute & other services)
*
- * Note that this is only used to access Cloud Configurations loaded from a JSON
- * config file, so there are no explicit property setters.
+ * Note that this is only used to access Cloud Configurations loaded from a JSON config file, so there are no explicit
+ * property setters.
*
- * This class also contains methods to query cloud sites and/or identity
- * services by ID.
+ * This class also contains methods to query cloud sites and/or identity services by ID.
*
*/
@JsonRootName("cloud_config")
@Component
public class CloudConfig {
-
+
private static final String CLOUD_SITE_VERSION = "2.5";
private static final String DEFAULT_CLOUD_SITE_ID = "DEFAULT";
@@ -56,41 +51,40 @@ public class CloudConfig {
private CatalogDbClient catalogDbClient;
/**
- * Get a specific CloudSites, based on an ID. The ID is first checked
- * against the regions, and if no match is found there, then against
- * individual entries to try and find one with a CLLI that matches the ID
- * and an AIC version of 2.5.
+ * Get a specific CloudSites, based on an ID. The ID is first checked against the regions, and if no match is found
+ * there, then against individual entries to try and find one with a CLLI that matches the ID and an AIC version of
+ * 2.5.
*
* @param id the ID to match
* @return an Optional of CloudSite object.
*/
- public synchronized Optional<CloudSite> getCloudSite(String id) {
- if (id == null) {
- return Optional.empty();
- }
- CloudSite cloudSite = catalogDbClient.getCloudSite(id);
+ public synchronized Optional<CloudSite> getCloudSite(String id) {
+ if (id == null) {
+ return Optional.empty();
+ }
+ CloudSite cloudSite = catalogDbClient.getCloudSite(id);
+
+ if (cloudSite != null) {
+ return Optional.of(cloudSite);
+ } else {
+ return getCloudSiteWithClli(id);
+ }
+ }
- if (cloudSite != null) {
- return Optional.of(cloudSite);
- } else {
- return getCloudSiteWithClli(id);
- }
- }
-
/**
- * Get a specific CloudSites, based on a CLLI and (optional) version, which
- * will be matched against the aic_version field of the CloudSite.
+ * Get a specific CloudSites, based on a CLLI and (optional) version, which will be matched against the aic_version
+ * field of the CloudSite.
*
- * @param clli
- * the CLLI to match
+ * @param clli the CLLI to match
* @return a CloudSite, or null of no match found
*/
private Optional<CloudSite> getCloudSiteWithClli(String clli) {
- Optional <CloudSite> cloudSiteOptional = Optional.ofNullable(catalogDbClient.getCloudSiteByClliAndAicVersion(clli,CLOUD_SITE_VERSION));
+ Optional<CloudSite> cloudSiteOptional =
+ Optional.ofNullable(catalogDbClient.getCloudSiteByClliAndAicVersion(clli, CLOUD_SITE_VERSION));
if (cloudSiteOptional.isPresent()) {
- return cloudSiteOptional;
+ return cloudSiteOptional;
} else {
- return getDefaultCloudSite(clli);
+ return getDefaultCloudSite(clli);
}
}
@@ -107,12 +101,13 @@ public class CloudConfig {
}
}
- /**
- * Get a specific CloudifyManager, based on an ID.
- * @param id the ID to match
- * @return a CloudifyManager, or null of no match found
- */
- public CloudifyManager getCloudifyManager (String id) {
+ /**
+ * Get a specific CloudifyManager, based on an ID.
+ *
+ * @param id the ID to match
+ * @return a CloudifyManager, or null of no match found
+ */
+ public CloudifyManager getCloudifyManager(String id) {
return catalogDbClient.getCloudifyManager(id);
- }
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfigIdentityMapper.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfigIdentityMapper.java
index f554aa46cd..cbc0428b15 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfigIdentityMapper.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfigIdentityMapper.java
@@ -20,11 +20,11 @@
package org.onap.so.cloud;
/**
- * This interface provides the method signature for mapping registration.
- * All mappings should be registered by the implementing class.
+ * This interface provides the method signature for mapping registration. All mappings should be registered by the
+ * implementing class.
*/
@FunctionalInterface
public interface CloudConfigIdentityMapper {
- public void registerAllMappings();
+ public void registerAllMappings();
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java
index 49c80b44b5..59c6becfbd 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java
@@ -21,13 +21,11 @@
package org.onap.so.cloud.authentication;
import java.util.Collections;
-
import org.onap.so.cloud.authentication.models.RackspaceAuthentication;
import org.onap.so.db.catalog.beans.AuthenticationType;
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.utils.CryptoUtils;
import org.springframework.stereotype.Component;
-
import com.woorea.openstack.keystone.model.Authentication;
import com.woorea.openstack.keystone.model.authentication.UsernamePassword;
import com.woorea.openstack.keystone.v3.model.Authentication.Identity;
@@ -44,44 +42,51 @@ import com.woorea.openstack.keystone.v3.model.Authentication.Scope.Project;
@Component
public final class AuthenticationMethodFactory {
- public final Authentication getAuthenticationFor(CloudIdentity cloudIdentity) {
- if (cloudIdentity == null) {
- throw new IllegalArgumentException("Cloud identity cannot be null");
- }
- if ((cloudIdentity.getIdentityAuthenticationType() == null)|| ("".equals(cloudIdentity.getIdentityAuthenticationType().toString()))) {
- throw new IllegalArgumentException("Cloud identity authentication type cannot be null or empty, provided value is " + cloudIdentity.getIdentityAuthenticationType() + ".");
- }
- AuthenticationType authenticationType = cloudIdentity.getIdentityAuthenticationType();
- if (AuthenticationType.RACKSPACE_APIKEY.equals(authenticationType)) {
- return new RackspaceAuthentication (cloudIdentity.getMsoId (), CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass ()));
- } else {
- return new UsernamePassword (cloudIdentity.getMsoId (), CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass ()));
- }
- }
-
-
- public final com.woorea.openstack.keystone.v3.model.Authentication getAuthenticationForV3(CloudIdentity cloudIdentity, String tenantId) {
- Identity identity = new Identity();
- Password password = new Password();
- User user = new User();
- Domain userDomain = new Domain();
- Scope scope = new Scope();
- Project project = new Project();
- Project.Domain projectDomain = new Project.Domain();
- userDomain.setName(cloudIdentity.getUserDomainName());
- projectDomain.setName(cloudIdentity.getProjectDomainName());
- user.setName(cloudIdentity.getMsoId());
- user.setPassword(CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass()));
- user.setDomain(userDomain);
- password.setUser(user);
- project.setDomain(projectDomain);
- project.setId(tenantId);
- scope.setProject(project);
- identity.setPassword(password);
- identity.setMethods(Collections.singletonList("password"));
- com.woorea.openstack.keystone.v3.model.Authentication v3Auth = new com.woorea.openstack.keystone.v3.model.Authentication();
- v3Auth.setIdentity(identity);
- v3Auth.setScope(scope);
- return v3Auth;
- }
+ public final Authentication getAuthenticationFor(CloudIdentity cloudIdentity) {
+ if (cloudIdentity == null) {
+ throw new IllegalArgumentException("Cloud identity cannot be null");
+ }
+ if ((cloudIdentity.getIdentityAuthenticationType() == null)
+ || ("".equals(cloudIdentity.getIdentityAuthenticationType().toString()))) {
+ throw new IllegalArgumentException(
+ "Cloud identity authentication type cannot be null or empty, provided value is "
+ + cloudIdentity.getIdentityAuthenticationType() + ".");
+ }
+ AuthenticationType authenticationType = cloudIdentity.getIdentityAuthenticationType();
+ if (AuthenticationType.RACKSPACE_APIKEY.equals(authenticationType)) {
+ return new RackspaceAuthentication(cloudIdentity.getMsoId(),
+ CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass()));
+ } else {
+ return new UsernamePassword(cloudIdentity.getMsoId(),
+ CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass()));
+ }
+ }
+
+
+ public final com.woorea.openstack.keystone.v3.model.Authentication getAuthenticationForV3(
+ CloudIdentity cloudIdentity, String tenantId) {
+ Identity identity = new Identity();
+ Password password = new Password();
+ User user = new User();
+ Domain userDomain = new Domain();
+ Scope scope = new Scope();
+ Project project = new Project();
+ Project.Domain projectDomain = new Project.Domain();
+ userDomain.setName(cloudIdentity.getUserDomainName());
+ projectDomain.setName(cloudIdentity.getProjectDomainName());
+ user.setName(cloudIdentity.getMsoId());
+ user.setPassword(CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass()));
+ user.setDomain(userDomain);
+ password.setUser(user);
+ project.setDomain(projectDomain);
+ project.setId(tenantId);
+ scope.setProject(project);
+ identity.setPassword(password);
+ identity.setMethods(Collections.singletonList("password"));
+ com.woorea.openstack.keystone.v3.model.Authentication v3Auth =
+ new com.woorea.openstack.keystone.v3.model.Authentication();
+ v3Auth.setIdentity(identity);
+ v3Auth.setScope(scope);
+ return v3Auth;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneAuthHolder.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneAuthHolder.java
index 49fd928f0f..4df8a91515 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneAuthHolder.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneAuthHolder.java
@@ -25,28 +25,33 @@ import java.util.Calendar;
public class KeystoneAuthHolder implements Serializable {
- private static final long serialVersionUID = -9073252905181739224L;
-
- private String id;
- private Calendar expiration;
- private String serviceUrl;
-
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public Calendar getexpiration() {
- return expiration;
- }
- public void setexpiration(Calendar expiration) {
- this.expiration = expiration;
- }
- public String getServiceUrl() {
- return serviceUrl;
- }
- public void setHeatUrl(String serviceUrl) {
- this.serviceUrl = serviceUrl;
- }
+ private static final long serialVersionUID = -9073252905181739224L;
+
+ private String id;
+ private Calendar expiration;
+ private String serviceUrl;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public Calendar getexpiration() {
+ return expiration;
+ }
+
+ public void setexpiration(Calendar expiration) {
+ this.expiration = expiration;
+ }
+
+ public String getServiceUrl() {
+ return serviceUrl;
+ }
+
+ public void setHeatUrl(String serviceUrl) {
+ this.serviceUrl = serviceUrl;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java
index 8fbccaaf69..f717144562 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java
@@ -25,7 +25,6 @@ import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
-
import org.onap.so.config.beans.PoConfig;
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.db.catalog.beans.CloudSite;
@@ -34,7 +33,6 @@ import org.onap.so.openstack.utils.MsoTenantUtils;
import org.onap.so.openstack.utils.MsoTenantUtilsFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.woorea.openstack.base.client.OpenStackConnectException;
import com.woorea.openstack.base.client.OpenStackRequest;
import com.woorea.openstack.base.client.OpenStackResponse;
@@ -43,7 +41,6 @@ import com.woorea.openstack.keystone.v3.Keystone;
import com.woorea.openstack.keystone.v3.model.Authentication;
import com.woorea.openstack.keystone.v3.model.Token;
import com.woorea.openstack.keystone.v3.model.Token.Service;
-
import net.jodah.failsafe.Failsafe;
import net.jodah.failsafe.RetryPolicy;
@@ -51,83 +48,83 @@ import net.jodah.failsafe.RetryPolicy;
@Component
public class KeystoneV3Authentication {
- @Autowired
+ @Autowired
private AuthenticationMethodFactory authenticationMethodFactory;
-
+
@Autowired
private MsoTenantUtilsFactory tenantUtilsFactory;
-
+
@Autowired
- private PoConfig poConfig;
-
- public KeystoneAuthHolder getToken(CloudSite cloudSite, String tenantId, String type) throws MsoException {
-
- String cloudId = cloudSite.getId();
+ private PoConfig poConfig;
+
+ public KeystoneAuthHolder getToken(CloudSite cloudSite, String tenantId, String type) throws MsoException {
+
+ String cloudId = cloudSite.getId();
String region = cloudSite.getRegionId();
- CloudIdentity cloudIdentity = cloudSite.getIdentityService();
- MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
+ CloudIdentity cloudIdentity = cloudSite.getIdentityService();
+ MsoTenantUtils tenantUtils =
+ tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
- Keystone keystoneTenantClient = new Keystone (keystoneUrl);
+ Keystone keystoneTenantClient = new Keystone(keystoneUrl);
Authentication v3Credentials = authenticationMethodFactory.getAuthenticationForV3(cloudIdentity, tenantId);
- OpenStackRequest<Token> v3Request = keystoneTenantClient.tokens ()
- .authenticate(v3Credentials);
-
- KeystoneAuthHolder holder = makeRequest(v3Request, type, region);
-
- return holder;
- }
-
- protected KeystoneAuthHolder makeRequest(OpenStackRequest<Token> v3Request, String type, String region) {
-
- OpenStackResponse response = Failsafe.with(createRetryPolicy()).get(() -> {
- return v3Request.request();
- });
- String id = response.header("X-Subject-Token");
- Token token = response.getEntity(Token.class);
- KeystoneAuthHolder result = new KeystoneAuthHolder();
- result.setId(id);
- result.setexpiration(token.getExpiresAt());
- result.setHeatUrl(findEndpointURL(token.getCatalog(), type, region, "public"));
- return result;
- }
-
- protected RetryPolicy createRetryPolicy() {
- RetryPolicy policy = new RetryPolicy();
- List<Predicate<Throwable>> result = new ArrayList<>();
- result.add(e -> {
- return e.getCause() instanceof OpenStackResponseException
- && Arrays.asList(poConfig.getRetryCodes().split(","))
- .contains(Integer.toString(((OpenStackResponseException)e).getStatus()));
- });
- result.add(e -> {
- return e.getCause() instanceof OpenStackConnectException;
- });
-
- Predicate<Throwable> pred = result.stream().reduce(Predicate::or).orElse(x -> false);
-
- policy.retryOn(error -> pred.test(error));
-
- policy.withDelay(poConfig.getRetryDelay(), TimeUnit.SECONDS)
- .withMaxRetries(poConfig.getRetryCount());
-
- return policy;
- }
-
- protected String findEndpointURL(List<Service> serviceCatalog, String type, String region, String facing) {
- for(Service service : serviceCatalog) {
- if(type.equals(service.getType())) {
- for(Service.Endpoint endpoint : service.getEndpoints()) {
- if(region == null || region.equals(endpoint.getRegion())) {
- if(facing.equals(endpoint.getInterface())) {
- return endpoint.getUrl();
- }
- }
- }
- }
- }
- throw new ServiceEndpointNotFoundException("endpoint url not found: type:" + type +" region: " + region + " facing: " + facing);
- }
+ OpenStackRequest<Token> v3Request = keystoneTenantClient.tokens().authenticate(v3Credentials);
+
+ KeystoneAuthHolder holder = makeRequest(v3Request, type, region);
+
+ return holder;
+ }
+
+ protected KeystoneAuthHolder makeRequest(OpenStackRequest<Token> v3Request, String type, String region) {
+
+ OpenStackResponse response = Failsafe.with(createRetryPolicy()).get(() -> {
+ return v3Request.request();
+ });
+ String id = response.header("X-Subject-Token");
+ Token token = response.getEntity(Token.class);
+ KeystoneAuthHolder result = new KeystoneAuthHolder();
+ result.setId(id);
+ result.setexpiration(token.getExpiresAt());
+ result.setHeatUrl(findEndpointURL(token.getCatalog(), type, region, "public"));
+ return result;
+ }
+
+ protected RetryPolicy createRetryPolicy() {
+ RetryPolicy policy = new RetryPolicy();
+ List<Predicate<Throwable>> result = new ArrayList<>();
+ result.add(e -> {
+ return e.getCause() instanceof OpenStackResponseException
+ && Arrays.asList(poConfig.getRetryCodes().split(","))
+ .contains(Integer.toString(((OpenStackResponseException) e).getStatus()));
+ });
+ result.add(e -> {
+ return e.getCause() instanceof OpenStackConnectException;
+ });
+
+ Predicate<Throwable> pred = result.stream().reduce(Predicate::or).orElse(x -> false);
+
+ policy.retryOn(error -> pred.test(error));
+
+ policy.withDelay(poConfig.getRetryDelay(), TimeUnit.SECONDS).withMaxRetries(poConfig.getRetryCount());
+
+ return policy;
+ }
+
+ protected String findEndpointURL(List<Service> serviceCatalog, String type, String region, String facing) {
+ for (Service service : serviceCatalog) {
+ if (type.equals(service.getType())) {
+ for (Service.Endpoint endpoint : service.getEndpoints()) {
+ if (region == null || region.equals(endpoint.getRegion())) {
+ if (facing.equals(endpoint.getInterface())) {
+ return endpoint.getUrl();
+ }
+ }
+ }
+ }
+ }
+ throw new ServiceEndpointNotFoundException(
+ "endpoint url not found: type:" + type + " region: " + region + " facing: " + facing);
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/ServiceEndpointNotFoundException.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/ServiceEndpointNotFoundException.java
index d95737d927..96a947804a 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/ServiceEndpointNotFoundException.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/ServiceEndpointNotFoundException.java
@@ -22,9 +22,9 @@ package org.onap.so.cloud.authentication;
public class ServiceEndpointNotFoundException extends RuntimeException {
- private static final long serialVersionUID = -5347215451284361397L;
+ private static final long serialVersionUID = -5347215451284361397L;
- public ServiceEndpointNotFoundException(String message) {
- super(message);
- }
+ public ServiceEndpointNotFoundException(String message) {
+ super(message);
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/models/RackspaceAuthentication.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/models/RackspaceAuthentication.java
index 009c9a4c6c..f8fa78ccfc 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/models/RackspaceAuthentication.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/models/RackspaceAuthentication.java
@@ -21,7 +21,6 @@
package org.onap.so.cloud.authentication.models;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -29,74 +28,77 @@ import com.woorea.openstack.keystone.model.Authentication;
@JsonRootName("auth")
public class RackspaceAuthentication extends Authentication {
-
- /**
- *
- */
- private static final long serialVersionUID = 5451283386875662918L;
-
- @JsonIgnore
- private String tenantId;
-
- @JsonIgnore
- private String tenantName;
-
- public static final class Token implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = -4448875265818207908L;
- private String username;
- private String apiKey;
-
- /**
- * @return the username
- */
- public String getUsername() {
- return username;
- }
- /**
- * @param username the username to set
- */
- public void setUsername(String username) {
- this.username = username;
- }
- /**
- * @return the apiKey
- */
- public String getApiKey() {
- return apiKey;
- }
- /**
- * @param apiKey the apiKey to set
- */
- public void setApiKey(String apiKey) {
- this.apiKey = apiKey;
- }
- }
-
- @JsonProperty("RAX-KSKEY:apiKeyCredentials")
- private Token token = new Token();
-
- public RackspaceAuthentication (String username, String apiKey) {
- this.token.username = username;
- this.token.apiKey = apiKey;
-
- }
-
- /**
- * @return the token
- */
- public Token getToken() {
- return token;
- }
-
- /**
- * @param token the token to set
- */
- public void setToken(Token token) {
- this.token = token;
- }
-
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 5451283386875662918L;
+
+ @JsonIgnore
+ private String tenantId;
+
+ @JsonIgnore
+ private String tenantName;
+
+ public static final class Token implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -4448875265818207908L;
+ private String username;
+ private String apiKey;
+
+ /**
+ * @return the username
+ */
+ public String getUsername() {
+ return username;
+ }
+
+ /**
+ * @param username the username to set
+ */
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ /**
+ * @return the apiKey
+ */
+ public String getApiKey() {
+ return apiKey;
+ }
+
+ /**
+ * @param apiKey the apiKey to set
+ */
+ public void setApiKey(String apiKey) {
+ this.apiKey = apiKey;
+ }
+ }
+
+ @JsonProperty("RAX-KSKEY:apiKeyCredentials")
+ private Token token = new Token();
+
+ public RackspaceAuthentication(String username, String apiKey) {
+ this.token.username = username;
+ this.token.apiKey = apiKey;
+
+ }
+
+ /**
+ * @return the token
+ */
+ public Token getToken() {
+ return token;
+ }
+
+ /**
+ * @param token the token to set
+ */
+ public void setToken(Token token) {
+ this.token = token;
+ }
+
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfo.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfo.java
index d2b3334c8c..42b77baeeb 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfo.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfo.java
@@ -40,12 +40,8 @@ public final class DeploymentInfo {
private final String actionStatus;
private final String errorMessage;
- DeploymentInfo(String id, DeploymentStatus deploymentStatus,
- Map<String, Object> deploymentOutputs,
- Map<String, Object> deploymentInputs,
- String lastAction,
- String actionStatus,
- String errorMessage) {
+ DeploymentInfo(String id, DeploymentStatus deploymentStatus, Map<String, Object> deploymentOutputs,
+ Map<String, Object> deploymentInputs, String lastAction, String actionStatus, String errorMessage) {
this.id = id;
this.status = deploymentStatus;
@@ -86,14 +82,9 @@ public final class DeploymentInfo {
@Override
public String toString() {
- return "DeploymentInfo {" +
- "id='" + id + '\'' +
- ", inputs='" + inputs + '\'' +
- ", outputs='" + outputs + '\'' +
- ", lastAction='" + lastAction + '\'' +
- ", status='" + status + '\'' +
- ", errorMessage='" + errorMessage + '\'' +
- '}';
+ return "DeploymentInfo {" + "id='" + id + '\'' + ", inputs='" + inputs + '\'' + ", outputs='" + outputs + '\''
+ + ", lastAction='" + lastAction + '\'' + ", status='" + status + '\'' + ", errorMessage='"
+ + errorMessage + '\'' + '}';
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java
index 2e12869c95..02ace5665d 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 Nokia.
- * =============================================================================
- * 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
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 Nokia.
+ * ============================================================================= 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
+ * 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.
+ * 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.so.cloudify.beans;
@@ -44,7 +39,9 @@ public final class DeploymentInfoBuilder {
}
public DeploymentInfoBuilder withDeploymentOutputs(Map<String, Object> deploymentOutputs) {
- this.deploymentOutputs = deploymentOutputs;
+ if (deploymentOutputs != null) {
+ this.deploymentOutputs = deploymentOutputs;
+ }
return this;
}
@@ -107,12 +104,7 @@ public final class DeploymentInfoBuilder {
}
public DeploymentInfo build() {
- return new DeploymentInfo(id,
- deploymentStatus,
- deploymentOutputs,
- deploymentInputs,
- lastAction,
- actionStatus,
- errorMessage);
+ return new DeploymentInfo(id, deploymentStatus, deploymentOutputs, deploymentInputs, lastAction, actionStatus,
+ errorMessage);
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentStatus.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentStatus.java
index 5aa47e9d6b..f7d6a9d214 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentStatus.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentStatus.java
@@ -22,10 +22,10 @@ package org.onap.so.cloudify.beans;
/*
- * Enum status values to capture the state of a deployment, based on last known workflow
- * (assume only INSTALL and UNINSTALL at this point).
+ * Enum status values to capture the state of a deployment, based on last known workflow (assume only INSTALL and
+ * UNINSTALL at this point).
*/
public enum DeploymentStatus {
- NOTFOUND, CREATED, INSTALLED, FAILED, INSTALLING, UNINSTALLING, UNKNOWN
+ NOTFOUND, CREATED, INSTALLED, FAILED, INSTALLING, UNINSTALLING, UNKNOWN
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoBlueprintAlreadyExists.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoBlueprintAlreadyExists.java
index d5d5684b0f..95912994bc 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoBlueprintAlreadyExists.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoBlueprintAlreadyExists.java
@@ -22,12 +22,13 @@ package org.onap.so.cloudify.exceptions;
public class MsoBlueprintAlreadyExists extends MsoCloudifyException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ // Constructor to create a new MsoCloudifyException instance
+ public MsoBlueprintAlreadyExists(String blueprintId, String cloud) {
+ // Set the detailed error as the Exception 'message'
+ super(409, "Conflict",
+ "Blueprint " + blueprintId + " already exists in Cloudify Manager supporting cloud site + " + cloud);
+ }
- // Constructor to create a new MsoCloudifyException instance
- public MsoBlueprintAlreadyExists (String blueprintId, String cloud) {
- // Set the detailed error as the Exception 'message'
- super(409, "Conflict", "Blueprint " + blueprintId + " already exists in Cloudify Manager supporting cloud site + " + cloud);
- }
-
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyException.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyException.java
index 992df5fd6a..441bd4dc07 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyException.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyException.java
@@ -26,61 +26,63 @@ import org.onap.so.openstack.exceptions.MsoExceptionCategory;
/**
* OpenStack exception.
*/
-public class MsoCloudifyException extends MsoException
-{
-
- /**
+public class MsoCloudifyException extends MsoException {
+
+ /**
* Serialization id.
*/
private static final long serialVersionUID = 3313636124141766495L;
-
+
private int statusCode;
- private String statusMessage;
- private String errorDetail;
- private boolean pendingWorkflow;
+ private String statusMessage;
+ private String errorDetail;
+ private boolean pendingWorkflow;
+
+ /**
+ * Constructor to create a new MsoOpenstackException instance
+ *
+ * @param code the error code
+ * @param message the error message
+ * @param detail error details
+ */
+ public MsoCloudifyException(int code, String message, String detail) {
+ // Set the detailed error as the Exception 'message'
+ super(detail);
+ super.category = MsoExceptionCategory.OPENSTACK;
+
+ this.statusCode = code;
+ this.statusMessage = message;
+ this.errorDetail = detail;
+ this.pendingWorkflow = false;
+ }
- /**
- * Constructor to create a new MsoOpenstackException instance
- * @param code the error code
- * @param message the error message
- * @param detail error details
- */
- public MsoCloudifyException (int code, String message, String detail) {
- // Set the detailed error as the Exception 'message'
- super(detail);
- super.category = MsoExceptionCategory.OPENSTACK;
-
- this.statusCode = code;
- this.statusMessage = message;
- this.errorDetail = detail;
- this.pendingWorkflow = false;
- }
-
- /**
- * Constructor to propagate the caught exception (mostly for stack trace)
+ /**
+ * Constructor to propagate the caught exception (mostly for stack trace)
+ *
* @param code the error code
* @param message the error message
* @param detail error details
- * @param e the cause
- */
- public MsoCloudifyException (int code, String message, String detail, Exception e) {
- // Set the detailed error as the Exception 'message'
- super(detail, e);
- super.category = MsoExceptionCategory.OPENSTACK;
-
- this.statusCode = code;
- this.statusMessage = message;
- this.errorDetail = detail;
- this.pendingWorkflow = false;
- }
-
- public void setPendingWorkflow (boolean pendingWorkflow) {
- this.pendingWorkflow = pendingWorkflow;
- }
-
- @Override
- public String toString () {
- String error = "" + statusCode + " " + statusMessage + ": " + errorDetail + (pendingWorkflow ? " [workflow pending]" : "");
- return error;
- }
+ * @param e the cause
+ */
+ public MsoCloudifyException(int code, String message, String detail, Exception e) {
+ // Set the detailed error as the Exception 'message'
+ super(detail, e);
+ super.category = MsoExceptionCategory.OPENSTACK;
+
+ this.statusCode = code;
+ this.statusMessage = message;
+ this.errorDetail = detail;
+ this.pendingWorkflow = false;
+ }
+
+ public void setPendingWorkflow(boolean pendingWorkflow) {
+ this.pendingWorkflow = pendingWorkflow;
+ }
+
+ @Override
+ public String toString() {
+ String error = "" + statusCode + " " + statusMessage + ": " + errorDetail
+ + (pendingWorkflow ? " [workflow pending]" : "");
+ return error;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyManagerNotFound.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyManagerNotFound.java
index 0c795478cd..bc6fd6204c 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyManagerNotFound.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyManagerNotFound.java
@@ -22,12 +22,12 @@ package org.onap.so.cloudify.exceptions;
public class MsoCloudifyManagerNotFound extends MsoCloudifyException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ // Constructor to create a new MsoCloudifyException instance
+ public MsoCloudifyManagerNotFound(String cloudSiteId) {
+ // Set the detailed error as the Exception 'message'
+ super(0, "Cloudify Manager Not Found", "No Cloudify Manager configured for cloud site " + cloudSiteId);
+ }
- // Constructor to create a new MsoCloudifyException instance
- public MsoCloudifyManagerNotFound (String cloudSiteId) {
- // Set the detailed error as the Exception 'message'
- super(0, "Cloudify Manager Not Found", "No Cloudify Manager configured for cloud site " + cloudSiteId);
- }
-
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeout.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeout.java
index 7dcd69d0a4..99b6ade326 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeout.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeout.java
@@ -25,40 +25,42 @@ import org.onap.so.openstack.exceptions.MsoException;
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
/**
- * MSO Exception when a Cloudify workflow execution times out waiting for completion.
- * Exception includes the last known state of the workflow execution.
+ * MSO Exception when a Cloudify workflow execution times out waiting for completion. Exception includes the last known
+ * state of the workflow execution.
*/
-public class MsoCloudifyTimeout extends MsoException
-{
-
- /**
+public class MsoCloudifyTimeout extends MsoException {
+
+ /**
* Serialization id.
*/
private static final long serialVersionUID = 3313636124141766495L;
-
- private Execution execution;
- /**
- * Constructor to create a new MsoOpenstackException instance
- * @param code the error code
- * @param message the error message
- * @param detail error details
- */
- public MsoCloudifyTimeout (Execution execution) {
- // Set the detailed error as the Exception 'message'
- super("Cloudify Workflow Timeout for workflow " + execution.getWorkflowId() + " on deployment " + execution.getDeploymentId());
- super.category = MsoExceptionCategory.OPENSTACK;
-
- this.execution = execution;
- }
-
- public Execution getExecution() {
- return this.execution;
- }
-
- @Override
- public String toString () {
- String error = "Workflow timeout: workflow=" + execution.getWorkflowId() + ",deployment=" + execution.getDeploymentId();
- return error;
- }
+ private Execution execution;
+
+ /**
+ * Constructor to create a new MsoOpenstackException instance
+ *
+ * @param code the error code
+ * @param message the error message
+ * @param detail error details
+ */
+ public MsoCloudifyTimeout(Execution execution) {
+ // Set the detailed error as the Exception 'message'
+ super("Cloudify Workflow Timeout for workflow " + execution.getWorkflowId() + " on deployment "
+ + execution.getDeploymentId());
+ super.category = MsoExceptionCategory.OPENSTACK;
+
+ this.execution = execution;
+ }
+
+ public Execution getExecution() {
+ return this.execution;
+ }
+
+ @Override
+ public String toString() {
+ String error = "Workflow timeout: workflow=" + execution.getWorkflowId() + ",deployment="
+ + execution.getDeploymentId();
+ return error;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java
index a84da50dc4..5c2348dffa 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java
@@ -22,33 +22,33 @@ package org.onap.so.cloudify.exceptions;
/**
* Reports an error with a Cloudify Workflow execution.
+ *
* @author JC1348
*
*/
public class MsoCloudifyWorkflowException extends MsoCloudifyException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ private String workflowStatus;
+ private boolean workflowStillRunning = false;
+
+ // Constructor to create a new MsoCloudifyException instance
+ public MsoCloudifyWorkflowException(String message, String deploymentId, String workflowId, String workflowStatus) {
+ super(0, "Workflow Exception",
+ "Workflow " + workflowId + " failed on deployment " + deploymentId + ": " + message);
+ this.workflowStatus = workflowStatus;
+ if (workflowStatus.equals("pending") || workflowStatus.equals("started") || workflowStatus.equals("cancelling")
+ || workflowStatus.equals("force_cancelling")) {
+ workflowStillRunning = true;
+ }
+ }
+
+ public String getWorkflowStatus() {
+ return workflowStatus;
+ }
- private String workflowStatus;
- private boolean workflowStillRunning = false;
-
- // Constructor to create a new MsoCloudifyException instance
- public MsoCloudifyWorkflowException (String message, String deploymentId, String workflowId, String workflowStatus)
- {
- super(0, "Workflow Exception", "Workflow " + workflowId + " failed on deployment " + deploymentId + ": " + message);
- this.workflowStatus = workflowStatus;
- if (workflowStatus.equals("pending") || workflowStatus.equals("started") ||
- workflowStatus.equals("cancelling") || workflowStatus.equals("force_cancelling"))
- {
- workflowStillRunning = true;
- }
- }
-
- public String getWorkflowStatus() {
- return workflowStatus;
- }
-
- public boolean isWorkflowStillRunning () {
- return workflowStillRunning;
- }
+ public boolean isWorkflowStillRunning() {
+ return workflowStillRunning;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoDeploymentAlreadyExists.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoDeploymentAlreadyExists.java
index 4f5685efb3..62112f4feb 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoDeploymentAlreadyExists.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoDeploymentAlreadyExists.java
@@ -22,12 +22,13 @@ package org.onap.so.cloudify.exceptions;
public class MsoDeploymentAlreadyExists extends MsoCloudifyException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ // Constructor to create a new MsoCloudifyException instance
+ public MsoDeploymentAlreadyExists(String deploymentId, String cloud) {
+ // Set the detailed error as the Exception 'message'
+ super(409, "Conflict",
+ "Deployment " + deploymentId + " already exists in Cloudify Manager suppporting cloud " + cloud);
+ }
- // Constructor to create a new MsoCloudifyException instance
- public MsoDeploymentAlreadyExists (String deploymentId, String cloud) {
- // Set the detailed error as the Exception 'message'
- super(409, "Conflict", "Deployment " + deploymentId + " already exists in Cloudify Manager suppporting cloud " + cloud);
- }
-
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java
index 50bcb8e54a..0a0f2787da 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java
@@ -102,9 +102,8 @@ import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
-public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
+public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin {
- private static final String CLOUDIFY_ERROR = "CloudifyError";
private static final String CLOUDIFY = "Cloudify";
private static final String CREATE_DEPLOYMENT = "CreateDeployment";
private static final String DELETE_DEPLOYMENT = "DeleteDeployment";
@@ -133,24 +132,21 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
/**
- * Create a new Deployment from a specified blueprint, and install it in the specified
- * cloud location and tenant. The blueprint identifier and parameter map are passed in
- * as arguments, along with the cloud access credentials. The blueprint should have been
- * previously uploaded to Cloudify.
+ * Create a new Deployment from a specified blueprint, and install it in the specified cloud location and tenant.
+ * The blueprint identifier and parameter map are passed in as arguments, along with the cloud access credentials.
+ * The blueprint should have been previously uploaded to Cloudify.
*
- * It is expected that parameters have been validated and contain at minimum the required
- * parameters for the given template with no extra (undefined) parameters..
+ * It is expected that parameters have been validated and contain at minimum the required parameters for the given
+ * template with no extra (undefined) parameters..
*
- * The deployment ID supplied by the caller must be unique in the scope of the Cloudify
- * tenant (not the Openstack tenant). However, it should also be globally unique, as it
- * will be the identifier for the resource going forward in Inventory. This latter is
- * managed by the higher levels invoking this function.
+ * The deployment ID supplied by the caller must be unique in the scope of the Cloudify tenant (not the Openstack
+ * tenant). However, it should also be globally unique, as it will be the identifier for the resource going forward
+ * in Inventory. This latter is managed by the higher levels invoking this function.
*
- * This function executes the "install" workflow on the newly created workflow. Cloudify
- * will be polled for completion unless the client requests otherwise.
+ * This function executes the "install" workflow on the newly created workflow. Cloudify will be polled for
+ * completion unless the client requests otherwise.
*
- * An error will be thrown if the requested Deployment already exists in the specified
- * Cloudify instance.
+ * An error will be thrown if the requested Deployment already exists in the specified Cloudify instance.
*
* @param cloudSiteId The cloud (may be a region) in which to create the stack.
* @param tenantId The Openstack ID of the tenant in which to create the Stack
@@ -165,22 +161,16 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
* @throws MsoIOException Thrown on Cloudify connection errors.
*/
- public DeploymentInfo createAndInstallDeployment (String cloudSiteId,
- String tenantId,
- String deploymentId,
- String blueprintId,
- Map <String, ? extends Object> inputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- boolean backout) throws MsoException
- {
+ public DeploymentInfo createAndInstallDeployment(String cloudSiteId, String tenantId, String deploymentId,
+ String blueprintId, Map<String, ? extends Object> inputs, boolean pollForCompletion, int timeoutMinutes,
+ boolean backout) throws MsoException {
// Obtain the cloud site information where we will create the stack
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSite.isPresent()) {
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- Cloudify cloudify = getCloudifyClient (cloudSite.get());
+ Cloudify cloudify = getCloudifyClient(cloudSite.get());
logger.debug("Ready to Create Deployment ({}) with input params: {}", deploymentId, inputs);
@@ -188,160 +178,150 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
// - from provided "environment" file
// - passed in by caller
// - special input for cloud-specific Credentials
- Map<String,Object> expandedInputs = new HashMap<> (inputs);
+ Map<String, Object> expandedInputs = new HashMap<>(inputs);
String platform = cloudSite.get().getPlatform();
if (platform == null || platform.equals("") || platform.equalsIgnoreCase("OPENSTACK")) {
- // Create the Cloudify OpenstackConfig with the credentials
- OpenstackConfig openstackConfig = getOpenstackConfig (cloudSite.get(), tenantId);
- expandedInputs.put("openstack_config", openstackConfig);
+ // Create the Cloudify OpenstackConfig with the credentials
+ OpenstackConfig openstackConfig = getOpenstackConfig(cloudSite.get(), tenantId);
+ expandedInputs.put("openstack_config", openstackConfig);
} else if (platform.equalsIgnoreCase("AZURE")) {
- // Create Cloudify AzureConfig with the credentials
- AzureConfig azureConfig = getAzureConfig (cloudSite.get(), tenantId);
- expandedInputs.put("azure_config", azureConfig);
+ // Create Cloudify AzureConfig with the credentials
+ AzureConfig azureConfig = getAzureConfig(cloudSite.get(), tenantId);
+ expandedInputs.put("azure_config", azureConfig);
}
// Build up the parameters to create a new deployment
- CreateDeploymentParams deploymentParams = new CreateDeploymentParams();
- deploymentParams.setBlueprintId(blueprintId);
- deploymentParams.setInputs(expandedInputs);
-
- Deployment deployment = null;
- try {
- CreateDeployment createDeploymentRequest = cloudify.deployments().create(deploymentId, deploymentParams);
- logger.debug(createDeploymentRequest.toString());
-
- deployment = executeAndRecordCloudifyRequest (createDeploymentRequest);
- }
- catch (CloudifyResponseException e) {
+ CreateDeploymentParams deploymentParams = new CreateDeploymentParams();
+ deploymentParams.setBlueprintId(blueprintId);
+ deploymentParams.setInputs(expandedInputs);
+
+ Deployment deployment = null;
+ try {
+ CreateDeployment createDeploymentRequest = cloudify.deployments().create(deploymentId, deploymentParams);
+ logger.debug(createDeploymentRequest.toString());
+
+ deployment = executeAndRecordCloudifyRequest(createDeploymentRequest);
+ } catch (CloudifyResponseException e) {
// Since this came on the 'Create Deployment' command, nothing was changed
// in the cloud. Return the error as an exception.
- if (e.getStatus () == 409) {
+ if (e.getStatus() == 409) {
// Deployment already exists. Return a specific error for this case
- MsoException me = new MsoDeploymentAlreadyExists (deploymentId, cloudSiteId);
- me.addContext (CREATE_DEPLOYMENT);
+ MsoException me = new MsoDeploymentAlreadyExists(deploymentId, cloudSiteId);
+ me.addContext(CREATE_DEPLOYMENT);
throw me;
} else {
// Convert the CloudifyResponseException to an MsoException
logger.debug("ERROR STATUS = {},\n{}\n{}", e.getStatus(), e.getMessage(), e.getLocalizedMessage());
- MsoException me = cloudifyExceptionToMsoException (e, CREATE_DEPLOYMENT);
- me.setCategory (MsoExceptionCategory.OPENSTACK);
+ MsoException me = cloudifyExceptionToMsoException(e, CREATE_DEPLOYMENT);
+ me.setCategory(MsoExceptionCategory.OPENSTACK);
throw me;
}
} catch (CloudifyConnectException e) {
// Error connecting to Cloudify instance. Convert to an MsoException
- throw cloudifyExceptionToMsoException (e, CREATE_DEPLOYMENT);
+ throw cloudifyExceptionToMsoException(e, CREATE_DEPLOYMENT);
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, CREATE_DEPLOYMENT);
+ throw runtimeExceptionToMsoException(e, CREATE_DEPLOYMENT);
}
- /*
- * It can take some time for Cloudify to be ready to execute a workflow
- * on the deployment. Sleep 30 seconds based on observation of behavior
- * in a Cloudify VM instance (delay due to "create_deployment_environment").
- */
- sleep(30000);
-
- /*
- * Next execute the "install" workflow.
- * Note - this assumes there are no additional parameters required for the workflow.
- */
- int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
+ /*
+ * It can take some time for Cloudify to be ready to execute a workflow on the deployment. Sleep 30 seconds
+ * based on observation of behavior in a Cloudify VM instance (delay due to "create_deployment_environment").
+ */
+ sleep(30000);
+
+ /*
+ * Next execute the "install" workflow. Note - this assumes there are no additional parameters required for the
+ * workflow.
+ */
+ int createPollInterval =
+ Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
Execution installWorkflow = null;
try {
- installWorkflow = executeWorkflow (cloudify, deploymentId, "install", null, pollForCompletion, pollTimeout, createPollInterval);
-
- if (installWorkflow.getStatus().equals(TERMINATED)) {
- // Success!
- // Create and return a DeploymentInfo structure. Include the Runtime outputs
- DeploymentOutputs outputs = getDeploymentOutputs (cloudify, deploymentId);
- return new DeploymentInfoBuilder()
- .withId(deployment.getId())
- .withDeploymentInputs(deployment.getInputs())
- .withDeploymentOutputs(outputs.getOutputs())
- .fromExecution(installWorkflow)
- .build();
- }
- else {
- // The workflow completed with errors. Must try to back it out.
- if (!backout)
- {
- logger.warn("{} Deployment installation failed, backout deletion suppressed {} {}",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
- "Exception in Deployment Installation, backout suppressed");
- }
- else {
- // Poll on delete if we rollback - use same values for now
- int deletePollInterval = createPollInterval;
- int deletePollTimeout = pollTimeout;
-
- try {
- // Run the uninstall to undo the install
- Execution uninstallWorkflow = executeWorkflow (cloudify, deploymentId, "uninstall", null, pollForCompletion, deletePollTimeout, deletePollInterval);
-
- if (uninstallWorkflow.getStatus().equals(TERMINATED))
- {
- // The uninstall completed. Delete the deployment itself
- DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId);
- executeAndRecordCloudifyRequest (deleteRequest);
- }
- else {
- // Didn't uninstall successfully. Log this error
- logger.error("{} Create Deployment: Cloudify error rolling back deployment install: {} {}",
- MessageEnum.RA_CREATE_STACK_ERR, installWorkflow.getError(),
- ErrorCode.BusinessProcesssError.getValue());
+ installWorkflow = executeWorkflow(cloudify, deploymentId, "install", null, pollForCompletion, pollTimeout,
+ createPollInterval);
+
+ if (installWorkflow.getStatus().equals(TERMINATED)) {
+ // Success!
+ // Create and return a DeploymentInfo structure. Include the Runtime outputs
+ return new DeploymentInfoBuilder().withId(deployment.getId())
+ .withDeploymentInputs(deployment.getInputs())
+ .withDeploymentOutputs(getDeploymentOutputs(cloudify, deploymentId).get())
+ .fromExecution(installWorkflow).build();
+ } else {
+ // The workflow completed with errors. Must try to back it out.
+ if (!backout) {
+ logger.warn("{} Deployment installation failed, backout deletion suppressed {} {}",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
+ "Exception in Deployment Installation, backout suppressed");
+ } else {
+ // Poll on delete if we rollback - use same values for now
+ int deletePollInterval = createPollInterval;
+ int deletePollTimeout = pollTimeout;
+
+ try {
+ // Run the uninstall to undo the install
+ Execution uninstallWorkflow = executeWorkflow(cloudify, deploymentId, "uninstall", null,
+ pollForCompletion, deletePollTimeout, deletePollInterval);
+
+ if (uninstallWorkflow.getStatus().equals(TERMINATED)) {
+ // The uninstall completed. Delete the deployment itself
+ DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId);
+ executeAndRecordCloudifyRequest(deleteRequest);
+ } else {
+ // Didn't uninstall successfully. Log this error
+ logger.error("{} Create Deployment: Cloudify error rolling back deployment install: {} {}",
+ MessageEnum.RA_CREATE_STACK_ERR, installWorkflow.getError(),
+ ErrorCode.BusinessProcesssError.getValue());
+ }
+ } catch (Exception e) {
+ // Catch-all for backout errors trying to uninstall/delete
+ // Log this error, and return the original exception
+ logger.error("{} Create Stack: Nested exception rolling back deployment install: {}",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e);
}
- }
- catch (Exception e) {
- // Catch-all for backout errors trying to uninstall/delete
- // Log this error, and return the original exception
- logger.error("{} Create Stack: Nested exception rolling back deployment install: {}",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e);
- }
- }
-
- MsoCloudifyException me = new MsoCloudifyException (0, "Workflow Execution Failed", installWorkflow.getError());
- me.addContext (CREATE_DEPLOYMENT);
+ }
+
+ MsoCloudifyException me =
+ new MsoCloudifyException(0, "Workflow Execution Failed", installWorkflow.getError());
+ me.addContext(CREATE_DEPLOYMENT);
throw me;
- }
- }
- catch (MsoException me) {
- // Install failed. Unless requested otherwise, back out the deployment
-
- if (!backout)
- {
- logger.warn("{} Deployment installation failed, backout deletion suppressed {}",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
- }
- else {
- // Poll on delete if we rollback - use same values for now
- int deletePollInterval = createPollInterval;
- int deletePollTimeout = pollTimeout;
-
- try {
- // Run the uninstall to undo the install.
- // Always try to run it, as it should be idempotent
- executeWorkflow (cloudify, deploymentId, "uninstall", null, pollForCompletion, deletePollTimeout, deletePollInterval);
-
- // Delete the deployment itself
- DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId);
- executeAndRecordCloudifyRequest (deleteRequest);
- }
- catch (Exception e) {
- // Catch-all for backout errors trying to uninstall/delete
- // Log this error, and return the original exception
- logger.error("{} Create Stack: Nested exception rolling back deployment install: {} ",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e);
- }
- }
+ }
+ } catch (MsoException me) {
+ // Install failed. Unless requested otherwise, back out the deployment
+
+ if (!backout) {
+ logger.warn("{} Deployment installation failed, backout deletion suppressed {}",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
+ } else {
+ // Poll on delete if we rollback - use same values for now
+ int deletePollInterval = createPollInterval;
+ int deletePollTimeout = pollTimeout;
+
+ try {
+ // Run the uninstall to undo the install.
+ // Always try to run it, as it should be idempotent
+ executeWorkflow(cloudify, deploymentId, "uninstall", null, pollForCompletion, deletePollTimeout,
+ deletePollInterval);
+
+ // Delete the deployment itself
+ DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId);
+ executeAndRecordCloudifyRequest(deleteRequest);
+ } catch (Exception e) {
+ // Catch-all for backout errors trying to uninstall/delete
+ // Log this error, and return the original exception
+ logger.error("{} Create Stack: Nested exception rolling back deployment install: {} ",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e);
+ }
+ }
// Propagate the original exception from Stack Query.
- me.addContext (CREATE_DEPLOYMENT);
+ me.addContext(CREATE_DEPLOYMENT);
throw me;
}
@@ -349,304 +329,275 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
/*
- * Get the runtime Outputs of a deployment.
- * Return the Map of tag/value outputs.
+ * Get the runtime Outputs of a deployment. Return the Map of tag/value outputs.
*/
- private DeploymentOutputs getDeploymentOutputs (Cloudify cloudify, String deploymentId)
- throws MsoException
- {
- // Build and send the Cloudify request
- DeploymentOutputs deploymentOutputs = null;
- try {
- GetDeploymentOutputs queryDeploymentOutputs = cloudify.deployments().outputsById(deploymentId);
- logger.debug(queryDeploymentOutputs.toString());
-
- deploymentOutputs = executeAndRecordCloudifyRequest(queryDeploymentOutputs);
- }
- catch (CloudifyConnectException ce) {
- // Couldn't connect to Cloudify
- logger.error("{} QueryDeploymentOutputs: Cloudify connection failure: {} ",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), ce);
- throw new MsoIOException (ce.getMessage(), ce);
- }
- catch (CloudifyResponseException re) {
- if (re.getStatus () == 404) {
- // No Outputs
- return null;
+ private Optional<Map<String, Object>> getDeploymentOutputs(Cloudify cloudify, String deploymentId)
+ throws MsoException {
+ // Build and send the Cloudify request
+ DeploymentOutputs deploymentOutputs;
+ try {
+ GetDeploymentOutputs queryDeploymentOutputs = cloudify.deployments().outputsById(deploymentId);
+ logger.debug(queryDeploymentOutputs.toString());
+
+ deploymentOutputs = executeAndRecordCloudifyRequest(queryDeploymentOutputs);
+ if (deploymentOutputs != null) {
+ return Optional.ofNullable(deploymentOutputs.getOutputs());
+ } else {
+ return Optional.empty();
+ }
+ } catch (CloudifyConnectException ce) {
+ // Couldn't connect to Cloudify
+ logger.error("{} QueryDeploymentOutputs: Cloudify connection failure: {} ", MessageEnum.RA_CREATE_STACK_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), ce);
+ throw new MsoIOException(ce.getMessage(), ce);
+ } catch (CloudifyResponseException re) {
+ if (re.getStatus() == 404) {
+ // No Outputs
+ return Optional.empty();
}
- throw new MsoCloudifyException (re.getStatus(), re.getMessage(), re.getLocalizedMessage(), re);
- }
- catch (Exception e) {
- // Catch-all
- throw new MsoAdapterException (e.getMessage(), e);
- }
-
- return deploymentOutputs;
+ throw new MsoCloudifyException(re.getStatus(), re.getMessage(), re.getLocalizedMessage(), re);
+ } catch (Exception e) {
+ // Catch-all
+ throw new MsoAdapterException(e.getMessage(), e);
+ }
}
/*
- * Execute a workflow on a deployment. Handle polling for completion with timeout.
- * Return the final Execution object with status.
- * Throw an exception on Errors.
- * Question - how does the client know whether rollback needs to be done?
+ * Execute a workflow on a deployment. Handle polling for completion with timeout. Return the final Execution object
+ * with status. Throw an exception on Errors. Question - how does the client know whether rollback needs to be done?
*/
- private Execution executeWorkflow (Cloudify cloudify, String deploymentId, String workflowId, Map<String,Object> workflowParams, boolean pollForCompletion, int timeout, int pollInterval)
- throws MsoCloudifyException
- {
+ private Execution executeWorkflow(Cloudify cloudify, String deploymentId, String workflowId,
+ Map<String, Object> workflowParams, boolean pollForCompletion, int timeout, int pollInterval)
+ throws MsoCloudifyException {
logger.debug("Executing '{}' workflow on deployment '{}'", workflowId, deploymentId);
- StartExecutionParams executeParams = new StartExecutionParams();
- executeParams.setWorkflowId(workflowId);
- executeParams.setDeploymentId(deploymentId);
- executeParams.setParameters(workflowParams);
-
- Execution execution = null;
- String executionId = null;
- String command = "start";
- Exception savedException = null;
-
- try {
- StartExecution executionRequest = cloudify.executions().start(executeParams);
- logger.debug(executionRequest.toString());
- execution = executeAndRecordCloudifyRequest (executionRequest);
- executionId = execution.getId();
-
- if (!pollForCompletion) {
- // Client did not request polling, so just return the Execution object
- return execution;
- }
-
- // Enter polling loop
- boolean timedOut = false;
- int pollTimeout = timeout;
-
- String status = execution.getStatus();
-
- // Create a reusable cloudify query request
- GetExecution queryExecution = cloudify.executions().byId(executionId);
- command = "query";
-
- while (!timedOut && !(status.equals(TERMINATED) || status.equals("failed") || status.equals(CANCELLED)))
- {
- // workflow is still running; check for timeout
- if (pollTimeout <= 0) {
- logger.debug("workflow {} timed out on deployment {}", execution.getWorkflowId(),
- execution.getDeploymentId());
- timedOut = true;
- continue;
- }
-
- sleep(pollInterval * 1000L);
-
- pollTimeout -= pollInterval;
- logger.debug("pollTimeout remaining: " + pollTimeout);
-
- execution = queryExecution.execute();
- status = execution.getStatus();
- }
-
- // Broke the loop. Check again for a terminal state
- if (status.equals(TERMINATED)){
- // Success!
- logger.debug("Workflow '{}' completed successfully on deployment '{}'", workflowId, deploymentId);
- return execution;
- }
- else if (status.equals("failed")){
- // Workflow failed. Log it and return the execution object (don't throw exception here)
- logger.error("{} Cloudify workflow failure: {} {} Execute Workflow: Failed: {}",
- MessageEnum.RA_CREATE_STACK_ERR, execution.getError(),
- ErrorCode.BusinessProcesssError.getValue(), execution.getError());
- return execution;
- }
- else if (status.equals(CANCELLED)){
- // Workflow was cancelled, leaving the deployment in an indeterminate state. Log it and return the execution object (don't throw exception here)
- logger.error("{} Cloudify workflow cancelled. Deployment is in an indeterminate state {} {} {}",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
- "Execute Workflow cancelled: ", workflowId);
- return execution;
- }
- else {
- // Can only get here after a timeout
- logger.error("{} Cloudify workflow timeout {} Execute Workflow: Timed Out", MessageEnum.RA_CREATE_STACK_ERR,
- ErrorCode.BusinessProcesssError.getValue());
- }
- }
- catch (CloudifyConnectException ce) {
- logger.error("{} {} Execute Workflow ({} {}): Cloudify connection failure {} ", MessageEnum.RA_CREATE_STACK_ERR,
- ErrorCode.BusinessProcesssError.getValue(), command, ce);
- savedException = ce;
- }
- catch (CloudifyResponseException re) {
- logger.error("{} {} Execute Workflow ({}): Cloudify response error {} ", MessageEnum.RA_CREATE_STACK_ERR,
- ErrorCode.BusinessProcesssError.getValue(), command, re.getMessage(), re);
- savedException = re;
- }
- catch (RuntimeException e) {
- // Catch-all
- logger.error("{} {} Execute Workflow ({}): Internal error {}", MessageEnum.RA_CREATE_STACK_ERR,
- ErrorCode.BusinessProcesssError.getValue(), command, e.getMessage(), e);
- savedException = e;
- }
-
- // Get to this point ONLY on an error or timeout
- // The cloudify execution is still running (we've not received a terminal status),
- // so try to Cancel it.
- CancelExecutionParams cancelParams = new CancelExecutionParams();
- cancelParams.setAction("cancel");
- // TODO: Use force_cancel?
-
- Execution cancelExecution = null;
-
- try {
- CancelExecution cancelRequest = cloudify.executions().cancel(executionId, cancelParams);
- logger.debug(cancelRequest.toString());
- cancelExecution = cancelRequest.execute();
-
- // Enter polling loop
- boolean timedOut = false;
- int cancelTimeout = timeout; // TODO: For now, just use same timeout
-
- String status = cancelExecution.getStatus();
-
- // Poll for completion. Create a reusable cloudify query request
- GetExecution queryExecution = cloudify.executions().byId(executionId);
-
- while (!timedOut && !status.equals(CANCELLED))
- {
- // workflow is still running; check for timeout
- if (cancelTimeout <= 0) {
- logger.debug("Cancel timeout for workflow {} on deployment {}", workflowId, deploymentId);
- timedOut = true;
- continue;
- }
-
- sleep(pollInterval * 1000L);
-
- cancelTimeout -= pollInterval;
- logger.debug("pollTimeout remaining: {}", cancelTimeout);
-
- execution = queryExecution.execute();
- status = execution.getStatus();
- }
-
- // Broke the loop. Check again for a terminal state
- if (status.equals(CANCELLED)){
- // Finished cancelling. Return the original exception
- logger.debug("Cancel workflow {} completed on deployment {}", workflowId, deploymentId);
- throw new MsoCloudifyException (-1, "", "", savedException);
- }
- else {
- // Can only get here after a timeout
- logger.debug("Cancel workflow {} timeout out on deployment {}", workflowId, deploymentId);
- MsoCloudifyException exception = new MsoCloudifyException (-1, "", "", savedException);
- exception.setPendingWorkflow(true);
- throw exception;
- }
- }
- catch (Exception e) {
- // Catch-all. Log the message and throw the original exception
- logger.debug("Cancel workflow {} failed for deployment : {} {}", workflowId, deploymentId, e);
- MsoCloudifyException exception = new MsoCloudifyException (-1, "", "", savedException);
- exception.setPendingWorkflow(true);
- throw exception;
- }
+ StartExecutionParams executeParams = new StartExecutionParams();
+ executeParams.setWorkflowId(workflowId);
+ executeParams.setDeploymentId(deploymentId);
+ executeParams.setParameters(workflowParams);
+
+ Execution execution = null;
+ String executionId = null;
+ String command = "start";
+ Exception savedException = null;
+
+ try {
+ StartExecution executionRequest = cloudify.executions().start(executeParams);
+ logger.debug(executionRequest.toString());
+ execution = executeAndRecordCloudifyRequest(executionRequest);
+ executionId = execution.getId();
+
+ if (!pollForCompletion) {
+ // Client did not request polling, so just return the Execution object
+ return execution;
+ }
+
+ // Enter polling loop
+ boolean timedOut = false;
+ int pollTimeout = timeout;
+
+ String status = execution.getStatus();
+
+ // Create a reusable cloudify query request
+ GetExecution queryExecution = cloudify.executions().byId(executionId);
+ command = "query";
+
+ while (!timedOut && !(status.equals(TERMINATED) || status.equals("failed") || status.equals(CANCELLED))) {
+ // workflow is still running; check for timeout
+ if (pollTimeout <= 0) {
+ logger.debug("workflow {} timed out on deployment {}", execution.getWorkflowId(),
+ execution.getDeploymentId());
+ timedOut = true;
+ continue;
+ }
+
+ sleep(pollInterval * 1000L);
+
+ pollTimeout -= pollInterval;
+ logger.debug("pollTimeout remaining: " + pollTimeout);
+
+ execution = queryExecution.execute();
+ status = execution.getStatus();
+ }
+
+ // Broke the loop. Check again for a terminal state
+ if (status.equals(TERMINATED)) {
+ // Success!
+ logger.debug("Workflow '{}' completed successfully on deployment '{}'", workflowId, deploymentId);
+ return execution;
+ } else if (status.equals("failed")) {
+ // Workflow failed. Log it and return the execution object (don't throw exception here)
+ logger.error("{} Cloudify workflow failure: {} {} Execute Workflow: Failed: {}",
+ MessageEnum.RA_CREATE_STACK_ERR, execution.getError(),
+ ErrorCode.BusinessProcesssError.getValue(), execution.getError());
+ return execution;
+ } else if (status.equals(CANCELLED)) {
+ // Workflow was cancelled, leaving the deployment in an indeterminate state. Log it and return the
+ // execution object (don't throw exception here)
+ logger.error("{} Cloudify workflow cancelled. Deployment is in an indeterminate state {} {} {}",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
+ "Execute Workflow cancelled: ", workflowId);
+ return execution;
+ } else {
+ // Can only get here after a timeout
+ logger.error("{} Cloudify workflow timeout {} Execute Workflow: Timed Out",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
+ }
+ } catch (CloudifyConnectException ce) {
+ logger.error("{} {} Execute Workflow ({} {}): Cloudify connection failure {} ",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), command, ce);
+ savedException = ce;
+ } catch (CloudifyResponseException re) {
+ logger.error("{} {} Execute Workflow ({}): Cloudify response error {} ", MessageEnum.RA_CREATE_STACK_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), command, re.getMessage(), re);
+ savedException = re;
+ } catch (RuntimeException e) {
+ // Catch-all
+ logger.error("{} {} Execute Workflow ({}): Internal error {}", MessageEnum.RA_CREATE_STACK_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), command, e.getMessage(), e);
+ savedException = e;
+ }
+
+ // Get to this point ONLY on an error or timeout
+ // The cloudify execution is still running (we've not received a terminal status),
+ // so try to Cancel it.
+ CancelExecutionParams cancelParams = new CancelExecutionParams();
+ cancelParams.setAction("cancel");
+ // TODO: Use force_cancel?
+
+ Execution cancelExecution = null;
+
+ try {
+ CancelExecution cancelRequest = cloudify.executions().cancel(executionId, cancelParams);
+ logger.debug(cancelRequest.toString());
+ cancelExecution = cancelRequest.execute();
+
+ // Enter polling loop
+ boolean timedOut = false;
+ int cancelTimeout = timeout; // TODO: For now, just use same timeout
+
+ String status = cancelExecution.getStatus();
+
+ // Poll for completion. Create a reusable cloudify query request
+ GetExecution queryExecution = cloudify.executions().byId(executionId);
+
+ while (!timedOut && !status.equals(CANCELLED)) {
+ // workflow is still running; check for timeout
+ if (cancelTimeout <= 0) {
+ logger.debug("Cancel timeout for workflow {} on deployment {}", workflowId, deploymentId);
+ timedOut = true;
+ continue;
+ }
+
+ sleep(pollInterval * 1000L);
+
+ cancelTimeout -= pollInterval;
+ logger.debug("pollTimeout remaining: {}", cancelTimeout);
+
+ execution = queryExecution.execute();
+ status = execution.getStatus();
+ }
+
+ // Broke the loop. Check again for a terminal state
+ if (status.equals(CANCELLED)) {
+ // Finished cancelling. Return the original exception
+ logger.debug("Cancel workflow {} completed on deployment {}", workflowId, deploymentId);
+ throw new MsoCloudifyException(-1, "", "", savedException);
+ } else {
+ // Can only get here after a timeout
+ logger.debug("Cancel workflow {} timeout out on deployment {}", workflowId, deploymentId);
+ MsoCloudifyException exception = new MsoCloudifyException(-1, "", "", savedException);
+ exception.setPendingWorkflow(true);
+ throw exception;
+ }
+ } catch (Exception e) {
+ // Catch-all. Log the message and throw the original exception
+ logger.debug("Cancel workflow {} failed for deployment {} :", workflowId, deploymentId, e);
+ MsoCloudifyException exception = new MsoCloudifyException(-1, "", "", savedException);
+ exception.setPendingWorkflow(true);
+ throw exception;
+ }
}
/**
- * Query for a Cloudify Deployment (by Name). This call will always return a
- * DeploymentInfo object. If the deployment does not exist, an "empty" DeploymentInfo will be
- * returned - containing only the deployment ID and a special status of NOTFOUND.
+ * Query for a Cloudify Deployment (by Name). This call will always return a DeploymentInfo object. If the
+ * deployment does not exist, an "empty" DeploymentInfo will be returned - containing only the deployment ID and a
+ * special status of NOTFOUND.
*
* @param tenantId The Openstack ID of the tenant in which to query
* @param cloudSiteId The cloud identifier (may be a region) in which to query
* @return A StackInfo object
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
*/
- public DeploymentInfo queryDeployment (String cloudSiteId, String tenantId, String deploymentId)
- throws MsoException
- {
- logger.debug ("Query Cloudify Deployment: {} in tenant {}", deploymentId, tenantId);
+ public DeploymentInfo queryDeployment(String cloudSiteId, String tenantId, String deploymentId)
+ throws MsoException {
+ logger.debug("Query Cloudify Deployment: {} in tenant {}", deploymentId, tenantId);
// Obtain the cloud site information where we will create the stack
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSite.isPresent()) {
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- Cloudify cloudify = getCloudifyClient (cloudSite.get());
-
- // Build and send the Cloudify request
- Deployment deployment = new Deployment();
- DeploymentOutputs outputs = null;
- try {
- GetDeployment queryDeployment = cloudify.deployments().byId(deploymentId);
- logger.debug(queryDeployment.toString());
-
-// deployment = queryDeployment.execute();
- deployment = executeAndRecordCloudifyRequest(queryDeployment);
-
- outputs = getDeploymentOutputs (cloudify, deploymentId);
-
- // Next look for the latest execution
- ListExecutions listExecutions = cloudify.executions().listFiltered ("deployment_id=" + deploymentId, "-created_at");
- Executions executions = listExecutions.execute();
-
- // If no executions, does this give NOT_FOUND or empty set?
- if (executions.getItems().isEmpty()) {
- return new DeploymentInfoBuilder()
- .withId(deployment.getId())
- .withDeploymentInputs(deployment.getInputs())
- .build();
- }
- else {
- return new DeploymentInfoBuilder()
- .withId(deployment.getId())
- .withDeploymentInputs(deployment.getInputs())
- .withDeploymentOutputs(outputs.getOutputs())
- .fromExecution(executions.getItems().get(0))
- .build();
- }
- }
- catch (CloudifyConnectException ce) {
- // Couldn't connect to Cloudify
- logger.error("{} QueryDeployment: Cloudify connection failure: {} ", MessageEnum.RA_CREATE_STACK_ERR,
- ErrorCode.BusinessProcesssError.getValue(), ce);
- throw new MsoIOException (ce.getMessage(), ce);
- }
- catch (CloudifyResponseException re) {
- if (re.getStatus () == 404) {
- // Got a NOT FOUND error. React differently based on deployment vs. execution
- if (deployment != null) {
- // Got NOT_FOUND on the executions. Assume this is a valid "empty" set
- return new DeploymentInfoBuilder()
- .withId(deployment.getId())
- .withDeploymentInputs(deployment.getInputs())
- .withDeploymentOutputs(outputs.getOutputs())
- .build();
- } else {
- // Deployment not found. Default status of a DeploymentInfo object is NOTFOUND
- return new DeploymentInfoBuilder().withId(deploymentId).build();
- }
+ Cloudify cloudify = getCloudifyClient(cloudSite.get());
+
+ // Build and send the Cloudify request
+ Deployment deployment = new Deployment();
+ try {
+ GetDeployment queryDeployment = cloudify.deployments().byId(deploymentId);
+ logger.debug(queryDeployment.toString());
+ deployment = executeAndRecordCloudifyRequest(queryDeployment);
+
+ // Next look for the latest execution
+ ListExecutions listExecutions =
+ cloudify.executions().listFiltered("deployment_id=" + deploymentId, "-created_at");
+ Executions executions = listExecutions.execute();
+
+ // If no executions, does this give NOT_FOUND or empty set?
+ if (executions.getItems().isEmpty()) {
+ return new DeploymentInfoBuilder().withId(deployment.getId())
+ .withDeploymentInputs(deployment.getInputs()).build();
+ } else {
+ return new DeploymentInfoBuilder().withId(deployment.getId())
+ .withDeploymentInputs(deployment.getInputs())
+ .withDeploymentOutputs(getDeploymentOutputs(cloudify, deploymentId).get())
+ .fromExecution(executions.getItems().get(0)).build();
}
- throw new MsoCloudifyException (re.getStatus(), re.getMessage(), re.getLocalizedMessage(), re);
- }
- catch (Exception e) {
- // Catch-all
- throw new MsoAdapterException (e.getMessage(), e);
- }
+ } catch (CloudifyConnectException ce) {
+ // Couldn't connect to Cloudify
+ logger.error("{} QueryDeployment: Cloudify connection failure: {} ", MessageEnum.RA_CREATE_STACK_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), ce);
+ throw new MsoIOException(ce.getMessage(), ce);
+ } catch (CloudifyResponseException re) {
+ if (re.getStatus() == 404) {
+ // Got a NOT FOUND error. React differently based on deployment vs. execution
+ if (deployment != null) {
+ // Got NOT_FOUND on the executions. Assume this is a valid "empty" set
+ return new DeploymentInfoBuilder().withId(deployment.getId())
+ .withDeploymentInputs(deployment.getInputs())
+ .withDeploymentOutputs(getDeploymentOutputs(cloudify, deploymentId).get()).build();
+ } else {
+ // Deployment not found. Default status of a DeploymentInfo object is NOTFOUND
+ return new DeploymentInfoBuilder().withId(deploymentId).build();
+ }
+ }
+ throw new MsoCloudifyException(re.getStatus(), re.getMessage(), re.getLocalizedMessage(), re);
+ } catch (Exception e) {
+ // Catch-all
+ throw new MsoAdapterException(e.getMessage(), e);
+ }
}
/**
- * Delete a Cloudify deployment (by ID). If the deployment is not found, it will be
- * considered a successful deletion. The return value is a DeploymentInfo object which
- * contains the last deployment status.
+ * Delete a Cloudify deployment (by ID). If the deployment is not found, it will be considered a successful
+ * deletion. The return value is a DeploymentInfo object which contains the last deployment status.
*
- * There is no rollback from a successful deletion. A deletion failure will
- * also result in an undefined deployment state - the components may or may not have been
- * all or partially deleted, so the resulting deployment must be considered invalid.
+ * There is no rollback from a successful deletion. A deletion failure will also result in an undefined deployment
+ * state - the components may or may not have been all or partially deleted, so the resulting deployment must be
+ * considered invalid.
*
* @param tenantId The Openstack ID of the tenant in which to perform the delete
* @param cloudSiteId The cloud identifier (may be a region) from which to delete the stack.
@@ -654,274 +605,247 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
* @throws MsoCloudSiteNotFound
*/
- public DeploymentInfo uninstallAndDeleteDeployment (String cloudSiteId,
- String tenantId,
- String deploymentId,
- int timeoutMinutes) throws MsoException
- {
+ public DeploymentInfo uninstallAndDeleteDeployment(String cloudSiteId, String tenantId, String deploymentId,
+ int timeoutMinutes) throws MsoException {
// Obtain the cloud site information where we will create the stack
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSite.isPresent()) {
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- Cloudify cloudify = getCloudifyClient (cloudSite.get());
+ Cloudify cloudify = getCloudifyClient(cloudSite.get());
- logger.debug ("Ready to Uninstall/Delete Deployment ({})", deploymentId);
+ logger.debug("Ready to Uninstall/Delete Deployment ({})", deploymentId);
// Query first to save the trouble if deployment not found
- Deployment deployment = null;
- try {
- GetDeployment queryDeploymentRequest = cloudify.deployments().byId(deploymentId);
- logger.debug(queryDeploymentRequest.toString());
-
- deployment = executeAndRecordCloudifyRequest (queryDeploymentRequest);
- }
- catch (CloudifyResponseException e) {
+ try {
+ GetDeployment queryDeploymentRequest = cloudify.deployments().byId(deploymentId);
+ logger.debug(queryDeploymentRequest.toString());
+
+ // deployment = executeAndRecordCloudifyRequest (queryDeploymentRequest);
+ } catch (CloudifyResponseException e) {
// Since this came on the 'Create Deployment' command, nothing was changed
// in the cloud. Return the error as an exception.
- if (e.getStatus () == 404) {
- // Deployment doesn't exist. Return a "NOTFOUND" DeploymentInfo object
- // TODO: Should return NULL?
+ if (e.getStatus() == 404) {
+ // Deployment doesn't exist. Return a "NOTFOUND" DeploymentInfo object
+ // TODO: Should return NULL?
logger.debug("Deployment requested for deletion does not exist: {}", deploymentId);
- return new DeploymentInfoBuilder()
- .withId(deploymentId)
- .withStatus(DeploymentStatus.NOTFOUND)
- .build();
- } else {
+ return new DeploymentInfoBuilder().withId(deploymentId).withStatus(DeploymentStatus.NOTFOUND).build();
+ } else {
// Convert the CloudifyResponseException to an MsoOpenstackException
logger.debug("ERROR STATUS = {}, \n {}\n {}\n {}", e.getStatus(), e.getMessage(),
- e.getLocalizedMessage(), e);
- MsoException me = cloudifyExceptionToMsoException (e, DELETE_DEPLOYMENT);
- me.setCategory (MsoExceptionCategory.INTERNAL);
+ e.getLocalizedMessage(), e);
+ MsoException me = cloudifyExceptionToMsoException(e, DELETE_DEPLOYMENT);
+ me.setCategory(MsoExceptionCategory.INTERNAL);
throw me;
}
} catch (CloudifyConnectException e) {
// Error connecting to Cloudify instance. Convert to an MsoException
- throw cloudifyExceptionToMsoException (e, DELETE_DEPLOYMENT);
+ throw cloudifyExceptionToMsoException(e, DELETE_DEPLOYMENT);
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, DELETE_DEPLOYMENT);
+ throw runtimeExceptionToMsoException(e, DELETE_DEPLOYMENT);
}
- /*
- * Query the outputs before deleting so they can be returned as well
- */
- DeploymentOutputs outputs = getDeploymentOutputs (cloudify, deploymentId);
-
- /*
- * Next execute the "uninstall" workflow.
- * Note - this assumes there are no additional parameters required for the workflow.
- */
- // TODO: No deletePollInterval that I'm aware of. Use the create interval
- int deletePollInterval = Integer.parseInt(this.environment.getProperty (deletePollIntervalProp, deletePollIntervalDefault));
+ /*
+ * Query the outputs before deleting so they can be returned as well
+ */
+ // DeploymentOutputs outputs = getDeploymentOutputs (cloudify, deploymentId);
+
+ /*
+ * Next execute the "uninstall" workflow. Note - this assumes there are no additional parameters required for
+ * the workflow.
+ */
+ // TODO: No deletePollInterval that I'm aware of. Use the create interval
+ int deletePollInterval =
+ Integer.parseInt(this.environment.getProperty(deletePollIntervalProp, deletePollIntervalDefault));
int pollTimeout = (timeoutMinutes * 60) + deletePollInterval;
Execution uninstallWorkflow = null;
try {
- uninstallWorkflow = executeWorkflow (cloudify, deploymentId, "uninstall", null, true, pollTimeout, deletePollInterval);
-
- if (uninstallWorkflow.getStatus().equals(TERMINATED)) {
- // Successful uninstall.
- logger.debug("Uninstall successful for deployment {}", deploymentId);
- }
- else {
- // The uninstall workflow completed with an error. Must fail the request, but will
- // leave the deployment in an indeterminate state, as cloud resources may still exist.
- MsoCloudifyException me = new MsoCloudifyException (0, "Uninstall Workflow Failed", uninstallWorkflow.getError());
- me.addContext (DELETE_DEPLOYMENT);
+ uninstallWorkflow =
+ executeWorkflow(cloudify, deploymentId, "uninstall", null, true, pollTimeout, deletePollInterval);
+
+ if (uninstallWorkflow.getStatus().equals(TERMINATED)) {
+ // Successful uninstall.
+ logger.debug("Uninstall successful for deployment {}", deploymentId);
+ } else {
+ // The uninstall workflow completed with an error. Must fail the request, but will
+ // leave the deployment in an indeterminate state, as cloud resources may still exist.
+ MsoCloudifyException me =
+ new MsoCloudifyException(0, "Uninstall Workflow Failed", uninstallWorkflow.getError());
+ me.addContext(DELETE_DEPLOYMENT);
throw me;
- }
- }
- catch (MsoException me) {
- // Uninstall workflow has failed.
- // Must fail the deletion... may leave the deployment in an inconclusive state
- me.addContext (DELETE_DEPLOYMENT);
+ }
+ } catch (MsoException me) {
+ // Uninstall workflow has failed.
+ // Must fail the deletion... may leave the deployment in an inconclusive state
+ me.addContext(DELETE_DEPLOYMENT);
throw me;
}
-
+
// At this point, the deployment has been successfully uninstalled.
// Next step is to delete the deployment itself
+ Deployment deployment;
try {
- DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId);
+ DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId);
logger.debug(deleteRequest.toString());
- // The delete request returns the deleted deployment
- deployment = deleteRequest.execute();
+ // The delete request returns the deleted deployment
+ deployment = deleteRequest.execute();
- }
- catch (CloudifyConnectException ce) {
- // Failed to delete. Must fail the request, but will leave the (uninstalled)
- // deployment in Cloudify DB.
- MsoCloudifyException me = new MsoCloudifyException (0, "Deployment Delete Failed", ce.getMessage(), ce);
- me.addContext (DELETE_DEPLOYMENT);
+ } catch (CloudifyConnectException ce) {
+ // Failed to delete. Must fail the request, but will leave the (uninstalled)
+ // deployment in Cloudify DB.
+ MsoCloudifyException me = new MsoCloudifyException(0, "Deployment Delete Failed", ce.getMessage(), ce);
+ me.addContext(DELETE_DEPLOYMENT);
throw me;
- }
- catch (CloudifyResponseException re) {
- // Failed to delete. Must fail the request, but will leave the (uninstalled)
- // deployment in the Cloudify DB.
- MsoCloudifyException me = new MsoCloudifyException (re.getStatus(), re.getMessage(), re.getMessage(), re);
- me.addContext (DELETE_DEPLOYMENT);
+ } catch (CloudifyResponseException re) {
+ // Failed to delete. Must fail the request, but will leave the (uninstalled)
+ // deployment in the Cloudify DB.
+ MsoCloudifyException me = new MsoCloudifyException(re.getStatus(), re.getMessage(), re.getMessage(), re);
+ me.addContext(DELETE_DEPLOYMENT);
throw me;
- }
- catch (Exception e) {
- // Catch-all
- MsoAdapterException ae = new MsoAdapterException (e.getMessage(), e);
- ae.addContext (DELETE_DEPLOYMENT);
+ } catch (Exception e) {
+ // Catch-all
+ MsoAdapterException ae = new MsoAdapterException(e.getMessage(), e);
+ ae.addContext(DELETE_DEPLOYMENT);
throw ae;
}
- // Return the deleted deployment info (with runtime outputs) along with the completed uninstall workflow status
- return new DeploymentInfoBuilder()
- .withId(deployment.getId())
- .withDeploymentInputs(deployment.getInputs())
- .withDeploymentOutputs(outputs.getOutputs())
- .fromExecution(uninstallWorkflow)
- .build();
+ // Return the deleted deployment info (with runtime outputs) along with the completed uninstall workflow status
+ return new DeploymentInfoBuilder().withId(deployment.getId()).withDeploymentInputs(deployment.getInputs())
+ .withDeploymentOutputs(getDeploymentOutputs(cloudify, deploymentId).get())
+ .fromExecution(uninstallWorkflow).build();
}
/**
- * Check if a blueprint is available for use at a targeted cloud site.
- * This requires checking the Cloudify Manager which is servicing that
- * cloud site to see if the specified blueprint has been loaded.
+ * Check if a blueprint is available for use at a targeted cloud site. This requires checking the Cloudify Manager
+ * which is servicing that cloud site to see if the specified blueprint has been loaded.
*
* @param cloudSiteId The cloud site where the blueprint is needed
* @param blueprintId The ID for the blueprint in Cloudify
*/
- public boolean isBlueprintLoaded (String cloudSiteId, String blueprintId)
- throws MsoException
- {
+ public boolean isBlueprintLoaded(String cloudSiteId, String blueprintId) throws MsoException {
// Obtain the cloud site information where we will load the blueprint
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSite.isPresent()) {
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- Cloudify cloudify = getCloudifyClient (cloudSite.get());
-
- GetBlueprint getRequest = cloudify.blueprints().getMetadataById(blueprintId);
- try {
- Blueprint bp = getRequest.execute();
- logger.debug("Blueprint exists: {}", bp.getId());
- return true;
- }
- catch (CloudifyResponseException ce) {
- if (ce.getStatus() == 404) {
- return false;
- } else {
- throw ce;
- }
- } catch (Exception e) {
- throw e;
- }
+ Cloudify cloudify = getCloudifyClient(cloudSite.get());
+
+ GetBlueprint getRequest = cloudify.blueprints().getMetadataById(blueprintId);
+ try {
+ Blueprint bp = getRequest.execute();
+ logger.debug("Blueprint exists: {}", bp.getId());
+ return true;
+ } catch (CloudifyResponseException ce) {
+ if (ce.getStatus() == 404) {
+ return false;
+ } else {
+ throw ce;
+ }
+ } catch (Exception e) {
+ throw e;
+ }
}
/**
- * Upload a blueprint to the Cloudify Manager that is servicing a Cloud Site.
- * The blueprint currently must be structured as a single directory with all
- * of the required files. One of those files is designated the "main file"
- * for the blueprint. Files are provided as byte arrays, though expect only
- * text files will be distributed from ASDC and stored by MSO.
+ * Upload a blueprint to the Cloudify Manager that is servicing a Cloud Site. The blueprint currently must be
+ * structured as a single directory with all of the required files. One of those files is designated the "main file"
+ * for the blueprint. Files are provided as byte arrays, though expect only text files will be distributed from ASDC
+ * and stored by MSO.
*
- * Cloudify requires a single root directory in its blueprint zip files.
- * The requested blueprint ID will also be used as the directory.
- * All of the files will be added to this directory in the zip file.
+ * Cloudify requires a single root directory in its blueprint zip files. The requested blueprint ID will also be
+ * used as the directory. All of the files will be added to this directory in the zip file.
*/
- public void uploadBlueprint (String cloudSiteId,
- String blueprintId,
- String mainFileName,
- Map<String,byte[]> blueprintFiles,
- boolean failIfExists)
- throws MsoException
- {
+ public void uploadBlueprint(String cloudSiteId, String blueprintId, String mainFileName,
+ Map<String, byte[]> blueprintFiles, boolean failIfExists) throws MsoException {
// Obtain the cloud site information where we will load the blueprint
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSite.isPresent()) {
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- Cloudify cloudify = getCloudifyClient (cloudSite.get());
+ Cloudify cloudify = getCloudifyClient(cloudSite.get());
- boolean blueprintUploaded = uploadBlueprint (cloudify, blueprintId, mainFileName, blueprintFiles);
+ boolean blueprintUploaded = uploadBlueprint(cloudify, blueprintId, mainFileName, blueprintFiles);
if (!blueprintUploaded && failIfExists) {
- throw new MsoAdapterException ("Blueprint already exists");
+ throw new MsoAdapterException("Blueprint already exists");
}
}
/*
- * Common method to load a blueprint. May be called from
+ * Common method to load a blueprint. May be called from
*/
- protected boolean uploadBlueprint (Cloudify cloudify, String blueprintId, String mainFileName, Map<String,byte[]> blueprintFiles)
- throws MsoException
- {
- // Check if it already exists. If so, return false.
- GetBlueprint getRequest = cloudify.blueprints().getMetadataById(blueprintId);
- try {
- Blueprint bp = getRequest.execute();
- logger.debug("Blueprint {} already exists.", bp.getId());
- return false;
- }
- catch (CloudifyResponseException ce) {
- if (ce.getStatus() == 404) {
- // This is the expected result.
- logger.debug("Verified that Blueprint doesn't exist yet");
- } else {
- throw ce;
- }
- } catch (Exception e) {
- throw e;
- }
-
- // Create a blueprint ZIP file in memory
- ByteArrayOutputStream zipBuffer = new ByteArrayOutputStream();
- ZipOutputStream zipOut = new ZipOutputStream(zipBuffer);
-
- try {
- // Put the root directory
- String rootDir = blueprintId + ((blueprintId.endsWith("/") ? "" : "/"));
- zipOut.putNextEntry(new ZipEntry (rootDir));
- zipOut.closeEntry();
-
- for (String fileName : blueprintFiles.keySet()) {
- ZipEntry ze = new ZipEntry (rootDir + fileName);
- zipOut.putNextEntry (ze);
- zipOut.write (blueprintFiles.get(fileName));
- zipOut.closeEntry();
- }
- zipOut.close();
- }
- catch (IOException e) {
- // Since we're writing to a byte array, this should never happen
- }
+ protected boolean uploadBlueprint(Cloudify cloudify, String blueprintId, String mainFileName,
+ Map<String, byte[]> blueprintFiles) throws MsoException {
+ // Check if it already exists. If so, return false.
+ GetBlueprint getRequest = cloudify.blueprints().getMetadataById(blueprintId);
+ try {
+ Blueprint bp = getRequest.execute();
+ logger.debug("Blueprint {} already exists.", bp.getId());
+ return false;
+ } catch (CloudifyResponseException ce) {
+ if (ce.getStatus() == 404) {
+ // This is the expected result.
+ logger.debug("Verified that Blueprint doesn't exist yet");
+ } else {
+ throw ce;
+ }
+ } catch (Exception e) {
+ throw e;
+ }
+
+ // Create a blueprint ZIP file in memory
+ ByteArrayOutputStream zipBuffer = new ByteArrayOutputStream();
+ ZipOutputStream zipOut = new ZipOutputStream(zipBuffer);
+
+ try {
+ // Put the root directory
+ String rootDir = blueprintId + ((blueprintId.endsWith("/") ? "" : "/"));
+ zipOut.putNextEntry(new ZipEntry(rootDir));
+ zipOut.closeEntry();
+
+ for (String fileName : blueprintFiles.keySet()) {
+ ZipEntry ze = new ZipEntry(rootDir + fileName);
+ zipOut.putNextEntry(ze);
+ zipOut.write(blueprintFiles.get(fileName));
+ zipOut.closeEntry();
+ }
+ zipOut.close();
+ } catch (IOException e) {
+ // Since we're writing to a byte array, this should never happen
+ }
logger.debug("Blueprint zip file size: {}", zipBuffer.size());
// Ready to upload the blueprint zip
- try (InputStream blueprintStream = new ByteArrayInputStream (zipBuffer.toByteArray())) {
- UploadBlueprint uploadRequest = cloudify.blueprints().uploadFromStream(blueprintId, mainFileName, blueprintStream);
- Blueprint blueprint = uploadRequest.execute();
- logger.debug("Successfully uploaded blueprint {}", blueprint.getId());
- }
- catch (CloudifyResponseException | CloudifyConnectException e) {
- throw cloudifyExceptionToMsoException (e, "UPLOAD_BLUEPRINT");
- }
- catch (RuntimeException e) {
- // Catch-all
- throw runtimeExceptionToMsoException (e, "UPLOAD_BLUEPRINT");
- } catch (IOException e) {
- // for try-with-resources
- throw ioExceptionToMsoException(e, "UPLOAD_BLUEPRINT");
- }
-
- return true;
+ try (InputStream blueprintStream = new ByteArrayInputStream(zipBuffer.toByteArray())) {
+ UploadBlueprint uploadRequest =
+ cloudify.blueprints().uploadFromStream(blueprintId, mainFileName, blueprintStream);
+ Blueprint blueprint = uploadRequest.execute();
+ logger.debug("Successfully uploaded blueprint {}", blueprint.getId());
+ } catch (CloudifyResponseException | CloudifyConnectException e) {
+ throw cloudifyExceptionToMsoException(e, "UPLOAD_BLUEPRINT");
+ } catch (RuntimeException e) {
+ // Catch-all
+ throw runtimeExceptionToMsoException(e, "UPLOAD_BLUEPRINT");
+ } catch (IOException e) {
+ // for try-with-resources
+ throw ioExceptionToMsoException(e, "UPLOAD_BLUEPRINT");
+ }
+
+ return true;
}
@@ -930,35 +854,33 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
// PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
/**
- * Get a Cloudify client for the specified cloud site.
- * Everything that is required can be found in the Cloud Config.
+ * Get a Cloudify client for the specified cloud site. Everything that is required can be found in the Cloud Config.
*
* @param cloudSite
* @return a Cloudify object
*/
- public Cloudify getCloudifyClient (CloudSite cloudSite) throws MsoException
- {
+ public Cloudify getCloudifyClient(CloudSite cloudSite) throws MsoException {
CloudifyManager cloudifyConfig = cloudConfig.getCloudifyManager(cloudSite.getCloudifyId());
if (cloudifyConfig == null) {
- throw new MsoCloudifyManagerNotFound (cloudSite.getId());
+ throw new MsoCloudifyManagerNotFound(cloudSite.getId());
}
// Get a Cloudify client
- // Set a Token Provider to fetch tokens from Cloudify itself.
+ // Set a Token Provider to fetch tokens from Cloudify itself.
String cloudifyUrl = cloudifyConfig.getCloudifyUrl();
- Cloudify cloudify = new Cloudify (cloudifyUrl);
- cloudify.setTokenProvider(new CloudifyClientTokenProvider(cloudifyUrl, cloudifyConfig.getUsername(), CryptoUtils.decryptCloudConfigPassword(cloudifyConfig.getPassword())));
+ Cloudify cloudify = new Cloudify(cloudifyUrl);
+ cloudify.setTokenProvider(new CloudifyClientTokenProvider(cloudifyUrl, cloudifyConfig.getUsername(),
+ CryptoUtils.decryptCloudConfigPassword(cloudifyConfig.getPassword())));
- return cloudify;
+ return cloudify;
}
/*
- * Query for a Cloudify Deployment. This function is needed in several places, so
- * a common method is useful. This method takes an authenticated CloudifyClient
- * (which internally identifies the cloud & tenant to search), and returns
- * a Deployment object if found, Null if not found, or an MsoCloudifyException
- * if the Cloudify API call fails.
+ * Query for a Cloudify Deployment. This function is needed in several places, so a common method is useful. This
+ * method takes an authenticated CloudifyClient (which internally identifies the cloud & tenant to search), and
+ * returns a Deployment object if found, Null if not found, or an MsoCloudifyException if the Cloudify API call
+ * fails.
*
* @param cloudifyClient an authenticated Cloudify client
*
@@ -968,234 +890,223 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
*
* @throws MsoCloudifyException Thrown if the Cloudify API call returns an exception
*/
- protected Deployment queryDeployment (Cloudify cloudify, String deploymentId) throws MsoException {
+ protected Deployment queryDeployment(Cloudify cloudify, String deploymentId) throws MsoException {
if (deploymentId == null) {
return null;
}
try {
- GetDeployment request = cloudify.deployments().byId (deploymentId);
- return executeAndRecordCloudifyRequest (request);
+ GetDeployment request = cloudify.deployments().byId(deploymentId);
+ return executeAndRecordCloudifyRequest(request);
} catch (CloudifyResponseException e) {
- if (e.getStatus () == 404) {
- logger.debug ("queryDeployment - not found: {}", deploymentId);
+ if (e.getStatus() == 404) {
+ logger.debug("queryDeployment - not found: {}", deploymentId);
return null;
} else {
// Convert the CloudifyResponseException to an MsoCloudifyException
- throw cloudifyExceptionToMsoException (e, "QueryDeployment");
+ throw cloudifyExceptionToMsoException(e, "QueryDeployment");
}
} catch (CloudifyConnectException e) {
// Connection to Openstack failed
- throw cloudifyExceptionToMsoException (e, "QueryDeployment");
+ throw cloudifyExceptionToMsoException(e, "QueryDeployment");
}
}
- public void copyStringOutputsToInputs(Map<String, String> inputs,
- Map<String, Object> otherStackOutputs, boolean overWrite) {
- if (inputs == null || otherStackOutputs == null)
- return;
-
- for (Map.Entry<String, Object> entry : otherStackOutputs.entrySet()) {
- String key = entry.getKey();
- Object value = entry.getValue();
-
- if (value instanceof JsonNode) {
- // This is a bit of mess - but I think it's the least impacting
- // let's convert it BACK to a string - then it will get converted back later
- try {
- inputs.put(key, this.convertNode((JsonNode) value));
- } catch (Exception e) {
- logger.debug("WARNING: unable to convert JsonNode output value for {}", key);
- //effect here is this value will not have been copied to the inputs - and therefore will error out downstream
- }
- } else if (value instanceof java.util.LinkedHashMap) {
- logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
- try {
- inputs.put(key, JSON_MAPPER.writeValueAsString(value));
- } catch (Exception e) {
- logger.debug("WARNING: unable to convert LinkedHashMap output value for {}", key);
+ public void copyStringOutputsToInputs(Map<String, String> inputs, Map<String, Object> otherStackOutputs,
+ boolean overWrite) {
+ if (inputs == null || otherStackOutputs == null)
+ return;
+
+ for (Map.Entry<String, Object> entry : otherStackOutputs.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+
+ if (value instanceof JsonNode) {
+ // This is a bit of mess - but I think it's the least impacting
+ // let's convert it BACK to a string - then it will get converted back later
+ try {
+ inputs.put(key, this.convertNode((JsonNode) value));
+ } catch (Exception e) {
+ logger.debug("WARNING: unable to convert JsonNode output value for {}", key);
+ // effect here is this value will not have been copied to the inputs - and therefore will error out
+ // downstream
+ }
+ } else if (value instanceof java.util.LinkedHashMap) {
+ logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
+ try {
+ inputs.put(key, JSON_MAPPER.writeValueAsString(value));
+ } catch (Exception e) {
+ logger.debug("WARNING: unable to convert LinkedHashMap output value for {}", key);
+ }
+ } else {
+ // just try to cast it - could be an integer or some such
+ try {
+ inputs.put(key, (String) value);
+ } catch (Exception e) {
+ logger.debug("WARNING: unable to convert output value for {}", key);
+ // effect here is this value will not have been copied to the inputs - and therefore will error out
+ // downstream
+ }
+ }
}
- } else {
- // just try to cast it - could be an integer or some such
- try {
- inputs.put(key, (String) value);
- } catch (Exception e) {
- logger.debug("WARNING: unable to convert output value for {}", key);
- //effect here is this value will not have been copied to the inputs - and therefore will error out downstream
- }
- }
- }
- return;
- }
-
- /*
- * Normalize an input value to an Object, based on the target parameter type.
- * If the type is not recognized, it will just be returned unchanged (as a string).
- */
- public Object convertInputValue (Object inputValue, HeatTemplateParam templateParam)
- {
- String type = templateParam.getParamType();
- logger.debug("Parameter: {} is of type {}", templateParam.getParamName(), type);
-
- if (type.equalsIgnoreCase("number")) {
- try {
- return Integer.valueOf(inputValue.toString());
- }
- catch (Exception e) {
- logger.debug("Unable to convert {} to an integer!", inputValue);
- return null;
- }
- } else if (type.equalsIgnoreCase("json")) {
- try {
- if (inputValue instanceof String) {
- return JSON_MAPPER.readTree(inputValue.toString());
- }
- //will already marshal to json without intervention
- return inputValue;
- }
- catch (Exception e) {
- logger.debug("Unable to convert {} to a JsonNode!", inputValue);
- return null;
- }
- } else if (type.equalsIgnoreCase("boolean")) {
- return new Boolean(inputValue.toString());
- }
-
- // Nothing else matched. Return the original string
- return inputValue;
- }
-
-
- private String convertNode(final JsonNode node) {
- try {
- final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
- return JSON_MAPPER.writeValueAsString(obj);
- } catch (JsonParseException jpe) {
- logger.debug("Error converting json to string {}", jpe);
- } catch (Exception e) {
- logger.debug("Error converting json to string {}", e);
+ return;
}
- return "[Error converting json to string]";
- }
-
-
+
+ /*
+ * Normalize an input value to an Object, based on the target parameter type. If the type is not recognized, it will
+ * just be returned unchanged (as a string).
+ */
+ public Object convertInputValue(Object inputValue, HeatTemplateParam templateParam) {
+ String type = templateParam.getParamType();
+ logger.debug("Parameter: {} is of type {}", templateParam.getParamName(), type);
+
+ if (type.equalsIgnoreCase("number")) {
+ try {
+ return Integer.valueOf(inputValue.toString());
+ } catch (Exception e) {
+ logger.debug("Unable to convert {} to an integer!", inputValue);
+ return null;
+ }
+ } else if (type.equalsIgnoreCase("json")) {
+ try {
+ if (inputValue instanceof String) {
+ return JSON_MAPPER.readTree(inputValue.toString());
+ }
+ // will already marshal to json without intervention
+ return inputValue;
+ } catch (Exception e) {
+ logger.debug("Unable to convert {} to a JsonNode!", inputValue);
+ return null;
+ }
+ } else if (type.equalsIgnoreCase("boolean")) {
+ return new Boolean(inputValue.toString());
+ }
+
+ // Nothing else matched. Return the original string
+ return inputValue;
+ }
+
+
+ private String convertNode(final JsonNode node) {
+ try {
+ final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
+ return JSON_MAPPER.writeValueAsString(obj);
+ } catch (JsonParseException jpe) {
+ logger.debug("Error converting json to string {}", jpe);
+ } catch (Exception e) {
+ logger.debug("Error converting json to string {}", e);
+ }
+ return "[Error converting json to string]";
+ }
+
+
/*
- * Method to execute a Cloudify command and track its execution time.
- * For the metrics log, a category of "Cloudify" is used along with a
- * sub-category that identifies the specific call (using the real
- * cloudify-client classname of the CloudifyRequest<T> parameter).
+ * Method to execute a Cloudify command and track its execution time. For the metrics log, a category of "Cloudify"
+ * is used along with a sub-category that identifies the specific call (using the real cloudify-client classname of
+ * the CloudifyRequest<T> parameter).
*/
- protected <T> T executeAndRecordCloudifyRequest (CloudifyRequest <T> request) {
+ protected <T> T executeAndRecordCloudifyRequest(CloudifyRequest<T> request) {
- String requestType;
- if (request.getClass ().getEnclosingClass () != null) {
- requestType = request.getClass ().getEnclosingClass ().getSimpleName () + "."
- + request.getClass ().getSimpleName ();
+ String requestType;
+ if (request.getClass().getEnclosingClass() != null) {
+ requestType =
+ request.getClass().getEnclosingClass().getSimpleName() + "." + request.getClass().getSimpleName();
} else {
- requestType = request.getClass ().getSimpleName ();
+ requestType = request.getClass().getSimpleName();
}
int retryDelay = poConfig.getRetryDelay();
int retryCount = poConfig.getRetryCount();
- String retryCodes = poConfig.getRetryCodes();
+ String retryCodes = poConfig.getRetryCodes();
// Run the actual command. All exceptions will be propagated
- while (true)
- {
- try {
- return request.execute ();
- }
- catch (CloudifyResponseException e) {
- boolean retry = false;
- if (retryCodes != null ) {
- int code = e.getStatus();
- logger.debug("Config values RetryDelay: {} RetryCount:{} RetryCodes:{} ResponseCode:{}", retryDelay,
- retryCount, retryCodes, code);
- for (String rCode : retryCodes.split (",")) {
- try {
- if (retryCount > 0 && code == Integer.parseInt (rCode))
- {
- retryCount--;
- retry = true;
- logger.debug(
- "CloudifyResponseException ResponseCode:{} request:{} Retry indicated. Attempts remaining:{}",
- code, requestType, retryCount);
- break;
- }
- } catch (NumberFormatException e1) {
- logger.error("{} No retries. Exception in parsing retry code in config:{} {}",
- MessageEnum.RA_CONFIG_EXC, rCode, ErrorCode.SchemaError.getValue());
+ while (true) {
+ try {
+ return request.execute();
+ } catch (CloudifyResponseException e) {
+ boolean retry = false;
+ if (retryCodes != null) {
+ int code = e.getStatus();
+ logger.debug("Config values RetryDelay: {} RetryCount:{} RetryCodes:{} ResponseCode:{}", retryDelay,
+ retryCount, retryCodes, code);
+ for (String rCode : retryCodes.split(",")) {
+ try {
+ if (retryCount > 0 && code == Integer.parseInt(rCode)) {
+ retryCount--;
+ retry = true;
+ logger.debug(
+ "CloudifyResponseException ResponseCode:{} request:{} Retry indicated. Attempts remaining:{}",
+ code, requestType, retryCount);
+ break;
+ }
+ } catch (NumberFormatException e1) {
+ logger.error("{} No retries. Exception in parsing retry code in config:{} {}",
+ MessageEnum.RA_CONFIG_EXC, rCode, ErrorCode.SchemaError.getValue());
+ throw e;
+ }
+ }
+ }
+ if (retry) {
+ sleep(retryDelay * 1000L);
+ } else
+ throw e; // exceeded retryCount or code is not retryable
+ } catch (CloudifyConnectException e) {
+ // Connection to Cloudify failed
+ if (retryCount > 0) {
+ retryCount--;
+ logger.debug(" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount);
+ sleep(retryDelay * 1000L);
+ } else
throw e;
- }
- }
- }
- if (retry)
- {
- sleep(retryDelay * 1000L);
- }
- else
- throw e; // exceeded retryCount or code is not retryable
- }
- catch (CloudifyConnectException e) {
- // Connection to Cloudify failed
- if (retryCount > 0)
- {
- retryCount--;
- logger.debug(" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount);
- sleep(retryDelay * 1000L);
- }
- else
- throw e;
-
- }
+
+ }
}
}
+
/*
- * Convert an Exception on a Cloudify call to an MsoCloudifyException.
- * This method supports CloudifyResponseException and CloudifyConnectException.
+ * Convert an Exception on a Cloudify call to an MsoCloudifyException. This method supports
+ * CloudifyResponseException and CloudifyConnectException.
*/
- protected MsoException cloudifyExceptionToMsoException (CloudifyBaseException e, String context) {
+ protected MsoException cloudifyExceptionToMsoException(CloudifyBaseException e, String context) {
MsoException me = null;
if (e instanceof CloudifyResponseException) {
- CloudifyResponseException re = (CloudifyResponseException) e;
+ CloudifyResponseException re = (CloudifyResponseException) e;
try {
// Failed Cloudify calls return an error entity body.
- CloudifyError error = re.getResponse ().getErrorEntity (CloudifyError.class);
+ CloudifyError error = re.getResponse().getErrorEntity(CloudifyError.class);
logger.error("{} {} {} Exception - Cloudify Error on {}: {}", MessageEnum.RA_CONNECTION_EXCEPTION,
- CLOUDIFY, ErrorCode.DataError.getValue(), context, error.getErrorCode());
+ CLOUDIFY, ErrorCode.DataError.getValue(), context, error.getErrorCode());
String fullError = error.getErrorCode() + ": " + error.getMessage();
logger.debug(fullError);
- me = new MsoCloudifyException (re.getStatus(),
- re.getMessage(),
- fullError);
+ me = new MsoCloudifyException(re.getStatus(), re.getMessage(), fullError);
} catch (Exception e2) {
// Couldn't parse the body as a "CloudifyError". Report the original HTTP error.
logger.error("{} {} {} Exception - HTTP Error on {}: {}, {} ", MessageEnum.RA_CONNECTION_EXCEPTION,
- CLOUDIFY, ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2);
- me = new MsoCloudifyException (re.getStatus (), re.getMessage (), "");
+ CLOUDIFY, ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2);
+ me = new MsoCloudifyException(re.getStatus(), re.getMessage(), "");
}
// Add the context of the error
- me.addContext (context);
+ me.addContext(context);
// Generate an alarm for 5XX and higher errors.
- if (re.getStatus () >= 500) {
+ if (re.getStatus() >= 500) {
}
} else if (e instanceof CloudifyConnectException) {
- CloudifyConnectException ce = (CloudifyConnectException) e;
+ CloudifyConnectException ce = (CloudifyConnectException) e;
- me = new MsoIOException (ce.getMessage ());
- me.addContext (context);
+ me = new MsoIOException(ce.getMessage());
+ me.addContext(context);
// Generate an alarm for all connection errors.
logger.error("{} {} {} Cloudify connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY,
- ErrorCode.DataError.getValue(), context, e);
+ ErrorCode.DataError.getValue(), context, e);
}
return me;
@@ -1212,88 +1123,75 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
/**
* VduPlugin interface for instantiate function.
*
- * This one is a bit more complex, in that it will first upload the blueprint if needed,
- * then create the Cloudify deployment and execute the install workflow.
+ * This one is a bit more complex, in that it will first upload the blueprint if needed, then create the Cloudify
+ * deployment and execute the install workflow.
*
- * This implementation also merges any parameters defined in the ENV file with the other
- * other input parameters for any undefined parameters).
- * The basic MsoCloudifyUtils separates blueprint management from deploument actions,
- * but the VduPlugin does not declare blueprint management operations.
+ * This implementation also merges any parameters defined in the ENV file with the other other input parameters for
+ * any undefined parameters). The basic MsoCloudifyUtils separates blueprint management from deploument actions, but
+ * the VduPlugin does not declare blueprint management operations.
*/
@Override
- public VduInstance instantiateVdu (
- CloudInfo cloudInfo,
- String instanceName,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException
- {
- String cloudSiteId = cloudInfo.getCloudSiteId();
- String tenantId = cloudInfo.getTenantId();
-
- // Translate the VDU ModelInformation structure to that which is needed for
- // creating and uploading a blueprint. Use the model customization UUID as
- // the blueprint identifier.
-
- String blueprintId = vduModel.getModelCustomizationUUID();
-
- try {
-
- if (! isBlueprintLoaded (cloudSiteId, blueprintId)) {
- logger.debug("Blueprint {} is not loaded. Will upload it now.", blueprintId);
-
- // Prepare the blueprint inputs. Need the set of blueprint templates and files,
- // plus the main blueprint name.
- Map<String,byte[]> blueprintFiles = new HashMap<>();
- String mainTemplate = "";
-
- // Add all of the blueprint artifacts from the VDU model
- List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
- for (VduArtifact vduArtifact: vduArtifacts)
- {
- // Add all artifacts to the blueprint, with one exception.
- // ENVIRONMENT files will be processed later as additional parameters.
-
- ArtifactType artifactType = vduArtifact.getType();
- if (artifactType != ArtifactType.ENVIRONMENT) {
- blueprintFiles.put(vduArtifact.getName(), vduArtifact.getContent());
-
- if (artifactType == ArtifactType.MAIN_TEMPLATE) {
- mainTemplate = vduArtifact.getName();
- }
- }
- }
-
- // Upload the blueprint package
- uploadBlueprint(cloudSiteId, blueprintId, mainTemplate, blueprintFiles, false);
- }
- }
- catch (Exception e) {
- throw new VduException ("CloudifyUtils (instantiateVDU): blueprint Exception", e);
- }
-
-
- // Next, create and install a new deployment based on the blueprint.
- // For Cloudify, the deploymentId is specified by the client. Just use the instance name
- // as the ID.
-
- try {
- // Query the Cloudify Deployment object and populate a VduInstance
- DeploymentInfo deployment = createAndInstallDeployment (cloudSiteId,
- tenantId,
- instanceName,
- blueprintId,
- inputs,
- true, // (poll for completion)
- vduModel.getTimeoutMinutes(),
- rollbackOnFailure);
-
- return deploymentInfoToVduInstance(deployment);
- }
- catch (Exception e) {
- throw new VduException ("CloudifyUtils (instantiateVDU): Create-and-install-deployment Exception", e);
- }
+ public VduInstance instantiateVdu(CloudInfo cloudInfo, String instanceName, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException {
+ String cloudSiteId = cloudInfo.getCloudSiteId();
+ String tenantId = cloudInfo.getTenantId();
+
+ // Translate the VDU ModelInformation structure to that which is needed for
+ // creating and uploading a blueprint. Use the model customization UUID as
+ // the blueprint identifier.
+
+ String blueprintId = vduModel.getModelCustomizationUUID();
+
+ try {
+
+ if (!isBlueprintLoaded(cloudSiteId, blueprintId)) {
+ logger.debug("Blueprint {} is not loaded. Will upload it now.", blueprintId);
+
+ // Prepare the blueprint inputs. Need the set of blueprint templates and files,
+ // plus the main blueprint name.
+ Map<String, byte[]> blueprintFiles = new HashMap<>();
+ String mainTemplate = "";
+
+ // Add all of the blueprint artifacts from the VDU model
+ List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
+ for (VduArtifact vduArtifact : vduArtifacts) {
+ // Add all artifacts to the blueprint, with one exception.
+ // ENVIRONMENT files will be processed later as additional parameters.
+
+ ArtifactType artifactType = vduArtifact.getType();
+ if (artifactType != ArtifactType.ENVIRONMENT) {
+ blueprintFiles.put(vduArtifact.getName(), vduArtifact.getContent());
+
+ if (artifactType == ArtifactType.MAIN_TEMPLATE) {
+ mainTemplate = vduArtifact.getName();
+ }
+ }
+ }
+
+ // Upload the blueprint package
+ uploadBlueprint(cloudSiteId, blueprintId, mainTemplate, blueprintFiles, false);
+ }
+ } catch (Exception e) {
+ throw new VduException("CloudifyUtils (instantiateVDU): blueprint Exception", e);
+ }
+
+
+ // Next, create and install a new deployment based on the blueprint.
+ // For Cloudify, the deploymentId is specified by the client. Just use the instance name
+ // as the ID.
+
+ try {
+ // Query the Cloudify Deployment object and populate a VduInstance
+ DeploymentInfo deployment =
+ createAndInstallDeployment(cloudSiteId, tenantId, instanceName, blueprintId, inputs, true, // (poll
+ // for
+ // completion)
+ vduModel.getTimeoutMinutes(), rollbackOnFailure);
+
+ return deploymentInfoToVduInstance(deployment);
+ } catch (Exception e) {
+ throw new VduException("CloudifyUtils (instantiateVDU): Create-and-install-deployment Exception", e);
+ }
}
@@ -1301,21 +1199,18 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
* VduPlugin interface for query function.
*/
@Override
- public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
- throws VduException
- {
- String cloudSiteId = cloudInfo.getCloudSiteId();
- String tenantId = cloudInfo.getTenantId();
-
- try {
- // Query the Cloudify Deployment object and populate a VduInstance
- DeploymentInfo deployment = queryDeployment (cloudSiteId, tenantId, instanceId);
-
- return deploymentInfoToVduInstance(deployment);
- }
- catch (Exception e) {
- throw new VduException ("Query VDU Exception", e);
- }
+ public VduInstance queryVdu(CloudInfo cloudInfo, String instanceId) throws VduException {
+ String cloudSiteId = cloudInfo.getCloudSiteId();
+ String tenantId = cloudInfo.getTenantId();
+
+ try {
+ // Query the Cloudify Deployment object and populate a VduInstance
+ DeploymentInfo deployment = queryDeployment(cloudSiteId, tenantId, instanceId);
+
+ return deploymentInfoToVduInstance(deployment);
+ } catch (Exception e) {
+ throw new VduException("Query VDU Exception", e);
+ }
}
@@ -1323,139 +1218,124 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
* VduPlugin interface for delete function.
*/
@Override
- public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
- throws VduException
- {
- String cloudSiteId = cloudInfo.getCloudSiteId();
- String tenantId = cloudInfo.getTenantId();
-
- try {
- // Uninstall and delete the Cloudify Deployment
- DeploymentInfo deployment = uninstallAndDeleteDeployment (cloudSiteId, tenantId, instanceId, timeoutMinutes);
-
- // Populate a VduInstance based on the deleted Cloudify Deployment object
- return deploymentInfoToVduInstance(deployment);
- }
- catch (Exception e) {
- throw new VduException ("Delete VDU Exception", e);
- }
+ public VduInstance deleteVdu(CloudInfo cloudInfo, String instanceId, int timeoutMinutes) throws VduException {
+ String cloudSiteId = cloudInfo.getCloudSiteId();
+ String tenantId = cloudInfo.getTenantId();
+
+ try {
+ // Uninstall and delete the Cloudify Deployment
+ DeploymentInfo deployment = uninstallAndDeleteDeployment(cloudSiteId, tenantId, instanceId, timeoutMinutes);
+
+ // Populate a VduInstance based on the deleted Cloudify Deployment object
+ return deploymentInfoToVduInstance(deployment);
+ } catch (Exception e) {
+ throw new VduException("Delete VDU Exception", e);
+ }
}
/**
* VduPlugin interface for update function.
*
- * Update is currently not supported in the MsoCloudifyUtils implementation.
- * Just return a VduException.
+ * Update is currently not supported in the MsoCloudifyUtils implementation. Just return a VduException.
*
*/
@Override
- public VduInstance updateVdu (
- CloudInfo cloudInfo,
- String instanceId,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException
- {
- throw new VduException ("CloudifyUtils: updateVDU interface not supported");
+ public VduInstance updateVdu(CloudInfo cloudInfo, String instanceId, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException {
+ throw new VduException("CloudifyUtils: updateVDU interface not supported");
}
/*
* Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
*/
- protected VduInstance deploymentInfoToVduInstance (DeploymentInfo deployment)
- {
- VduInstance vduInstance = new VduInstance();
+ protected VduInstance deploymentInfoToVduInstance(DeploymentInfo deployment) {
+ VduInstance vduInstance = new VduInstance();
- // only one ID in Cloudify, use for both VDU name and ID
- vduInstance.setVduInstanceId(deployment.getId());
- vduInstance.setVduInstanceName(deployment.getId());
+ // only one ID in Cloudify, use for both VDU name and ID
+ vduInstance.setVduInstanceId(deployment.getId());
+ vduInstance.setVduInstanceName(deployment.getId());
- // Copy inputs and outputs
- vduInstance.setInputs(deployment.getInputs());
- vduInstance.setOutputs(deployment.getOutputs());
+ // Copy inputs and outputs
+ vduInstance.setInputs(deployment.getInputs());
+ vduInstance.setOutputs(deployment.getOutputs());
- // Translate the status elements
- vduInstance.setStatus(deploymentStatusToVduStatus (deployment));
+ // Translate the status elements
+ vduInstance.setStatus(deploymentStatusToVduStatus(deployment));
- return vduInstance;
+ return vduInstance;
}
- protected VduStatus deploymentStatusToVduStatus (DeploymentInfo deployment)
- {
- VduStatus vduStatus = new VduStatus();
-
- // Determine the status based on last action & status
- // DeploymentInfo object should be enhanced to report a better status internally.
- DeploymentStatus status = deployment.getStatus();
-
- if (status == null) {
- vduStatus.setState(VduStateType.UNKNOWN);
- }
- else if (status == DeploymentStatus.NOTFOUND) {
- vduStatus.setState(VduStateType.NOTFOUND);
- }
- else if (status == DeploymentStatus.INSTALLED) {
- vduStatus.setState(VduStateType.INSTANTIATED);
- }
- else if (status == DeploymentStatus.CREATED) {
- // Deployment exists but is not installed. This shouldn't really happen,
- // since create + install or uninstall + delete are always done together.
- // But account for it anyway, assuming the operation is still in progress.
- String lastAction = deployment.getLastAction();
- if (lastAction == null)
- vduStatus.setState(VduStateType.INSTANTIATING);
- else
- vduStatus.setState(VduStateType.DELETING);
- }
- else if (status == DeploymentStatus.FAILED) {
- vduStatus.setState(VduStateType.FAILED);
- } else {
- vduStatus.setState(VduStateType.UNKNOWN);
- }
-
- vduStatus.setErrorMessage(deployment.getErrorMessage());
- vduStatus.setLastAction(new PluginAction(deployment.getLastAction(), deployment.getActionStatus(), deployment.getErrorMessage()));
-
- return vduStatus;
+ protected VduStatus deploymentStatusToVduStatus(DeploymentInfo deployment) {
+ VduStatus vduStatus = new VduStatus();
+
+ // Determine the status based on last action & status
+ // DeploymentInfo object should be enhanced to report a better status internally.
+ DeploymentStatus status = deployment.getStatus();
+
+ if (status == null) {
+ vduStatus.setState(VduStateType.UNKNOWN);
+ } else if (status == DeploymentStatus.NOTFOUND) {
+ vduStatus.setState(VduStateType.NOTFOUND);
+ } else if (status == DeploymentStatus.INSTALLED) {
+ vduStatus.setState(VduStateType.INSTANTIATED);
+ } else if (status == DeploymentStatus.CREATED) {
+ // Deployment exists but is not installed. This shouldn't really happen,
+ // since create + install or uninstall + delete are always done together.
+ // But account for it anyway, assuming the operation is still in progress.
+ String lastAction = deployment.getLastAction();
+ if (lastAction == null)
+ vduStatus.setState(VduStateType.INSTANTIATING);
+ else
+ vduStatus.setState(VduStateType.DELETING);
+ } else if (status == DeploymentStatus.FAILED) {
+ vduStatus.setState(VduStateType.FAILED);
+ } else {
+ vduStatus.setState(VduStateType.UNKNOWN);
+ }
+
+ vduStatus.setErrorMessage(deployment.getErrorMessage());
+ vduStatus.setLastAction(new PluginAction(deployment.getLastAction(), deployment.getActionStatus(),
+ deployment.getErrorMessage()));
+
+ return vduStatus;
}
/*
- * Return an OpenstackConfig object as expected by Cloudify Openstack Plug-in.
- * Base the values on the CloudSite definition.
+ * Return an OpenstackConfig object as expected by Cloudify Openstack Plug-in. Base the values on the CloudSite
+ * definition.
*/
- protected OpenstackConfig getOpenstackConfig (CloudSite cloudSite, String tenantId) {
+ protected OpenstackConfig getOpenstackConfig(CloudSite cloudSite, String tenantId) {
OpenstackConfig openstackConfig = new OpenstackConfig();
- openstackConfig.setRegion (cloudSite.getRegionId());
- openstackConfig.setAuthUrl (cloudSite.getIdentityService().getIdentityUrl());
- openstackConfig.setUsername (cloudSite.getIdentityService().getMsoId());
- openstackConfig.setPassword (CryptoUtils.decryptCloudConfigPassword(cloudSite.getIdentityService().getMsoPass()));
- openstackConfig.setTenantName (tenantId);
+ openstackConfig.setRegion(cloudSite.getRegionId());
+ openstackConfig.setAuthUrl(cloudSite.getIdentityService().getIdentityUrl());
+ openstackConfig.setUsername(cloudSite.getIdentityService().getMsoId());
+ openstackConfig
+ .setPassword(CryptoUtils.decryptCloudConfigPassword(cloudSite.getIdentityService().getMsoPass()));
+ openstackConfig.setTenantName(tenantId);
return openstackConfig;
}
/*
- * Return an Azure object as expected by Cloudify Azure Plug-in.
- * Base the values on the CloudSite definition.
+ * Return an Azure object as expected by Cloudify Azure Plug-in. Base the values on the CloudSite definition.
*/
- protected AzureConfig getAzureConfig (CloudSite cloudSite, String tenantId) {
+ protected AzureConfig getAzureConfig(CloudSite cloudSite, String tenantId) {
AzureConfig azureConfig = new AzureConfig();
// TODO: Use adminTenant for now, instead of adding another element
- azureConfig.setSubscriptionId (cloudSite.getIdentityService().getAdminTenant());
- azureConfig.setTenantId (tenantId);
- azureConfig.setClientId (cloudSite.getIdentityService().getMsoId());
- azureConfig.setClientSecret (cloudSite.getIdentityService().getMsoPass());
+ azureConfig.setSubscriptionId(cloudSite.getIdentityService().getAdminTenant());
+ azureConfig.setTenantId(tenantId);
+ azureConfig.setClientId(cloudSite.getIdentityService().getMsoId());
+ azureConfig.setClientSecret(cloudSite.getIdentityService().getMsoPass());
return azureConfig;
}
private void sleep(long time) {
- try {
- Thread.sleep(time);
- } catch (InterruptedException e) {
- logger.debug("Thread interrupted while sleeping!", e);
- Thread.currentThread().interrupt();
- }
+ try {
+ Thread.sleep(time);
+ } catch (InterruptedException e) {
+ logger.debug("Thread interrupted while sleeping!", e);
+ Thread.currentThread().interrupt();
+ }
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/config/beans/PoConfig.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/config/beans/PoConfig.java
index 9995a23668..0a63c0975f 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/config/beans/PoConfig.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/config/beans/PoConfig.java
@@ -24,44 +24,53 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
-@ConfigurationProperties(prefix="org.onap.so.adapters.po")
+@ConfigurationProperties(prefix = "org.onap.so.adapters.po")
public class PoConfig {
- private String retryCodes;
- private int retryDelay;
- private int retryCount;
- private int pollTimeout;
- private int pollInterval;
-
- public String getRetryCodes() {
- return retryCodes;
- }
- public void setRetryCodes(String retryCodes) {
- this.retryCodes = retryCodes;
- }
- public int getRetryDelay() {
- return retryDelay;
- }
- public void setRetryDelay(int retryDelay) {
- this.retryDelay = retryDelay;
- }
- public int getRetryCount() {
- return retryCount;
- }
- public void setRetryCount(int retryCount) {
- this.retryCount = retryCount;
- }
- public int getPollTimeout() {
- return pollTimeout;
- }
- public void setPollTimeout(int pollTimeout) {
- this.pollTimeout = pollTimeout;
- }
- public int getPollInterval() {
- return pollInterval;
- }
- public void setPollInterval(int pollInterval) {
- this.pollInterval = pollInterval;
- }
-
+ private String retryCodes;
+ private int retryDelay;
+ private int retryCount;
+ private int pollTimeout;
+ private int pollInterval;
+
+ public String getRetryCodes() {
+ return retryCodes;
+ }
+
+ public void setRetryCodes(String retryCodes) {
+ this.retryCodes = retryCodes;
+ }
+
+ public int getRetryDelay() {
+ return retryDelay;
+ }
+
+ public void setRetryDelay(int retryDelay) {
+ this.retryDelay = retryDelay;
+ }
+
+ public int getRetryCount() {
+ return retryCount;
+ }
+
+ public void setRetryCount(int retryCount) {
+ this.retryCount = retryCount;
+ }
+
+ public int getPollTimeout() {
+ return pollTimeout;
+ }
+
+ public void setPollTimeout(int pollTimeout) {
+ this.pollTimeout = pollTimeout;
+ }
+
+ public int getPollInterval() {
+ return pollInterval;
+ }
+
+ public void setPollInterval(int pollInterval) {
+ this.pollInterval = pollInterval;
+ }
+
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/HeatCacheEntry.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/HeatCacheEntry.java
index 5eaca976d0..43fb47b414 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/HeatCacheEntry.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/HeatCacheEntry.java
@@ -22,13 +22,11 @@ package org.onap.so.openstack.beans;
import java.io.Serializable;
import java.util.Calendar;
-
import com.woorea.openstack.heat.Heat;
/*
- * An entry in the Heat Client Cache. It saves the Heat client object
- * along with the token expiration. After this interval, this cache
- * item will no longer be used.
+ * An entry in the Heat Client Cache. It saves the Heat client object along with the token expiration. After this
+ * interval, this cache item will no longer be used.
*/
public class HeatCacheEntry implements Serializable {
@@ -38,19 +36,19 @@ public class HeatCacheEntry implements Serializable {
private String token;
private Calendar expires;
- public HeatCacheEntry (String heatUrl, String token, Calendar expires) {
+ public HeatCacheEntry(String heatUrl, String token, Calendar expires) {
this.heatUrl = heatUrl;
this.token = token;
this.expires = expires;
}
- public Heat getHeatClient () {
- Heat heatClient = new Heat (heatUrl);
- heatClient.token (token);
+ public Heat getHeatClient() {
+ Heat heatClient = new Heat(heatUrl);
+ heatClient.token(token);
return heatClient;
}
- public boolean isExpired () {
+ public boolean isExpired() {
if (expires == null) {
return true;
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/NeutronCacheEntry.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/NeutronCacheEntry.java
index d89fd1a73f..7c8b3601c0 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/NeutronCacheEntry.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/NeutronCacheEntry.java
@@ -24,44 +24,43 @@ import java.io.Serializable;
import java.util.Calendar;
/*
- * An entry in the Neutron Client Cache. It saves the Neutron client object
- * along with the token expiration. After this interval, this cache
- * item will no longer be used.
+ * An entry in the Neutron Client Cache. It saves the Neutron client object along with the token expiration. After this
+ * interval, this cache item will no longer be used.
*/
public class NeutronCacheEntry implements Serializable {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- private String neutronUrl;
- private String token;
- private Calendar expires;
+ private String neutronUrl;
+ private String token;
+ private Calendar expires;
- public NeutronCacheEntry (String neutronUrl, String token, Calendar expires) {
- this.neutronUrl = neutronUrl;
- this.token = token;
- this.expires = expires;
- }
-
- public String getNeutronUrl() {
- return neutronUrl;
- }
+ public NeutronCacheEntry(String neutronUrl, String token, Calendar expires) {
+ this.neutronUrl = neutronUrl;
+ this.token = token;
+ this.expires = expires;
+ }
- public void setNeutronUrl(String neutronUrl) {
- this.neutronUrl = neutronUrl;
- }
+ public String getNeutronUrl() {
+ return neutronUrl;
+ }
- public String getToken() {
- return token;
- }
+ public void setNeutronUrl(String neutronUrl) {
+ this.neutronUrl = neutronUrl;
+ }
- public void setToken(String token) {
- this.token = token;
- }
+ public String getToken() {
+ return token;
+ }
- public boolean isExpired() {
- if (expires == null) {
+ public void setToken(String token) {
+ this.token = token;
+ }
+
+ public boolean isExpired() {
+ if (expires == null) {
return true;
}
return System.currentTimeMillis() > expires.getTimeInMillis();
- }
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/VnfRollback.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/VnfRollback.java
index bb8aa92281..258afc1e75 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/VnfRollback.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/VnfRollback.java
@@ -7,9 +7,9 @@
* 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.
@@ -22,195 +22,231 @@ package org.onap.so.openstack.beans;
import org.onap.so.entity.MsoRequest;
import org.springframework.stereotype.Component;
+
/**
- * Javabean representing the rollback criteria following a "Create VNF"
- * operation. This structure can be passed back to the "Rollback VNF"
- * operation to undo the effects of the create.
+ * Javabean representing the rollback criteria following a "Create VNF" operation. This structure can be passed back to
+ * the "Rollback VNF" operation to undo the effects of the create.
*
*
*/
@Component
public class VnfRollback {
- private String vnfId;
- private String tenantId;
- private String cloudSiteId;
- private boolean tenantCreated = false;
- private boolean vnfCreated = false;
- private MsoRequest msoRequest;
- private String volumeGroupName;
- private String volumeGroupId;
- private String requestType;
- private String volumeGroupHeatStackId;
- private String baseGroupHeatStackId;
- private boolean isBase = false;
- private String vfModuleStackId;
- private String modelCustomizationUuid; //NOTE: this is the vfModule's modelCustomizationUuid
- private String mode = "HEAT";
-
- public VnfRollback() {}
-
- /**
- * For backwards compatibility... orchestration mode defaults to HEAT
- *
- * @param vnfId
- * @param tenantId
- * @param cloudSiteId
- * @param tenantCreated
- * @param vnfCreated
- * @param msoRequest
- * @param volumeGroupName
- * @param volumeGroupId
- * @param requestType
- * @param modelCustomizationUuid
- */
- public VnfRollback(String vnfId, String tenantId, String cloudSiteId,
- boolean tenantCreated, boolean vnfCreated,
- MsoRequest msoRequest,
- String volumeGroupName, String volumeGroupId, String requestType, String modelCustomizationUuid) {
- super();
- this.vnfId = vnfId;
- this.tenantId = tenantId;
- this.cloudSiteId = cloudSiteId;
- this.tenantCreated = tenantCreated;
- this.vnfCreated = vnfCreated;
- this.msoRequest = msoRequest;
- this.volumeGroupName = volumeGroupName;
- this.volumeGroupId = volumeGroupId;
- this.requestType = requestType;
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
-
- /**
- * For backwards compatibility... orchestration mode defaults to HEAT
- *
- * @param vnfId
- * @param tenantId
- * @param cloudSiteId
- * @param tenantCreated
- * @param vnfCreated
- * @param msoRequest
- * @param volumeGroupName
- * @param volumeGroupId
- * @param requestType
- * @param modelCustomizationUuid
- */
- public VnfRollback(String vnfId, String tenantId, String cloudSiteId,
- boolean tenantCreated, boolean vnfCreated,
- MsoRequest msoRequest, String volumeGroupName, String volumeGroupId,
- String requestType, String modelCustomizationUuid, String orchestrationMode) {
- super();
- this.vnfId = vnfId;
- this.tenantId = tenantId;
- this.cloudSiteId = cloudSiteId;
- this.tenantCreated = tenantCreated;
- this.vnfCreated = vnfCreated;
- this.msoRequest = msoRequest;
- this.volumeGroupName = volumeGroupName;
- this.volumeGroupId = volumeGroupId;
- this.requestType = requestType;
- this.modelCustomizationUuid = modelCustomizationUuid;
- this.mode = orchestrationMode;
- }
-
- public String getVnfId() {
- return vnfId;
- }
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getCloudSiteId() {
- return cloudSiteId;
- }
- public void setCloudSiteId(String cloudId) {
- this.cloudSiteId = cloudId;
- }
- public boolean getTenantCreated() {
- return tenantCreated;
- }
- public void setTenantCreated(boolean tenantCreated) {
- this.tenantCreated = tenantCreated;
- }
- public boolean getVnfCreated() {
- return vnfCreated;
- }
- public void setVnfCreated(boolean vnfCreated) {
- this.vnfCreated = vnfCreated;
- }
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
- public void setMsoRequest (MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
- public String getVolumeGroupName() {
- return this.volumeGroupName;
- }
- public void setVolumeGroupName(String volumeGroupName) {
- this.volumeGroupName = volumeGroupName;
- }
- public String getVolumeGroupId() {
- return this.volumeGroupId;
- }
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
- public String getRequestType() {
- return this.requestType;
- }
- public void setRequestType(String requestType) {
- this.requestType = requestType;
- }
- public String getVolumeGroupHeatStackId() {
- return this.volumeGroupHeatStackId;
- }
- public void setVolumeGroupHeatStackId(String volumeGroupHeatStackId) {
- this.volumeGroupHeatStackId = volumeGroupHeatStackId;
- }
-
- public String getBaseGroupHeatStackId() {
- return this.baseGroupHeatStackId;
- }
- public void setBaseGroupHeatStackId(String baseGroupHeatStackId) {
- this.baseGroupHeatStackId = baseGroupHeatStackId;
- }
-
- public boolean isBase() {
- return this.isBase;
- }
- public void setIsBase(boolean isBase) {
- this.isBase = isBase;
- }
- public String getVfModuleStackId() {
- return this.vfModuleStackId;
- }
- public void setVfModuleStackId(String vfModuleStackId) {
- this.vfModuleStackId = vfModuleStackId;
- }
- public String getModelCustomizationUuid() {
- return this.modelCustomizationUuid;
- }
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
- public String getMode() {
- return this.mode;
- }
- public void setMode(String mode) {
- this.mode = mode;
- }
- @Override
+ private String vnfId;
+ private String tenantId;
+ private String cloudSiteId;
+ private String cloudOwner;
+ private boolean tenantCreated = false;
+ private boolean vnfCreated = false;
+ private MsoRequest msoRequest;
+ private String volumeGroupName;
+ private String volumeGroupId;
+ private String requestType;
+ private String volumeGroupHeatStackId;
+ private String baseGroupHeatStackId;
+ private boolean isBase = false;
+ private String vfModuleStackId;
+ private String modelCustomizationUuid; // NOTE: this is the vfModule's modelCustomizationUuid
+ private String mode = "HEAT";
+
+ public VnfRollback() {}
+
+ /**
+ * For backwards compatibility... orchestration mode defaults to HEAT
+ *
+ * @param vnfId
+ * @param tenantId
+ * @param cloudSiteId
+ * @param cloudOwner
+ * @param tenantCreated
+ * @param vnfCreated
+ * @param msoRequest
+ * @param volumeGroupName
+ * @param volumeGroupId
+ * @param requestType
+ * @param modelCustomizationUuid
+ */
+ public VnfRollback(String vnfId, String tenantId, String cloudOwner, String cloudSiteId, boolean tenantCreated,
+ boolean vnfCreated, MsoRequest msoRequest, String volumeGroupName, String volumeGroupId, String requestType,
+ String modelCustomizationUuid) {
+ super();
+ this.vnfId = vnfId;
+ this.tenantId = tenantId;
+ this.cloudSiteId = cloudSiteId;
+ this.cloudOwner = cloudOwner;
+ this.tenantCreated = tenantCreated;
+ this.vnfCreated = vnfCreated;
+ this.msoRequest = msoRequest;
+ this.volumeGroupName = volumeGroupName;
+ this.volumeGroupId = volumeGroupId;
+ this.requestType = requestType;
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ /**
+ * For backwards compatibility... orchestration mode defaults to HEAT
+ *
+ * @param vnfId
+ * @param tenantId
+ * @param cloudSiteId
+ * @param cloudOwner
+ * @param tenantCreated
+ * @param vnfCreated
+ * @param msoRequest
+ * @param volumeGroupName
+ * @param volumeGroupId
+ * @param requestType
+ * @param modelCustomizationUuid
+ */
+ public VnfRollback(String vnfId, String tenantId, String cloudOwner, String cloudSiteId, boolean tenantCreated,
+ boolean vnfCreated, MsoRequest msoRequest, String volumeGroupName, String volumeGroupId, String requestType,
+ String modelCustomizationUuid, String orchestrationMode) {
+ super();
+ this.vnfId = vnfId;
+ this.tenantId = tenantId;
+ this.cloudSiteId = cloudSiteId;
+ this.cloudOwner = cloudOwner;
+ this.tenantCreated = tenantCreated;
+ this.vnfCreated = vnfCreated;
+ this.msoRequest = msoRequest;
+ this.volumeGroupName = volumeGroupName;
+ this.volumeGroupId = volumeGroupId;
+ this.requestType = requestType;
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ this.mode = orchestrationMode;
+ }
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudId) {
+ this.cloudSiteId = cloudId;
+ }
+
+ public String getCloudOwner() {
+ return cloudOwner;
+ }
+
+ public void setCloudOwner(String cloudOwner) {
+ this.cloudOwner = cloudOwner;
+ }
+
+ public boolean getTenantCreated() {
+ return tenantCreated;
+ }
+
+ public void setTenantCreated(boolean tenantCreated) {
+ this.tenantCreated = tenantCreated;
+ }
+
+ public boolean getVnfCreated() {
+ return vnfCreated;
+ }
+
+ public void setVnfCreated(boolean vnfCreated) {
+ this.vnfCreated = vnfCreated;
+ }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
+
+ public String getVolumeGroupName() {
+ return this.volumeGroupName;
+ }
+
+ public void setVolumeGroupName(String volumeGroupName) {
+ this.volumeGroupName = volumeGroupName;
+ }
+
+ public String getVolumeGroupId() {
+ return this.volumeGroupId;
+ }
+
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ public String getRequestType() {
+ return this.requestType;
+ }
+
+ public void setRequestType(String requestType) {
+ this.requestType = requestType;
+ }
+
+ public String getVolumeGroupHeatStackId() {
+ return this.volumeGroupHeatStackId;
+ }
+
+ public void setVolumeGroupHeatStackId(String volumeGroupHeatStackId) {
+ this.volumeGroupHeatStackId = volumeGroupHeatStackId;
+ }
+
+ public String getBaseGroupHeatStackId() {
+ return this.baseGroupHeatStackId;
+ }
+
+ public void setBaseGroupHeatStackId(String baseGroupHeatStackId) {
+ this.baseGroupHeatStackId = baseGroupHeatStackId;
+ }
+
+ public boolean isBase() {
+ return this.isBase;
+ }
+
+ public void setIsBase(boolean isBase) {
+ this.isBase = isBase;
+ }
+
+ public String getVfModuleStackId() {
+ return this.vfModuleStackId;
+ }
+
+ public void setVfModuleStackId(String vfModuleStackId) {
+ this.vfModuleStackId = vfModuleStackId;
+ }
+
+ public String getModelCustomizationUuid() {
+ return this.modelCustomizationUuid;
+ }
+
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ public String getMode() {
+ return this.mode;
+ }
+
+ public void setMode(String mode) {
+ this.mode = mode;
+ }
+
+ @Override
public String toString() {
- return "VnfRollback: cloud=" + cloudSiteId + ", tenant=" + tenantId +
- ", vnf=" + vnfId + ", tenantCreated=" + tenantCreated +
- ", vnfCreated=" + vnfCreated + ", requestType = " + requestType
- + ", modelCustomizationUuid=" + this.modelCustomizationUuid
- + ", mode=" + mode;
- }
+ return "VnfRollback: cloud=" + cloudSiteId + ", cloudOwner=" + cloudOwner + ", tenant=" + tenantId + ", vnf="
+ + vnfId + ", tenantCreated=" + tenantCreated + ", vnfCreated=" + vnfCreated + ", requestType = "
+ + requestType + ", modelCustomizationUuid=" + this.modelCustomizationUuid + ", mode=" + mode;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java
index 5a7f67ea3c..c9a548d5f1 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java
@@ -54,103 +54,94 @@ import org.springframework.stereotype.Component;
@Component("CommonUtils")
public class MsoCommonUtils {
- private static Logger logger = LoggerFactory.getLogger(MsoCommonUtils.class);
+ private static Logger logger = LoggerFactory.getLogger(MsoCommonUtils.class);
- @Autowired
- private PoConfig poConfig;
+ @Autowired
+ private PoConfig poConfig;
/*
- * Method to execute an Openstack command and track its execution time.
- * For the metrics log, a category of "Openstack" is used along with a
- * sub-category that identifies the specific call (using the real
+ * Method to execute an Openstack command and track its execution time. For the metrics log, a category of
+ * "Openstack" is used along with a sub-category that identifies the specific call (using the real
* openstack-java-sdk classname of the OpenStackRequest<T> parameter).
*/
- protected <T> T executeAndRecordOpenstackRequest (OpenStackRequest <T> request) {
+ protected <T> T executeAndRecordOpenstackRequest(OpenStackRequest<T> request) {
- int limit;
+ int limit;
- long start = System.currentTimeMillis ();
- String requestType;
- if (request.getClass ().getEnclosingClass () != null) {
- requestType = request.getClass ().getEnclosingClass ().getSimpleName () + "."
- + request.getClass ().getSimpleName ();
+ long start = System.currentTimeMillis();
+ String requestType;
+ if (request.getClass().getEnclosingClass() != null) {
+ requestType =
+ request.getClass().getEnclosingClass().getSimpleName() + "." + request.getClass().getSimpleName();
} else {
- requestType = request.getClass ().getSimpleName ();
+ requestType = request.getClass().getSimpleName();
}
int retryDelay = poConfig.getRetryDelay();
int retryCount = poConfig.getRetryCount();
- String retryCodes = poConfig.getRetryCodes();
+ String retryCodes = poConfig.getRetryCodes();
// Run the actual command. All exceptions will be propagated
- while (true)
- {
- try {
- return request.execute ();
- }
- catch (OpenStackResponseException e) {
- boolean retry = false;
- if (retryCodes != null ) {
- int code = e.getStatus();
- logger.debug("Config values RetryDelay:{} RetryCount:{} RetryCodes:{} ResponseCode:{}", retryDelay,
- retryCount, retryCodes, code);
- for (String rCode : retryCodes.split (",")) {
- try {
- if (retryCount > 0 && code == Integer.parseInt (rCode))
- {
- retryCount--;
- retry = true;
- logger.debug(
- "OpenStackResponseException ResponseCode: {} request:{} Retry indicated. Attempts remaining:{}",
- code, requestType, retryCount);
- break;
- }
- } catch (NumberFormatException e1) {
- logger.error("{} No retries. Exception in parsing retry code in config:{} {} {}",
- MessageEnum.RA_CONFIG_EXC, rCode, ErrorCode.SchemaError.getValue(),
- "Exception in parsing retry code in config");
+ while (true) {
+ try {
+ return request.execute();
+ } catch (OpenStackResponseException e) {
+ boolean retry = false;
+ if (retryCodes != null) {
+ int code = e.getStatus();
+ logger.debug("Config values RetryDelay:{} RetryCount:{} RetryCodes:{} ResponseCode:{}", retryDelay,
+ retryCount, retryCodes, code);
+ for (String rCode : retryCodes.split(",")) {
+ try {
+ if (retryCount > 0 && code == Integer.parseInt(rCode)) {
+ retryCount--;
+ retry = true;
+ logger.debug(
+ "OpenStackResponseException ResponseCode: {} request:{} Retry indicated. Attempts remaining:{}",
+ code, requestType, retryCount);
+ break;
+ }
+ } catch (NumberFormatException e1) {
+ logger.error("{} No retries. Exception in parsing retry code in config:{} {} {}",
+ MessageEnum.RA_CONFIG_EXC, rCode, ErrorCode.SchemaError.getValue(),
+ "Exception in parsing retry code in config");
+ throw e;
+ }
+ }
+ }
+ if (retry) {
+ try {
+ Thread.sleep(retryDelay * 1000L);
+ } catch (InterruptedException e1) {
+ logger.debug("Thread interrupted while sleeping", e1);
+ Thread.currentThread().interrupt();
+ }
+ } else
+ throw e; // exceeded retryCount or code is not retryable
+ } catch (OpenStackConnectException e) {
+ // Connection to Openstack failed
+ if (retryCount > 0) {
+ retryCount--;
+ logger.debug(" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount);
+ try {
+ Thread.sleep(retryDelay * 1000L);
+ } catch (InterruptedException e1) {
+ logger.debug("Thread interrupted while sleeping", e1);
+ Thread.currentThread().interrupt();
+ }
+ } else
throw e;
- }
- }
- }
- if (retry)
- {
- try {
- Thread.sleep (retryDelay * 1000L);
- } catch (InterruptedException e1) {
- logger.debug ("Thread interrupted while sleeping", e1);
- Thread.currentThread().interrupt();
- }
- }
- else
- throw e; // exceeded retryCount or code is not retryable
- }
- catch (OpenStackConnectException e) {
- // Connection to Openstack failed
- if (retryCount > 0)
- {
- retryCount--;
- logger.debug (" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount);
- try {
- Thread.sleep (retryDelay * 1000L);
- } catch (InterruptedException e1) {
- logger.debug ("Thread interrupted while sleeping", e1);
- Thread.currentThread().interrupt();
- }
- }
- else
- throw e;
-
- }
+
+ }
}
}
/*
- * Convert an Openstack Exception on a Keystone call to an MsoException.
- * This method supports both OpenstackResponseException and OpenStackConnectException.
+ * Convert an Openstack Exception on a Keystone call to an MsoException. This method supports both
+ * OpenstackResponseException and OpenStackConnectException.
*/
- protected MsoException keystoneErrorToMsoException (OpenStackBaseException e, String context) {
+ protected MsoException keystoneErrorToMsoException(OpenStackBaseException e, String context) {
MsoException me = null;
if (e instanceof OpenStackResponseException) {
@@ -158,43 +149,43 @@ public class MsoCommonUtils {
try {
// Failed Keystone calls return an Error entity body.
- Error error = re.getResponse ().getErrorEntity (Error.class);
- logger.error("{} {} Openstack Keystone Error on {}: {}",
- MessageEnum.RA_CONNECTION_EXCEPTION, ErrorCode.DataError.getValue(), context, error);
- me = new MsoOpenstackException (error.getCode (), error.getTitle (), error.getMessage ());
+ Error error = re.getResponse().getErrorEntity(Error.class);
+ logger.error("{} {} Openstack Keystone Error on {}: {}", MessageEnum.RA_CONNECTION_EXCEPTION,
+ ErrorCode.DataError.getValue(), context, error);
+ me = new MsoOpenstackException(error.getCode(), error.getTitle(), error.getMessage());
} catch (Exception e2) {
// Can't parse the body as an "Error". Report the HTTP error
logger.error("{} {} HTTP Error on {}: {}, {}", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, re.getStatus(), re.getMessage(), e2);
- me = new MsoOpenstackException (re.getStatus (), re.getMessage (), "");
+ ErrorCode.DataError.getValue(), context, re.getStatus(), re.getMessage(), e2);
+ me = new MsoOpenstackException(re.getStatus(), re.getMessage(), "");
}
// Add the context of the error
- me.addContext (context);
+ me.addContext(context);
// Generate an alarm for 5XX and higher errors.
- if (re.getStatus () >= 500) {
+ if (re.getStatus() >= 500) {
}
} else if (e instanceof OpenStackConnectException) {
OpenStackConnectException ce = (OpenStackConnectException) e;
- me = new MsoIOException (ce.getMessage ());
- me.addContext (context);
+ me = new MsoIOException(ce.getMessage());
+ me.addContext(context);
// Generate an alarm for all connection errors.
logger.error("{} {} Openstack Keystone connection error on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG,
- ErrorCode.DataError.getValue(), context, e);
+ ErrorCode.DataError.getValue(), context, e);
}
return me;
}
/*
- * Convert an Openstack Exception on a Heat call to an MsoOpenstackException.
- * This method supports both OpenstackResponseException and OpenStackConnectException.
+ * Convert an Openstack Exception on a Heat call to an MsoOpenstackException. This method supports both
+ * OpenstackResponseException and OpenStackConnectException.
*/
- protected MsoException heatExceptionToMsoException (OpenStackBaseException e, String context) {
+ protected MsoException heatExceptionToMsoException(OpenStackBaseException e, String context) {
MsoException me = null;
if (e instanceof OpenStackResponseException) {
@@ -202,49 +193,49 @@ public class MsoCommonUtils {
try {
// Failed Heat calls return an Explanation entity body.
- Explanation explanation = re.getResponse ().getErrorEntity (Explanation.class);
+ Explanation explanation = re.getResponse().getErrorEntity(Explanation.class);
logger.error("{} {} Exception - Openstack Error on {} : {}", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, explanation.toString());
- String fullError = explanation.getExplanation() + ", error.type=" + explanation.getError().getType() + ", error.message=" + explanation.getError().getMessage();
+ ErrorCode.DataError.getValue(), context, explanation.toString());
+ String fullError = explanation.getExplanation() + ", error.type=" + explanation.getError().getType()
+ + ", error.message=" + explanation.getError().getMessage();
logger.debug(fullError);
- me = new MsoOpenstackException (explanation.getCode (),
- explanation.getTitle (),
- //explanation.getExplanation ());
- fullError);
+ me = new MsoOpenstackException(explanation.getCode(), explanation.getTitle(),
+ // explanation.getExplanation ());
+ fullError);
} catch (Exception e2) {
// Couldn't parse the body as an "Explanation". Report the original HTTP error.
logger.error("{} {} Exception - HTTP Error on {}: {}, ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2);
- me = new MsoOpenstackException (re.getStatus (), re.getMessage (), "");
+ ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2);
+ me = new MsoOpenstackException(re.getStatus(), re.getMessage(), "");
}
// Add the context of the error
- me.addContext (context);
+ me.addContext(context);
// Generate an alarm for 5XX and higher errors.
- if (re.getStatus () >= 500) {
+ if (re.getStatus() >= 500) {
}
} else if (e instanceof OpenStackConnectException) {
OpenStackConnectException ce = (OpenStackConnectException) e;
- me = new MsoIOException (ce.getMessage ());
- me.addContext (context);
+ me = new MsoIOException(ce.getMessage());
+ me.addContext(context);
// Generate an alarm for all connection errors.
logger.error("{} {} Openstack Heat connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, e);
+ ErrorCode.DataError.getValue(), context, e);
}
return me;
}
/*
- * Convert an Openstack Exception on a Neutron call to an MsoOpenstackException.
- * This method supports both OpenstackResponseException and OpenStackConnectException.
+ * Convert an Openstack Exception on a Neutron call to an MsoOpenstackException. This method supports both
+ * OpenstackResponseException and OpenStackConnectException.
*/
- protected MsoException neutronExceptionToMsoException (OpenStackBaseException e, String context) {
+ protected MsoException neutronExceptionToMsoException(OpenStackBaseException e, String context) {
MsoException me = null;
if (e instanceof OpenStackResponseException) {
@@ -252,171 +243,165 @@ public class MsoCommonUtils {
try {
// Failed Neutron calls return an NeutronError entity body
- NeutronError error = re.getResponse ().getErrorEntity (NeutronError.class);
+ NeutronError error = re.getResponse().getErrorEntity(NeutronError.class);
logger.error("{} {} Openstack Neutron Error on {} {}", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, error);
- me = new MsoOpenstackException (re.getStatus (), error.getType (), error.getMessage ());
+ ErrorCode.DataError.getValue(), context, error);
+ me = new MsoOpenstackException(re.getStatus(), error.getType(), error.getMessage());
} catch (Exception e2) {
// Couldn't parse body as a NeutronError. Report the HTTP error.
logger.error("{} {} Openstack HTTP Error on {}: {}, {}", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2);
- me = new MsoOpenstackException (re.getStatus (), re.getMessage (), null);
+ ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2);
+ me = new MsoOpenstackException(re.getStatus(), re.getMessage(), null);
}
// Add the context of the error
- me.addContext (context);
+ me.addContext(context);
// Generate an alarm for 5XX and higher errors.
- if (re.getStatus () >= 500) {
+ if (re.getStatus() >= 500) {
}
} else if (e instanceof OpenStackConnectException) {
OpenStackConnectException ce = (OpenStackConnectException) e;
- me = new MsoIOException (ce.getMessage ());
- me.addContext (context);
+ me = new MsoIOException(ce.getMessage());
+ me.addContext(context);
// Generate an alarm for all connection errors.
logger.error("{} {} Openstack Neutron Connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, e);
+ ErrorCode.DataError.getValue(), context, e);
}
return me;
}
/*
- * Convert a Java Runtime Exception to an MsoException.
- * All Runtime exceptions will be translated into an MsoAdapterException,
- * which captures internal errors.
- * Alarms will be generated on all such exceptions.
+ * Convert a Java Runtime Exception to an MsoException. All Runtime exceptions will be translated into an
+ * MsoAdapterException, which captures internal errors. Alarms will be generated on all such exceptions.
*/
- protected MsoException runtimeExceptionToMsoException (RuntimeException e, String context) {
- MsoAdapterException me = new MsoAdapterException (e.getMessage (), e);
- me.addContext (context);
- me.setCategory (MsoExceptionCategory.INTERNAL);
+ protected MsoException runtimeExceptionToMsoException(RuntimeException e, String context) {
+ MsoAdapterException me = new MsoAdapterException(e.getMessage(), e);
+ me.addContext(context);
+ me.setCategory(MsoExceptionCategory.INTERNAL);
// Always generate an alarm for internal exceptions
logger.error("{} {} An exception occured on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG,
- ErrorCode.DataError.getValue(), context, e);
+ ErrorCode.DataError.getValue(), context, e);
return me;
}
protected MsoException ioExceptionToMsoException(IOException e, String context) {
- MsoAdapterException me = new MsoAdapterException (e.getMessage (), e);
- me.addContext (context);
- me.setCategory (MsoExceptionCategory.INTERNAL);
+ MsoAdapterException me = new MsoAdapterException(e.getMessage(), e);
+ me.addContext(context);
+ me.setCategory(MsoExceptionCategory.INTERNAL);
// Always generate an alarm for internal exceptions
logger.error("{} {} An exception occured on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG,
- ErrorCode.DataError.getValue(), context, e);
+ ErrorCode.DataError.getValue(), context, e);
return me;
}
- public boolean isNullOrEmpty (String s) {
+ public boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
- protected CreateStackParam createStackParam(String stackName,
- String heatTemplate,
- Map <String, ?> stackInputs,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files,
- Map <String, Object> heatFiles) {
+ protected CreateStackParam createStackParam(String stackName, String heatTemplate, Map<String, ?> stackInputs,
+ int timeoutMinutes, String environment, Map<String, Object> files, Map<String, Object> heatFiles) {
// Create local variables checking to see if we have an environment, nested, get_files
// Could later add some checks to see if it's valid.
boolean haveEnvtVariable = true;
- if (environment == null || "".equalsIgnoreCase (environment.trim ())) {
+ if (environment == null || "".equalsIgnoreCase(environment.trim())) {
haveEnvtVariable = false;
- logger.debug ("createStackParam called with no environment variable");
+ logger.debug("createStackParam called with no environment variable");
} else {
logger.debug("createStackParam called with an environment variable: {}", environment);
}
boolean haveFiles = true;
- if (files == null || files.isEmpty ()) {
+ if (files == null || files.isEmpty()) {
haveFiles = false;
- logger.debug ("createStackParam called with no files / child template ids");
+ logger.debug("createStackParam called with no files / child template ids");
} else {
logger.debug("createStackParam called with {} files / child template ids", files.size());
}
boolean haveHeatFiles = true;
- if (heatFiles == null || heatFiles.isEmpty ()) {
+ if (heatFiles == null || heatFiles.isEmpty()) {
haveHeatFiles = false;
- logger.debug ("createStackParam called with no heatFiles");
+ logger.debug("createStackParam called with no heatFiles");
} else {
logger.debug("createStackParam called with {} heatFiles", heatFiles.size());
}
- //force entire stackInput object to generic Map<String, Object> for openstack compatibility
- ObjectMapper mapper = new ObjectMapper();
- Map<String, Object> normalized = new HashMap<>();
- try {
- normalized = mapper.readValue(mapper.writeValueAsString(stackInputs), new TypeReference<HashMap<String,Object>>() {});
- } catch (IOException e1) {
- logger.debug("could not map json", e1);
- }
-
- // Build up the stack to create
- // Disable auto-rollback, because error reason is lost. Always rollback in the code.
- CreateStackParam stack = new CreateStackParam ();
- stack.setStackName (stackName);
- stack.setTimeoutMinutes (timeoutMinutes);
- stack.setParameters (normalized);
- stack.setTemplate (heatTemplate);
- stack.setDisableRollback (true);
- // TJM New for PO Adapter - add envt variable
- if (haveEnvtVariable) {
- logger.debug("Found an environment variable - value: {}", environment);
- stack.setEnvironment (environment);
- }
- // Now handle nested templates or get_files - have to combine if we have both
- // as they're both treated as "files:" on the stack.
- if (haveFiles && haveHeatFiles) {
- // Let's do this here - not in the bean
- logger.debug ("Found files AND heatFiles - combine and add!");
- Map <String, Object> combinedFiles = new HashMap <> ();
- for (Entry<String, Object> entry : files.entrySet()) {
- combinedFiles.put(entry.getKey(), entry.getValue());
- }
- for (Entry<String, Object> entry : heatFiles.entrySet()) {
- combinedFiles.put(entry.getKey(), entry.getValue());
- }
- stack.setFiles (combinedFiles);
- } else {
- // Handle if we only have one or neither:
- if (haveFiles) {
- logger.debug ("Found files - adding to stack");
- stack.setFiles (files);
- }
- if (haveHeatFiles) {
- logger.debug ("Found heatFiles - adding to stack");
- // the setFiles was modified to handle adding the entries
- stack.setFiles (heatFiles);
- }
- }
-
- // 1802 - attempt to add better formatted printout of request to openstack
- try {
- Map<String, Object> inputs = new HashMap<>();
- for (Entry<String, ?> entry : stackInputs.entrySet()) {
- if (entry.getValue() != null) {
- inputs.put(entry.getKey(), entry.getValue());
- }
- }
- logger.debug("stack request: {}", stack.toString());
- } catch (Exception e) {
- // that's okay - this is a nice-to-have
- logger.debug("(had an issue printing nicely formatted request to debuglog) {}", e.getMessage());
- }
-
- return stack;
+ // force entire stackInput object to generic Map<String, Object> for openstack compatibility
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String, Object> normalized = new HashMap<>();
+ try {
+ normalized = mapper.readValue(mapper.writeValueAsString(stackInputs),
+ new TypeReference<HashMap<String, Object>>() {});
+ } catch (IOException e1) {
+ logger.debug("could not map json", e1);
+ }
+
+ // Build up the stack to create
+ // Disable auto-rollback, because error reason is lost. Always rollback in the code.
+ CreateStackParam stack = new CreateStackParam();
+ stack.setStackName(stackName);
+ stack.setTimeoutMinutes(timeoutMinutes);
+ stack.setParameters(normalized);
+ stack.setTemplate(heatTemplate);
+ stack.setDisableRollback(true);
+ // TJM New for PO Adapter - add envt variable
+ if (haveEnvtVariable) {
+ logger.debug("Found an environment variable - value: {}", environment);
+ stack.setEnvironment(environment);
+ }
+ // Now handle nested templates or get_files - have to combine if we have both
+ // as they're both treated as "files:" on the stack.
+ if (haveFiles && haveHeatFiles) {
+ // Let's do this here - not in the bean
+ logger.debug("Found files AND heatFiles - combine and add!");
+ Map<String, Object> combinedFiles = new HashMap<>();
+ for (Entry<String, Object> entry : files.entrySet()) {
+ combinedFiles.put(entry.getKey(), entry.getValue());
+ }
+ for (Entry<String, Object> entry : heatFiles.entrySet()) {
+ combinedFiles.put(entry.getKey(), entry.getValue());
+ }
+ stack.setFiles(combinedFiles);
+ } else {
+ // Handle if we only have one or neither:
+ if (haveFiles) {
+ logger.debug("Found files - adding to stack");
+ stack.setFiles(files);
+ }
+ if (haveHeatFiles) {
+ logger.debug("Found heatFiles - adding to stack");
+ // the setFiles was modified to handle adding the entries
+ stack.setFiles(heatFiles);
+ }
+ }
+
+ // 1802 - attempt to add better formatted printout of request to openstack
+ try {
+ Map<String, Object> inputs = new HashMap<>();
+ for (Entry<String, ?> entry : stackInputs.entrySet()) {
+ if (entry.getValue() != null) {
+ inputs.put(entry.getKey(), entry.getValue());
+ }
+ }
+ logger.debug("stack request: {}", stack.toString());
+ } catch (Exception e) {
+ // that's okay - this is a nice-to-have
+ logger.debug("(had an issue printing nicely formatted request to debuglog) {}", e.getMessage());
+ }
+
+ return stack;
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java
index 4b53006c21..a21db78cee 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java
@@ -34,210 +34,216 @@ import org.slf4j.LoggerFactory;
public class MsoHeatEnvironmentEntry {
private static final Logger logger = LoggerFactory.getLogger(MsoHeatEnvironmentEntry.class);
-
- private Set<MsoHeatEnvironmentParameter> parameters = null;
- private Set<MsoHeatEnvironmentResource> resources = null;
- private StringBuilder rawEntry = null;
- private boolean valid = true;
- private String errorString = null;
- private StringBuilder resourceRegistryEntryRaw = null;
-
- public MsoHeatEnvironmentEntry() {
- super();
- }
-
- public MsoHeatEnvironmentEntry(StringBuilder sb) {
- this();
- this.rawEntry = sb;
- this.processRawEntry();
- }
-
- private void processRawEntry() {
- try {
- if (this.rawEntry == null || "".equals(this.rawEntry.toString()))
- return;
- byte[] b = this.rawEntry.toString().getBytes();
- MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(b);
- this.parameters = yaml.getParameterListFromEnvt();
- //this.resources = yaml.getResourceListFromEnvt();
- StringBuilder sb = this.getResourceRegistryRawEntry();
- if (sb == null) {
- this.resourceRegistryEntryRaw = new StringBuilder("");
- } else {
- this.resourceRegistryEntryRaw = sb;
- }
- } catch (Exception e) {
- logger.debug("Exception:", e);
- this.valid = false;
- this.errorString = e.getMessage();
- //e.printStackTrace();
- }
- }
-
- public boolean isValid() {
- return this.valid;
- }
- public String getErrorString() {
- return this.errorString;
- }
-
- public Set<MsoHeatEnvironmentParameter> getParameters() {
- return this.parameters;
- }
- public Set<MsoHeatEnvironmentResource> getResources() {
- return this.resources;
- }
- public void setParameters(Set<MsoHeatEnvironmentParameter> paramSet) {
- if (paramSet == null) {
- this.parameters = null;
- } else {
- this.parameters = paramSet;
- }
- }
- public void setResources(Set<MsoHeatEnvironmentResource> resourceSet) {
- if (resourceSet == null) {
- this.resources = null;
- } else {
- this.resources = resourceSet;
- }
- }
-
- public void addParameter(MsoHeatEnvironmentParameter hep) {
- if (this.parameters == null) {
- this.parameters = new HashSet<>();
- }
- this.parameters.add(hep);
- }
- public void addResource(MsoHeatEnvironmentResource her) {
- if (this.resources == null) {
- this.resources = new HashSet<>();
- }
- this.resources.add(her);
- }
-
- public int getNumberOfParameters() {
- return this.parameters.size();
- }
- public int getNumberOfResources() {
- return this.resources.size();
- }
-
- public boolean hasResources() {
- if (this.resources != null && this.resources.size() > 0) {
- return true;
- }
- return false;
- }
- public boolean hasParameters() {
- if (this.parameters != null && this.parameters.size() > 0) {
- return true;
- }
- return false;
- }
-
- public boolean containsParameter(String paramName) {
- boolean contains = false;
- if (this.parameters == null || this.parameters.size() < 1) {
- return false;
- }
- if (this.parameters.contains(new MsoHeatEnvironmentParameter(paramName))) {
- contains = true;
- }
- return contains;
- }
-
- public boolean containsParameter(String paramName, String paramAlias) {
- if (this.containsParameter(paramName)) {
- return true;
- }
- if (this.containsParameter(paramAlias)) {
- return true;
- }
- return false;
- }
-
+
+ private Set<MsoHeatEnvironmentParameter> parameters = null;
+ private Set<MsoHeatEnvironmentResource> resources = null;
+ private StringBuilder rawEntry = null;
+ private boolean valid = true;
+ private String errorString = null;
+ private StringBuilder resourceRegistryEntryRaw = null;
+
+ public MsoHeatEnvironmentEntry() {
+ super();
+ }
+
+ public MsoHeatEnvironmentEntry(StringBuilder sb) {
+ this();
+ this.rawEntry = sb;
+ this.processRawEntry();
+ }
+
+ private void processRawEntry() {
+ try {
+ if (this.rawEntry == null || "".equals(this.rawEntry.toString()))
+ return;
+ byte[] b = this.rawEntry.toString().getBytes();
+ MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(b);
+ this.parameters = yaml.getParameterListFromEnvt();
+ // this.resources = yaml.getResourceListFromEnvt();
+ StringBuilder sb = this.getResourceRegistryRawEntry();
+ if (sb == null) {
+ this.resourceRegistryEntryRaw = new StringBuilder("");
+ } else {
+ this.resourceRegistryEntryRaw = sb;
+ }
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ this.valid = false;
+ this.errorString = e.getMessage();
+ // e.printStackTrace();
+ }
+ }
+
+ public boolean isValid() {
+ return this.valid;
+ }
+
+ public String getErrorString() {
+ return this.errorString;
+ }
+
+ public Set<MsoHeatEnvironmentParameter> getParameters() {
+ return this.parameters;
+ }
+
+ public Set<MsoHeatEnvironmentResource> getResources() {
+ return this.resources;
+ }
+
+ public void setParameters(Set<MsoHeatEnvironmentParameter> paramSet) {
+ if (paramSet == null) {
+ this.parameters = null;
+ } else {
+ this.parameters = paramSet;
+ }
+ }
+
+ public void setResources(Set<MsoHeatEnvironmentResource> resourceSet) {
+ if (resourceSet == null) {
+ this.resources = null;
+ } else {
+ this.resources = resourceSet;
+ }
+ }
+
+ public void addParameter(MsoHeatEnvironmentParameter hep) {
+ if (this.parameters == null) {
+ this.parameters = new HashSet<>();
+ }
+ this.parameters.add(hep);
+ }
+
+ public void addResource(MsoHeatEnvironmentResource her) {
+ if (this.resources == null) {
+ this.resources = new HashSet<>();
+ }
+ this.resources.add(her);
+ }
+
+ public int getNumberOfParameters() {
+ return this.parameters.size();
+ }
+
+ public int getNumberOfResources() {
+ return this.resources.size();
+ }
+
+ public boolean hasResources() {
+ if (this.resources != null && this.resources.size() > 0) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean hasParameters() {
+ if (this.parameters != null && this.parameters.size() > 0) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean containsParameter(String paramName) {
+ boolean contains = false;
+ if (this.parameters == null || this.parameters.size() < 1) {
+ return false;
+ }
+ if (this.parameters.contains(new MsoHeatEnvironmentParameter(paramName))) {
+ contains = true;
+ }
+ return contains;
+ }
+
+ public boolean containsParameter(String paramName, String paramAlias) {
+ if (this.containsParameter(paramName)) {
+ return true;
+ }
+ if (this.containsParameter(paramAlias)) {
+ return true;
+ }
+ return false;
+ }
+
@Override
public String toString() {
- return "MsoHeatEnvironmentEntry{" + "parameters=" + parameters +
- ", resourceRegistryEntryRaw='" + resourceRegistryEntryRaw + '\'' +
- '}';
+ return "MsoHeatEnvironmentEntry{" + "parameters=" + parameters + ", resourceRegistryEntryRaw='"
+ + resourceRegistryEntryRaw + '\'' + '}';
+ }
+
+ public StringBuilder toFullStringExcludeNonParams(Set<HeatTemplateParam> params) {
+ // Basically give back the envt - but exclude the params that aren't in the HeatTemplate
+
+ StringBuilder sb = new StringBuilder();
+ ArrayList<String> paramNameList = new ArrayList<String>(params.size());
+ for (HeatTemplateParam htp : params) {
+ paramNameList.add(htp.getParamName());
+ }
+
+ if (this.hasParameters()) {
+ sb.append("parameters:\n");
+ for (MsoHeatEnvironmentParameter hep : this.parameters) {
+ String paramName = hep.getName();
+ if (paramNameList.contains(paramName)) {
+ // This parameter *is* in the Heat Template - so include it:
+ sb.append(" " + hep.getName() + ": " + hep.getValue() + "\n");
+ // New - 1607 - if any of the params mapped badly - JUST RETURN THE ORIGINAL ENVT!
+ if (hep.getValue().startsWith("_BAD")) {
+ return this.rawEntry;
+ }
+ }
+ }
+ sb.append("\n");
+ }
+ // if (this.hasResources()) {
+ // sb.append("resource_registry:\n");
+ // for (MsoHeatEnvironmentResource her : this.resources) {
+ // sb.append(" \"" + her.getName() + "\": " + her.getValue() + "\n");
+ // }
+ // }
+ sb.append("\n");
+ sb.append(this.resourceRegistryEntryRaw);
+ return sb;
+ }
+
+ public StringBuilder toFullString() {
+ StringBuilder sb = new StringBuilder();
+
+ if (this.hasParameters()) {
+ sb.append("parameters:\n");
+ for (MsoHeatEnvironmentParameter hep : this.parameters) {
+ sb.append(" " + hep.getName() + ": " + hep.getValue() + "\n");
+ }
+ sb.append("\n");
+ }
+ // if (this.hasResources()) {
+ // sb.append("resource_registry:\n");
+ // for (MsoHeatEnvironmentResource her : this.resources) {
+ // sb.append(" \"" + her.getName() + "\": " + her.getValue() + "\n");
+ // }
+ // }
+ sb.append("\n");
+ sb.append(this.resourceRegistryEntryRaw);
+ return sb;
+ }
+
+ public StringBuilder getRawEntry() {
+ return this.rawEntry;
+ }
+
+ private StringBuilder getResourceRegistryRawEntry() {
+
+ if (this.rawEntry == null) {
+ return null;
+ }
+
+ StringBuilder sb = new StringBuilder();
+ int indexOf = this.rawEntry.indexOf("resource_registry:");
+ if (indexOf < 0) { // no resource_registry:
+ return null;
+ }
+ sb.append(this.rawEntry.substring(indexOf));
+ return sb;
}
- public StringBuilder toFullStringExcludeNonParams(Set<HeatTemplateParam> params) {
- // Basically give back the envt - but exclude the params that aren't in the HeatTemplate
-
- StringBuilder sb = new StringBuilder();
- ArrayList<String> paramNameList = new ArrayList<String>(params.size());
- for (HeatTemplateParam htp : params) {
- paramNameList.add(htp.getParamName());
- }
-
- if (this.hasParameters()) {
- sb.append("parameters:\n");
- for (MsoHeatEnvironmentParameter hep : this.parameters) {
- String paramName = hep.getName();
- if (paramNameList.contains(paramName)) {
- // This parameter *is* in the Heat Template - so include it:
- sb.append(" " + hep.getName() + ": " + hep.getValue() + "\n");
- // New - 1607 - if any of the params mapped badly - JUST RETURN THE ORIGINAL ENVT!
- if (hep.getValue().startsWith("_BAD")) {
- return this.rawEntry;
- }
- }
- }
- sb.append("\n");
- }
-// if (this.hasResources()) {
-// sb.append("resource_registry:\n");
-// for (MsoHeatEnvironmentResource her : this.resources) {
-// sb.append(" \"" + her.getName() + "\": " + her.getValue() + "\n");
-// }
-// }
- sb.append("\n");
- sb.append(this.resourceRegistryEntryRaw);
- return sb;
- }
-
- public StringBuilder toFullString() {
- StringBuilder sb = new StringBuilder();
-
- if (this.hasParameters()) {
- sb.append("parameters:\n");
- for (MsoHeatEnvironmentParameter hep : this.parameters) {
- sb.append(" " + hep.getName() + ": " + hep.getValue() + "\n");
- }
- sb.append("\n");
- }
-// if (this.hasResources()) {
-// sb.append("resource_registry:\n");
-// for (MsoHeatEnvironmentResource her : this.resources) {
-// sb.append(" \"" + her.getName() + "\": " + her.getValue() + "\n");
-// }
-// }
- sb.append("\n");
- sb.append(this.resourceRegistryEntryRaw);
- return sb;
- }
-
- public StringBuilder getRawEntry() {
- return this.rawEntry;
- }
-
- private StringBuilder getResourceRegistryRawEntry() {
-
- if (this.rawEntry == null) {
- return null;
- }
-
- StringBuilder sb = new StringBuilder();
- int indexOf = this.rawEntry.indexOf("resource_registry:");
- if (indexOf < 0) { // no resource_registry:
- return null;
- }
- sb.append(this.rawEntry.substring(indexOf));
- return sb;
- }
-
public void setHPAParameters(StringBuilder hpasb) {
try {
MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(hpasb.toString().getBytes());
@@ -252,7 +258,7 @@ public class MsoHeatEnvironmentEntry {
} catch (Exception e) {
logger.debug("Exception:", e);
this.errorString = e.getMessage();
- //e.printStackTrace();
+ // e.printStackTrace();
}
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameter.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameter.java
index 7e4c9d00c4..8b39b27546 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameter.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameter.java
@@ -24,54 +24,59 @@ import java.util.Objects;
public class MsoHeatEnvironmentParameter {
- private String name;
- private String value;
-
- public MsoHeatEnvironmentParameter(String name, String value) {
- super();
- this.name = name;
- this.value = value;
- }
- public MsoHeatEnvironmentParameter(String name) {
- // Allow to initialize with a null value
- this(name, null);
- }
- public MsoHeatEnvironmentParameter() {
- this(null, null);
- }
-
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
-
- public String getValue() {
- return this.value;
- }
- public void setValue(String value) {
- this.value = value;
- }
- public String toString() {
- return this.name + ": " + this.value;
- }
-
- public boolean equals(Object o) {
- if (!(o instanceof MsoHeatEnvironmentParameter)) {
- return false;
- }
- if (this == o) {
- return true;
- }
- MsoHeatEnvironmentParameter hep = (MsoHeatEnvironmentParameter) o;
- // If the name of the parameter is the same, then they're equal
+ private String name;
+ private String value;
+
+ public MsoHeatEnvironmentParameter(String name, String value) {
+ super();
+ this.name = name;
+ this.value = value;
+ }
+
+ public MsoHeatEnvironmentParameter(String name) {
+ // Allow to initialize with a null value
+ this(name, null);
+ }
+
+ public MsoHeatEnvironmentParameter() {
+ this(null, null);
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getValue() {
+ return this.value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public String toString() {
+ return this.name + ": " + this.value;
+ }
+
+ public boolean equals(Object o) {
+ if (!(o instanceof MsoHeatEnvironmentParameter)) {
+ return false;
+ }
+ if (this == o) {
+ return true;
+ }
+ MsoHeatEnvironmentParameter hep = (MsoHeatEnvironmentParameter) o;
+ // If the name of the parameter is the same, then they're equal
return hep.getName().equals(this.getName());
- }
-
- public int hashCode() {
+ }
+
+ public int hashCode() {
return Objects.hashCode(this.name);
- }
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java
index 56bab31880..04c62cc841 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java
@@ -29,71 +29,72 @@ import org.slf4j.LoggerFactory;
public class MsoHeatEnvironmentResource {
private static final Logger logger = LoggerFactory.getLogger(MsoHeatEnvironmentResource.class);
-
- private String name;
- private String value;
-
- public MsoHeatEnvironmentResource(String name, String value) {
- super();
- this.name = name;
- this.value = value;
- }
- public MsoHeatEnvironmentResource(String name) {
- // Allow to initialize with a null value
- this(name, null);
- }
- public MsoHeatEnvironmentResource() {
- this(null, null);
- }
-
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
-
- public String getValue() {
- return this.value;
- }
- public void setValue(String value) {
- this.value = value;
- }
-
- @Override
- public String toString() {
- return "\"" +
- this.name +
- "\": " +
- this.value;
- }
-
- @Override
- public boolean equals(Object o) {
- if (!(o instanceof MsoHeatEnvironmentResource)) {
- return false;
- }
- if (this == o) {
- return true;
- }
- MsoHeatEnvironmentResource her = (MsoHeatEnvironmentResource) o;
- // If the name of the parameter is the same, then they're equal
- if (her.getName().equals(this.getName())) {
- return true;
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- int result = 0;
- try {
- result = this.name.hashCode();
- } catch (Exception e) {
- logger.debug("Exception:", e);
+
+ private String name;
+ private String value;
+
+ public MsoHeatEnvironmentResource(String name, String value) {
+ super();
+ this.name = name;
+ this.value = value;
+ }
+
+ public MsoHeatEnvironmentResource(String name) {
+ // Allow to initialize with a null value
+ this(name, null);
+ }
+
+ public MsoHeatEnvironmentResource() {
+ this(null, null);
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getValue() {
+ return this.value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return "\"" + this.name + "\": " + this.value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof MsoHeatEnvironmentResource)) {
+ return false;
+ }
+ if (this == o) {
+ return true;
+ }
+ MsoHeatEnvironmentResource her = (MsoHeatEnvironmentResource) o;
+ // If the name of the parameter is the same, then they're equal
+ if (her.getName().equals(this.getName())) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = 0;
+ try {
+ result = this.name.hashCode();
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ }
+ return result;
}
- return result;
- }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java
index 60088fc612..b54301509f 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java
@@ -38,7 +38,6 @@ import com.woorea.openstack.keystone.Keystone;
import com.woorea.openstack.keystone.model.Access;
import com.woorea.openstack.keystone.model.Authentication;
import com.woorea.openstack.keystone.utils.KeystoneUtils;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -90,7 +89,7 @@ import org.springframework.stereotype.Component;
@Primary
@Component
-public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
+public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin {
private static final String TOKEN_AUTH = "TokenAuth";
@@ -114,10 +113,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
@Autowired
private MsoTenantUtilsFactory tenantUtilsFactory;
-
+
@Autowired
private KeystoneV3Authentication keystoneV3Authentication;
-
+
private static final Logger logger = LoggerFactory.getLogger(MsoHeatUtils.class);
// Properties names and variables (with default values)
@@ -131,128 +130,68 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
/**
- * keep this old method signature here to maintain backwards compatibility. keep others as well.
- * this method does not include environment, files, or heatFiles
+ * keep this old method signature here to maintain backwards compatibility. keep others as well. this method does
+ * not include environment, files, or heatFiles
*/
- public StackInfo createStack (String cloudSiteId,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, ?> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes) throws MsoException {
+ public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes)
+ throws MsoException {
// Just call the new method with the environment & files variable set to null
- return this.createStack (cloudSiteId,
- tenantId,
- stackName,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- null,
- null,
- null,
- true);
+ return this.createStack(cloudSiteId, cloudOwner, tenantId, stackName, null, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, null, null, null, true);
}
// This method has environment, but not files or heatFiles
- public StackInfo createStack (String cloudSiteId,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, ?> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment) throws MsoException {
+ public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes,
+ String environment) throws MsoException {
// Just call the new method with the files/heatFiles variables set to null
- return this.createStack (cloudSiteId,
- tenantId,
- stackName,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- environment,
- null,
- null,
- true);
+ return this.createStack(cloudSiteId, cloudOwner, tenantId, stackName, null, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, environment, null, null, true);
}
// This method has environment and files, but not heatFiles.
- public StackInfo createStack (String cloudSiteId,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, ?> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files) throws MsoException {
- return this.createStack (cloudSiteId,
- tenantId,
- stackName,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- environment,
- files,
- null,
- true);
+ public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes,
+ String environment, Map<String, Object> files) throws MsoException {
+ return this.createStack(cloudSiteId, cloudOwner, tenantId, stackName, null, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, environment, files, null, true);
}
// This method has environment, files, heatfiles
- public StackInfo createStack (String cloudSiteId,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, ?> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files,
- Map <String, Object> heatFiles) throws MsoException {
- return this.createStack (cloudSiteId,
- tenantId,
- stackName,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- environment,
- files,
- heatFiles,
- true);
+ public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes,
+ String environment, Map<String, Object> files, Map<String, Object> heatFiles) throws MsoException {
+ return this.createStack(cloudSiteId, cloudOwner, tenantId, stackName, null, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, environment, files, heatFiles, true);
}
/**
- * Create a new Stack in the specified cloud location and tenant. The Heat template
- * and parameter map are passed in as arguments, along with the cloud access credentials.
- * It is expected that parameters have been validated and contain at minimum the required
- * parameters for the given template with no extra (undefined) parameters..
+ * Create a new Stack in the specified cloud location and tenant. The Heat template and parameter map are passed in
+ * as arguments, along with the cloud access credentials. It is expected that parameters have been validated and
+ * contain at minimum the required parameters for the given template with no extra (undefined) parameters..
*
- * The Stack name supplied by the caller must be unique in the scope of this tenant.
- * However, it should also be globally unique, as it will be the identifier for the
- * resource going forward in Inventory. This latter is managed by the higher levels
- * invoking this function.
+ * The Stack name supplied by the caller must be unique in the scope of this tenant. However, it should also be
+ * globally unique, as it will be the identifier for the resource going forward in Inventory. This latter is managed
+ * by the higher levels invoking this function.
*
- * The caller may choose to let this function poll Openstack for completion of the
- * stack creation, or may handle polling itself via separate calls to query the status.
- * In either case, a StackInfo object will be returned containing the current status.
- * When polling is enabled, a status of CREATED is expected. When not polling, a
+ * The caller may choose to let this function poll Openstack for completion of the stack creation, or may handle
+ * polling itself via separate calls to query the status. In either case, a StackInfo object will be returned
+ * containing the current status. When polling is enabled, a status of CREATED is expected. When not polling, a
* status of BUILDING is expected.
*
- * An error will be thrown if the requested Stack already exists in the specified
- * Tenant and Cloud.
+ * An error will be thrown if the requested Stack already exists in the specified Tenant and Cloud.
*
- * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as
- * parameters for createStack. If environment is non-null, it will be added to the stack.
- * The nested templates and get_file entries both end up being added to the "files" on the
- * stack. We must combine them before we add them to the stack if they're both non-null.
+ * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as parameters for
+ * createStack. If environment is non-null, it will be added to the stack. The nested templates and get_file entries
+ * both end up being added to the "files" on the stack. We must combine them before we add them to the stack if
+ * they're both non-null.
*
* @param cloudSiteId The cloud (may be a region) in which to create the stack.
+ * @param cloudOwner the cloud owner of the cloud site in which to create the stack
* @param tenantId The Openstack ID of the tenant in which to create the Stack
* @param stackName The name of the stack to create
+ * @param vduModelInfo contains information about the vdu model (added for plugin adapter)
* @param heatTemplate The Heat template
* @param stackInputs A map of key/value inputs
* @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
@@ -266,17 +205,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
*/
@SuppressWarnings("unchecked")
- public StackInfo createStack (String cloudSiteId,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, ?> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files,
- Map <String, Object> heatFiles,
- boolean backout) throws MsoException {
+ public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ VduModelInfo vduModel, String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion,
+ int timeoutMinutes, String environment, Map<String, Object> files, Map<String, Object> heatFiles,
+ boolean backout) throws MsoException {
// Take out the multicloud inputs, if present.
for (String key : MsoMulticloudUtils.MULTICLOUD_INPUTS) {
@@ -288,320 +220,327 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
}
}
- CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
+ CreateStackParam stack =
+ createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
// Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
logger.debug("Found: {}", cloudSite);
// Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
// This could throw MsoTenantNotFound or MsoOpenstackException (both propagated)
- Heat heatClient = getHeatClient (cloudSite, tenantId);
+ Heat heatClient = getHeatClient(cloudSite, tenantId);
logger.debug("Found: {}", heatClient);
- logger.debug ("Ready to Create Stack ({}) with input params: {}", heatTemplate, stackInputs);
+ logger.debug("Ready to Create Stack ({}) with input params: {}", heatTemplate, stackInputs);
Stack heatStack = null;
try {
- OpenStackRequest <Stack> request = heatClient.getStacks ().create (stack);
+ OpenStackRequest<Stack> request = heatClient.getStacks().create(stack);
CloudIdentity cloudIdentity = cloudSite.getIdentityService();
- request.header ("X-Auth-User", cloudIdentity.getMsoId ());
- request.header ("X-Auth-Key", CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass ()));
- heatStack = executeAndRecordOpenstackRequest (request);
+ request.header("X-Auth-User", cloudIdentity.getMsoId());
+ request.header("X-Auth-Key", CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass()));
+ heatStack = executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 409) {
- MsoStackAlreadyExists me = new MsoStackAlreadyExists (stackName, tenantId, cloudSiteId);
- me.addContext (CREATE_STACK);
+ if (e.getStatus() == 409) {
+ MsoStackAlreadyExists me = new MsoStackAlreadyExists(stackName, tenantId, cloudSiteId);
+ me.addContext(CREATE_STACK);
throw me;
- } else {
+ } else {
logger.debug("ERROR STATUS = {},\n{}\n{}", e.getStatus(), e.getMessage(), e.getLocalizedMessage());
- throw heatExceptionToMsoException (e, CREATE_STACK);
+ throw heatExceptionToMsoException(e, CREATE_STACK);
}
- } catch (OpenStackConnectException e) {
- throw heatExceptionToMsoException (e, CREATE_STACK);
- } catch (RuntimeException e) {
- throw runtimeExceptionToMsoException (e, CREATE_STACK);
+ } catch (OpenStackConnectException e) {
+ throw heatExceptionToMsoException(e, CREATE_STACK);
+ } catch (RuntimeException e) {
+ throw runtimeExceptionToMsoException(e, CREATE_STACK);
}
// Subsequent access by the canonical name "<stack name>/<stack-id>".
// Otherwise, simple query by name returns a 302 redirect.
// NOTE: This is specific to the v1 Orchestration API.
- String canonicalName = stackName + "/" + heatStack.getId ();
-
+ String canonicalName = stackName + "/" + heatStack.getId();
+
if (pollForCompletion) {
heatStack = pollStackForCompletion(cloudSiteId, tenantId, stackName, timeoutMinutes, backout, heatClient,
- heatStack, canonicalName);
+ heatStack, canonicalName);
} else {
// Get initial status, since it will have been null after the create.
- heatStack = queryHeatStack (heatClient, canonicalName);
- logger.debug (heatStack.getStackStatus ());
+ heatStack = queryHeatStack(heatClient, canonicalName);
+ logger.debug(heatStack.getStackStatus());
}
return new StackInfoMapper(heatStack).map();
}
- private Stack pollStackForCompletion(String cloudSiteId, String tenantId, String stackName, int timeoutMinutes,
- boolean backout, Heat heatClient, Stack heatStack, String canonicalName)
- throws MsoException, MsoOpenstackException {
- int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
- int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
- int deletePollInterval = createPollInterval;
- int deletePollTimeout = pollTimeout;
- boolean createTimedOut = false;
- StringBuilder stackErrorStatusReason = new StringBuilder("");
- logger.debug("createPollInterval={}, pollTimeout={}", createPollInterval, pollTimeout);
-
- while (true) {
- try {
- heatStack = queryHeatStack (heatClient, canonicalName);
- logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName);
+ private Stack pollStackForCompletion(String cloudSiteId, String tenantId, String stackName, int timeoutMinutes,
+ boolean backout, Heat heatClient, Stack heatStack, String canonicalName)
+ throws MsoException, MsoOpenstackException {
+ int createPollInterval =
+ Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
+ int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
+ int deletePollInterval = createPollInterval;
+ int deletePollTimeout = pollTimeout;
+ boolean createTimedOut = false;
+ StringBuilder stackErrorStatusReason = new StringBuilder("");
+ logger.debug("createPollInterval={}, pollTimeout={}", createPollInterval, pollTimeout);
+
+ while (true) {
try {
- logger.debug("Current stack {}", this.getOutputsAsStringBuilder(heatStack).toString());
- } catch (Exception e) {
- logger.debug("an error occurred trying to print out the current outputs of the stack", e);
- }
-
- if ("CREATE_IN_PROGRESS".equals (heatStack.getStackStatus ())) {
- if (pollTimeout <= 0) {
- logger.error("{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Create stack timeout",
- MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
- heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
- createTimedOut = true;
- break;
- }
- sleep(createPollInterval * 1000L);
- pollTimeout -= createPollInterval;
- logger.debug("pollTimeout remaining: {}", pollTimeout);
- } else {
- stackErrorStatusReason.append("Stack error (" + heatStack.getStackStatus() + "): " + heatStack.getStackStatusReason());
- break;
- }
- } catch (MsoException me) {
- // Cannot query the stack status. Something is wrong.
- // Try to roll back the stack
- if (!backout)
- {
- logger.warn("{} Exception in Create Stack, stack deletion suppressed {}",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
- }
- else
- {
- try {
- logger.debug(
- "Create Stack error - unable to query for stack status - attempting to delete stack: {}"
- + " - This will likely fail and/or we won't be able to query to see if delete worked",
- canonicalName);
- OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName);
- executeAndRecordOpenstackRequest (request);
- boolean deleted = false;
- while (!deleted) {
- try {
- heatStack = queryHeatStack(heatClient, canonicalName);
- if (heatStack != null) {
- logger.debug(heatStack.getStackStatus());
- if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
- if (deletePollTimeout <= 0) {
- logger.error(
- "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout",
+ heatStack = queryHeatStack(heatClient, canonicalName);
+ logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName);
+ try {
+ logger.debug("Current stack {}", this.getOutputsAsStringBuilder(heatStack).toString());
+ } catch (Exception e) {
+ logger.debug("an error occurred trying to print out the current outputs of the stack", e);
+ }
+
+ if ("CREATE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
+ if (pollTimeout <= 0) {
+ logger.error("{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Create stack timeout",
MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
- break;
- } else {
- sleep(deletePollInterval * 1000L);
- deletePollTimeout -= deletePollInterval;
- }
- } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){
- logger.debug("DELETE_COMPLETE for {}", canonicalName);
- deleted = true;
- continue;
- } else {
- //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
- break;
- }
- } else {
- // assume if we can't find it - it's deleted
- logger.debug("heatStack returned null - assume the stack {} has been deleted", canonicalName);
- deleted = true;
- continue;
- }
-
- } catch (Exception e3) {
- // Just log this one. We will report the original exception.
- logger.error("{} Create Stack: Nested exception rolling back stack: {} ",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e3);
- }
- }
- } catch (Exception e2) {
- // Just log this one. We will report the original exception.
- logger.error("{} Create Stack: Nested exception rolling back stack: {} ",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e2);
+ createTimedOut = true;
+ break;
+ }
+ sleep(createPollInterval * 1000L);
+ pollTimeout -= createPollInterval;
+ logger.debug("pollTimeout remaining: {}", pollTimeout);
+ } else {
+ stackErrorStatusReason.append(
+ "Stack error (" + heatStack.getStackStatus() + "): " + heatStack.getStackStatusReason());
+ break;
+ }
+ } catch (MsoException me) {
+ // Cannot query the stack status. Something is wrong.
+ // Try to roll back the stack
+ if (!backout) {
+ logger.warn("{} Exception in Create Stack, stack deletion suppressed {}",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
+ } else {
+ try {
+ logger.debug(
+ "Create Stack error - unable to query for stack status - attempting to delete stack: {}"
+ + " - This will likely fail and/or we won't be able to query to see if delete worked",
+ canonicalName);
+ OpenStackRequest<Void> request = heatClient.getStacks().deleteByName(canonicalName);
+ executeAndRecordOpenstackRequest(request);
+ boolean deleted = false;
+ while (!deleted) {
+ try {
+ heatStack = queryHeatStack(heatClient, canonicalName);
+ if (heatStack != null) {
+ logger.debug(heatStack.getStackStatus());
+ if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
+ if (deletePollTimeout <= 0) {
+ logger.error(
+ "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout",
+ MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId,
+ stackName, heatStack.getStackStatus(),
+ ErrorCode.AvailabilityError.getValue());
+ break;
+ } else {
+ sleep(deletePollInterval * 1000L);
+ deletePollTimeout -= deletePollInterval;
+ }
+ } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())) {
+ logger.debug("DELETE_COMPLETE for {}", canonicalName);
+ deleted = true;
+ continue;
+ } else {
+ // got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and
+ // evaluate
+ break;
+ }
+ } else {
+ // assume if we can't find it - it's deleted
+ logger.debug("heatStack returned null - assume the stack {} has been deleted",
+ canonicalName);
+ deleted = true;
+ continue;
+ }
+
+ } catch (Exception e3) {
+ // Just log this one. We will report the original exception.
+ logger.error("{} Create Stack: Nested exception rolling back stack: {} ",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
+ e3);
+ }
+ }
+ } catch (Exception e2) {
+ // Just log this one. We will report the original exception.
+ logger.error("{} Create Stack: Nested exception rolling back stack: {} ",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e2);
+ }
+ }
+
+ // Propagate the original exception from Stack Query.
+ me.addContext(CREATE_STACK);
+ throw me;
}
- }
-
- // Propagate the original exception from Stack Query.
- me.addContext (CREATE_STACK);
- throw me;
- }
- }
-
- if (!"CREATE_COMPLETE".equals (heatStack.getStackStatus ())) {
- logger.error("{} Create Stack error: Polling complete with non-success status: {}, {} {} ",
- MessageEnum.RA_CREATE_STACK_ERR, heatStack.getStackStatus(), heatStack.getStackStatusReason(),
- ErrorCode.BusinessProcesssError.getValue());
-
- // Rollback the stack creation, since it is in an indeterminate state.
- if (!backout)
- {
- logger.warn(
- "{} Create Stack errored, stack deletion suppressed {} Create Stack error, stack deletion suppressed",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
}
- else
- {
- try {
- logger.debug("Create Stack errored - attempting to DELETE stack: {}", canonicalName);
- logger.debug("deletePollInterval={}, deletePollTimeout={}", deletePollInterval, deletePollTimeout);
- OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName);
- executeAndRecordOpenstackRequest (request);
- boolean deleted = false;
- while (!deleted) {
- try {
- heatStack = queryHeatStack(heatClient, canonicalName);
- if (heatStack != null) {
- logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName);
- if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
- if (deletePollTimeout <= 0) {
- logger.error(
- "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout",
- MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
- heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
- break;
- } else {
- sleep(deletePollInterval * 1000L);
- deletePollTimeout -= deletePollInterval;
- logger.debug("deletePollTimeout remaining: {}", deletePollTimeout);
+
+ if (!"CREATE_COMPLETE".equals(heatStack.getStackStatus())) {
+ logger.error("{} Create Stack error: Polling complete with non-success status: {}, {} {} ",
+ MessageEnum.RA_CREATE_STACK_ERR, heatStack.getStackStatus(), heatStack.getStackStatusReason(),
+ ErrorCode.BusinessProcesssError.getValue());
+
+ // Rollback the stack creation, since it is in an indeterminate state.
+ if (!backout) {
+ logger.warn(
+ "{} Create Stack errored, stack deletion suppressed {} Create Stack error, stack deletion suppressed",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
+ } else {
+ try {
+ logger.debug("Create Stack errored - attempting to DELETE stack: {}", canonicalName);
+ logger.debug("deletePollInterval={}, deletePollTimeout={}", deletePollInterval, deletePollTimeout);
+ OpenStackRequest<Void> request = heatClient.getStacks().deleteByName(canonicalName);
+ executeAndRecordOpenstackRequest(request);
+ boolean deleted = false;
+ while (!deleted) {
+ try {
+ heatStack = queryHeatStack(heatClient, canonicalName);
+ if (heatStack != null) {
+ logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName);
+ if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
+ if (deletePollTimeout <= 0) {
+ logger.error(
+ "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout",
+ MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
+ heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
+ break;
+ } else {
+ sleep(deletePollInterval * 1000L);
+ deletePollTimeout -= deletePollInterval;
+ logger.debug("deletePollTimeout remaining: {}", deletePollTimeout);
+ }
+ } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())) {
+ logger.debug("DELETE_COMPLETE for {}", canonicalName);
+ deleted = true;
+ continue;
+ } else if ("DELETE_FAILED".equals(heatStack.getStackStatus())) {
+ // Warn about this (?) - but still throw the original exception
+ logger.warn(
+ "{} Create Stack errored, stack deletion FAILED {} Create Stack error, stack deletion FAILED",
+ MessageEnum.RA_CREATE_STACK_ERR,
+ ErrorCode.BusinessProcesssError.getValue());
+ logger.debug(
+ "Stack deletion FAILED on a rollback of a create - {}, status={}, reason={}",
+ canonicalName, heatStack.getStackStatus(),
+ heatStack.getStackStatusReason());
+ break;
+ } else {
+ // got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and
+ // evaluate
+ break;
+ }
+ } else {
+ // assume if we can't find it - it's deleted
+ logger.debug("heatStack returned null - assume the stack {} has been deleted",
+ canonicalName);
+ deleted = true;
+ continue;
+ }
+
+ } catch (MsoException me2) {
+ // We got an exception on the delete - don't throw this exception - throw the original -
+ // just log.
+ logger.debug("Exception thrown trying to delete {} on a create->rollback: {} ",
+ canonicalName, me2.getContextMessage(), me2);
+ logger.warn("{} Create Stack errored, then stack deletion FAILED - exception thrown {} {}",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
+ me2.getContextMessage());
+ }
+
+ } // end while !deleted
+ StringBuilder errorContextMessage;
+ if (createTimedOut) {
+ errorContextMessage = new StringBuilder("Stack Creation Timeout");
+ } else {
+ errorContextMessage = stackErrorStatusReason;
}
- } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){
- logger.debug("DELETE_COMPLETE for {}", canonicalName);
- deleted = true;
- continue;
- } else if ("DELETE_FAILED".equals(heatStack.getStackStatus())) {
- // Warn about this (?) - but still throw the original exception
- logger.warn(
- "{} Create Stack errored, stack deletion FAILED {} Create Stack error, stack deletion FAILED",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
- logger.debug("Stack deletion FAILED on a rollback of a create - {}, status={}, reason={}",
- canonicalName, heatStack.getStackStatus(), heatStack.getStackStatusReason());
- break;
- } else {
- //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
- break;
- }
- } else {
- // assume if we can't find it - it's deleted
- logger.debug("heatStack returned null - assume the stack {} has been deleted", canonicalName);
- deleted = true;
- continue;
- }
-
- } catch (MsoException me2) {
- // We got an exception on the delete - don't throw this exception - throw the original - just log.
- logger.debug("Exception thrown trying to delete {} on a create->rollback: {} ", canonicalName,
- me2.getContextMessage(), me2);
- logger.warn("{} Create Stack errored, then stack deletion FAILED - exception thrown {} {}",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
- me2.getContextMessage());
- }
-
- } // end while !deleted
- StringBuilder errorContextMessage;
- if (createTimedOut) {
- errorContextMessage = new StringBuilder("Stack Creation Timeout");
- } else {
- errorContextMessage = stackErrorStatusReason;
- }
- if (deleted) {
- errorContextMessage.append(" - stack successfully deleted");
- } else {
- errorContextMessage.append(" - encountered an error trying to delete the stack");
- }
- } catch (Exception e2) {
- // shouldn't happen - but handle
- logger.error("{} Create Stack: Nested exception rolling back stack: {} ", MessageEnum.RA_CREATE_STACK_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e2);
- }
- }
- MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
- me.addContext(CREATE_STACK);
- throw me;
- }
- return heatStack;
- }
+ if (deleted) {
+ errorContextMessage.append(" - stack successfully deleted");
+ } else {
+ errorContextMessage.append(" - encountered an error trying to delete the stack");
+ }
+ } catch (Exception e2) {
+ // shouldn't happen - but handle
+ logger.error("{} Create Stack: Nested exception rolling back stack: {} ",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e2);
+ }
+ }
+ MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
+ me.addContext(CREATE_STACK);
+ throw me;
+ }
+ return heatStack;
+ }
/**
- * Query for a single stack (by Name) in a tenant. This call will always return a
- * StackInfo object. If the stack does not exist, an "empty" StackInfo will be
- * returned - containing only the stack name and a status of NOTFOUND.
+ * Query for a single stack (by Name) in a tenant. This call will always return a StackInfo object. If the stack
+ * does not exist, an "empty" StackInfo will be returned - containing only the stack name and a status of NOTFOUND.
*
* @param tenantId The Openstack ID of the tenant in which to query
* @param cloudSiteId The cloud identifier (may be a region) in which to query
+ * @param cloudOwner the cloud owner of the cloud site in which to query
* @param stackName The name of the stack to query (may be simple or canonical)
* @return A StackInfo object
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
*/
- public StackInfo queryStack (String cloudSiteId, String tenantId, String stackName) throws MsoException {
- logger.debug ("Query HEAT stack: {} in tenant {}", stackName, tenantId);
+ public StackInfo queryStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName)
+ throws MsoException {
+ logger.debug("Query HEAT stack: {} in tenant {}", stackName, tenantId);
// Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
logger.debug("Found: {}", cloudSite.toString());
// Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
Heat heatClient = null;
try {
- heatClient = getHeatClient (cloudSite, tenantId);
+ heatClient = getHeatClient(cloudSite, tenantId);
if (heatClient != null) {
logger.debug("Found: {}", heatClient.toString());
}
} catch (MsoTenantNotFound e) {
// Tenant doesn't exist, so stack doesn't either
- logger.debug ("Tenant with id " + tenantId + "not found.", e);
- return new StackInfo (stackName, HeatStatus.NOTFOUND);
+ logger.debug("Tenant with id " + tenantId + "not found.", e);
+ return new StackInfo(stackName, HeatStatus.NOTFOUND);
} catch (MsoException me) {
// Got an Openstack error. Propagate it
logger.error("{} {} Openstack Exception on Token request: ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.AvailabilityError.getValue(), me);
- me.addContext ("QueryStack");
+ ErrorCode.AvailabilityError.getValue(), me);
+ me.addContext("QueryStack");
throw me;
}
// Query the Stack.
// An MsoException will propagate transparently to the caller.
- Stack heatStack = queryHeatStack (heatClient, stackName);
+ Stack heatStack = queryHeatStack(heatClient, stackName);
if (heatStack == null) {
// Stack does not exist. Return a StackInfo with status NOTFOUND
- return new StackInfo (stackName, HeatStatus.NOTFOUND);
+ return new StackInfo(stackName, HeatStatus.NOTFOUND);
}
return new StackInfoMapper(heatStack).map();
}
/**
- * Delete a stack (by Name/ID) in a tenant. If the stack is not found, it will be
- * considered a successful deletion. The return value is a StackInfo object which
- * contains the current stack status.
+ * Delete a stack (by Name/ID) in a tenant. If the stack is not found, it will be considered a successful deletion.
+ * The return value is a StackInfo object which contains the current stack status.
*
- * The client may choose to let the adapter poll Openstack for completion of the
- * stack deletion, or may handle polling itself via separate query calls. In either
- * case, a StackInfo object will be returned. When polling is enabled, a final
- * status of NOTFOUND is expected. When not polling, a status of DELETING is expected.
+ * The client may choose to let the adapter poll Openstack for completion of the stack deletion, or may handle
+ * polling itself via separate query calls. In either case, a StackInfo object will be returned. When polling is
+ * enabled, a final status of NOTFOUND is expected. When not polling, a status of DELETING is expected.
*
- * There is no rollback from a successful stack deletion. A deletion failure will
- * also result in an undefined stack state - the components may or may not have been
- * all or partially deleted, so the resulting stack must be considered invalid.
+ * There is no rollback from a successful stack deletion. A deletion failure will also result in an undefined stack
+ * state - the components may or may not have been all or partially deleted, so the resulting stack must be
+ * considered invalid.
*
* @param tenantId The Openstack ID of the tenant in which to perform the delete
+ * @param cloudOwner the cloud owner of the cloud site in which to delete the stack
* @param cloudSiteId The cloud identifier (may be a region) from which to delete the stack.
* @param stackName The name/id of the stack to delete. May be simple or canonical
* @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
@@ -609,39 +548,37 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
* @throws MsoCloudSiteNotFound
*/
- public StackInfo deleteStack (String tenantId,
- String cloudSiteId,
- String stackName,
- boolean pollForCompletion) throws MsoException {
+ public StackInfo deleteStack(String tenantId, String cloudOwner, String cloudSiteId, String stackName,
+ boolean pollForCompletion) throws MsoException {
// Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
logger.debug("Found: {}", cloudSite.toString());
// Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
Heat heatClient = null;
try {
- heatClient = getHeatClient (cloudSite, tenantId);
+ heatClient = getHeatClient(cloudSite, tenantId);
if (heatClient != null) {
logger.debug("Found: {}", heatClient.toString());
}
} catch (MsoTenantNotFound e) {
// Tenant doesn't exist, so stack doesn't either
- logger.debug ("Tenant with id " + tenantId + "not found.", e);
- return new StackInfo (stackName, HeatStatus.NOTFOUND);
+ logger.debug("Tenant with id " + tenantId + "not found.", e);
+ return new StackInfo(stackName, HeatStatus.NOTFOUND);
} catch (MsoException me) {
// Got an Openstack error. Propagate it
logger.error("{} {} Openstack Exception on Token request: ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.AvailabilityError.getValue(), me);
- me.addContext (DELETE_STACK);
+ ErrorCode.AvailabilityError.getValue(), me);
+ me.addContext(DELETE_STACK);
throw me;
}
// OK if stack not found, perform a query first
- Stack heatStack = queryHeatStack (heatClient, stackName);
- if (heatStack == null || "DELETE_COMPLETE".equals (heatStack.getStackStatus ())) {
+ Stack heatStack = queryHeatStack(heatClient, stackName);
+ if (heatStack == null || "DELETE_COMPLETE".equals(heatStack.getStackStatus())) {
// Not found. Return a StackInfo with status NOTFOUND
- return new StackInfo (stackName, HeatStatus.NOTFOUND);
+ return new StackInfo(stackName, HeatStatus.NOTFOUND);
}
// Delete the stack.
@@ -649,56 +586,56 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
// Use canonical name "<stack name>/<stack-id>" to delete.
// Otherwise, deletion by name returns a 302 redirect.
// NOTE: This is specific to the v1 Orchestration API.
- String canonicalName = heatStack.getStackName () + "/" + heatStack.getId ();
+ String canonicalName = heatStack.getStackName() + "/" + heatStack.getId();
try {
- OpenStackRequest <Void> request = null;
- if(null != heatClient) {
- request = heatClient.getStacks ().deleteByName (canonicalName);
- }
- else {
- logger.debug ("Heat Client is NULL" );
+ OpenStackRequest<Void> request = null;
+ if (null != heatClient) {
+ request = heatClient.getStacks().deleteByName(canonicalName);
+ } else {
+ logger.debug("Heat Client is NULL");
}
- executeAndRecordOpenstackRequest (request);
+ executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 404) {
+ if (e.getStatus() == 404) {
// Not found. We are OK with this. Return a StackInfo with status NOTFOUND
- return new StackInfo (stackName, HeatStatus.NOTFOUND);
+ return new StackInfo(stackName, HeatStatus.NOTFOUND);
} else {
// Convert the OpenStackResponseException to an MsoOpenstackException
- throw heatExceptionToMsoException (e, DELETE_STACK);
+ throw heatExceptionToMsoException(e, DELETE_STACK);
}
} catch (OpenStackConnectException e) {
// Error connecting to Openstack instance. Convert to an MsoException
- throw heatExceptionToMsoException (e, DELETE_STACK);
+ throw heatExceptionToMsoException(e, DELETE_STACK);
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, DELETE_STACK);
+ throw runtimeExceptionToMsoException(e, DELETE_STACK);
}
// Requery the stack for current status.
// It will probably still exist with "DELETE_IN_PROGRESS" status.
- heatStack = queryHeatStack (heatClient, canonicalName);
+ heatStack = queryHeatStack(heatClient, canonicalName);
if (pollForCompletion) {
// Set a timeout on polling
- int pollInterval = Integer.parseInt(this.environment.getProperty(deletePollIntervalProp, "" + deletePollIntervalDefault));
- int pollTimeout = Integer.parseInt(this.environment.getProperty(deletePollTimeoutProp, "" + deletePollIntervalDefault));
+ int pollInterval = Integer
+ .parseInt(this.environment.getProperty(deletePollIntervalProp, "" + deletePollIntervalDefault));
+ int pollTimeout = Integer
+ .parseInt(this.environment.getProperty(deletePollTimeoutProp, "" + deletePollIntervalDefault));
// When querying by canonical name, Openstack returns DELETE_COMPLETE status
// instead of "404" (which would result from query by stack name).
- while (heatStack != null && !"DELETE_COMPLETE".equals (heatStack.getStackStatus ())) {
- logger.debug ("Stack status: {}", heatStack.getStackStatus ());
+ while (heatStack != null && !"DELETE_COMPLETE".equals(heatStack.getStackStatus())) {
+ logger.debug("Stack status: {}", heatStack.getStackStatus());
- if ("DELETE_FAILED".equals (heatStack.getStackStatus ())) {
+ if ("DELETE_FAILED".equals(heatStack.getStackStatus())) {
// Throw a 'special case' of MsoOpenstackException to report the Heat status
- String error = "Stack delete error (" + heatStack.getStackStatus ()
- + "): "
- + heatStack.getStackStatusReason ();
- MsoOpenstackException me = new MsoOpenstackException (0, "", error);
- me.addContext (DELETE_STACK);
+ String error = "Stack delete error (" + heatStack.getStackStatus() + "): "
+ + heatStack.getStackStatusReason();
+ MsoOpenstackException me = new MsoOpenstackException(0, "", error);
+ me.addContext(DELETE_STACK);
// Alarm this condition, stack deletion failed
@@ -708,12 +645,12 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
if (pollTimeout <= 0) {
logger.error("{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Delete Stack Timeout",
- MessageEnum.RA_DELETE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
- heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
+ MessageEnum.RA_DELETE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
+ heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
// Throw a 'special case' of MsoOpenstackException to report the Heat status
- MsoOpenstackException me = new MsoOpenstackException (0, "", "Stack Deletion Timeout");
- me.addContext (DELETE_STACK);
+ MsoOpenstackException me = new MsoOpenstackException(0, "", "Stack Deletion Timeout");
+ me.addContext(DELETE_STACK);
// Alarm this condition, stack deletion failed
@@ -726,26 +663,26 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
pollTimeout -= pollInterval;
logger.debug("pollTimeout remaining: {}", pollTimeout);
- heatStack = queryHeatStack (heatClient, canonicalName);
+ heatStack = queryHeatStack(heatClient, canonicalName);
}
// The stack is gone when this point is reached
- return new StackInfo (stackName, HeatStatus.NOTFOUND);
+ return new StackInfo(stackName, HeatStatus.NOTFOUND);
}
// Return the current status (if not polling, the delete may still be in progress)
StackInfo stackInfo = new StackInfoMapper(heatStack).map();
- stackInfo.setName (stackName);
+ stackInfo.setName(stackName);
return stackInfo;
}
/**
- * Query for all stacks in a tenant site. This call will return a List of StackInfo
- * objects, one for each deployed stack.
+ * Query for all stacks in a tenant site. This call will return a List of StackInfo objects, one for each deployed
+ * stack.
*
- * Note that this is limited to a single site. To ensure that a tenant is truly
- * empty would require looping across all tenant endpoints.
+ * Note that this is limited to a single site. To ensure that a tenant is truly empty would require looping across
+ * all tenant endpoints.
*
* @param tenantId The Openstack ID of the tenant to query
* @param cloudSiteId The cloud identifier (may be a region) in which to query.
@@ -753,101 +690,96 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
* @throws MsoCloudSiteNotFound
*/
- public List <StackInfo> queryAllStacks (String tenantId, String cloudSiteId) throws MsoException {
+ public List<StackInfo> queryAllStacks(String tenantId, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
// Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
- Heat heatClient = getHeatClient (cloudSite, tenantId);
+ Heat heatClient = getHeatClient(cloudSite, tenantId);
try {
- OpenStackRequest <Stacks> request = heatClient.getStacks ().list ();
- Stacks stacks = executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Stacks> request = heatClient.getStacks().list();
+ Stacks stacks = executeAndRecordOpenstackRequest(request);
- List <StackInfo> stackList = new ArrayList <> ();
+ List<StackInfo> stackList = new ArrayList<>();
// Not sure if returns an empty list or null if no stacks exist
if (stacks != null) {
for (Stack stack : stacks) {
- stackList.add (new StackInfoMapper(stack).map());
+ stackList.add(new StackInfoMapper(stack).map());
}
}
return stackList;
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 404) {
+ if (e.getStatus() == 404) {
// Not sure if this can happen, but return an empty list
- logger.debug ("queryAllStacks - stack not found: ");
- return new ArrayList <> ();
+ logger.debug("queryAllStacks - stack not found: ");
+ return new ArrayList<>();
} else {
// Convert the OpenStackResponseException to an MsoOpenstackException
- throw heatExceptionToMsoException (e, QUERY_ALL_STACKS);
+ throw heatExceptionToMsoException(e, QUERY_ALL_STACKS);
}
} catch (OpenStackConnectException e) {
// Error connecting to Openstack instance. Convert to an MsoException
- throw heatExceptionToMsoException (e, QUERY_ALL_STACKS);
+ throw heatExceptionToMsoException(e, QUERY_ALL_STACKS);
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, QUERY_ALL_STACKS);
+ throw runtimeExceptionToMsoException(e, QUERY_ALL_STACKS);
}
}
/**
- * Validate parameters to be passed to Heat template. This method performs
- * three functions:
- * 1. Apply default values to parameters which have them defined
- * 2. Report any required parameters that are missing. This will generate an
- * exception in the caller, since stack create/update operations would fail.
- * 3. Report and remove any extraneous parameters. This will allow clients to
- * pass supersets of parameters and not get errors.
+ * Validate parameters to be passed to Heat template. This method performs three functions: 1. Apply default values
+ * to parameters which have them defined 2. Report any required parameters that are missing. This will generate an
+ * exception in the caller, since stack create/update operations would fail. 3. Report and remove any extraneous
+ * parameters. This will allow clients to pass supersets of parameters and not get errors.
*
- * These functions depend on the HeatTemplate definition from the MSO Catalog DB,
- * along with the input parameter Map. The output is an updated parameter map.
- * If the parameters are invalid for the template, an IllegalArgumentException
- * is thrown.
+ * These functions depend on the HeatTemplate definition from the MSO Catalog DB, along with the input parameter
+ * Map. The output is an updated parameter map. If the parameters are invalid for the template, an
+ * IllegalArgumentException is thrown.
*/
- public Map <String, Object> validateStackParams (Map <String, Object> inputParams,
- HeatTemplate heatTemplate) {
+ public Map<String, Object> validateStackParams(Map<String, Object> inputParams, HeatTemplate heatTemplate) {
// Check that required parameters have been supplied for this template type
StringBuilder missingParams = null;
- List <String> paramList = new ArrayList <> ();
+ List<String> paramList = new ArrayList<>();
// TODO: Enhance DB to support defaults for Heat Template parameters
- for (HeatTemplateParam parm : heatTemplate.getParameters ()) {
- if (parm.isRequired () && !inputParams.containsKey (parm.getParamName ())) {
+ for (HeatTemplateParam parm : heatTemplate.getParameters()) {
+ if (parm.isRequired() && !inputParams.containsKey(parm.getParamName())) {
if (missingParams == null) {
missingParams = new StringBuilder(parm.getParamName());
} else {
missingParams.append("," + parm.getParamName());
}
}
- paramList.add (parm.getParamName ());
+ paramList.add(parm.getParamName());
}
if (missingParams != null) {
// Problem - missing one or more required parameters
String error = "Missing Required inputs for HEAT Template: " + missingParams;
logger.error("{} for HEAT Template {} Missing Required inputs for HEAT Template: {}",
- MessageEnum.RA_MISSING_PARAM, ErrorCode.SchemaError.getValue(), missingParams);
- throw new IllegalArgumentException (error);
+ MessageEnum.RA_MISSING_PARAM, ErrorCode.SchemaError.getValue(), missingParams);
+ throw new IllegalArgumentException(error);
}
// Remove any extraneous parameters (don't throw an error)
- Map <String, Object> updatedParams = new HashMap <> ();
- List <String> extraParams = new ArrayList <> ();
+ Map<String, Object> updatedParams = new HashMap<>();
+ List<String> extraParams = new ArrayList<>();
for (Entry<String, Object> entry : inputParams.entrySet()) {
- if (!paramList.contains(entry.getKey())) {
- // This is not a valid parameter for this template
- extraParams.add(entry.getKey());
- } else {
- updatedParams.put(entry.getKey(), entry.getValue());
- }
+ if (!paramList.contains(entry.getKey())) {
+ // This is not a valid parameter for this template
+ extraParams.add(entry.getKey());
+ } else {
+ updatedParams.put(entry.getKey(), entry.getValue());
+ }
}
- if (!extraParams.isEmpty ()) {
+ if (!extraParams.isEmpty()) {
logger.warn("{} Heat Stack ({}) extra input params received: {} {}", MessageEnum.RA_GENERAL_WARNING,
- heatTemplate.getTemplateName(), extraParams, ErrorCode.DataError.getValue());
+ heatTemplate.getTemplateName(), extraParams, ErrorCode.DataError.getValue());
}
return updatedParams;
@@ -857,637 +789,626 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
// PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
/**
- * Get a Heat client for the Openstack Identity service.
- * This requires a 'member'-level userId + password, which will be retrieved from
- * properties based on the specified cloud Id. The tenant in which to operate
- * must also be provided.
+ * Get a Heat client for the Openstack Identity service. This requires a 'member'-level userId + password, which
+ * will be retrieved from properties based on the specified cloud Id. The tenant in which to operate must also be
+ * provided.
* <p>
- * On successful authentication, the Heat object will be cached for the
- * tenantID + cloudId so that it can be reused without reauthenticating with
- * Openstack every time.
+ * On successful authentication, the Heat object will be cached for the tenantID + cloudId so that it can be reused
+ * without reauthenticating with Openstack every time.
*
* @return an authenticated Heat object
*/
- public Heat getHeatClient (CloudSite cloudSite, String tenantId) throws MsoException {
+ public Heat getHeatClient(CloudSite cloudSite, String tenantId) throws MsoException {
String cloudId = cloudSite.getId();
// For DCP/LCP, the region should be the cloudId.
- String region = cloudSite.getRegionId ();
+ String region = cloudSite.getRegionId();
// Obtain an MSO token for the tenant
CloudIdentity cloudIdentity = cloudSite.getIdentityService();
logger.debug("Found: {}", cloudIdentity.toString());
- MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
+ MsoTenantUtils tenantUtils =
+ tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
logger.debug("keystoneUrl={}", keystoneUrl);
String heatUrl = null;
String tokenId = null;
Calendar expiration = null;
- try {
- if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
- Keystone keystoneTenantClient = new Keystone (keystoneUrl);
- Access access = null;
-
- Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
-
- OpenStackRequest <Access> request = keystoneTenantClient.tokens ()
- .authenticate (credentials).withTenantId (tenantId);
-
- access = executeAndRecordOpenstackRequest (request);
-
- try {
- // Isolate trying to printout the region IDs
- try {
- logger.debug("access={}", access.toString());
- for (Access.Service service : access.getServiceCatalog()) {
- List<Access.Service.Endpoint> endpoints = service.getEndpoints();
- for (Access.Service.Endpoint endpoint : endpoints) {
- logger.debug("AIC returned region={}", endpoint.getRegion());
- }
- }
- } catch (Exception e) {
- logger.debug("Encountered an error trying to printout Access object returned from AIC. {}",
- e.getMessage(), e);
- }
- heatUrl = KeystoneUtils.findEndpointURL (access.getServiceCatalog (), "orchestration", region, "public");
- logger.debug("heatUrl={}, region={}", heatUrl, region);
- } catch (RuntimeException e) {
- // This comes back for not found (probably an incorrect region ID)
- String error = "AIC did not match an orchestration service for: region=" + region + ",cloud=" + cloudIdentity.getIdentityUrl();
- throw new MsoAdapterException (error, e);
- }
- tokenId = access.getToken ().getId ();
- expiration = access.getToken ().getExpires ();
- } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
- try {
- KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "orchestration");
- tokenId = holder.getId();
- expiration = holder.getexpiration();
- heatUrl = holder.getServiceUrl();
- } catch (ServiceEndpointNotFoundException e) {
- // This comes back for not found (probably an incorrect region ID)
- String error = "cloud did not match an orchestration service for: region=" + region + ",cloud=" + cloudIdentity.getIdentityUrl();
- throw new MsoAdapterException (error, e);
- }
- }
- } catch (OpenStackResponseException e) {
- if (e.getStatus () == 401) {
+ try {
+ if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
+ Keystone keystoneTenantClient = new Keystone(keystoneUrl);
+ Access access = null;
+
+ Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
+
+ OpenStackRequest<Access> request =
+ keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId);
+
+ access = executeAndRecordOpenstackRequest(request);
+
+ try {
+ // Isolate trying to printout the region IDs
+ try {
+ logger.debug("access={}", access.toString());
+ for (Access.Service service : access.getServiceCatalog()) {
+ List<Access.Service.Endpoint> endpoints = service.getEndpoints();
+ for (Access.Service.Endpoint endpoint : endpoints) {
+ logger.debug("AIC returned region={}", endpoint.getRegion());
+ }
+ }
+ } catch (Exception e) {
+ logger.debug("Encountered an error trying to printout Access object returned from AIC. {}",
+ e.getMessage(), e);
+ }
+ heatUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "orchestration", region,
+ "public");
+ logger.debug("heatUrl={}, region={}", heatUrl, region);
+ } catch (RuntimeException e) {
+ // This comes back for not found (probably an incorrect region ID)
+ String error = "AIC did not match an orchestration service for: region=" + region + ",cloud="
+ + cloudIdentity.getIdentityUrl();
+ throw new MsoAdapterException(error, e);
+ }
+ tokenId = access.getToken().getId();
+ expiration = access.getToken().getExpires();
+ } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
+ try {
+ KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "orchestration");
+ tokenId = holder.getId();
+ expiration = holder.getexpiration();
+ heatUrl = holder.getServiceUrl();
+ } catch (ServiceEndpointNotFoundException e) {
+ // This comes back for not found (probably an incorrect region ID)
+ String error = "cloud did not match an orchestration service for: region=" + region + ",cloud="
+ + cloudIdentity.getIdentityUrl();
+ throw new MsoAdapterException(error, e);
+ }
+ }
+ } catch (OpenStackResponseException e) {
+ if (e.getStatus() == 401) {
// Authentication error.
- String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId ();
+ String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId();
- throw new MsoAdapterException (error);
+ throw new MsoAdapterException(error);
} else {
- throw keystoneErrorToMsoException (e, TOKEN_AUTH);
+ throw keystoneErrorToMsoException(e, TOKEN_AUTH);
}
} catch (OpenStackConnectException e) {
// Connection to Openstack failed
- MsoIOException me = new MsoIOException (e.getMessage (), e);
- me.addContext (TOKEN_AUTH);
+ MsoIOException me = new MsoIOException(e.getMessage(), e);
+ me.addContext(TOKEN_AUTH);
throw me;
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, TOKEN_AUTH);
+ throw runtimeExceptionToMsoException(e, TOKEN_AUTH);
}
- Heat heatClient = new Heat (heatUrl);
- heatClient.token (tokenId);
+ Heat heatClient = new Heat(heatUrl);
+ heatClient.token(tokenId);
return heatClient;
}
/*
- * Query for a Heat Stack. This function is needed in several places, so
- * a common method is useful. This method takes an authenticated Heat Client
- * (which internally identifies the cloud & tenant to search), and returns
- * a Stack object if found, Null if not found, or an MsoOpenstackException
- * if the Openstack API call fails.
+ * Query for a Heat Stack. This function is needed in several places, so a common method is useful. This method
+ * takes an authenticated Heat Client (which internally identifies the cloud & tenant to search), and returns a
+ * Stack object if found, Null if not found, or an MsoOpenstackException if the Openstack API call fails.
*
- * The stack name may be a simple name or a canonical name ("{name}/{id}").
- * When simple name is used, Openstack always returns a 302 redirect which
- * results in a 2nd request (to the canonical name). Note that query by
- * canonical name for a deleted stack returns a Stack object with status
- * "DELETE_COMPLETE" while query by simple name for a deleted stack returns
- * HTTP 404.
+ * The stack name may be a simple name or a canonical name ("{name}/{id}"). When simple name is used, Openstack
+ * always returns a 302 redirect which results in a 2nd request (to the canonical name). Note that query by
+ * canonical name for a deleted stack returns a Stack object with status "DELETE_COMPLETE" while query by simple
+ * name for a deleted stack returns HTTP 404.
*
* @param heatClient an authenticated Heat client
*
* @param stackName the stack name to query
*
- * @return a Stack object that describes the current stack or null if the
- * requested stack doesn't exist.
+ * @return a Stack object that describes the current stack or null if the requested stack doesn't exist.
*
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
*/
- protected Stack queryHeatStack (Heat heatClient, String stackName) throws MsoException {
+ protected Stack queryHeatStack(Heat heatClient, String stackName) throws MsoException {
if (stackName == null) {
return null;
}
try {
- OpenStackRequest <Stack> request = heatClient.getStacks ().byName (stackName);
- return executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Stack> request = heatClient.getStacks().byName(stackName);
+ return executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- logger.error("Error in Query Stack", e);
- if (e.getStatus () == 404) {
- logger.debug ("queryHeatStack - stack not found: {}", stackName);
+ logger.error("Error in Query Stack", e);
+ if (e.getStatus() == 404) {
+ logger.debug("queryHeatStack - stack not found: {}", stackName);
return null;
} else {
// Convert the OpenStackResponseException to an MsoOpenstackException
- throw heatExceptionToMsoException (e, "QueryStack");
+ throw heatExceptionToMsoException(e, "QueryStack");
}
} catch (OpenStackConnectException e) {
// Connection to Openstack failed
- throw heatExceptionToMsoException (e, "QueryAllStack");
+ throw heatExceptionToMsoException(e, "QueryAllStack");
}
}
- public Map<String, Object> queryStackForOutputs(String cloudSiteId,
- String tenantId, String stackName) throws MsoException {
- logger.debug("MsoHeatUtils.queryStackForOutputs)");
- StackInfo heatStack = this.queryStack(cloudSiteId, tenantId, stackName);
- if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
- return null;
- }
- return heatStack.getOutputs();
- }
-
- public void copyStringOutputsToInputs(Map<String, Object> inputs,
- Map<String, Object> otherStackOutputs, boolean overWrite) {
- if (inputs == null || otherStackOutputs == null)
- return;
- for (String key : otherStackOutputs.keySet()) {
- if (!inputs.containsKey(key)) {
- Object obj = otherStackOutputs.get(key);
- if (obj instanceof String) {
- inputs.put(key, (String) otherStackOutputs.get(key));
- } else if (obj instanceof JsonNode ){
- // This is a bit of mess - but I think it's the least impacting
- // let's convert it BACK to a string - then it will get converted back later
- try {
- String str = this.convertNode((JsonNode) obj);
- inputs.put(key, str);
- } catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode {} ", key, e);
- //effect here is this value will not have been copied to the inputs - and therefore will error out downstream
- }
- } else if (obj instanceof java.util.LinkedHashMap) {
- logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
- try {
- String str = JSON_MAPPER.writeValueAsString(obj);
- inputs.put(key, str);
- } catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap {} ", key, e);
- }
- } else if (obj instanceof Integer) {
- try {
- String str = "" + obj;
- inputs.put(key, str);
- } catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer {} ", key, e);
- }
- } else {
- try {
- String str = obj.toString();
- inputs.put(key, str);
- } catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for Other {} ({}) ", key, e.getMessage(), e);
- //effect here is this value will not have been copied to the inputs - and therefore will error out downstream
- }
- }
- }
- }
- return;
- }
- public StringBuilder requestToStringBuilder(CreateStackParam stack) {
- StringBuilder sb = new StringBuilder();
- sb.append("Stack:\n");
- sb.append("\tStackName: " + stack.getStackName());
- sb.append("\tTemplateUrl: " + stack.getTemplateUrl());
- sb.append("\tTemplate: " + stack.getTemplate());
- sb.append("\tEnvironment: " + stack.getEnvironment());
- sb.append("\tTimeout: " + stack.getTimeoutMinutes());
- sb.append("\tParameters:\n");
- Map<String, Object> params = stack.getParameters();
- if (params == null || params.size() < 1) {
- sb.append("\nNONE");
- } else {
- for (String key : params.keySet()) {
- if (params.get(key) instanceof String) {
- sb.append("\n").append(key).append("=").append((String) params.get(key));
- } else if (params.get(key) instanceof JsonNode) {
- String jsonStringOut = this.convertNode((JsonNode)params.get(key));
- sb.append("\n").append(key).append("=").append(jsonStringOut);
- } else if (params.get(key) instanceof Integer) {
- String integerOut = "" + params.get(key);
- sb.append("\n").append(key).append("=").append(integerOut);
-
- } else {
- try {
- String str = params.get(key).toString();
- sb.append("\n").append(key).append("=").append(str);
- } catch (Exception e) {
- logger.debug("Exception :", e);
- }
- }
- }
- }
- return sb;
- }
-
- private String convertNode(final JsonNode node) {
- try {
- final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
- final String json = JSON_MAPPER.writeValueAsString(obj);
- return json;
- } catch (Exception e) {
- logger.debug("Error converting json to string {} ", e.getMessage(), e);
+ public Map<String, Object> queryStackForOutputs(String cloudSiteId, String cloudOwner, String tenantId,
+ String stackName) throws MsoException {
+ logger.debug("MsoHeatUtils.queryStackForOutputs)");
+ StackInfo heatStack = this.queryStack(cloudSiteId, cloudOwner, tenantId, stackName);
+ if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
+ return null;
+ }
+ return heatStack.getOutputs();
+ }
+
+ public void copyStringOutputsToInputs(Map<String, Object> inputs, Map<String, Object> otherStackOutputs,
+ boolean overWrite) {
+ if (inputs == null || otherStackOutputs == null)
+ return;
+ for (String key : otherStackOutputs.keySet()) {
+ if (!inputs.containsKey(key)) {
+ Object obj = otherStackOutputs.get(key);
+ if (obj instanceof String) {
+ inputs.put(key, (String) otherStackOutputs.get(key));
+ } else if (obj instanceof JsonNode) {
+ // This is a bit of mess - but I think it's the least impacting
+ // let's convert it BACK to a string - then it will get converted back later
+ try {
+ String str = this.convertNode((JsonNode) obj);
+ inputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode {} ", key, e);
+ // effect here is this value will not have been copied to the inputs - and therefore will error
+ // out downstream
+ }
+ } else if (obj instanceof java.util.LinkedHashMap) {
+ logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
+ try {
+ String str = JSON_MAPPER.writeValueAsString(obj);
+ inputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap {} ", key, e);
+ }
+ } else if (obj instanceof Integer) {
+ try {
+ String str = "" + obj;
+ inputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer {} ", key, e);
+ }
+ } else {
+ try {
+ String str = obj.toString();
+ inputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for Other {} ({}) ", key,
+ e.getMessage(), e);
+ // effect here is this value will not have been copied to the inputs - and therefore will error
+ // out downstream
+ }
+ }
+ }
+ }
+ return;
+ }
+
+ public StringBuilder requestToStringBuilder(CreateStackParam stack) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Stack:\n");
+ sb.append("\tStackName: " + stack.getStackName());
+ sb.append("\tTemplateUrl: " + stack.getTemplateUrl());
+ sb.append("\tTemplate: " + stack.getTemplate());
+ sb.append("\tEnvironment: " + stack.getEnvironment());
+ sb.append("\tTimeout: " + stack.getTimeoutMinutes());
+ sb.append("\tParameters:\n");
+ Map<String, Object> params = stack.getParameters();
+ if (params == null || params.size() < 1) {
+ sb.append("\nNONE");
+ } else {
+ for (String key : params.keySet()) {
+ if (params.get(key) instanceof String) {
+ sb.append("\n").append(key).append("=").append((String) params.get(key));
+ } else if (params.get(key) instanceof JsonNode) {
+ String jsonStringOut = this.convertNode((JsonNode) params.get(key));
+ sb.append("\n").append(key).append("=").append(jsonStringOut);
+ } else if (params.get(key) instanceof Integer) {
+ String integerOut = "" + params.get(key);
+ sb.append("\n").append(key).append("=").append(integerOut);
+
+ } else {
+ try {
+ String str = params.get(key).toString();
+ sb.append("\n").append(key).append("=").append(str);
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ }
+ }
+ }
+ }
+ return sb;
+ }
+
+ private String convertNode(final JsonNode node) {
+ try {
+ final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
+ final String json = JSON_MAPPER.writeValueAsString(obj);
+ return json;
+ } catch (Exception e) {
+ logger.debug("Error converting json to string {} ", e.getMessage(), e);
+ }
+ return "[Error converting json to string]";
+ }
+
+
+ protected StringBuilder getOutputsAsStringBuilder(Stack heatStack) {
+ // This should only be used as a utility to print out the stack outputs
+ // to the log
+ StringBuilder sb = new StringBuilder("");
+ if (heatStack == null) {
+ sb.append("(heatStack is null)");
+ return sb;
+ }
+ List<Output> outputList = heatStack.getOutputs();
+ if (outputList == null || outputList.isEmpty()) {
+ sb.append("(outputs is empty)");
+ return sb;
+ }
+ Map<String, Object> outputs = new HashMap<>();
+ for (Output outputItem : outputList) {
+ outputs.put(outputItem.getOutputKey(), outputItem.getOutputValue());
+ }
+ int counter = 0;
+ sb.append("OUTPUTS:\n");
+ for (String key : outputs.keySet()) {
+ sb.append("outputs[").append(counter++).append("]: ").append(key).append("=");
+ Object obj = outputs.get(key);
+ if (obj instanceof String) {
+ sb.append((String) obj).append(" (a string)");
+ } else if (obj instanceof JsonNode) {
+ sb.append(this.convertNode((JsonNode) obj)).append(" (a JsonNode)");
+ } else if (obj instanceof java.util.LinkedHashMap) {
+ try {
+ String str = JSON_MAPPER.writeValueAsString(obj);
+ sb.append(str).append(" (a java.util.LinkedHashMap)");
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ sb.append("(a LinkedHashMap value that would not convert nicely)");
+ }
+ } else if (obj instanceof Integer) {
+ String str = "";
+ try {
+ str = obj.toString() + " (an Integer)\n";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(an Integer unable to call .toString() on)";
+ }
+ sb.append(str);
+ } else if (obj instanceof ArrayList) {
+ String str = "";
+ try {
+ str = obj.toString() + " (an ArrayList)";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(an ArrayList unable to call .toString() on?)";
+ }
+ sb.append(str);
+ } else if (obj instanceof Boolean) {
+ String str = "";
+ try {
+ str = obj.toString() + " (a Boolean)";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(an Boolean unable to call .toString() on?)";
+ }
+ sb.append(str);
+ } else {
+ String str = "";
+ try {
+ str = obj.toString() + " (unknown Object type)";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(a value unable to call .toString() on?)";
+ }
+ sb.append(str);
+ }
+ sb.append("\n");
+ }
+ sb.append("[END]");
+ return sb;
+ }
+
+
+ public void copyBaseOutputsToInputs(Map<String, Object> inputs, Map<String, Object> otherStackOutputs,
+ List<String> paramNames, Map<String, String> aliases) {
+ if (inputs == null || otherStackOutputs == null)
+ return;
+ for (String key : otherStackOutputs.keySet()) {
+ if (paramNames != null) {
+ if (!paramNames.contains(key) && !aliases.containsKey(key)) {
+ logger.debug("\tParameter {} is NOT defined to be in the template - do not copy to inputs", key);
+ continue;
+ }
+ if (aliases.containsKey(key)) {
+ logger.debug("Found an alias! Will move {} to {}", key, aliases.get(key));
+ Object obj = otherStackOutputs.get(key);
+ key = aliases.get(key);
+ otherStackOutputs.put(key, obj);
+ }
+ }
+ if (!inputs.containsKey(key)) {
+ Object obj = otherStackOutputs.get(key);
+ logger.debug("\t**Adding {} to inputs (.toString()={}", key, obj.toString());
+ if (obj instanceof String) {
+ logger.debug("\t\t**A String");
+ inputs.put(key, obj);
+ } else if (obj instanceof Integer) {
+ logger.debug("\t\t**An Integer");
+ inputs.put(key, obj);
+ } else if (obj instanceof JsonNode) {
+ logger.debug("\t\t**A JsonNode");
+ inputs.put(key, obj);
+ } else if (obj instanceof Boolean) {
+ logger.debug("\t\t**A Boolean");
+ inputs.put(key, obj);
+ } else if (obj instanceof java.util.LinkedHashMap) {
+ logger.debug("\t\t**A java.util.LinkedHashMap **");
+ inputs.put(key, obj);
+ } else if (obj instanceof java.util.ArrayList) {
+ logger.debug("\t\t**An ArrayList");
+ inputs.put(key, obj);
+ } else {
+ logger.debug("\t\t**UNKNOWN OBJECT TYPE");
+ inputs.put(key, obj);
+ }
+ } else {
+ logger.debug("key={} is already in the inputs - will not overwrite", key);
+ }
+ }
+ return;
+ }
+
+ public List<String> convertCdlToArrayList(String cdl) {
+ String cdl2 = cdl.trim();
+ String cdl3;
+ if (cdl2.startsWith("[") && cdl2.endsWith("]")) {
+ cdl3 = cdl2.substring(1, cdl2.lastIndexOf("]"));
+ } else {
+ cdl3 = cdl2;
+ }
+ return new ArrayList<>(Arrays.asList(cdl3.split(",")));
}
- return "[Error converting json to string]";
- }
-
-
- protected StringBuilder getOutputsAsStringBuilder(Stack heatStack) {
- // This should only be used as a utility to print out the stack outputs
- // to the log
- StringBuilder sb = new StringBuilder("");
- if (heatStack == null) {
- sb.append("(heatStack is null)");
- return sb;
- }
- List<Output> outputList = heatStack.getOutputs();
- if (outputList == null || outputList.isEmpty()) {
- sb.append("(outputs is empty)");
- return sb;
- }
- Map<String, Object> outputs = new HashMap<>();
- for (Output outputItem : outputList) {
- outputs.put(outputItem.getOutputKey(), outputItem.getOutputValue());
- }
- int counter = 0;
- sb.append("OUTPUTS:\n");
- for (String key : outputs.keySet()) {
- sb.append("outputs[").append(counter++).append("]: ").append(key).append("=");
- Object obj = outputs.get(key);
- if (obj instanceof String) {
- sb.append((String) obj).append(" (a string)");
- } else if (obj instanceof JsonNode) {
- sb.append(this.convertNode((JsonNode) obj)).append(" (a JsonNode)");
- } else if (obj instanceof java.util.LinkedHashMap) {
- try {
- String str = JSON_MAPPER.writeValueAsString(obj);
- sb.append(str).append(" (a java.util.LinkedHashMap)");
- } catch (Exception e) {
- logger.debug("Exception :", e);
- sb.append("(a LinkedHashMap value that would not convert nicely)");
- }
- } else if (obj instanceof Integer) {
- String str = "";
- try {
- str = obj.toString() + " (an Integer)\n";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(an Integer unable to call .toString() on)";
- }
- sb.append(str);
- } else if (obj instanceof ArrayList) {
- String str = "";
- try {
- str = obj.toString() + " (an ArrayList)";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(an ArrayList unable to call .toString() on?)";
- }
- sb.append(str);
- } else if (obj instanceof Boolean) {
- String str = "";
- try {
- str = obj.toString() + " (a Boolean)";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(an Boolean unable to call .toString() on?)";
- }
- sb.append(str);
- }
- else {
- String str = "";
- try {
- str = obj.toString() + " (unknown Object type)";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(a value unable to call .toString() on?)";
- }
- sb.append(str);
- }
- sb.append("\n");
- }
- sb.append("[END]");
- return sb;
- }
-
-
- public void copyBaseOutputsToInputs(Map<String, Object> inputs,
- Map<String, Object> otherStackOutputs, List<String> paramNames, Map<String, String> aliases) {
- if (inputs == null || otherStackOutputs == null)
- return;
- for (String key : otherStackOutputs.keySet()) {
- if (paramNames != null) {
- if (!paramNames.contains(key) && !aliases.containsKey(key)) {
- logger.debug("\tParameter {} is NOT defined to be in the template - do not copy to inputs", key);
- continue;
- }
- if (aliases.containsKey(key)) {
- logger.debug("Found an alias! Will move {} to {}", key, aliases.get(key));
- Object obj = otherStackOutputs.get(key);
- key = aliases.get(key);
- otherStackOutputs.put(key, obj);
- }
- }
- if (!inputs.containsKey(key)) {
- Object obj = otherStackOutputs.get(key);
- logger.debug("\t**Adding {} to inputs (.toString()={}", key, obj.toString());
- if (obj instanceof String) {
- logger.debug("\t\t**A String");
- inputs.put(key, obj);
- } else if (obj instanceof Integer) {
- logger.debug("\t\t**An Integer");
- inputs.put(key, obj);
- } else if (obj instanceof JsonNode) {
- logger.debug("\t\t**A JsonNode");
- inputs.put(key, obj);
- } else if (obj instanceof Boolean) {
- logger.debug("\t\t**A Boolean");
- inputs.put(key, obj);
- } else if (obj instanceof java.util.LinkedHashMap) {
- logger.debug("\t\t**A java.util.LinkedHashMap **");
- inputs.put(key, obj);
- } else if (obj instanceof java.util.ArrayList) {
- logger.debug("\t\t**An ArrayList");
- inputs.put(key, obj);
- } else {
- logger.debug("\t\t**UNKNOWN OBJECT TYPE");
- inputs.put(key, obj);
- }
- } else {
- logger.debug("key={} is already in the inputs - will not overwrite", key);
- }
- }
- return;
- }
-
- public List<String> convertCdlToArrayList(String cdl) {
- String cdl2 = cdl.trim();
- String cdl3;
- if (cdl2.startsWith("[") && cdl2.endsWith("]")) {
- cdl3 = cdl2.substring(1, cdl2.lastIndexOf("]"));
- } else {
- cdl3 = cdl2;
- }
- return new ArrayList<>(Arrays.asList(cdl3.split(",")));
- }
/**
- * New with 1707 - this method will convert all the String *values* of the inputs
- * to their "actual" object type (based on the param type: in the db - which comes from the template):
- * (heat variable type) -> java Object type
- * string -> String
- * number -> Integer
- * json -> marshal object to json
- * comma_delimited_list -> ArrayList
- * boolean -> Boolean
- * if any of the conversions should fail, we will default to adding it to the inputs
- * as a string - see if Openstack can handle it.
- * Also, will remove any params that are extra.
- * Any aliases will be converted to their appropriate name (anyone use this feature?)
+ * New with 1707 - this method will convert all the String *values* of the inputs to their "actual" object type
+ * (based on the param type: in the db - which comes from the template): (heat variable type) -> java Object type
+ * string -> String number -> Integer json -> marshal object to json comma_delimited_list -> ArrayList boolean ->
+ * Boolean if any of the conversions should fail, we will default to adding it to the inputs as a string - see if
+ * Openstack can handle it. Also, will remove any params that are extra. Any aliases will be converted to their
+ * appropriate name (anyone use this feature?)
+ *
* @param inputs - the Map<String, String> of the inputs received on the request
* @param template the HeatTemplate object - this is so we can also verify if the param is valid for this template
* @return HashMap<String, Object> of the inputs, cleaned and converted
*/
- public Map<String, Object> convertInputMap(Map<String, Object> inputs, HeatTemplate template) {
- HashMap<String, Object> newInputs = new HashMap<>();
- HashMap<String, HeatTemplateParam> params = new HashMap<>();
- HashMap<String, HeatTemplateParam> paramAliases = new HashMap<>();
-
- if (inputs == null) {
- logger.debug("convertInputMap - inputs is null - nothing to do here");
- return new HashMap<>();
- }
-
- logger.debug("convertInputMap in MsoHeatUtils called, with {} inputs, and template {}", inputs.size(),
- template.getArtifactUuid());
- try {
- logger.debug(template.toString());
- Set<HeatTemplateParam> paramSet = template.getParameters();
- logger.debug("paramSet has {} entries", paramSet.size());
- } catch (Exception e) {
- logger.debug("Exception occurred in convertInputMap:" + e.getMessage(), e);
- }
-
- for (HeatTemplateParam htp : template.getParameters()) {
- logger.debug("Adding {}", htp.getParamName());
- params.put(htp.getParamName(), htp);
- if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) {
- logger.debug("\tFound ALIAS {} -> {}", htp.getParamName(), htp.getParamAlias());
- paramAliases.put(htp.getParamAlias(), htp);
- }
- }
- logger.debug("Now iterate through the inputs...");
- for (String key : inputs.keySet()) {
- logger.debug("key={}", key);
- boolean alias = false;
- String realName = null;
- if (!params.containsKey(key)) {
- logger.debug("{} is not a parameter in the template! - check for an alias", key);
- // add check here for an alias
- if (!paramAliases.containsKey(key)) {
- logger.debug("The parameter {} is in the inputs, but it's not a parameter for this template - omit", key);
- continue;
- } else {
- alias = true;
- realName = paramAliases.get(key).getParamName();
- logger.debug("FOUND AN ALIAS! Will use {} in lieu of give key/alias {}", realName, key);
+ public Map<String, Object> convertInputMap(Map<String, Object> inputs, HeatTemplate template) {
+ HashMap<String, Object> newInputs = new HashMap<>();
+ HashMap<String, HeatTemplateParam> params = new HashMap<>();
+ HashMap<String, HeatTemplateParam> paramAliases = new HashMap<>();
+
+ if (inputs == null) {
+ logger.debug("convertInputMap - inputs is null - nothing to do here");
+ return new HashMap<>();
+ }
+
+ logger.debug("convertInputMap in MsoHeatUtils called, with {} inputs, and template {}", inputs.size(),
+ template.getArtifactUuid());
+ try {
+ logger.debug(template.toString());
+ Set<HeatTemplateParam> paramSet = template.getParameters();
+ logger.debug("paramSet has {} entries", paramSet.size());
+ } catch (Exception e) {
+ logger.debug("Exception occurred in convertInputMap {} :", e.getMessage(), e);
+ }
+
+ for (HeatTemplateParam htp : template.getParameters()) {
+ logger.debug("Adding {}", htp.getParamName());
+ params.put(htp.getParamName(), htp);
+ if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) {
+ logger.debug("\tFound ALIAS {} -> {}", htp.getParamName(), htp.getParamAlias());
+ paramAliases.put(htp.getParamAlias(), htp);
+ }
+ }
+ logger.debug("Now iterate through the inputs...");
+ for (String key : inputs.keySet()) {
+ logger.debug("key={}", key);
+ boolean alias = false;
+ String realName = null;
+ if (!params.containsKey(key)) {
+ logger.debug("{} is not a parameter in the template! - check for an alias", key);
+ // add check here for an alias
+ if (!paramAliases.containsKey(key)) {
+ logger.debug("The parameter {} is in the inputs, but it's not a parameter for this template - omit",
+ key);
+ continue;
+ } else {
+ alias = true;
+ realName = paramAliases.get(key).getParamName();
+ logger.debug("FOUND AN ALIAS! Will use {} in lieu of give key/alias {}", realName, key);
+ }
+ }
+ String type = params.get(key).getParamType();
+ if (type == null || "".equals(type)) {
+ logger.debug("**PARAM_TYPE is null/empty for {}, will default to string", key);
+ type = "string";
+ }
+ logger.debug("Parameter: {} is of type {}", key, type);
+ if ("string".equalsIgnoreCase(type)) {
+ // Easiest!
+ String str = inputs.get(key) != null ? inputs.get(key).toString() : null;
+ if (alias)
+ newInputs.put(realName, str);
+ else
+ newInputs.put(key, str);
+ } else if ("number".equalsIgnoreCase(type)) {
+ String integerString = inputs.get(key) != null ? inputs.get(key).toString() : null;
+ Integer anInteger = null;
+ try {
+ anInteger = Integer.parseInt(integerString);
+ } catch (Exception e) {
+ logger.debug("Unable to convert {} to an integer!!", integerString, e);
+ anInteger = null;
+ }
+ if (anInteger != null) {
+ if (alias)
+ newInputs.put(realName, anInteger);
+ else
+ newInputs.put(key, anInteger);
+ } else {
+ if (alias)
+ newInputs.put(realName, integerString);
+ else
+ newInputs.put(key, integerString);
+ }
+ } else if ("json".equalsIgnoreCase(type)) {
+ Object jsonObj = inputs.get(key);
+ Object json;
+ try {
+ if (jsonObj instanceof String) {
+ json = JSON_MAPPER.readTree(jsonObj.toString());
+ } else {
+ // will already marshal to json without intervention
+ json = jsonObj;
+ }
+ } catch (IOException e) {
+ logger.error("failed to map to json, directly converting to string instead", e);
+ json = jsonObj.toString();
+ }
+ if (alias)
+ newInputs.put(realName, json);
+ else
+ newInputs.put(key, json);
+ } else if ("comma_delimited_list".equalsIgnoreCase(type)) {
+ String commaSeparated = inputs.get(key) != null ? inputs.get(key).toString() : null;
+ try {
+ List<String> anArrayList = this.convertCdlToArrayList(commaSeparated);
+ if (alias)
+ newInputs.put(realName, anArrayList);
+ else
+ newInputs.put(key, anArrayList);
+ } catch (Exception e) {
+ logger.debug("Unable to convert {} to an ArrayList!!", commaSeparated, e);
+ if (alias)
+ newInputs.put(realName, commaSeparated);
+ else
+ newInputs.put(key, commaSeparated);
+ }
+ } else if ("boolean".equalsIgnoreCase(type)) {
+ String booleanString = inputs.get(key) != null ? inputs.get(key).toString() : null;
+ Boolean aBool = Boolean.valueOf(booleanString);
+ if (alias)
+ newInputs.put(realName, aBool);
+ else
+ newInputs.put(key, aBool);
+ } else {
+ // it's null or something undefined - just add it back as a String
+ String str = inputs.get(key).toString();
+ if (alias)
+ newInputs.put(realName, str);
+ else
+ newInputs.put(key, str);
+ }
+ }
+ return newInputs;
+ }
+
+ /*
+ * This helpful method added for Valet
+ */
+ public String getCloudSiteKeystoneUrl(String cloudSiteId) throws MsoCloudSiteNotFound {
+ String keystone_url = null;
+ try {
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudIdentity cloudIdentity = cloudSite.getIdentityService();
+ keystone_url = cloudIdentity.getIdentityUrl();
+ } catch (Exception e) {
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- }
- String type = params.get(key).getParamType();
- if (type == null || "".equals(type)) {
- logger.debug("**PARAM_TYPE is null/empty for {}, will default to string", key);
- type = "string";
- }
- logger.debug("Parameter: {} is of type {}", key, type);
- if ("string".equalsIgnoreCase(type)) {
- // Easiest!
- String str = inputs.get(key) != null ? inputs.get(key).toString() : null;
- if (alias)
- newInputs.put(realName, str);
- else
- newInputs.put(key, str);
- } else if ("number".equalsIgnoreCase(type)) {
- String integerString = inputs.get(key) != null ? inputs.get(key).toString() : null;
- Integer anInteger = null;
- try {
- anInteger = Integer.parseInt(integerString);
- } catch (Exception e) {
- logger.debug("Unable to convert {} to an integer!!", integerString, e);
- anInteger = null;
- }
- if (anInteger != null) {
- if (alias)
- newInputs.put(realName, anInteger);
- else
- newInputs.put(key, anInteger);
- }
- else {
- if (alias)
- newInputs.put(realName, integerString);
- else
- newInputs.put(key, integerString);
- }
- } else if ("json".equalsIgnoreCase(type)) {
- Object jsonObj = inputs.get(key);
- Object json;
- try {
- if (jsonObj instanceof String) {
- json = JSON_MAPPER.readTree(jsonObj.toString());
- } else {
- //will already marshal to json without intervention
- json = jsonObj;
- }
- } catch (IOException e) {
- logger.error("failed to map to json, directly converting to string instead", e);
- json = jsonObj.toString();
- }
- if (alias)
- newInputs.put(realName, json);
- else
- newInputs.put(key, json);
- } else if ("comma_delimited_list".equalsIgnoreCase(type)) {
- String commaSeparated = inputs.get(key) != null ? inputs.get(key).toString() : null;
- try {
- List<String> anArrayList = this.convertCdlToArrayList(commaSeparated);
- if (alias)
- newInputs.put(realName, anArrayList);
- else
- newInputs.put(key, anArrayList);
- } catch (Exception e) {
- logger.debug("Unable to convert {} to an ArrayList!!", commaSeparated, e);
- if (alias)
- newInputs.put(realName, commaSeparated);
- else
- newInputs.put(key, commaSeparated);
- }
- } else if ("boolean".equalsIgnoreCase(type)) {
- String booleanString = inputs.get(key) != null ? inputs.get(key).toString() : null;
- Boolean aBool = Boolean.valueOf(booleanString);
- if (alias)
- newInputs.put(realName, aBool);
- else
- newInputs.put(key, aBool);
- } else {
- // it's null or something undefined - just add it back as a String
- String str = inputs.get(key).toString();
- if (alias)
- newInputs.put(realName, str);
- else
- newInputs.put(key, str);
- }
- }
- return newInputs;
- }
-
- /*
- * This helpful method added for Valet
- */
- public String getCloudSiteKeystoneUrl(String cloudSiteId) throws MsoCloudSiteNotFound {
- String keystone_url = null;
- try {
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
- CloudIdentity cloudIdentity = cloudSite.getIdentityService();
- keystone_url = cloudIdentity.getIdentityUrl();
- } catch (Exception e) {
- throw new MsoCloudSiteNotFound(cloudSiteId);
- }
- if (keystone_url == null || keystone_url.isEmpty()) {
- throw new MsoCloudSiteNotFound(cloudSiteId);
- }
- return keystone_url;
- }
-
- /*
- * Create a string suitable for being dumped to a debug log that creates a
- * pseudo-JSON request dumping what's being sent to Openstack API in the create or update request
- */
-
- private String printStackRequest(String tenantId,
- Map<String, Object> heatFiles,
- Map<String, Object> nestedTemplates,
- String environment,
- Map<String, Object> inputs,
- String vfModuleName,
- String template,
- int timeoutMinutes,
- boolean backout,
- String cloudSiteId) {
- StringBuilder sb = new StringBuilder();
- sb.append("CREATE STACK REQUEST (formatted for readability)\n");
- sb.append("tenant=" + tenantId + ", cloud=" + cloudSiteId);
- sb.append("{\n");
- sb.append(" \"stack_name\": \"" + vfModuleName + "\",\n");
- sb.append(" \"disable_rollback\": " + backout + ",\n");
- sb.append(" \"timeout_mins\": " + timeoutMinutes + ",\n");
- sb.append(" \"template\": {\n");
- sb.append(template);
- sb.append(" },\n");
- sb.append(" \"environment\": {\n");
- if (environment == null)
- sb.append("<none>");
- else
- sb.append(environment);
- sb.append(" },\n");
- sb.append(" \"files\": {\n");
- int filesCounter = 0;
- if (heatFiles != null) {
- for (String key : heatFiles.keySet()) {
- filesCounter++;
- if (filesCounter > 1) {
- sb.append(",\n");
- }
- sb.append(" \"" + key + "\": {\n");
- sb.append(heatFiles.get(key).toString() + "\n }");
- }
- }
- if (nestedTemplates != null) {
- for (String key : nestedTemplates.keySet()) {
- filesCounter++;
- if (filesCounter > 1) {
- sb.append(",\n");
- }
- sb.append(" \"" + key + "\": {\n");
- sb.append(nestedTemplates.get(key).toString() + "\n }");
- }
- }
- sb.append("\n },\n");
- sb.append(" \"parameters\": {\n");
- int paramCounter = 0;
- for (String name : inputs.keySet()) {
- paramCounter++;
- if (paramCounter > 1) {
- sb.append(",\n");
- }
- Object o = inputs.get(name);
- if (o instanceof java.lang.String) {
- sb.append(" \"" + name + "\": \"" + inputs.get(name).toString() + "\"");
- } else if (o instanceof Integer) {
- sb.append(" \"" + name + "\": " + inputs.get(name).toString() );
- } else if (o instanceof ArrayList) {
- sb.append(" \"" + name + "\": " + inputs.get(name).toString() );
- } else if (o instanceof Boolean) {
- sb.append(" \"" + name + "\": " + inputs.get(name).toString() );
- } else {
- sb.append(" \"" + name + "\": " + "\"(there was an issue trying to dump this value...)\"" );
- }
- }
- sb.append("\n }\n}\n");
-
- return sb.toString();
- }
-
- /*******************************************************************************
+ if (keystone_url == null || keystone_url.isEmpty()) {
+ throw new MsoCloudSiteNotFound(cloudSiteId);
+ }
+ return keystone_url;
+ }
+
+ /*
+ * Create a string suitable for being dumped to a debug log that creates a pseudo-JSON request dumping what's being
+ * sent to Openstack API in the create or update request
+ */
+
+ private String printStackRequest(String tenantId, Map<String, Object> heatFiles,
+ Map<String, Object> nestedTemplates, String environment, Map<String, Object> inputs, String vfModuleName,
+ String template, int timeoutMinutes, boolean backout, String cloudSiteId) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("CREATE STACK REQUEST (formatted for readability)\n");
+ sb.append("tenant=" + tenantId + ", cloud=" + cloudSiteId);
+ sb.append("{\n");
+ sb.append(" \"stack_name\": \"" + vfModuleName + "\",\n");
+ sb.append(" \"disable_rollback\": " + backout + ",\n");
+ sb.append(" \"timeout_mins\": " + timeoutMinutes + ",\n");
+ sb.append(" \"template\": {\n");
+ sb.append(template);
+ sb.append(" },\n");
+ sb.append(" \"environment\": {\n");
+ if (environment == null)
+ sb.append("<none>");
+ else
+ sb.append(environment);
+ sb.append(" },\n");
+ sb.append(" \"files\": {\n");
+ int filesCounter = 0;
+ if (heatFiles != null) {
+ for (String key : heatFiles.keySet()) {
+ filesCounter++;
+ if (filesCounter > 1) {
+ sb.append(",\n");
+ }
+ sb.append(" \"" + key + "\": {\n");
+ sb.append(heatFiles.get(key).toString() + "\n }");
+ }
+ }
+ if (nestedTemplates != null) {
+ for (String key : nestedTemplates.keySet()) {
+ filesCounter++;
+ if (filesCounter > 1) {
+ sb.append(",\n");
+ }
+ sb.append(" \"" + key + "\": {\n");
+ sb.append(nestedTemplates.get(key).toString() + "\n }");
+ }
+ }
+ sb.append("\n },\n");
+ sb.append(" \"parameters\": {\n");
+ int paramCounter = 0;
+ for (String name : inputs.keySet()) {
+ paramCounter++;
+ if (paramCounter > 1) {
+ sb.append(",\n");
+ }
+ Object o = inputs.get(name);
+ if (o instanceof java.lang.String) {
+ sb.append(" \"" + name + "\": \"" + inputs.get(name).toString() + "\"");
+ } else if (o instanceof Integer) {
+ sb.append(" \"" + name + "\": " + inputs.get(name).toString());
+ } else if (o instanceof ArrayList) {
+ sb.append(" \"" + name + "\": " + inputs.get(name).toString());
+ } else if (o instanceof Boolean) {
+ sb.append(" \"" + name + "\": " + inputs.get(name).toString());
+ } else {
+ sb.append(" \"" + name + "\": " + "\"(there was an issue trying to dump this value...)\"");
+ }
+ }
+ sb.append("\n }\n}\n");
+
+ return sb.toString();
+ }
+
+ /*******************************************************************************
*
* Methods (and associated utilities) to implement the VduPlugin interface
*
@@ -1496,61 +1417,47 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
/**
* VduPlugin interface for instantiate function.
*
- * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
- * and then invoke the existing function.
+ * Translate the VduPlugin parameters to the corresponding 'createStack' parameters, and then invoke the existing
+ * function.
*/
@Override
- public VduInstance instantiateVdu (
- CloudInfo cloudInfo,
- String instanceName,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException
- {
- String cloudSiteId = cloudInfo.getCloudSiteId();
- String tenantId = cloudInfo.getTenantId();
-
- // Translate the VDU ModelInformation structure to that which is needed for
- // creating the Heat stack. Loop through the artifacts, looking specifically
- // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
- // be attached as a FILE.
- String heatTemplate = null;
- Map<String,Object> nestedTemplates = new HashMap<>();
- Map<String,Object> files = new HashMap<>();
- String heatEnvironment = null;
-
- for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
- if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
- heatTemplate = new String(vduArtifact.getContent());
- }
- else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
- nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
- }
- else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
- heatEnvironment = new String(vduArtifact.getContent());
- }
- }
-
- try {
- StackInfo stackInfo = createStack (cloudSiteId,
- tenantId,
- instanceName,
- heatTemplate,
- inputs,
- true, // poll for completion
- vduModel.getTimeoutMinutes(),
- heatEnvironment,
- nestedTemplates,
- files,
- rollbackOnFailure);
-
- // Populate a vduInstance from the StackInfo
- return stackInfoToVduInstance(stackInfo);
- }
- catch (Exception e) {
- throw new VduException ("MsoHeatUtils (instantiateVDU): createStack Exception", e);
- }
+ public VduInstance instantiateVdu(CloudInfo cloudInfo, String instanceName, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException {
+ String cloudSiteId = cloudInfo.getCloudSiteId();
+ String cloudOwner = cloudInfo.getCloudOwner();
+ String tenantId = cloudInfo.getTenantId();
+
+ // Translate the VDU ModelInformation structure to that which is needed for
+ // creating the Heat stack. Loop through the artifacts, looking specifically
+ // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
+ // be attached as a FILE.
+ String heatTemplate = null;
+ Map<String, Object> nestedTemplates = new HashMap<>();
+ Map<String, Object> files = new HashMap<>();
+ String heatEnvironment = null;
+
+ for (VduArtifact vduArtifact : vduModel.getArtifacts()) {
+ if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
+ heatTemplate = new String(vduArtifact.getContent());
+ } else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
+ nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
+ } else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
+ heatEnvironment = new String(vduArtifact.getContent());
+ }
+ }
+
+ try {
+ StackInfo stackInfo =
+ createStack(cloudSiteId, cloudOwner, tenantId, instanceName, vduModel, heatTemplate, inputs, true, // poll
+ // for
+ // completion
+ vduModel.getTimeoutMinutes(), heatEnvironment, nestedTemplates, files, rollbackOnFailure);
+
+ // Populate a vduInstance from the StackInfo
+ return stackInfoToVduInstance(stackInfo);
+ } catch (Exception e) {
+ throw new VduException("MsoHeatUtils (instantiateVDU): createStack Exception", e);
+ }
}
@@ -1558,21 +1465,19 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
* VduPlugin interface for query function.
*/
@Override
- public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
- throws VduException
- {
- String cloudSiteId = cloudInfo.getCloudSiteId();
- String tenantId = cloudInfo.getTenantId();
-
- try {
- // Query the Cloudify Deployment object and populate a VduInstance
- StackInfo stackInfo = queryStack (cloudSiteId, tenantId, instanceId);
-
- return stackInfoToVduInstance(stackInfo);
- }
- catch (Exception e) {
- throw new VduException ("MsoHeatUtile (queryVdu): queryStack Exception ", e);
- }
+ public VduInstance queryVdu(CloudInfo cloudInfo, String instanceId) throws VduException {
+ String cloudSiteId = cloudInfo.getCloudSiteId();
+ String cloudOwner = cloudInfo.getCloudOwner();
+ String tenantId = cloudInfo.getTenantId();
+
+ try {
+ // Query the Cloudify Deployment object and populate a VduInstance
+ StackInfo stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
+
+ return stackInfoToVduInstance(stackInfo);
+ } catch (Exception e) {
+ throw new VduException("MsoHeatUtile (queryVdu): queryStack Exception ", e);
+ }
}
@@ -1580,134 +1485,120 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
* VduPlugin interface for delete function.
*/
@Override
- public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
- throws VduException
- {
- String cloudSiteId = cloudInfo.getCloudSiteId();
- String tenantId = cloudInfo.getTenantId();
-
- try {
- // Delete the Heat stack
- StackInfo stackInfo = deleteStack (tenantId, cloudSiteId, instanceId, true);
-
- // Populate a VduInstance based on the deleted Cloudify Deployment object
- VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
-
- // Override return state to DELETED (HeatUtils sets to NOTFOUND)
- vduInstance.getStatus().setState(VduStateType.DELETED);
-
- return vduInstance;
- }
- catch (Exception e) {
- throw new VduException ("Delete VDU Exception", e);
- }
+ public VduInstance deleteVdu(CloudInfo cloudInfo, String instanceId, int timeoutMinutes) throws VduException {
+ String cloudSiteId = cloudInfo.getCloudSiteId();
+ String cloudOwner = cloudInfo.getCloudOwner();
+ String tenantId = cloudInfo.getTenantId();
+
+ try {
+ // Delete the Heat stack
+ StackInfo stackInfo = deleteStack(tenantId, cloudOwner, cloudSiteId, instanceId, true);
+
+ // Populate a VduInstance based on the deleted Cloudify Deployment object
+ VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
+
+ // Override return state to DELETED (HeatUtils sets to NOTFOUND)
+ vduInstance.getStatus().setState(VduStateType.DELETED);
+
+ return vduInstance;
+ } catch (Exception e) {
+ throw new VduException("Delete VDU Exception", e);
+ }
}
/**
* VduPlugin interface for update function.
*
- * Update is currently not supported in the MsoHeatUtils implementation of VduPlugin.
- * Just return a VduException.
+ * Update is currently not supported in the MsoHeatUtils implementation of VduPlugin. Just return a VduException.
*
*/
@Override
- public VduInstance updateVdu (
- CloudInfo cloudInfo,
- String instanceId,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException
- {
- throw new VduException ("MsoHeatUtils: updateVdu interface not supported");
+ public VduInstance updateVdu(CloudInfo cloudInfo, String instanceId, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException {
+ throw new VduException("MsoHeatUtils: updateVdu interface not supported");
}
/*
* Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
*/
- protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
- {
- VduInstance vduInstance = new VduInstance();
+ protected VduInstance stackInfoToVduInstance(StackInfo stackInfo) {
+ VduInstance vduInstance = new VduInstance();
+
+ // The full canonical name as the instance UUID
+ vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
+ vduInstance.setVduInstanceName(stackInfo.getName());
+
+ // Copy inputs and outputs
+ vduInstance.setInputs(stackInfo.getParameters());
+ vduInstance.setOutputs(stackInfo.getOutputs());
+
+ // Translate the status elements
+ vduInstance.setStatus(stackStatusToVduStatus(stackInfo));
- // The full canonical name as the instance UUID
- vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
- vduInstance.setVduInstanceName(stackInfo.getName());
+ return vduInstance;
+ }
- // Copy inputs and outputs
- vduInstance.setInputs(stackInfo.getParameters());
- vduInstance.setOutputs(stackInfo.getOutputs());
+ private VduStatus stackStatusToVduStatus(StackInfo stackInfo) {
+ VduStatus vduStatus = new VduStatus();
+
+ // Map the status fields to more generic VduStatus.
+ // There are lots of HeatStatus values, so this is a bit long...
+ HeatStatus heatStatus = stackInfo.getStatus();
+ String statusMessage = stackInfo.getStatusMessage();
+
+ if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
+ vduStatus.setState(VduStateType.INSTANTIATING);
+ vduStatus.setLastAction((new PluginAction("create", "in_progress", statusMessage)));
+ } else if (heatStatus == HeatStatus.NOTFOUND) {
+ vduStatus.setState(VduStateType.NOTFOUND);
+ } else if (heatStatus == HeatStatus.CREATED) {
+ vduStatus.setState(VduStateType.INSTANTIATED);
+ vduStatus.setLastAction((new PluginAction("create", "complete", statusMessage)));
+ } else if (heatStatus == HeatStatus.UPDATED) {
+ vduStatus.setState(VduStateType.INSTANTIATED);
+ vduStatus.setLastAction((new PluginAction("update", "complete", statusMessage)));
+ } else if (heatStatus == HeatStatus.UPDATING) {
+ vduStatus.setState(VduStateType.UPDATING);
+ vduStatus.setLastAction((new PluginAction("update", "in_progress", statusMessage)));
+ } else if (heatStatus == HeatStatus.DELETING) {
+ vduStatus.setState(VduStateType.DELETING);
+ vduStatus.setLastAction((new PluginAction("delete", "in_progress", statusMessage)));
+ } else if (heatStatus == HeatStatus.FAILED) {
+ vduStatus.setState(VduStateType.FAILED);
+ vduStatus.setErrorMessage(stackInfo.getStatusMessage());
+ } else {
+ vduStatus.setState(VduStateType.UNKNOWN);
+ }
- // Translate the status elements
- vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
+ return vduStatus;
+ }
- return vduInstance;
+ public Resources queryStackResources(String cloudSiteId, String tenantId, String stackName, int nestedDepth)
+ throws MsoException {
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Heat heatClient = getHeatClient(cloudSite, tenantId);
+ OpenStackRequest<Resources> request =
+ heatClient.getResources().listResources(stackName).queryParam("nested_depth", nestedDepth);
+ return executeAndRecordOpenstackRequest(request);
}
- private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
- {
- VduStatus vduStatus = new VduStatus();
-
- // Map the status fields to more generic VduStatus.
- // There are lots of HeatStatus values, so this is a bit long...
- HeatStatus heatStatus = stackInfo.getStatus();
- String statusMessage = stackInfo.getStatusMessage();
-
- if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
- vduStatus.setState(VduStateType.INSTANTIATING);
- vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
- }
- else if (heatStatus == HeatStatus.NOTFOUND) {
- vduStatus.setState(VduStateType.NOTFOUND);
- }
- else if (heatStatus == HeatStatus.CREATED) {
- vduStatus.setState(VduStateType.INSTANTIATED);
- vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
- }
- else if (heatStatus == HeatStatus.UPDATED) {
- vduStatus.setState(VduStateType.INSTANTIATED);
- vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
- }
- else if (heatStatus == HeatStatus.UPDATING) {
- vduStatus.setState(VduStateType.UPDATING);
- vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
- }
- else if (heatStatus == HeatStatus.DELETING) {
- vduStatus.setState(VduStateType.DELETING);
- vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
- }
- else if (heatStatus == HeatStatus.FAILED) {
- vduStatus.setState(VduStateType.FAILED);
- vduStatus.setErrorMessage(stackInfo.getStatusMessage());
- } else {
- vduStatus.setState(VduStateType.UNKNOWN);
- }
-
- return vduStatus;
+ public <R> R executeHeatClientRequest(String url, String cloudSiteId, String tenantId, Class<R> returnType)
+ throws MsoException {
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Heat heatClient = getHeatClient(cloudSite, tenantId);
+ OpenStackRequest<R> request = heatClient.get(url, returnType);
+ return executeAndRecordOpenstackRequest(request);
}
-
- public Resources queryStackResources(String cloudSiteId, String tenantId, String stackName) throws MsoException {
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId)
- .orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
- Heat heatClient = getHeatClient(cloudSite, tenantId);
- OpenStackRequest<Resources> request = heatClient.getResources().listResources(stackName);
- return executeAndRecordOpenstackRequest(request);
- }
-
- public <R> R executeHeatClientRequest(String url, String cloudSiteId, String tenantId, Class<R> returnType) throws MsoException {
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId)
- .orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
- Heat heatClient = getHeatClient(cloudSite, tenantId);
- OpenStackRequest<R> request = heatClient.get(url, returnType);
- return executeAndRecordOpenstackRequest(request);
- }
protected void sleep(long time) {
- try {
+ try {
Thread.sleep(time);
} catch (InterruptedException e) {
- logger.debug ("Thread interrupted while sleeping", e);
+ logger.debug("Thread interrupted while sleeping", e);
Thread.currentThread().interrupt();
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java
index d93ce9e1e1..1bf780f6d3 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java
@@ -10,9 +10,9 @@
* 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.
@@ -67,89 +67,46 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
* Keep these methods around for backward compatibility
*/
- public StackInfo updateStack (String cloudSiteId,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, Object> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes) throws MsoException {
+ public StackInfo updateStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, Object> stackInputs, boolean pollForCompletion, int timeoutMinutes)
+ throws MsoException {
// Keeping this method to allow compatibility with no environment or files variable sent. In this case,
// simply return the new method with the environment variable set to null.
- return this.updateStack (cloudSiteId,
- tenantId,
- stackName,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- null,
- null,
- null);
+ return this.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, null, null, null);
}
- public StackInfo updateStack (String cloudSiteId,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, Object> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment) throws MsoException {
+ public StackInfo updateStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, Object> stackInputs, boolean pollForCompletion, int timeoutMinutes,
+ String environment) throws MsoException {
// Keeping this method to allow compatibility with no environment variable sent. In this case,
// simply return the new method with the files variable set to null.
- return this.updateStack (cloudSiteId,
- tenantId,
- stackName,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- environment,
- null,
- null);
+ return this.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, environment, null, null);
}
- public StackInfo updateStack (String cloudSiteId,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, Object> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files) throws MsoException {
- return this.updateStack (cloudSiteId,
- tenantId,
- stackName,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- environment,
- files,
- null);
+ public StackInfo updateStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, Object> stackInputs, boolean pollForCompletion, int timeoutMinutes,
+ String environment, Map<String, Object> files) throws MsoException {
+ return this.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, environment, files, null);
}
/**
- * Update a Stack in the specified cloud location and tenant. The Heat template
- * and parameter map are passed in as arguments, along with the cloud access credentials.
- * It is expected that parameters have been validated and contain at minimum the required
- * parameters for the given template with no extra (undefined) parameters..
+ * Update a Stack in the specified cloud location and tenant. The Heat template and parameter map are passed in as
+ * arguments, along with the cloud access credentials. It is expected that parameters have been validated and
+ * contain at minimum the required parameters for the given template with no extra (undefined) parameters..
*
- * The Stack name supplied by the caller must be unique in the scope of this tenant.
- * However, it should also be globally unique, as it will be the identifier for the
- * resource going forward in Inventory. This latter is managed by the higher levels
- * invoking this function.
+ * The Stack name supplied by the caller must be unique in the scope of this tenant. However, it should also be
+ * globally unique, as it will be the identifier for the resource going forward in Inventory. This latter is managed
+ * by the higher levels invoking this function.
*
- * The caller may choose to let this function poll Openstack for completion of the
- * stack creation, or may handle polling itself via separate calls to query the status.
- * In either case, a StackInfo object will be returned containing the current status.
- * When polling is enabled, a status of CREATED is expected. When not polling, a
+ * The caller may choose to let this function poll Openstack for completion of the stack creation, or may handle
+ * polling itself via separate calls to query the status. In either case, a StackInfo object will be returned
+ * containing the current status. When polling is enabled, a status of CREATED is expected. When not polling, a
* status of BUILDING is expected.
*
- * An error will be thrown if the requested Stack already exists in the specified
- * Tenant and Cloud.
+ * An error will be thrown if the requested Stack already exists in the specified Tenant and Cloud.
*
* @param tenantId The Openstack ID of the tenant in which to create the Stack
* @param cloudSiteId The cloud identifier (may be a region) in which to create the tenant.
@@ -164,104 +121,98 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
* @throws MsoException Thrown if the Openstack API call returns an exception.
*/
- public StackInfo updateStack (String cloudSiteId,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, Object> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files,
- Map <String, Object> heatFiles) throws MsoException {
+ public StackInfo updateStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, Object> stackInputs, boolean pollForCompletion, int timeoutMinutes,
+ String environment, Map<String, Object> files, Map<String, Object> heatFiles) throws MsoException {
boolean heatEnvtVariable = true;
- if (environment == null || "".equalsIgnoreCase (environment.trim ())) {
+ if (environment == null || "".equalsIgnoreCase(environment.trim())) {
heatEnvtVariable = false;
}
boolean haveFiles = true;
- if (files == null || files.isEmpty ()) {
+ if (files == null || files.isEmpty()) {
haveFiles = false;
}
boolean haveHeatFiles = true;
- if (heatFiles == null || heatFiles.isEmpty ()) {
+ if (heatFiles == null || heatFiles.isEmpty()) {
haveHeatFiles = false;
}
// Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
// Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
// This could throw MsoTenantNotFound or MsoOpenstackException (both propagated)
- Heat heatClient = getHeatClient (cloudSite, tenantId);
+ Heat heatClient = getHeatClient(cloudSite, tenantId);
// Perform a query first to get the current status
- Stack heatStack = queryHeatStack (heatClient, stackName);
- if (heatStack == null || "DELETE_COMPLETE".equals (heatStack.getStackStatus ())) {
+ Stack heatStack = queryHeatStack(heatClient, stackName);
+ if (heatStack == null || "DELETE_COMPLETE".equals(heatStack.getStackStatus())) {
// Not found. Return a StackInfo with status NOTFOUND
- throw new MsoStackNotFound (stackName, tenantId, cloudSiteId);
+ throw new MsoStackNotFound(stackName, tenantId, cloudSiteId);
}
// Use canonical name "<stack name>/<stack-id>" to update the stack.
// Otherwise, update by name returns a 302 redirect.
// NOTE: This is specific to the v1 Orchestration API.
- String canonicalName = heatStack.getStackName () + "/" + heatStack.getId ();
+ String canonicalName = heatStack.getStackName() + "/" + heatStack.getId();
- logger.debug ("Ready to Update Stack ({}) with input params: {}", canonicalName, stackInputs);
- //force entire stackInput object to generic Map<String, Object> for openstack compatibility
- ObjectMapper mapper = new ObjectMapper();
- Map<String, Object> normalized = new HashMap<>();
- try {
- normalized = mapper.readValue(mapper.writeValueAsString(stackInputs), new TypeReference<HashMap<String,Object>>() {});
- } catch (IOException e1) {
- logger.debug("could not map json", e1);
- }
+ logger.debug("Ready to Update Stack ({}) with input params: {}", canonicalName, stackInputs);
+ // force entire stackInput object to generic Map<String, Object> for openstack compatibility
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String, Object> normalized = new HashMap<>();
+ try {
+ normalized = mapper.readValue(mapper.writeValueAsString(stackInputs),
+ new TypeReference<HashMap<String, Object>>() {});
+ } catch (IOException e1) {
+ logger.debug("could not map json", e1);
+ }
// Build up the stack update parameters
// Disable auto-rollback, because error reason is lost. Always rollback in the code.
- UpdateStackParam stack = new UpdateStackParam ();
- stack.setTimeoutMinutes (timeoutMinutes);
- stack.setParameters (normalized);
- stack.setTemplate (heatTemplate);
- stack.setDisableRollback (true);
+ UpdateStackParam stack = new UpdateStackParam();
+ stack.setTimeoutMinutes(timeoutMinutes);
+ stack.setParameters(normalized);
+ stack.setTemplate(heatTemplate);
+ stack.setDisableRollback(true);
// TJM add envt to stack
if (heatEnvtVariable) {
- stack.setEnvironment (environment);
+ stack.setEnvironment(environment);
}
// Handle nested templates & get_files here. if we have both - must combine
// and then add to stack (both are part of "files:" being added to stack)
if (haveFiles && haveHeatFiles) {
// Let's do this here - not in the bean
- logger.debug ("Found files AND heatFiles - combine and add!");
- Map <String, Object> combinedFiles = new HashMap<>();
- for (String keyString : files.keySet ()) {
- combinedFiles.put (keyString, files.get (keyString));
+ logger.debug("Found files AND heatFiles - combine and add!");
+ Map<String, Object> combinedFiles = new HashMap<>();
+ for (String keyString : files.keySet()) {
+ combinedFiles.put(keyString, files.get(keyString));
}
- for (String keyString : heatFiles.keySet ()) {
- combinedFiles.put (keyString, heatFiles.get (keyString));
+ for (String keyString : heatFiles.keySet()) {
+ combinedFiles.put(keyString, heatFiles.get(keyString));
}
- stack.setFiles (combinedFiles);
+ stack.setFiles(combinedFiles);
} else {
// Handle case where we have one or neither
if (haveFiles) {
- stack.setFiles (files);
+ stack.setFiles(files);
}
if (haveHeatFiles) {
// setFiles method modified to handle adding a map.
- stack.setFiles (heatFiles);
+ stack.setFiles(heatFiles);
}
}
try {
// Execute the actual Openstack command to update the Heat stack
- OpenStackRequest <Void> request = heatClient.getStacks ().update (canonicalName, stack);
- executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Void> request = heatClient.getStacks().update(canonicalName, stack);
+ executeAndRecordOpenstackRequest(request);
} catch (OpenStackBaseException e) {
// Since this came on the 'Update Stack' command, nothing was changed
// in the cloud. Rethrow the error as an MSO exception.
- throw heatExceptionToMsoException (e, UPDATE_STACK);
+ throw heatExceptionToMsoException(e, UPDATE_STACK);
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, UPDATE_STACK);
+ throw runtimeExceptionToMsoException(e, UPDATE_STACK);
}
// If client has requested a final response, poll for stack completion
@@ -270,36 +221,37 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
// Set a time limit on overall polling.
// Use the resource (template) timeout for Openstack (expressed in minutes)
// and add one poll interval to give Openstack a chance to fail on its own.
- int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
+ int createPollInterval =
+ Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
boolean loopAgain = true;
while (loopAgain) {
try {
- updateStack = queryHeatStack (heatClient, canonicalName);
+ updateStack = queryHeatStack(heatClient, canonicalName);
logger.debug("{} ({}) ", updateStack.getStackStatus(), canonicalName);
try {
- logger
- .debug("Current stack {}" + this.getOutputsAsStringBuilderWithUpdate(heatStack).toString());
+ logger.debug(
+ "Current stack {}" + this.getOutputsAsStringBuilderWithUpdate(heatStack).toString());
} catch (Exception e) {
logger.debug("an error occurred trying to print out the current outputs of the stack", e);
}
- if ("UPDATE_IN_PROGRESS".equals (updateStack.getStackStatus ())) {
+ if ("UPDATE_IN_PROGRESS".equals(updateStack.getStackStatus())) {
// Stack update is still running.
// Sleep and try again unless timeout has been reached
if (pollTimeout <= 0) {
// Note that this should not occur, since there is a timeout specified
// in the Openstack call.
logger.error(
- "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Update stack timeout",
- MessageEnum.RA_UPDATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
- updateStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
+ "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Update stack timeout",
+ MessageEnum.RA_UPDATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
+ updateStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
loopAgain = false;
} else {
try {
- Thread.sleep (createPollInterval * 1000L);
+ Thread.sleep(createPollInterval * 1000L);
} catch (InterruptedException e) {
// If we are interrupted, we should stop ASAP.
loopAgain = false;
@@ -316,34 +268,33 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
// Cannot query the stack. Something is wrong.
// TODO: No way to roll back the stack at this point. What to do?
- e.addContext (UPDATE_STACK);
+ e.addContext(UPDATE_STACK);
throw e;
}
}
- if (!"UPDATE_COMPLETE".equals (updateStack.getStackStatus ())) {
+ if (!"UPDATE_COMPLETE".equals(updateStack.getStackStatus())) {
logger.error("{} Stack status: {} Stack status reason: {} {} Update Stack error",
- MessageEnum.RA_UPDATE_STACK_ERR, updateStack.getStackStatus(), updateStack.getStackStatusReason(),
- ErrorCode.DataError.getValue());
+ MessageEnum.RA_UPDATE_STACK_ERR, updateStack.getStackStatus(),
+ updateStack.getStackStatusReason(), ErrorCode.DataError.getValue());
// TODO: No way to roll back the stack at this point. What to do?
// Throw a 'special case' of MsoOpenstackException to report the Heat status
MsoOpenstackException me = null;
- if ("UPDATE_IN_PROGRESS".equals (updateStack.getStackStatus ())) {
- me = new MsoOpenstackException (0, "", "Stack Update Timeout");
+ if ("UPDATE_IN_PROGRESS".equals(updateStack.getStackStatus())) {
+ me = new MsoOpenstackException(0, "", "Stack Update Timeout");
} else {
- String error = "Stack error (" + updateStack.getStackStatus ()
- + "): "
- + updateStack.getStackStatusReason ();
- me = new MsoOpenstackException (0, "", error);
+ String error =
+ "Stack error (" + updateStack.getStackStatus() + "): " + updateStack.getStackStatusReason();
+ me = new MsoOpenstackException(0, "", error);
}
- me.addContext (UPDATE_STACK);
+ me.addContext(UPDATE_STACK);
throw me;
}
} else {
// Return the current status.
- updateStack = queryHeatStack (heatClient, canonicalName);
+ updateStack = queryHeatStack(heatClient, canonicalName);
if (updateStack != null) {
logger.debug("UpdateStack, status = {}", updateStack.getStackStatus());
} else {
@@ -353,93 +304,92 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
return new StackInfoMapper(updateStack).map();
}
- private StringBuilder getOutputsAsStringBuilderWithUpdate(Stack heatStack) {
- // This should only be used as a utility to print out the stack outputs
- // to the log
- StringBuilder sb = new StringBuilder("");
- if (heatStack == null) {
- sb.append("(heatStack is null)");
- return sb;
- }
- List<Output> outputList = heatStack.getOutputs();
- if (outputList == null || outputList.isEmpty()) {
- sb.append("(outputs is empty)");
- return sb;
- }
- Map<String, Object> outputs = new HashMap<>();
- for (Output outputItem : outputList) {
- outputs.put(outputItem.getOutputKey(), outputItem.getOutputValue());
- }
- int counter = 0;
- sb.append("OUTPUTS:\n");
- for (String key : outputs.keySet()) {
- sb.append("outputs[").append(counter++).append("]: ").append(key).append("=");
- Object obj = outputs.get(key);
- if (obj instanceof String) {
- sb.append((String) obj).append(" (a string)");
- } else if (obj instanceof JsonNode) {
- sb.append(this.convertNodeWithUpdate((JsonNode) obj)).append(" (a JsonNode)");
- } else if (obj instanceof java.util.LinkedHashMap) {
- try {
- String str = JSON_MAPPER.writeValueAsString(obj);
- sb.append(str).append(" (a java.util.LinkedHashMap)");
- } catch (Exception e) {
- logger.debug("Exception :", e);
- sb.append("(a LinkedHashMap value that would not convert nicely)");
- }
- } else if (obj instanceof Integer) {
- String str = "";
- try {
- str = obj.toString() + " (an Integer)\n";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(an Integer unable to call .toString() on)";
- }
- sb.append(str);
- } else if (obj instanceof ArrayList) {
- String str = "";
- try {
- str = obj.toString() + " (an ArrayList)";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(an ArrayList unable to call .toString() on?)";
- }
- sb.append(str);
- } else if (obj instanceof Boolean) {
- String str = "";
- try {
- str = obj.toString() + " (a Boolean)";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(an Boolean unable to call .toString() on?)";
- }
- sb.append(str);
- }
- else {
- String str = "";
- try {
- str = obj.toString() + " (unknown Object type)";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(a value unable to call .toString() on?)";
- }
- sb.append(str);
- }
- sb.append("\n");
- }
- sb.append("[END]");
- return sb;
- }
+ private StringBuilder getOutputsAsStringBuilderWithUpdate(Stack heatStack) {
+ // This should only be used as a utility to print out the stack outputs
+ // to the log
+ StringBuilder sb = new StringBuilder("");
+ if (heatStack == null) {
+ sb.append("(heatStack is null)");
+ return sb;
+ }
+ List<Output> outputList = heatStack.getOutputs();
+ if (outputList == null || outputList.isEmpty()) {
+ sb.append("(outputs is empty)");
+ return sb;
+ }
+ Map<String, Object> outputs = new HashMap<>();
+ for (Output outputItem : outputList) {
+ outputs.put(outputItem.getOutputKey(), outputItem.getOutputValue());
+ }
+ int counter = 0;
+ sb.append("OUTPUTS:\n");
+ for (String key : outputs.keySet()) {
+ sb.append("outputs[").append(counter++).append("]: ").append(key).append("=");
+ Object obj = outputs.get(key);
+ if (obj instanceof String) {
+ sb.append((String) obj).append(" (a string)");
+ } else if (obj instanceof JsonNode) {
+ sb.append(this.convertNodeWithUpdate((JsonNode) obj)).append(" (a JsonNode)");
+ } else if (obj instanceof java.util.LinkedHashMap) {
+ try {
+ String str = JSON_MAPPER.writeValueAsString(obj);
+ sb.append(str).append(" (a java.util.LinkedHashMap)");
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ sb.append("(a LinkedHashMap value that would not convert nicely)");
+ }
+ } else if (obj instanceof Integer) {
+ String str = "";
+ try {
+ str = obj.toString() + " (an Integer)\n";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(an Integer unable to call .toString() on)";
+ }
+ sb.append(str);
+ } else if (obj instanceof ArrayList) {
+ String str = "";
+ try {
+ str = obj.toString() + " (an ArrayList)";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(an ArrayList unable to call .toString() on?)";
+ }
+ sb.append(str);
+ } else if (obj instanceof Boolean) {
+ String str = "";
+ try {
+ str = obj.toString() + " (a Boolean)";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(an Boolean unable to call .toString() on?)";
+ }
+ sb.append(str);
+ } else {
+ String str = "";
+ try {
+ str = obj.toString() + " (unknown Object type)";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(a value unable to call .toString() on?)";
+ }
+ sb.append(str);
+ }
+ sb.append("\n");
+ }
+ sb.append("[END]");
+ return sb;
+ }
- private String convertNodeWithUpdate(final JsonNode node) {
- try {
- final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
- final String json = JSON_MAPPER.writeValueAsString(obj);
- return json;
- } catch (Exception e) {
- logger.debug("Error converting json to string {} ", e.getMessage(), e);
+ private String convertNodeWithUpdate(final JsonNode node) {
+ try {
+ final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
+ final String json = JSON_MAPPER.writeValueAsString(obj);
+ return json;
+ } catch (Exception e) {
+ logger.debug("Error converting json to string {} ", e.getMessage(), e);
+ }
+ return "[Error converting json to string]";
}
- return "[Error converting json to string]";
- }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java
index c96cca9f61..cfc8c23c5f 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java
@@ -62,25 +62,24 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
@Autowired
private AuthenticationMethodFactory authenticationMethodFactory;
-
- @Autowired
- private MsoHeatUtils msoHeatUtils;
-
- @Autowired
- private MsoNeutronUtils msoNeutronUtils;
-
- @Autowired
- private MsoTenantUtilsFactory tenantUtilsFactory;
+
+ @Autowired
+ private MsoHeatUtils msoHeatUtils;
+
+ @Autowired
+ private MsoNeutronUtils msoNeutronUtils;
+
+ @Autowired
+ private MsoTenantUtilsFactory tenantUtilsFactory;
+
/**
- * Create a tenant with the specified name in the given cloud. If the tenant already exists,
- * an Exception will be thrown. The MSO User will also be added to the "member" list of
- * the new tenant to perform subsequent Nova/Heat commands in the tenant. If the MSO User
- * association fails, the entire transaction will be rolled back.
+ * Create a tenant with the specified name in the given cloud. If the tenant already exists, an Exception will be
+ * thrown. The MSO User will also be added to the "member" list of the new tenant to perform subsequent Nova/Heat
+ * commands in the tenant. If the MSO User association fails, the entire transaction will be rolled back.
* <p>
- * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin
- * requests go to the centralized identity service in DCP. However, if some artifact
- * must exist in each local LCP instance as well, then it will be needed to access the
- * correct region.
+ * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin requests go to the centralized
+ * identity service in DCP. However, if some artifact must exist in each local LCP instance as well, then it will be
+ * needed to access the correct region.
* <p>
*
* @param tenantName The tenant name to create
@@ -89,44 +88,42 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
* @throws MsoTenantAlreadyExists Thrown if the requested tenant already exists
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
*/
- public String createTenant (String tenantName,
- String cloudSiteId,
- Map <String, String> metadata,
- boolean backout) throws MsoException {
+ public String createTenant(String tenantName, String cloudSiteId, Map<String, String> metadata, boolean backout)
+ throws MsoException {
// Obtain the cloud site information where we will create the tenant
Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSiteOpt.isPresent()) {
logger.error("{} MSOCloudSite {} not found {} ", MessageEnum.RA_CREATE_TENANT_ERR, cloudSiteId,
- ErrorCode.DataError.getValue());
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ ErrorCode.DataError.getValue());
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSiteOpt.get());
Tenant tenant = null;
try {
// Check if the tenant already exists
- tenant = findTenantByName (keystoneAdminClient, tenantName);
+ tenant = findTenantByName(keystoneAdminClient, tenantName);
if (tenant != null) {
// Tenant already exists. Throw an exception
logger.error("{} Tenant name {} already exists on Cloud site id {}, {}",
- MessageEnum.RA_TENANT_ALREADY_EXIST, tenantName, cloudSiteId, ErrorCode.DataError.getValue());
- throw new MsoTenantAlreadyExists (tenantName, cloudSiteId);
+ MessageEnum.RA_TENANT_ALREADY_EXIST, tenantName, cloudSiteId, ErrorCode.DataError.getValue());
+ throw new MsoTenantAlreadyExists(tenantName, cloudSiteId);
}
// Does not exist, create a new one
- tenant = new Tenant ();
- tenant.setName (tenantName);
- tenant.setDescription ("SDN Tenant (via MSO)");
- tenant.setEnabled (true);
+ tenant = new Tenant();
+ tenant.setName(tenantName);
+ tenant.setDescription("SDN Tenant (via MSO)");
+ tenant.setEnabled(true);
- OpenStackRequest <Tenant> request = keystoneAdminClient.tenants ().create (tenant);
- tenant = executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Tenant> request = keystoneAdminClient.tenants().create(tenant);
+ tenant = executeAndRecordOpenstackRequest(request);
} catch (OpenStackBaseException e) {
// Convert Keystone OpenStackResponseException to MsoOpenstackException
- throw keystoneErrorToMsoException (e, "CreateTenant");
+ throw keystoneErrorToMsoException(e, "CreateTenant");
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, "CreateTenant");
+ throw runtimeExceptionToMsoException(e, "CreateTenant");
}
// Add MSO User to the tenant as a member and
@@ -134,67 +131,61 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
try {
CloudIdentity cloudIdentity = cloudSiteOpt.get().getIdentityService();
- User msoUser = findUserByNameOrId (keystoneAdminClient, cloudIdentity.getMsoId ());
- Role memberRole = findRoleByNameOrId (keystoneAdminClient, cloudIdentity.getMemberRole ());
-
- if(msoUser != null && memberRole != null) {
- OpenStackRequest <Void> request = keystoneAdminClient.tenants ().addUser (tenant.getId (),
- msoUser.getId (),
- memberRole.getId ());
- executeAndRecordOpenstackRequest (request);
+ User msoUser = findUserByNameOrId(keystoneAdminClient, cloudIdentity.getMsoId());
+ Role memberRole = findRoleByNameOrId(keystoneAdminClient, cloudIdentity.getMemberRole());
+
+ if (msoUser != null && memberRole != null) {
+ OpenStackRequest<Void> request =
+ keystoneAdminClient.tenants().addUser(tenant.getId(), msoUser.getId(), memberRole.getId());
+ executeAndRecordOpenstackRequest(request);
}
- if (cloudIdentity.getTenantMetadata () && metadata != null && !metadata.isEmpty ()) {
- Metadata tenantMetadata = new Metadata ();
- tenantMetadata.setMetadata (metadata);
+ if (cloudIdentity.getTenantMetadata() && metadata != null && !metadata.isEmpty()) {
+ Metadata tenantMetadata = new Metadata();
+ tenantMetadata.setMetadata(metadata);
- OpenStackRequest <Metadata> metaRequest = keystoneAdminClient.tenants ()
- .createOrUpdateMetadata (tenant.getId (),
- tenantMetadata);
- executeAndRecordOpenstackRequest (metaRequest);
+ OpenStackRequest<Metadata> metaRequest =
+ keystoneAdminClient.tenants().createOrUpdateMetadata(tenant.getId(), tenantMetadata);
+ executeAndRecordOpenstackRequest(metaRequest);
}
} catch (Exception e) {
// Failed to attach MSO User to the new tenant. Can't operate without access,
// so roll back the tenant.
- if (!backout)
- {
- logger.warn("{} Create Tenant errored, Tenant deletion suppressed {} ", MessageEnum.RA_CREATE_TENANT_ERR,
- ErrorCode.DataError.getValue());
- }
- else
- {
- try {
- OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ());
- executeAndRecordOpenstackRequest (request);
- } catch (Exception e2) {
- // Just log this one. We will report the original exception.
- logger.error("{} Nested exception rolling back tenant {} ", MessageEnum.RA_CREATE_TENANT_ERR,
- ErrorCode.DataError.getValue(), e2);
+ if (!backout) {
+ logger.warn("{} Create Tenant errored, Tenant deletion suppressed {} ",
+ MessageEnum.RA_CREATE_TENANT_ERR, ErrorCode.DataError.getValue());
+ } else {
+ try {
+ OpenStackRequest<Void> request = keystoneAdminClient.tenants().delete(tenant.getId());
+ executeAndRecordOpenstackRequest(request);
+ } catch (Exception e2) {
+ // Just log this one. We will report the original exception.
+ logger.error("{} Nested exception rolling back tenant {} ", MessageEnum.RA_CREATE_TENANT_ERR,
+ ErrorCode.DataError.getValue(), e2);
+ }
}
- }
-
+
// Propagate the original exception on user/role/tenant mapping
if (e instanceof OpenStackBaseException) {
// Convert Keystone Exception to MsoOpenstackException
- throw keystoneErrorToMsoException ((OpenStackBaseException) e, "CreateTenantUser");
+ throw keystoneErrorToMsoException((OpenStackBaseException) e, "CreateTenantUser");
} else {
- MsoAdapterException me = new MsoAdapterException (e.getMessage (), e);
- me.addContext ("CreateTenantUser");
+ MsoAdapterException me = new MsoAdapterException(e.getMessage(), e);
+ me.addContext("CreateTenantUser");
throw me;
}
}
- return tenant.getId ();
+ return tenant.getId();
}
/**
- * Query for a tenant by ID in the given cloud. If the tenant exists,
- * return an MsoTenant object. If not, return null.
+ * Query for a tenant by ID in the given cloud. If the tenant exists, return an MsoTenant object. If not, return
+ * null.
* <p>
- * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin
- * requests go to the centralized identity service in DCP. However, if some artifact
- * must exist in each local LCP instance as well, then it will be needed to access the
- * correct region.
+ * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin requests go to the centralized
+ * identity service in DCP. However, if some artifact must exist in each local LCP instance as well, then it will be
+ * needed to access the correct region.
* <p>
*
* @param tenantId The Openstack ID of the tenant to query
@@ -202,47 +193,46 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
* @return the tenant properties of the queried tenant, or null if not found
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
*/
- public MsoTenant queryTenant (String tenantId, String cloudSiteId) throws MsoException {
+ public MsoTenant queryTenant(String tenantId, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will query the tenant
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
- Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
+ Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSite);
// Check if the tenant exists and return its Tenant Id
try {
- Tenant tenant = findTenantById (keystoneAdminClient, tenantId);
+ Tenant tenant = findTenantById(keystoneAdminClient, tenantId);
if (tenant == null) {
return null;
}
- Map <String, String> metadata = new HashMap <String, String> ();
- if (cloudSite.getIdentityService().getTenantMetadata ()) {
- OpenStackRequest <Metadata> request = keystoneAdminClient.tenants ().showMetadata (tenant.getId ());
- Metadata tenantMetadata = executeAndRecordOpenstackRequest (request);
+ Map<String, String> metadata = new HashMap<String, String>();
+ if (cloudSite.getIdentityService().getTenantMetadata()) {
+ OpenStackRequest<Metadata> request = keystoneAdminClient.tenants().showMetadata(tenant.getId());
+ Metadata tenantMetadata = executeAndRecordOpenstackRequest(request);
if (tenantMetadata != null) {
- metadata = tenantMetadata.getMetadata ();
+ metadata = tenantMetadata.getMetadata();
}
}
- return new MsoTenant (tenant.getId (), tenant.getName (), metadata);
+ return new MsoTenant(tenant.getId(), tenant.getName(), metadata);
} catch (OpenStackBaseException e) {
// Convert Keystone OpenStackResponseException to MsoOpenstackException
- throw keystoneErrorToMsoException (e, "QueryTenant");
+ throw keystoneErrorToMsoException(e, "QueryTenant");
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, "QueryTenant");
+ throw runtimeExceptionToMsoException(e, "QueryTenant");
}
}
/**
- * Query for a tenant with the specified name in the given cloud. If the tenant exists,
- * return an MsoTenant object. If not, return null. This query is useful if the client
- * knows it has the tenant name, skipping an initial lookup by ID that would always fail.
+ * Query for a tenant with the specified name in the given cloud. If the tenant exists, return an MsoTenant object.
+ * If not, return null. This query is useful if the client knows it has the tenant name, skipping an initial lookup
+ * by ID that would always fail.
* <p>
- * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin
- * requests go to the centralized identity service in DCP. However, if some artifact
- * must exist in each local LCP instance as well, then it will be needed to access the
- * correct region.
+ * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin requests go to the centralized
+ * identity service in DCP. However, if some artifact must exist in each local LCP instance as well, then it will be
+ * needed to access the correct region.
* <p>
*
* @param tenantName The name of the tenant to query
@@ -250,44 +240,43 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
* @return the tenant properties of the queried tenant, or null if not found
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
*/
- public MsoTenant queryTenantByName (String tenantName, String cloudSiteId) throws MsoException {
+ public MsoTenant queryTenantByName(String tenantName, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will query the tenant
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
- Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSite);
try {
- Tenant tenant = findTenantByName (keystoneAdminClient, tenantName);
+ Tenant tenant = findTenantByName(keystoneAdminClient, tenantName);
if (tenant == null) {
return null;
}
- Map <String, String> metadata = new HashMap <String, String> ();
- if (cloudSite.getIdentityService().getTenantMetadata ()) {
- OpenStackRequest <Metadata> request = keystoneAdminClient.tenants ().showMetadata (tenant.getId ());
- Metadata tenantMetadata = executeAndRecordOpenstackRequest (request);
+ Map<String, String> metadata = new HashMap<String, String>();
+ if (cloudSite.getIdentityService().getTenantMetadata()) {
+ OpenStackRequest<Metadata> request = keystoneAdminClient.tenants().showMetadata(tenant.getId());
+ Metadata tenantMetadata = executeAndRecordOpenstackRequest(request);
if (tenantMetadata != null) {
- metadata = tenantMetadata.getMetadata ();
+ metadata = tenantMetadata.getMetadata();
}
}
- return new MsoTenant (tenant.getId (), tenant.getName (), metadata);
+ return new MsoTenant(tenant.getId(), tenant.getName(), metadata);
} catch (OpenStackBaseException e) {
// Convert Keystone OpenStackResponseException to MsoOpenstackException
- throw keystoneErrorToMsoException (e, "QueryTenantName");
+ throw keystoneErrorToMsoException(e, "QueryTenantName");
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, "QueryTenantName");
+ throw runtimeExceptionToMsoException(e, "QueryTenantName");
}
}
/**
- * Delete the specified Tenant (by ID) in the given cloud. This method returns true or
- * false, depending on whether the tenant existed and was successfully deleted, or if
- * the tenant already did not exist. Both cases are treated as success (no Exceptions).
+ * Delete the specified Tenant (by ID) in the given cloud. This method returns true or false, depending on whether
+ * the tenant existed and was successfully deleted, or if the tenant already did not exist. Both cases are treated
+ * as success (no Exceptions).
* <p>
- * Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity
- * service in DCP. So deleting a tenant from one cloudSiteId will remove it from all
- * sites managed by that identity service.
+ * Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity service in DCP. So deleting a
+ * tenant from one cloudSiteId will remove it from all sites managed by that identity service.
* <p>
*
* @param tenantId The Openstack ID of the tenant to delete
@@ -295,43 +284,42 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
* @return true if the tenant was deleted, false if the tenant did not exist.
* @throws MsoOpenstackException If the Openstack API call returns an exception.
*/
- public boolean deleteTenant (String tenantId, String cloudSiteId) throws MsoException {
+ public boolean deleteTenant(String tenantId, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will query the tenant
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
- Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSite);
try {
// Check that the tenant exists. Also, need the ID to delete
- Tenant tenant = findTenantById (keystoneAdminClient, tenantId);
+ Tenant tenant = findTenantById(keystoneAdminClient, tenantId);
if (tenant == null) {
logger.error("{} Tenant id {} not found on cloud site id {}, {}", MessageEnum.RA_TENANT_NOT_FOUND,
- tenantId, cloudSiteId, ErrorCode.DataError.getValue());
+ tenantId, cloudSiteId, ErrorCode.DataError.getValue());
return false;
}
- OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ());
- executeAndRecordOpenstackRequest (request);
- logger.debug ("Deleted Tenant {} ({})", tenant.getId(), tenant.getName());
+ OpenStackRequest<Void> request = keystoneAdminClient.tenants().delete(tenant.getId());
+ executeAndRecordOpenstackRequest(request);
+ logger.debug("Deleted Tenant {} ({})", tenant.getId(), tenant.getName());
} catch (OpenStackBaseException e) {
// Convert Keystone OpenStackResponseException to MsoOpenstackException
- throw keystoneErrorToMsoException (e, "Delete Tenant");
+ throw keystoneErrorToMsoException(e, "Delete Tenant");
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, "DeleteTenant");
+ throw runtimeExceptionToMsoException(e, "DeleteTenant");
}
return true;
}
/**
- * Delete the specified Tenant (by Name) in the given cloud. This method returns true or
- * false, depending on whether the tenant existed and was successfully deleted, or if
- * the tenant already did not exist. Both cases are treated as success (no Exceptions).
+ * Delete the specified Tenant (by Name) in the given cloud. This method returns true or false, depending on whether
+ * the tenant existed and was successfully deleted, or if the tenant already did not exist. Both cases are treated
+ * as success (no Exceptions).
* <p>
- * Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity
- * service in DCP. So deleting a tenant from one cloudSiteId will remove it from all
- * sites managed by that identity service.
+ * Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity service in DCP. So deleting a
+ * tenant from one cloudSiteId will remove it from all sites managed by that identity service.
* <p>
*
* @param tenantName The name of the tenant to delete
@@ -339,37 +327,37 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
* @return true if the tenant was deleted, false if the tenant did not exist.
* @throws MsoOpenstackException If the Openstack API call returns an exception.
*/
- public boolean deleteTenantByName (String tenantName, String cloudSiteId) throws MsoException {
+ public boolean deleteTenantByName(String tenantName, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will query the tenant
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSite.isPresent()) {
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite.get());
+ Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSite.get());
try {
// Need the Tenant ID to delete (can't directly delete by name)
- Tenant tenant = findTenantByName (keystoneAdminClient, tenantName);
+ Tenant tenant = findTenantByName(keystoneAdminClient, tenantName);
if (tenant == null) {
// OK if tenant already doesn't exist.
logger.error("{} Tenant {} not found on Cloud site id {}, {}", MessageEnum.RA_TENANT_NOT_FOUND,
- tenantName, cloudSiteId, ErrorCode.DataError.getValue());
+ tenantName, cloudSiteId, ErrorCode.DataError.getValue());
return false;
}
// Execute the Delete. It has no return value.
- OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ());
- executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Void> request = keystoneAdminClient.tenants().delete(tenant.getId());
+ executeAndRecordOpenstackRequest(request);
logger.debug("Deleted Tenant {} ({})", tenant.getId(), tenant.getName());
} catch (OpenStackBaseException e) {
// Note: It doesn't seem to matter if tenant doesn't exist, no exception is thrown.
// Convert Keystone OpenStackResponseException to MsoOpenstackException
- throw keystoneErrorToMsoException (e, "DeleteTenant");
+ throw keystoneErrorToMsoException(e, "DeleteTenant");
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, "DeleteTenant");
+ throw runtimeExceptionToMsoException(e, "DeleteTenant");
}
return true;
@@ -379,26 +367,24 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
// PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
/*
- * Get a Keystone Admin client for the Openstack Identity service.
- * This requires an 'admin'-level userId + password along with an 'admin' tenant
- * in the target cloud. These values will be retrieved from properties based
- * on the specified cloud ID.
- * <p>
- * On successful authentication, the Keystone object will be cached for the cloudId
- * so that it can be reused without going back to Openstack every time.
+ * Get a Keystone Admin client for the Openstack Identity service. This requires an 'admin'-level userId + password
+ * along with an 'admin' tenant in the target cloud. These values will be retrieved from properties based on the
+ * specified cloud ID. <p> On successful authentication, the Keystone object will be cached for the cloudId so that
+ * it can be reused without going back to Openstack every time.
*
* @param cloudId
*
* @return an authenticated Keystone object
*/
- public Keystone getKeystoneAdminClient (CloudSite cloudSite) throws MsoException {
+ public Keystone getKeystoneAdminClient(CloudSite cloudSite) throws MsoException {
CloudIdentity cloudIdentity = cloudSite.getIdentityService();
- String cloudId = cloudIdentity.getId ();
- String adminTenantName = cloudIdentity.getAdminTenant ();
- String region = cloudSite.getRegionId ();
+ String cloudId = cloudIdentity.getId();
+ String adminTenantName = cloudIdentity.getAdminTenant();
+ String region = cloudSite.getRegionId();
- MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
+ MsoTenantUtils tenantUtils =
+ tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
final String keystoneUrl = tenantUtils.getKeystoneUrl(region, cloudIdentity);
Keystone keystone = new Keystone(keystoneUrl);
@@ -406,51 +392,50 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
Access access = null;
String token = null;
try {
- Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
- OpenStackRequest <Access> request = keystone.tokens ()
- .authenticate (credentials)
- .withTenantName (adminTenantName);
- access = executeAndRecordOpenstackRequest (request);
- token = access.getToken ().getId ();
+ Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
+ OpenStackRequest<Access> request =
+ keystone.tokens().authenticate(credentials).withTenantName(adminTenantName);
+ access = executeAndRecordOpenstackRequest(request);
+ token = access.getToken().getId();
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 401) {
+ if (e.getStatus() == 401) {
// Authentication error. Can't access admin tenant - something is mis-configured
- String error = "MSO Authentication Failed for " + cloudIdentity.getId ();
+ String error = "MSO Authentication Failed for " + cloudIdentity.getId();
- throw new MsoAdapterException (error);
+ throw new MsoAdapterException(error);
} else {
- throw keystoneErrorToMsoException (e, "TokenAuth");
+ throw keystoneErrorToMsoException(e, "TokenAuth");
}
} catch (OpenStackConnectException e) {
// Connection to Openstack failed
- throw keystoneErrorToMsoException (e, "TokenAuth");
+ throw keystoneErrorToMsoException(e, "TokenAuth");
}
// Get the Identity service URL. Throws runtime exception if not found per region.
String adminUrl = null;
try {
- // TODO: FOR TESTING!!!!
- adminUrl = KeystoneUtils.findEndpointURL (access.getServiceCatalog (), "identity", region, "public");
- adminUrl = adminUrl.replaceFirst("5000", "35357");
+ // TODO: FOR TESTING!!!!
+ adminUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "identity", region, "public");
+ adminUrl = adminUrl.replaceFirst("5000", "35357");
} catch (RuntimeException e) {
- String error = "Identity service not found: region=" + region + ",cloud=" + cloudIdentity.getId ();
+ String error = "Identity service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
logger.error("{} Region: {} Cloud identity {} {} Exception in findEndpointURL ",
- MessageEnum.IDENTITY_SERVICE_NOT_FOUND, region, cloudIdentity.getId(),
- ErrorCode.DataError.getValue(), e);
- throw new MsoAdapterException (error, e);
+ MessageEnum.IDENTITY_SERVICE_NOT_FOUND, region, cloudIdentity.getId(),
+ ErrorCode.DataError.getValue(), e);
+ throw new MsoAdapterException(error, e);
}
// A new Keystone object is required for the new URL. Use the auth token from above.
// Note: this doesn't go back to Openstack, it's just a local object.
- keystone = new Keystone (adminUrl);
- keystone.token (token);
+ keystone = new Keystone(adminUrl);
+ keystone.token(token);
return keystone;
}
/*
- * Find a tenant (or query its existance) by its Name or Id. Check first against the
- * ID. If that fails, then try by name.
+ * Find a tenant (or query its existance) by its Name or Id. Check first against the ID. If that fails, then try by
+ * name.
*
* @param adminClient an authenticated Keystone object
*
@@ -458,14 +443,14 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
*
* @return a Tenant object or null if not found
*/
- public Tenant findTenantByNameOrId (Keystone adminClient, String tenantNameOrId) {
+ public Tenant findTenantByNameOrId(Keystone adminClient, String tenantNameOrId) {
if (tenantNameOrId == null) {
return null;
}
- Tenant tenant = findTenantById (adminClient, tenantNameOrId);
+ Tenant tenant = findTenantById(adminClient, tenantNameOrId);
if (tenant == null) {
- tenant = findTenantByName (adminClient, tenantNameOrId);
+ tenant = findTenantByName(adminClient, tenantNameOrId);
}
return tenant;
@@ -480,28 +465,28 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
*
* @return a Tenant object or null if not found
*/
- private Tenant findTenantById (Keystone adminClient, String tenantId) {
+ private Tenant findTenantById(Keystone adminClient, String tenantId) {
if (tenantId == null) {
return null;
}
try {
- OpenStackRequest <Tenant> request = adminClient.tenants ().show (tenantId);
- return executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Tenant> request = adminClient.tenants().show(tenantId);
+ return executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 404) {
+ if (e.getStatus() == 404) {
return null;
} else {
logger.error("{} {} Openstack Error, GET Tenant by Id ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), tenantId, e);
+ ErrorCode.DataError.getValue(), tenantId, e);
throw e;
}
}
}
/*
- * Find a tenant (or query its existance) by its Name. This method avoids an
- * initial lookup by ID when it's known that we have the tenant Name.
+ * Find a tenant (or query its existance) by its Name. This method avoids an initial lookup by ID when it's known
+ * that we have the tenant Name.
*
* @param adminClient an authenticated Keystone object
*
@@ -509,28 +494,27 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
*
* @return a Tenant object or null if not found
*/
- public Tenant findTenantByName (Keystone adminClient, String tenantName) {
+ public Tenant findTenantByName(Keystone adminClient, String tenantName) {
if (tenantName == null) {
return null;
}
try {
- OpenStackRequest <Tenant> request = adminClient.tenants ().show ("").queryParam ("name", tenantName);
- return executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Tenant> request = adminClient.tenants().show("").queryParam("name", tenantName);
+ return executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 404) {
+ if (e.getStatus() == 404) {
return null;
} else {
logger.error("{} {} Openstack Error, GET Tenant By Name ({}) ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), tenantName, e);
+ ErrorCode.DataError.getValue(), tenantName, e);
throw e;
}
}
}
/*
- * Look up an Openstack User by Name or Openstack ID. Check the ID first, and if that
- * fails, try the Name.
+ * Look up an Openstack User by Name or Openstack ID. Check the ID first, and if that fails, try the Name.
*
* @param adminClient an authenticated Keystone object
*
@@ -538,29 +522,28 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
*
* @return a User object or null if not found
*/
- private User findUserByNameOrId (Keystone adminClient, String userNameOrId) {
+ private User findUserByNameOrId(Keystone adminClient, String userNameOrId) {
if (userNameOrId == null) {
return null;
}
try {
- OpenStackRequest <User> request = adminClient.users ().show (userNameOrId);
- return executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<User> request = adminClient.users().show(userNameOrId);
+ return executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 404) {
+ if (e.getStatus() == 404) {
// Not found by ID. Search for name
- return findUserByName (adminClient, userNameOrId);
+ return findUserByName(adminClient, userNameOrId);
} else {
logger.error("{} {} Openstack Error, GET User ({}) ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), userNameOrId, e);
+ ErrorCode.DataError.getValue(), userNameOrId, e);
throw e;
}
}
}
/*
- * Look up an Openstack User by Name. This avoids initial Openstack query by ID
- * if we know we have the User Name.
+ * Look up an Openstack User by Name. This avoids initial Openstack query by ID if we know we have the User Name.
*
* @param adminClient an authenticated Keystone object
*
@@ -568,31 +551,29 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
*
* @return a User object or null if not found
*/
- public User findUserByName (Keystone adminClient, String userName) {
+ public User findUserByName(Keystone adminClient, String userName) {
if (userName == null) {
return null;
}
try {
- OpenStackRequest <User> request = adminClient.users ().show ("").queryParam ("name", userName);
- return executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<User> request = adminClient.users().show("").queryParam("name", userName);
+ return executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 404) {
+ if (e.getStatus() == 404) {
return null;
} else {
logger.error("{} {} Openstack Error, GET User By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), userName, e);
+ ErrorCode.DataError.getValue(), userName, e);
throw e;
}
}
}
/*
- * Look up an Openstack Role by Name or Id. There is no direct query for Roles, so
- * need to retrieve a full list from Openstack and look for a match. By default,
- * Openstack should have a "_member_" role for normal VM-level privileges and an
- * "admin" role for expanded privileges (e.g. administer tenants, users, and roles).
- * <p>
+ * Look up an Openstack Role by Name or Id. There is no direct query for Roles, so need to retrieve a full list from
+ * Openstack and look for a match. By default, Openstack should have a "_member_" role for normal VM-level
+ * privileges and an "admin" role for expanded privileges (e.g. administer tenants, users, and roles). <p>
*
* @param adminClient an authenticated Keystone object
*
@@ -600,17 +581,17 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
*
* @return a Role object
*/
- private Role findRoleByNameOrId (Keystone adminClient, String roleNameOrId) {
+ private Role findRoleByNameOrId(Keystone adminClient, String roleNameOrId) {
if (roleNameOrId == null) {
return null;
}
// Search by name or ID. Must search in list
- OpenStackRequest <Roles> request = adminClient.roles ().list ();
- Roles roles = executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Roles> request = adminClient.roles().list();
+ Roles roles = executeAndRecordOpenstackRequest(request);
for (Role role : roles) {
- if (roleNameOrId.equals (role.getName ()) || roleNameOrId.equals (role.getId ())) {
+ if (roleNameOrId.equals(role.getName()) || roleNameOrId.equals(role.getId())) {
return role;
}
}
@@ -618,8 +599,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
return null;
}
- @Override
- public String getKeystoneUrl(String regionId, CloudIdentity cloudIdentity) throws MsoException {
- return cloudIdentity.getIdentityUrl();
- }
+ @Override
+ public String getKeystoneUrl(String regionId, CloudIdentity cloudIdentity) throws MsoException {
+ return cloudIdentity.getIdentityUrl();
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java
index 067763cc1a..63bc235363 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java
@@ -21,7 +21,6 @@
package org.onap.so.openstack.utils;
import java.util.Map;
-
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.openstack.beans.MsoTenant;
import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
@@ -31,31 +30,31 @@ import org.springframework.stereotype.Component;
@Component
public class MsoKeystoneV3Utils extends MsoTenantUtils {
- @Override
- public String createTenant(String tenantName, String cloudSiteId, Map<String, String> metadata, boolean backout)
- throws MsoException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public MsoTenant queryTenant(String tenantId, String cloudSiteId) throws MsoException, MsoCloudSiteNotFound {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public MsoTenant queryTenantByName(String tenantName, String cloudSiteId)
- throws MsoException, MsoCloudSiteNotFound {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean deleteTenant(String tenantId, String cloudSiteId) throws MsoException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getKeystoneUrl(String regionId, CloudIdentity cloudIdentity) throws MsoException {
- return cloudIdentity.getIdentityUrl();
- }
+ @Override
+ public String createTenant(String tenantName, String cloudSiteId, Map<String, String> metadata, boolean backout)
+ throws MsoException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public MsoTenant queryTenant(String tenantId, String cloudSiteId) throws MsoException, MsoCloudSiteNotFound {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public MsoTenant queryTenantByName(String tenantName, String cloudSiteId)
+ throws MsoException, MsoCloudSiteNotFound {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean deleteTenant(String tenantId, String cloudSiteId) throws MsoException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public String getKeystoneUrl(String regionId, CloudIdentity cloudIdentity) throws MsoException {
+ return cloudIdentity.getIdentityUrl();
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java
index a939f79cf9..2788387bc1 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java
@@ -33,6 +33,7 @@ import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriBuilderException;
import org.onap.so.adapters.vdu.CloudInfo;
import org.onap.so.adapters.vdu.PluginAction;
@@ -44,9 +45,9 @@ import org.onap.so.adapters.vdu.VduModelInfo;
import org.onap.so.adapters.vdu.VduPlugin;
import org.onap.so.adapters.vdu.VduStateType;
import org.onap.so.adapters.vdu.VduStatus;
+import org.onap.so.client.HttpClient;
import org.onap.so.client.HttpClientFactory;
import org.onap.so.client.RestClient;
-import org.onap.so.db.catalog.beans.CloudSite;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.onap.so.openstack.beans.HeatStatus;
@@ -63,19 +64,24 @@ import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
-public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
+public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
public static final String OOF_DIRECTIVES = "oof_directives";
public static final String SDNC_DIRECTIVES = "sdnc_directives";
+ public static final String USER_DIRECTIVES = "user_directives";
public static final String VNF_ID = "vnf_id";
public static final String VF_MODULE_ID = "vf_module_id";
public static final String TEMPLATE_TYPE = "template_type";
+ public static final String MULTICLOUD_QUERY_BODY_NULL = "multicloudQueryBody is null";
public static final List<String> MULTICLOUD_INPUTS =
- Arrays.asList(OOF_DIRECTIVES, SDNC_DIRECTIVES, TEMPLATE_TYPE);
+ Arrays.asList(OOF_DIRECTIVES, SDNC_DIRECTIVES, USER_DIRECTIVES, TEMPLATE_TYPE);
private static final Logger logger = LoggerFactory.getLogger(MsoMulticloudUtils.class);
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
+ private static final Integer DEFAULT_MSB_PORT = 80;
+ private static final String DEFAULT_MSB_IP = "127.0.0.1";
+ private static final String ONAP_IP = "ONAP_IP";
private final HttpClientFactory httpClientFactory = new HttpClientFactory();
@Autowired
@@ -88,31 +94,28 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
*******************************************************************************/
/**
- * Create a new Stack in the specified cloud location and tenant. The Heat template
- * and parameter map are passed in as arguments, along with the cloud access credentials.
- * It is expected that parameters have been validated and contain at minimum the required
- * parameters for the given template with no extra (undefined) parameters..
+ * Create a new Stack in the specified cloud location and tenant. The Heat template and parameter map are passed in
+ * as arguments, along with the cloud access credentials. It is expected that parameters have been validated and
+ * contain at minimum the required parameters for the given template with no extra (undefined) parameters..
*
- * The Stack name supplied by the caller must be unique in the scope of this tenant.
- * However, it should also be globally unique, as it will be the identifier for the
- * resource going forward in Inventory. This latter is managed by the higher levels
- * invoking this function.
+ * The Stack name supplied by the caller must be unique in the scope of this tenant. However, it should also be
+ * globally unique, as it will be the identifier for the resource going forward in Inventory. This latter is managed
+ * by the higher levels invoking this function.
*
- * The caller may choose to let this function poll Openstack for completion of the
- * stack creation, or may handle polling itself via separate calls to query the status.
- * In either case, a StackInfo object will be returned containing the current status.
- * When polling is enabled, a status of CREATED is expected. When not polling, a
+ * The caller may choose to let this function poll Openstack for completion of the stack creation, or may handle
+ * polling itself via separate calls to query the status. In either case, a StackInfo object will be returned
+ * containing the current status. When polling is enabled, a status of CREATED is expected. When not polling, a
* status of BUILDING is expected.
*
- * An error will be thrown if the requested Stack already exists in the specified
- * Tenant and Cloud.
+ * An error will be thrown if the requested Stack already exists in the specified Tenant and Cloud.
*
- * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as
- * parameters for createStack. If environment is non-null, it will be added to the stack.
- * The nested templates and get_file entries both end up being added to the "files" on the
- * stack. We must combine them before we add them to the stack if they're both non-null.
+ * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as parameters for
+ * createStack. If environment is non-null, it will be added to the stack. The nested templates and get_file entries
+ * both end up being added to the "files" on the stack. We must combine them before we add them to the stack if
+ * they're both non-null.
*
- * @param cloudSiteId The cloud (may be a region) in which to create the stack.
+ * @param cloudSiteId The cloud (may be a region) in which to create the stack
+ * @param cloudOwner the cloud owner of the cloud site in which to create the stack
* @param tenantId The Openstack ID of the tenant in which to create the Stack
* @param stackName The name of the stack to create
* @param heatTemplate The Heat template
@@ -129,28 +132,22 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
@SuppressWarnings("unchecked")
@Override
- public StackInfo createStack (String cloudSiteId,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, ?> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files,
- Map <String, Object> heatFiles,
- boolean backout) throws MsoException {
+ public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ VduModelInfo vduModel, String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion,
+ int timeoutMinutes, String environment, Map<String, Object> files, Map<String, Object> heatFiles,
+ boolean backout) throws MsoException {
logger.trace("Started MsoMulticloudUtils.createStack");
// Get the directives, if present.
String oofDirectives = "{}";
String sdncDirectives = "{}";
+ String userDirectives = "{}";
String genericVnfId = "";
String vfModuleId = "";
String templateType = "";
- for (String key: MULTICLOUD_INPUTS) {
+ for (String key : MULTICLOUD_INPUTS) {
if (!stackInputs.isEmpty() && stackInputs.containsKey(key)) {
if (key == OOF_DIRECTIVES) {
oofDirectives = (String) stackInputs.get(key);
@@ -158,6 +155,9 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
if (key == SDNC_DIRECTIVES) {
sdncDirectives = (String) stackInputs.get(key);
}
+ if (key == USER_DIRECTIVES) {
+ sdncDirectives = (String) stackInputs.get(key);
+ }
if (key == TEMPLATE_TYPE) {
templateType = (String) stackInputs.get(key);
}
@@ -168,30 +168,35 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
}
- if (!stackInputs.isEmpty() && stackInputs.containsKey(VF_MODULE_ID)){
+ if (!stackInputs.isEmpty() && stackInputs.containsKey(VF_MODULE_ID)) {
vfModuleId = (String) stackInputs.get(VF_MODULE_ID);
}
- if (!stackInputs.isEmpty() && stackInputs.containsKey(VNF_ID)){
+ if (!stackInputs.isEmpty() && stackInputs.containsKey(VNF_ID)) {
genericVnfId = (String) stackInputs.get(VNF_ID);
}
// create the multicloud payload
- CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
+ CreateStackParam stack =
+ createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
- MulticloudRequest multicloudRequest= new MulticloudRequest();
+ MulticloudRequest multicloudRequest = new MulticloudRequest();
multicloudRequest.setGenericVnfId(genericVnfId);
multicloudRequest.setVfModuleId(vfModuleId);
+ multicloudRequest.setVfModuleModelInvariantId(vduModel.getModelInvariantUUID());
+ multicloudRequest.setVfModuleModelVersionId(vduModel.getModelUUID());
+ multicloudRequest.setVfModuleModelCustomizationId(vduModel.getModelCustomizationUUID());
multicloudRequest.setTemplateType(templateType);
multicloudRequest.setTemplateData(stack);
multicloudRequest.setOofDirectives(getDirectiveNode(oofDirectives));
multicloudRequest.setSdncDirectives(getDirectiveNode(sdncDirectives));
+ multicloudRequest.setUserDirectives(getDirectiveNode(userDirectives));
if (logger.isDebugEnabled()) {
logger.debug(String.format("Multicloud Request is: %s", multicloudRequest.toString()));
}
- String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, null);
- RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
+ String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, null);
+ RestClient multicloudClient = getMulticloudClient(multicloudEndpoint, tenantId);
if (multicloudClient == null) {
MsoOpenstackException me = new MsoOpenstackException(0, "", "Multicloud client could not be initialized");
@@ -213,7 +218,16 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
if (logger.isDebugEnabled()) {
logger.debug("Multicloud Create Response Body: {}", multicloudResponseBody);
}
- return getStackStatus(cloudSiteId, tenantId, canonicalName, pollForCompletion, timeoutMinutes, backout);
+ StackInfo stackStatus = getStackStatus(cloudSiteId, cloudOwner, tenantId, canonicalName, pollForCompletion,
+ timeoutMinutes, backout);
+
+ if (HeatStatus.CREATED.equals(stackStatus.getStatus())) {
+ String workloadId = multicloudResponseBody == null ? null : multicloudResponseBody.getWorkloadId();
+ multicloudAaiUpdate(cloudSiteId, cloudOwner, tenantId, genericVnfId, vfModuleId, workloadId,
+ pollForCompletion, timeoutMinutes);
+ }
+
+ return stackStatus;
}
StringBuilder stackErrorStatusReason = new StringBuilder(response.getStatusInfo().getReasonPhrase());
if (null != multicloudResponseBody) {
@@ -225,10 +239,10 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
@Override
- public Map<String, Object> queryStackForOutputs(String cloudSiteId,
- String tenantId, String stackName) throws MsoException {
+ public Map<String, Object> queryStackForOutputs(String cloudSiteId, String cloudOwner, String tenantId,
+ String stackName) throws MsoException {
logger.debug("MsoHeatUtils.queryStackForOutputs)");
- StackInfo heatStack = this.queryStack(cloudSiteId, tenantId, stackName);
+ StackInfo heatStack = this.queryStack(cloudSiteId, cloudOwner, tenantId, stackName);
if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
return null;
}
@@ -236,20 +250,21 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
/**
- * Query for a single stack (by ID) in a tenant. This call will always return a
- * StackInfo object. If the stack does not exist, an "empty" StackInfo will be
- * returned - containing only the stack name and a status of NOTFOUND.
+ * Query for a single stack (by ID) in a tenant. This call will always return a StackInfo object. If the stack does
+ * not exist, an "empty" StackInfo will be returned - containing only the stack name and a status of NOTFOUND.
*
* @param tenantId The Openstack ID of the tenant in which to query
* @param cloudSiteId The cloud identifier (may be a region) in which to query
+ * @param cloudOwner cloud owner of the cloud site in which to query
* @param stackId The ID of the stack to query
* @return A StackInfo object
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
*/
@Override
- public StackInfo queryStack (String cloudSiteId, String tenantId, String instanceId) throws MsoException {
+ public StackInfo queryStack(String cloudSiteId, String cloudOwner, String tenantId, String instanceId)
+ throws MsoException {
if (logger.isDebugEnabled()) {
- logger.debug (String.format("Query multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
+ logger.debug(String.format("Query multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
}
String stackName = null;
String stackId = null;
@@ -265,13 +280,13 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
StackInfo returnInfo = new StackInfo();
returnInfo.setName(stackName);
- String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, stackId);
- RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
+ String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, stackId);
+ RestClient multicloudClient = getMulticloudClient(multicloudEndpoint, tenantId);
if (multicloudClient != null) {
Response response = multicloudClient.get();
if (logger.isDebugEnabled()) {
- logger.debug (String.format("Mulicloud GET Response: %s", response.toString()));
+ logger.debug(String.format("Multicloud GET Response: %s", response.toString()));
}
MulticloudQueryResponse multicloudQueryBody = null;
@@ -279,12 +294,17 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
returnInfo.setStatus(HeatStatus.NOTFOUND);
returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
} else if (response.getStatus() == Response.Status.OK.getStatusCode() && response.hasEntity()) {
- multicloudQueryBody = getQueryBody((java.io.InputStream)response.getEntity());
- returnInfo.setCanonicalName(stackName + "/" + multicloudQueryBody.getWorkloadId());
- returnInfo.setStatus(getHeatStatus(multicloudQueryBody.getWorkloadStatus()));
- returnInfo.setStatusMessage(multicloudQueryBody.getWorkloadStatus());
- if (logger.isDebugEnabled()) {
- logger.debug("Multicloud Create Response Body: " + multicloudQueryBody.toString());
+ multicloudQueryBody = getQueryBody((java.io.InputStream) response.getEntity());
+ if (multicloudQueryBody != null) {
+ returnInfo.setCanonicalName(stackName + "/" + multicloudQueryBody.getWorkloadId());
+ returnInfo.setStatus(getHeatStatus(multicloudQueryBody.getWorkloadStatus()));
+ returnInfo.setStatusMessage(multicloudQueryBody.getWorkloadStatus());
+ if (logger.isDebugEnabled()) {
+ logger.debug("Multicloud Create Response Body: " + multicloudQueryBody.toString());
+ }
+ } else {
+ returnInfo.setStatus(HeatStatus.FAILED);
+ returnInfo.setStatusMessage(MULTICLOUD_QUERY_BODY_NULL);
}
} else {
returnInfo.setStatus(HeatStatus.FAILED);
@@ -295,9 +315,10 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
return returnInfo;
}
- public StackInfo deleteStack (String cloudSiteId, String tenantId, String instanceId) throws MsoException {
+ public StackInfo deleteStack(String cloudSiteId, String cloudOwner, String tenantId, String instanceId)
+ throws MsoException {
if (logger.isDebugEnabled()) {
- logger.debug (String.format("Delete multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
+ logger.debug(String.format("Delete multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
}
String stackName = null;
String stackId = null;
@@ -314,8 +335,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
returnInfo.setName(stackName);
Response response = null;
- String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, stackId);
- RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
+ String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, stackId);
+ RestClient multicloudClient = getMulticloudClient(multicloudEndpoint, tenantId);
if (multicloudClient != null) {
response = multicloudClient.delete();
@@ -327,7 +348,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
returnInfo.setStatus(HeatStatus.NOTFOUND);
returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
} else if (response.getStatus() == Response.Status.NO_CONTENT.getStatusCode()) {
- return getStackStatus(cloudSiteId, tenantId, instanceId);
+ return getStackStatus(cloudSiteId, cloudOwner, tenantId, instanceId);
} else {
returnInfo.setStatus(HeatStatus.FAILED);
returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
@@ -342,24 +363,119 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
// PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
private HeatStatus getHeatStatus(String workloadStatus) {
- if (workloadStatus.length() == 0) return HeatStatus.INIT;
- if ("CREATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.BUILDING;
- if ("CREATE_COMPLETE".equals(workloadStatus)) return HeatStatus.CREATED;
- if ("CREATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
- if ("DELETE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.DELETING;
- if ("DELETE_COMPLETE".equals(workloadStatus)) return HeatStatus.NOTFOUND;
- if ("DELETE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
- if ("UPDATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.UPDATING;
- if ("UPDATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
- if ("UPDATE_COMPLETE".equals(workloadStatus)) return HeatStatus.UPDATED;
+ if (workloadStatus.length() == 0)
+ return HeatStatus.INIT;
+ if ("CREATE_IN_PROGRESS".equals(workloadStatus))
+ return HeatStatus.BUILDING;
+ if ("CREATE_COMPLETE".equals(workloadStatus))
+ return HeatStatus.CREATED;
+ if ("CREATE_FAILED".equals(workloadStatus))
+ return HeatStatus.FAILED;
+ if ("DELETE_IN_PROGRESS".equals(workloadStatus))
+ return HeatStatus.DELETING;
+ if ("DELETE_COMPLETE".equals(workloadStatus))
+ return HeatStatus.NOTFOUND;
+ if ("DELETE_FAILED".equals(workloadStatus))
+ return HeatStatus.FAILED;
+ if ("UPDATE_IN_PROGRESS".equals(workloadStatus))
+ return HeatStatus.UPDATING;
+ if ("UPDATE_FAILED".equals(workloadStatus))
+ return HeatStatus.FAILED;
+ if ("UPDATE_COMPLETE".equals(workloadStatus))
+ return HeatStatus.UPDATED;
return HeatStatus.UNKNOWN;
}
- private StackInfo getStackStatus(String cloudSiteId, String tenantId, String instanceId) throws MsoException {
- return getStackStatus(cloudSiteId, tenantId, instanceId, false, 0, false);
+ private void multicloudAaiUpdate(String cloudSiteId, String cloudOwner, String tenantId, String genericVnfId,
+ String vfModuleId, String workloadId, boolean pollForCompletion, int timeoutMinutes) {
+
+ MulticloudRequest multicloudRequest = new MulticloudRequest();
+
+ multicloudRequest.setGenericVnfId(genericVnfId);
+ multicloudRequest.setVfModuleId(vfModuleId);
+
+ String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, workloadId);
+ RestClient multicloudClient = getMulticloudClient(multicloudEndpoint, tenantId);
+
+ if (multicloudClient == null) {
+ if (logger.isDebugEnabled())
+ logger.debug("Multicloud client could not be initialized");
+ return;
+ }
+
+ Response response = multicloudClient.post(multicloudRequest);
+ if (response.getStatus() != Response.Status.ACCEPTED.getStatusCode()) {
+ if (logger.isDebugEnabled())
+ logger.debug(
+ "Multicloud AAI update request failed: " + response.getStatus() + response.getStatusInfo());
+ return;
+ }
+
+ if (!pollForCompletion) {
+ return;
+ }
+
+ int updatePollInterval =
+ Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
+ int pollTimeout = (timeoutMinutes * 60) + updatePollInterval;
+ boolean updateTimedOut = false;
+ logger.debug("updatePollInterval=" + updatePollInterval + ", pollTimeout=" + pollTimeout);
+
+ StackInfo stackInfo = null;
+ while (true) {
+ try {
+ stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, workloadId);
+ if (logger.isDebugEnabled())
+ logger.debug(stackInfo.getStatus() + " (" + workloadId + ")");
+
+ if (HeatStatus.UPDATING.equals(stackInfo.getStatus())) {
+ if (pollTimeout <= 0) {
+ // Note that this should not occur, since there is a timeout specified
+ // in the Openstack (multicloud?) call.
+ if (logger.isDebugEnabled())
+ logger.debug("Multicloud AAI update timeout failure: {} {} {} {}", cloudOwner, cloudSiteId,
+ tenantId, workloadId);
+ updateTimedOut = true;
+ break;
+ }
+
+ sleep(updatePollInterval * 1000L);
+
+ pollTimeout -= updatePollInterval;
+ if (logger.isDebugEnabled())
+ logger.debug("pollTimeout remaining: " + pollTimeout);
+ } else {
+ break;
+ }
+ } catch (MsoException me) {
+ if (logger.isDebugEnabled())
+ logger.debug("Multicloud AAI update exception: {} {} {} {}", cloudOwner, cloudSiteId, tenantId,
+ workloadId, me);
+ return;
+ }
+ }
+ if (updateTimedOut) {
+ if (logger.isDebugEnabled())
+ logger.debug("Multicloud AAI update request failed: {} {}", response.getStatus(),
+ response.getStatusInfo().toString());
+ } else if (!HeatStatus.UPDATED.equals(stackInfo.getStatus())) {
+ if (logger.isDebugEnabled())
+ logger.debug("Multicloud AAI update request failed: {} {}", response.getStatus(),
+ response.getStatusInfo().toString());
+ } else {
+ if (logger.isDebugEnabled())
+ logger.debug("Multicloud AAI update successful: {} {}", response.getStatus(),
+ response.getStatusInfo().toString());
+ }
+ }
+
+ private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId)
+ throws MsoException {
+ return getStackStatus(cloudSiteId, cloudOwner, tenantId, instanceId, false, 0, false);
}
- private StackInfo getStackStatus(String cloudSiteId, String tenantId, String instanceId, boolean pollForCompletion, int timeoutMinutes, boolean backout) throws MsoException {
+ private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId,
+ boolean pollForCompletion, int timeoutMinutes, boolean backout) throws MsoException {
StackInfo stackInfo = new StackInfo();
// If client has requested a final response, poll for stack completion
@@ -368,7 +484,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
// Use the resource (template) timeout for Openstack (expressed in minutes)
// and add one poll interval to give Openstack a chance to fail on its own.s
- int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
+ int createPollInterval =
+ Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
// New 1610 - poll on delete if we rollback - use same values for now
int deletePollInterval = createPollInterval;
@@ -379,8 +496,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
while (true) {
try {
- stackInfo = queryStack(cloudSiteId, tenantId, instanceId);
- logger.debug (stackInfo.getStatus() + " (" + instanceId + ")");
+ stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
+ logger.debug(stackInfo.getStatus() + " (" + instanceId + ")");
if (HeatStatus.BUILDING.equals(stackInfo.getStatus())) {
// Stack creation is still running.
@@ -388,7 +505,10 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
if (pollTimeout <= 0) {
// Note that this should not occur, since there is a timeout specified
// in the Openstack (multicloud?) call.
- logger.error(String.format("%s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudSiteId, tenantId, instanceId, stackInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(), "Create stack timeout"));
+ logger.error(String.format("%s %s %s %s %s %s %s %s %d %s",
+ MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId,
+ instanceId, stackInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(),
+ "Create stack timeout"));
createTimedOut = true;
break;
}
@@ -398,111 +518,146 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
pollTimeout -= createPollInterval;
logger.debug("pollTimeout remaining: " + pollTimeout);
} else {
- //save off the status & reason msg before we attempt delete
- stackErrorStatusReason.append("Stack error (" + stackInfo.getStatus() + "): " + stackInfo.getStatusMessage());
+ // save off the status & reason msg before we attempt delete
+ stackErrorStatusReason
+ .append("Stack error (" + stackInfo.getStatus() + "): " + stackInfo.getStatusMessage());
break;
}
} catch (MsoException me) {
// Cannot query the stack status. Something is wrong.
// Try to roll back the stack
if (!backout) {
- logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack error, stack deletion suppressed", "", "", ErrorCode.BusinessProcesssError.getValue(), "Exception in Create Stack, stack deletion suppressed"));
+ logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack error, stack deletion suppressed", "", "",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Exception in Create Stack, stack deletion suppressed"));
} else {
try {
- logger.debug("Create Stack error - unable to query for stack status - attempting to delete stack: " + instanceId + " - This will likely fail and/or we won't be able to query to see if delete worked");
- StackInfo deleteInfo = deleteStack(cloudSiteId, tenantId, instanceId);
- // this may be a waste of time - if we just got an exception trying to query the stack - we'll just
+ logger.debug(
+ "Create Stack error - unable to query for stack status - attempting to delete stack: "
+ + instanceId
+ + " - This will likely fail and/or we won't be able to query to see if delete worked");
+ StackInfo deleteInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
+ // this may be a waste of time - if we just got an exception trying to query the stack -
+ // we'll just
// get another one, n'est-ce pas?
boolean deleted = false;
while (!deleted) {
try {
- StackInfo queryInfo = queryStack(cloudSiteId, tenantId, instanceId);
+ StackInfo queryInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
if (deletePollTimeout <= 0) {
- logger.error(String.format("%s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudSiteId, tenantId, instanceId,
- queryInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(),
+ logger.error(String.format("%s %s %s %s %s %s %s %s %d %s",
+ MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner,
+ cloudSiteId, tenantId, instanceId, queryInfo.getStatus(), "", "",
+ ErrorCode.AvailabilityError.getValue(),
"Rollback: DELETE stack timeout"));
break;
} else {
sleep(deletePollInterval * 1000L);
deletePollTimeout -= deletePollInterval;
}
- } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
+ } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())) {
logger.debug("DELETE_COMPLETE for " + instanceId);
deleted = true;
continue;
} else {
- //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
+ // got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and
+ // evaluate
break;
}
} catch (Exception e3) {
// Just log this one. We will report the original exception.
- logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e3, "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack: Nested exception rolling back stack on error on query"));
+ logger.error(String.format("%s %s %s %s %d %s",
+ MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack: Nested exception rolling back stack: " + e3, "", "",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create Stack: Nested exception rolling back stack on error on query"));
}
}
} catch (Exception e2) {
// Just log this one. We will report the original exception.
- logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e2, "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack: Nested exception rolling back stack"));
+ logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack: Nested exception rolling back stack: " + e2, "", "",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create Stack: Nested exception rolling back stack"));
}
}
// Propagate the original exception from Stack Query.
- me.addContext (CREATE_STACK);
+ me.addContext(CREATE_STACK);
throw me;
}
}
if (!HeatStatus.CREATED.equals(stackInfo.getStatus())) {
- logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack error: Polling complete with non-success status: "
- + stackInfo.getStatus () + ", " + stackInfo.getStatusMessage(), "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error"));
+ logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack error: Polling complete with non-success status: " + stackInfo.getStatus() + ", "
+ + stackInfo.getStatusMessage(),
+ "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error"));
// Rollback the stack creation, since it is in an indeterminate state.
if (!backout) {
- logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, stack deletion suppressed", "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error, stack deletion suppressed"));
- }
- else
- {
+ logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack errored, stack deletion suppressed", "", "",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create Stack error, stack deletion suppressed"));
+ } else {
try {
logger.debug("Create Stack errored - attempting to DELETE stack: " + instanceId);
- logger.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout=" + deletePollTimeout);
- StackInfo deleteInfo = deleteStack(cloudSiteId, tenantId, instanceId);
+ logger.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout="
+ + deletePollTimeout);
+ StackInfo deleteInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
boolean deleted = false;
while (!deleted) {
try {
- StackInfo queryInfo = queryStack(cloudSiteId, tenantId, instanceId);
+ StackInfo queryInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
if (deletePollTimeout <= 0) {
- logger.error(String.format("%s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudSiteId, tenantId, instanceId,
- queryInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(),
+ logger.error(String.format("%s %s %s %s %s %s %s %s %d %s",
+ MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId,
+ tenantId, instanceId, queryInfo.getStatus(), "", "",
+ ErrorCode.AvailabilityError.getValue(),
"Rollback: DELETE stack timeout"));
break;
} else {
sleep(deletePollInterval * 1000L);
deletePollTimeout -= deletePollInterval;
}
- } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
+ } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())) {
logger.debug("DELETE_COMPLETE for " + instanceId);
deleted = true;
continue;
} else {
- //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
- logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, stack deletion FAILED", "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error, stack deletion FAILED"));
- logger.debug("Stack deletion FAILED on a rollback of a create - " + instanceId + ", status=" + queryInfo.getStatus() + ", reason=" + queryInfo.getStatusMessage());
+ // got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and
+ // evaluate
+ logger.warn(String.format("%s %s %s %s %d %s",
+ MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack errored, stack deletion FAILED", "", "",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create Stack error, stack deletion FAILED"));
+ logger.debug("Stack deletion FAILED on a rollback of a create - " + instanceId
+ + ", status=" + queryInfo.getStatus() + ", reason="
+ + queryInfo.getStatusMessage());
break;
}
} catch (MsoException me2) {
// Just log this one. We will report the original exception.
- logger.debug("Exception thrown trying to delete " + instanceId + " on a create->rollback: " + me2.getContextMessage(), me2);
- logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, then stack deletion FAILED - exception thrown", "", "", ErrorCode.BusinessProcesssError.getValue(), me2.getContextMessage()));
+ logger.debug("Exception thrown trying to delete " + instanceId
+ + " on a create->rollback: " + me2.getContextMessage(), me2);
+ logger.warn(String.format("%s %s %s %s %d %s",
+ MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack errored, then stack deletion FAILED - exception thrown", "", "",
+ ErrorCode.BusinessProcesssError.getValue(), me2.getContextMessage()));
}
}
StringBuilder errorContextMessage;
if (createTimedOut) {
errorContextMessage = new StringBuilder("Stack Creation Timeout");
} else {
- errorContextMessage = stackErrorStatusReason;
+ errorContextMessage = stackErrorStatusReason;
}
if (deleted) {
errorContextMessage.append(" - stack successfully deleted");
@@ -511,7 +666,10 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
} catch (MsoException e2) {
// shouldn't happen - but handle
- logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e2, "", "", ErrorCode.BusinessProcesssError.getValue(), "Exception in Create Stack: rolling back stack"));
+ logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack: Nested exception rolling back stack: " + e2, "", "",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Exception in Create Stack: rolling back stack"));
}
}
MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
@@ -520,14 +678,16 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
} else {
// Get initial status, since it will have been null after the create.
- stackInfo = queryStack(cloudSiteId, tenantId, instanceId);
+ stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
logger.debug("Multicloud stack query status is: " + stackInfo.getStatus());
}
return stackInfo;
}
private HeatStatus mapResponseToHeatStatus(Response response) {
- if (response.getStatusInfo().getStatusCode() == Response.Status.OK.getStatusCode()) {
+ if (response == null) {
+ return HeatStatus.FAILED;
+ } else if (response.getStatusInfo().getStatusCode() == Response.Status.OK.getStatusCode()) {
return HeatStatus.CREATED;
} else if (response.getStatusInfo().getStatusCode() == Response.Status.CREATED.getStatusCode()) {
return HeatStatus.CREATED;
@@ -580,11 +740,16 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
return null;
}
- private String getMulticloudEndpoint(String cloudSiteId, String workloadId) throws MsoCloudSiteNotFound {
+ private String getMulticloudEndpoint(String cloudSiteId, String cloudOwner, String workloadId) {
+ String msbIp = System.getenv().get(ONAP_IP);
+ if (null == msbIp || msbIp.isEmpty()) {
+ msbIp = environment.getProperty("mso.msb-ip", DEFAULT_MSB_IP);
+ }
+ Integer msbPort = environment.getProperty("mso.msb-port", Integer.class, DEFAULT_MSB_PORT);
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
- String endpoint = cloudSite.getIdentityService().getIdentityUrl();
+ String path = "/api/multicloud/v1/" + cloudOwner + "/" + cloudSiteId + "/infra_workload";
+ String endpoint = UriBuilder.fromPath(path).host(msbIp).port(msbPort).scheme("http").build().toString();
if (workloadId != null) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Multicloud Endpoint is: %s/%s", endpoint, workloadId));
@@ -598,18 +763,22 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
}
- private RestClient getMulticloudClient(String endpoint) {
- RestClient client = null;
+ private RestClient getMulticloudClient(String endpoint, String tenantId) {
+ HttpClient client = null;
try {
- client = httpClientFactory.newJsonClient(
- new URL(endpoint),
- TargetEntity.MULTICLOUD);
+ client = httpClientFactory.newJsonClient(new URL(endpoint), TargetEntity.MULTICLOUD);
+ if (tenantId != null && !tenantId.isEmpty()) {
+ client.addAdditionalHeader("Project", tenantId);
+ }
} catch (MalformedURLException e) {
- logger.debug(String.format("Encountered malformed URL error getting multicloud rest client %s", e.getMessage()));
+ logger.debug(
+ String.format("Encountered malformed URL error getting multicloud rest client %s", e.getMessage()));
} catch (IllegalArgumentException e) {
- logger.debug(String.format("Encountered illegal argument getting multicloud rest client %s",e.getMessage()));
+ logger.debug(
+ String.format("Encountered illegal argument getting multicloud rest client %s", e.getMessage()));
} catch (UriBuilderException e) {
- logger.debug(String.format("Encountered URI builder error getting multicloud rest client %s", e.getMessage()));
+ logger.debug(
+ String.format("Encountered URI builder error getting multicloud rest client %s", e.getMessage()));
}
return client;
}
@@ -618,10 +787,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
try {
return JSON_MAPPER.readTree(directives);
} catch (Exception e) {
- logger.error(String.format("%s %s %s %s %d %s",
- MessageEnum.RA_CREATE_STACK_ERR.toString(),
- "Create Stack: " + e, "", "",
- ErrorCode.BusinessProcesssError.getValue(),
+ logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack: " + e, "", "", ErrorCode.BusinessProcesssError.getValue(),
"Exception in Create Stack: Invalid JSON format of directives" + directives));
MsoException me = new MsoAdapterException("Invalid JSON format of directives parameter: " + directives);
me.addContext(CREATE_STACK);
@@ -632,59 +799,45 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
/**
* VduPlugin interface for instantiate function.
*
- * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
- * and then invoke the existing function.
+ * Translate the VduPlugin parameters to the corresponding 'createStack' parameters, and then invoke the existing
+ * function.
*/
@Override
- public VduInstance instantiateVdu (
- CloudInfo cloudInfo,
- String instanceName,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException
- {
+ public VduInstance instantiateVdu(CloudInfo cloudInfo, String instanceName, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException {
String cloudSiteId = cloudInfo.getCloudSiteId();
+ String cloudOwner = cloudInfo.getCloudOwner();
String tenantId = cloudInfo.getTenantId();
// Translate the VDU ModelInformation structure to that which is needed for
- // creating the Heat stack. Loop through the artifacts, looking specifically
- // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
+ // creating the Heat stack. Loop through the artifacts, looking specifically
+ // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
// be attached as a FILE.
String heatTemplate = null;
- Map<String,Object> nestedTemplates = new HashMap<>();
- Map<String,Object> files = new HashMap<>();
+ Map<String, Object> nestedTemplates = new HashMap<>();
+ Map<String, Object> files = new HashMap<>();
String heatEnvironment = null;
- for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
+ for (VduArtifact vduArtifact : vduModel.getArtifacts()) {
if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
heatTemplate = new String(vduArtifact.getContent());
- }
- else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
+ } else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
- }
- else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
+ } else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
heatEnvironment = new String(vduArtifact.getContent());
}
}
try {
- StackInfo stackInfo = createStack (cloudSiteId,
- tenantId,
- instanceName,
- heatTemplate,
- inputs,
- true, // poll for completion
- vduModel.getTimeoutMinutes(),
- heatEnvironment,
- nestedTemplates,
- files,
- rollbackOnFailure);
+ StackInfo stackInfo =
+ createStack(cloudSiteId, cloudOwner, tenantId, instanceName, vduModel, heatTemplate, inputs, true, // poll
+ // for
+ // completion
+ vduModel.getTimeoutMinutes(), heatEnvironment, nestedTemplates, files, rollbackOnFailure);
// Populate a vduInstance from the StackInfo
return stackInfoToVduInstance(stackInfo);
- }
- catch (Exception e) {
- throw new VduException ("MsoMulticloudUtils (instantiateVDU): createStack Exception", e);
+ } catch (Exception e) {
+ throw new VduException("MsoMulticloudUtils (instantiateVDU): createStack Exception", e);
}
}
@@ -693,20 +846,18 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
* VduPlugin interface for query function.
*/
@Override
- public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
- throws VduException
- {
+ public VduInstance queryVdu(CloudInfo cloudInfo, String instanceId) throws VduException {
String cloudSiteId = cloudInfo.getCloudSiteId();
+ String cloudOwner = cloudInfo.getCloudOwner();
String tenantId = cloudInfo.getTenantId();
try {
- // Query the Cloudify Deployment object and populate a VduInstance
- StackInfo stackInfo = queryStack (cloudSiteId, tenantId, instanceId);
+ // Query the Cloudify Deployment object and populate a VduInstance
+ StackInfo stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
return stackInfoToVduInstance(stackInfo);
- }
- catch (Exception e) {
- throw new VduException ("MsoMulticloudUtils (queryVdu): queryStack Exception ", e);
+ } catch (Exception e) {
+ throw new VduException("MsoMulticloudUtils (queryVdu): queryStack Exception ", e);
}
}
@@ -715,15 +866,14 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
* VduPlugin interface for delete function.
*/
@Override
- public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
- throws VduException
- {
+ public VduInstance deleteVdu(CloudInfo cloudInfo, String instanceId, int timeoutMinutes) throws VduException {
String cloudSiteId = cloudInfo.getCloudSiteId();
+ String cloudOwner = cloudInfo.getCloudOwner();
String tenantId = cloudInfo.getTenantId();
try {
// Delete the Multicloud stack
- StackInfo stackInfo = deleteStack (cloudSiteId, tenantId, instanceId);
+ StackInfo stackInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
// Populate a VduInstance based on the deleted Cloudify Deployment object
VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
@@ -732,9 +882,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
vduInstance.getStatus().setState(VduStateType.DELETED);
return vduInstance;
- }
- catch (Exception e) {
- throw new VduException ("Delete VDU Exception", e);
+ } catch (Exception e) {
+ throw new VduException("Delete VDU Exception", e);
}
}
@@ -742,28 +891,21 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
/**
* VduPlugin interface for update function.
*
- * Update is currently not supported in the MsoMulticloudUtils implementation of VduPlugin.
- * Just return a VduException.
+ * Update is currently not supported in the MsoMulticloudUtils implementation of VduPlugin. Just return a
+ * VduException.
*
*/
@Override
- public VduInstance updateVdu (
- CloudInfo cloudInfo,
- String instanceId,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException
- {
- throw new VduException ("MsoMulticloudUtils: updateVdu interface not supported");
+ public VduInstance updateVdu(CloudInfo cloudInfo, String instanceId, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException {
+ throw new VduException("MsoMulticloudUtils: updateVdu interface not supported");
}
/*
* Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
*/
- protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
- {
+ protected VduInstance stackInfoToVduInstance(StackInfo stackInfo) {
VduInstance vduInstance = new VduInstance();
if (logger.isDebugEnabled()) {
@@ -778,13 +920,12 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
vduInstance.setOutputs(stackInfo.getOutputs());
// Translate the status elements
- vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
+ vduInstance.setStatus(stackStatusToVduStatus(stackInfo));
return vduInstance;
}
- private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
- {
+ private VduStatus stackStatusToVduStatus(StackInfo stackInfo) {
VduStatus vduStatus = new VduStatus();
// Map the status fields to more generic VduStatus.
@@ -798,30 +939,24 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
logger.debug(String.format("Stack Status Message: %s", statusMessage));
}
- if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
+ if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
vduStatus.setState(VduStateType.INSTANTIATING);
- vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
- }
- else if (heatStatus == HeatStatus.NOTFOUND) {
+ vduStatus.setLastAction((new PluginAction("create", "in_progress", statusMessage)));
+ } else if (heatStatus == HeatStatus.NOTFOUND) {
vduStatus.setState(VduStateType.NOTFOUND);
- }
- else if (heatStatus == HeatStatus.CREATED) {
+ } else if (heatStatus == HeatStatus.CREATED) {
vduStatus.setState(VduStateType.INSTANTIATED);
- vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
- }
- else if (heatStatus == HeatStatus.UPDATED) {
+ vduStatus.setLastAction((new PluginAction("create", "complete", statusMessage)));
+ } else if (heatStatus == HeatStatus.UPDATED) {
vduStatus.setState(VduStateType.INSTANTIATED);
- vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
- }
- else if (heatStatus == HeatStatus.UPDATING) {
+ vduStatus.setLastAction((new PluginAction("update", "complete", statusMessage)));
+ } else if (heatStatus == HeatStatus.UPDATING) {
vduStatus.setState(VduStateType.UPDATING);
- vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
- }
- else if (heatStatus == HeatStatus.DELETING) {
+ vduStatus.setLastAction((new PluginAction("update", "in_progress", statusMessage)));
+ } else if (heatStatus == HeatStatus.DELETING) {
vduStatus.setState(VduStateType.DELETING);
- vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
- }
- else if (heatStatus == HeatStatus.FAILED) {
+ vduStatus.setLastAction((new PluginAction("delete", "in_progress", statusMessage)));
+ } else if (heatStatus == HeatStatus.FAILED) {
vduStatus.setState(VduStateType.FAILED);
vduStatus.setErrorMessage(stackInfo.getStatusMessage());
} else {
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java
index 22ce6d9781..78db27f65e 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java
@@ -23,21 +23,10 @@
package org.onap.so.openstack.utils;
-import com.woorea.openstack.base.client.OpenStackBaseException;
-import com.woorea.openstack.base.client.OpenStackConnectException;
-import com.woorea.openstack.base.client.OpenStackRequest;
-import com.woorea.openstack.base.client.OpenStackResponseException;
-import com.woorea.openstack.keystone.Keystone;
-import com.woorea.openstack.keystone.model.Access;
-import com.woorea.openstack.keystone.model.Authentication;
-import com.woorea.openstack.keystone.utils.KeystoneUtils;
-import com.woorea.openstack.quantum.Quantum;
-import com.woorea.openstack.quantum.model.Network;
-import com.woorea.openstack.quantum.model.Networks;
-import com.woorea.openstack.quantum.model.Segment;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
+import java.util.Optional;
import org.onap.so.cloud.CloudConfig;
import org.onap.so.cloud.authentication.AuthenticationMethodFactory;
import org.onap.so.cloud.authentication.KeystoneAuthHolder;
@@ -61,478 +50,510 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
+import com.woorea.openstack.base.client.OpenStackBaseException;
+import com.woorea.openstack.base.client.OpenStackConnectException;
+import com.woorea.openstack.base.client.OpenStackRequest;
+import com.woorea.openstack.base.client.OpenStackResponseException;
+import com.woorea.openstack.keystone.Keystone;
+import com.woorea.openstack.keystone.model.Access;
+import com.woorea.openstack.keystone.model.Authentication;
+import com.woorea.openstack.keystone.utils.KeystoneUtils;
+import com.woorea.openstack.quantum.Quantum;
+import com.woorea.openstack.quantum.model.Network;
+import com.woorea.openstack.quantum.model.Networks;
+import com.woorea.openstack.quantum.model.Port;
+import com.woorea.openstack.quantum.model.Segment;
@Component
-public class MsoNeutronUtils extends MsoCommonUtils
-{
+public class MsoNeutronUtils extends MsoCommonUtils {
- // Fetch cloud configuration each time (may be cached in CloudConfig class)
- @Autowired
- private CloudConfig cloudConfig;
+ // Fetch cloud configuration each time (may be cached in CloudConfig class)
+ @Autowired
+ private CloudConfig cloudConfig;
- @Autowired
+ @Autowired
private AuthenticationMethodFactory authenticationMethodFactory;
-
- @Autowired
- private MsoTenantUtilsFactory tenantUtilsFactory;
- @Autowired
- private KeystoneV3Authentication keystoneV3Authentication;
+ @Autowired
+ private MsoTenantUtilsFactory tenantUtilsFactory;
+
+ @Autowired
+ private KeystoneV3Authentication keystoneV3Authentication;
private static Logger logger = LoggerFactory.getLogger(MsoNeutronUtils.class);
public enum NetworkType {
- BASIC, PROVIDER, MULTI_PROVIDER
- };
-
- /**
- * Create a network with the specified parameters in the given cloud/tenant.
- *
- * If a network already exists with the same name, an exception will be thrown. Note that
- * this is an MSO-imposed restriction. Openstack does not require uniqueness on network names.
- * <p>
- * @param cloudSiteId The cloud identifier (may be a region) in which to create the network.
- * @param tenantId The tenant in which to create the network
- * @param type The type of network to create (Basic, Provider, Multi-Provider)
- * @param networkName The network name to create
- * @param provider The provider network name (for Provider or Multi-Provider networks)
- * @param vlans A list of VLAN segments for the network (for Provider or Multi-Provider networks)
- * @return a NetworkInfo object which describes the newly created network
- * @throws MsoNetworkAlreadyExists Thrown if a network with the same name already exists
- * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
- * @throws MsoCloudSiteNotFound Thrown if the cloudSite is invalid or unknown
- */
- public NetworkInfo createNetwork (String cloudSiteId, String tenantId, NetworkType type, String networkName, String provider, List<Integer> vlans)
- throws MsoException
- {
- // Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
-
- Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
- // Check if a network already exists with this name
- // Openstack will allow duplicate name, so require explicit check
- Network network = findNetworkByName (neutronClient, networkName);
-
- if (network != null) {
- // Network already exists. Throw an exception
- logger.error("{} Network {} on Cloud site {} for tenant {} already exists {}",
- MessageEnum.RA_NETWORK_ALREADY_EXIST, networkName, cloudSiteId, tenantId,
- ErrorCode.DataError.getValue());
- throw new MsoNetworkAlreadyExists (networkName, tenantId, cloudSiteId);
- }
-
- // Does not exist, create a new one
- network = new Network();
- network.setName(networkName);
- network.setAdminStateUp(true);
-
- if (type == NetworkType.PROVIDER) {
- if (provider != null && vlans != null && vlans.size() > 0) {
- network.setProviderPhysicalNetwork (provider);
- network.setProviderNetworkType("vlan");
- network.setProviderSegmentationId (vlans.get(0));
- }
- } else if (type == NetworkType.MULTI_PROVIDER) {
- if (provider != null && vlans != null && vlans.size() > 0) {
- List<Segment> segments = new ArrayList<>(vlans.size());
- for (int vlan : vlans) {
- Segment segment = new Segment();
- segment.setProviderPhysicalNetwork (provider);
- segment.setProviderNetworkType("vlan");
- segment.setProviderSegmentationId (vlan);
-
- segments.add(segment);
- }
- network.setSegments(segments);
- }
- }
-
- try {
- OpenStackRequest<Network> request = neutronClient.networks().create(network);
- Network newNetwork = executeAndRecordOpenstackRequest(request);
- return new NetworkInfoMapper(newNetwork).map();
- }
- catch (OpenStackBaseException e) {
- // Convert Neutron exception to an MsoOpenstackException
- MsoException me = neutronExceptionToMsoException (e, "CreateNetwork");
- throw me;
- }
- catch (RuntimeException e) {
- // Catch-all
- MsoException me = runtimeExceptionToMsoException(e, "CreateNetwork");
- throw me;
- }
- }
-
-
- /**
- * Query for a network with the specified name or ID in the given cloud. If the network exists,
- * return an NetworkInfo object. If not, return null.
- * <p>
- * Whenever possible, the network ID should be used as it is much more efficient. Query by
- * name requires retrieval of all networks for the tenant and search for matching name.
- * <p>
- * @param networkNameOrId The network to query
- * @param tenantId The Openstack tenant to look in for the network
- * @param cloudSiteId The cloud identifier (may be a region) in which to query the network.
- * @return a NetworkInfo object describing the queried network, or null if not found
- * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
- * @throws MsoCloudSiteNotFound
- */
- public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException
- {
- logger.debug("In queryNetwork");
-
- // Obtain the cloud site information
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
-
- Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
- // Check if the network exists and return its info
- try {
- Network network = findNetworkByNameOrId (neutronClient, networkNameOrId);
- if (network == null) {
- logger.debug("Query Network: {} not found in tenant {}", networkNameOrId, tenantId);
- return null;
- }
- return new NetworkInfoMapper(network).map();
- }
- catch (OpenStackBaseException e) {
- // Convert Neutron exception to an MsoOpenstackException
- MsoException me = neutronExceptionToMsoException (e, "QueryNetwork");
- throw me;
- }
- catch (RuntimeException e) {
- // Catch-all
- MsoException me = runtimeExceptionToMsoException(e, "QueryNetwork");
- throw me;
- }
- }
-
- /**
- * Delete the specified Network (by ID) in the given cloud.
- * If the network does not exist, success is returned.
- * <p>
- * @param networkId Openstack ID of the network to delete
- * @param tenantId The Openstack tenant.
- * @param cloudSiteId The cloud identifier (may be a region) from which to delete the network.
- * @return true if the network was deleted, false if the network did not exist
- * @throws MsoOpenstackException If the Openstack API call returns an exception, this local
- * exception will be thrown.
- * @throws MsoCloudSiteNotFound
- */
- public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException
- {
- // Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
- Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
- try {
- // Check that the network exists.
- Network network = findNetworkById (neutronClient, networkId);
- if (network == null) {
- logger.info("{} Network not found! Network id: {} Cloud site: {} Tenant: {} ",
- MessageEnum.RA_DELETE_NETWORK_EXC, networkId, cloudSiteId, tenantId);
- return false;
- }
-
- OpenStackRequest<Void> request = neutronClient.networks().delete(network.getId());
- executeAndRecordOpenstackRequest(request);
-
- logger.debug("Deleted Network {} ({})", network.getId(), network.getName());
+ BASIC, PROVIDER, MULTI_PROVIDER
+ };
+
+ /**
+ * Create a network with the specified parameters in the given cloud/tenant.
+ *
+ * If a network already exists with the same name, an exception will be thrown. Note that this is an MSO-imposed
+ * restriction. Openstack does not require uniqueness on network names.
+ * <p>
+ *
+ * @param cloudSiteId The cloud identifier (may be a region) in which to create the network.
+ * @param tenantId The tenant in which to create the network
+ * @param type The type of network to create (Basic, Provider, Multi-Provider)
+ * @param networkName The network name to create
+ * @param provider The provider network name (for Provider or Multi-Provider networks)
+ * @param vlans A list of VLAN segments for the network (for Provider or Multi-Provider networks)
+ * @return a NetworkInfo object which describes the newly created network
+ * @throws MsoNetworkAlreadyExists Thrown if a network with the same name already exists
+ * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
+ * @throws MsoCloudSiteNotFound Thrown if the cloudSite is invalid or unknown
+ */
+ public NetworkInfo createNetwork(String cloudSiteId, String tenantId, NetworkType type, String networkName,
+ String provider, List<Integer> vlans) throws MsoException {
+ // Obtain the cloud site information where we will create the stack
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+
+ Quantum neutronClient = getNeutronClient(cloudSite, tenantId);
+
+ // Check if a network already exists with this name
+ // Openstack will allow duplicate name, so require explicit check
+ Network network = findNetworkByName(neutronClient, networkName);
+
+ if (network != null) {
+ // Network already exists. Throw an exception
+ logger.error("{} Network {} on Cloud site {} for tenant {} already exists {}",
+ MessageEnum.RA_NETWORK_ALREADY_EXIST, networkName, cloudSiteId, tenantId,
+ ErrorCode.DataError.getValue());
+ throw new MsoNetworkAlreadyExists(networkName, tenantId, cloudSiteId);
+ }
+
+ // Does not exist, create a new one
+ network = new Network();
+ network.setName(networkName);
+ network.setAdminStateUp(true);
+
+ if (type == NetworkType.PROVIDER) {
+ if (provider != null && vlans != null && vlans.size() > 0) {
+ network.setProviderPhysicalNetwork(provider);
+ network.setProviderNetworkType("vlan");
+ network.setProviderSegmentationId(vlans.get(0));
+ }
+ } else if (type == NetworkType.MULTI_PROVIDER) {
+ if (provider != null && vlans != null && vlans.size() > 0) {
+ List<Segment> segments = new ArrayList<>(vlans.size());
+ for (int vlan : vlans) {
+ Segment segment = new Segment();
+ segment.setProviderPhysicalNetwork(provider);
+ segment.setProviderNetworkType("vlan");
+ segment.setProviderSegmentationId(vlan);
+
+ segments.add(segment);
+ }
+ network.setSegments(segments);
+ }
+ }
+
+ try {
+ OpenStackRequest<Network> request = neutronClient.networks().create(network);
+ Network newNetwork = executeAndRecordOpenstackRequest(request);
+ return new NetworkInfoMapper(newNetwork).map();
+ } catch (OpenStackBaseException e) {
+ // Convert Neutron exception to an MsoOpenstackException
+ MsoException me = neutronExceptionToMsoException(e, "CreateNetwork");
+ throw me;
+ } catch (RuntimeException e) {
+ // Catch-all
+ MsoException me = runtimeExceptionToMsoException(e, "CreateNetwork");
+ throw me;
+ }
+ }
+
+
+ /**
+ * Query for a network with the specified name or ID in the given cloud. If the network exists, return an
+ * NetworkInfo object. If not, return null.
+ * <p>
+ * Whenever possible, the network ID should be used as it is much more efficient. Query by name requires retrieval
+ * of all networks for the tenant and search for matching name.
+ * <p>
+ *
+ * @param networkNameOrId The network to query
+ * @param tenantId The Openstack tenant to look in for the network
+ * @param cloudSiteId The cloud identifier (may be a region) in which to query the network.
+ * @return a NetworkInfo object describing the queried network, or null if not found
+ * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
+ * @throws MsoCloudSiteNotFound
+ */
+ public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException {
+ logger.debug("In queryNetwork");
+
+ // Obtain the cloud site information
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+
+ Quantum neutronClient = getNeutronClient(cloudSite, tenantId);
+
+ // Check if the network exists and return its info
+ try {
+ Network network = findNetworkByNameOrId(neutronClient, networkNameOrId);
+ if (network == null) {
+ logger.debug("Query Network: {} not found in tenant {}", networkNameOrId, tenantId);
+ return null;
+ }
+ return new NetworkInfoMapper(network).map();
+ } catch (OpenStackBaseException e) {
+ // Convert Neutron exception to an MsoOpenstackException
+ MsoException me = neutronExceptionToMsoException(e, "QueryNetwork");
+ throw me;
+ } catch (RuntimeException e) {
+ // Catch-all
+ MsoException me = runtimeExceptionToMsoException(e, "QueryNetwork");
+ throw me;
+ }
+ }
+
+ public Optional<Port> getNeutronPort(String neutronPortId, String tenantId, String cloudSiteId) {
+ try {
+ logger.debug("Finding Neutron port:" + neutronPortId);
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Quantum neutronClient = getNeutronClient(cloudSite, tenantId);
+ Port port = findPortById(neutronClient, neutronPortId);
+ if (port == null) {
+ return Optional.empty();
+ }
+ return Optional.of(port);
+ } catch (RuntimeException | MsoException e) {
+ logger.error("Error retrieving neutron port", e);
+ return Optional.empty();
+ }
+ }
+
+ /**
+ * Delete the specified Network (by ID) in the given cloud. If the network does not exist, success is returned.
+ * <p>
+ *
+ * @param networkId Openstack ID of the network to delete
+ * @param tenantId The Openstack tenant.
+ * @param cloudSiteId The cloud identifier (may be a region) from which to delete the network.
+ * @return true if the network was deleted, false if the network did not exist
+ * @throws MsoOpenstackException If the Openstack API call returns an exception, this local exception will be
+ * thrown.
+ * @throws MsoCloudSiteNotFound
+ */
+ public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException {
+ // Obtain the cloud site information where we will create the stack
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Quantum neutronClient = getNeutronClient(cloudSite, tenantId);
+
+ try {
+ // Check that the network exists.
+ Network network = findNetworkById(neutronClient, networkId);
+ if (network == null) {
+ logger.info("{} Network not found! Network id: {} Cloud site: {} Tenant: {} ",
+ MessageEnum.RA_DELETE_NETWORK_EXC, networkId, cloudSiteId, tenantId);
+ return false;
+ }
+
+ OpenStackRequest<Void> request = neutronClient.networks().delete(network.getId());
+ executeAndRecordOpenstackRequest(request);
+
+ logger.debug("Deleted Network {} ({})", network.getId(), network.getName());
+ } catch (OpenStackBaseException e) {
+ // Convert Neutron exception to an MsoOpenstackException
+ MsoException me = neutronExceptionToMsoException(e, "Delete Network");
+ throw me;
+ } catch (RuntimeException e) {
+ // Catch-all
+ MsoException me = runtimeExceptionToMsoException(e, "DeleteNetwork");
+ throw me;
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Update a network with the specified parameters in the given cloud/tenant.
+ *
+ * Specifically, this call is intended to update the VLAN segments on a multi-provider network. The provider
+ * segments will be replaced with the supplied list of VLANs.
+ * <p>
+ * Note that updating the 'segments' array is not normally supported by Neutron. This method relies on a Platform
+ * Orchestration extension (using SDN controller to manage the virtual networking).
+ *
+ * @param cloudSiteId The cloud site ID (may be a region) in which to update the network.
+ * @param tenantId Openstack ID of the tenant in which to update the network
+ * @param networkId The unique Openstack ID of the network to be updated
+ * @param type The network type (Basic, Provider, Multi-Provider)
+ * @param provider The provider network name. This should not change.
+ * @param vlans The list of VLAN segments to replace
+ * @return a NetworkInfo object which describes the updated network
+ * @throws MsoNetworkNotFound Thrown if the requested network does not exist
+ * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
+ * @throws MsoCloudSiteNotFound
+ */
+ public NetworkInfo updateNetwork(String cloudSiteId, String tenantId, String networkId, NetworkType type,
+ String provider, List<Integer> vlans) throws MsoException {
+ // Obtain the cloud site information where we will create the stack
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Quantum neutronClient = getNeutronClient(cloudSite, tenantId);
+
+ // Check that the network exists
+ Network network = findNetworkById(neutronClient, networkId);
+
+ if (network == null) {
+ // Network not found. Throw an exception
+ logger.error("{} Network {} on Cloud site {} for Tenant {} not found {}", MessageEnum.RA_NETWORK_NOT_FOUND,
+ networkId, cloudSiteId, tenantId, ErrorCode.DataError.getValue());
+ throw new MsoNetworkNotFound(networkId, tenantId, cloudSiteId);
+ }
+
+ // Overwrite the properties to be updated
+ if (type == NetworkType.PROVIDER) {
+ if (provider != null && vlans != null && vlans.size() > 0) {
+ network.setProviderPhysicalNetwork(provider);
+ network.setProviderNetworkType("vlan");
+ network.setProviderSegmentationId(vlans.get(0));
+ }
+ } else if (type == NetworkType.MULTI_PROVIDER) {
+ if (provider != null && vlans != null && vlans.size() > 0) {
+ List<Segment> segments = new ArrayList<>(vlans.size());
+ for (int vlan : vlans) {
+ Segment segment = new Segment();
+ segment.setProviderPhysicalNetwork(provider);
+ segment.setProviderNetworkType("vlan");
+ segment.setProviderSegmentationId(vlan);
+
+ segments.add(segment);
+ }
+ network.setSegments(segments);
+ }
+ }
+
+ try {
+ OpenStackRequest<Network> request = neutronClient.networks().update(network);
+ Network newNetwork = executeAndRecordOpenstackRequest(request);
+ return new NetworkInfoMapper(newNetwork).map();
+ } catch (OpenStackBaseException e) {
+ // Convert Neutron exception to an MsoOpenstackException
+ MsoException me = neutronExceptionToMsoException(e, "UpdateNetwork");
+ throw me;
+ } catch (RuntimeException e) {
+ // Catch-all
+ MsoException me = runtimeExceptionToMsoException(e, "UpdateNetwork");
+ throw me;
+ }
}
- catch (OpenStackBaseException e) {
- // Convert Neutron exception to an MsoOpenstackException
- MsoException me = neutronExceptionToMsoException (e, "Delete Network");
- throw me;
- }
- catch (RuntimeException e) {
- // Catch-all
- MsoException me = runtimeExceptionToMsoException(e, "DeleteNetwork");
- throw me;
- }
-
- return true;
- }
-
-
- /**
- * Update a network with the specified parameters in the given cloud/tenant.
- *
- * Specifically, this call is intended to update the VLAN segments on a
- * multi-provider network. The provider segments will be replaced with the
- * supplied list of VLANs.
- * <p>
- * Note that updating the 'segments' array is not normally supported by Neutron.
- * This method relies on a Platform Orchestration extension (using SDN controller
- * to manage the virtual networking).
- *
- * @param cloudSiteId The cloud site ID (may be a region) in which to update the network.
- * @param tenantId Openstack ID of the tenant in which to update the network
- * @param networkId The unique Openstack ID of the network to be updated
- * @param type The network type (Basic, Provider, Multi-Provider)
- * @param provider The provider network name. This should not change.
- * @param vlans The list of VLAN segments to replace
- * @return a NetworkInfo object which describes the updated network
- * @throws MsoNetworkNotFound Thrown if the requested network does not exist
- * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
- * @throws MsoCloudSiteNotFound
- */
- public NetworkInfo updateNetwork (String cloudSiteId, String tenantId, String networkId, NetworkType type, String provider, List<Integer> vlans)
- throws MsoException
- {
- // Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
- Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
- // Check that the network exists
- Network network = findNetworkById (neutronClient, networkId);
-
- if (network == null) {
- // Network not found. Throw an exception
- logger.error("{} Network {} on Cloud site {} for Tenant {} not found {}", MessageEnum.RA_NETWORK_NOT_FOUND,
- networkId, cloudSiteId, tenantId, ErrorCode.DataError.getValue());
- throw new MsoNetworkNotFound (networkId, tenantId, cloudSiteId);
- }
-
- // Overwrite the properties to be updated
- if (type == NetworkType.PROVIDER) {
- if (provider != null && vlans != null && vlans.size() > 0) {
- network.setProviderPhysicalNetwork (provider);
- network.setProviderNetworkType("vlan");
- network.setProviderSegmentationId (vlans.get(0));
- }
- } else if (type == NetworkType.MULTI_PROVIDER) {
- if (provider != null && vlans != null && vlans.size() > 0) {
- List<Segment> segments = new ArrayList<>(vlans.size());
- for (int vlan : vlans) {
- Segment segment = new Segment();
- segment.setProviderPhysicalNetwork (provider);
- segment.setProviderNetworkType("vlan");
- segment.setProviderSegmentationId (vlan);
-
- segments.add(segment);
- }
- network.setSegments(segments);
- }
- }
-
- try {
- OpenStackRequest<Network> request = neutronClient.networks().update(network);
- Network newNetwork = executeAndRecordOpenstackRequest(request);
- return new NetworkInfoMapper(newNetwork).map();
- }
- catch (OpenStackBaseException e) {
- // Convert Neutron exception to an MsoOpenstackException
- MsoException me = neutronExceptionToMsoException (e, "UpdateNetwork");
- throw me;
- }
- catch (RuntimeException e) {
- // Catch-all
- MsoException me = runtimeExceptionToMsoException(e, "UpdateNetwork");
- throw me;
- }
- }
-
-
- // -------------------------------------------------------------------
- // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
-
- /**
- * Get a Neutron (Quantum) client for the Openstack Network service.
- * This requires a 'member'-level userId + password, which will be retrieved from
- * properties based on the specified cloud Id. The tenant in which to operate
- * must also be provided.
- * <p>
- * On successful authentication, the Quantum object will be cached for the
- * tenantID + cloudId so that it can be reused without reauthenticating with
- * Openstack every time.
- *
- * @param cloudSite - a cloud site definition
- * @param tenantId - Openstack tenant ID
- * @return an authenticated Quantum object
- */
- private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException
- {
- String cloudId = cloudSite.getId();
- String region = cloudSite.getRegionId();
-
-
- // Obtain an MSO token for the tenant from the identity service
- CloudIdentity cloudIdentity = cloudSite.getIdentityService();
- MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
+
+
+ // -------------------------------------------------------------------
+ // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
+
+ /**
+ * Get a Neutron (Quantum) client for the Openstack Network service. This requires a 'member'-level userId +
+ * password, which will be retrieved from properties based on the specified cloud Id. The tenant in which to operate
+ * must also be provided.
+ * <p>
+ * On successful authentication, the Quantum object will be cached for the tenantID + cloudId so that it can be
+ * reused without reauthenticating with Openstack every time.
+ *
+ * @param cloudSite - a cloud site definition
+ * @param tenantId - Openstack tenant ID
+ * @return an authenticated Quantum object
+ */
+ private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException {
+ String cloudId = cloudSite.getId();
+ String region = cloudSite.getRegionId();
+
+
+ // Obtain an MSO token for the tenant from the identity service
+ CloudIdentity cloudIdentity = cloudSite.getIdentityService();
+ MsoTenantUtils tenantUtils =
+ tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
final String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
- String neutronUrl = null;
- String tokenId = null;
- Calendar expiration = null;
- try {
- if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
- Keystone keystoneTenantClient = new Keystone(keystoneUrl);
- Access access = null;
-
- Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
- OpenStackRequest<Access> request = keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId);
- access = executeAndRecordOpenstackRequest(request);
-
-
- try {
- neutronUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "network", region, "public");
- if (! neutronUrl.endsWith("/")) {
- neutronUrl += "/v2.0/";
- }
- } catch (RuntimeException e) {
- // This comes back for not found (probably an incorrect region ID)
- String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
- throw new MsoAdapterException (error, e);
- }
- tokenId = access.getToken().getId();
- expiration = access.getToken().getExpires();
- } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
- try {
- KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "network");
- tokenId = holder.getId();
- expiration = holder.getexpiration();
- neutronUrl = holder.getServiceUrl();
- if (! neutronUrl.endsWith("/")) {
- neutronUrl += "/v2.0/";
- }
- } catch (ServiceEndpointNotFoundException e) {
- // This comes back for not found (probably an incorrect region ID)
- String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
- throw new MsoAdapterException (error, e);
- }
- }
- }
- catch (OpenStackResponseException e) {
- if (e.getStatus() == 401) {
- // Authentication error.
- String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId();
-
- throw new MsoAdapterException(error);
- }
- else {
- MsoException me = keystoneErrorToMsoException(e, "TokenAuth");
- throw me;
- }
- }
- catch (OpenStackConnectException e) {
- // Connection to Openstack failed
- MsoIOException me = new MsoIOException (e.getMessage(), e);
- me.addContext("TokenAuth");
- throw me;
- }
- catch (RuntimeException e) {
- // Catch-all
- MsoException me = runtimeExceptionToMsoException(e, "TokenAuth");
- throw me;
- }
-
- Quantum neutronClient = new Quantum(neutronUrl);
- neutronClient.token(tokenId);
- return neutronClient;
- }
-
- /*
- * Find a tenant (or query its existence) by its Name or Id. Check first against the
- * ID. If that fails, then try by name.
- *
- * @param adminClient an authenticated Keystone object
- * @param tenantName the tenant name or ID to query
- * @return a Tenant object or null if not found
- */
- public Network findNetworkByNameOrId (Quantum neutronClient, String networkNameOrId)
- {
- if (networkNameOrId == null) {
+ String neutronUrl = null;
+ String tokenId = null;
+ Calendar expiration = null;
+ try {
+ if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
+ Keystone keystoneTenantClient = new Keystone(keystoneUrl);
+ Access access = null;
+
+ Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
+ OpenStackRequest<Access> request =
+ keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId);
+ access = executeAndRecordOpenstackRequest(request);
+
+
+ try {
+ neutronUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "network", region, "public");
+ if (!neutronUrl.endsWith("/")) {
+ neutronUrl += "/v2.0/";
+ }
+ } catch (RuntimeException e) {
+ // This comes back for not found (probably an incorrect region ID)
+ String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
+ throw new MsoAdapterException(error, e);
+ }
+ tokenId = access.getToken().getId();
+ expiration = access.getToken().getExpires();
+ } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
+ try {
+ KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "network");
+ tokenId = holder.getId();
+ expiration = holder.getexpiration();
+ neutronUrl = holder.getServiceUrl();
+ if (!neutronUrl.endsWith("/")) {
+ neutronUrl += "/v2.0/";
+ }
+ } catch (ServiceEndpointNotFoundException e) {
+ // This comes back for not found (probably an incorrect region ID)
+ String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
+ throw new MsoAdapterException(error, e);
+ }
+ }
+ } catch (OpenStackResponseException e) {
+ if (e.getStatus() == 401) {
+ // Authentication error.
+ String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId();
+
+ throw new MsoAdapterException(error);
+ } else {
+ MsoException me = keystoneErrorToMsoException(e, "TokenAuth");
+ throw me;
+ }
+ } catch (OpenStackConnectException e) {
+ // Connection to Openstack failed
+ MsoIOException me = new MsoIOException(e.getMessage(), e);
+ me.addContext("TokenAuth");
+ throw me;
+ } catch (RuntimeException e) {
+ // Catch-all
+ MsoException me = runtimeExceptionToMsoException(e, "TokenAuth");
+ throw me;
+ }
+
+ Quantum neutronClient = new Quantum(neutronUrl);
+ neutronClient.token(tokenId);
+ return neutronClient;
+ }
+
+ /*
+ * Find a tenant (or query its existence) by its Name or Id. Check first against the ID. If that fails, then try by
+ * name.
+ *
+ * @param adminClient an authenticated Keystone object
+ *
+ * @param tenantName the tenant name or ID to query
+ *
+ * @return a Tenant object or null if not found
+ */
+ public Network findNetworkByNameOrId(Quantum neutronClient, String networkNameOrId) {
+ if (networkNameOrId == null) {
return null;
}
- Network network = findNetworkById(neutronClient, networkNameOrId);
+ Network network = findNetworkById(neutronClient, networkNameOrId);
- if (network == null) {
+ if (network == null) {
network = findNetworkByName(neutronClient, networkNameOrId);
}
- return network;
- }
-
- /*
- * Find a network (or query its existence) by its Id.
- *
- * @param neutronClient an authenticated Quantum object
- * @param networkId the network ID to query
- * @return a Network object or null if not found
- */
- private Network findNetworkById (Quantum neutronClient, String networkId)
- {
- if (networkId == null) {
+ return network;
+ }
+
+ /*
+ * Find a network (or query its existence) by its Id.
+ *
+ * @param neutronClient an authenticated Quantum object
+ *
+ * @param networkId the network ID to query
+ *
+ * @return a Network object or null if not found
+ */
+ private Network findNetworkById(Quantum neutronClient, String networkId) {
+ if (networkId == null) {
return null;
}
- try {
- OpenStackRequest<Network> request = neutronClient.networks().show(networkId);
- Network network = executeAndRecordOpenstackRequest(request);
- return network;
- }
- catch (OpenStackResponseException e) {
- if (e.getStatus() == 404) {
- return null;
- } else {
- logger.error("{} {} Openstack Error, GET Network By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), networkId, e);
- throw e;
- }
- }
- }
-
- /*
- * Find a network (or query its existence) by its Name. This method avoids an
- * initial lookup by ID when it's known that we have the network Name.
- *
- * Neutron does not support 'name=*' query parameter for Network query (show).
- * The only way to query by name is to retrieve all networks and look for the
- * match. While inefficient, this capability will be provided as it is needed
- * by MSO, but should be avoided in favor of ID whenever possible.
- *
- * TODO:
- * Network names are not required to be unique, though MSO will attempt to enforce
- * uniqueness. This call probably needs to return an error (instead of returning
- * the first match).
- *
- * @param neutronClient an authenticated Quantum object
- * @param networkName the network name to query
- * @return a Network object or null if not found
- */
- public Network findNetworkByName (Quantum neutronClient, String networkName)
- {
- if (networkName == null) {
+ try {
+ OpenStackRequest<Network> request = neutronClient.networks().show(networkId);
+ Network network = executeAndRecordOpenstackRequest(request);
+ return network;
+ } catch (OpenStackResponseException e) {
+ if (e.getStatus() == 404) {
+ return null;
+ } else {
+ logger.error("{} {} Openstack Error, GET Network By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
+ ErrorCode.DataError.getValue(), networkId, e);
+ throw e;
+ }
+ }
+ }
+
+
+ private Port findPortById(Quantum neutronClient, String neutronPortId) {
+ if (neutronPortId == null) {
return null;
}
- try {
- OpenStackRequest<Networks> request = neutronClient.networks().list();
- Networks networks = executeAndRecordOpenstackRequest(request);
- for (Network network : networks.getList()) {
- if (network.getName().equals(networkName)) {
- logger.debug("Found match on network name: {}", networkName);
- return network;
- }
- }
- logger.debug("findNetworkByName - no match found for {}", networkName);
- return null;
- }
- catch (OpenStackResponseException e) {
- if (e.getStatus() == 404) {
- return null;
- } else {
- logger.error("{} {} Openstack Error, GET Network By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), networkName, e);
- throw e;
- }
- }
- }
+ try {
+ OpenStackRequest<Port> request = neutronClient.ports().show(neutronPortId);
+ Port port = executeAndRecordOpenstackRequest(request);
+ return port;
+ } catch (OpenStackResponseException e) {
+ if (e.getStatus() == 404) {
+ logger.warn("Neutron port not found: " + neutronPortId, "Neutron port not found: " + neutronPortId);
+ return null;
+ } else {
+ logger.error("{} {} Openstack Error, GET Neutron Port By ID ({}): ",
+ MessageEnum.RA_CONNECTION_EXCEPTION, ErrorCode.DataError.getValue(), neutronPortId, e);
+ throw e;
+ }
+ }
+ }
+
+ /*
+ * Find a network (or query its existence) by its Name. This method avoids an initial lookup by ID when it's known
+ * that we have the network Name.
+ *
+ * Neutron does not support 'name=*' query parameter for Network query (show). The only way to query by name is to
+ * retrieve all networks and look for the match. While inefficient, this capability will be provided as it is needed
+ * by MSO, but should be avoided in favor of ID whenever possible.
+ *
+ * TODO: Network names are not required to be unique, though MSO will attempt to enforce uniqueness. This call
+ * probably needs to return an error (instead of returning the first match).
+ *
+ * @param neutronClient an authenticated Quantum object
+ *
+ * @param networkName the network name to query
+ *
+ * @return a Network object or null if not found
+ */
+ public Network findNetworkByName(Quantum neutronClient, String networkName) {
+ if (networkName == null) {
+ return null;
+ }
+
+ try {
+ OpenStackRequest<Networks> request = neutronClient.networks().list();
+ Networks networks = executeAndRecordOpenstackRequest(request);
+ for (Network network : networks.getList()) {
+ if (network.getName().equals(networkName)) {
+ logger.debug("Found match on network name: {}", networkName);
+ return network;
+ }
+ }
+ logger.debug("findNetworkByName - no match found for {}", networkName);
+ return null;
+ } catch (OpenStackResponseException e) {
+ if (e.getStatus() == 404) {
+ return null;
+ } else {
+ logger.error("{} {} Openstack Error, GET Network By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
+ ErrorCode.DataError.getValue(), networkName, e);
+ throw e;
+ }
+ }
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java
index 7cf41dbac9..e10c108165 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java
@@ -38,19 +38,17 @@ public abstract class MsoTenantUtils extends MsoCommonUtils {
@Autowired
protected CloudConfig cloudConfig;
- public abstract String createTenant (String tenantName, String cloudSiteId, Map <String, String> metadata, boolean backout)
- throws MsoException;
-
- public abstract MsoTenant queryTenant (String tenantId, String cloudSiteId)
- throws MsoException, MsoCloudSiteNotFound;
-
- public abstract MsoTenant queryTenantByName (String tenantName, String cloudSiteId)
- throws MsoException, MsoCloudSiteNotFound;
-
- public abstract boolean deleteTenant (String tenantId, String cloudSiteId)
- throws MsoException;
-
- public abstract String getKeystoneUrl (String regionId, CloudIdentity cloudIdentity)
- throws MsoException;
+ public abstract String createTenant(String tenantName, String cloudSiteId, Map<String, String> metadata,
+ boolean backout) throws MsoException;
+
+ public abstract MsoTenant queryTenant(String tenantId, String cloudSiteId)
+ throws MsoException, MsoCloudSiteNotFound;
+
+ public abstract MsoTenant queryTenantByName(String tenantName, String cloudSiteId)
+ throws MsoException, MsoCloudSiteNotFound;
+
+ public abstract boolean deleteTenant(String tenantId, String cloudSiteId) throws MsoException;
+
+ public abstract String getKeystoneUrl(String regionId, CloudIdentity cloudIdentity) throws MsoException;
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java
index c5b93d9fbe..514cb2eb7b 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java
@@ -36,28 +36,28 @@ public class MsoTenantUtilsFactory {
protected static Logger logger = LoggerFactory.getLogger(MsoTenantUtilsFactory.class);
@Autowired
- protected CloudConfig cloudConfig;
- @Autowired
- protected MsoKeystoneUtils keystoneUtils;
- @Autowired
- protected MsoKeystoneV3Utils keystoneV3Utils;
-
- // based on Cloud IdentityServerType returns ORM or KEYSTONE Utils
- public MsoTenantUtils getTenantUtils(String cloudSiteId) throws MsoCloudSiteNotFound {
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
-
- return getTenantUtilsByServerType(cloudSite.getIdentityService().getIdentityServerType());
- }
-
- public MsoTenantUtils getTenantUtilsByServerType(ServerType serverType) {
-
- MsoTenantUtils tenantU = null;
- if (ServerType.KEYSTONE.equals(serverType)) {
- tenantU = keystoneUtils;
- } else if (ServerType.KEYSTONE_V3.equals(serverType)) {
- tenantU = keystoneV3Utils;
- }
- return tenantU;
- }
+ protected CloudConfig cloudConfig;
+ @Autowired
+ protected MsoKeystoneUtils keystoneUtils;
+ @Autowired
+ protected MsoKeystoneV3Utils keystoneV3Utils;
+
+ // based on Cloud IdentityServerType returns ORM or KEYSTONE Utils
+ public MsoTenantUtils getTenantUtils(String cloudSiteId) throws MsoCloudSiteNotFound {
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+
+ return getTenantUtilsByServerType(cloudSite.getIdentityService().getIdentityServerType());
+ }
+
+ public MsoTenantUtils getTenantUtilsByServerType(ServerType serverType) {
+
+ MsoTenantUtils tenantU = null;
+ if (ServerType.KEYSTONE.equals(serverType)) {
+ tenantU = keystoneUtils;
+ } else if (ServerType.KEYSTONE_V3.equals(serverType)) {
+ tenantU = keystoneV3Utils;
+ }
+ return tenantU;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java
index 5f26449f0f..0541a8f51b 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java
@@ -40,39 +40,40 @@ import org.yaml.snakeyaml.Yaml;
public class MsoYamlEditorWithEnvt {
private static final Logger logger = LoggerFactory.getLogger(MsoYamlEditorWithEnvt.class);
-
- private Map <String, Object> yml;
- private Yaml yaml = new Yaml ();
+
+ private Map<String, Object> yml;
+ private Yaml yaml = new Yaml();
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
- public MsoYamlEditorWithEnvt() {
- super();
- }
- public MsoYamlEditorWithEnvt(byte[] b) {
- init(b);
- }
+ public MsoYamlEditorWithEnvt() {
+ super();
+ }
+
+ public MsoYamlEditorWithEnvt(byte[] b) {
+ init(b);
+ }
@SuppressWarnings("unchecked")
- private synchronized void init (byte[] body) {
- InputStream input = new ByteArrayInputStream (body);
- yml = (Map <String, Object>) yaml.load (input);
- }
+ private synchronized void init(byte[] body) {
+ InputStream input = new ByteArrayInputStream(body);
+ yml = (Map<String, Object>) yaml.load(input);
+ }
@SuppressWarnings("unchecked")
- public synchronized Set <MsoHeatEnvironmentParameter> getParameterListFromEnvt() {
- // In an environment entry, the parameters section can only contain the name:value -
- // not other attributes.
- Set <MsoHeatEnvironmentParameter> paramSet = new HashSet<>();
- Map<String, Object> resourceMap = null;
- try {
- resourceMap = (Map<String,Object>) yml.get("parameters");
- } catch (Exception e) {
- logger.debug("Exception:", e);
- return paramSet;
- }
- if (resourceMap == null) {
- return paramSet;
- }
+ public synchronized Set<MsoHeatEnvironmentParameter> getParameterListFromEnvt() {
+ // In an environment entry, the parameters section can only contain the name:value -
+ // not other attributes.
+ Set<MsoHeatEnvironmentParameter> paramSet = new HashSet<>();
+ Map<String, Object> resourceMap = null;
+ try {
+ resourceMap = (Map<String, Object>) yml.get("parameters");
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ return paramSet;
+ }
+ if (resourceMap == null) {
+ return paramSet;
+ }
for (Entry<String, Object> stringObjectEntry : resourceMap.entrySet()) {
MsoHeatEnvironmentParameter hep = new MsoHeatEnvironmentParameter();
@@ -84,7 +85,7 @@ public class MsoYamlEditorWithEnvt {
// but this adds an extra '\n' at the end - which won't hurt - but we don't need it
value = value.substring(0, value.length() - 1);
} else if (obj instanceof LinkedHashMap) {
- //Handle that it's json
+ // Handle that it's json
try {
value = JSON_MAPPER.writeValueAsString(obj);
} catch (Exception e) {
@@ -92,20 +93,21 @@ public class MsoYamlEditorWithEnvt {
value = "_BAD_JSON_MAPPING";
}
} else {
- //this handles integers/longs/floats/etc.
+ // this handles integers/longs/floats/etc.
value = String.valueOf(obj);
}
hep.setName((String) pair.getKey());
hep.setValue(value);
paramSet.add(hep);
}
- return paramSet;
+ return paramSet;
}
- public synchronized Set <MsoHeatEnvironmentResource> getResourceListFromEnvt() {
- try {
- Set<MsoHeatEnvironmentResource> resourceList = new HashSet<>();
- @SuppressWarnings("unchecked")
- Map<String, Object> resourceMap = (Map<String,Object>) yml.get("resource_registry");
+
+ public synchronized Set<MsoHeatEnvironmentResource> getResourceListFromEnvt() {
+ try {
+ Set<MsoHeatEnvironmentResource> resourceList = new HashSet<>();
+ @SuppressWarnings("unchecked")
+ Map<String, Object> resourceMap = (Map<String, Object>) yml.get("resource_registry");
for (Entry<String, Object> stringObjectEntry : resourceMap.entrySet()) {
MsoHeatEnvironmentResource her = new MsoHeatEnvironmentResource();
@@ -114,16 +116,17 @@ public class MsoYamlEditorWithEnvt {
her.setValue((String) pair.getValue());
resourceList.add(her);
}
- return resourceList;
- } catch (Exception e) {
- logger.debug("Exception:", e);
- }
- return null;
+ return resourceList;
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ }
+ return null;
}
- public synchronized Set <HeatTemplateParam> getParameterList () {
- Set <HeatTemplateParam> paramSet = new HashSet <> ();
+
+ public synchronized Set<HeatTemplateParam> getParameterList() {
+ Set<HeatTemplateParam> paramSet = new HashSet<>();
@SuppressWarnings("unchecked")
- Map <String, Object> resourceMap = (Map <String, Object>) yml.get ("parameters");
+ Map<String, Object> resourceMap = (Map<String, Object>) yml.get("parameters");
for (Entry<String, Object> stringObjectEntry : resourceMap.entrySet()) {
HeatTemplateParam param = new HeatTemplateParam();
@@ -138,7 +141,7 @@ public class MsoYamlEditorWithEnvt {
// This exception only - the value is an integer. For what we're doing
// here - we don't care - so set value to something - and it will
// get marked as not being required - which is correct.
- //System.out.println("cce exception!");
+ // System.out.println("cce exception!");
value = "300";
// okay
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java
index 543ad07d52..a4cdba22a1 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java
@@ -22,7 +22,6 @@ package org.onap.so.openstack.utils;
import java.io.Serializable;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -30,10 +29,7 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "id",
- "links"
-})
+@JsonPropertyOrder({"id", "links"})
public class MulticloudCreateHeatResponse implements Serializable {
private final static long serialVersionUID = -5215028275577848311L;
@@ -43,8 +39,7 @@ public class MulticloudCreateHeatResponse implements Serializable {
private List<MulticloudCreateLinkResponse> links;
@JsonCreator
- public MulticloudCreateHeatResponse(
- @JsonProperty("id") String id,
+ public MulticloudCreateHeatResponse(@JsonProperty("id") String id,
@JsonProperty("links") List<MulticloudCreateLinkResponse> links) {
this.id = id;
this.links = links;
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java
index b609ac96c4..e8a5b1480e 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java
@@ -29,10 +29,7 @@ import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "href",
- "rel"
-})
+@JsonPropertyOrder({"href", "rel"})
public class MulticloudCreateLinkResponse implements Serializable {
private final static long serialVersionUID = -5215028275577848311L;
@@ -42,9 +39,7 @@ public class MulticloudCreateLinkResponse implements Serializable {
private String rel;
@JsonCreator
- public MulticloudCreateLinkResponse(
- @JsonProperty("href") String href,
- @JsonProperty("rel") String rel) {
+ public MulticloudCreateLinkResponse(@JsonProperty("href") String href, @JsonProperty("rel") String rel) {
this.href = href;
this.rel = rel;
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java
index fafd4a074d..bb15e58c88 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java
@@ -28,11 +28,7 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "template_type",
- "workload_id",
- "template_response"
-})
+@JsonPropertyOrder({"template_type", "workload_id", "template_response"})
public class MulticloudCreateResponse implements Serializable {
private final static long serialVersionUID = -5215028275577848311L;
@@ -44,8 +40,7 @@ public class MulticloudCreateResponse implements Serializable {
private MulticloudCreateStackResponse templateResponse;
@JsonCreator
- public MulticloudCreateResponse(
- @JsonProperty("template_type") String templateType,
+ public MulticloudCreateResponse(@JsonProperty("template_type") String templateType,
@JsonProperty("workload_id") String workloadId,
@JsonProperty("template_response") MulticloudCreateStackResponse templateResponse) {
this.templateType = templateType;
@@ -85,6 +80,7 @@ public class MulticloudCreateResponse implements Serializable {
@Override
public String toString() {
- return new ToStringBuilder(this).append("templateType", templateType).append("workloadId", workloadId).append("templateResponse", templateResponse).toString();
+ return new ToStringBuilder(this).append("templateType", templateType).append("workloadId", workloadId)
+ .append("templateResponse", templateResponse).toString();
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java
index f1d44a8814..67cb73539d 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java
@@ -28,9 +28,7 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "stack"
-})
+@JsonPropertyOrder({"stack"})
public class MulticloudCreateStackResponse implements Serializable {
private final static long serialVersionUID = -5215028275577848311L;
@@ -38,8 +36,7 @@ public class MulticloudCreateStackResponse implements Serializable {
private MulticloudCreateHeatResponse stack;
@JsonCreator
- public MulticloudCreateStackResponse(
- @JsonProperty("stack") MulticloudCreateHeatResponse stack) {
+ public MulticloudCreateStackResponse(@JsonProperty("stack") MulticloudCreateHeatResponse stack) {
this.stack = stack;
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java
index b22e9dc03e..ca8f041aae 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java
@@ -28,11 +28,7 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "template_type",
- "workload_id",
- "workload_status"
-})
+@JsonPropertyOrder({"template_type", "workload_id", "workload_status"})
public class MulticloudQueryResponse implements Serializable {
private final static long serialVersionUID = -5215028275577848311L;
@@ -44,10 +40,8 @@ public class MulticloudQueryResponse implements Serializable {
private String workloadStatus;
@JsonCreator
- public MulticloudQueryResponse(
- @JsonProperty("template_type") String templateType,
- @JsonProperty("workload_id") String workloadId,
- @JsonProperty("workload_status") String workloadStatus) {
+ public MulticloudQueryResponse(@JsonProperty("template_type") String templateType,
+ @JsonProperty("workload_id") String workloadId, @JsonProperty("workload_status") String workloadStatus) {
this.templateType = templateType;
this.workloadId = workloadId;
this.workloadStatus = workloadStatus;
@@ -85,6 +79,7 @@ public class MulticloudQueryResponse implements Serializable {
@Override
public String toString() {
- return new ToStringBuilder(this).append("templateType", templateType).append("workloadId", workloadId).append("workloadStatus", workloadStatus).toString();
+ return new ToStringBuilder(this).append("templateType", templateType).append("workloadId", workloadId)
+ .append("workloadStatus", workloadStatus).toString();
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java
index 4204813cec..b733552a2b 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
- * Copyright (C) 2018 Intel Corp. All rights reserved.
+ * Copyright (C) 2019 Intel Corp. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,18 +26,12 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.JsonNode;
import com.woorea.openstack.heat.model.CreateStackParam;
-
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "generic-vnf-id",
- "vf-module-id",
- "oof_directives",
- "sdnc_directives",
- "template_type",
- "template_data"
-})
+@JsonPropertyOrder({"generic-vnf-id", "vf-module-id", "vf-module-model-invariant-id", "vf-module-model-version-id",
+ "vf-module-model-customization-id", "oof_directives", "sdnc_directives", "user_directives", "template_type",
+ "template_data"})
public class MulticloudRequest implements Serializable {
private final static long serialVersionUID = -5215028275577848311L;
@@ -45,10 +39,18 @@ public class MulticloudRequest implements Serializable {
private String genericVnfId;
@JsonProperty("vf-module-id")
private String vfModuleId;
+ @JsonProperty("vf-module-model-invariant-id")
+ private String vfModuleModelInvariantId;
+ @JsonProperty("vf-module-model-version-id")
+ private String vfModuleModelVersionId;
+ @JsonProperty("vf-module-model-customization-id")
+ private String vfModuleModelCustomizationId;
@JsonProperty("oof_directives")
private JsonNode oofDirectives;
@JsonProperty("sdnc_directives")
private JsonNode sdncDirectives;
+ @JsonProperty("user_directives")
+ private JsonNode userDirectives;
@JsonProperty("template_type")
private String templateType;
@JsonProperty("template_data")
@@ -75,6 +77,36 @@ public class MulticloudRequest implements Serializable {
this.vfModuleId = vfModuleId;
}
+ @JsonProperty("vf-module-model-invariant-id")
+ public String getVfModuleModelInvariantId() {
+ return vfModuleModelInvariantId;
+ }
+
+ @JsonProperty("vf-module-model-invariant-id")
+ public void setVfModuleModelInvariantId(String vfModuleModelInvariantId) {
+ this.vfModuleModelInvariantId = vfModuleModelInvariantId;
+ }
+
+ @JsonProperty("vf-module-model-version-id")
+ public String getVfModuleModelVersionId() {
+ return vfModuleModelVersionId;
+ }
+
+ @JsonProperty("vf-module-model-version-id")
+ public void setVfModuleModelVersionId(String vfModuleModelVersionId) {
+ this.vfModuleModelVersionId = vfModuleModelVersionId;
+ }
+
+ @JsonProperty("vf-module-model-customization-id")
+ public String getVfModuleModelCustomizationId() {
+ return vfModuleModelCustomizationId;
+ }
+
+ @JsonProperty("vf-module-model-customization-id")
+ public void setVfModuleModelCustomizationId(String vfModuleModelCustomizationId) {
+ this.vfModuleModelCustomizationId = vfModuleModelCustomizationId;
+ }
+
@JsonProperty("oof_directives")
public JsonNode getOofDirectives() {
return oofDirectives;
@@ -95,6 +127,16 @@ public class MulticloudRequest implements Serializable {
this.sdncDirectives = sdncDirectives;
}
+ @JsonProperty("user_directives")
+ public JsonNode getUserDirectives() {
+ return userDirectives;
+ }
+
+ @JsonProperty("user_directives")
+ public void setUserDirectives(JsonNode userDirectives) {
+ this.userDirectives = userDirectives;
+ }
+
@JsonProperty("template_type")
public String getTemplateType() {
return templateType;
@@ -117,7 +159,13 @@ public class MulticloudRequest implements Serializable {
@Override
public String toString() {
- return new ToStringBuilder(this).append("genericVnfId", genericVnfId).append("vfModuleId", vfModuleId).append("oofDirectives", oofDirectives).append("sdncDirectives", sdncDirectives).append("templateType", templateType).append("templateData", templateData).toString();
+ return new ToStringBuilder(this).append("genericVnfId", genericVnfId).append("vfModuleId", vfModuleId)
+ .append("vfModuleModelInvariantId", vfModuleModelInvariantId)
+ .append("vfModuleModelVersionId", vfModuleModelVersionId)
+ .append("vfModuleModelCustomizationId", vfModuleModelCustomizationId)
+ .append("oofDirectives", oofDirectives).append("sdncDirectives", sdncDirectives)
+ .append("userDirectives", userDirectives).append("templateType", templateType)
+ .append("templateData", templateData).toString();
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java
new file mode 100644
index 0000000000..a9365a3946
--- /dev/null
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java
@@ -0,0 +1,32 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * 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.so;
+
+import org.junit.runner.RunWith;
+import com.googlecode.junittoolbox.SuiteClasses;
+import com.googlecode.junittoolbox.WildcardPatternSuite;
+
+@RunWith(WildcardPatternSuite.class)
+@SuiteClasses("**/*Test.class")
+public class AllTestsTestSuite {
+ // the class remains empty,
+ // used only as a holder for the above annotations
+}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java
index 9cfdf53094..ecdd052b73 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java
@@ -23,7 +23,13 @@
package org.onap.so;
-import com.github.tomakehurst.wiremock.client.WireMock;
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import javax.ws.rs.core.MediaType;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.junit.After;
@@ -33,20 +39,14 @@ import org.onap.so.db.catalog.beans.AuthenticationType;
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.db.catalog.beans.CloudSite;
import org.onap.so.db.catalog.beans.ServerType;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
-
-import javax.ws.rs.core.MediaType;
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
-
-import static com.github.tomakehurst.wiremock.client.WireMock.*;
-import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
-import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
+import com.github.tomakehurst.wiremock.WireMockServer;
+import com.github.tomakehurst.wiremock.client.WireMock;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@@ -54,75 +54,74 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
@AutoConfigureWireMock(port = 0)
public abstract class BaseTest extends TestDataSetup {
- @Value("${wiremock.server.port}")
- protected int wireMockPort;
-
- @After
- public void after() {
- WireMock.reset();
- }
+ @Value("${wiremock.server.port}")
+ protected int wireMockPort;
+ @Autowired
+ protected WireMockServer wireMockServer;
+
+ @After
+ public void after() {
+ wireMockServer.resetAll();
+ }
- protected static String getBody(String body, int port, String urlPath) throws IOException {
- return body.replaceAll("port", "http://localhost:" + port + urlPath);
- }
+ protected static String getBody(String body, int port, String urlPath) throws IOException {
+ return body.replaceAll("port", "http://localhost:" + port + urlPath);
+ }
- @Before
- public void init() throws IOException {
- CloudIdentity identity = getCloudIdentity();
- CloudSite cloudSite = getCloudSite(identity);
- mockCloud(identity, cloudSite);
- }
+ @Before
+ public void init() throws IOException {
+ CloudIdentity identity = getCloudIdentity();
+ CloudSite cloudSite = getCloudSite(identity);
+ mockCloud(identity, cloudSite);
+ }
- private void mockCloud(CloudIdentity identity, CloudSite cloudSite) throws IOException {
- stubFor(get(urlPathEqualTo("/cloudSite/MTN13")).willReturn(aResponse()
- .withBody(getBody(mapper.writeValueAsString(cloudSite),wireMockPort, ""))
- .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- stubFor(get(urlPathEqualTo("/cloudSite/DEFAULT")).willReturn(aResponse()
- .withBody(getBody(mapper.writeValueAsString(cloudSite),wireMockPort, ""))
- .withHeader(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- stubFor(get(urlPathEqualTo("/cloudIdentity/mtn13")).willReturn(aResponse()
- .withBody(getBody(mapper.writeValueAsString(identity),wireMockPort, ""))
- .withHeader(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- }
+ private void mockCloud(CloudIdentity identity, CloudSite cloudSite) throws IOException {
+ wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/MTN13")).willReturn(aResponse()
+ .withBody(getBody(mapper.writeValueAsString(cloudSite), wireMockPort, ""))
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/DEFAULT")).willReturn(aResponse()
+ .withBody(getBody(mapper.writeValueAsString(cloudSite), wireMockPort, ""))
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/cloudIdentity/mtn13")).willReturn(aResponse()
+ .withBody(getBody(mapper.writeValueAsString(identity), wireMockPort, ""))
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
+ }
- protected CloudIdentity getCloudIdentity() {
- CloudIdentity identity = new CloudIdentity();
- identity.setId("mtn13");
- identity.setMsoId("m93945");
- identity.setMsoPass("93937EA01B94A10A49279D4572B48369");
- identity.setAdminTenant("admin");
- identity.setMemberRole("admin");
- identity.setTenantMetadata(false);
- identity.setIdentityUrl("http://localhost:"+wireMockPort+"/v2.0");
- identity.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
- identity.setIdentityServerType(ServerType.KEYSTONE);
- return identity;
- }
+ protected CloudIdentity getCloudIdentity() {
+ CloudIdentity identity = new CloudIdentity();
+ identity.setId("mtn13");
+ identity.setMsoId("m93945");
+ identity.setMsoPass("93937EA01B94A10A49279D4572B48369");
+ identity.setAdminTenant("admin");
+ identity.setMemberRole("admin");
+ identity.setTenantMetadata(false);
+ identity.setIdentityUrl("http://localhost:" + wireMockPort + "/v2.0");
+ identity.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
+ identity.setIdentityServerType(ServerType.KEYSTONE);
+ return identity;
+ }
- protected CloudSite getCloudSite(CloudIdentity identity) {
- CloudSite cloudSite = new CloudSite();
- cloudSite.setId("MTN13");
- cloudSite.setCloudVersion("3.0");
- cloudSite.setClli("MDT13");
- cloudSite.setRegionId("mtn13");
- cloudSite.setIdentityService(identity);
- return cloudSite;
- }
+ protected CloudSite getCloudSite(CloudIdentity identity) {
+ CloudSite cloudSite = new CloudSite();
+ cloudSite.setId("MTN13");
+ cloudSite.setCloudVersion("3.0");
+ cloudSite.setClli("MDT13");
+ cloudSite.setRegionId("mtn13");
+ cloudSite.setIdentityService(identity);
+ return cloudSite;
+ }
- private static String readFile(String fileName) throws IOException {
- try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
- StringBuilder sb = new StringBuilder();
- String line = br.readLine();
+ private static String readFile(String fileName) throws IOException {
+ try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
- while (line != null) {
- sb.append(line);
- sb.append("\n");
- line = br.readLine();
- }
- return sb.toString();
- }
- }
+ while (line != null) {
+ sb.append(line);
+ sb.append("\n");
+ line = br.readLine();
+ }
+ return sb.toString();
+ }
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
index c1705508ce..75794efe79 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
@@ -28,11 +28,10 @@ import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
-
import javax.sql.DataSource;
@Configuration
-@Profile({"test","local"})
+@Profile({"test", "local"})
public class EmbeddedMariaDbConfig {
@Bean
@@ -42,21 +41,16 @@ public class EmbeddedMariaDbConfig {
@Bean
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java
index 0820076c66..120c3e3493 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java
@@ -27,121 +27,116 @@ import static com.github.tomakehurst.wiremock.client.WireMock.delete;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
-import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
-
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.apache.http.HttpStatus;
+import com.github.tomakehurst.wiremock.WireMockServer;
public class StubOpenStack {
- public static void mockOpenStackResponseAccess(int port) throws IOException {
- stubFor(post(urlPathEqualTo("/v2.0/tokens")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
+ public static void mockOpenStackResponseAccess(WireMockServer wireMockServer, int port) throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenStackResponseUnauthorized(int port) throws IOException {
- stubFor(
- post(urlPathEqualTo("/v2.0/tokens"))
+ public static void mockOpenStackResponseUnauthorized(WireMockServer wireMockServer, int port) throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
.willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_UNAUTHORIZED)));
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_UNAUTHORIZED)));
}
- public static void mockOpenStackDelete(String id) {
- stubFor(delete(urlMatching("/mockPublicUrl/stacks/" + id)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
+ public static void mockOpenStackDelete(WireMockServer wireMockServer, String id) {
+ wireMockServer.stubFor(delete(urlMatching("/mockPublicUrl/stacks/" + id))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenStackGet(String id) {
- stubFor(
- get(urlPathEqualTo("/mockPublicUrl/stacks/" + id))
+ public static void mockOpenStackGet(WireMockServer wireMockServer, String id) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + id))
.willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Stack_Created.json")
- .withStatus(HttpStatus.SC_OK)));
+ .withBodyFile("OpenstackResponse_Stack_Created.json").withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenStackPostStack_200(String filename) {
- stubFor(post(urlPathEqualTo("/mockPublicUrl/stacks")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
+ public static void mockOpenStackPostStack_200(WireMockServer wireMockServer, String filename) {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/stacks")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenStackPostTenantWithBodyFile_200() throws IOException {
- stubFor(post(urlPathEqualTo("/mockPublicUrl/tenants"))
+ public static void mockOpenStackPostTenantWithBodyFile_200(WireMockServer wireMockServer) throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/tenants"))
.willReturn(aResponse().withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenStackGetTenantByName(String tenantName) throws IOException {
- stubFor(get(urlMatching("/mockPublicUrl/tenants/[?]name=" + tenantName))
+ public static void mockOpenStackGetTenantByName(WireMockServer wireMockServer, String tenantName)
+ throws IOException {
+ wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/tenants/[?]name=" + tenantName))
.willReturn(aResponse().withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenStackGetTenantById(String tenantId) throws IOException {
- stubFor(get(urlPathEqualTo("/mockPublicUrl/tenants/tenantId"))
+ public static void mockOpenStackGetTenantById(WireMockServer wireMockServer, String tenantId) throws IOException {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/tenants/tenantId"))
.willReturn(aResponse().withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenStackDeleteTenantById_200(String tenantId) {
- stubFor(delete(urlPathEqualTo("/mockPublicUrl/tenants/" + tenantId)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
+ public static void mockOpenStackDeleteTenantById_200(WireMockServer wireMockServer, String tenantId) {
+ wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/tenants/" + tenantId))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenStackGetUserById(String user) {
- stubFor(get(urlPathEqualTo("/mockPublicUrl/users/" + user)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK)));
+ public static void mockOpenStackGetUserById(WireMockServer wireMockServer, String user) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/users/" + user))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenStackGetUserByName(String userName) {
- stubFor(get(urlMatching("/mockPublicUrl/users/[?]name=" + userName)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK)));
+ public static void mockOpenStackGetUserByName(WireMockServer wireMockServer, String userName) {
+ wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/users/[?]name=" + userName))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenStackGetUserByName_500(String userName) {
- stubFor(get(urlMatching("/mockPublicUrl/users/[?]name=" + userName)).willReturn(aResponse()
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+ public static void mockOpenStackGetUserByName_500(WireMockServer wireMockServer, String userName) {
+ wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/users/[?]name=" + userName))
+ .willReturn(aResponse().withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
}
- public static void mockOpenStackGetRoles_200(String roleFor) {
- stubFor(get(urlPathEqualTo("/mockPublicUrl/" + roleFor + "/roles")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Roles.json").withStatus(HttpStatus.SC_OK)));
+ public static void mockOpenStackGetRoles_200(WireMockServer wireMockServer, String roleFor) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/" + roleFor + "/roles"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_Roles.json").withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenstackPostNetwork(String responseFile) {
- stubFor(post(urlPathEqualTo("/mockPublicUrl/v2.0/networks")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)
- .withStatus(HttpStatus.SC_OK)));
+ public static void mockOpenstackPostNetwork(WireMockServer wireMockServer, String responseFile) {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/v2.0/networks"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile(responseFile)
+ .withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenstackPutNetwork(String responseFile, String networkId) {
- stubFor(put(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+networkId)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)
- .withStatus(HttpStatus.SC_OK)));
+ public static void mockOpenstackPutNetwork(WireMockServer wireMockServer, String responseFile, String networkId) {
+ wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile(responseFile)
+ .withStatus(HttpStatus.SC_OK)));
}
-
- public static void mockOpenStackGetNeutronNetwork(String filename,String networkId) {
- stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+ networkId))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
+
+ public static void mockOpenStackGetNeutronNetwork(WireMockServer wireMockServer, String filename,
+ String networkId) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId)).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenStackGetNeutronNetwork_500(String networkId) {
- stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+ networkId))
+ public static void mockOpenStackGetNeutronNetwork_500(WireMockServer wireMockServer, String networkId) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId))
.willReturn(aResponse().withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
}
- public static void mockOpenStackDeleteNeutronNetwork(String networkId) {
- stubFor(delete(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId))
+ public static void mockOpenStackDeleteNeutronNetwork(WireMockServer wireMockServer, String networkId) {
+ wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId))
.willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
}
@@ -160,6 +155,7 @@ public class StubOpenStack {
}
public static String getBodyFromFile(String fileName, int port, String urlPath) throws IOException {
- return readFile("src/test/resources/__files/" + fileName).replaceAll("port", "http://localhost:" + port + urlPath);
+ return readFile("src/test/resources/__files/" + fileName).replaceAll("port",
+ "http://localhost:" + port + urlPath);
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java
index 479731c870..f73c3a8e6c 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java
@@ -28,12 +28,12 @@ import org.springframework.context.annotation.Profile;
@SpringBootApplication
@Profile("test")
-@ComponentScan(basePackages = {"org.onap.so", "com.att"}, excludeFilters = {
- @Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
+@ComponentScan(basePackages = {"org.onap.so", "com.att"},
+ excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
public class TestApplication {
- public static void main(String... args) {
- SpringApplication.run(TestApplication.class, args);
- System.getProperties().setProperty("mso.db", "MARIADB");
- System.getProperties().setProperty("server.name", "Springboot");
- }
+ public static void main(String... args) {
+ SpringApplication.run(TestApplication.class, args);
+ System.getProperties().setProperty("mso.db", "MARIADB");
+ System.getProperties().setProperty("server.name", "Springboot");
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java
index 21c4c225ba..61cc24b31a 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java
@@ -23,18 +23,17 @@ package org.onap.so;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
-
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestDataSetup {
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- public static final String RESOURCE_PATH = "src/test/resources/__files/";
- public ObjectMapper mapper;
-
- @Before
- public void testDataSetupBefore() {
- mapper = new ObjectMapper();
- }
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ public static final String RESOURCE_PATH = "src/test/resources/__files/";
+ public ObjectMapper mapper;
+
+ @Before
+ public void testDataSetupBefore() {
+ mapper = new ObjectMapper();
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java
index ea25fe580d..fb3b3e0dc5 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java
@@ -21,9 +21,7 @@
package org.onap.so.cloud;
import static org.junit.Assert.*;
-
import java.util.Optional;
-
import org.junit.Test;
import org.onap.so.BaseTest;
import org.onap.so.db.catalog.beans.AuthenticationType;
@@ -38,35 +36,35 @@ import org.springframework.beans.factory.annotation.Autowired;
*
*
*/
-public class CloudConfigTest extends BaseTest{
+public class CloudConfigTest extends BaseTest {
+
+ @Autowired
+ private CloudConfig con;
- @Autowired
- private CloudConfig con;
+ /**
+ * This method implements a test for the getCloudSite method.
+ */
+ @Test
+ public final void testGetCloudSite() {
+ CloudSite site1 = con.getCloudSite("MTN13").get();
- /**
- * This method implements a test for the getCloudSite method.
- */
- @Test
- public final void testGetCloudSite () {
- CloudSite site1 = con.getCloudSite("MTN13").get();
+ assertEquals("mtn13", site1.getRegionId());
+ assertEquals("mtn13", site1.getIdentityServiceId());
+ assertEquals("MDT13", site1.getClli());
+ assertEquals("3.0", site1.getCloudVersion());
+ }
- assertEquals ("mtn13", site1.getRegionId());
- assertEquals ("mtn13", site1.getIdentityServiceId());
- assertEquals ("MDT13", site1.getClli());
- assertEquals ("3.0", site1.getCloudVersion());
- }
+ /**
+ * This method implements a test for the getCloudSite method.
+ */
+ @Test
+ public final void testGetDefaultCloudSite() {
+ Optional<CloudSite> site = con.getCloudSite("NotThere");
+ assertTrue(site.isPresent());
+ CloudSite site1 = site.get();
+ assertEquals("NotThere", site1.getRegionId());
+ assertEquals("MDT13", site1.getClli());
+ assertEquals("NotThere", site1.getId());
+ }
- /**
- * This method implements a test for the getCloudSite method.
- */
- @Test
- public final void testGetDefaultCloudSite () {
- Optional<CloudSite> site = con.getCloudSite("NotThere");
- assertTrue(site.isPresent());
- CloudSite site1 = site.get();
- assertEquals ("NotThere", site1.getRegionId());
- assertEquals("MDT13", site1.getClli());
- assertEquals("NotThere", site1.getId());
- }
-
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java
index 096d5dad8b..6c58cda2d1 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java
@@ -25,7 +25,6 @@ import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.db.catalog.beans.CloudSite;
import org.onap.so.db.catalog.beans.CloudifyManager;
import org.onap.so.openpojo.rules.ToStringTester;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.impl.PojoClassFactory;
import com.openpojo.validation.Validator;
@@ -37,23 +36,18 @@ import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
public class CloudPojoTest {
- @Test
- public void pojoStructure() {
- test(PojoClassFactory.getPojoClass(CloudIdentity.class));
- test(PojoClassFactory.getPojoClass(CloudifyManager.class));
- test(PojoClassFactory.getPojoClass(CloudSite.class));
- test(PojoClassFactory.getPojoClass(CloudConfig.class));
- }
-
- private void test(PojoClass pojoClass) {
- Validator validator = ValidatorBuilder.create()
- .with(new EqualsAndHashCodeMatchRule())
- .with(new NoPrimitivesRule())
- .with(new NoPublicFieldsRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .with(new ToStringTester())
- .build();
- validator.validate(pojoClass);
- }
+ @Test
+ public void pojoStructure() {
+ test(PojoClassFactory.getPojoClass(CloudIdentity.class));
+ test(PojoClassFactory.getPojoClass(CloudifyManager.class));
+ test(PojoClassFactory.getPojoClass(CloudSite.class));
+ test(PojoClassFactory.getPojoClass(CloudConfig.class));
+ }
+
+ private void test(PojoClass pojoClass) {
+ Validator validator = ValidatorBuilder.create().with(new EqualsAndHashCodeMatchRule())
+ .with(new NoPrimitivesRule()).with(new NoPublicFieldsRule()).with(new SetterTester())
+ .with(new GetterTester()).with(new ToStringTester()).build();
+ validator.validate(pojoClass);
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java
index a5abe75af2..41aac0084c 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java
@@ -23,17 +23,14 @@ package org.onap.so.cloud.authentication;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import org.junit.Test;
import org.onap.so.cloud.authentication.models.RackspaceAuthentication;
import org.onap.so.db.catalog.beans.AuthenticationType;
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.utils.CryptoUtils;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -41,81 +38,83 @@ import com.woorea.openstack.keystone.model.Authentication;
import com.woorea.openstack.keystone.model.authentication.UsernamePassword;
/**
- * A few JUnit tests to evaluate the new factory that manages authentication
- * types and their associated wrapper classes. Here it is assumed that core types
- * only are tested.
+ * A few JUnit tests to evaluate the new factory that manages authentication types and their associated wrapper classes.
+ * Here it is assumed that core types only are tested.
*
*/
public class AuthenticationMethodTest {
- private AuthenticationMethodFactory authenticationMethodFactory = new AuthenticationMethodFactory();
- /**
- *
- */
- public AuthenticationMethodTest() {
- // TODO Auto-generated constructor stub
- }
-
- @Test
- public void testCustomRackspaceAuth() {
- CloudIdentity ci = new CloudIdentity();
- ci.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY);
- ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
- ci.setMsoId("test");
-
- Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
- assertTrue(RackspaceAuthentication.class.equals(auth.getClass()));
-
- }
-
- @Test
- public void testCoreUsernamePasswordAuth() {
- CloudIdentity ci = new CloudIdentity();
- ci.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
- ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
- ci.setMsoId("someuser");
-
- Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
- assertTrue(UsernamePassword.class.equals(auth.getClass()));
-
- }
-
- @Test
- public void testCustomRackspaceAuthFromCloudIdentity() {
- CloudIdentity ci = new CloudIdentity();
- ci.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY);
- ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
- ci.setMsoId("test");
-
- Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
- assertTrue(RackspaceAuthentication.class.equals(auth.getClass()));
- }
-
- @Test
- public void testCoreUsernamePasswordAuthFromCloudIdentity() {
- CloudIdentity ci = new CloudIdentity();
- ci.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
- ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
- ci.setMsoId("someuser");
-
- Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
- assertTrue(UsernamePassword.class.equals(auth.getClass()));
-
- }
-
- @Test
- public void getAuthenticationForV3Test() throws JsonParseException, JsonMappingException, IOException {
-
- CloudIdentity identity = new CloudIdentity();
- identity.setMsoId("my-username");
- identity.setMsoPass(CryptoUtils.encryptCloudConfigPassword("my-password"));
- identity.setProjectDomainName("test-domain");
- identity.setUserDomainName("user-domain");
- ObjectMapper mapper = new ObjectMapper();
- com.woorea.openstack.keystone.v3.model.Authentication expected =
- mapper.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/__files/KeystoneV3Payload.json"))), com.woorea.openstack.keystone.v3.model.Authentication.class);
- com.woorea.openstack.keystone.v3.model.Authentication actual = authenticationMethodFactory.getAuthenticationForV3(identity, "project-x");
-
- assertThat(actual, sameBeanAs(expected));
- }
+ private AuthenticationMethodFactory authenticationMethodFactory = new AuthenticationMethodFactory();
+
+ /**
+ *
+ */
+ public AuthenticationMethodTest() {
+ // TODO Auto-generated constructor stub
+ }
+
+ @Test
+ public void testCustomRackspaceAuth() {
+ CloudIdentity ci = new CloudIdentity();
+ ci.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY);
+ ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
+ ci.setMsoId("test");
+
+ Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
+ assertTrue(RackspaceAuthentication.class.equals(auth.getClass()));
+
+ }
+
+ @Test
+ public void testCoreUsernamePasswordAuth() {
+ CloudIdentity ci = new CloudIdentity();
+ ci.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
+ ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
+ ci.setMsoId("someuser");
+
+ Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
+ assertTrue(UsernamePassword.class.equals(auth.getClass()));
+
+ }
+
+ @Test
+ public void testCustomRackspaceAuthFromCloudIdentity() {
+ CloudIdentity ci = new CloudIdentity();
+ ci.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY);
+ ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
+ ci.setMsoId("test");
+
+ Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
+ assertTrue(RackspaceAuthentication.class.equals(auth.getClass()));
+ }
+
+ @Test
+ public void testCoreUsernamePasswordAuthFromCloudIdentity() {
+ CloudIdentity ci = new CloudIdentity();
+ ci.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
+ ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
+ ci.setMsoId("someuser");
+
+ Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
+ assertTrue(UsernamePassword.class.equals(auth.getClass()));
+
+ }
+
+ @Test
+ public void getAuthenticationForV3Test() throws JsonParseException, JsonMappingException, IOException {
+
+ CloudIdentity identity = new CloudIdentity();
+ identity.setMsoId("my-username");
+ identity.setMsoPass(CryptoUtils.encryptCloudConfigPassword("my-password"));
+ identity.setProjectDomainName("test-domain");
+ identity.setUserDomainName("user-domain");
+ ObjectMapper mapper = new ObjectMapper();
+ com.woorea.openstack.keystone.v3.model.Authentication expected = mapper.readValue(
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/KeystoneV3Payload.json"))),
+ com.woorea.openstack.keystone.v3.model.Authentication.class);
+ com.woorea.openstack.keystone.v3.model.Authentication actual =
+ authenticationMethodFactory.getAuthenticationForV3(identity, "project-x");
+
+ assertThat(actual, sameBeanAs(expected));
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java
index 8469ad506c..5bd77d8e10 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java
@@ -19,22 +19,17 @@
*/
/*
- * ============LICENSE_START==========================================
- * ONAP - SO
- * ===================================================================
- * Copyright (c) 2019 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
+ * ============LICENSE_START========================================== ONAP - SO
+ * =================================================================== Copyright (c) 2019 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
+ * 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.
+ * 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=============================================
* ====================================================================
@@ -42,9 +37,7 @@
package org.onap.so.cloud.authentication;
import static org.junit.Assert.assertEquals;
-
import java.util.Calendar;
-
import org.junit.Before;
import org.junit.Test;
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java
index 8f172b79ca..9fbb45a2c3 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java
@@ -1,26 +1,20 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 Nokia.
- * =============================================================================
- * 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
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 Nokia.
+ * ============================================================================= 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
+ * 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.
+ * 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.so.cloudify.beans;
import static org.assertj.core.api.Assertions.assertThat;
-
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import org.onap.so.cloudify.v3.model.Execution;
@@ -33,15 +27,10 @@ public class DeploymentInfoBuilderTest {
@Test
public void shouldConstructDeploymentInfo_withBasicValues() {
- DeploymentInfo deploymentInfo = new DeploymentInfoBuilder()
- .withId("id")
- .withStatus(DeploymentStatus.CREATED)
- .withDeploymentOutputs(ImmutableMap.of())
- .withDeploymentInputs(ImmutableMap.of())
- .withActionStatus("started")
- .withLastAction(INSTALL_WORKFLOW_ID)
- .withErrorMessage(ERROR_MESSAGE)
- .build();
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.CREATED)
+ .withDeploymentOutputs(ImmutableMap.of()).withDeploymentInputs(ImmutableMap.of())
+ .withActionStatus("started").withLastAction(INSTALL_WORKFLOW_ID).withErrorMessage(ERROR_MESSAGE)
+ .build();
assertThat(deploymentInfo.getId()).isEqualTo("id");
assertThat(deploymentInfo.getStatus()).isEqualTo(DeploymentStatus.CREATED);
@@ -54,9 +43,7 @@ public class DeploymentInfoBuilderTest {
@Test
public void shouldConstructDeploymentInfo_withCreateDeploymentStatus_fromNullExecution() {
- DeploymentInfo deploymentInfo = new DeploymentInfoBuilder()
- .fromExecution(null)
- .build();
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().fromExecution(null).build();
assertThat(deploymentInfo.getStatus()).isEqualTo(DeploymentStatus.CREATED);
}
@@ -149,20 +136,24 @@ public class DeploymentInfoBuilderTest {
verifyDeploymentInfoConstruction(workflowIdLastAction, status, expectedDeploymentStatus);
}
+ @Test
+ public void shouldSetEmptyOutputsMapWhenInputIsNull() {
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withDeploymentOutputs(null).build();
+ assertThat(deploymentInfo.getOutputs()).isEmpty();
+ }
+
private void verifyDeploymentInfoConstruction(String workflowIdLastAction, String actionStatus,
- DeploymentStatus expectedDeploymentStatus) {
+ DeploymentStatus expectedDeploymentStatus) {
Execution execution = new Execution();
execution.setWorkflowId(workflowIdLastAction);
execution.setStatus(actionStatus);
execution.setError(ERROR_MESSAGE);
- DeploymentInfo deploymentInfo = new DeploymentInfoBuilder()
- .fromExecution(execution)
- .build();
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().fromExecution(execution).build();
assertThat(deploymentInfo.getLastAction()).isEqualTo(workflowIdLastAction);
assertThat(deploymentInfo.getActionStatus()).isEqualTo(actionStatus);
assertThat(deploymentInfo.getErrorMessage()).isEqualTo(ERROR_MESSAGE);
assertThat(deploymentInfo.getStatus()).isEqualTo(expectedDeploymentStatus);
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java
index 4bf087b7a4..d45f685795 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java
@@ -1,39 +1,33 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * 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
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ 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
+ * 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.
+ * 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.so.cloudify.exceptions;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class MsoCloudifyExceptionTest {
-
- @Test
+
+ @Test
public void test() {
Exception e = null;
- boolean pendingWorkflow=true;
- MsoCloudifyException mce=new MsoCloudifyException(200, "message", "detail");
- MsoCloudifyException mcl=new MsoCloudifyException(200, "message", "detail", e);
+ boolean pendingWorkflow = true;
+ MsoCloudifyException mce = new MsoCloudifyException(200, "message", "detail");
+ MsoCloudifyException mcl = new MsoCloudifyException(200, "message", "detail", e);
mce.setPendingWorkflow(pendingWorkflow);
- assert(mcl.toString()!=null);
+ assert (mcl.toString() != null);
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java
index a1859e491a..08b2356fdc 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java
@@ -1,35 +1,29 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * 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
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ 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
+ * 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.
+ * 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.so.cloudify.exceptions;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class MsoCloudifyTest {
-
- @Test
+
+ @Test
public void test() {
- MsoBlueprintAlreadyExists mbae=new MsoBlueprintAlreadyExists("blueprintId", "cloud");
- MsoCloudifyManagerNotFound mcm=new MsoCloudifyManagerNotFound("cloudSiteId");
- MsoDeploymentAlreadyExists mdae=new MsoDeploymentAlreadyExists("deploymentId", "cloud");
+ MsoBlueprintAlreadyExists mbae = new MsoBlueprintAlreadyExists("blueprintId", "cloud");
+ MsoCloudifyManagerNotFound mcm = new MsoCloudifyManagerNotFound("cloudSiteId");
+ MsoDeploymentAlreadyExists mdae = new MsoDeploymentAlreadyExists("deploymentId", "cloud");
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java
index 21c625feb3..48c5c877a5 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java
@@ -1,38 +1,32 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * 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
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ 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
+ * 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.
+ * 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.so.cloudify.exceptions;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
-
import org.junit.Test;
import org.onap.so.cloudify.v3.model.Execution;
public class MsoCloudifyTimeoutTest {
-
- @Test
+
+ @Test
public void test() {
- Execution execution=mock(Execution.class);
- MsoCloudifyTimeout mct=new MsoCloudifyTimeout(execution);
+ Execution execution = mock(Execution.class);
+ MsoCloudifyTimeout mct = new MsoCloudifyTimeout(execution);
mct.getExecution();
- assert(mct.toString()!=null);
+ assert (mct.toString() != null);
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java
index 68df574611..b8b2c97a65 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java
@@ -1,36 +1,31 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * 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
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ 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
+ * 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.
+ * 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.so.cloudify.exceptions;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class MsoCloudifyWorkflowExceptionTest {
-
- @Test
+
+ @Test
public void test() {
- MsoCloudifyWorkflowException mcw=new MsoCloudifyWorkflowException("message", "id", "workflowId", "workflowStatus");
+ MsoCloudifyWorkflowException mcw =
+ new MsoCloudifyWorkflowException("message", "id", "workflowId", "workflowStatus");
mcw.getWorkflowStatus();
assertFalse(mcw.isWorkflowStillRunning());
-
+
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java
index 833b4ab760..d14115971c 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java
@@ -33,7 +33,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
@@ -42,7 +41,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
@@ -67,7 +65,6 @@ import org.onap.so.db.catalog.beans.HeatTemplateParam;
import org.onap.so.openstack.exceptions.MsoAdapterException;
import org.onap.so.openstack.exceptions.MsoException;
import org.skyscreamer.jsonassert.JSONAssert;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -76,273 +73,264 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class MsoCloudifyUtilsTest {
- private static final String CLOUD_SITE_ID = "cloudSiteIdTest";
- private static final String BLUEPRINT_ID = "bluePrintIdTest";
- private static final String FILE_NAME = "fileName";
-
- @Test
- public void instantiateVduTest() throws MsoException {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("id");
- expected.setVduInstanceName("id");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.INSTANTIATED);
- status.setLastAction(new PluginAction(null, null, null));
- expected.setStatus(status);
-
- MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class);
- CloudSite site = new CloudSite();
- Optional<CloudSite> opSite = Optional.ofNullable(site);
- CloudConfig config = Mockito.mock(CloudConfig.class);
- cloudify.cloudConfig = config;
- Cloudify cloudifyClient = new Cloudify("cloudSite");
- CloudInfo cloudInfo = new CloudInfo();
- cloudInfo.setCloudSiteId("cloudSiteId");
- cloudInfo.setTenantId("tenantId");
- VduModelInfo vduModel = new VduModelInfo();
- vduModel.setModelCustomizationUUID("blueprintId");
- vduModel.setTimeoutMinutes(1);
- VduArtifact artifact = new VduArtifact();
- artifact.setName("name");
- artifact.setType(ArtifactType.MAIN_TEMPLATE);
- byte[] content = new byte[1];
- artifact.setContent(content);
- List<VduArtifact> artifacts = new ArrayList<>();
- artifacts.add(artifact);
- vduModel.setArtifacts(artifacts);
- DeploymentInfo deployment = new DeploymentInfoBuilder()
- .withId("id")
- .withStatus(DeploymentStatus.INSTALLED)
- .build();
- Map<String, byte[]> blueprintFiles = new HashMap<>();
- blueprintFiles.put(artifact.getName(), artifact.getContent());
- String instanceName = "instanceName";
- Map<String, Object> inputs = new HashMap<>();
- boolean rollbackOnFailure = true;
-
- when(config.getCloudSite(cloudInfo.getCloudSiteId())).thenReturn(opSite);
- doReturn(false).when(cloudify).isBlueprintLoaded(cloudInfo.getCloudSiteId(),
- vduModel.getModelCustomizationUUID());
- doReturn(cloudifyClient).when(cloudify).getCloudifyClient(site);
- doReturn(true).when(cloudify).uploadBlueprint(cloudifyClient, vduModel.getModelCustomizationUUID(),
- artifact.getName(), blueprintFiles);
- doReturn(deployment).when(cloudify).createAndInstallDeployment(cloudInfo.getCloudSiteId(),
- cloudInfo.getTenantId(), instanceName, vduModel.getModelCustomizationUUID(), inputs, true,
- vduModel.getTimeoutMinutes(), rollbackOnFailure);
-
- VduInstance actual = cloudify.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void queryVduTest() throws MsoException {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("id");
- expected.setVduInstanceName("id");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.INSTANTIATED);
- status.setLastAction(new PluginAction(null, null, null));
- expected.setStatus(status);
-
- CloudInfo cloudInfo = new CloudInfo();
- cloudInfo.setCloudSiteId("cloudSiteId");
- cloudInfo.setTenantId("tenantId");
- DeploymentInfo deployment = new DeploymentInfoBuilder()
- .withId("id")
- .withStatus(DeploymentStatus.INSTALLED)
- .build();
- String instanceId = "instanceId";
-
- MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class);
-
- doReturn(deployment).when(cloudify).queryDeployment(cloudInfo.getCloudSiteId(), cloudInfo.getTenantId(),
- instanceId);
-
- VduInstance actual = cloudify.queryVdu(cloudInfo, instanceId);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void deleteVduTest() throws MsoException {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("id");
- expected.setVduInstanceName("id");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.DELETING);
- status.setLastAction(new PluginAction("deleting", null, null));
- expected.setStatus(status);
-
- CloudInfo cloudInfo = new CloudInfo();
- cloudInfo.setCloudSiteId("cloudSiteId");
- cloudInfo.setTenantId("tenantId");
- String instanceId = "instanceId";
- int timeoutMinutes = 1;
- DeploymentInfo deploymentInfo = new DeploymentInfoBuilder()
- .withId("id")
- .withStatus(DeploymentStatus.CREATED)
- .withLastAction("deleting").build();
- MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class);
- doReturn(deploymentInfo).when(cloudify).uninstallAndDeleteDeployment(cloudInfo.getCloudSiteId(),
- cloudInfo.getTenantId(), instanceId, timeoutMinutes);
-
- VduInstance actual = cloudify.deleteVdu(cloudInfo, instanceId, timeoutMinutes);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void deploymentInfoToVduInstanceTest() {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("id");
- expected.setVduInstanceName("id");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.DELETING);
- status.setLastAction(new PluginAction("deleting", null, null));
- expected.setStatus(status);
-
- DeploymentInfo deploymentInfo = new DeploymentInfoBuilder()
- .withId("id")
- .withStatus(DeploymentStatus.CREATED)
- .withLastAction("deleting").build();
-
- MsoCloudifyUtils cloudify = new MsoCloudifyUtils();
-
- VduInstance actual = cloudify.deploymentInfoToVduInstance(deploymentInfo);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void deploymentStatusToVduStatusTest() {
- VduStatus expected = new VduStatus();
- expected.setState(VduStateType.DELETING);
- expected.setLastAction(new PluginAction("deleting", null, null));
-
- DeploymentInfo deploymentInfo = new DeploymentInfoBuilder()
- .withId("id")
- .withStatus(DeploymentStatus.CREATED)
- .withLastAction("deleting").build();
-
- MsoCloudifyUtils cloudify = new MsoCloudifyUtils();
-
- VduStatus actual = cloudify.deploymentStatusToVduStatus(deploymentInfo);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void getAzureConfigTest() {
- AzureConfig expected = new AzureConfig();
- expected.setSubscriptionId("subscriptionId");
- expected.setTenantId("tenantId");
- expected.setClientId("msoId");
- expected.setClientSecret("msoPass");
-
- MsoCloudifyUtils cloudify = new MsoCloudifyUtils();
- CloudSite cloudSite = Mockito.mock(CloudSite.class);
- CloudIdentity cloudIdentity = Mockito.mock(CloudIdentity.class);
- when(cloudSite.getIdentityService()).thenReturn(cloudIdentity);
- when(cloudIdentity.getAdminTenant()).thenReturn("subscriptionId");
- when(cloudIdentity.getMsoId()).thenReturn("msoId");
- when(cloudIdentity.getMsoPass()).thenReturn("msoPass");
- String tenantId = "tenantId";
- AzureConfig actual = cloudify.getAzureConfig(cloudSite, tenantId);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void uploadBlueprintSuccessful() throws MsoException {
- // given
- MsoCloudifyUtils testedObjectSpy = spy(MsoCloudifyUtils.class);
- testedObjectSpy.cloudConfig = mock(CloudConfig.class);
- Map<String, byte[]> blueprints = new HashMap<>();
-
- mockCloudConfig(testedObjectSpy);
- doReturn(true).when(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID),
- eq(FILE_NAME), eq(blueprints));
- // when
- testedObjectSpy.uploadBlueprint(CLOUD_SITE_ID, BLUEPRINT_ID, FILE_NAME, blueprints, true);
- // then
- verify(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME),
- eq(blueprints));
- }
-
- @Test
- public void uploadBlueprint_exceptionThrown_blueprintExists() throws MsoException {
- // given
- MsoCloudifyUtils testedObjectSpy = spy(MsoCloudifyUtils.class);
- testedObjectSpy.cloudConfig = mock(CloudConfig.class);
- Map<String, byte[]> blueprints = new HashMap<>();
-
- mockCloudConfig(testedObjectSpy);
- doReturn(false).when(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID),
- eq(FILE_NAME), eq(blueprints));
- // when
- try {
- testedObjectSpy.uploadBlueprint(CLOUD_SITE_ID, BLUEPRINT_ID, FILE_NAME, blueprints, true);
- // then
- fail("MsoAdapterException should be thrown");
- } catch (MsoAdapterException e) {
- Assert.assertEquals(e.getMessage(), "Blueprint already exists");
- }
- verify(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME),
- eq(blueprints));
- }
-
- @Test
- public void convertInputValueTest() throws JsonParseException, JsonMappingException, IOException {
- MsoCloudifyUtils utils = new MsoCloudifyUtils();
- ObjectMapper mapper = new ObjectMapper();
- HeatTemplateParam paramNum = new HeatTemplateParam();
- paramNum.setParamType("number");
- paramNum.setParamName("my-number");
-
- HeatTemplateParam paramString = new HeatTemplateParam();
- paramString.setParamType("string");
- paramString.setParamName("my-string");
-
- HeatTemplateParam paramJson = new HeatTemplateParam();
- paramJson.setParamType("json");
- paramJson.setParamName("my-json");
-
- HeatTemplateParam paramJsonEscaped = new HeatTemplateParam();
- paramJsonEscaped.setParamType("json");
- paramJsonEscaped.setParamName("my-json-escaped");
-
- Map<String, Object> jsonMap = mapper.readValue(getJson("free-form.json"), new TypeReference<Map<String, Object>>(){});
-
- assertEquals(3, utils.convertInputValue("3", paramNum));
- assertEquals("hello", utils.convertInputValue("hello", paramString));
- assertTrue("expect no change in type", utils.convertInputValue(jsonMap, paramJson) instanceof Map);
- assertTrue("expect string to become jsonNode", utils.convertInputValue(getJson("free-form.json"), paramJsonEscaped) instanceof JsonNode);
-
- JSONAssert.assertEquals(getJson("free-form.json"), mapper.writeValueAsString(utils.convertInputValue(getJson("free-form.json"), paramJsonEscaped)), false);
-
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/MsoHeatUtils/" + filename)));
- }
-
- private void mockCloudConfig(MsoCloudifyUtils testedObjectSpy) {
- CloudifyManager cloudifyManager = createCloudifyManager();
- when(testedObjectSpy.cloudConfig.getCloudSite(CLOUD_SITE_ID)).thenReturn(Optional.of(createCloudSite()));
- when(testedObjectSpy.cloudConfig.getCloudifyManager(CLOUD_SITE_ID)).thenReturn(cloudifyManager);
- }
-
- private CloudifyManager createCloudifyManager() {
- CloudifyManager cloudifyManager = new CloudifyManager();
- cloudifyManager.setCloudifyUrl("cloudUrlTest");
- cloudifyManager.setPassword("546573746F736973546573746F736973");
- return cloudifyManager;
- }
-
- private CloudSite createCloudSite() {
- CloudSite cloudSite = new CloudSite();
- cloudSite.setCloudifyId(CLOUD_SITE_ID);
- return cloudSite;
- }
+ private static final String CLOUD_SITE_ID = "cloudSiteIdTest";
+ private static final String BLUEPRINT_ID = "bluePrintIdTest";
+ private static final String FILE_NAME = "fileName";
+
+ @Test
+ public void instantiateVduTest() throws MsoException {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("id");
+ expected.setVduInstanceName("id");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.INSTANTIATED);
+ status.setLastAction(new PluginAction(null, null, null));
+ expected.setStatus(status);
+
+ MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class);
+ CloudSite site = new CloudSite();
+ Optional<CloudSite> opSite = Optional.ofNullable(site);
+ CloudConfig config = Mockito.mock(CloudConfig.class);
+ cloudify.cloudConfig = config;
+ Cloudify cloudifyClient = new Cloudify("cloudSite");
+ CloudInfo cloudInfo = new CloudInfo();
+ cloudInfo.setCloudSiteId("cloudSiteId");
+ cloudInfo.setTenantId("tenantId");
+ VduModelInfo vduModel = new VduModelInfo();
+ vduModel.setModelCustomizationUUID("blueprintId");
+ vduModel.setTimeoutMinutes(1);
+ VduArtifact artifact = new VduArtifact();
+ artifact.setName("name");
+ artifact.setType(ArtifactType.MAIN_TEMPLATE);
+ byte[] content = new byte[1];
+ artifact.setContent(content);
+ List<VduArtifact> artifacts = new ArrayList<>();
+ artifacts.add(artifact);
+ vduModel.setArtifacts(artifacts);
+ DeploymentInfo deployment =
+ new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.INSTALLED).build();
+ Map<String, byte[]> blueprintFiles = new HashMap<>();
+ blueprintFiles.put(artifact.getName(), artifact.getContent());
+ String instanceName = "instanceName";
+ Map<String, Object> inputs = new HashMap<>();
+ boolean rollbackOnFailure = true;
+
+ when(config.getCloudSite(cloudInfo.getCloudSiteId())).thenReturn(opSite);
+ doReturn(false).when(cloudify).isBlueprintLoaded(cloudInfo.getCloudSiteId(),
+ vduModel.getModelCustomizationUUID());
+ doReturn(cloudifyClient).when(cloudify).getCloudifyClient(site);
+ doReturn(true).when(cloudify).uploadBlueprint(cloudifyClient, vduModel.getModelCustomizationUUID(),
+ artifact.getName(), blueprintFiles);
+ doReturn(deployment).when(cloudify).createAndInstallDeployment(cloudInfo.getCloudSiteId(),
+ cloudInfo.getTenantId(), instanceName, vduModel.getModelCustomizationUUID(), inputs, true,
+ vduModel.getTimeoutMinutes(), rollbackOnFailure);
+
+ VduInstance actual = cloudify.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void queryVduTest() throws MsoException {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("id");
+ expected.setVduInstanceName("id");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.INSTANTIATED);
+ status.setLastAction(new PluginAction(null, null, null));
+ expected.setStatus(status);
+
+ CloudInfo cloudInfo = new CloudInfo();
+ cloudInfo.setCloudSiteId("cloudSiteId");
+ cloudInfo.setTenantId("tenantId");
+ DeploymentInfo deployment =
+ new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.INSTALLED).build();
+ String instanceId = "instanceId";
+
+ MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class);
+
+ doReturn(deployment).when(cloudify).queryDeployment(cloudInfo.getCloudSiteId(), cloudInfo.getTenantId(),
+ instanceId);
+
+ VduInstance actual = cloudify.queryVdu(cloudInfo, instanceId);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void deleteVduTest() throws MsoException {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("id");
+ expected.setVduInstanceName("id");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.DELETING);
+ status.setLastAction(new PluginAction("deleting", null, null));
+ expected.setStatus(status);
+
+ CloudInfo cloudInfo = new CloudInfo();
+ cloudInfo.setCloudSiteId("cloudSiteId");
+ cloudInfo.setTenantId("tenantId");
+ String instanceId = "instanceId";
+ int timeoutMinutes = 1;
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.CREATED)
+ .withLastAction("deleting").build();
+ MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class);
+ doReturn(deploymentInfo).when(cloudify).uninstallAndDeleteDeployment(cloudInfo.getCloudSiteId(),
+ cloudInfo.getTenantId(), instanceId, timeoutMinutes);
+
+ VduInstance actual = cloudify.deleteVdu(cloudInfo, instanceId, timeoutMinutes);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void deploymentInfoToVduInstanceTest() {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("id");
+ expected.setVduInstanceName("id");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.DELETING);
+ status.setLastAction(new PluginAction("deleting", null, null));
+ expected.setStatus(status);
+
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.CREATED)
+ .withLastAction("deleting").build();
+
+ MsoCloudifyUtils cloudify = new MsoCloudifyUtils();
+
+ VduInstance actual = cloudify.deploymentInfoToVduInstance(deploymentInfo);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void deploymentStatusToVduStatusTest() {
+ VduStatus expected = new VduStatus();
+ expected.setState(VduStateType.DELETING);
+ expected.setLastAction(new PluginAction("deleting", null, null));
+
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.CREATED)
+ .withLastAction("deleting").build();
+
+ MsoCloudifyUtils cloudify = new MsoCloudifyUtils();
+
+ VduStatus actual = cloudify.deploymentStatusToVduStatus(deploymentInfo);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void getAzureConfigTest() {
+ AzureConfig expected = new AzureConfig();
+ expected.setSubscriptionId("subscriptionId");
+ expected.setTenantId("tenantId");
+ expected.setClientId("msoId");
+ expected.setClientSecret("msoPass");
+
+ MsoCloudifyUtils cloudify = new MsoCloudifyUtils();
+ CloudSite cloudSite = Mockito.mock(CloudSite.class);
+ CloudIdentity cloudIdentity = Mockito.mock(CloudIdentity.class);
+ when(cloudSite.getIdentityService()).thenReturn(cloudIdentity);
+ when(cloudIdentity.getAdminTenant()).thenReturn("subscriptionId");
+ when(cloudIdentity.getMsoId()).thenReturn("msoId");
+ when(cloudIdentity.getMsoPass()).thenReturn("msoPass");
+ String tenantId = "tenantId";
+ AzureConfig actual = cloudify.getAzureConfig(cloudSite, tenantId);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void uploadBlueprintSuccessful() throws MsoException {
+ // given
+ MsoCloudifyUtils testedObjectSpy = spy(MsoCloudifyUtils.class);
+ testedObjectSpy.cloudConfig = mock(CloudConfig.class);
+ Map<String, byte[]> blueprints = new HashMap<>();
+
+ mockCloudConfig(testedObjectSpy);
+ doReturn(true).when(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME),
+ eq(blueprints));
+ // when
+ testedObjectSpy.uploadBlueprint(CLOUD_SITE_ID, BLUEPRINT_ID, FILE_NAME, blueprints, true);
+ // then
+ verify(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME), eq(blueprints));
+ }
+
+ @Test
+ public void uploadBlueprint_exceptionThrown_blueprintExists() throws MsoException {
+ // given
+ MsoCloudifyUtils testedObjectSpy = spy(MsoCloudifyUtils.class);
+ testedObjectSpy.cloudConfig = mock(CloudConfig.class);
+ Map<String, byte[]> blueprints = new HashMap<>();
+
+ mockCloudConfig(testedObjectSpy);
+ doReturn(false).when(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME),
+ eq(blueprints));
+ // when
+ try {
+ testedObjectSpy.uploadBlueprint(CLOUD_SITE_ID, BLUEPRINT_ID, FILE_NAME, blueprints, true);
+ // then
+ fail("MsoAdapterException should be thrown");
+ } catch (MsoAdapterException e) {
+ Assert.assertEquals(e.getMessage(), "Blueprint already exists");
+ }
+ verify(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME), eq(blueprints));
+ }
+
+ @Test
+ public void convertInputValueTest() throws JsonParseException, JsonMappingException, IOException {
+ MsoCloudifyUtils utils = new MsoCloudifyUtils();
+ ObjectMapper mapper = new ObjectMapper();
+ HeatTemplateParam paramNum = new HeatTemplateParam();
+ paramNum.setParamType("number");
+ paramNum.setParamName("my-number");
+
+ HeatTemplateParam paramString = new HeatTemplateParam();
+ paramString.setParamType("string");
+ paramString.setParamName("my-string");
+
+ HeatTemplateParam paramJson = new HeatTemplateParam();
+ paramJson.setParamType("json");
+ paramJson.setParamName("my-json");
+
+ HeatTemplateParam paramJsonEscaped = new HeatTemplateParam();
+ paramJsonEscaped.setParamType("json");
+ paramJsonEscaped.setParamName("my-json-escaped");
+
+ Map<String, Object> jsonMap =
+ mapper.readValue(getJson("free-form.json"), new TypeReference<Map<String, Object>>() {});
+
+ assertEquals(3, utils.convertInputValue("3", paramNum));
+ assertEquals("hello", utils.convertInputValue("hello", paramString));
+ assertTrue("expect no change in type", utils.convertInputValue(jsonMap, paramJson) instanceof Map);
+ assertTrue("expect string to become jsonNode",
+ utils.convertInputValue(getJson("free-form.json"), paramJsonEscaped) instanceof JsonNode);
+
+ JSONAssert.assertEquals(getJson("free-form.json"),
+ mapper.writeValueAsString(utils.convertInputValue(getJson("free-form.json"), paramJsonEscaped)), false);
+
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/MsoHeatUtils/" + filename)));
+ }
+
+ private void mockCloudConfig(MsoCloudifyUtils testedObjectSpy) {
+ CloudifyManager cloudifyManager = createCloudifyManager();
+ when(testedObjectSpy.cloudConfig.getCloudSite(CLOUD_SITE_ID)).thenReturn(Optional.of(createCloudSite()));
+ when(testedObjectSpy.cloudConfig.getCloudifyManager(CLOUD_SITE_ID)).thenReturn(cloudifyManager);
+ }
+
+ private CloudifyManager createCloudifyManager() {
+ CloudifyManager cloudifyManager = new CloudifyManager();
+ cloudifyManager.setCloudifyUrl("cloudUrlTest");
+ cloudifyManager.setPassword("546573746F736973546573746F736973");
+ return cloudifyManager;
+ }
+
+ private CloudSite createCloudSite() {
+ CloudSite cloudSite = new CloudSite();
+ cloudSite.setCloudifyId(CLOUD_SITE_ID);
+ return cloudSite;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java
index 1884b3243a..870b4d98f2 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java
@@ -28,15 +28,15 @@ import org.springframework.beans.factory.annotation.Autowired;
public class PoConfigTest extends BaseTest {
-
- @Autowired
- private PoConfig poConfig;
-
-
- @Test
- public void tenantConfigValues() {
- assertEquals("504", poConfig.getRetryCodes());
- assertEquals(5, poConfig.getRetryDelay());
-
- }
+
+ @Autowired
+ private PoConfig poConfig;
+
+
+ @Test
+ public void tenantConfigValues() {
+ assertEquals("504", poConfig.getRetryCodes());
+ assertEquals(5, poConfig.getRetryDelay());
+
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java
index b675f4814d..f8d07250f5 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java
@@ -23,43 +23,41 @@ package org.onap.so.openstack.beans;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
import java.util.Calendar;
import java.util.GregorianCalendar;
-
import org.junit.Test;
import org.onap.so.BaseTest;
public class HeatCacheEntryTest {
-
- private static final String HEAT_URL = "testHeatUrl";
- private static final String TOKEN = "testToken";
- @Test
- public void getHeatClientTest() {
- Calendar expires = new GregorianCalendar(2013,0,31);
- HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
- assertNotNull(heatCacheEntry.getHeatClient());
- }
-
- @Test
- public void isExpiredTrueTest() {
- Calendar expires = new GregorianCalendar(2013,0,31);
- HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
- assertTrue(heatCacheEntry.isExpired());
- }
-
- @Test
- public void isExpiredFalseTest() {
- Calendar expires = new GregorianCalendar(2100,0,31);
- HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
- assertFalse(heatCacheEntry.isExpired());
- }
-
- @Test
- public void isExpiredNullTest() {
- Calendar expires = null;
- HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
- assertTrue(heatCacheEntry.isExpired());
- }
+ private static final String HEAT_URL = "testHeatUrl";
+ private static final String TOKEN = "testToken";
+
+ @Test
+ public void getHeatClientTest() {
+ Calendar expires = new GregorianCalendar(2013, 0, 31);
+ HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
+ assertNotNull(heatCacheEntry.getHeatClient());
+ }
+
+ @Test
+ public void isExpiredTrueTest() {
+ Calendar expires = new GregorianCalendar(2013, 0, 31);
+ HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
+ assertTrue(heatCacheEntry.isExpired());
+ }
+
+ @Test
+ public void isExpiredFalseTest() {
+ Calendar expires = new GregorianCalendar(2100, 0, 31);
+ HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
+ assertFalse(heatCacheEntry.isExpired());
+ }
+
+ @Test
+ public void isExpiredNullTest() {
+ Calendar expires = null;
+ HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
+ assertTrue(heatCacheEntry.isExpired());
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java
index 379501f206..ece5b21f19 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java
@@ -1,42 +1,36 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * 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
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ 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
+ * 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.
+ * 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.so.openstack.beans;
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Test;
public class MsoTenantTest {
- MsoTenant ms = new MsoTenant();
-
+ MsoTenant ms = new MsoTenant();
+
@Test
public void test() {
- Map<String, String> map = new HashMap<>();
- map.put("id","name");
- ms.setTenantId("tenantId");
- ms.setTenantName("tenantName");
- ms.setMetadata(map);
- assert(ms.getMetadata().equals(map));
- assert(ms.getTenantId().equals("tenantId"));
- assert(ms.getTenantName().equals("tenantName"));
+ Map<String, String> map = new HashMap<>();
+ map.put("id", "name");
+ ms.setTenantId("tenantId");
+ ms.setTenantName("tenantName");
+ ms.setMetadata(map);
+ assert (ms.getMetadata().equals(map));
+ assert (ms.getTenantId().equals("tenantId"));
+ assert (ms.getTenantName().equals("tenantName"));
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java
index 5a5e2bb75e..142007089a 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java
@@ -1,22 +1,17 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * 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
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ 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
+ * 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.
+ * 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.so.openstack.beans;
@@ -34,12 +29,12 @@ public class NetworkRollbackTest {
@InjectMocks
NetworkRollback nr = new NetworkRollback();
-
+
@Test
public void test() {
List<Integer> vlans = new ArrayList();
- vlans.add(1);
- vlans.add(2);
+ vlans.add(1);
+ vlans.add(2);
nr.setCloudId("cloudId");
nr.setModelCustomizationUuid("modelCustomizationUuid");
nr.setNetworkId("networkId");
@@ -52,18 +47,18 @@ public class NetworkRollbackTest {
nr.setNetworkCreated(false);
nr.setVlans(vlans);
nr.setMsoRequest(ms);
- assert(nr.getCloudId().equals("cloudId"));
- assert(nr.getModelCustomizationUuid().equals("modelCustomizationUuid"));
- assert(nr.getNetworkId().equals("networkId"));
- assert(nr.getNetworkName().equals("networkName"));
- assert(nr.getNetworkStackId().equals("networkStackId"));
- assert(nr.getNeutronNetworkId().equals("neutronNetworkId"));
- assert(nr.getPhysicalNetwork().equals("physicalNetwork"));
- assert(nr.getNetworkType().equals("networkType"));
- assert(nr.getTenantId().equals("tenantId"));
- assert(nr.getMsoRequest().equals(ms));
+ assert (nr.getCloudId().equals("cloudId"));
+ assert (nr.getModelCustomizationUuid().equals("modelCustomizationUuid"));
+ assert (nr.getNetworkId().equals("networkId"));
+ assert (nr.getNetworkName().equals("networkName"));
+ assert (nr.getNetworkStackId().equals("networkStackId"));
+ assert (nr.getNeutronNetworkId().equals("neutronNetworkId"));
+ assert (nr.getPhysicalNetwork().equals("physicalNetwork"));
+ assert (nr.getNetworkType().equals("networkType"));
+ assert (nr.getTenantId().equals("tenantId"));
+ assert (nr.getMsoRequest().equals(ms));
assertFalse(nr.getNetworkCreated());
- assert(nr.getVlans().equals(vlans));
- assert(nr.toString()!=null);
+ assert (nr.getVlans().equals(vlans));
+ assert (nr.toString() != null);
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java
index 8626e7d177..2c67431f02 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java
@@ -22,36 +22,34 @@ package org.onap.so.openstack.beans;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
import java.util.Calendar;
import java.util.GregorianCalendar;
-
import org.junit.Test;
import org.onap.so.BaseTest;
public class NeutronCacheEntryTest {
-
- private static final String NEUTRON_URL = "testNeutronUrl";
- private static final String TOKEN = "testToken";
-
- @Test
- public void isExpiredTrueTest() {
- Calendar expires = new GregorianCalendar(2013,0,31);
- NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires);
- assertTrue(neutronCacheEntry.isExpired());
- }
-
- @Test
- public void isExpiredFalseTest() {
- Calendar expires = new GregorianCalendar(2100,0,31);
- NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires);
- assertFalse(neutronCacheEntry.isExpired());
- }
-
- @Test
- public void isExpiredNullTest() {
- Calendar expires = null;
- NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires);
- assertTrue(neutronCacheEntry.isExpired());
- }
+
+ private static final String NEUTRON_URL = "testNeutronUrl";
+ private static final String TOKEN = "testToken";
+
+ @Test
+ public void isExpiredTrueTest() {
+ Calendar expires = new GregorianCalendar(2013, 0, 31);
+ NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires);
+ assertTrue(neutronCacheEntry.isExpired());
+ }
+
+ @Test
+ public void isExpiredFalseTest() {
+ Calendar expires = new GregorianCalendar(2100, 0, 31);
+ NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires);
+ assertFalse(neutronCacheEntry.isExpired());
+ }
+
+ @Test
+ public void isExpiredNullTest() {
+ Calendar expires = null;
+ NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires);
+ assertTrue(neutronCacheEntry.isExpired());
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java
index ac194ccee2..9c2ed66318 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java
@@ -30,18 +30,15 @@ import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
public class OpenstackBeansPojoTest {
- @Test
- public void pojoStructure() {
- test(PojoClassFactory.getPojoClass(VnfRollback.class));
- test(PojoClassFactory.getPojoClass(NeutronCacheEntry.class));
- test(PojoClassFactory.getPojoClass(HeatCacheEntry.class));
- }
-
- private void test(PojoClass pojoClass) {
- Validator validator = ValidatorBuilder.create()
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
- validator.validate(pojoClass);
- }
+ @Test
+ public void pojoStructure() {
+ test(PojoClassFactory.getPojoClass(VnfRollback.class));
+ test(PojoClassFactory.getPojoClass(NeutronCacheEntry.class));
+ test(PojoClassFactory.getPojoClass(HeatCacheEntry.class));
+ }
+
+ private void test(PojoClass pojoClass) {
+ Validator validator = ValidatorBuilder.create().with(new SetterTester()).with(new GetterTester()).build();
+ validator.validate(pojoClass);
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java
index 163f141c5d..f3614c1b09 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java
@@ -21,70 +21,73 @@
package org.onap.so.openstack.beans;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.BaseTest;
import org.onap.so.entity.MsoRequest;
import org.springframework.beans.factory.annotation.Autowired;
public class VnfRollbackTest extends BaseTest {
- @Autowired
- private VnfRollback vnfRollback;
-
- private String vnfId = "testVnfId";
- private String tenantId = "testTenantId";
- private String cloudSiteId = "testCloudSiteId";
- private boolean tenantCreated = true;
- private boolean vnfCreated = true;
- private MsoRequest msoRequest = new MsoRequest();
- private String volumeGroupName = "testVolumeGroupName";
- private String volumeGroupId = "testVolumeGroupId";
- private String requestType = "testRequestType";
- private String modelCustomizationUuid = "testModelCustimizationUuid";
- private String orchestrationMode = "testOrchestrationMode";
- private static final String VNF_ROLLBACK_STRING = "VnfRollback: cloud=testCloudSiteId, tenant=testTenantId, vnf=testVnfId, "
- + "tenantCreated=true, vnfCreated=true, requestType = testRequestType, modelCustomizationUuid=testModelCustimizationUuid, mode=testOrchestrationMode";
-
- @Test
- public void VnfRollbackInstantiationTest() {
- vnfRollback = new VnfRollback(vnfId, tenantId, cloudSiteId, tenantCreated, vnfCreated,
- msoRequest, volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid);
-
- assertEquals(vnfId, vnfRollback.getVnfId());
- assertEquals(tenantId, vnfRollback.getTenantId());
- assertEquals(cloudSiteId, vnfRollback.getCloudSiteId());
- assertEquals(tenantCreated, vnfRollback.getTenantCreated());
- assertEquals(vnfCreated, vnfRollback.getVnfCreated());
- assertEquals(msoRequest, vnfRollback.getMsoRequest());
- assertEquals(volumeGroupName, vnfRollback.getVolumeGroupName());
- assertEquals(volumeGroupId, vnfRollback.getVolumeGroupId());
- assertEquals(requestType, vnfRollback.getRequestType());
- assertEquals(modelCustomizationUuid, vnfRollback.getModelCustomizationUuid());
- }
-
- @Test
- public void VnfRollbackInstantiationOrchestrationModeTest() {
- vnfRollback = new VnfRollback(vnfId, tenantId, cloudSiteId, tenantCreated, vnfCreated,
- msoRequest, volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid, orchestrationMode);
-
- assertEquals(vnfId, vnfRollback.getVnfId());
- assertEquals(tenantId, vnfRollback.getTenantId());
- assertEquals(cloudSiteId, vnfRollback.getCloudSiteId());
- assertEquals(tenantCreated, vnfRollback.getTenantCreated());
- assertEquals(vnfCreated, vnfRollback.getVnfCreated());
- assertEquals(msoRequest, vnfRollback.getMsoRequest());
- assertEquals(volumeGroupName, vnfRollback.getVolumeGroupName());
- assertEquals(volumeGroupId, vnfRollback.getVolumeGroupId());
- assertEquals(requestType, vnfRollback.getRequestType());
- assertEquals(modelCustomizationUuid, vnfRollback.getModelCustomizationUuid());
- assertEquals(orchestrationMode, vnfRollback.getMode());
- }
-
- @Test
- public void toStringTest() {
- vnfRollback = new VnfRollback(vnfId, tenantId, cloudSiteId, tenantCreated, vnfCreated,
- msoRequest, volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid, orchestrationMode);
-
- assertEquals(VNF_ROLLBACK_STRING, vnfRollback.toString());
- }
+ @Autowired
+ private VnfRollback vnfRollback;
+
+ private String vnfId = "testVnfId";
+ private String tenantId = "testTenantId";
+ private String cloudOwner = "testCloudOwner";
+ private String cloudSiteId = "testCloudSiteId";
+ private boolean tenantCreated = true;
+ private boolean vnfCreated = true;
+ private MsoRequest msoRequest = new MsoRequest();
+ private String volumeGroupName = "testVolumeGroupName";
+ private String volumeGroupId = "testVolumeGroupId";
+ private String requestType = "testRequestType";
+ private String modelCustomizationUuid = "testModelCustimizationUuid";
+ private String orchestrationMode = "testOrchestrationMode";
+ private static final String VNF_ROLLBACK_STRING =
+ "VnfRollback: cloud=testCloudSiteId, cloudOwner=testCloudOwner, tenant=testTenantId, vnf=testVnfId, "
+ + "tenantCreated=true, vnfCreated=true, requestType = testRequestType, modelCustomizationUuid=testModelCustimizationUuid, mode=testOrchestrationMode";
+
+ @Test
+ public void VnfRollbackInstantiationTest() {
+ vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated, msoRequest,
+ volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid);
+
+ assertEquals(vnfId, vnfRollback.getVnfId());
+ assertEquals(tenantId, vnfRollback.getTenantId());
+ assertEquals(cloudOwner, vnfRollback.getCloudOwner());
+ assertEquals(cloudSiteId, vnfRollback.getCloudSiteId());
+ assertEquals(tenantCreated, vnfRollback.getTenantCreated());
+ assertEquals(vnfCreated, vnfRollback.getVnfCreated());
+ assertEquals(msoRequest, vnfRollback.getMsoRequest());
+ assertEquals(volumeGroupName, vnfRollback.getVolumeGroupName());
+ assertEquals(volumeGroupId, vnfRollback.getVolumeGroupId());
+ assertEquals(requestType, vnfRollback.getRequestType());
+ assertEquals(modelCustomizationUuid, vnfRollback.getModelCustomizationUuid());
+ }
+
+ @Test
+ public void VnfRollbackInstantiationOrchestrationModeTest() {
+ vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated, msoRequest,
+ volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid, orchestrationMode);
+
+ assertEquals(vnfId, vnfRollback.getVnfId());
+ assertEquals(tenantId, vnfRollback.getTenantId());
+ assertEquals(cloudOwner, vnfRollback.getCloudOwner());
+ assertEquals(cloudSiteId, vnfRollback.getCloudSiteId());
+ assertEquals(tenantCreated, vnfRollback.getTenantCreated());
+ assertEquals(vnfCreated, vnfRollback.getVnfCreated());
+ assertEquals(msoRequest, vnfRollback.getMsoRequest());
+ assertEquals(volumeGroupName, vnfRollback.getVolumeGroupName());
+ assertEquals(volumeGroupId, vnfRollback.getVolumeGroupId());
+ assertEquals(requestType, vnfRollback.getRequestType());
+ assertEquals(modelCustomizationUuid, vnfRollback.getModelCustomizationUuid());
+ assertEquals(orchestrationMode, vnfRollback.getMode());
+ }
+
+ @Test
+ public void toStringTest() {
+ vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated, msoRequest,
+ volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid, orchestrationMode);
+
+ assertEquals(VNF_ROLLBACK_STRING, vnfRollback.toString());
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java
index dbce712cb0..5cf7c86522 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java
@@ -27,10 +27,8 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
-
import java.io.File;
import java.io.IOException;
-
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -42,7 +40,6 @@ import org.onap.so.openstack.exceptions.MsoIOException;
import org.onap.so.openstack.exceptions.MsoOpenstackException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -59,149 +56,150 @@ import com.woorea.openstack.quantum.model.NeutronError;
* This class implements test methods of the MsoCommonUtils
*/
public class MsoCommonUtilsTest extends BaseTest {
- @Autowired
- @Qualifier("CommonUtils")
- private MsoCommonUtils commonUtils;
-
- @Mock
- private OpenStackRequest openstackRequest;
-
- @Test
+ @Autowired
+ @Qualifier("CommonUtils")
+ private MsoCommonUtils commonUtils;
+
+ @Mock
+ private OpenStackRequest openstackRequest;
+
+ @Test
public final void testExecuteAndRecordOpenstackRequest() {
- Mockito.when(openstackRequest.endpoint()).thenReturn("localhost");
- Mockito.when(openstackRequest.path()).thenReturn("/test");
- //TODO:Must try a real connection
- assertNull(commonUtils.executeAndRecordOpenstackRequest (openstackRequest));
- }
-
- @Test
- public void testexecuteAndRecordOpenstackRequestResponseException() {
- expectedException.expect(OpenStackResponseException.class);
-
- doThrow(OpenStackResponseException.class).when(openstackRequest).execute();
-
- commonUtils.executeAndRecordOpenstackRequest(openstackRequest);
- }
-
- @Test
- public void testexecuteAndRecordOpenstackRequestConnectException() {
- expectedException.expect(OpenStackConnectException.class);
-
- doThrow(OpenStackConnectException.class).when(openstackRequest).execute();
-
- commonUtils.executeAndRecordOpenstackRequest(openstackRequest);
- }
-
- @Test
+ Mockito.when(openstackRequest.endpoint()).thenReturn("localhost");
+ Mockito.when(openstackRequest.path()).thenReturn("/test");
+ // TODO:Must try a real connection
+ assertNull(commonUtils.executeAndRecordOpenstackRequest(openstackRequest));
+ }
+
+ @Test
+ public void testexecuteAndRecordOpenstackRequestResponseException() {
+ expectedException.expect(OpenStackResponseException.class);
+
+ doThrow(OpenStackResponseException.class).when(openstackRequest).execute();
+
+ commonUtils.executeAndRecordOpenstackRequest(openstackRequest);
+ }
+
+ @Test
+ public void testexecuteAndRecordOpenstackRequestConnectException() {
+ expectedException.expect(OpenStackConnectException.class);
+
+ doThrow(OpenStackConnectException.class).when(openstackRequest).execute();
+
+ commonUtils.executeAndRecordOpenstackRequest(openstackRequest);
+ }
+
+ @Test
public final void testKeystoneErrorToMsoException() throws JsonParseException, JsonMappingException, IOException {
- OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
-
- OpenStackBaseException openStackResponseException = new OpenStackResponseException("response",1);
-
- MsoException me = commonUtils.keystoneErrorToMsoException(openStackConnectException,"ContextError");
-
- assertTrue(me instanceof MsoIOException);
- assertTrue("connect".equals(me.getMessage()));
-
-
- MsoException me2 = commonUtils.keystoneErrorToMsoException(openStackResponseException,"ContextError");
- assertTrue(me2 instanceof MsoOpenstackException);
- assertTrue("ContextError".equals(me2.getContext()));
- assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
-
-
- OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
- Error error = mapper.readValue(new File(RESOURCE_PATH + "Error.json"), Error.class);
-
- doReturn(error).when(openStackResponse).getErrorEntity(eq(Error.class));
-
- openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
-
- MsoException me3 = commonUtils.keystoneErrorToMsoException(openStackResponseException,"ContextError");
-
- assertTrue(me3 instanceof MsoOpenstackException);
- assertEquals("1 title: message", me3.toString());
- }
-
- @Test
- public final void testHeatExceptionToMsoException() throws JsonParseException, JsonMappingException, IOException {
- OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
-
- OpenStackBaseException openStackResponseException = new OpenStackResponseException("response",1);
-
- MsoException me = commonUtils.heatExceptionToMsoException(openStackConnectException,"ContextError");
-
- assertTrue(me instanceof MsoIOException);
- assertTrue("connect".equals(me.getMessage()));
-
-
- MsoException me2 = commonUtils.heatExceptionToMsoException(openStackResponseException,"ContextError");
- assertTrue(me2 instanceof MsoOpenstackException);
- assertTrue("ContextError".equals(me2.getContext()));
- assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
-
-
- OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
- Explanation explanation = mapper.readValue(new File(RESOURCE_PATH + "Explanation.json"), Explanation.class);
-
- doReturn(explanation).when(openStackResponse).getErrorEntity(eq(Explanation.class));
-
- openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
-
- MsoException me3 = commonUtils.heatExceptionToMsoException(openStackResponseException,"ContextError");
-
- assertTrue(me3 instanceof MsoOpenstackException);
- assertEquals("1 title: explanation, error.type=null, error.message=null", me3.toString());
- }
-
- @Test
- public final void testNeutronExceptionToMsoException() throws JsonParseException, JsonMappingException, IOException {
- OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
-
- OpenStackBaseException openStackResponseException = new OpenStackResponseException("response",1);
-
- MsoException me = commonUtils.neutronExceptionToMsoException(openStackConnectException,"ContextError");
-
- assertTrue(me instanceof MsoIOException);
- assertTrue("connect".equals(me.getMessage()));
-
- MsoException me2 = commonUtils.neutronExceptionToMsoException(openStackResponseException,"ContextError");
- assertTrue(me2 instanceof MsoOpenstackException);
- assertTrue("ContextError".equals(me2.getContext()));
- assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
-
-
- OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
- NeutronError explanation = mapper.readValue(new File(RESOURCE_PATH + "NeutronError.json"), NeutronError.class);
-
- doReturn(explanation).when(openStackResponse).getErrorEntity(eq(NeutronError.class));
-
- openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
-
- MsoException me3 = commonUtils.neutronExceptionToMsoException(openStackResponseException,"ContextError");
-
- assertTrue(me3 instanceof MsoOpenstackException);
- assertEquals("501 type: message", me3.toString());
- }
-
- @Test
- public final void testRuntimeExceptionToMsoException() {
- RuntimeException re = new RuntimeException("runtime");
- MsoException me = commonUtils.runtimeExceptionToMsoException(re, "ContextError");
-
- assertTrue(me instanceof MsoAdapterException);
- assertTrue("ContextError".equals(me.getContext()));
+ OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
+
+ OpenStackBaseException openStackResponseException = new OpenStackResponseException("response", 1);
+
+ MsoException me = commonUtils.keystoneErrorToMsoException(openStackConnectException, "ContextError");
+
+ assertTrue(me instanceof MsoIOException);
+ assertTrue("connect".equals(me.getMessage()));
+
+
+ MsoException me2 = commonUtils.keystoneErrorToMsoException(openStackResponseException, "ContextError");
+ assertTrue(me2 instanceof MsoOpenstackException);
+ assertTrue("ContextError".equals(me2.getContext()));
+ assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
+
+
+ OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
+ Error error = mapper.readValue(new File(RESOURCE_PATH + "Error.json"), Error.class);
+
+ doReturn(error).when(openStackResponse).getErrorEntity(eq(Error.class));
+
+ openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
+
+ MsoException me3 = commonUtils.keystoneErrorToMsoException(openStackResponseException, "ContextError");
+
+ assertTrue(me3 instanceof MsoOpenstackException);
+ assertEquals("1 title: message", me3.toString());
+ }
+
+ @Test
+ public final void testHeatExceptionToMsoException() throws JsonParseException, JsonMappingException, IOException {
+ OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
+
+ OpenStackBaseException openStackResponseException = new OpenStackResponseException("response", 1);
+
+ MsoException me = commonUtils.heatExceptionToMsoException(openStackConnectException, "ContextError");
+
+ assertTrue(me instanceof MsoIOException);
+ assertTrue("connect".equals(me.getMessage()));
+
+
+ MsoException me2 = commonUtils.heatExceptionToMsoException(openStackResponseException, "ContextError");
+ assertTrue(me2 instanceof MsoOpenstackException);
+ assertTrue("ContextError".equals(me2.getContext()));
+ assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
+
+
+ OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
+ Explanation explanation = mapper.readValue(new File(RESOURCE_PATH + "Explanation.json"), Explanation.class);
+
+ doReturn(explanation).when(openStackResponse).getErrorEntity(eq(Explanation.class));
+
+ openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
+
+ MsoException me3 = commonUtils.heatExceptionToMsoException(openStackResponseException, "ContextError");
+
+ assertTrue(me3 instanceof MsoOpenstackException);
+ assertEquals("1 title: explanation, error.type=null, error.message=null", me3.toString());
+ }
+
+ @Test
+ public final void testNeutronExceptionToMsoException()
+ throws JsonParseException, JsonMappingException, IOException {
+ OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
+
+ OpenStackBaseException openStackResponseException = new OpenStackResponseException("response", 1);
+
+ MsoException me = commonUtils.neutronExceptionToMsoException(openStackConnectException, "ContextError");
+
+ assertTrue(me instanceof MsoIOException);
+ assertTrue("connect".equals(me.getMessage()));
+
+ MsoException me2 = commonUtils.neutronExceptionToMsoException(openStackResponseException, "ContextError");
+ assertTrue(me2 instanceof MsoOpenstackException);
+ assertTrue("ContextError".equals(me2.getContext()));
+ assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
+
+
+ OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
+ NeutronError explanation = mapper.readValue(new File(RESOURCE_PATH + "NeutronError.json"), NeutronError.class);
+
+ doReturn(explanation).when(openStackResponse).getErrorEntity(eq(NeutronError.class));
+
+ openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
+
+ MsoException me3 = commonUtils.neutronExceptionToMsoException(openStackResponseException, "ContextError");
+
+ assertTrue(me3 instanceof MsoOpenstackException);
+ assertEquals("501 type: message", me3.toString());
+ }
+
+ @Test
+ public final void testRuntimeExceptionToMsoException() {
+ RuntimeException re = new RuntimeException("runtime");
+ MsoException me = commonUtils.runtimeExceptionToMsoException(re, "ContextError");
+
+ assertTrue(me instanceof MsoAdapterException);
+ assertTrue("ContextError".equals(me.getContext()));
assertTrue(MsoExceptionCategory.INTERNAL.equals(me.getCategory()));
- }
-
- @Test
- public void testIoExceptionToMsoException() {
- IOException exception = new IOException("IOExceptionTestMessage");
-
- MsoException msoException = commonUtils.ioExceptionToMsoException(exception, "ContextError");
-
- assertTrue(msoException instanceof MsoAdapterException);
- assertEquals("ContextError", msoException.getContext());
- assertTrue(MsoExceptionCategory.INTERNAL.equals(msoException.getCategory()));
- }
+ }
+
+ @Test
+ public void testIoExceptionToMsoException() {
+ IOException exception = new IOException("IOExceptionTestMessage");
+
+ MsoException msoException = commonUtils.ioExceptionToMsoException(exception, "ContextError");
+
+ assertTrue(msoException instanceof MsoAdapterException);
+ assertEquals("ContextError", msoException.getContext());
+ assertTrue(MsoExceptionCategory.INTERNAL.equals(msoException.getCategory()));
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java
index 700d03dad3..1b98f14e8c 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java
@@ -25,16 +25,13 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
-
import org.junit.Test;
import org.onap.so.TestDataSetup;
import org.onap.so.db.catalog.beans.HeatTemplateParam;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -43,8 +40,8 @@ public class MsoHeatEnvironmentEntryTest extends TestDataSetup {
private static final String PARAMETER_NAME = "keyTest";
private static final String VALUE_NAME = "valueTest";
private static final String NOT_EXISTING_PARAM = "notExistingParam";
- private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY = "parameters: {"
- + PARAMETER_NAME + ": " + VALUE_NAME + "}";
+ private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY =
+ "parameters: {" + PARAMETER_NAME + ": " + VALUE_NAME + "}";
private static final String RAW_ENTRY_WITH_RESOURCE_REGISTRY = "resource_registry: resourceTest";
private static final String RAW_ENTRY_INVALID = "invalidRawEntry";
@@ -57,13 +54,15 @@ public class MsoHeatEnvironmentEntryTest extends TestDataSetup {
}
@Test
- public void toFullString_ResourceRegistryNotPresentInRawEntry() throws JsonParseException, JsonMappingException, IOException {
+ public void toFullString_ResourceRegistryNotPresentInRawEntry()
+ throws JsonParseException, JsonMappingException, IOException {
StringBuilder sb = new StringBuilder(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY);
-
+
MsoHeatEnvironmentEntry testedObject = new MsoHeatEnvironmentEntry(sb);
-
- HeatTemplateParam heatTemplateParam = mapper.readValue(new File(RESOURCE_PATH + "HeatTemplateParam.json"), HeatTemplateParam.class);
-
+
+ HeatTemplateParam heatTemplateParam =
+ mapper.readValue(new File(RESOURCE_PATH + "HeatTemplateParam.json"), HeatTemplateParam.class);
+
assertThat(testedObject.getRawEntry()).isEqualTo(sb);
assertThat(testedObject.isValid()).isTrue();
assertThat(testedObject.containsParameter(PARAMETER_NAME)).isTrue();
@@ -71,18 +70,22 @@ public class MsoHeatEnvironmentEntryTest extends TestDataSetup {
assertTrue(testedObject.containsParameter(PARAMETER_NAME, "dummyAlias"));
assertTrue(testedObject.containsParameter("dummyName", PARAMETER_NAME));
assertFalse(testedObject.containsParameter("dummyName", "dummyAlias"));
- assertEquals("parameters:\n " + PARAMETER_NAME + ": " + VALUE_NAME + "\n\n\n", testedObject.toFullString().toString());
- assertEquals("parameters:\n " + PARAMETER_NAME + ": " + VALUE_NAME + "\n\n\n", testedObject.toFullStringExcludeNonParams(new HashSet<HeatTemplateParam>(Arrays.asList(heatTemplateParam))).toString());
+ assertEquals("parameters:\n " + PARAMETER_NAME + ": " + VALUE_NAME + "\n\n\n",
+ testedObject.toFullString().toString());
+ assertEquals("parameters:\n " + PARAMETER_NAME + ": " + VALUE_NAME + "\n\n\n",
+ testedObject
+ .toFullStringExcludeNonParams(new HashSet<HeatTemplateParam>(Arrays.asList(heatTemplateParam)))
+ .toString());
assertEquals(1, testedObject.getNumberOfParameters());
assertFalse(testedObject.hasResources());
-
+
MsoHeatEnvironmentResource heatResource = new MsoHeatEnvironmentResource("resourceName", "resourceValue");
MsoHeatEnvironmentParameter heatParameter = new MsoHeatEnvironmentParameter("parameterName", "parameterValue");
testedObject.addResource(heatResource);
testedObject.addParameter(heatParameter);
assertEquals(1, testedObject.getNumberOfResources());
assertEquals(2, testedObject.getNumberOfParameters());
-
+
testedObject.setResources(null);
testedObject.setParameters(null);
assertNull(testedObject.getParameters());
@@ -91,7 +94,7 @@ public class MsoHeatEnvironmentEntryTest extends TestDataSetup {
@Test
public void toFullString_ExceptionOccurred() {
- StringBuilder sb = new StringBuilder(RAW_ENTRY_INVALID);
+ StringBuilder sb = new StringBuilder(RAW_ENTRY_INVALID);
MsoHeatEnvironmentEntry testedObject = new MsoHeatEnvironmentEntry(sb);
assertThat(testedObject.getRawEntry()).isEqualTo(sb);
assertThat(testedObject.isValid()).isFalse();
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java
index 182a6d0e02..954f237ffe 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java
@@ -1,46 +1,40 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * 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
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ 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
+ * 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.
+ * 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.so.openstack.utils;
import static org.mockito.Mockito.mock;
-
import org.junit.Test;
public class MsoHeatEnvironmentParameterTest {
- @Test
- public void test() {
- MsoHeatEnvironmentParameter hep=mock(MsoHeatEnvironmentParameter.class);
- Object op=hep.getName();
- MsoHeatEnvironmentParameter meo=new MsoHeatEnvironmentParameter();
- MsoHeatEnvironmentParameter mea=new MsoHeatEnvironmentParameter("name");
- MsoHeatEnvironmentParameter mep=new MsoHeatEnvironmentParameter("name"," value");
- mea.setName("name");
- mep.setValue("value");
- assert(mea.getName().equals("name"));
- assert(mep.getValue().equals("value"));
- assert(meo.toString()!=null);
- //assertTrue(op.equals(hep));
- meo.equals(op);
- meo.hashCode();
- }
+ @Test
+ public void test() {
+ MsoHeatEnvironmentParameter hep = mock(MsoHeatEnvironmentParameter.class);
+ Object op = hep.getName();
+ MsoHeatEnvironmentParameter meo = new MsoHeatEnvironmentParameter();
+ MsoHeatEnvironmentParameter mea = new MsoHeatEnvironmentParameter("name");
+ MsoHeatEnvironmentParameter mep = new MsoHeatEnvironmentParameter("name", " value");
+ mea.setName("name");
+ mep.setValue("value");
+ assert (mea.getName().equals("name"));
+ assert (mep.getValue().equals("value"));
+ assert (meo.toString() != null);
+ // assertTrue(op.equals(hep));
+ meo.equals(op);
+ meo.hashCode();
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java
index 934c149055..2c67dfd009 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java
@@ -1,49 +1,43 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * 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
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ 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
+ * 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.
+ * 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.so.openstack.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
import org.junit.Test;
public class MsoHeatEnvironmentResourceTest {
- @Test
- public void test() {
- Object op = true;
+ @Test
+ public void test() {
+ Object op = true;
+
+ MsoHeatEnvironmentResource mre = new MsoHeatEnvironmentResource("name");
+ MsoHeatEnvironmentResource mae = new MsoHeatEnvironmentResource("name", "maeValue");
+ MsoHeatEnvironmentResource msoHER = new MsoHeatEnvironmentResource();
- MsoHeatEnvironmentResource mre = new MsoHeatEnvironmentResource("name");
- MsoHeatEnvironmentResource mae = new MsoHeatEnvironmentResource("name", "maeValue");
- MsoHeatEnvironmentResource msoHER = new MsoHeatEnvironmentResource();
-
- msoHER.setName("msoHERName");
- msoHER.setValue("msoHERValue");
+ msoHER.setName("msoHERName");
+ msoHER.setValue("msoHERValue");
- assertEquals("name", mre.getName());
- assertEquals("maeValue", mae.getValue());
- assertEquals("\"msoHERName\": msoHERValue", msoHER.toString());
- assertEquals("\"name\": maeValue", mae.toString());
- assertFalse(mae.equals(op));
- assertTrue(mae.equals(mre));
- assertEquals("name".hashCode(), mae.hashCode());
- }
+ assertEquals("name", mre.getName());
+ assertEquals("maeValue", mae.getValue());
+ assertEquals("\"msoHERName\": msoHERValue", msoHER.toString());
+ assertEquals("\"name\": maeValue", mae.toString());
+ assertFalse(mae.equals(op));
+ assertTrue(mae.equals(mre));
+ assertEquals("name".hashCode(), mae.hashCode());
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java
index f9fc9284fe..3f5402cc99 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java
@@ -24,14 +24,10 @@ package org.onap.so.openstack.utils;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
-import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertNotNull;
-
-import com.woorea.openstack.heat.Heat;
-import com.woorea.openstack.heat.model.CreateStackParam;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
@@ -58,144 +54,147 @@ import org.onap.so.openstack.exceptions.MsoException;
import org.onap.so.openstack.exceptions.MsoIOException;
import org.onap.so.openstack.exceptions.MsoOpenstackException;
import org.springframework.beans.factory.annotation.Autowired;
+import com.woorea.openstack.heat.Heat;
+import com.woorea.openstack.heat.model.CreateStackParam;
+
+public class MsoHeatUtilsTest extends BaseTest {
+
+ @Autowired
+ private MsoHeatUtils heatUtils;
+
+ @Test
+ public void instantiateVduTest() throws MsoException, IOException {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b");
+ expected.setVduInstanceName("name");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.INSTANTIATED);
+ status.setLastAction((new PluginAction("create", "complete", null)));
+ expected.setStatus(status);
+
+ CloudInfo cloudInfo = new CloudInfo();
+ cloudInfo.setCloudSiteId("MTN13");
+ cloudInfo.setTenantId("tenantId");
+ VduModelInfo vduModel = new VduModelInfo();
+ vduModel.setModelCustomizationUUID("blueprintId");
+ vduModel.setTimeoutMinutes(1);
+ VduArtifact artifact = new VduArtifact();
+ artifact.setName("name");
+ artifact.setType(ArtifactType.MAIN_TEMPLATE);
+ byte[] content = new byte[1];
+ artifact.setContent(content);
+ List<VduArtifact> artifacts = new ArrayList<>();
+ artifacts.add(artifact);
+ vduModel.setArtifacts(artifacts);
+ Map<String, byte[]> blueprintFiles = new HashMap<>();
+ blueprintFiles.put(artifact.getName(), artifact.getContent());
+ String instanceName = "instanceName";
+ Map<String, Object> inputs = new HashMap<>();
+ boolean rollbackOnFailure = true;
+
+ StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json");
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceName/stackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK)));
+
+ VduInstance actual = heatUtils.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
-public class MsoHeatUtilsTest extends BaseTest{
-
- @Autowired
- private MsoHeatUtils heatUtils;
-
- @Test
- public void instantiateVduTest() throws MsoException, IOException {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b");
- expected.setVduInstanceName("name");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.INSTANTIATED);
- status.setLastAction((new PluginAction("create", "complete", null)));
- expected.setStatus(status);
-
- CloudInfo cloudInfo = new CloudInfo();
- cloudInfo.setCloudSiteId("MTN13");
- cloudInfo.setTenantId("tenantId");
- VduModelInfo vduModel = new VduModelInfo();
- vduModel.setModelCustomizationUUID("blueprintId");
- vduModel.setTimeoutMinutes(1);
- VduArtifact artifact = new VduArtifact();
- artifact.setName("name");
- artifact.setType(ArtifactType.MAIN_TEMPLATE);
- byte[] content = new byte[1];
- artifact.setContent(content);
- List<VduArtifact> artifacts = new ArrayList<>();
- artifacts.add(artifact);
- vduModel.setArtifacts(artifacts);
- Map<String, byte[]> blueprintFiles = new HashMap<>();
- blueprintFiles.put(artifact.getName(), artifact.getContent());
- String instanceName = "instanceName";
- Map<String, Object> inputs = new HashMap<>();
- boolean rollbackOnFailure = true;
-
- StubOpenStack.mockOpenStackResponseAccess(wireMockPort);
- StubOpenStack.mockOpenStackPostStack_200("OpenstackResponse_Stack_Created.json");
-
- stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceName/stackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_StackId.json")
- .withStatus(HttpStatus.SC_OK)));
-
- VduInstance actual = heatUtils.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
-
- @Test
- public void queryVduTest() throws Exception {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b");
- expected.setVduInstanceName("name");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.INSTANTIATED);
- status.setLastAction((new PluginAction("create", "complete",null)));
- expected.setStatus(status);
-
- CloudInfo cloudInfo = new CloudInfo();
- cloudInfo.setCloudSiteId("mtn13");
- cloudInfo.setTenantId("tenantId");
- String instanceId = "instanceId";
-
- StubOpenStack.mockOpenStackResponseAccess(wireMockPort);
- StubOpenStack.mockOpenStackPostStack_200("OpenstackResponse_Stack_Created.json");
-
- stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_StackId.json")
- .withStatus(HttpStatus.SC_OK)));
-
- VduInstance actual = heatUtils.queryVdu(cloudInfo, instanceId);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void deleteVduTest() throws Exception {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("instanceId");
- expected.setVduInstanceName("instanceId");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.DELETED);
- expected.setStatus(status);
-
- CloudInfo cloudInfo = new CloudInfo();
- cloudInfo.setCloudSiteId("mtn13");
- cloudInfo.setTenantId("tenantId");
- String instanceId = "instanceId";
-
- int timeoutInMinutes = 1;
-
- StubOpenStack.mockOpenStackResponseAccess(wireMockPort);
- stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId")).willReturn(aResponse().withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK)));
- StubOpenStack.mockOpenStackDelete("name/da886914-efb2-4917-b335-c8381528d90b");
- stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/name/da886914-efb2-4917-b335-c8381528d90b")).willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_DeleteComplete.json").withStatus(HttpStatus.SC_OK)));
-
- VduInstance actual = heatUtils.deleteVdu(cloudInfo, instanceId, timeoutInMinutes);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public final void requestToStringBuilderTest() {
- CreateStackParam param = new CreateStackParam();
- param.setDisableRollback(false);
- param.setEnvironment("environment");
- param.setFiles(new HashMap<String, Object>());
- param.setParameters(new HashMap<>());
- param.setStackName("stackName");
- param.setTemplate("template");
- param.setTemplateUrl("http://templateUrl");
- param.setTimeoutMinutes(1);
-
- StringBuilder stringBuilder = heatUtils.requestToStringBuilder(param);
-
- Assert.assertTrue(stringBuilder.toString().contains("StackName:"));
- }
-
- @Test
- public final void copyBaseOutputsToInputsTest() {
- Map<String, Object> inputs = new HashMap<>();
- inputs.put("str1", "str");
- Map<String, Object> otherStackOutputs = new HashMap<>();
- otherStackOutputs.put("str", "str");
- List<String> paramNames = new ArrayList<>();
- Map<String, String> aliases = new HashMap<>();
- aliases.put("str", "str");
- heatUtils.copyBaseOutputsToInputs(inputs, otherStackOutputs, null, aliases);
- Assert.assertEquals("str",otherStackOutputs.get("str"));
- }
+ @Test
+ public void queryVduTest() throws Exception {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b");
+ expected.setVduInstanceName("name");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.INSTANTIATED);
+ status.setLastAction((new PluginAction("create", "complete", null)));
+ expected.setStatus(status);
+
+ CloudInfo cloudInfo = new CloudInfo();
+ cloudInfo.setCloudSiteId("mtn13");
+ cloudInfo.setTenantId("tenantId");
+ String instanceId = "instanceId";
+
+ StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json");
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK)));
+
+ VduInstance actual = heatUtils.queryVdu(cloudInfo, instanceId);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void deleteVduTest() throws Exception {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("instanceId");
+ expected.setVduInstanceName("instanceId");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.DELETED);
+ expected.setStatus(status);
+
+ CloudInfo cloudInfo = new CloudInfo();
+ cloudInfo.setCloudSiteId("mtn13");
+ cloudInfo.setTenantId("tenantId");
+ String instanceId = "instanceId";
+
+ int timeoutInMinutes = 1;
+
+ StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId"))
+ .willReturn(aResponse().withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK)));
+ StubOpenStack.mockOpenStackDelete(wireMockServer, "name/da886914-efb2-4917-b335-c8381528d90b");
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/name/da886914-efb2-4917-b335-c8381528d90b"))
+ .willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_DeleteComplete.json")
+ .withStatus(HttpStatus.SC_OK)));
+
+ VduInstance actual = heatUtils.deleteVdu(cloudInfo, instanceId, timeoutInMinutes);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public final void requestToStringBuilderTest() {
+ CreateStackParam param = new CreateStackParam();
+ param.setDisableRollback(false);
+ param.setEnvironment("environment");
+ param.setFiles(new HashMap<String, Object>());
+ param.setParameters(new HashMap<>());
+ param.setStackName("stackName");
+ param.setTemplate("template");
+ param.setTemplateUrl("http://templateUrl");
+ param.setTimeoutMinutes(1);
+
+ StringBuilder stringBuilder = heatUtils.requestToStringBuilder(param);
+
+ Assert.assertTrue(stringBuilder.toString().contains("StackName:"));
+ }
+
+ @Test
+ public final void copyBaseOutputsToInputsTest() {
+ Map<String, Object> inputs = new HashMap<>();
+ inputs.put("str1", "str");
+ Map<String, Object> otherStackOutputs = new HashMap<>();
+ otherStackOutputs.put("str", "str");
+ List<String> paramNames = new ArrayList<>();
+ Map<String, String> aliases = new HashMap<>();
+ aliases.put("str", "str");
+ heatUtils.copyBaseOutputsToInputs(inputs, otherStackOutputs, null, aliases);
+ Assert.assertEquals("str", otherStackOutputs.get("str"));
+ }
@Test
public final void getHeatClientSuccessTest() throws MsoException, IOException {
CloudSite cloudSite = getCloudSite(getCloudIdentity());
- StubOpenStack.mockOpenStackResponseAccess(wireMockPort);
+ StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
Heat heatClient = heatUtils.getHeatClient(cloudSite, "TEST-tenant");
assertNotNull(heatClient);
}
@@ -210,7 +209,7 @@ public class MsoHeatUtilsTest extends BaseTest{
@Test(expected = MsoAdapterException.class)
public final void getHeatClientOpenStackResponseException401Test() throws MsoException, IOException {
CloudSite cloudSite = getCloudSite(getCloudIdentity());
- StubOpenStack.mockOpenStackResponseUnauthorized(wireMockPort);
+ StubOpenStack.mockOpenStackResponseUnauthorized(wireMockServer, wireMockPort);
heatUtils.getHeatClient(cloudSite, "TEST-tenant");
}
@@ -226,12 +225,11 @@ public class MsoHeatUtilsTest extends BaseTest{
@Test
public final void createStackSuccessTest() throws MsoException, IOException {
CloudSite cloudSite = getCloudSite(getCloudIdentity());
- StubOpenStack.mockOpenStackResponseAccess(wireMockPort);
- StubOpenStack.mockOpenStackPostStack_200("OpenstackResponse_Stack_Created.json");
- StubOpenStack.mockOpenStackGet("TEST-stack/stackId");
- StackInfo stackInfo = heatUtils.createStack(cloudSite.getId(), "tenantId", "TEST-stack",
- "TEST-heat", new HashMap<>(), false, 1, "TEST-env",
- new HashMap<>(), new HashMap<>(), false);
+ StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json");
+ StubOpenStack.mockOpenStackGet(wireMockServer, "TEST-stack/stackId");
+ StackInfo stackInfo = heatUtils.createStack(cloudSite.getId(), "CloudOwner", "tenantId", "TEST-stack", null,
+ "TEST-heat", new HashMap<>(), false, 1, "TEST-env", new HashMap<>(), new HashMap<>(), false);
assertNotNull(stackInfo);
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java
index 9edc805cf3..7a48dc092a 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java
@@ -23,7 +23,6 @@ package org.onap.so.openstack.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
@@ -33,12 +32,10 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import org.junit.Test;
import org.onap.so.db.catalog.beans.HeatTemplate;
import org.onap.so.db.catalog.beans.HeatTemplateParam;
import org.skyscreamer.jsonassert.JSONAssert;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -47,150 +44,153 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class MsoHeatUtilsUnitTest {
-
- private ObjectMapper mapper = new ObjectMapper();
- @Test
- public void convertInputMapTest() throws JsonParseException, JsonMappingException, IOException {
- MsoHeatUtils utils = new MsoHeatUtils();
-
- Map<String, Object> input = new HashMap<>();
- HeatTemplate template = new HeatTemplate();
- template.setArtifactUuid("my-uuid");
- Set<HeatTemplateParam> parameters = template.getParameters();
- HeatTemplateParam paramNum = new HeatTemplateParam();
- paramNum.setParamType("number");
- paramNum.setParamName("my-number");
- input.put("my-number", "3");
-
- HeatTemplateParam paramString = new HeatTemplateParam();
- paramString.setParamType("string");
- paramString.setParamName("my-string");
- input.put("my-string", "hello");
-
- HeatTemplateParam paramJson = new HeatTemplateParam();
- paramJson.setParamType("json");
- paramJson.setParamName("my-json");
-
- HeatTemplateParam paramJsonEscaped = new HeatTemplateParam();
- paramJsonEscaped.setParamType("json");
- paramJsonEscaped.setParamName("my-json-escaped");
-
- Map<String, Object> jsonMap = mapper.readValue(getJson("free-form.json"), new TypeReference<Map<String, Object>>(){});
- input.put("my-json", jsonMap);
-
- input.put("my-json-escaped", getJson("free-form.json"));
-
- parameters.add(paramNum);
- parameters.add(paramString);
- parameters.add(paramJson);
- parameters.add(paramJsonEscaped);
-
- Map<String, Object> output = utils.convertInputMap(input, template);
-
- assertEquals(3, output.get("my-number"));
- assertEquals("hello", output.get("my-string"));
- assertTrue("expect no change in type", output.get("my-json") instanceof Map);
- assertTrue("expect string to become jsonNode", output.get("my-json-escaped") instanceof JsonNode);
-
- JSONAssert.assertEquals(getJson("free-form.json"), mapper.writeValueAsString(output.get("my-json-escaped")), false);
- }
-
- @Test
- public final void convertInputMapValuesTest() {
- MsoHeatUtils utils = new MsoHeatUtils();
- Map<String, Object> inputs = new HashMap<>();
- Set<HeatTemplateParam> params = new HashSet<>();
- HeatTemplate ht = new HeatTemplate();
- HeatTemplateParam htp = new HeatTemplateParam();
- htp.setParamName("vnf_name");
- htp.setParamType("string");
- params.add(htp);
- inputs.put("vnf_name", "a_vnf_name");
- htp = new HeatTemplateParam();
- htp.setParamName("image_size");
- htp.setParamType("number");
- params.add(htp);
- inputs.put("image_size", "1024");
- htp = new HeatTemplateParam();
- htp.setParamName("external");
- htp.setParamType("boolean");
- params.add(htp);
- inputs.put("external", "false");
- htp = new HeatTemplateParam();
- htp.setParamName("oam_ips");
- htp.setParamType("comma_delimited_list");
- params.add(htp);
- inputs.put("oam_ips", "a,b");
- htp = new HeatTemplateParam();
- htp.setParamName("oam_prefixes");
- htp.setParamType("json");
- params.add(htp);
- String jsonEscInput = "[{\"prefix\": \"aValue\"}, {\"prefix\": \"aValue2\"}]";
- inputs.put("oam_prefixes", jsonEscInput);
- ht.setParameters(params);
-
- Map<String, Object> output = utils.convertInputMap(inputs, ht);
-
- assertEquals("a_vnf_name", output.get("vnf_name"));
- assertEquals(1024, output.get("image_size"));
- assertEquals(false, output.get("external"));
- List<String> cdl = new ArrayList<>();
- cdl.add(0, "a");
- cdl.add(1, "b");
- assertEquals(cdl, output.get("oam_ips"));
- ObjectMapper JSON_MAPPER = new ObjectMapper();
- JsonNode jn = null;
- try {
- jn = JSON_MAPPER.readTree(jsonEscInput);
- } catch (Exception e) {
- }
- assertEquals(jn, output.get("oam_prefixes"));
- }
-
- @Test
- public final void convertInputMapNullsTest() {
- MsoHeatUtils utils = new MsoHeatUtils();
- Map<String, Object> inputs = new HashMap<>();
- Set<HeatTemplateParam> params = new HashSet<>();
- HeatTemplate ht = new HeatTemplate();
- HeatTemplateParam htp = new HeatTemplateParam();
- htp.setParamName("vnf_name");
- htp.setParamType("string");
- params.add(htp);
- inputs.put("vnf_name", null);
- htp = new HeatTemplateParam();
- htp.setParamName("image_size");
- htp.setParamType("number");
- params.add(htp);
- inputs.put("image_size", null);
- htp = new HeatTemplateParam();
- htp.setParamName("external");
- htp.setParamType("boolean");
- params.add(htp);
- inputs.put("external", null);
- htp = new HeatTemplateParam();
- htp.setParamName("oam_ips");
- htp.setParamType("comma_delimited_list");
- params.add(htp);
- inputs.put("oam_ips", null);
- htp = new HeatTemplateParam();
- htp.setParamName("oam_prefixes");
- htp.setParamType("json");
- params.add(htp);
- inputs.put("oam_prefixes", null);
- ht.setParameters(params);
-
- Map<String, Object> output = utils.convertInputMap(inputs, ht);
-
- assertNull(output.get("vnf_name"));
- assertNull(output.get("image_size"));
- assertEquals(false, output.get("external"));
- assertNull(output.get("oam_ips"));
- assertNull(output.get("oam_prefixes"));
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/MsoHeatUtils/" + filename)));
- }
-
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ public void convertInputMapTest() throws JsonParseException, JsonMappingException, IOException {
+ MsoHeatUtils utils = new MsoHeatUtils();
+
+ Map<String, Object> input = new HashMap<>();
+ HeatTemplate template = new HeatTemplate();
+ template.setArtifactUuid("my-uuid");
+ Set<HeatTemplateParam> parameters = template.getParameters();
+ HeatTemplateParam paramNum = new HeatTemplateParam();
+ paramNum.setParamType("number");
+ paramNum.setParamName("my-number");
+ input.put("my-number", "3");
+
+ HeatTemplateParam paramString = new HeatTemplateParam();
+ paramString.setParamType("string");
+ paramString.setParamName("my-string");
+ input.put("my-string", "hello");
+
+ HeatTemplateParam paramJson = new HeatTemplateParam();
+ paramJson.setParamType("json");
+ paramJson.setParamName("my-json");
+
+ HeatTemplateParam paramJsonEscaped = new HeatTemplateParam();
+ paramJsonEscaped.setParamType("json");
+ paramJsonEscaped.setParamName("my-json-escaped");
+
+ Map<String, Object> jsonMap =
+ mapper.readValue(getJson("free-form.json"), new TypeReference<Map<String, Object>>() {});
+ input.put("my-json", jsonMap);
+
+ input.put("my-json-escaped", getJson("free-form.json"));
+
+ parameters.add(paramNum);
+ parameters.add(paramString);
+ parameters.add(paramJson);
+ parameters.add(paramJsonEscaped);
+
+ Map<String, Object> output = utils.convertInputMap(input, template);
+
+ assertEquals(3, output.get("my-number"));
+ assertEquals("hello", output.get("my-string"));
+ assertTrue("expect no change in type", output.get("my-json") instanceof Map);
+ assertTrue("expect string to become jsonNode", output.get("my-json-escaped") instanceof JsonNode);
+
+ JSONAssert.assertEquals(getJson("free-form.json"), mapper.writeValueAsString(output.get("my-json-escaped")),
+ false);
+ }
+
+ @Test
+ public final void convertInputMapValuesTest() {
+ MsoHeatUtils utils = new MsoHeatUtils();
+ Map<String, Object> inputs = new HashMap<>();
+ Set<HeatTemplateParam> params = new HashSet<>();
+ HeatTemplate ht = new HeatTemplate();
+ HeatTemplateParam htp = new HeatTemplateParam();
+ htp.setParamName("vnf_name");
+ htp.setParamType("string");
+ params.add(htp);
+ inputs.put("vnf_name", "a_vnf_name");
+ htp = new HeatTemplateParam();
+ htp.setParamName("image_size");
+ htp.setParamType("number");
+ params.add(htp);
+ inputs.put("image_size", "1024");
+ htp = new HeatTemplateParam();
+ htp.setParamName("external");
+ htp.setParamType("boolean");
+ params.add(htp);
+ inputs.put("external", "false");
+ htp = new HeatTemplateParam();
+ htp.setParamName("oam_ips");
+ htp.setParamType("comma_delimited_list");
+ params.add(htp);
+ inputs.put("oam_ips", "a,b");
+ htp = new HeatTemplateParam();
+ htp.setParamName("oam_prefixes");
+ htp.setParamType("json");
+ params.add(htp);
+ String jsonEscInput = "[{\"prefix\": \"aValue\"}, {\"prefix\": \"aValue2\"}]";
+ inputs.put("oam_prefixes", jsonEscInput);
+ ht.setParameters(params);
+
+ Map<String, Object> output = utils.convertInputMap(inputs, ht);
+
+ assertEquals("a_vnf_name", output.get("vnf_name"));
+ assertEquals(1024, output.get("image_size"));
+ assertEquals(false, output.get("external"));
+ List<String> cdl = new ArrayList<>();
+ cdl.add(0, "a");
+ cdl.add(1, "b");
+ assertEquals(cdl, output.get("oam_ips"));
+ ObjectMapper JSON_MAPPER = new ObjectMapper();
+ JsonNode jn = null;
+ try {
+ jn = JSON_MAPPER.readTree(jsonEscInput);
+ } catch (Exception e) {
+ }
+ assertEquals(jn, output.get("oam_prefixes"));
+ }
+
+ @Test
+ public final void convertInputMapNullsTest() {
+ MsoHeatUtils utils = new MsoHeatUtils();
+ Map<String, Object> inputs = new HashMap<>();
+ Set<HeatTemplateParam> params = new HashSet<>();
+ HeatTemplate ht = new HeatTemplate();
+ HeatTemplateParam htp = new HeatTemplateParam();
+ htp.setParamName("vnf_name");
+ htp.setParamType("string");
+ params.add(htp);
+ inputs.put("vnf_name", null);
+ htp = new HeatTemplateParam();
+ htp.setParamName("image_size");
+ htp.setParamType("number");
+ params.add(htp);
+ inputs.put("image_size", null);
+ htp = new HeatTemplateParam();
+ htp.setParamName("external");
+ htp.setParamType("boolean");
+ params.add(htp);
+ inputs.put("external", null);
+ htp = new HeatTemplateParam();
+ htp.setParamName("oam_ips");
+ htp.setParamType("comma_delimited_list");
+ params.add(htp);
+ inputs.put("oam_ips", null);
+ htp = new HeatTemplateParam();
+ htp.setParamName("oam_prefixes");
+ htp.setParamType("json");
+ params.add(htp);
+ inputs.put("oam_prefixes", null);
+ ht.setParameters(params);
+
+ Map<String, Object> output = utils.convertInputMap(inputs, ht);
+
+ assertNull(output.get("vnf_name"));
+ assertNull(output.get("image_size"));
+ assertEquals(false, output.get("external"));
+ assertNull(output.get("oam_ips"));
+ assertNull(output.get("oam_prefixes"));
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/MsoHeatUtils/" + filename)));
+ }
+
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java
index b735e735c9..8951f8a304 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java
@@ -26,13 +26,11 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
-
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -48,7 +46,6 @@ import org.onap.so.openstack.beans.HeatStatus;
import org.onap.so.openstack.beans.StackInfo;
import org.onap.so.openstack.exceptions.MsoException;
import org.springframework.core.env.Environment;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.woorea.openstack.base.client.OpenStackRequest;
@@ -57,107 +54,110 @@ import com.woorea.openstack.heat.model.Stack;
@RunWith(MockitoJUnitRunner.class)
public class MsoHeatUtilsWithUpdateTest extends TestDataSetup {
- @Mock
- private CloudConfig cloudConfig;
-
- @Mock
- private Environment environment;
-
- @Spy
- @InjectMocks
- private MsoHeatUtilsWithUpdate heatUtils;
-
- private String cloudSiteId;
- private String tenantId;
- private String stackName;
- private String heatTemplate;
- private Map<String, Object> stackInputs;
- private boolean pollForCompletion;
- private int timeoutMinutes;
-
- @Before
- public void before() {
- MockitoAnnotations.initMocks(this);
-
- cloudSiteId = "cloudSiteId";
- tenantId = "tenantId";
- stackName = "stackName";
- heatTemplate = "heatTemplate";
- stackInputs = new HashMap<>();
- pollForCompletion = true;
- timeoutMinutes = 0;
- }
-
- @Test
- public void updateStackTest() throws MsoException, JsonParseException, JsonMappingException, IOException {
- CloudSite cloudSite = new CloudSite();
- Heat heatClient = new Heat("endpoint");
- Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class);
- Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class);
-
- StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null);
- expectedStackInfo.setCanonicalName("stackName/id");
-
- doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class));
- doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class));
- doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class));
- doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class));
- doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class));
-
- StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, tenantId, stackName,
- heatTemplate, stackInputs, pollForCompletion, timeoutMinutes);
-
- assertThat(actualStackInfo, sameBeanAs(expectedStackInfo));
- }
-
- @Test
- public void updateStackWithEnvironmentTest() throws JsonParseException, JsonMappingException, IOException, MsoException {
- String environmentString = "environmentString";
-
- CloudSite cloudSite = new CloudSite();
- Heat heatClient = new Heat("endpoint");
- Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class);
- Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class);
-
- StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null);
- expectedStackInfo.setCanonicalName("stackName/id");
-
- doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class));
- doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class));
-
- doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class));
- doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class));
- doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class));
-
- StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, tenantId, stackName,
- heatTemplate, stackInputs, pollForCompletion, timeoutMinutes, environmentString);
-
- assertThat(actualStackInfo, sameBeanAs(expectedStackInfo));
- }
-
- @Test
- public void updateStackWithFilesTest() throws MsoException, JsonParseException, JsonMappingException, IOException {
- String environmentString = "environmentString";
- Map<String, Object> files = new HashMap<>();
- files.put("file1", new Object());
-
- CloudSite cloudSite = new CloudSite();
- Heat heatClient = new Heat("endpoint");
- Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class);
- Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class);
-
- StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null);
- expectedStackInfo.setCanonicalName("stackName/id");
-
- doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class));
- doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class));
- doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class));
- doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class));
- doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class));
-
- StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, tenantId, stackName,
- heatTemplate, stackInputs, pollForCompletion, timeoutMinutes , environmentString, files);
-
- assertThat(actualStackInfo, sameBeanAs(expectedStackInfo));
- }
+ @Mock
+ private CloudConfig cloudConfig;
+
+ @Mock
+ private Environment environment;
+
+ @Spy
+ @InjectMocks
+ private MsoHeatUtilsWithUpdate heatUtils;
+
+ private String cloudOwner;
+ private String cloudSiteId;
+ private String tenantId;
+ private String stackName;
+ private String heatTemplate;
+ private Map<String, Object> stackInputs;
+ private boolean pollForCompletion;
+ private int timeoutMinutes;
+
+ @Before
+ public void before() {
+ MockitoAnnotations.initMocks(this);
+
+ cloudOwner = "cloudOwner";
+ cloudSiteId = "cloudSiteId";
+ tenantId = "tenantId";
+ stackName = "stackName";
+ heatTemplate = "heatTemplate";
+ stackInputs = new HashMap<>();
+ pollForCompletion = true;
+ timeoutMinutes = 0;
+ }
+
+ @Test
+ public void updateStackTest() throws MsoException, JsonParseException, JsonMappingException, IOException {
+ CloudSite cloudSite = new CloudSite();
+ Heat heatClient = new Heat("endpoint");
+ Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class);
+ Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class);
+
+ StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null);
+ expectedStackInfo.setCanonicalName("stackName/id");
+
+ doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class));
+ doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class));
+ doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class));
+ doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class));
+ doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class));
+
+ StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate,
+ stackInputs, pollForCompletion, timeoutMinutes);
+
+ assertThat(actualStackInfo, sameBeanAs(expectedStackInfo));
+ }
+
+ @Test
+ public void updateStackWithEnvironmentTest()
+ throws JsonParseException, JsonMappingException, IOException, MsoException {
+ String environmentString = "environmentString";
+
+ CloudSite cloudSite = new CloudSite();
+ Heat heatClient = new Heat("endpoint");
+ Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class);
+ Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class);
+
+ StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null);
+ expectedStackInfo.setCanonicalName("stackName/id");
+
+ doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class));
+ doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class));
+
+ doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class));
+ doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class));
+ doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class));
+
+ StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate,
+ stackInputs, pollForCompletion, timeoutMinutes, environmentString);
+
+ assertThat(actualStackInfo, sameBeanAs(expectedStackInfo));
+ }
+
+ @Test
+ public void updateStackWithFilesTest() throws MsoException, JsonParseException, JsonMappingException, IOException {
+ String environmentString = "environmentString";
+ Map<String, Object> files = new HashMap<>();
+ files.put("file1", new Object());
+
+ CloudSite cloudSite = new CloudSite();
+ Heat heatClient = new Heat("endpoint");
+ Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class);
+ Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class);
+
+ StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null);
+ expectedStackInfo.setCanonicalName("stackName/id");
+
+ doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class));
+ doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class));
+ doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class));
+ doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class));
+ doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class));
+
+ StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate,
+ stackInputs, pollForCompletion, timeoutMinutes, environmentString, files);
+
+ assertThat(actualStackInfo, sameBeanAs(expectedStackInfo));
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java
index 5100407633..6ecabfd45a 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java
@@ -28,7 +28,6 @@ import org.onap.so.BaseTest;
import org.onap.so.openstack.beans.MsoTenant;
import org.onap.so.openstack.exceptions.MsoException;
import org.springframework.beans.factory.annotation.Autowired;
-
import java.io.IOException;
import java.util.HashMap;
@@ -39,15 +38,15 @@ public class MsoKeystoneUtilsTest extends BaseTest {
@Before
public void before() throws IOException {
- StubOpenStack.mockOpenStackResponseAccess(wireMockPort);
+ StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
}
@Test
public void createTenantTest() throws Exception {
- StubOpenStack.mockOpenStackPostTenantWithBodyFile_200();
+ StubOpenStack.mockOpenStackPostTenantWithBodyFile_200(wireMockServer);
- StubOpenStack.mockOpenStackGetUserById("john");
- StubOpenStack.mockOpenStackGetRoles_200("OS-KSADM");
+ StubOpenStack.mockOpenStackGetUserById(wireMockServer, "john");
+ StubOpenStack.mockOpenStackGetRoles_200(wireMockServer, "OS-KSADM");
String response = msoKeystoneUtils.createTenant("tenant", "MTN13", new HashMap<>(), true);
Assert.assertEquals("tenantId", response);
@@ -55,10 +54,10 @@ public class MsoKeystoneUtilsTest extends BaseTest {
@Test
public void createTenantTest_FindUserByName() throws Exception {
- StubOpenStack.mockOpenStackPostTenantWithBodyFile_200();
+ StubOpenStack.mockOpenStackPostTenantWithBodyFile_200(wireMockServer);
- StubOpenStack.mockOpenStackGetUserByName("john");
- StubOpenStack.mockOpenStackGetRoles_200("OS-KSADM");
+ StubOpenStack.mockOpenStackGetUserByName(wireMockServer, "john");
+ StubOpenStack.mockOpenStackGetRoles_200(wireMockServer, "OS-KSADM");
String response = msoKeystoneUtils.createTenant("tenant", "MTN13", new HashMap<>(), true);
Assert.assertEquals("tenantId", response);
@@ -67,15 +66,15 @@ public class MsoKeystoneUtilsTest extends BaseTest {
@Test
public void createTenantTest_Exception() throws Exception {
expectedException.expect(MsoException.class);
- StubOpenStack.mockOpenStackPostTenantWithBodyFile_200();
- StubOpenStack.mockOpenStackGetUserByName_500("john");
- StubOpenStack.mockOpenStackGetRoles_200("OS-KSADM");
+ StubOpenStack.mockOpenStackPostTenantWithBodyFile_200(wireMockServer);
+ StubOpenStack.mockOpenStackGetUserByName_500(wireMockServer, "john");
+ StubOpenStack.mockOpenStackGetRoles_200(wireMockServer, "OS-KSADM");
msoKeystoneUtils.createTenant("tenant", "Test", new HashMap<>(), true);
}
@Test
public void queryTenantTest() throws Exception {
- StubOpenStack.mockOpenStackGetTenantById("tenantId");
+ StubOpenStack.mockOpenStackGetTenantById(wireMockServer, "tenantId");
MsoTenant msoTenant = msoKeystoneUtils.queryTenant("tenantId", "MTN13");
@@ -84,7 +83,7 @@ public class MsoKeystoneUtilsTest extends BaseTest {
@Test
public void queryTenantByNameTest() throws Exception {
- StubOpenStack.mockOpenStackGetTenantByName("tenant");
+ StubOpenStack.mockOpenStackGetTenantByName(wireMockServer, "tenant");
MsoTenant msoTenant = msoKeystoneUtils.queryTenantByName("tenant", "MTN13");
@@ -93,8 +92,8 @@ public class MsoKeystoneUtilsTest extends BaseTest {
@Test
public void deleteTenantTest() throws Exception {
- StubOpenStack.mockOpenStackGetTenantById("tenantId");
- StubOpenStack.mockOpenStackDeleteTenantById_200("tenantId");
+ StubOpenStack.mockOpenStackGetTenantById(wireMockServer, "tenantId");
+ StubOpenStack.mockOpenStackDeleteTenantById_200(wireMockServer, "tenantId");
boolean result = msoKeystoneUtils.deleteTenant("tenantId", "MTN13");
Assert.assertTrue(result);
@@ -102,8 +101,8 @@ public class MsoKeystoneUtilsTest extends BaseTest {
@Test
public void deleteTenantByNameTest() throws Exception {
- StubOpenStack.mockOpenStackGetTenantByName("tenant");
- StubOpenStack.mockOpenStackDeleteTenantById_200("tenantId");
+ StubOpenStack.mockOpenStackGetTenantByName(wireMockServer, "tenant");
+ StubOpenStack.mockOpenStackDeleteTenantById_200(wireMockServer, "tenantId");
boolean result = msoKeystoneUtils.deleteTenantByName("tenant", "MTN13");
Assert.assertTrue(result);
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java
index fcb651e4dd..0d8f451a6d 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java
@@ -21,25 +21,34 @@
package org.onap.so.openstack.utils;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
-import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
-
+import static org.onap.so.openstack.utils.MsoMulticloudUtils.MULTICLOUD_QUERY_BODY_NULL;
import java.io.IOException;
import java.util.HashMap;
import java.util.Optional;
import org.apache.http.HttpStatus;
+import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.onap.so.BaseTest;
+import org.onap.so.adapters.vdu.CloudInfo;
+import org.onap.so.adapters.vdu.VduException;
+import org.onap.so.adapters.vdu.VduInstance;
+import org.onap.so.adapters.vdu.VduModelInfo;
+import org.onap.so.adapters.vdu.VduStateType;
import org.onap.so.cloud.CloudConfig;
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.db.catalog.beans.CloudSite;
+import org.onap.so.openstack.beans.HeatStatus;
import org.onap.so.openstack.beans.StackInfo;
import org.onap.so.openstack.exceptions.MsoException;
import org.springframework.beans.factory.annotation.Autowired;
@@ -56,32 +65,92 @@ public class MsoMulticloudUtilsTest extends BaseTest {
private CloudConfig cloudConfigMock;
private static final String CREATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": "
- + "\"TEST-workload\", \"template_response\": {\"stack\": {\"id\": \"TEST-stack\", \"links\": []}}}";
+ + "\"TEST-workload\", \"template_response\": {\"stack\": {\"id\": \"TEST-stack\", \"links\": []}}}";
+ private static final String UPDATE_STACK_RESPONSE =
+ "{\"template_type\": \"TEST-template\", \"workload_id\": " + "\"TEST-workload\"}";
+ private static final String GET_CREATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": "
+ + "\"TEST-workload\", \"workload_status\": \"CREATE_COMPLETE\"}";
+ private static final String GET_UPDATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": "
+ + "\"TEST-workload\", \"workload_status\": \"UPDATE_COMPLETE\"}";
+
+ private static final String MULTICLOUD_CREATE_PATH = "/api/multicloud/v1/CloudOwner/MTN14/infra_workload";
+ private static final String MULTICLOUD_UPDATE_PATH =
+ "/api/multicloud/v1/CloudOwner/MTN14/infra_workload/TEST-workload";
+ private static final String MULTICLOUD_GET_PATH =
+ "/api/multicloud/v1/CloudOwner/MTN14/infra_workload/TEST-workload";
@Test
public void createStackSuccess() throws MsoException, IOException {
- stubFor(post(urlPathEqualTo("/v2.0"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(CREATE_STACK_RESPONSE)
- .withStatus(HttpStatus.SC_CREATED)));
- StackInfo result = multicloudUtils.createStack("MTN13", "TEST-tenant", "TEST-stack",
- "TEST-heat", new HashMap<>(), false, 200, "TEST-env",
- new HashMap<>(), new HashMap<>());
+ wireMockServer
+ .stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).inScenario("CREATE")
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(CREATE_STACK_RESPONSE).withStatus(HttpStatus.SC_CREATED))
+ .willSetStateTo("CREATING"));
+ wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH)).inScenario("CREATE")
+ .whenScenarioStateIs("CREATING").willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(GET_CREATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_UPDATE_PATH))
+ .inScenario("CREATE").willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_ACCEPTED))
+ .willSetStateTo("UPDATING"));
+ wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH)).inScenario("CREATE")
+ .whenScenarioStateIs("UPDATING").willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(GET_UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK)));
+ StackInfo result =
+ multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(),
+ "TEST-heat", new HashMap<>(), true, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false);
+ wireMockServer.resetScenarios();
assertNotNull(result);
assertEquals("TEST-stack", result.getName());
}
@Test
+ public void deleteStack() throws MsoException {
+ StackInfo result = multicloudUtils.deleteStack("MTN13", "CloudOwner", "TEST-tenant", "instanceId");
+ assertNotNull(result);
+ assertTrue(HeatStatus.NOTFOUND == result.getStatus());
+ }
+
+ @Test
+ public void queryStack() throws MsoException {
+ StackInfo result = multicloudUtils.queryStack("MTN13", "CloudOwner", "TEST-tenant", "instanceId");
+ assertTrue(HeatStatus.NOTFOUND == result.getStatus());
+ }
+
+ @Test
+ public void queryStackWithNullMulticloudQueryBody() throws MsoException {
+ wireMockServer.stubFor(get(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/instanceId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(CREATE_STACK_RESPONSE)
+ .withStatus(HttpStatus.SC_OK)));
+
+ StackInfo result = multicloudUtils.queryStack("MTN13", "CloudOwner", "TEST-tenant", "instanceId");
+ assertTrue(HeatStatus.FAILED == result.getStatus());
+ assertEquals(MULTICLOUD_QUERY_BODY_NULL, result.getStatusMessage());
+ }
+
+ @Test(expected = VduException.class)
+ public void updateVdu() throws MsoException {
+ multicloudUtils.updateVdu(new CloudInfo(), "instanceId", new HashMap<>(), new VduModelInfo(), false);
+ }
+
+ @Test
+ public void deleteVdu() throws VduException {
+ CloudInfo cloudInfo = new CloudInfo("cloudSiteId", "cloudOwner", "tenantId", "tenantName");
+ VduInstance vduInstance = multicloudUtils.deleteVdu(cloudInfo, "instanceId", 3);
+ assertNotNull(vduInstance);
+ assertTrue(VduStateType.DELETED == vduInstance.getStatus().getState());
+ }
+
+ @Ignore
+ @Test
public void createStackMulticloudClientIsNull() {
try {
multicloudUtilsMock.cloudConfig = cloudConfigMock;
CloudSite cloudSite = new CloudSite();
cloudSite.setIdentityService(new CloudIdentity());
- when(cloudConfigMock.getCloudSite("MTN13")).
- thenReturn(Optional.of(cloudSite));
- multicloudUtilsMock.createStack("MTN13", "TEST-tenant", "TEST-stack",
- "TEST-heat", new HashMap<>(), false, 200, "TEST-env",
- new HashMap<>(), new HashMap<>());
+ when(cloudConfigMock.getCloudSite("MTN13")).thenReturn(Optional.of(cloudSite));
+ multicloudUtilsMock.createStack("MNT14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(),
+ "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false);
} catch (MsoException e) {
assertEquals("0 : Multicloud client could not be initialized", e.toString());
return;
@@ -92,12 +161,10 @@ public class MsoMulticloudUtilsTest extends BaseTest {
@Test
public void createStackBadRequest() {
try {
- stubFor(post(urlPathEqualTo("/v2.0"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_BAD_REQUEST)));
- multicloudUtils.createStack("MTN13", "TEST-tenant", "TEST-stack",
- "TEST-heat", new HashMap<>(), false, 200, "TEST-env",
- new HashMap<>(), new HashMap<>());
+ wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_BAD_REQUEST)));
+ multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(),
+ "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false);
} catch (MsoException e) {
assertEquals("0 : Bad Request", e.toString());
return;
@@ -107,12 +174,11 @@ public class MsoMulticloudUtilsTest extends BaseTest {
@Test
public void createStackEmptyResponseEntity() throws MsoException {
- stubFor(post(urlPathEqualTo("/v2.0"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_CREATED)));
- StackInfo result = multicloudUtils.createStack("MTN13", "TEST-tenant", "TEST-stack",
- "TEST-heat", new HashMap<>(), false, 200, "TEST-env",
- new HashMap<>(), new HashMap<>());
+ wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_CREATED)));
+ StackInfo result =
+ multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(),
+ "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false);
assertNotNull(result);
assertEquals("TEST-stack/", result.getName());
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java
index f679e1f776..56cdb128aa 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java
@@ -28,98 +28,105 @@ import org.onap.so.BaseTest;
import org.onap.so.openstack.beans.NetworkInfo;
import org.onap.so.openstack.exceptions.MsoException;
import org.springframework.beans.factory.annotation.Autowired;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-public class MsoNeutronUtilsTest extends BaseTest{
-
+public class MsoNeutronUtilsTest extends BaseTest {
+
@Autowired
private MsoNeutronUtils msoNeutronUtils;
private List<Integer> vlans;
-
+
@Before
public void before() throws IOException {
vlans = new ArrayList<>();
vlans.add(3014);
- StubOpenStack.mockOpenStackResponseAccess(wireMockPort);
+ StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
}
-
+
@Test
public void createNetworkTest_OpenStackBaseException() throws Exception {
expectedException.expect(MsoException.class);
- msoNeutronUtils.createNetwork("MTN13", "tenantId",
- MsoNeutronUtils.NetworkType.PROVIDER,"networkName", "PROVIDER", vlans);
+ msoNeutronUtils.createNetwork("MTN13", "tenantId", MsoNeutronUtils.NetworkType.PROVIDER, "networkName",
+ "PROVIDER", vlans);
}
@Test
public void createNetworkTest_NetworkTypeAsMultiProvider() throws Exception {
- StubOpenStack.mockOpenstackPostNetwork("OpenstackCreateNeutronNetworkResponse.json");
+ StubOpenStack.mockOpenstackPostNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json");
NetworkInfo networkInfo = msoNeutronUtils.createNetwork("MTN13", "tenantId",
- MsoNeutronUtils.NetworkType.MULTI_PROVIDER,"networkName","PROVIDER", vlans);
+ MsoNeutronUtils.NetworkType.MULTI_PROVIDER, "networkName", "PROVIDER", vlans);
- Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9",networkInfo.getId());
+ Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9", networkInfo.getId());
}
@Test
public void createNetworkTest() throws Exception {
- StubOpenStack.mockOpenstackPostNetwork("OpenstackCreateNeutronNetworkResponse.json");
+ StubOpenStack.mockOpenstackPostNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json");
NetworkInfo networkInfo = msoNeutronUtils.createNetwork("MTN13", "tenantId",
- MsoNeutronUtils.NetworkType.PROVIDER,"networkName","PROVIDER", vlans);
+ MsoNeutronUtils.NetworkType.PROVIDER, "networkName", "PROVIDER", vlans);
- Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9",networkInfo.getId());
+ Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9", networkInfo.getId());
}
@Test
public void queryNetworkTest() throws Exception {
- StubOpenStack.mockOpenStackGetNeutronNetwork("GetNeutronNetwork.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
- NetworkInfo networkInfo = msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId","MTN13");
+ StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
+ NetworkInfo networkInfo =
+ msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId", "MTN13");
- Assert.assertEquals("net1",networkInfo.getName());
+ Assert.assertEquals("net1", networkInfo.getName());
}
@Test
public void queryNetworkTest_404() throws Exception {
- NetworkInfo networkInfo = msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId","MTN13");
+ NetworkInfo networkInfo =
+ msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId", "MTN13");
Assert.assertNull(networkInfo);
}
@Test
public void queryNetworkTest_500() throws Exception {
expectedException.expect(MsoException.class);
- StubOpenStack.mockOpenStackGetNeutronNetwork_500("43173f6a-d699-414b-888f-ab243dda6dfe");
- msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId","MTN13");
+ StubOpenStack.mockOpenStackGetNeutronNetwork_500(wireMockServer, "43173f6a-d699-414b-888f-ab243dda6dfe");
+ msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId", "MTN13");
}
@Test
public void deleteNetworkkTest() throws Exception {
- StubOpenStack.mockOpenStackGetNeutronNetwork("GetNeutronNetwork.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
- StubOpenStack.mockOpenStackDeleteNeutronNetwork("43173f6a-d699-414b-888f-ab243dda6dfe");
- Boolean result = msoNeutronUtils.deleteNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId","MTN13");
+ StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
+ StubOpenStack.mockOpenStackDeleteNeutronNetwork(wireMockServer, "43173f6a-d699-414b-888f-ab243dda6dfe");
+ Boolean result = msoNeutronUtils.deleteNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId", "MTN13");
Assert.assertTrue(result);
}
@Test
public void updateNetworkTest() throws Exception {
- StubOpenStack.mockOpenStackGetNeutronNetwork("GetNeutronNetwork.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
- StubOpenStack.mockOpenstackPutNetwork("OpenstackCreateNeutronNetworkResponse.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
+ StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
+ StubOpenStack.mockOpenstackPutNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
NetworkInfo networkInfo = msoNeutronUtils.updateNetwork("MTN13", "tenantId",
- "43173f6a-d699-414b-888f-ab243dda6dfe",MsoNeutronUtils.NetworkType.PROVIDER,"PROVIDER", vlans);
+ "43173f6a-d699-414b-888f-ab243dda6dfe", MsoNeutronUtils.NetworkType.PROVIDER, "PROVIDER", vlans);
- Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9",networkInfo.getId());
+ Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9", networkInfo.getId());
}
@Test
public void updateNetworkTest_NetworkTypeAsMultiProvider() throws Exception {
- StubOpenStack.mockOpenStackGetNeutronNetwork("GetNeutronNetwork.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
- StubOpenStack.mockOpenstackPutNetwork("OpenstackCreateNeutronNetworkResponse.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
+ StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
+ StubOpenStack.mockOpenstackPutNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
NetworkInfo networkInfo = msoNeutronUtils.updateNetwork("MTN13", "tenantId",
- "43173f6a-d699-414b-888f-ab243dda6dfe",MsoNeutronUtils.NetworkType.MULTI_PROVIDER,"PROVIDER", vlans);
+ "43173f6a-d699-414b-888f-ab243dda6dfe", MsoNeutronUtils.NetworkType.MULTI_PROVIDER, "PROVIDER", vlans);
- Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9",networkInfo.getId());
+ Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9", networkInfo.getId());
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java
index f2717ab7ce..c9f3a8a8a8 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java
@@ -27,7 +27,6 @@ import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
-
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -59,7 +58,7 @@ public class MsoTenantUtilsFactoryTest {
// WHEN
MsoCloudSiteNotFound msoCloudSiteNotFound = catchThrowableOfType(
- () -> msoTenantUtilsFactory.getTenantUtils(cloudSiteId), MsoCloudSiteNotFound.class);
+ () -> msoTenantUtilsFactory.getTenantUtils(cloudSiteId), MsoCloudSiteNotFound.class);
// THEN
assertThat(msoCloudSiteNotFound.getMessage()).contains(cloudSiteId);
@@ -90,7 +89,7 @@ public class MsoTenantUtilsFactoryTest {
}
private <T extends MsoTenantUtils> void shouldReturnAppropriateUtilsInstanceForGivenServerType(
- ServerType serverType, T expectedInstance) throws MsoCloudSiteNotFound {
+ ServerType serverType, T expectedInstance) throws MsoCloudSiteNotFound {
// GIVEN
String cloudSiteId = "CloudSiteId";
CloudSite cloudSite = mock(CloudSite.class, RETURNS_DEEP_STUBS);
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java
index 70b5f2699d..90e874fc84 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java
@@ -1,95 +1,90 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * 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
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ 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
+ * 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.
+ * 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.so.openstack.utils;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertNull;
-
import java.io.File;
import java.io.IOException;
import java.util.Set;
-
import org.junit.Test;
import org.onap.so.TestDataSetup;
import org.onap.so.db.catalog.beans.HeatTemplateParam;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
public class MsoYamlEditorWithEnvtTest extends TestDataSetup {
- private MsoYamlEditorWithEnvt yaml;
+ private MsoYamlEditorWithEnvt yaml;
private static final String PARAMETER_NAME = "keyTest";
private static final String PARAMETER_VALUE = "{type : paramType}";
private static final String RESOURCE_NAME = "resourceKey";
private static final String RESOURCE_VALUE = "resourceValue";
- private static final String RAW_ENTRY_WITH_RESOURCE_REGISTRY = "resource_registry: {" + RESOURCE_NAME + " : " + RESOURCE_VALUE + "}";
- private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY = "parameters: {"
- + PARAMETER_NAME + ": " + PARAMETER_VALUE + "}";
-
- @Test
- public void getParameterListTest() throws JsonParseException, JsonMappingException, IOException {
- yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY.getBytes());
-
- MsoHeatEnvironmentParameter expectedHeatParam = mapper.readValue(new File(RESOURCE_PATH + "HeatEnvironmentParameter.json"), MsoHeatEnvironmentParameter.class);
-
- Set<MsoHeatEnvironmentParameter> heatEnvironmentSet = yaml.getParameterListFromEnvt();
-
- for(MsoHeatEnvironmentParameter heatEnvironment : heatEnvironmentSet) {
- assertThat(heatEnvironment, sameBeanAs(expectedHeatParam));
- }
- }
-
- @Test
- public void getResourceListFromEnvtTest() {
- yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_RESOURCE_REGISTRY.getBytes());
-
- MsoHeatEnvironmentResource expectedHeatResource = new MsoHeatEnvironmentResource(RESOURCE_NAME, RESOURCE_VALUE);
-
- Set<MsoHeatEnvironmentResource> heatResourceSet = yaml.getResourceListFromEnvt();
-
- for(MsoHeatEnvironmentResource heatResource : heatResourceSet) {
- assertThat(heatResource, sameBeanAs(expectedHeatResource));
- }
- }
-
- @Test
- public void getResourceListFromEnvtExceptionTest() {
- yaml = new MsoYamlEditorWithEnvt();
-
- Set<MsoHeatEnvironmentResource> heatResourceSet = yaml.getResourceListFromEnvt();
-
- assertNull(heatResourceSet);
- }
-
- @Test
- public void getParameterListFromEnvtTest() throws JsonParseException, JsonMappingException, IOException {
- yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY.getBytes());
-
- HeatTemplateParam expectedHeatParam = mapper.readValue(new File(RESOURCE_PATH + "HeatTemplateParamExpected.json"), HeatTemplateParam.class);
-
- Set<HeatTemplateParam> heatParamSet = yaml.getParameterList();
-
- for(HeatTemplateParam heatParam : heatParamSet) {
- assertThat(heatParam, sameBeanAs(expectedHeatParam));
- }
- }
+ private static final String RAW_ENTRY_WITH_RESOURCE_REGISTRY =
+ "resource_registry: {" + RESOURCE_NAME + " : " + RESOURCE_VALUE + "}";
+ private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY =
+ "parameters: {" + PARAMETER_NAME + ": " + PARAMETER_VALUE + "}";
+
+ @Test
+ public void getParameterListTest() throws JsonParseException, JsonMappingException, IOException {
+ yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY.getBytes());
+
+ MsoHeatEnvironmentParameter expectedHeatParam = mapper.readValue(
+ new File(RESOURCE_PATH + "HeatEnvironmentParameter.json"), MsoHeatEnvironmentParameter.class);
+
+ Set<MsoHeatEnvironmentParameter> heatEnvironmentSet = yaml.getParameterListFromEnvt();
+
+ for (MsoHeatEnvironmentParameter heatEnvironment : heatEnvironmentSet) {
+ assertThat(heatEnvironment, sameBeanAs(expectedHeatParam));
+ }
+ }
+
+ @Test
+ public void getResourceListFromEnvtTest() {
+ yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_RESOURCE_REGISTRY.getBytes());
+
+ MsoHeatEnvironmentResource expectedHeatResource = new MsoHeatEnvironmentResource(RESOURCE_NAME, RESOURCE_VALUE);
+
+ Set<MsoHeatEnvironmentResource> heatResourceSet = yaml.getResourceListFromEnvt();
+
+ for (MsoHeatEnvironmentResource heatResource : heatResourceSet) {
+ assertThat(heatResource, sameBeanAs(expectedHeatResource));
+ }
+ }
+
+ @Test
+ public void getResourceListFromEnvtExceptionTest() {
+ yaml = new MsoYamlEditorWithEnvt();
+
+ Set<MsoHeatEnvironmentResource> heatResourceSet = yaml.getResourceListFromEnvt();
+
+ assertNull(heatResourceSet);
+ }
+
+ @Test
+ public void getParameterListFromEnvtTest() throws JsonParseException, JsonMappingException, IOException {
+ yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY.getBytes());
+
+ HeatTemplateParam expectedHeatParam =
+ mapper.readValue(new File(RESOURCE_PATH + "HeatTemplateParamExpected.json"), HeatTemplateParam.class);
+
+ Set<HeatTemplateParam> heatParamSet = yaml.getParameterList();
+
+ for (HeatTemplateParam heatParam : heatParamSet) {
+ assertThat(heatParam, sameBeanAs(expectedHeatParam));
+ }
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/resources/application-test.yaml b/adapters/mso-adapter-utils/src/test/resources/application-test.yaml
index 368df847be..32a4db6b80 100644
--- a/adapters/mso-adapter-utils/src/test/resources/application-test.yaml
+++ b/adapters/mso-adapter-utils/src/test/resources/application-test.yaml
@@ -51,6 +51,8 @@ tomcat:
max-threads: 50
mso:
logPath: logs
+ msb-ip: localhost
+ msb-port: ${wiremock.server.port}
catalog:
db:
spring:
@@ -91,4 +93,4 @@ management:
enabled-by-default: false
endpoint:
info:
- enabled: true \ No newline at end of file
+ enabled: true