aboutsummaryrefslogtreecommitdiffstats
path: root/adapters/mso-adapter-utils/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'adapters/mso-adapter-utils/src/main')
-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.java32
-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.java1840
-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.java405
-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.java2265
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java403
-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.java412
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java956
-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.java25
42 files changed, 4463 insertions, 4848 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 3b945ae484..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;
@@ -109,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 6b16194471..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,7 +102,7 @@ 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 = "Cloudify";
private static final String CREATE_DEPLOYMENT = "CreateDeployment";
@@ -132,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
@@ -164,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);
@@ -187,159 +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
- 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());
+ 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;
}
@@ -347,302 +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 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();
+ 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);
- }
+ 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();
- 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();
- }
- }
- 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();
- }
+ 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.
@@ -650,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
- try {
- GetDeployment queryDeploymentRequest = cloudify.deployments().byId(deploymentId);
- logger.debug(queryDeploymentRequest.toString());
+ try {
+ GetDeployment queryDeploymentRequest = cloudify.deployments().byId(deploymentId);
+ logger.debug(queryDeploymentRequest.toString());
- // deployment = executeAndRecordCloudifyRequest (queryDeploymentRequest);
- }
- catch (CloudifyResponseException e) {
+ // 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;
+ 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(getDeploymentOutputs(cloudify, deploymentId).get())
- .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;
}
@@ -926,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
*
@@ -964,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]";
- }
-
-
+
/*
- * 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).
+ * 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]";
+ }
- protected <T> T executeAndRecordCloudifyRequest (CloudifyRequest <T> request) {
- String requestType;
- if (request.getClass ().getEnclosingClass () != null) {
- requestType = request.getClass ().getEnclosingClass ().getSimpleName () + "."
- + request.getClass ().getSimpleName ();
+ /*
+ * 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) {
+
+ 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;
@@ -1208,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);
+ }
}
@@ -1297,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);
+ }
}
@@ -1319,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 8da4df28b1..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
@@ -22,206 +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 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;
- }
+ 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) {
+
+ 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 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 + ", cloudOwner=" + cloudOwner + ", 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 300d06b5d1..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";
@@ -131,136 +130,62 @@ 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 cloudOwner,
- 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,
- cloudOwner,
- tenantId,
- stackName,
- null,
- 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 cloudOwner,
- 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,
- cloudOwner,
- tenantId,
- stackName,
- null,
- 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 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);
+ 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 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);
+ 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
@@ -280,19 +205,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
*/
@SuppressWarnings("unchecked")
- 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 {
+ 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) {
@@ -304,259 +220,265 @@ 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);
+ throw heatExceptionToMsoException(e, CREATE_STACK);
} catch (RuntimeException e) {
- throw runtimeExceptionToMsoException (e, CREATE_STACK);
+ 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;
+ }
+ if (deleted) {
+ errorContextMessage.append(" - stack successfully deleted");
+ } else {
+ errorContextMessage.append(" - encountered an error trying to delete the stack");
}
- } 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;
- }
+ } 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
@@ -565,61 +487,60 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
* @return A StackInfo object
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
*/
- public StackInfo queryStack (String cloudSiteId, String cloudOwner, 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 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
@@ -627,40 +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 cloudOwner,
- 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.
@@ -668,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
@@ -727,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
@@ -745,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.
@@ -772,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;
@@ -876,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 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);
+ 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);
+ }
+ 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 }");
+ }
}
- }
- 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();
- }
-
- /*******************************************************************************
+ 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
*
@@ -1515,64 +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 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);
- }
+ 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);
+ }
}
@@ -1580,22 +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 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);
- }
+ 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);
+ }
}
@@ -1603,135 +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 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);
- }
+ 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, 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);
- }
-
- 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 c378be7d4b..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
@@ -67,95 +67,46 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
* Keep these methods around for backward compatibility
*/
- public StackInfo updateStack (String cloudSiteId,
- String cloudOwner,
- 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,
- cloudOwner,
- 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 cloudOwner,
- 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,
- cloudOwner,
- 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 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);
+ 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.
@@ -170,105 +121,98 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
* @throws MsoException Thrown if the Openstack API call returns an exception.
*/
- 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 {
+ 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
@@ -277,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;
@@ -323,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 {
@@ -360,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 eb003cdda6..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
@@ -64,7 +64,7 @@ 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";
@@ -94,29 +94,25 @@ 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 cloudOwner the cloud owner of the cloud site in which to create the stack
@@ -136,19 +132,10 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
@SuppressWarnings("unchecked")
@Override
- 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 {
+ 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");
@@ -160,7 +147,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
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);
@@ -181,17 +168,18 @@ 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);
@@ -230,11 +218,13 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
if (logger.isDebugEnabled()) {
logger.debug("Multicloud Create Response Body: {}", multicloudResponseBody);
}
- StackInfo stackStatus = getStackStatus(cloudSiteId, cloudOwner, 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);
+ multicloudAaiUpdate(cloudSiteId, cloudOwner, tenantId, genericVnfId, vfModuleId, workloadId,
+ pollForCompletion, timeoutMinutes);
}
return stackStatus;
@@ -249,8 +239,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
@Override
- public Map<String, Object> queryStackForOutputs(String cloudSiteId, String cloudOwner,
- 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, cloudOwner, tenantId, stackName);
if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
@@ -260,9 +250,8 @@ 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
@@ -272,9 +261,10 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
*/
@Override
- public StackInfo queryStack (String cloudSiteId, String cloudOwner, 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;
@@ -296,7 +286,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
if (multicloudClient != null) {
Response response = multicloudClient.get();
if (logger.isDebugEnabled()) {
- logger.debug (String.format("Multicloud GET Response: %s", response.toString()));
+ logger.debug(String.format("Multicloud GET Response: %s", response.toString()));
}
MulticloudQueryResponse multicloudQueryBody = null;
@@ -304,7 +294,7 @@ 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());
+ multicloudQueryBody = getQueryBody((java.io.InputStream) response.getEntity());
if (multicloudQueryBody != null) {
returnInfo.setCanonicalName(stackName + "/" + multicloudQueryBody.getWorkloadId());
returnInfo.setStatus(getHeatStatus(multicloudQueryBody.getWorkloadStatus()));
@@ -325,9 +315,10 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
return returnInfo;
}
- public StackInfo deleteStack (String cloudSiteId, String cloudOwner, 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;
@@ -372,23 +363,33 @@ 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 void multicloudAaiUpdate(String cloudSiteId, String cloudOwner, String tenantId, String genericVnfId, String vfModuleId, String workloadId,
- boolean pollForCompletion, int timeoutMinutes) {
+ private void multicloudAaiUpdate(String cloudSiteId, String cloudOwner, String tenantId, String genericVnfId,
+ String vfModuleId, String workloadId, boolean pollForCompletion, int timeoutMinutes) {
- MulticloudRequest multicloudRequest= new MulticloudRequest();
+ MulticloudRequest multicloudRequest = new MulticloudRequest();
multicloudRequest.setGenericVnfId(genericVnfId);
multicloudRequest.setVfModuleId(vfModuleId);
@@ -405,7 +406,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
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());
+ logger.debug(
+ "Multicloud AAI update request failed: " + response.getStatus() + response.getStatusInfo());
return;
}
@@ -413,7 +415,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
return;
}
- int updatePollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
+ int updatePollInterval =
+ Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
int pollTimeout = (timeoutMinutes * 60) + updatePollInterval;
boolean updateTimedOut = false;
logger.debug("updatePollInterval=" + updatePollInterval + ", pollTimeout=" + pollTimeout);
@@ -423,14 +426,15 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
try {
stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, workloadId);
if (logger.isDebugEnabled())
- logger.debug (stackInfo.getStatus() + " (" + workloadId + ")");
+ 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);
+ logger.debug("Multicloud AAI update timeout failure: {} {} {} {}", cloudOwner, cloudSiteId,
+ tenantId, workloadId);
updateTimedOut = true;
break;
}
@@ -445,27 +449,33 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
} catch (MsoException me) {
if (logger.isDebugEnabled())
- logger.debug("Multicloud AAI update exception: {} {} {} {}", cloudOwner, cloudSiteId, tenantId, workloadId, me);
+ 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());
+ 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());
+ 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());
+ logger.debug("Multicloud AAI update successful: {} {}", response.getStatus(),
+ response.getStatusInfo().toString());
}
}
- private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
+ 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 cloudOwner, 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
@@ -474,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;
@@ -486,7 +497,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
while (true) {
try {
stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
- logger.debug (stackInfo.getStatus() + " (" + instanceId + ")");
+ logger.debug(stackInfo.getStatus() + " (" + instanceId + ")");
if (HeatStatus.BUILDING.equals(stackInfo.getStatus())) {
// Stack creation is still running.
@@ -494,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 %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, 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;
}
@@ -504,20 +518,28 @@ 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");
+ 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
+ // 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) {
@@ -526,52 +548,66 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
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 %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, 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);
+ logger.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout="
+ + deletePollTimeout);
StackInfo deleteInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
boolean deleted = false;
while (!deleted) {
@@ -580,35 +616,48 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
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 %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, 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");
@@ -617,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());
@@ -714,18 +766,19 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
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;
}
@@ -734,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);
@@ -748,62 +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,
- cloudOwner,
- tenantId,
- instanceName,
- vduModel,
- 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);
}
}
@@ -812,21 +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, cloudOwner, 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);
}
}
@@ -835,16 +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, cloudOwner, tenantId, instanceId);
+ StackInfo stackInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
// Populate a VduInstance based on the deleted Cloudify Deployment object
VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
@@ -853,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);
}
}
@@ -863,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()) {
@@ -899,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.
@@ -919,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 850f16ff4d..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
@@ -27,7 +27,6 @@ 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;
@@ -51,7 +50,6 @@ 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;
@@ -67,519 +65,495 @@ 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;
- }
- }
-
- 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());
+ 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;
+ }
}
- 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());
+
+ 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;
+ }
+ }
+
+
+ // -------------------------------------------------------------------
+ // 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;
- }
- }
- }
-
-
- private Port findPortById (Quantum neutronClient, String neutronPortId)
- {
- if (neutronPortId == 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<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) {
+ 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;
- }
- }
- }
+ 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 3689d34204..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
@@ -26,22 +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",
- "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"
-})
+@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;
@@ -169,15 +159,12 @@ public class MulticloudRequest implements Serializable {
@Override
public String toString() {
- return new ToStringBuilder(this).append("genericVnfId", genericVnfId)
- .append("vfModuleId", vfModuleId)
+ 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("oofDirectives", oofDirectives).append("sdncDirectives", sdncDirectives)
+ .append("userDirectives", userDirectives).append("templateType", templateType)
.append("templateData", templateData).toString();
}