diff options
author | Benjamin, Max (mb388a) <mb388a@us.att.com> | 2018-07-30 15:56:09 -0400 |
---|---|---|
committer | Benjamin, Max (mb388a) <mb388a@us.att.com> | 2018-07-31 11:09:25 -0400 |
commit | 5a6a6de6f1a26a1897e4917a0df613e25a24eb70 (patch) | |
tree | 59a968f27b4b603aacc9d5e7b51fb598aeec5321 /adapters/mso-adapter-utils/src/main/java | |
parent | b6dc38501f3b746426b42d9de4cc883d894149e8 (diff) |
Containerization feature of SO
Change-Id: I95381232eeefcd247a66a5cec370a8ce1c288e18
Issue-ID: SO-670
Signed-off-by: Benjamin, Max (mb388a) <mb388a@us.att.com>
Diffstat (limited to 'adapters/mso-adapter-utils/src/main/java')
57 files changed, 2128 insertions, 4102 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduPlugin.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/adapters/vdu/VduPlugin.java index 3484646387..ff30c0ee70 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduPlugin.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/adapters/vdu/VduPlugin.java @@ -1,186 +1,186 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.mso.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).
- *
- * 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)
- */
-import java.util.Map;
-
-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
- * 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.
- *
- * 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.
- *
- * @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.
- */
- 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.
- *
- * 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.).
- *
- * @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.
- */
- 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.
- *
- * @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?
- *
- * @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.
- */
- 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.
- *
- * @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.
- *
- * @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.
- */
- public VduInstance updateVdu (
- CloudInfo cloudInfo,
- String instanceId,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException;
-
+/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.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). + * + * 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) + */ +import java.util.Map; + +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 + * 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. + * + * 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. + * + * @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. + */ + 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. + * + * 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.). + * + * @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. + */ + 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. + * + * @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? + * + * @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. + */ + 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. + * + * @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. + * + * @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. + */ + 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/openecomp/mso/cloud/IdentityServerTypeJsonDeserializer.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/Application.java index 093f7ff38b..bc04b09588 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityServerTypeJsonDeserializer.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/Application.java @@ -1,45 +1,38 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
-/**
- *
- */
-package org.openecomp.mso.cloud;
-
-import java.io.IOException;
-
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.core.JsonToken;
-import com.fasterxml.jackson.databind.DeserializationContext;
-import com.fasterxml.jackson.databind.JsonDeserializer;
-
-
-public class IdentityServerTypeJsonDeserializer extends JsonDeserializer<IdentityServerTypeAbstract> {
-
- @Override
- public IdentityServerTypeAbstract deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
- throws IOException, JsonProcessingException {
- JsonToken token = jsonParser.getCurrentToken();
- if (JsonToken.VALUE_STRING.equals(token)) {
- return IdentityServerTypeAbstract.valueOf(jsonParser.getText());
- } else {
- return null;
- }
- }
-}
+/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.cloud; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication(scanBasePackages = { "org.onap"}) +@EnableJpaRepositories({"org.onap.so.db.catalog.data.repository", "org.onap.so.db.request.data.repository"}) +@EntityScan({"org.onap.so.db.catalog.beans", "org.onap.so.db.request.beans"}) +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + System.getProperties().setProperty("mso.db", "MARIADB"); + System.getProperties().setProperty("server.name", "Springboot"); + } +} diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduStateType.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/AuthenticationType.java index 92f5cdab3f..7cb2222525 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduStateType.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/AuthenticationType.java @@ -1,36 +1,25 @@ -/*-
- * ============LICENSE_START=======================================================
- * OPENECOMP - MSO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.mso.adapters.vdu;
-
-
-/*
- * Enum status values to capture the state of a generic (cloud-agnostic) VDU.
- */
-public enum VduStateType {
- NOTFOUND,
- INSTANTIATING,
- INSTANTIATED,
- DELETING,
- DELETED, // Note - only returned in success response to deleteVdu call.
- UPDATING,
- FAILED,
- UNKNOWN
-}
+/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.cloud; + +public enum AuthenticationType { + USERNAME_PASSWORD, RACKSPACE_APIKEY; +} 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 new file mode 100644 index 0000000000..ef5f8232e0 --- /dev/null +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfig.java @@ -0,0 +1,216 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.cloud; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; + +import javax.annotation.PostConstruct; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonRootName; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.EqualsBuilder; + +/** + * 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. + * + * This class also contains methods to query cloud sites and/or identity + * services by ID. + * + */ + +@Configuration +@JsonRootName("cloud_config") +@ConfigurationProperties(prefix="cloud_config") +public class CloudConfig { + + private static final String CLOUD_SITE_VERSION = "2.5"; + private static final String DEFAULT_CLOUD_SITE_ID = "default"; + + @JsonProperty("identity_services") + private Map<String, CloudIdentity> identityServices = new HashMap<>(); + + @JsonProperty("cloud_sites") + private Map <String, CloudSite> cloudSites = new HashMap<>(); + + @JsonProperty("cloudify_managers") + private Map <String, CloudifyManager> cloudifyManagers = new HashMap<>(); + + @PostConstruct + private void init() { + for (Entry<String, CloudIdentity> entry : identityServices.entrySet()) { + entry.getValue().setId(entry.getKey()); + } + + for (Entry<String, CloudSite> entry : cloudSites.entrySet()) { + entry.getValue().setId(entry.getKey()); + } + + for (Entry<String, CloudifyManager> entry : cloudifyManagers.entrySet()) { + entry.getValue().setId(entry.getKey()); + } + } + + /** + * Get a map of all identity services that have been loaded. + */ + public Map<String, CloudIdentity> getIdentityServices() { + return identityServices; + } + + /** + * Get a map of all cloud sites that have been loaded. + */ + public Map<String, CloudSite> getCloudSites() { + return cloudSites; + } + + /** + * Get a Map of all CloudifyManagers that have been loaded. + * @return the Map + */ + public Map<String,CloudifyManager> getCloudifyManagers() { + return cloudifyManagers; + } + + /** + * 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(); + } + if (cloudSites.containsKey(id)) { + return Optional.ofNullable(cloudSites.get(id)); + } else { + return getCloudSiteWithClli(id); + } + } + + public String getCloudSiteId(CloudSite cloudSite) { + for(Entry<String, CloudSite> entry : this.getCloudSites().entrySet()){ + if(entry.getValue().equals(cloudSite)) + return entry.getKey(); + } + return null; + } + + /** + * 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 version + * the version to match; may be null in which case any version + * matches + * @return a CloudSite, or null of no match found + */ + private Optional<CloudSite> getCloudSiteWithClli(String clli) { + Optional <CloudSite> cloudSiteOptional = cloudSites.values().stream().filter(cs -> + cs.getClli() != null && clli.equals(cs.getClli()) && (CLOUD_SITE_VERSION.equals(cs.getAicVersion()))) + .findAny(); + if (cloudSiteOptional.isPresent()) { + return cloudSiteOptional; + } else { + return getDefaultCloudSite(clli); + } + } + + private Optional<CloudSite> getDefaultCloudSite(String clli) { + Optional<CloudSite> cloudSiteOpt = cloudSites.values().stream() + .filter(cs -> cs.getId().equalsIgnoreCase(DEFAULT_CLOUD_SITE_ID)).findAny(); + if (cloudSiteOpt.isPresent()) { + CloudSite defaultCloudSite = cloudSiteOpt.get(); + CloudSite clone = new CloudSite(defaultCloudSite); + clone.setRegionId(clli); + clone.setId(clli); + return Optional.of(clone); + } else { + return Optional.empty(); + } + } + + /** + * Get a specific CloudIdentity, based on an ID. + * + * @param id + * the ID to match + * @return a CloudIdentity, or null of no match found + */ + public CloudIdentity getIdentityService(String id) { + return identityServices.get(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 cloudifyManagers.get(id); + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) + .append("identityServices", getIdentityServices()).append("cloudSites", getCloudSites()).toString(); + } + + @Override + public boolean equals(final Object other) { + if (other == null) { + return false; + } + if (!getClass().equals(other.getClass())) { + return false; + } + CloudConfig castOther = (CloudConfig) other; + return new EqualsBuilder().append(getIdentityServices(), castOther.getIdentityServices()) + .append(getCloudSites(), castOther.getCloudSites()).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(1, 31).append(getIdentityServices()).append(getCloudSites()).toHashCode(); + } +} diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfigIdentityMapper.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfigIdentityMapper.java index 9677d0ee1c..f554aa46cd 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfigIdentityMapper.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfigIdentityMapper.java @@ -1,30 +1,30 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.openecomp.mso.cloud;
-
-/**
- * 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();
-}
+/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.cloud; + +/** + * 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(); +} diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudIdentity.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudIdentity.java new file mode 100644 index 0000000000..188a93025e --- /dev/null +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudIdentity.java @@ -0,0 +1,203 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.cloud; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.openpojo.business.annotation.BusinessKey; +import org.apache.commons.lang3.builder.HashCodeBuilder; + +import java.util.Comparator; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * JavaBean JSON class for a CloudIdentity. This bean represents a cloud identity + * service instance (i.e. a DCP node) in the NVP/AIC cloud. It will be loaded via + * CloudConfig object, of which it is a component (a CloudConfig JSON configuration + * file may contain multiple CloudIdentity definitions). + * + * Note that this is only used to access Cloud Configurations loaded from a + * JSON config file, so there are no explicit setters. + * + */ +public class CloudIdentity { + + @JsonProperty + @BusinessKey + private String id; + @JsonProperty("identity_url") + @BusinessKey + private String identityUrl; + @JsonProperty("mso_id") + @BusinessKey + private String msoId; + @JsonProperty("mso_pass") + @BusinessKey + private String msoPass; + @JsonProperty("admin_tenant") + @BusinessKey + private String adminTenant; + @JsonProperty("member_role") + @BusinessKey + private String memberRole; + @JsonProperty("tenant_metadata") + @BusinessKey + private Boolean tenantMetadata; + @JsonProperty("identity_server_type") + @BusinessKey + private ServerType identityServerType; + @JsonProperty("identity_authentication_type") + @BusinessKey + private AuthenticationType identityAuthenticationType; + + public CloudIdentity() {} + + public String getId () { + return id; + } + + public void setId (String id) { + this.id = id; + } + + public String getIdentityUrl() { + return this.identityUrl; + } + public void setIdentityUrl(String url) { + this.identityUrl = url; + } + + public String getMsoId () { + return msoId; + } + + public void setMsoId (String id) { + this.msoId = id; + } + + public String getMsoPass () { + return msoPass; + } + + public void setMsoPass (String pwd) { + this.msoPass = pwd; + } + + public String getAdminTenant () { + return adminTenant; + } + + public void setAdminTenant (String tenant) { + this.adminTenant = tenant; + } + + public String getMemberRole () { + return memberRole; + } + + public void setMemberRole (String role) { + this.memberRole = role; + } + + public Boolean hasTenantMetadata () { + return tenantMetadata; + } + + public void setTenantMetadata (Boolean meta) { + this.tenantMetadata = meta; + } + + public ServerType getIdentityServerType() { + return this.identityServerType; + } + public void setIdentityServerType(ServerType ist) { + this.identityServerType = ist; + } + public String getIdentityServerTypeAsString() { + return this.identityServerType.toString(); + } + /** + * @return the identityAuthenticationType + */ + public AuthenticationType getIdentityAuthenticationType() { + return identityAuthenticationType; + } + + /** + * @param identityAuthenticationType the identityAuthenticationType to set + */ + public void setIdentityAuthenticationType(AuthenticationType identityAuthenticationType) { + this.identityAuthenticationType = identityAuthenticationType; + } + + @Override + public CloudIdentity clone() { + CloudIdentity cloudIdentityCopy = new CloudIdentity(); + + cloudIdentityCopy.id = this.id; + cloudIdentityCopy.identityUrl = this.identityUrl; + cloudIdentityCopy.msoId = this.msoId; + cloudIdentityCopy.msoPass = this.msoPass; + cloudIdentityCopy.adminTenant = this.adminTenant; + cloudIdentityCopy.memberRole = this.memberRole; + cloudIdentityCopy.tenantMetadata = this.tenantMetadata; + cloudIdentityCopy.identityServerType = this.identityServerType; + cloudIdentityCopy.identityAuthenticationType = this.identityAuthenticationType; + + return cloudIdentityCopy; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("id", getId()) + .append("identityUrl", getIdentityUrl()).append("msoId", getMsoId()) + .append("adminTenant", getAdminTenant()).append("memberRole", getMemberRole()) + .append("tenantMetadata", hasTenantMetadata()).append("identityServerType", getIdentityServerType()) + .append("identityAuthenticationType", getIdentityAuthenticationType()).toString(); + } + + @Override + public boolean equals(final Object other) { + if (other == null) { + return false; + } + if (!getClass().equals(other.getClass())) { + return false; + } + CloudIdentity castOther = (CloudIdentity) other; + return new EqualsBuilder().append(getId(), castOther.getId()) + .append(getIdentityUrl(), castOther.getIdentityUrl()).append(getMsoId(), castOther.getMsoId()) + .append(getMsoPass(), castOther.getMsoPass()).append(getAdminTenant(), castOther.getAdminTenant()) + .append(getMemberRole(), castOther.getMemberRole()) + .append(hasTenantMetadata(), castOther.hasTenantMetadata()) + .append(getIdentityServerType(), castOther.getIdentityServerType()) + .append(getIdentityAuthenticationType(), castOther.getIdentityAuthenticationType()).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(1, 31).append(getId()).append(getIdentityUrl()).append(getMsoId()) + .append(getMsoPass()).append(getAdminTenant()).append(getMemberRole()).append(hasTenantMetadata()) + .append(getIdentityServerType()).append(getIdentityAuthenticationType()).toHashCode(); + } +}
\ No newline at end of file diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudSite.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudSite.java index 1d013ebc60..f38403d0cd 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudSite.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudSite.java @@ -18,10 +18,17 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.cloud; +package org.onap.so.cloud; +import java.util.Comparator; + import com.fasterxml.jackson.annotation.JsonProperty; +import com.openpojo.business.annotation.BusinessKey; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; /** * JavaBean JSON class for a CloudSite. This bean represents a cloud location @@ -35,32 +42,55 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ public class CloudSite { @JsonProperty + @BusinessKey private String id; @JsonProperty("region_id") + @BusinessKey private String regionId; @JsonProperty("identity_service_id") + @BusinessKey private String identityServiceId; @JsonProperty("aic_version") - private String aic_version; + @BusinessKey + private String aicVersion; @JsonProperty("clli") + @BusinessKey private String clli; @JsonProperty("cloudify_id") + @BusinessKey private String cloudifyId; @JsonProperty("platform") + @BusinessKey private String platform; @JsonProperty("orchestrator") + @BusinessKey private String orchestrator; - + // Derived property (set by CloudConfig loader based on identityServiceId) private CloudIdentity identityService; // Derived property (set by CloudConfig loader based on cloudifyId) private CloudifyManager cloudifyManager; - - public CloudSite() {} + public CloudSite() { + + } + + public CloudSite(CloudSite site) { + this.aicVersion = site.getAicVersion(); + this.clli = site.getClli(); + this.cloudifyId = this.getCloudifyId(); + this.cloudifyManager = this.getCloudifyManager(); + this.id = site.getId(); + this.identityService = site.getIdentityService(); + this.identityServiceId = site.getIdentityServiceId(); + this.orchestrator = site.getOrchestrator(); + this.platform = site.getPlatform(); + this.regionId = this.getRegionId(); + } public String getId() { - return id; + return this.id; } + public void setId(String id) { this.id = id; } @@ -76,21 +106,16 @@ public class CloudSite { public String getIdentityServiceId() { return identityServiceId; } - - public CloudIdentity getIdentityService () { - return identityService; - } - - public void setIdentityService (CloudIdentity identity) { - this.identityService = identity; - } - public String getAic_version() { - return aic_version; + public void setIdentityServiceId(String identityServiceId) { + this.identityServiceId = identityServiceId; + } + public String getAicVersion() { + return aicVersion; } - public void setAic_version(String aic_version) { - this.aic_version = aic_version; + public void setAicVersion(String aicVersion) { + this.aicVersion = aicVersion; } public String getClli() { @@ -108,14 +133,6 @@ public class CloudSite { public void setCloudifyId (String id) { this.cloudifyId = id; } - - public CloudifyManager getCloudifyManager () { - return cloudifyManager; - } - - public void setCloudifyManager (CloudifyManager cloudify) { - this.cloudifyManager = cloudify; - } public String getPlatform() { return platform; @@ -133,76 +150,47 @@ public class CloudSite { this.orchestrator = orchestrator; } - @Override - public String toString() { - return "CloudSite: id=" + id + - ", regionId=" + regionId + - ", identityServiceId=" + identityServiceId + - ", aic_version=" + aic_version + - ", clli=" + clli + - ", cloudifyId=" + cloudifyId + - ", platform=" + platform + - ", orchestrator=" + orchestrator; + public CloudIdentity getIdentityService () { + return identityService; } - @Override - public CloudSite clone() { - CloudSite cloudSiteCopy = new CloudSite(); - cloudSiteCopy.id = this.id; - cloudSiteCopy.regionId = this.regionId; - cloudSiteCopy.identityServiceId = this.identityServiceId; - cloudSiteCopy.aic_version = this.aic_version; - cloudSiteCopy.clli = this.clli; - cloudSiteCopy.identityService = this.identityService.clone(); - cloudSiteCopy.cloudifyId = this.cloudifyId; - if (this.cloudifyManager != null) cloudSiteCopy.cloudifyManager = this.cloudifyManager.clone(); - cloudSiteCopy.platform = this.platform; - cloudSiteCopy.orchestrator = this.orchestrator; - - return cloudSiteCopy; + public void setIdentityService (CloudIdentity identity) { + this.identityService = identity; + } + + public CloudifyManager getCloudifyManager () { + return cloudifyManager; + } + + public void setCloudifyManager (CloudifyManager cloudify) { + this.cloudifyManager = cloudify; } @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((identityService == null) ? 0 : identityService.hashCode()); - result = prime * result + ((identityServiceId == null) ? 0 : identityServiceId.hashCode()); - result = prime * result + ((regionId == null) ? 0 : regionId.hashCode()); - result = prime * result + ((aic_version == null) ? 0 : aic_version.hashCode()); - result = prime * result + ((clli == null) ? 0 : clli.hashCode()); - return result; + public String toString() { + return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("regionId", getRegionId()) + .append("identityServiceId", getIdentityServiceId()).append("aicVersion", getAicVersion()) + .append("clli", getClli()).append("cloudifyId", getCloudifyId()).append("platform", getPlatform()) + .append("orchestrator", getOrchestrator()).toString(); } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - CloudSite other = (CloudSite) obj; - if (!cmp(id, other.id)) - return false; - if (!cmp(regionId, other.regionId)) - return false; - if (!cmp(identityServiceId, other.identityServiceId)) - return false; - if (!cmp(aic_version, other.aic_version)) - return false; - if (!cmp(clli, other.clli)) + public boolean equals(final Object other) { + if (other == null) { return false; - if (!cmp(identityService, other.identityService)) + } + if (!getClass().equals(other.getClass())) { return false; - return true; - } - private boolean cmp(Object a, Object b) { - if (a == null) { - return (b == null); - } else { - return a.equals(b); } + CloudSite castOther = (CloudSite) other; + return new EqualsBuilder().append(getRegionId(), castOther.getRegionId()) + .append(getIdentityServiceId(), castOther.getIdentityServiceId()) + .append(getAicVersion(), castOther.getAicVersion()).append(getClli(), castOther.getClli()).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(1, 31).append(getRegionId()).append(getIdentityServiceId()).append(getAicVersion()) + .append(getClli()).toHashCode(); } -} +}
\ No newline at end of file diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudifyManager.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudifyManager.java index 98f2266216..1bf3f136b0 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudifyManager.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudifyManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,15 +18,21 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.cloud; +package org.onap.so.cloud; import java.security.GeneralSecurityException; +import java.util.Comparator; -import com.fasterxml.jackson.annotation.JsonProperty; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; +import org.onap.so.utils.CryptoUtils; -import org.openecomp.mso.utils.CryptoUtils; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.openpojo.business.annotation.BusinessKey; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.EqualsBuilder; /** * JavaBean JSON class for a Cloudify Manager. This bean represents a Cloudify @@ -44,21 +50,28 @@ import org.openecomp.mso.logger.MsoLogger; */ public class CloudifyManager { - private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); + private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, CloudifyManager.class); + @BusinessKey @JsonProperty private String id; + + @BusinessKey @JsonProperty ("cloudify_url") private String cloudifyUrl; + + @BusinessKey @JsonProperty("username") private String username; + + @BusinessKey @JsonProperty("password") private String password; + + @BusinessKey @JsonProperty("version") private String version; - private static String cloudKey = "aa3871669d893c7fb8abbcda31b88b4f"; - public CloudifyManager() {} public String getId() { @@ -85,12 +98,7 @@ public class CloudifyManager { } public String getPassword() { - try { - return CryptoUtils.decrypt (password, cloudKey); - } catch (GeneralSecurityException e) { - LOGGER.error (MessageEnum.RA_GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in getMsoPass", e); - return null; - } + return password; } public void setPassword(String password) { @@ -105,16 +113,6 @@ public class CloudifyManager { this.version = version; } - - @Override - public String toString() { - return "CloudifyManager: id=" + id + - ", cloudifyUrl=" + cloudifyUrl + - ", username=" + username + - ", password=" + password + - ", version=" + version; - } - @Override public CloudifyManager clone() { CloudifyManager cloudifyManagerCopy = new CloudifyManager(); @@ -127,43 +125,29 @@ public class CloudifyManager { } @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((cloudifyUrl == null) ? 0 : cloudifyUrl.hashCode()); - result = prime * result + ((username == null) ? 0 : username.hashCode()); - result = prime * result + ((password == null) ? 0 : password.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - return result; + public String toString() { + return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("id", getId()) + .append("cloudifyUrl", getCloudifyUrl()).append("username", getUsername()) + .append("password", getPassword()).append("version", getVersion()).toString(); } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - CloudifyManager other = (CloudifyManager) obj; - if (!cmp(id, other.id)) - return false; - if (!cmp(cloudifyUrl, other.cloudifyUrl)) - return false; - if (!cmp(username, other.username)) + public boolean equals(final Object other) { + if (other == null) { return false; - if (!cmp(version, other.version)) - return false; - if (!cmp(password, other.password)) + } + if (!getClass().equals(other.getClass())) { return false; - return true; - } - private boolean cmp(Object a, Object b) { - if (a == null) { - return (b == null); - } else { - return a.equals(b); } + CloudifyManager castOther = (CloudifyManager) other; + return new EqualsBuilder().append(getId(), castOther.getId()) + .append(getCloudifyUrl(), castOther.getCloudifyUrl()).append(getUsername(), castOther.getUsername()) + .append(getPassword(), castOther.getPassword()).append(getVersion(), castOther.getVersion()).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(1, 31).append(getId()).append(getCloudifyUrl()).append(getUsername()) + .append(getPassword()).append(getVersion()).toHashCode(); } -} +}
\ No newline at end of file diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityAuthenticationTypeJsonSerializer.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/ServerType.java index 065010035c..ac59018c6b 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityAuthenticationTypeJsonSerializer.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/ServerType.java @@ -1,36 +1,25 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.openecomp.mso.cloud;
-
-import java.io.IOException;
-
-import com.fasterxml.jackson.core.JsonGenerator;
-import com.fasterxml.jackson.databind.JsonSerializer;
-import com.fasterxml.jackson.databind.SerializerProvider;
-
-
-public class IdentityAuthenticationTypeJsonSerializer extends JsonSerializer<IdentityAuthenticationTypeAbstract> {
-
- @Override
- public void serialize(IdentityAuthenticationTypeAbstract tmpObj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
- throws IOException {
- jsonGenerator.writeObject(tmpObj.toString());
- }
-}
+/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.cloud; + +public enum ServerType { + KEYSTONE, ORM; +} 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 new file mode 100644 index 0000000000..5c648eb5e3 --- /dev/null +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.cloud.authentication; + +import org.onap.so.cloud.AuthenticationType; +import org.onap.so.cloud.CloudIdentity; +import org.onap.so.cloud.authentication.models.RackspaceAuthentication; +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; + +/** + * This factory manages all the wrappers associated to authentication types. + * + */ +@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 ())); + } + } +} diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/models/RackspaceAuthentication.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/models/RackspaceAuthentication.java index 6c00349b85..009c9a4c6c 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/models/RackspaceAuthentication.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/models/RackspaceAuthentication.java @@ -1,27 +1,26 @@ -/* - * ============LICENSE_START========================================== - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * =================================================================== +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * http://www.apache.org/licenses/LICENSE-2.0 + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ============LICENSE_END============================================ - * - * ECOMP and OpenECOMP are trademarks - * and service marks of AT&T Intellectual Property. - * + * ============LICENSE_END========================================================= */ -package org.openecomp.mso.cloud.authentication.models; +package org.onap.so.cloud.authentication.models; + +import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @@ -31,10 +30,23 @@ import com.woorea.openstack.keystone.model.Authentication; @JsonRootName("auth") public class RackspaceAuthentication extends Authentication { + /** + * + */ private static final long serialVersionUID = 5451283386875662918L; - public static final class Token { + @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; diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/beans/DeploymentInfo.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfo.java index 9387e22f38..c6e29d05d7 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/beans/DeploymentInfo.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,14 +18,14 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.cloudify.beans; +package org.onap.so.cloudify.beans; -import java.util.Map; import java.util.HashMap; +import java.util.Map; -import org.openecomp.mso.cloudify.v3.model.Deployment; -import org.openecomp.mso.cloudify.v3.model.DeploymentOutputs; -import org.openecomp.mso.cloudify.v3.model.Execution; +import org.onap.so.cloudify.v3.model.Deployment; +import org.onap.so.cloudify.v3.model.DeploymentOutputs; +import org.onap.so.cloudify.v3.model.Execution; /* * This Java bean class relays Heat stack status information to ActiveVOS processes. diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/beans/DeploymentStatus.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentStatus.java index cef5e78c20..5aa47e9d6b 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/beans/DeploymentStatus.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentStatus.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.cloudify.beans; +package org.onap.so.cloudify.beans; /* diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/exceptions/MsoBlueprintAlreadyExists.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoBlueprintAlreadyExists.java index 1bdd6f3850..d5d5684b0f 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/exceptions/MsoBlueprintAlreadyExists.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoBlueprintAlreadyExists.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.cloudify.exceptions; +package org.onap.so.cloudify.exceptions; public class MsoBlueprintAlreadyExists extends MsoCloudifyException { diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/exceptions/MsoCloudifyException.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyException.java index f2469f4706..992df5fd6a 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/exceptions/MsoCloudifyException.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,10 +18,10 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.cloudify.exceptions; +package org.onap.so.cloudify.exceptions; -import org.openecomp.mso.openstack.exceptions.MsoException; -import org.openecomp.mso.openstack.exceptions.MsoExceptionCategory; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.exceptions.MsoExceptionCategory; /** * OpenStack exception. diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/exceptions/MsoCloudifyManagerNotFound.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyManagerNotFound.java index 601e5b78ea..0c795478cd 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/exceptions/MsoCloudifyManagerNotFound.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyManagerNotFound.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.cloudify.exceptions; +package org.onap.so.cloudify.exceptions; public class MsoCloudifyManagerNotFound extends MsoCloudifyException { diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/exceptions/MsoCloudifyTimeout.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeout.java index ba1e2a721b..7dcd69d0a4 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/exceptions/MsoCloudifyTimeout.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeout.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,11 +18,11 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.cloudify.exceptions; +package org.onap.so.cloudify.exceptions; -import org.openecomp.mso.cloudify.v3.model.Execution; -import org.openecomp.mso.openstack.exceptions.MsoException; -import org.openecomp.mso.openstack.exceptions.MsoExceptionCategory; +import org.onap.so.cloudify.v3.model.Execution; +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. diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/exceptions/MsoCloudifyWorkflowException.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java index a397135667..a84da50dc4 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/exceptions/MsoCloudifyWorkflowException.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.cloudify.exceptions; +package org.onap.so.cloudify.exceptions; /** * Reports an error with a Cloudify Workflow execution. diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/exceptions/MsoDeploymentAlreadyExists.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoDeploymentAlreadyExists.java index 37f97a8ce9..4f5685efb3 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/exceptions/MsoDeploymentAlreadyExists.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoDeploymentAlreadyExists.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.cloudify.exceptions; +package org.onap.so.cloudify.exceptions; public class MsoDeploymentAlreadyExists extends MsoCloudifyException { diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/utils/MsoCloudifyUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java index bc3aa4f94f..aa8e37f12b 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloudify/utils/MsoCloudifyUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,8 +18,7 @@ * ============LICENSE_END========================================================= */ - -package org.openecomp.mso.cloudify.utils; +package org.onap.so.cloudify.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -32,128 +31,104 @@ import java.util.Optional; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import org.openecomp.mso.adapters.vdu.CloudInfo; -import org.openecomp.mso.adapters.vdu.PluginAction; -import org.openecomp.mso.adapters.vdu.VduArtifact; -import org.openecomp.mso.adapters.vdu.VduArtifact.ArtifactType; -import org.openecomp.mso.adapters.vdu.VduException; -import org.openecomp.mso.adapters.vdu.VduInstance; -import org.openecomp.mso.adapters.vdu.VduModelInfo; -import org.openecomp.mso.adapters.vdu.VduPlugin; -import org.openecomp.mso.adapters.vdu.VduStateType; -import org.openecomp.mso.adapters.vdu.VduStatus; -import org.openecomp.mso.cloud.CloudConfig; -import org.openecomp.mso.cloud.CloudConfigFactory; -import org.openecomp.mso.cloud.CloudSite; -import org.openecomp.mso.cloud.CloudifyManager; -import org.openecomp.mso.cloudify.base.client.CloudifyBaseException; -import org.openecomp.mso.cloudify.base.client.CloudifyClientTokenProvider; -import org.openecomp.mso.cloudify.base.client.CloudifyConnectException; -import org.openecomp.mso.cloudify.base.client.CloudifyRequest; -import org.openecomp.mso.cloudify.base.client.CloudifyResponseException; -import org.openecomp.mso.cloudify.beans.DeploymentInfo; -import org.openecomp.mso.cloudify.beans.DeploymentStatus; -import org.openecomp.mso.cloudify.exceptions.MsoCloudifyException; -import org.openecomp.mso.cloudify.exceptions.MsoCloudifyManagerNotFound; -import org.openecomp.mso.cloudify.exceptions.MsoDeploymentAlreadyExists; -import org.openecomp.mso.cloudify.v3.client.BlueprintsResource.GetBlueprint; -import org.openecomp.mso.cloudify.v3.client.BlueprintsResource.UploadBlueprint; -import org.openecomp.mso.cloudify.v3.client.Cloudify; -import org.openecomp.mso.cloudify.v3.client.DeploymentsResource.CreateDeployment; -import org.openecomp.mso.cloudify.v3.client.DeploymentsResource.DeleteDeployment; -import org.openecomp.mso.cloudify.v3.client.DeploymentsResource.GetDeployment; -import org.openecomp.mso.cloudify.v3.client.DeploymentsResource.GetDeploymentOutputs; -import org.openecomp.mso.cloudify.v3.client.ExecutionsResource.CancelExecution; -import org.openecomp.mso.cloudify.v3.client.ExecutionsResource.GetExecution; -import org.openecomp.mso.cloudify.v3.client.ExecutionsResource.ListExecutions; -import org.openecomp.mso.cloudify.v3.client.ExecutionsResource.StartExecution; -import org.openecomp.mso.cloudify.v3.model.AzureConfig; -import org.openecomp.mso.cloudify.v3.model.Blueprint; -import org.openecomp.mso.cloudify.v3.model.CancelExecutionParams; -import org.openecomp.mso.cloudify.v3.model.CloudifyError; -import org.openecomp.mso.cloudify.v3.model.CreateDeploymentParams; -import org.openecomp.mso.cloudify.v3.model.Deployment; -import org.openecomp.mso.cloudify.v3.model.DeploymentOutputs; -import org.openecomp.mso.cloudify.v3.model.Execution; -import org.openecomp.mso.cloudify.v3.model.Executions; -import org.openecomp.mso.cloudify.v3.model.OpenstackConfig; -import org.openecomp.mso.cloudify.v3.model.StartExecutionParams; -import org.openecomp.mso.db.catalog.beans.HeatTemplateParam; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoAlarmLogger; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.openstack.exceptions.MsoAdapterException; -import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound; -import org.openecomp.mso.openstack.exceptions.MsoException; -import org.openecomp.mso.openstack.exceptions.MsoExceptionCategory; -import org.openecomp.mso.openstack.exceptions.MsoIOException; -import org.openecomp.mso.openstack.exceptions.MsoOpenstackException; -import org.openecomp.mso.openstack.utils.MsoCommonUtils; -import org.openecomp.mso.properties.MsoJavaProperties; -import org.openecomp.mso.properties.MsoPropertiesException; -import org.openecomp.mso.properties.MsoPropertiesFactory; +import org.onap.so.adapters.vdu.CloudInfo; +import org.onap.so.adapters.vdu.PluginAction; +import org.onap.so.adapters.vdu.VduArtifact; +import org.onap.so.adapters.vdu.VduArtifact.ArtifactType; +import org.onap.so.adapters.vdu.VduException; +import org.onap.so.adapters.vdu.VduInstance; +import org.onap.so.adapters.vdu.VduModelInfo; +import org.onap.so.adapters.vdu.VduPlugin; +import org.onap.so.adapters.vdu.VduStateType; +import org.onap.so.adapters.vdu.VduStatus; +import org.onap.so.cloud.CloudConfig; +import org.onap.so.cloud.CloudSite; +import org.onap.so.cloud.CloudifyManager; +import org.onap.so.cloudify.base.client.CloudifyBaseException; +import org.onap.so.cloudify.base.client.CloudifyClientTokenProvider; +import org.onap.so.cloudify.base.client.CloudifyConnectException; +import org.onap.so.cloudify.base.client.CloudifyRequest; +import org.onap.so.cloudify.base.client.CloudifyResponseException; +import org.onap.so.cloudify.beans.DeploymentInfo; +import org.onap.so.cloudify.beans.DeploymentStatus; +import org.onap.so.cloudify.exceptions.MsoCloudifyException; +import org.onap.so.cloudify.exceptions.MsoCloudifyManagerNotFound; +import org.onap.so.cloudify.exceptions.MsoDeploymentAlreadyExists; +import org.onap.so.cloudify.v3.client.BlueprintsResource.GetBlueprint; +import org.onap.so.cloudify.v3.client.BlueprintsResource.UploadBlueprint; +import org.onap.so.cloudify.v3.client.Cloudify; +import org.onap.so.cloudify.v3.client.DeploymentsResource.CreateDeployment; +import org.onap.so.cloudify.v3.client.DeploymentsResource.DeleteDeployment; +import org.onap.so.cloudify.v3.client.DeploymentsResource.GetDeployment; +import org.onap.so.cloudify.v3.client.DeploymentsResource.GetDeploymentOutputs; +import org.onap.so.cloudify.v3.client.ExecutionsResource.CancelExecution; +import org.onap.so.cloudify.v3.client.ExecutionsResource.GetExecution; +import org.onap.so.cloudify.v3.client.ExecutionsResource.ListExecutions; +import org.onap.so.cloudify.v3.client.ExecutionsResource.StartExecution; +import org.onap.so.cloudify.v3.model.AzureConfig; +import org.onap.so.cloudify.v3.model.Blueprint; +import org.onap.so.cloudify.v3.model.CancelExecutionParams; +import org.onap.so.cloudify.v3.model.CloudifyError; +import org.onap.so.cloudify.v3.model.CreateDeploymentParams; +import org.onap.so.cloudify.v3.model.Deployment; +import org.onap.so.cloudify.v3.model.DeploymentOutputs; +import org.onap.so.cloudify.v3.model.Execution; +import org.onap.so.cloudify.v3.model.Executions; +import org.onap.so.cloudify.v3.model.OpenstackConfig; +import org.onap.so.cloudify.v3.model.StartExecutionParams; +import org.onap.so.config.beans.PoConfig; +import org.onap.so.db.catalog.beans.HeatTemplateParam; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoAlarmLogger; +import org.onap.so.logger.MsoLogger; +import org.onap.so.openstack.exceptions.MsoAdapterException; +import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.exceptions.MsoExceptionCategory; +import org.onap.so.openstack.exceptions.MsoIOException; +import org.onap.so.openstack.exceptions.MsoOpenstackException; +import org.onap.so.openstack.utils.MsoCommonUtils; +import org.onap.so.utils.CryptoUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +@Component public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ - - private MsoPropertiesFactory msoPropertiesFactory; - private CloudConfigFactory cloudConfigFactory; private static final String CLOUDIFY_ERROR = "CloudifyError"; - + private static final String CLOUDIFY = "Cloudify"; private static final String CREATE_DEPLOYMENT = "CreateDeployment"; private static final String DELETE_DEPLOYMENT = "DeleteDeployment"; + private static final String TERMINATED = "terminated"; + private static final String CANCELLED = "cancelled"; // Fetch cloud configuration each time (may be cached in CloudConfig class) + @Autowired protected CloudConfig cloudConfig; + + @Autowired + private Environment environment; + + @Autowired + private PoConfig poConfig; - private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); - - protected MsoJavaProperties msoProps = null; + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoCloudifyUtils.class); // Properties names and variables (with default values) - protected String createPollIntervalProp = "ecomp.mso.adapters.heat.create.pollInterval"; - private String deletePollIntervalProp = "ecomp.mso.adapters.heat.delete.pollInterval"; + protected String createPollIntervalProp = "ecomp.mso.adapters.po.pollInterval"; + private String deletePollIntervalProp = "ecomp.mso.adapters.po.pollInterval"; - protected int createPollIntervalDefault = 15; - private int deletePollIntervalDefault = 15; + protected String createPollIntervalDefault = "15"; + private String deletePollIntervalDefault = "15"; private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); /** - * This constructor MUST be used ONLY in the JUNIT tests, not for real code. - */ - public MsoCloudifyUtils() { - - } - /** - * This constructor MUST be used ONLY in the JUNIT tests, not for real code. - * The MsoPropertiesFactory will be added by EJB injection. - * - * @param msoPropID ID of the mso pro config as defined in web.xml - * @param msoPropFactory The mso properties factory instanciated by EJB injection - * @param cloudConfFactory the Cloud Config instantiated by EJB injection - */ - public MsoCloudifyUtils (String msoPropID, MsoPropertiesFactory msoPropFactory, CloudConfigFactory cloudConfFactory) { - msoPropertiesFactory = msoPropFactory; - cloudConfigFactory = cloudConfFactory; - // Dynamically get properties each time (in case reloaded). - - try { - msoProps = msoPropertiesFactory.getMsoJavaProperties (msoPropID); - } catch (MsoPropertiesException e) { - LOGGER.error (MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. Mso Properties ID not found in cache: " + msoPropID, "", "", MsoLogger.ErrorCode.DataError, "Exception - Mso Properties ID not found in cache", e); - } - cloudConfig = cloudConfigFactory.getCloudConfig (); - LOGGER.debug("MsoCloudifyUtils:" + msoPropID); - - } - - - /** * 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 @@ -226,7 +201,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Build up the parameters to create a new deployment CreateDeploymentParams deploymentParams = new CreateDeploymentParams(); deploymentParams.setBlueprintId(blueprintId); - deploymentParams.setInputs((Map<String,Object>)expandedInputs); + deploymentParams.setInputs(expandedInputs); Deployment deployment = null; try { @@ -252,8 +227,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } } catch (CloudifyConnectException e) { // Error connecting to Cloudify instance. Convert to an MsoException - MsoException me = cloudifyExceptionToMsoException (e, CREATE_DEPLOYMENT); - throw me; + throw cloudifyExceptionToMsoException (e, CREATE_DEPLOYMENT); } catch (RuntimeException e) { // Catch-all throw runtimeExceptionToMsoException (e, CREATE_DEPLOYMENT); @@ -264,15 +238,13 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ * on the deployment. Sleep 30 seconds based on observation of behavior * in a Cloudify VM instance (delay due to "create_deployment_environment"). */ - try { - Thread.sleep(30000); - } catch (InterruptedException e) {} + sleep(30000); /* * Next execute the "install" workflow. * Note - this assumes there are no additional parameters required for the workflow. */ - int createPollInterval = msoProps.getIntProperty (createPollIntervalProp, createPollIntervalDefault); + int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault)); int pollTimeout = (timeoutMinutes * 60) + createPollInterval; Execution installWorkflow = null; @@ -280,12 +252,11 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ try { installWorkflow = executeWorkflow (cloudify, deploymentId, "install", null, pollForCompletion, pollTimeout, createPollInterval); - if (installWorkflow.getStatus().equals("terminated")) { + if (installWorkflow.getStatus().equals(TERMINATED)) { // Success! // Create and return a DeploymentInfo structure. Include the Runtime outputs DeploymentOutputs outputs = getDeploymentOutputs (cloudify, deploymentId); - DeploymentInfo deploymentInfo = new DeploymentInfo (deployment, outputs, installWorkflow); - return deploymentInfo; + return new DeploymentInfo (deployment, outputs, installWorkflow); } else { // The workflow completed with errors. Must try to back it out. @@ -302,7 +273,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Run the uninstall to undo the install Execution uninstallWorkflow = executeWorkflow (cloudify, deploymentId, "uninstall", null, pollForCompletion, deletePollTimeout, deletePollInterval); - if (uninstallWorkflow.getStatus().equals("terminated")) + if (uninstallWorkflow.getStatus().equals(TERMINATED)) { // The uninstall completed. Delete the deployment itself DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId); @@ -376,7 +347,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ GetDeploymentOutputs queryDeploymentOutputs = cloudify.deployments().outputsById(deploymentId); LOGGER.debug (queryDeploymentOutputs.toString()); - deploymentOutputs = executeAndRecordCloudifyRequest(queryDeploymentOutputs, msoProps); + deploymentOutputs = executeAndRecordCloudifyRequest(queryDeploymentOutputs); } catch (CloudifyConnectException ce) { // Couldn't connect to Cloudify @@ -440,7 +411,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ GetExecution queryExecution = cloudify.executions().byId(executionId); command = "query"; - while (!timedOut && !(status.equals("terminated") || status.equals("failed") || status.equals("cancelled"))) + while (!timedOut && !(status.equals(TERMINATED) || status.equals("failed") || status.equals(CANCELLED))) { // workflow is still running; check for timeout if (pollTimeout <= 0) { @@ -449,9 +420,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ continue; } - try { - Thread.sleep (pollInterval * 1000L); - } catch (InterruptedException e) {} + sleep(pollInterval * 1000L); pollTimeout -= pollInterval; LOGGER.debug("pollTimeout remaining: " + pollTimeout); @@ -461,7 +430,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } // Broke the loop. Check again for a terminal state - if (status.equals("terminated")){ + if (status.equals(TERMINATED)){ // Success! LOGGER.debug ("Workflow '" + workflowId + "' completed successfully on deployment '" + deploymentId + "'"); return execution; @@ -471,7 +440,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Cloudify workflow failure: " + execution.getError(), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow: Failed: " + execution.getError()); return execution; } - else if (status.equals("cancelled")){ + 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 (MessageEnum.RA_CREATE_STACK_ERR, "Cloudify workflow cancelled. Deployment is in an indeterminate state", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow cancelled: " + workflowId); return execution; @@ -518,7 +487,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Poll for completion. Create a reusable cloudify query request GetExecution queryExecution = cloudify.executions().byId(executionId); - while (!timedOut && !status.equals("cancelled")) + while (!timedOut && !status.equals(CANCELLED)) { // workflow is still running; check for timeout if (cancelTimeout <= 0) { @@ -527,9 +496,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ continue; } - try { - Thread.sleep (pollInterval * 1000L); - } catch (InterruptedException e) {} + sleep(pollInterval * 1000L); cancelTimeout -= pollInterval; LOGGER.debug("pollTimeout remaining: " + cancelTimeout); @@ -539,7 +506,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } // Broke the loop. Check again for a terminal state - if (status.equals("cancelled")){ + if (status.equals(CANCELLED)){ // Finished cancelling. Return the original exception LOGGER.debug ("Cancel workflow " + workflowId + " completed on deployment " + deploymentId); throw new MsoCloudifyException (-1, "", "", savedException); @@ -596,7 +563,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ LOGGER.debug (queryDeployment.toString()); // deployment = queryDeployment.execute(); - deployment = executeAndRecordCloudifyRequest(queryDeployment, msoProps); + deployment = executeAndRecordCloudifyRequest(queryDeployment); outputs = getDeploymentOutputs (cloudify, deploymentId); @@ -694,8 +661,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } } catch (CloudifyConnectException e) { // Error connecting to Cloudify instance. Convert to an MsoException - MsoException me = cloudifyExceptionToMsoException (e, DELETE_DEPLOYMENT); - throw me; + throw cloudifyExceptionToMsoException (e, DELETE_DEPLOYMENT); } catch (RuntimeException e) { // Catch-all throw runtimeExceptionToMsoException (e, DELETE_DEPLOYMENT); @@ -711,7 +677,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ * 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 = msoProps.getIntProperty (deletePollIntervalProp, deletePollIntervalDefault); + int deletePollInterval = Integer.parseInt(this.environment.getProperty (deletePollIntervalProp, deletePollIntervalDefault)); int pollTimeout = (timeoutMinutes * 60) + deletePollInterval; Execution uninstallWorkflow = null; @@ -719,7 +685,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ try { uninstallWorkflow = executeWorkflow (cloudify, deploymentId, "uninstall", null, true, pollTimeout, deletePollInterval); - if (uninstallWorkflow.getStatus().equals("terminated")) { + if (uninstallWorkflow.getStatus().equals(TERMINATED)) { // Successful uninstall. LOGGER.debug("Uninstall successful for deployment " + deploymentId); } @@ -896,30 +862,22 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ LOGGER.debug ("Blueprint zip file size: " + zipBuffer.size()); // Ready to upload the blueprint zip - InputStream blueprintStream = new ByteArrayInputStream (zipBuffer.toByteArray()); - try { + + try (InputStream blueprintStream = new ByteArrayInputStream (zipBuffer.toByteArray())) { UploadBlueprint uploadRequest = cloudify.blueprints().uploadFromStream(blueprintId, mainFileName, blueprintStream); Blueprint blueprint = uploadRequest.execute(); System.out.println("Successfully uploaded blueprint " + blueprint.getId()); } - catch (CloudifyResponseException e) { - MsoException me = cloudifyExceptionToMsoException (e, "UPLOAD_BLUEPRINT"); - throw me; - } - catch (CloudifyConnectException e) { - MsoException me = cloudifyExceptionToMsoException (e, "UPLOAD_BLUEPRINT"); - throw me; + catch (CloudifyResponseException | CloudifyConnectException e) { + throw cloudifyExceptionToMsoException (e, "UPLOAD_BLUEPRINT"); } catch (RuntimeException e) { // Catch-all - MsoException me = runtimeExceptionToMsoException (e, "UPLOAD_BLUEPRINT"); - throw me; - } - finally { - try { - blueprintStream.close(); - } catch (IOException e) {} - } + throw runtimeExceptionToMsoException (e, "UPLOAD_BLUEPRINT"); + } catch (IOException e) { + // for try-with-resources + throw ioExceptionToMsoException(e, "UPLOAD_BLUEPRINT"); + } return true; } @@ -938,16 +896,16 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ */ public Cloudify getCloudifyClient (CloudSite cloudSite) throws MsoException { - CloudifyManager cloudifyConfig = cloudSite.getCloudifyManager(); + CloudifyManager cloudifyConfig = cloudConfig.getCloudifyManager(cloudSite.getCloudifyId()); if (cloudifyConfig == null) { - throw new MsoCloudifyManagerNotFound (cloudSite.getId()); + throw new MsoCloudifyManagerNotFound (cloudConfig.getCloudSiteId(cloudSite)); } // Get a Cloudify client // 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(), cloudifyConfig.getPassword())); + cloudify.setTokenProvider(new CloudifyClientTokenProvider(cloudifyUrl, cloudifyConfig.getUsername(), CryptoUtils.decryptCloudConfigPassword(cloudifyConfig.getPassword()))); return cloudify; } @@ -974,7 +932,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } try { GetDeployment request = cloudify.deployments().byId (deploymentId); - return executeAndRecordCloudifyRequest (request, msoProps); + return executeAndRecordCloudifyRequest (request); } catch (CloudifyResponseException e) { if (e.getStatus () == 404) { LOGGER.debug ("queryDeployment - not found: " + deploymentId); @@ -994,38 +952,34 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ 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("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 (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("WARNING: unable to convert LinkedHashMap output value for "+ key); - } - } else { - // just try to cast it - could be an integer or some such - try { - String str = (String) obj; - inputs.put(key, str); - } 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 - } + + 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 } } } @@ -1051,8 +1005,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } } else if (type.equalsIgnoreCase("json")) { try { - JsonNode jsonNode = new ObjectMapper().readTree(inputValue); - return jsonNode; + return new ObjectMapper().readTree(inputValue); } catch (Exception e) { LOGGER.debug("Unable to convert " + inputValue + " to a JsonNode!"); @@ -1070,8 +1023,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ 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; + return JSON_MAPPER.writeValueAsString(obj); } catch (JsonParseException jpe) { LOGGER.debug("Error converting json to string " + jpe.getMessage()); } catch (Exception e) { @@ -1088,28 +1040,8 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ * cloudify-client classname of the CloudifyRequest<T> parameter). */ - protected static <T> T executeAndRecordCloudifyRequest (CloudifyRequest <T> request) - { - return executeAndRecordCloudifyRequest (request, null); - } - protected static <T> T executeAndRecordCloudifyRequest (CloudifyRequest <T> request, MsoJavaProperties msoProps) { - - int limit; - // Get the name and method name of the parent class, which triggered this method - StackTraceElement[] classArr = new Exception ().getStackTrace (); - if (classArr.length >=2) { - limit = 3; - } else { - limit = classArr.length; - } - String parentServiceMethodName = classArr[0].getClassName () + "." + classArr[0].getMethodName (); - for (int i = 1; i < limit; i++) { - String className = classArr[i].getClassName (); - if (!className.equals (MsoCommonUtils.class.getName ())) { - parentServiceMethodName = className + "." + classArr[i].getMethodName (); - break; - } - } + + protected <T> T executeAndRecordCloudifyRequest (CloudifyRequest <T> request) { String requestType; if (request.getClass ().getEnclosingClass () != null) { @@ -1119,15 +1051,9 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ requestType = request.getClass ().getSimpleName (); } - int retryDelay = retryDelayDefault; - int retryCount = retryCountDefault; - String retryCodes = retryCodesDefault; - if (msoProps != null) //extra check to avoid NPE - { - retryDelay = msoProps.getIntProperty (retryDelayProp, retryDelayDefault); - retryCount = msoProps.getIntProperty (retryCountProp, retryCountDefault); - retryCodes = msoProps.getProperty (retryCodesProp, retryCodesDefault); - } + int retryDelay = poConfig.getRetryDelay(); + int retryCount = poConfig.getRetryCount(); + String retryCodes = poConfig.getRetryCodes(); // Run the actual command. All exceptions will be propagated while (true) @@ -1146,7 +1072,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ { retryCount--; retry = true; - LOGGER.debug ("CloudifyResponseException ResponseCode:" + code + " at:" + parentServiceMethodName + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); + LOGGER.debug ("CloudifyResponseException ResponseCode:" + code + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); break; } } catch (NumberFormatException e1) { @@ -1157,11 +1083,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } if (retry) { - try { - Thread.sleep (retryDelay * 1000L); - } catch (InterruptedException e1) { - LOGGER.debug ("Thread interrupted while sleeping", e1); - } + sleep(retryDelay * 1000L); } else throw e; // exceeded retryCount or code is not retryable @@ -1171,12 +1093,8 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (retryCount > 0) { retryCount--; - LOGGER.debug ("CloudifyConnectException at:" + parentServiceMethodName + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); - try { - Thread.sleep (retryDelay * 1000L); - } catch (InterruptedException e1) { - LOGGER.debug ("Thread interrupted while sleeping", e1); - } + LOGGER.debug (" request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); + sleep(retryDelay * 1000L); } else throw e; @@ -1197,7 +1115,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ try { // Failed Cloudify calls return an error entity body. CloudifyError error = re.getResponse ().getErrorEntity (CloudifyError.class); - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Cloudify", "Cloudify Error on " + context + ": " + error.getErrorCode(), "Cloudify", "", MsoLogger.ErrorCode.DataError, "Exception - Cloudify Error on " + context); + LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY, "Cloudify Error on " + context + ": " + error.getErrorCode(), CLOUDIFY, "", MsoLogger.ErrorCode.DataError, "Exception - Cloudify Error on " + context); String fullError = error.getErrorCode() + ": " + error.getMessage(); LOGGER.debug(fullError); me = new MsoCloudifyException (re.getStatus(), @@ -1205,7 +1123,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ fullError); } catch (Exception e2) { // Couldn't parse the body as a "CloudifyError". Report the original HTTP error. - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Cloudify", "HTTP Error on " + context + ": " + re.getStatus() + "," + e.getMessage(), "Cloudify", "", MsoLogger.ErrorCode.DataError, "Exception - HTTP Error on " + context, e2); + LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY, "HTTP Error on " + context + ": " + re.getStatus() + "," + e.getMessage(), CLOUDIFY, "", MsoLogger.ErrorCode.DataError, "Exception - HTTP Error on " + context, e2); me = new MsoCloudifyException (re.getStatus (), re.getMessage (), ""); } @@ -1214,7 +1132,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Generate an alarm for 5XX and higher errors. if (re.getStatus () >= 500) { - alarmLogger.sendAlarm ("CloudifyError", MsoAlarmLogger.CRITICAL, me.getContextMessage ()); + alarmLogger.sendAlarm (CLOUDIFY_ERROR, MsoAlarmLogger.CRITICAL, me.getContextMessage ()); } } else if (e instanceof CloudifyConnectException) { CloudifyConnectException ce = (CloudifyConnectException) e; @@ -1224,7 +1142,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Generate an alarm for all connection errors. alarmLogger.sendAlarm ("CloudifyIOError", MsoAlarmLogger.CRITICAL, me.getContextMessage ()); - LOGGER.error(MessageEnum.RA_CONNECTION_EXCEPTION, "Cloudify", "Cloudify connection error on " + context + ": " + e, "Cloudify", "", MsoLogger.ErrorCode.DataError, "Cloudify connection error on " + context); + LOGGER.error(MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY, "Cloudify connection error on " + context + ": " + e, CLOUDIFY, "", MsoLogger.ErrorCode.DataError, "Cloudify connection error on " + context); } return me; @@ -1249,7 +1167,8 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ * The basic MsoCloudifyUtils separates blueprint management from deploument actions, * but the VduPlugin does not declare blueprint management operations. */ - public VduInstance instantiateVdu ( + @Override + public VduInstance instantiateVdu ( CloudInfo cloudInfo, String instanceName, Map<String,Object> inputs, @@ -1317,9 +1236,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ vduModel.getTimeoutMinutes(), rollbackOnFailure); - VduInstance vduInstance = deploymentInfoToVduInstance(deployment); - - return vduInstance; + return deploymentInfoToVduInstance(deployment); } catch (Exception e) { throw new VduException ("CloudifyUtils (instantiateVDU): Create-and-install-deployment Exception", e); @@ -1330,7 +1247,8 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ /** * VduPlugin interface for query function. */ - public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId) + @Override + public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId) throws VduException { String cloudSiteId = cloudInfo.getCloudSiteId(); @@ -1340,9 +1258,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Query the Cloudify Deployment object and populate a VduInstance DeploymentInfo deployment = queryDeployment (cloudSiteId, tenantId, instanceId); - VduInstance vduInstance = deploymentInfoToVduInstance(deployment); - - return vduInstance; + return deploymentInfoToVduInstance(deployment); } catch (Exception e) { throw new VduException ("Query VDU Exception", e); @@ -1353,7 +1269,8 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ /** * VduPlugin interface for delete function. */ - public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes) + @Override + public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes) throws VduException { String cloudSiteId = cloudInfo.getCloudSiteId(); @@ -1364,9 +1281,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ DeploymentInfo deployment = uninstallAndDeleteDeployment (cloudSiteId, tenantId, instanceId, timeoutMinutes); // Populate a VduInstance based on the deleted Cloudify Deployment object - VduInstance vduInstance = deploymentInfoToVduInstance(deployment); - - return vduInstance; + return deploymentInfoToVduInstance(deployment); } catch (Exception e) { throw new VduException ("Delete VDU Exception", e); @@ -1381,7 +1296,8 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ * Just return a VduException. * */ - public VduInstance updateVdu ( + @Override + public VduInstance updateVdu ( CloudInfo cloudInfo, String instanceId, Map<String,Object> inputs, @@ -1460,9 +1376,9 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ 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 (cloudSite.getIdentityService().getMsoPass()); + openstackConfig.setAuthUrl (cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()).getIdentityUrl()); + openstackConfig.setUsername (cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()).getMsoId()); + openstackConfig.setPassword (CryptoUtils.decryptCloudConfigPassword(cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()).getMsoPass())); openstackConfig.setTenantName (tenantId); return openstackConfig; } @@ -1480,4 +1396,13 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ 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(); + } + } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityServerTypeJsonSerializer.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/config/beans/PoConfig.java index d2662a1622..3098a5410a 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityServerTypeJsonSerializer.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/config/beans/PoConfig.java @@ -1,37 +1,53 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.openecomp.mso.cloud;
-
-import java.io.IOException;
-
-import com.fasterxml.jackson.core.JsonGenerator;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.JsonSerializer;
-import com.fasterxml.jackson.databind.SerializerProvider;
-
-
-public class IdentityServerTypeJsonSerializer extends JsonSerializer<IdentityServerTypeAbstract> {
-
- @Override
- public void serialize(IdentityServerTypeAbstract tmpObj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
- throws IOException, JsonProcessingException {
- jsonGenerator.writeObject(tmpObj.toString());
- }
-}
+/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.config.beans; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix="adapters.po") +public class PoConfig { + + private String retryCodes; + private int retryDelay; + private int retryCount; + + 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; + } + +} 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 new file mode 100644 index 0000000000..5eaca976d0 --- /dev/null +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/HeatCacheEntry.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.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. + */ +public class HeatCacheEntry implements Serializable { + + private static final long serialVersionUID = 1L; + + private String heatUrl; + private String token; + private 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); + return heatClient; + } + + 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/NeutronCacheEntry.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/NeutronCacheEntry.java new file mode 100644 index 0000000000..d89fd1a73f --- /dev/null +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/NeutronCacheEntry.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.openstack.beans; + +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. + */ +public class NeutronCacheEntry implements Serializable { + private static final long serialVersionUID = 1L; + + 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 void setNeutronUrl(String neutronUrl) { + this.neutronUrl = neutronUrl; + } + + public String getToken() { + return token; + } + + 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/openecomp/mso/openstack/beans/VnfRollback.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/VnfRollback.java index 43b742f326..bb8aa92281 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/VnfRollback.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/VnfRollback.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,9 +18,10 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.openstack.beans; +package org.onap.so.openstack.beans; -import org.openecomp.mso.entity.MsoRequest; +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" @@ -28,6 +29,7 @@ import org.openecomp.mso.entity.MsoRequest; * * */ +@Component public class VnfRollback { private String vnfId; private String tenantId; diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoCommonUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java index 7d6de317ad..98793601d0 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoCommonUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java @@ -18,18 +18,23 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.openstack.utils; - - -import org.openecomp.mso.logger.MsoAlarmLogger; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.openstack.exceptions.MsoAdapterException; -import org.openecomp.mso.openstack.exceptions.MsoException; -import org.openecomp.mso.openstack.exceptions.MsoExceptionCategory; -import org.openecomp.mso.openstack.exceptions.MsoIOException; -import org.openecomp.mso.openstack.exceptions.MsoOpenstackException; -import org.openecomp.mso.properties.MsoJavaProperties; +package org.onap.so.openstack.utils; + + +import java.io.IOException; + +import org.onap.so.config.beans.PoConfig; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoAlarmLogger; +import org.onap.so.logger.MsoLogger; +import org.onap.so.openstack.exceptions.MsoAdapterException; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.exceptions.MsoExceptionCategory; +import org.onap.so.openstack.exceptions.MsoIOException; +import org.onap.so.openstack.exceptions.MsoOpenstackException; +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; @@ -38,17 +43,14 @@ import com.woorea.openstack.heat.model.Explanation; import com.woorea.openstack.keystone.model.Error; import com.woorea.openstack.quantum.model.NeutronError; +@Component("CommonUtils") public class MsoCommonUtils { - private static MsoLogger logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); - protected static MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); - protected static String retryDelayProp = "ecomp.mso.adapters.po.retryDelay"; - protected static String retryCountProp = "ecomp.mso.adapters.po.retryCount"; - protected static String retryCodesProp = "ecomp.mso.adapters.po.retryCodes"; - protected static int retryDelayDefault = 5; - protected static int retryCountDefault = 3; - protected static String retryCodesDefault = "504"; - + private static MsoLogger logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, MsoCommonUtils.class); + protected static MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); + + @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 @@ -56,29 +58,11 @@ public class MsoCommonUtils { * openstack-java-sdk classname of the OpenStackRequest<T> parameter). */ - protected static <T> T executeAndRecordOpenstackRequest (OpenStackRequest <T> request) - { - return executeAndRecordOpenstackRequest (request, null); - } - protected static <T> T executeAndRecordOpenstackRequest (OpenStackRequest <T> request, MsoJavaProperties msoProps) { + protected <T> T executeAndRecordOpenstackRequest (OpenStackRequest <T> request) { int limit; - // Get the name and method name of the parent class, which triggered this method - StackTraceElement[] classArr = new Exception ().getStackTrace (); - if (classArr.length >=2) { - limit = 3; - } else { - limit = classArr.length; - } - String parentServiceMethodName = classArr[0].getClassName () + "." + classArr[0].getMethodName (); - for (int i = 1; i < limit; i++) { - String className = classArr[i].getClassName (); - if (!className.equals (MsoCommonUtils.class.getName ())) { - parentServiceMethodName = className + "." + classArr[i].getMethodName (); - break; - } - } - + + long start = System.currentTimeMillis (); String requestType; if (request.getClass ().getEnclosingClass () != null) { requestType = request.getClass ().getEnclosingClass ().getSimpleName () + "." @@ -87,16 +71,10 @@ public class MsoCommonUtils { requestType = request.getClass ().getSimpleName (); } - int retryDelay = retryDelayDefault; - int retryCount = retryCountDefault; - String retryCodes = retryCodesDefault; - if (msoProps != null) //extra check to avoid NPE - { - retryDelay = msoProps.getIntProperty (retryDelayProp, retryDelayDefault); - retryCount = msoProps.getIntProperty (retryCountProp, retryCountDefault); - retryCodes = msoProps.getProperty (retryCodesProp, retryCodesDefault); - } - + int retryDelay = poConfig.getRetryDelay(); + int retryCount = poConfig.getRetryCount(); + String retryCodes = poConfig.getRetryCodes(); + // Run the actual command. All exceptions will be propagated while (true) { @@ -114,7 +92,7 @@ public class MsoCommonUtils { { retryCount--; retry = true; - logger.debug ("OpenStackResponseException ResponseCode:" + code + " at:" + parentServiceMethodName + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); + logger.debug ("OpenStackResponseException ResponseCode:" + code + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); break; } } catch (NumberFormatException e1) { @@ -140,7 +118,7 @@ public class MsoCommonUtils { if (retryCount > 0) { retryCount--; - logger.debug ("OpenstackConnectException at:" + parentServiceMethodName + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); + logger.debug (" request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); try { Thread.sleep (retryDelay * 1000L); } catch (InterruptedException e1) { @@ -159,7 +137,7 @@ public class MsoCommonUtils { * Convert an Openstack Exception on a Keystone call to an MsoException. * This method supports both OpenstackResponseException and OpenStackConnectException. */ - protected static MsoException keystoneErrorToMsoException (OpenStackBaseException e, String context) { + protected MsoException keystoneErrorToMsoException (OpenStackBaseException e, String context) { MsoException me = null; if (e instanceof OpenStackResponseException) { @@ -303,11 +281,23 @@ public class MsoCommonUtils { return me; } + + protected MsoException ioExceptionToMsoException(IOException e, String context) { + MsoAdapterException me = new MsoAdapterException (e.getMessage (), e); + me.addContext (context); + me.setCategory (MsoExceptionCategory.INTERNAL); - public static boolean isNullOrEmpty (String s) { - return s == null || s.isEmpty(); - } + // Always generate an alarm for internal exceptions + logger.error(MessageEnum.RA_GENERAL_EXCEPTION_ARG, "An exception occured on "+ context + ": " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "An exception occured on "+ context); + alarmLogger.sendAlarm ("AdapterInternalError", MsoAlarmLogger.CRITICAL, me.getContextMessage ()); + return me; + } + public boolean isNullOrEmpty (String s) { + return s == null || s.isEmpty(); + } + + } 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 new file mode 100644 index 0000000000..c95e62dad0 --- /dev/null +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java @@ -0,0 +1,257 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.openstack.utils; + + + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +import org.onap.so.db.catalog.beans.HeatTemplateParam; +import org.onap.so.logger.MsoLogger; + +public class MsoHeatEnvironmentEntry { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, 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; + } + + @Override + public String toString() { + 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 void setHPAParameters(StringBuilder hpasb) { + try { + MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(hpasb.toString().getBytes()); + Set<MsoHeatEnvironmentParameter> hpaParams = yaml.getParameterListFromEnvt(); + for (MsoHeatEnvironmentParameter hpaparam : hpaParams) { + for (MsoHeatEnvironmentParameter param : this.parameters) { + if (param.getName() == hpaparam.getName()) { + param.setValue(hpaparam.getValue()); + } + } + } + } catch (Exception e) { + LOGGER.debug("Exception:", e); + this.errorString = e.getMessage(); + //e.printStackTrace(); + } + } +} diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentParameter.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameter.java index cd1a3e5130..7e4c9d00c4 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentParameter.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameter.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.openstack.utils; +package org.onap.so.openstack.utils; import java.util.Objects; diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentResource.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java index a0c9b7a105..c174b58f95 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentResource.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java @@ -19,13 +19,13 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.openstack.utils; +package org.onap.so.openstack.utils; -import org.openecomp.mso.logger.MsoLogger; +import org.onap.so.logger.MsoLogger; public class MsoHeatEnvironmentResource { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatEnvironmentResource.class); private String name; private String value; diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java index f7723b6a8f..e5ece20cb7 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java @@ -8,9 +8,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,49 +19,54 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.openstack.utils; +package org.onap.so.openstack.utils; -import java.io.Serializable; +import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; -import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; -import org.openecomp.mso.adapters.vdu.CloudInfo; -import org.openecomp.mso.adapters.vdu.PluginAction; -import org.openecomp.mso.adapters.vdu.VduArtifact; -import org.openecomp.mso.adapters.vdu.VduArtifact.ArtifactType; -import org.openecomp.mso.adapters.vdu.VduException; -import org.openecomp.mso.adapters.vdu.VduInstance; -import org.openecomp.mso.adapters.vdu.VduModelInfo; -import org.openecomp.mso.adapters.vdu.VduPlugin; -import org.openecomp.mso.adapters.vdu.VduStateType; -import org.openecomp.mso.adapters.vdu.VduStatus; -import org.openecomp.mso.cloud.CloudConfig; -import org.openecomp.mso.cloud.CloudConfigFactory; -import org.openecomp.mso.cloud.CloudIdentity; -import org.openecomp.mso.cloud.CloudSite; -import org.openecomp.mso.db.catalog.beans.HeatTemplate; -import org.openecomp.mso.db.catalog.beans.HeatTemplateParam; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoAlarmLogger; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.openstack.beans.HeatStatus; -import org.openecomp.mso.openstack.beans.StackInfo; -import org.openecomp.mso.openstack.exceptions.MsoAdapterException; -import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound; -import org.openecomp.mso.openstack.exceptions.MsoException; -import org.openecomp.mso.openstack.exceptions.MsoIOException; -import org.openecomp.mso.openstack.exceptions.MsoOpenstackException; -import org.openecomp.mso.openstack.exceptions.MsoStackAlreadyExists; -import org.openecomp.mso.openstack.exceptions.MsoTenantNotFound; -import org.openecomp.mso.properties.MsoJavaProperties; -import org.openecomp.mso.properties.MsoPropertiesException; -import org.openecomp.mso.properties.MsoPropertiesFactory; - +import org.onap.so.adapters.vdu.CloudInfo; +import org.onap.so.adapters.vdu.PluginAction; +import org.onap.so.adapters.vdu.VduArtifact; +import org.onap.so.adapters.vdu.VduArtifact.ArtifactType; +import org.onap.so.adapters.vdu.VduException; +import org.onap.so.adapters.vdu.VduInstance; +import org.onap.so.adapters.vdu.VduModelInfo; +import org.onap.so.adapters.vdu.VduPlugin; +import org.onap.so.adapters.vdu.VduStateType; +import org.onap.so.adapters.vdu.VduStatus; +import org.onap.so.cloud.CloudConfig; +import org.onap.so.cloud.CloudIdentity; +import org.onap.so.cloud.CloudSite; +import org.onap.so.cloud.authentication.AuthenticationMethodFactory; +import org.onap.so.db.catalog.beans.HeatTemplate; +import org.onap.so.db.catalog.beans.HeatTemplateParam; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoAlarmLogger; +import org.onap.so.logger.MsoLogger; +import org.onap.so.openstack.beans.HeatCacheEntry; +import org.onap.so.openstack.beans.HeatStatus; +import org.onap.so.openstack.beans.StackInfo; +import org.onap.so.openstack.exceptions.MsoAdapterException; +import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.exceptions.MsoIOException; +import org.onap.so.openstack.exceptions.MsoOpenstackException; +import org.onap.so.openstack.exceptions.MsoStackAlreadyExists; +import org.onap.so.openstack.exceptions.MsoTenantNotFound; +import org.onap.so.openstack.mappers.StackInfoMapper; +import org.onap.so.utils.CryptoUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Primary; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.woorea.openstack.base.client.OpenStackConnectException; @@ -77,12 +82,10 @@ import com.woorea.openstack.keystone.model.Access; import com.woorea.openstack.keystone.model.Authentication; import com.woorea.openstack.keystone.utils.KeystoneUtils; +@Primary +@Component public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ - private MsoPropertiesFactory msoPropertiesFactory; - - private CloudConfigFactory cloudConfigFactory; - private static final String TOKEN_AUTH = "TokenAuth"; private static final String QUERY_ALL_STACKS = "QueryAllStacks"; @@ -100,54 +103,30 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // The cache key is "tenantId:cloudId" private static Map <String, HeatCacheEntry> heatClientCache = new HashMap <> (); - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); - - protected MsoJavaProperties msoProps = null; + // Fetch cloud configuration each time (may be cached in CloudConfig class) + @Autowired + protected CloudConfig cloudConfig; + + @Autowired + private Environment environment; + @Autowired + private AuthenticationMethodFactory authenticationMethodFactory; + + @Autowired + private MsoTenantUtilsFactory tenantUtilsFactory; + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatUtils.class); + // Properties names and variables (with default values) - protected String createPollIntervalProp = "ecomp.mso.adapters.heat.create.pollInterval"; - private String deletePollIntervalProp = "ecomp.mso.adapters.heat.delete.pollInterval"; - private String deletePollTimeoutProp = "ecomp.mso.adapters.heat.delete.pollTimeout"; - - protected int createPollIntervalDefault = 15; - private int deletePollIntervalDefault = 15; - private int deletePollTimeoutDefault = 300; - private String msoPropID; + protected String createPollIntervalProp = "ecomp.mso.adapters.po.pollInterval"; + private String deletePollIntervalProp = "ecomp.mso.adapters.po.pollInterval"; + private String deletePollTimeoutProp = "ecomp.mso.adapters.po.pollTimeout"; - private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); - - /** - * This constructor MUST be used ONLY in the JUNIT tests, not for real code. - */ - public MsoHeatUtils() { - - } + protected static final String createPollIntervalDefault = "15"; + private static final String deletePollIntervalDefault = "15"; - /** - * This constructor MUST be used ONLY in the JUNIT tests, not for real code. - * The MsoPropertiesFactory will be added by EJB injection. - * - * @param msoPropID ID of the mso pro config as defined in web.xml - * @param msoPropFactory The mso properties factory instanciated by EJB injection - * @param cloudConfFactory the Cloud Config instantiated by EJB injection - */ - public MsoHeatUtils (String msoPropID, MsoPropertiesFactory msoPropFactory, CloudConfigFactory cloudConfFactory) { - msoPropertiesFactory = msoPropFactory; - cloudConfigFactory = cloudConfFactory; - this.msoPropID = msoPropID; - // Dynamically get properties each time (in case reloaded). - - try { - msoProps = msoPropertiesFactory.getMsoJavaProperties (msoPropID); - } catch (MsoPropertiesException e) { - LOGGER.error (MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. Mso Properties ID not found in cache: " + msoPropID, "", "", MsoLogger.ErrorCode.DataError, "Exception - Mso Properties ID not found in cache", e); - } - LOGGER.debug("MsoHeatUtils:" + msoPropID); - } - - protected CloudConfigFactory getCloudConfigFactory() { - return cloudConfigFactory; - } + private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); /** * keep this old method signature here to maintain backwards compatibility. keep others as well. @@ -323,7 +302,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow( + 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) @@ -335,12 +314,21 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ LOGGER.debug ("Ready to Create Stack (" + heatTemplate + ") with input params: " + 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 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 ((Map <String, Object>) stackInputs); + stack.setParameters (normalized); stack.setTemplate (heatTemplate); stack.setDisableRollback (true); // TJM New for PO Adapter - add envt variable @@ -354,11 +342,11 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // 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)); + for (Entry<String, Object> entry : files.entrySet()) { + combinedFiles.put(entry.getKey(), entry.getValue()); } - for (String keyString : heatFiles.keySet ()) { - combinedFiles.put (keyString, heatFiles.get (keyString)); + for (Entry<String, Object> entry : heatFiles.entrySet()) { + combinedFiles.put(entry.getKey(), entry.getValue()); } stack.setFiles (combinedFiles); } else { @@ -376,11 +364,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // 1802 - attempt to add better formatted printout of request to openstack try { - Map<String, Object> inputs = new HashMap<String, Object>(); - for (String key : stackInputs.keySet()) { - Object o = (Object) stackInputs.get(key); - if (o != null) { - inputs.put(key, o); + Map<String, Object> inputs = new HashMap<>(); + for (Entry<String, ?> entry : stackInputs.entrySet()) { + if (entry.getValue() != null) { + inputs.put(entry.getKey(), entry.getValue()); } } LOGGER.debug(this.printStackRequest(tenantId, heatFiles, files, environment, inputs, stackName, heatTemplate, timeoutMinutes, backout, cloudSiteId)); @@ -395,15 +382,15 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ OpenStackRequest <Stack> request = heatClient.getStacks ().create (stack); // Begin X-Auth-User // Obtain an MSO token for the tenant - CloudIdentity cloudIdentity = cloudSite.getIdentityService (); + CloudIdentity cloudIdentity = cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()); // cloudIdentity.getMsoId(), cloudIdentity.getMsoPass() //req request.header ("X-Auth-User", cloudIdentity.getMsoId ()); - request.header ("X-Auth-Key", cloudIdentity.getMsoPass ()); + request.header ("X-Auth-Key", CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass ())); LOGGER.debug ("headers added, about to executeAndRecordOpenstackRequest"); //LOGGER.debug(this.requestToStringBuilder(stack).toString()); // END - try to fix X-Auth-User - heatStack = executeAndRecordOpenstackRequest (request, msoProps); + heatStack = executeAndRecordOpenstackRequest (request); } catch (OpenStackResponseException e) { // Since this came on the 'Create Stack' command, nothing was changed // in the cloud. Return the error as an exception. @@ -434,8 +421,9 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ if (pollForCompletion) { // 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 = msoProps.getIntProperty (createPollIntervalProp, createPollIntervalDefault); + // 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 pollTimeout = (timeoutMinutes * 60) + createPollInterval; // New 1610 - poll on delete if we rollback - use same values for now int deletePollInterval = createPollInterval; @@ -464,11 +452,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ createTimedOut = true; break; } - try { - Thread.sleep (createPollInterval * 1000L); - } catch (InterruptedException e) { - LOGGER.debug ("Thread interrupted while sleeping", e); - } + + sleep(createPollInterval * 1000L); pollTimeout -= createPollInterval; LOGGER.debug("pollTimeout remaining: " + pollTimeout); @@ -489,7 +474,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { LOGGER.debug("Create Stack error - unable to query for stack status - attempting to delete stack: " + canonicalName + " - This will likely fail and/or we won't be able to query to see if delete worked"); OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName); - executeAndRecordOpenstackRequest (request, msoProps); + executeAndRecordOpenstackRequest (request); // 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; @@ -505,11 +490,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ "Rollback: DELETE stack timeout"); break; } else { - try { - Thread.sleep(deletePollInterval * 1000L); - } catch (InterruptedException ie) { - LOGGER.debug("Thread interrupted while sleeping", ie); - } + sleep(deletePollInterval * 1000L); deletePollTimeout -= deletePollInterval; } } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){ @@ -560,7 +541,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ LOGGER.debug("Create Stack errored - attempting to DELETE stack: " + canonicalName); LOGGER.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout=" + deletePollTimeout); OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName); - executeAndRecordOpenstackRequest (request, msoProps); + executeAndRecordOpenstackRequest (request); boolean deleted = false; while (!deleted) { try { @@ -574,11 +555,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ "Rollback: DELETE stack timeout"); break; } else { - try { - Thread.sleep(deletePollInterval * 1000L); - } catch (InterruptedException ie) { - LOGGER.debug("Thread interrupted while sleeping", ie); - } + sleep(deletePollInterval * 1000L); deletePollTimeout -= deletePollInterval; LOGGER.debug("deletePollTimeout remaining: " + deletePollTimeout); } @@ -641,7 +618,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ LOGGER.debug (heatStack.getStackStatus ()); } - return new StackInfo (heatStack); + return new StackInfoMapper(heatStack).map(); } /** @@ -659,7 +636,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ LOGGER.debug ("Query HEAT stack: " + stackName + " in tenant " + tenantId); // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow( + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); LOGGER.debug("Found: " + cloudSite.toString()); @@ -687,11 +664,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ if (heatStack == null) { // Stack does not exist. Return a StackInfo with status NOTFOUND - StackInfo stackInfo = new StackInfo (stackName, HeatStatus.NOTFOUND); - return stackInfo; + return new StackInfo (stackName, HeatStatus.NOTFOUND); } - return new StackInfo (heatStack); + return new StackInfoMapper(heatStack).map(); } /** @@ -721,7 +697,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ String stackName, boolean pollForCompletion) throws MsoException { // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow( + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); LOGGER.debug("Found: " + cloudSite.toString()); @@ -766,7 +742,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ LOGGER.debug ("Heat Client is NULL" ); } - executeAndRecordOpenstackRequest (request, msoProps); + executeAndRecordOpenstackRequest (request); } catch (OpenStackResponseException e) { if (e.getStatus () == 404) { // Not found. We are OK with this. Return a StackInfo with status NOTFOUND @@ -789,8 +765,9 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ if (pollForCompletion) { // Set a timeout on polling - int pollInterval = msoProps.getIntProperty (deletePollIntervalProp, deletePollIntervalDefault); - int pollTimeout = msoProps.getIntProperty (deletePollTimeoutProp, deletePollTimeoutDefault); + + 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). @@ -824,13 +801,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ throw me; } - try { - Thread.sleep (pollInterval * 1000L); - } catch (InterruptedException e) { - LOGGER.debug ("Thread interrupted while sleeping", e); - } + sleep(pollInterval * 1000L); pollTimeout -= pollInterval; + LOGGER.debug("pollTimeout remaining: " + pollTimeout); heatStack = queryHeatStack (heatClient, canonicalName); } @@ -840,7 +814,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } // Return the current status (if not polling, the delete may still be in progress) - StackInfo stackInfo = new StackInfo (heatStack); + StackInfo stackInfo = new StackInfoMapper(heatStack).map(); stackInfo.setName (stackName); return stackInfo; @@ -861,21 +835,21 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ */ public List <StackInfo> queryAllStacks (String tenantId, String cloudSiteId) throws MsoException { // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow( + 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); try { OpenStackRequest <Stacks> request = heatClient.getStacks ().list (); - Stacks stacks = executeAndRecordOpenstackRequest (request, msoProps); + Stacks stacks = executeAndRecordOpenstackRequest (request); 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 StackInfo (stack)); + stackList.add (new StackInfoMapper(stack).map()); } } @@ -913,7 +887,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ * is thrown. */ public Map <String, Object> validateStackParams (Map <String, Object> inputParams, - HeatTemplate heatTemplate) throws IllegalArgumentException { + HeatTemplate heatTemplate) { // Check that required parameters have been supplied for this template type StringBuilder missingParams = null; List <String> paramList = new ArrayList <> (); @@ -940,14 +914,16 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // Remove any extraneous parameters (don't throw an error) Map <String, Object> updatedParams = new HashMap <> (); List <String> extraParams = new ArrayList <> (); - for (String key : inputParams.keySet ()) { - if (!paramList.contains (key)) { - // This is not a valid parameter for this template - extraParams.add (key); - } else { - updatedParams.put (key, inputParams.get (key)); - } + + 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 (!extraParams.isEmpty ()) { LOGGER.warn (MessageEnum.RA_GENERAL_WARNING, "Heat Stack (" + heatTemplate.getTemplateName () + ") extra input params received: " @@ -973,7 +949,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ * @return an authenticated Heat object */ public Heat getHeatClient (CloudSite cloudSite, String tenantId) throws MsoException { - String cloudId = cloudSite.getId (); + String cloudId = cloudConfig.getCloudSiteId(cloudSite); // Check first in the cache of previously authorized clients String cacheKey = cloudId + ":" + tenantId; @@ -989,19 +965,20 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } // Obtain an MSO token for the tenant - CloudIdentity cloudIdentity = cloudSite.getIdentityService (); + CloudIdentity cloudIdentity = cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()); LOGGER.debug("Found: " + cloudIdentity.toString()); - String keystoneUrl = cloudIdentity.getKeystoneUrl (cloudId, msoPropID); + MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType()); + String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity); LOGGER.debug("keystoneUrl=" + keystoneUrl); Keystone keystoneTenantClient = new Keystone (keystoneUrl); Access access = null; try { - Authentication credentials = cloudIdentity.getAuthentication (); + Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity); OpenStackRequest <Access> request = keystoneTenantClient.tokens () .authenticate (credentials).withTenantId (tenantId); - access = executeAndRecordOpenstackRequest (request, msoProps); + access = executeAndRecordOpenstackRequest (request); } catch (OpenStackResponseException e) { if (e.getStatus () == 401) { // Authentication error. @@ -1025,11 +1002,23 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ String region = cloudSite.getRegionId (); String heatUrl = null; 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()); + } heatUrl = KeystoneUtils.findEndpointURL (access.getServiceCatalog (), "orchestration", region, "public"); LOGGER.debug("heatUrl=" + heatUrl + ", region=" + region); } catch (RuntimeException e) { // This comes back for not found (probably an incorrect region ID) - String error = "Orchestration service not found: region=" + region + ",cloud=" + cloudIdentity.getId (); + String error = "AIC did not match an orchestration service for: region=" + region + ",cloud=" + cloudIdentity.getIdentityUrl(); alarmLogger.sendAlarm ("MsoConfigurationError", MsoAlarmLogger.CRITICAL, error); throw new MsoAdapterException (error, e); } @@ -1057,7 +1046,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ * <p> * */ - public static void expireHeatClient (String tenantId, String cloudId) { + public void expireHeatClient (String tenantId, String cloudId) { String cacheKey = cloudId + ":" + tenantId; if (heatClientCache.containsKey (cacheKey)) { heatClientCache.remove (cacheKey); @@ -1090,11 +1079,11 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ */ protected Stack queryHeatStack (Heat heatClient, String stackName) throws MsoException { if (stackName == null) { - return null; + return null; } try { OpenStackRequest <Stack> request = heatClient.getStacks ().byName (stackName); - return executeAndRecordOpenstackRequest (request, msoProps); + return executeAndRecordOpenstackRequest (request); } catch (OpenStackResponseException e) { if (e.getStatus () == 404) { LOGGER.debug ("queryHeatStack - stack not found: " + stackName); @@ -1109,56 +1098,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } } - /* - * 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. - */ - private static class HeatCacheEntry implements Serializable { - - private static final long serialVersionUID = 1L; - - private String heatUrl; - private String token; - private 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); - return heatClient; - } - - public boolean isExpired () { - return expires == null || System.currentTimeMillis() > expires.getTimeInMillis(); - - } - } - - /** - * Clean up the Heat client cache to remove expired entries. - */ - public static void heatCacheCleanup () { - for (String cacheKey : heatClientCache.keySet ()) { - if (heatClientCache.get (cacheKey).isExpired ()) { - heatClientCache.remove (cacheKey); - LOGGER.debug ("Cleaned Up Cached Heat Client for " + cacheKey); - } - } - } - - /** - * Reset the Heat client cache. - * This may be useful if cached credentials get out of sync. - */ - public static void heatCacheReset () { - heatClientCache = new HashMap <> (); - } public Map<String, Object> queryStackForOutputs(String cloudSiteId, String tenantId, String stackName) throws MsoException { @@ -1167,18 +1106,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) { return null; } - Map<String, Object> outputs = heatStack.getOutputs(); - return outputs; - } - - public void queryAndCopyOutputsToInputs(String cloudSiteId, - String tenantId, String stackName, Map<String, String> inputs, - boolean overWrite) throws MsoException { - LOGGER.debug("MsoHeatUtils.queryAndCopyOutputsToInputs"); - Map<String, Object> outputs = this.queryStackForOutputs(cloudSiteId, - tenantId, stackName); - this.copyStringOutputsToInputs(inputs, outputs, overWrite); - return; + return heatStack.getOutputs(); } public void copyStringOutputsToInputs(Map<String, String> inputs, @@ -1356,7 +1284,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ public void copyBaseOutputsToInputs(Map<String, Object> inputs, - Map<String, Object> otherStackOutputs, ArrayList<String> paramNames, HashMap<String, String> aliases) { + Map<String, Object> otherStackOutputs, List<String> paramNames, Map<String, String> aliases) { if (inputs == null || otherStackOutputs == null) return; for (String key : otherStackOutputs.keySet()) { @@ -1389,15 +1317,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ inputs.put(key, obj); } else if (obj instanceof java.util.LinkedHashMap) { LOGGER.debug("\t\t**A java.util.LinkedHashMap **"); - //Object objJson = this.convertObjectToJsonNode(obj.toString()); - //if (objJson == null) { - // LOGGER.debug("\t\tFAILED!! Will just put LinkedHashMap on the inputs"); inputs.put(key, obj); - //} - //else { - // LOGGER.debug("\t\tSuccessfully converted to JsonNode: " + objJson.toString()); - // inputs.put(key, objJson); - //} } else if (obj instanceof java.util.ArrayList) { LOGGER.debug("\t\t**An ArrayList"); inputs.put(key, obj); @@ -1412,22 +1332,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ return; } - public JsonNode convertObjectToJsonNode(Object lhm) { - if (lhm == null) { - return null; - } - JsonNode jsonNode = null; - try { - String jsonString = lhm.toString(); - jsonNode = new ObjectMapper().readTree(jsonString); - } catch (Exception e) { - LOGGER.debug("Unable to convert " + lhm.toString() + " to a JsonNode " + e.getMessage(), e); - jsonNode = null; - } - return jsonNode; - } - - public ArrayList<String> convertCdlToArrayList(String cdl) { + public List<String> convertCdlToArrayList(String cdl) { String cdl2 = cdl.trim(); String cdl3; if (cdl2.startsWith("[") && cdl2.endsWith("]")) { @@ -1435,8 +1340,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } else { cdl3 = cdl2; } - ArrayList<String> list = new ArrayList<>(Arrays.asList(cdl3.split(","))); - return list; + return new ArrayList<>(Arrays.asList(cdl3.split(","))); } /** @@ -1456,7 +1360,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ * @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 HashMap<String, Object> convertInputMap(Map<String, String> inputs, HeatTemplate template) { + public Map<String, Object> convertInputMap(Map<String, String> inputs, HeatTemplate template) { HashMap<String, Object> newInputs = new HashMap<>(); HashMap<String, HeatTemplateParam> params = new HashMap<>(); HashMap<String, HeatTemplateParam> paramAliases = new HashMap<>(); @@ -1546,7 +1450,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } else if ("comma_delimited_list".equalsIgnoreCase(type)) { String commaSeparated = inputs.get(key); try { - ArrayList<String> anArrayList = this.convertCdlToArrayList(commaSeparated); + List<String> anArrayList = this.convertCdlToArrayList(commaSeparated); if (alias) newInputs.put(realName, anArrayList); else @@ -1577,6 +1481,23 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ 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 = cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()); + 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 @@ -1593,7 +1514,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ int timeoutMinutes, boolean backout, String cloudSiteId) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("CREATE STACK REQUEST (formatted for readability)\n"); sb.append("tenant=" + tenantId + ", cloud=" + cloudSiteId); sb.append("{\n"); @@ -1669,7 +1590,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ * Translate the VduPlugin parameters to the corresponding 'createStack' parameters, * and then invoke the existing function. */ - public VduInstance instantiateVdu ( + @Override + public VduInstance instantiateVdu ( CloudInfo cloudInfo, String instanceName, Map<String,Object> inputs, @@ -1715,9 +1637,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ rollbackOnFailure); // Populate a vduInstance from the StackInfo - VduInstance vduInstance = stackInfoToVduInstance(stackInfo); - - return vduInstance; + return stackInfoToVduInstance(stackInfo); } catch (Exception e) { throw new VduException ("MsoHeatUtils (instantiateVDU): createStack Exception", e); @@ -1728,7 +1648,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ /** * VduPlugin interface for query function. */ - public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId) + @Override + public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId) throws VduException { String cloudSiteId = cloudInfo.getCloudSiteId(); @@ -1738,9 +1659,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // Query the Cloudify Deployment object and populate a VduInstance StackInfo stackInfo = queryStack (cloudSiteId, tenantId, instanceId); - VduInstance vduInstance = stackInfoToVduInstance(stackInfo); - - return vduInstance; + return stackInfoToVduInstance(stackInfo); } catch (Exception e) { throw new VduException ("MsoHeatUtile (queryVdu): queryStack Exception ", e); @@ -1751,7 +1670,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ /** * VduPlugin interface for delete function. */ - public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes) + @Override + public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes) throws VduException { String cloudSiteId = cloudInfo.getCloudSiteId(); @@ -1782,7 +1702,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ * Just return a VduException. * */ - public VduInstance updateVdu ( + @Override + public VduInstance updateVdu ( CloudInfo cloudInfo, String instanceId, Map<String,Object> inputs, @@ -1856,5 +1777,14 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ return vduStatus; } + + private void sleep(long time) { + 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/openecomp/mso/openstack/utils/MsoHeatUtilsWithUpdate.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java index 08ae9df4b5..0b3f9dfe17 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtilsWithUpdate.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java @@ -19,27 +19,30 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.openstack.utils; +package org.onap.so.openstack.utils; + +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.openecomp.mso.cloud.CloudConfigFactory; -import org.openecomp.mso.cloud.CloudSite; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.openstack.beans.StackInfo; -import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound; -import org.openecomp.mso.openstack.exceptions.MsoException; -import org.openecomp.mso.openstack.exceptions.MsoOpenstackException; -import org.openecomp.mso.openstack.exceptions.MsoStackNotFound; -import org.openecomp.mso.properties.MsoJavaProperties; -import org.openecomp.mso.properties.MsoPropertiesException; -import org.openecomp.mso.properties.MsoPropertiesFactory; +import org.onap.so.cloud.CloudConfig; +import org.onap.so.cloud.CloudSite; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; +import org.onap.so.openstack.beans.StackInfo; +import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.exceptions.MsoOpenstackException; +import org.onap.so.openstack.exceptions.MsoStackNotFound; +import org.onap.so.openstack.mappers.StackInfoMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.woorea.openstack.base.client.OpenStackBaseException; @@ -49,25 +52,16 @@ import com.woorea.openstack.heat.model.Stack; import com.woorea.openstack.heat.model.Stack.Output; import com.woorea.openstack.heat.model.UpdateStackParam; +@Component public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { private static final String UPDATE_STACK = "UpdateStack"; - private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); - - protected MsoJavaProperties msoProps = null; + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatUtilsWithUpdate.class); private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); - - public MsoHeatUtilsWithUpdate (String msoPropID, MsoPropertiesFactory msoPropertiesFactory, CloudConfigFactory cloudConfFactory) { - super (msoPropID,msoPropertiesFactory,cloudConfFactory); - - try { - msoProps = msoPropertiesFactory.getMsoJavaProperties (msoPropID); - } catch (MsoPropertiesException e) { - LOGGER.error (MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. Mso Properties ID not found in cache: " + msoPropID, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception Mso Properties ID not found in cache: " + msoPropID, e); - } - } + @Autowired + private Environment environment; /* * Keep these methods around for backward compatibility */ @@ -193,7 +187,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { } // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow( + 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) @@ -212,12 +206,19 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { String canonicalName = heatStack.getStackName () + "/" + heatStack.getId (); LOGGER.debug ("Ready to Update Stack (" + canonicalName + ") with input params: " + 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 (stackInputs); + stack.setParameters (normalized); stack.setTemplate (heatTemplate); stack.setDisableRollback (true); // TJM add envt to stack @@ -252,7 +253,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { try { // Execute the actual Openstack command to update the Heat stack OpenStackRequest <Void> request = heatClient.getStacks ().update (canonicalName, stack); - executeAndRecordOpenstackRequest (request, msoProps); + 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. @@ -268,7 +269,7 @@ 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 = msoProps.getIntProperty (createPollIntervalProp, createPollIntervalDefault); + int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault)); int pollTimeout = (timeoutMinutes * 60) + createPollInterval; boolean loopAgain = true; @@ -277,7 +278,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { updateStack = queryHeatStack (heatClient, canonicalName); LOGGER.debug (updateStack.getStackStatus () + " (" + canonicalName + ")"); try { - LOGGER.debug("Current stack " + this.getOutputsAsStringBuilder(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); } @@ -342,10 +343,10 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { LOGGER.debug ("UpdateStack, stack not found"); } } - return new StackInfo (updateStack); + return new StackInfoMapper(updateStack).map(); } - private StringBuilder getOutputsAsStringBuilder(Stack heatStack) { + 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(""); @@ -370,7 +371,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { 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)"); + sb.append(this.convertNodeWithUpdate((JsonNode) obj)).append(" (a JsonNode)"); } else if (obj instanceof java.util.LinkedHashMap) { try { String str = JSON_MAPPER.writeValueAsString(obj); @@ -423,7 +424,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { return sb; } - private String convertNode(final JsonNode node) { + private String convertNodeWithUpdate(final JsonNode node) { try { final Object obj = JSON_MAPPER.treeToValue(node, Object.class); final String json = JSON_MAPPER.writeValueAsString(obj); diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoKeystoneUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java index 1f3c43c79e..d3ec74db8d 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoKeystoneUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java @@ -18,42 +18,45 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.openstack.utils; +package org.onap.so.openstack.utils; import java.io.Serializable; import java.util.Calendar; import java.util.HashMap; import java.util.Map; - import java.util.Optional; -import org.openecomp.mso.cloud.CloudConfigFactory; -import org.openecomp.mso.cloud.CloudIdentity; -import org.openecomp.mso.cloud.CloudSite; -import org.openecomp.mso.logger.MsoAlarmLogger; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.openstack.beans.MsoTenant; -import org.openecomp.mso.openstack.exceptions.MsoAdapterException; -import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound; -import org.openecomp.mso.openstack.exceptions.MsoException; -import org.openecomp.mso.openstack.exceptions.MsoOpenstackException; -import org.openecomp.mso.openstack.exceptions.MsoTenantAlreadyExists; +import org.onap.so.cloud.CloudIdentity; +import org.onap.so.cloud.CloudSite; +import org.onap.so.cloud.authentication.AuthenticationMethodFactory; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoAlarmLogger; +import org.onap.so.logger.MsoLogger; +import org.onap.so.openstack.beans.MsoTenant; +import org.onap.so.openstack.exceptions.MsoAdapterException; +import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.exceptions.MsoOpenstackException; +import org.onap.so.openstack.exceptions.MsoTenantAlreadyExists; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + import com.woorea.openstack.base.client.OpenStackBaseException; import com.woorea.openstack.base.client.OpenStackConnectException; import com.woorea.openstack.base.client.OpenStackRequest; import com.woorea.openstack.base.client.OpenStackResponseException; import com.woorea.openstack.keystone.Keystone; import com.woorea.openstack.keystone.model.Access; +import com.woorea.openstack.keystone.model.Authentication; import com.woorea.openstack.keystone.model.Metadata; import com.woorea.openstack.keystone.model.Role; import com.woorea.openstack.keystone.model.Roles; import com.woorea.openstack.keystone.model.Tenant; import com.woorea.openstack.keystone.model.User; import com.woorea.openstack.keystone.utils.KeystoneUtils; -import com.woorea.openstack.keystone.model.Authentication; +@Component public class MsoKeystoneUtils extends MsoTenantUtils { // Cache the Keystone Clients statically. Since there is just one MSO user, there is no @@ -63,15 +66,19 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // The cache key is "cloudId" private static Map <String, KeystoneCacheEntry> adminClientCache = new HashMap<>(); - private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); - String msoPropID; + private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoKeystoneUtils.class); - public MsoKeystoneUtils(String msoPropID, CloudConfigFactory cloudConfigFactory) { - super(msoPropID, cloudConfigFactory); - this.msoPropID = msoPropID; - LOGGER.debug("MsoKeyStoneUtils:" + msoPropID); - } - + @Autowired + private AuthenticationMethodFactory authenticationMethodFactory; + + @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 @@ -85,7 +92,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { * <p> * * @param tenantName The tenant name to create - * @param cloudSiteId The cloud identifier (may be a region) in which to create the tenant. + * @param cloudId The cloud identifier (may be a region) in which to create the tenant. * @return the tenant ID of the newly created tenant * @throws MsoTenantAlreadyExists Thrown if the requested tenant already exists * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception @@ -95,7 +102,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { Map <String, String> metadata, boolean backout) throws MsoException { // Obtain the cloud site information where we will create the tenant - Optional<CloudSite> cloudSiteOpt = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId); + Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId); if (!cloudSiteOpt.isPresent()) { LOGGER.error(MessageEnum.RA_CREATE_TENANT_ERR, "MSOCloudSite not found", "", "", MsoLogger.ErrorCode.DataError, "MSOCloudSite not found"); throw new MsoCloudSiteNotFound (cloudSiteId); @@ -119,7 +126,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { tenant.setEnabled (true); OpenStackRequest <Tenant> request = keystoneAdminClient.tenants ().create (tenant); - tenant = executeAndRecordOpenstackRequest (request, msoProps); + tenant = executeAndRecordOpenstackRequest (request); } catch (OpenStackBaseException e) { // Convert Keystone OpenStackResponseException to MsoOpenstackException throw keystoneErrorToMsoException (e, "CreateTenant"); @@ -131,15 +138,17 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // Add MSO User to the tenant as a member and // apply tenant metadata if supported by the cloud site try { - CloudIdentity cloudIdentity = cloudSiteOpt.get().getIdentityService (); + CloudIdentity cloudIdentity = cloudConfig.getIdentityService(cloudSiteOpt.get().getIdentityServiceId()); User msoUser = findUserByNameOrId (keystoneAdminClient, cloudIdentity.getMsoId ()); Role memberRole = findRoleByNameOrId (keystoneAdminClient, cloudIdentity.getMemberRole ()); - - OpenStackRequest <Void> request = keystoneAdminClient.tenants ().addUser (tenant.getId (), - msoUser.getId (), - memberRole.getId ()); - executeAndRecordOpenstackRequest (request, msoProps); + + if(msoUser != null && memberRole != null) { + OpenStackRequest <Void> request = keystoneAdminClient.tenants ().addUser (tenant.getId (), + msoUser.getId (), + memberRole.getId ()); + executeAndRecordOpenstackRequest (request); + } if (cloudIdentity.hasTenantMetadata () && metadata != null && !metadata.isEmpty ()) { Metadata tenantMetadata = new Metadata (); @@ -148,7 +157,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { OpenStackRequest <Metadata> metaRequest = keystoneAdminClient.tenants () .createOrUpdateMetadata (tenant.getId (), tenantMetadata); - executeAndRecordOpenstackRequest (metaRequest, msoProps); + executeAndRecordOpenstackRequest (metaRequest); } } catch (Exception e) { // Failed to attach MSO User to the new tenant. Can't operate without access, @@ -161,7 +170,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { { try { OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ()); - executeAndRecordOpenstackRequest (request, msoProps); + executeAndRecordOpenstackRequest (request); } catch (Exception e2) { // Just log this one. We will report the original exception. LOGGER.error (MessageEnum.RA_CREATE_TENANT_ERR, "Nested exception rolling back tenant", "Openstack", "", MsoLogger.ErrorCode.DataError, "Create Tenant error, Nested exception rolling back tenant", e2); @@ -199,7 +208,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { */ public MsoTenant queryTenant (String tenantId, String cloudSiteId) throws MsoException { // Obtain the cloud site information where we will query the tenant - CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow( + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite); @@ -211,10 +220,10 @@ public class MsoKeystoneUtils extends MsoTenantUtils { return null; } - Map <String, String> metadata = new HashMap<>(); - if (cloudSite.getIdentityService ().hasTenantMetadata ()) { + Map <String, String> metadata = new HashMap <String, String> (); + if (cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()).hasTenantMetadata ()) { OpenStackRequest <Metadata> request = keystoneAdminClient.tenants ().showMetadata (tenant.getId ()); - Metadata tenantMetadata = executeAndRecordOpenstackRequest (request, msoProps); + Metadata tenantMetadata = executeAndRecordOpenstackRequest (request); if (tenantMetadata != null) { metadata = tenantMetadata.getMetadata (); } @@ -247,7 +256,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { */ public MsoTenant queryTenantByName (String tenantName, String cloudSiteId) throws MsoException { // Obtain the cloud site information where we will query the tenant - CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow( + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite); @@ -257,10 +266,10 @@ public class MsoKeystoneUtils extends MsoTenantUtils { return null; } - Map <String, String> metadata = new HashMap<>(); - if (cloudSite.getIdentityService ().hasTenantMetadata ()) { + Map <String, String> metadata = new HashMap <String, String> (); + if (cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()).hasTenantMetadata ()) { OpenStackRequest <Metadata> request = keystoneAdminClient.tenants ().showMetadata (tenant.getId ()); - Metadata tenantMetadata = executeAndRecordOpenstackRequest (request, msoProps); + Metadata tenantMetadata = executeAndRecordOpenstackRequest (request); if (tenantMetadata != null) { metadata = tenantMetadata.getMetadata (); } @@ -292,7 +301,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { */ public boolean deleteTenant (String tenantId, String cloudSiteId) throws MsoException { // Obtain the cloud site information where we will query the tenant - CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow( + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite); @@ -305,12 +314,12 @@ public class MsoKeystoneUtils extends MsoTenantUtils { } OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ()); - executeAndRecordOpenstackRequest (request, msoProps); + executeAndRecordOpenstackRequest (request); LOGGER.debug ("Deleted Tenant " + tenant.getId () + " (" + tenant.getName () + ")"); // Clear any cached clients. Not really needed, ID will not be reused. - MsoHeatUtils.expireHeatClient (tenant.getId (), cloudSiteId); - MsoNeutronUtils.expireNeutronClient (tenant.getId (), cloudSiteId); + msoHeatUtils.expireHeatClient (tenant.getId (), cloudSiteId); + msoNeutronUtils.expireNeutronClient (tenant.getId (), cloudSiteId); } catch (OpenStackBaseException e) { // Convert Keystone OpenStackResponseException to MsoOpenstackException throw keystoneErrorToMsoException (e, "Delete Tenant"); @@ -322,6 +331,59 @@ public class MsoKeystoneUtils extends MsoTenantUtils { 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). + * <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. + * <p> + * + * @param tenantName The name of the tenant to delete + * @param cloudSiteId The cloud identifier from which to delete the tenant. + * @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 { + // Obtain the cloud site information where we will query the tenant + Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId); + if (!cloudSite.isPresent()) { + throw new MsoCloudSiteNotFound (cloudSiteId); + } + Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite.get()); + + try { + // Need the Tenant ID to delete (can't directly delete by name) + Tenant tenant = findTenantByName (keystoneAdminClient, tenantName); + if (tenant == null) { + // OK if tenant already doesn't exist. + LOGGER.error(MessageEnum.RA_TENANT_NOT_FOUND, tenantName, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant not found"); + return false; + } + + // Execute the Delete. It has no return value. + OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ()); + executeAndRecordOpenstackRequest (request); + + LOGGER.debug ("Deleted Tenant " + tenant.getId () + " (" + tenant.getName () + ")"); + + // Clear any cached clients. Not really needed, ID will not be reused. + msoHeatUtils.expireHeatClient (tenant.getId (), cloudSiteId); + msoNeutronUtils.expireNeutronClient (tenant.getId (), cloudSiteId); + } 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"); + } catch (RuntimeException e) { + // Catch-all + throw runtimeExceptionToMsoException (e, "DeleteTenant"); + } + + return true; + } + // ------------------------------------------------------------------- // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS @@ -339,7 +401,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { * @return an authenticated Keystone object */ public Keystone getKeystoneAdminClient (CloudSite cloudSite) throws MsoException { - CloudIdentity cloudIdentity = cloudSite.getIdentityService (); + CloudIdentity cloudIdentity = cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()); String cloudId = cloudIdentity.getId (); String adminTenantName = cloudIdentity.getAdminTenant (); @@ -355,18 +417,19 @@ public class MsoKeystoneUtils extends MsoTenantUtils { adminClientCache.remove (cloudId); } } - - Keystone keystone = new Keystone (cloudIdentity.getKeystoneUrl (region, msoPropID)); + MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType()); + final String keystoneUrl = tenantUtils.getKeystoneUrl(region, cloudIdentity); + Keystone keystone = new Keystone(keystoneUrl); // Must authenticate against the 'admin' tenant to get the services endpoints Access access = null; String token = null; try { - Authentication credentials = cloudIdentity.getAuthentication (); + Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity); OpenStackRequest <Access> request = keystone.tokens () .authenticate (credentials) .withTenantName (adminTenantName); - access = executeAndRecordOpenstackRequest (request, msoProps); + access = executeAndRecordOpenstackRequest (request); token = access.getToken ().getId (); } catch (OpenStackResponseException e) { if (e.getStatus () == 401) { @@ -408,6 +471,29 @@ public class MsoKeystoneUtils extends MsoTenantUtils { } /* + * 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 + * + * @param tenantName the tenant name or ID to query + * + * @return a Tenant object or null if not found + */ + public Tenant findTenantByNameOrId (Keystone adminClient, String tenantNameOrId) { + if (tenantNameOrId == null) { + return null; + } + + Tenant tenant = findTenantById (adminClient, tenantNameOrId); + if (tenant == null) { + tenant = findTenantByName (adminClient, tenantNameOrId); + } + + return tenant; + } + + /* * Find a tenant (or query its existance) by its Id. * * @param adminClient an authenticated Keystone object @@ -423,7 +509,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { try { OpenStackRequest <Tenant> request = adminClient.tenants ().show (tenantId); - return executeAndRecordOpenstackRequest (request, msoProps); + return executeAndRecordOpenstackRequest (request); } catch (OpenStackResponseException e) { if (e.getStatus () == 404) { return null; @@ -451,7 +537,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { try { OpenStackRequest <Tenant> request = adminClient.tenants ().show ("").queryParam ("name", tenantName); - return executeAndRecordOpenstackRequest (request, msoProps); + return executeAndRecordOpenstackRequest (request); } catch (OpenStackResponseException e) { if (e.getStatus () == 404) { return null; @@ -479,7 +565,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { try { OpenStackRequest <User> request = adminClient.users ().show (userNameOrId); - return executeAndRecordOpenstackRequest (request, msoProps); + return executeAndRecordOpenstackRequest (request); } catch (OpenStackResponseException e) { if (e.getStatus () == 404) { // Not found by ID. Search for name @@ -508,7 +594,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { try { OpenStackRequest <User> request = adminClient.users ().show ("").queryParam ("name", userName); - return executeAndRecordOpenstackRequest (request, msoProps); + return executeAndRecordOpenstackRequest (request); } catch (OpenStackResponseException e) { if (e.getStatus () == 404) { return null; @@ -539,7 +625,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // Search by name or ID. Must search in list OpenStackRequest <Roles> request = adminClient.roles ().list (); - Roles roles = executeAndRecordOpenstackRequest (request, msoProps); + Roles roles = executeAndRecordOpenstackRequest (request); for (Role role : roles) { if (roleNameOrId.equals (role.getName ()) || roleNameOrId.equals (role.getId ())) { @@ -573,32 +659,11 @@ public class MsoKeystoneUtils extends MsoTenantUtils { public boolean isExpired () { // adding arbitrary guard timer of 5 minutes return expires == null || System.currentTimeMillis() > (expires.getTimeInMillis() - 300000); - - } - } - - /** - * Clean up the Admin client cache to remove expired entries. - */ - public static void adminCacheCleanup () { - for (String cacheKey : adminClientCache.keySet ()) { - if (adminClientCache.get (cacheKey).isExpired ()) { - adminClientCache.remove (cacheKey); - LOGGER.debug ("Cleaned Up Cached Admin Client for " + cacheKey); - } } } - /** - * Reset the Admin client cache. - * This may be useful if cached credentials get out of sync. - */ - public static void adminCacheReset () { - adminClientCache = new HashMap<>(); - } - @Override - public String getKeystoneUrl(String regionId, String msoPropID, CloudIdentity cloudIdentity) { + public String getKeystoneUrl(String regionId, CloudIdentity cloudIdentity) throws MsoException { return cloudIdentity.getIdentityUrl(); } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoNeutronUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java index df769ec0c2..adeb008ad5 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoNeutronUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,44 +18,49 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.openstack.utils; +package org.onap.so.openstack.utils; -import java.io.Serializable; import java.util.ArrayList; -import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.openecomp.mso.cloud.CloudConfig; -import org.openecomp.mso.cloud.CloudConfigFactory; -import org.openecomp.mso.cloud.CloudIdentity; -import org.openecomp.mso.cloud.CloudSite; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoAlarmLogger; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.openstack.beans.NetworkInfo; -import org.openecomp.mso.openstack.exceptions.MsoAdapterException; -import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound; -import org.openecomp.mso.openstack.exceptions.MsoException; -import org.openecomp.mso.openstack.exceptions.MsoIOException; -import org.openecomp.mso.openstack.exceptions.MsoNetworkAlreadyExists; -import org.openecomp.mso.openstack.exceptions.MsoNetworkNotFound; -import org.openecomp.mso.openstack.exceptions.MsoOpenstackException; +import org.onap.so.cloud.CloudConfig; +import org.onap.so.cloud.CloudIdentity; +import org.onap.so.cloud.CloudSite; +import org.onap.so.cloud.authentication.AuthenticationMethodFactory; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoAlarmLogger; +import org.onap.so.logger.MsoLogger; +import org.onap.so.openstack.beans.NetworkInfo; +import org.onap.so.openstack.beans.NeutronCacheEntry; +import org.onap.so.openstack.exceptions.MsoAdapterException; +import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.exceptions.MsoIOException; +import org.onap.so.openstack.exceptions.MsoNetworkAlreadyExists; +import org.onap.so.openstack.exceptions.MsoNetworkNotFound; +import org.onap.so.openstack.exceptions.MsoOpenstackException; +import org.onap.so.openstack.exceptions.MsoTenantNotFound; +import org.onap.so.openstack.mappers.NetworkInfoMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + import com.woorea.openstack.base.client.OpenStackBaseException; import com.woorea.openstack.base.client.OpenStackConnectException; import com.woorea.openstack.base.client.OpenStackRequest; import com.woorea.openstack.base.client.OpenStackResponseException; import com.woorea.openstack.keystone.Keystone; import com.woorea.openstack.keystone.model.Access; +import com.woorea.openstack.keystone.model.Authentication; import com.woorea.openstack.keystone.utils.KeystoneUtils; import com.woorea.openstack.quantum.Quantum; import com.woorea.openstack.quantum.model.Network; import com.woorea.openstack.quantum.model.Networks; import com.woorea.openstack.quantum.model.Segment; -import com.woorea.openstack.keystone.model.Authentication; +@Component public class MsoNeutronUtils extends MsoCommonUtils { // Cache Neutron Clients statically. Since there is just one MSO user, there is no @@ -65,24 +70,22 @@ public class MsoNeutronUtils extends MsoCommonUtils // The cache key is "tenantId:cloudId" private static Map<String,NeutronCacheEntry> neutronClientCache = new HashMap<>(); - private CloudConfigFactory cloudConfigFactory; - - private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); - private String msoPropID; + // Fetch cloud configuration each time (may be cached in CloudConfig class) + @Autowired + private CloudConfig cloudConfig; + @Autowired + private AuthenticationMethodFactory authenticationMethodFactory; + + @Autowired + private MsoTenantUtilsFactory tenantUtilsFactory; + + private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoNeutronUtils.class); + public enum NetworkType { BASIC, PROVIDER, MULTI_PROVIDER }; - public MsoNeutronUtils(String msoPropID, CloudConfigFactory cloudConfigFactory) { - this.cloudConfigFactory = cloudConfigFactory; - this.msoPropID = msoPropID; - } - - protected CloudConfigFactory getCloudConfigFactory() { - return cloudConfigFactory; - } - /** * Create a network with the specified parameters in the given cloud/tenant. * @@ -104,7 +107,7 @@ public class MsoNeutronUtils extends MsoCommonUtils throws MsoException { // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow( + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); Quantum neutronClient = getNeutronClient (cloudSite, tenantId); @@ -148,7 +151,7 @@ public class MsoNeutronUtils extends MsoCommonUtils try { OpenStackRequest<Network> request = neutronClient.networks().create(network); Network newNetwork = executeAndRecordOpenstackRequest(request); - return new NetworkInfo(newNetwork); + return new NetworkInfoMapper(newNetwork).map(); } catch (OpenStackBaseException e) { // Convert Neutron exception to an MsoOpenstackException @@ -182,10 +185,11 @@ public class MsoNeutronUtils extends MsoCommonUtils LOGGER.debug("In queryNetwork"); // Obtain the cloud site information - CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow( + 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); @@ -193,7 +197,7 @@ public class MsoNeutronUtils extends MsoCommonUtils LOGGER.debug ("Query Network: " + networkNameOrId + " not found in tenant " + tenantId); return null; } - return new NetworkInfo(network); + return new NetworkInfoMapper(network).map(); } catch (OpenStackBaseException e) { // Convert Neutron exception to an MsoOpenstackException @@ -222,9 +226,10 @@ public class MsoNeutronUtils extends MsoCommonUtils public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException { // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow( + 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); @@ -279,9 +284,10 @@ public class MsoNeutronUtils extends MsoCommonUtils throws MsoException { // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = getCloudConfigFactory().getCloudConfig().getCloudSite(cloudSiteId).orElseThrow( + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); Quantum neutronClient = getNeutronClient (cloudSite, tenantId); + // Check that the network exists Network network = findNetworkById (neutronClient, networkId); @@ -316,7 +322,7 @@ public class MsoNeutronUtils extends MsoCommonUtils try { OpenStackRequest<Network> request = neutronClient.networks().update(network); Network newNetwork = executeAndRecordOpenstackRequest(request); - return new NetworkInfo(newNetwork); + return new NetworkInfoMapper(newNetwork).map(); } catch (OpenStackBaseException e) { // Convert Neutron exception to an MsoOpenstackException @@ -357,7 +363,9 @@ public class MsoNeutronUtils extends MsoCommonUtils if (neutronClientCache.containsKey(cacheKey)) { if (! neutronClientCache.get(cacheKey).isExpired()) { LOGGER.debug ("Using Cached HEAT Client for " + cacheKey); - Quantum neutronClient = neutronClientCache.get(cacheKey).getNeutronClient(); + NeutronCacheEntry cacheEntry = neutronClientCache.get(cacheKey); + Quantum neutronClient = new Quantum(cacheEntry.getNeutronUrl()); + neutronClient.token(cacheEntry.getToken()); return neutronClient; } else { @@ -368,11 +376,13 @@ public class MsoNeutronUtils extends MsoCommonUtils } // Obtain an MSO token for the tenant from the identity service - CloudIdentity cloudIdentity = cloudSite.getIdentityService(); - Keystone keystoneTenantClient = new Keystone (cloudIdentity.getKeystoneUrl(cloudId, msoPropID)); + CloudIdentity cloudIdentity = cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()); + MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType()); + final String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity); + Keystone keystoneTenantClient = new Keystone(keystoneUrl); Access access = null; try { - Authentication credentials = cloudIdentity.getAuthentication (); + Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity); OpenStackRequest<Access> request = keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId); access = executeAndRecordOpenstackRequest(request); } @@ -428,8 +438,11 @@ public class MsoNeutronUtils extends MsoCommonUtils * the KeystoneClient in case where a tenant is deleted. In that case, * all cached credentials must be purged so that fresh authentication is * done on subsequent calls. + * <p> + * @param tenantName + * @param cloudId */ - public static void expireNeutronClient (String tenantId, String cloudId) { + public void expireNeutronClient (String tenantId, String cloudId) { String cacheKey = cloudId + ":" + tenantId; if (neutronClientCache.containsKey(cacheKey)) { neutronClientCache.remove(cacheKey); @@ -468,7 +481,7 @@ public class MsoNeutronUtils extends MsoCommonUtils * @param networkId the network ID to query * @return a Network object or null if not found */ - private static Network findNetworkById (Quantum neutronClient, String networkId) + private Network findNetworkById (Quantum neutronClient, String networkId) { if (networkId == null) { return null; @@ -534,55 +547,4 @@ public class MsoNeutronUtils extends MsoCommonUtils } } } - - - /* - * 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. - */ - private static class NeutronCacheEntry implements Serializable - { - private static final long serialVersionUID = 1L; - - 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 Quantum getNeutronClient () { - Quantum neutronClient = new Quantum(neutronUrl); - neutronClient.token(token); - return neutronClient; - } - - public boolean isExpired() { - return expires == null || System.currentTimeMillis() > expires.getTimeInMillis(); - } - } - - /** - * Clean up the Neutron client cache to remove expired entries. - */ - public static void neutronCacheCleanup () { - for (String cacheKey : neutronClientCache.keySet()) { - if (neutronClientCache.get(cacheKey).isExpired()) { - neutronClientCache.remove(cacheKey); - LOGGER.debug ("Cleaned Up Cached Neutron Client for " + cacheKey); - } - } - } - - /** - * Reset the Neutron client cache. - * This may be useful if cached credentials get out of sync. - */ - public static void neutronCacheReset () { - neutronClientCache = new HashMap<>(); - } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java index 964babd1e0..28911bc45c 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java @@ -18,44 +18,27 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.openstack.utils; +package org.onap.so.openstack.utils; import java.util.Map; -import org.openecomp.mso.cloud.CloudConfigFactory; -import org.openecomp.mso.cloud.CloudIdentity; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.openstack.beans.MsoTenant; -import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound; -import org.openecomp.mso.openstack.exceptions.MsoException; -import org.openecomp.mso.properties.MsoJavaProperties; -import org.openecomp.mso.properties.MsoPropertiesException; -import org.openecomp.mso.properties.MsoPropertiesFactory; -public abstract class MsoTenantUtils extends MsoCommonUtils { - - private CloudConfigFactory cloudConfigFactory; - protected MsoPropertiesFactory msoPropFactory; - protected static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); - protected MsoJavaProperties msoProps; +import org.onap.so.cloud.CloudConfig; +import org.onap.so.cloud.CloudIdentity; +import org.onap.so.logger.MsoLogger; +import org.onap.so.openstack.beans.MsoTenant; +import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; +import org.onap.so.openstack.exceptions.MsoException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; - public MsoTenantUtils (String msoPropID, CloudConfigFactory cloudConfigFactory) { - this.cloudConfigFactory = cloudConfigFactory; - msoPropFactory = new MsoPropertiesFactory(); - - LOGGER.debug("msoTenantUtils:" + msoPropID); - - try { - msoProps = msoPropFactory.getMsoJavaProperties (msoPropID); - } catch (MsoPropertiesException e) { - LOGGER.error (MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. Mso Properties ID not found in cache: " + msoPropID, "", "", MsoLogger.ErrorCode.DataError, "Exception - Mso Properties ID not found in cache", e); - } - } +@Component +public abstract class MsoTenantUtils extends MsoCommonUtils { - public CloudConfigFactory getCloudConfigFactory() { - return cloudConfigFactory; - } + protected static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoTenantUtils.class); + + @Autowired + protected CloudConfig cloudConfig; public abstract String createTenant (String tenantName, String cloudSiteId, Map <String, String> metadata, boolean backout) throws MsoException; @@ -69,7 +52,7 @@ public abstract class MsoTenantUtils extends MsoCommonUtils { public abstract boolean deleteTenant (String tenantId, String cloudSiteId) throws MsoException; - public abstract String getKeystoneUrl (String regionId, String msoPropID, CloudIdentity cloudIdentity) + 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 new file mode 100644 index 0000000000..68d0ef2fad --- /dev/null +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.openstack.utils; + +import org.onap.so.cloud.CloudConfig; +import org.onap.so.cloud.CloudSite; +import org.onap.so.cloud.ServerType; +import org.onap.so.logger.MsoLogger; +import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class MsoTenantUtilsFactory { + + protected static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, MsoTenantUtilsFactory.class); + @Autowired + protected CloudConfig cloudConfig; + @Autowired + protected MsoKeystoneUtils keystoneUtils; + + // 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(cloudConfig.getIdentityService(cloudSite.getIdentityServiceId()).getIdentityServerType()); + } + + public MsoTenantUtils getTenantUtilsByServerType(ServerType serverType) { + + MsoTenantUtils tenantU = null; + if (ServerType.KEYSTONE.equals(serverType)) { + tenantU = keystoneUtils; + } + return tenantU; + } +} diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoYamlEditorWithEnvt.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java index 8704911e26..649eb6b07c 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoYamlEditorWithEnvt.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java @@ -19,7 +19,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.openstack.utils; +package org.onap.so.openstack.utils; @@ -29,18 +29,18 @@ import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; -import java.util.Set; import java.util.Map.Entry; -import org.openecomp.mso.db.catalog.beans.HeatTemplateParam; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Set; +import org.onap.so.db.catalog.beans.HeatTemplateParam; +import org.onap.so.logger.MsoLogger; import org.yaml.snakeyaml.Yaml; -import org.openecomp.mso.logger.MsoLogger; +import com.fasterxml.jackson.databind.ObjectMapper; public class MsoYamlEditorWithEnvt { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoYamlEditorWithEnvt.class); private Map <String, Object> yml; private Yaml yaml = new Yaml (); diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/CloudInfo.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/CloudInfo.java deleted file mode 100644 index 035524510e..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/CloudInfo.java +++ /dev/null @@ -1,69 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.mso.adapters.vdu;
-
-/**
- * Cloud information structure for deploying/managing a VDU. Includes the cloud site
- * as well as tenant information within the site. Currently this is defined as a
- * cloud site ID. which would map to a CloudConfig entry.
- * Perhaps the CloudConfig entry itself should be provided, instead of requiring each
- * plug-in to query it.
- *
- * The meaning of 'tenant' may differ by cloud provider, but every cloud supports some
- * sort of tenant partitioning.
- *
- */
-public class CloudInfo {
-
- private String cloudSiteId;
- private String tenantId;
- private String tenantName;//bpmn query and pass
-
- public CloudInfo() {
- }
-
- public CloudInfo (String cloudSiteId, String tenantId, String tenantName) {
- this.cloudSiteId = cloudSiteId;
- this.tenantId = tenantId;
- this.tenantName = tenantName;
- }
-
- public String getCloudSiteId() {
- return cloudSiteId;
- }
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
- public String getTenantId() {
- return tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getTenantName() {
- return tenantName;
- }
- public void setTenantName(String tenantName) {
- this.tenantName = tenantName;
- }
-
-
-}
\ No newline at end of file diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/PluginAction.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/PluginAction.java deleted file mode 100644 index 1f3cf2f113..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/PluginAction.java +++ /dev/null @@ -1,63 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.mso.adapters.vdu;
-
-/**
- * Java beam representing a detailed action performed within a plugin during VDU
- * orchestration. This allows the plugin to convey more detailed information about
- * recent activities it has performed. It is primarily intended for logging and
- * troubleshooting, so plugins are free to populate this as desired.
- */
-public class PluginAction {
-
- private String action;
- private String status;
- private String rawMessage;
-
- public PluginAction () {
- }
-
- public PluginAction (String action, String status, String rawMessage) {
- this.action = action;
- this.status = status;
- this.rawMessage = rawMessage;
- }
-
- public String getAction() {
- return action;
- }
- public void setAction(String action) {
- this.action = action;
- }
- public String getStatus() {
- return status;
- }
- public void setStatus(String status) {
- this.status = status;
- }
- public String getRawMessage() {
- return rawMessage;
- }
- public void setRawMessage(String rawMessage) {
- this.rawMessage = rawMessage;
- }
-
-}
\ No newline at end of file diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduArtifact.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduArtifact.java deleted file mode 100644 index 7696f3bc24..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduArtifact.java +++ /dev/null @@ -1,80 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.mso.adapters.vdu;
-
-import java.util.Arrays;
-import java.util.Objects;
-
-public class VduArtifact {
-
- // Enumerate the types of artifacts permitted. This may need to be a variable string
- // value if arbitrary (cloud-specific) artifacts may be attached to VDUs in ASDC.
- public enum ArtifactType {
- MAIN_TEMPLATE, NESTED_TEMPLATE, CONFIG_FILE, SCRIPT_FILE, TEXT_FILE, ENVIRONMENT
- }
-
- private String name;
- private byte[] content;
- private ArtifactType type;
-
- // Default constructor
- public VduArtifact() {}
-
- // Fully specified constructor
- public VduArtifact (String name, byte[] content, ArtifactType type) {
- this.name = name;
- this.content = content;
- this.type = type;
- }
-
- public String getName() {
- return name;
- }
- public void setName (String name) {
- this.name = name;
- }
- public byte[] getContent() {
- return content;
- }
- public void setContent(byte[] content) {
- this.content = content;
- }
- public ArtifactType getType() {
- return type;
- }
- public void setType(ArtifactType type) {
- this.type = type;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- VduArtifact that = (VduArtifact) o;
- return Objects.equals(name, that.name) &&
- Arrays.equals(content, that.content) &&
- type == that.type;
- }
-}
\ No newline at end of file diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduException.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduException.java deleted file mode 100644 index 3fd1d2ec8a..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduException.java +++ /dev/null @@ -1,60 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * OPENECOMP - MSO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.mso.adapters.vdu;
-
-import org.openecomp.mso.openstack.exceptions.MsoException;
-import org.openecomp.mso.openstack.exceptions.MsoExceptionCategory;
-
-/**
- * OpenStack exception.
- */
-public class VduException extends MsoException
-{
-
- /**
- * Serialization id.
- */
- private static final long serialVersionUID = 3313636124141766495L;
-
- /**
- * Constructor to create a new VduException instance
- * @param detail error details
- */
- public VduException (String detail) {
- // Set the detailed error as the Exception 'message'
- super(detail);
- // TODO: Need a more generic category than OPENSTACK
- super.category = MsoExceptionCategory.OPENSTACK;
- }
-
- /**
- * Constructor to create a new VduException instance
- * @param detail error details
- * @param e the cause
- */
- public VduException (String detail, Exception e) {
- // Set the detailed error as the Exception 'message'
- super(detail, e);
- // TODO: Need a more generic category than OPENSTACK
- super.category = MsoExceptionCategory.OPENSTACK;
- }
-
-}
\ No newline at end of file diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduInstance.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduInstance.java deleted file mode 100644 index 5a5a6ab3d2..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduInstance.java +++ /dev/null @@ -1,80 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * OPENECOMP - MSO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.mso.adapters.vdu;
-
-import java.util.Map;
-import java.util.HashMap;
-
-/*
- * This Java bean class relays VDU status information in a cloud-agnostic format.
- *
- * This bean is returned by all implementors of the VduPlugin interface operations
- * (instantiate, query, delete).
- */
-
-public class VduInstance {
- // Set defaults for everything
- protected String vduInstanceId;
- protected String vduInstanceName;
- protected VduStatus status;
- protected Map<String, Object> outputs = new HashMap<>();
- protected Map<String, Object> inputs = new HashMap<>();
-
- public String getVduInstanceId() {
- return vduInstanceId;
- }
-
- public void setVduInstanceId(String vduInstanceId) {
- this.vduInstanceId = vduInstanceId;
- }
-
- public String getVduInstanceName() {
- return vduInstanceName;
- }
-
- public void setVduInstanceName(String vduInstanceName) {
- this.vduInstanceName = vduInstanceName;
- }
-
- public VduStatus getStatus() {
- return status;
- }
-
- public void setStatus(VduStatus status) {
- this.status = status;
- }
-
- public Map<String, Object> getOutputs() {
- return outputs;
- }
-
- public void setOutputs(Map<String, Object> outputs) {
- this.outputs = outputs;
- }
-
- public Map<String, Object> getInputs() {
- return inputs;
- }
-
- public void setInputs(Map<String, Object> inputs) {
- this.inputs = inputs;
- }
-}
\ No newline at end of file diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduModelInfo.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduModelInfo.java deleted file mode 100644 index 3cef29255f..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduModelInfo.java +++ /dev/null @@ -1,50 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.mso.adapters.vdu;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class VduModelInfo {
- private String modelCustomizationUUID;
- private int timeoutMinutes;
- private List<VduArtifact> artifacts = new ArrayList<>();
-
- public String getModelCustomizationUUID() {
- return modelCustomizationUUID;
- }
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
- public int getTimeoutMinutes() {
- return timeoutMinutes;
- }
- public void setTimeoutMinutes(int timeoutMinutes) {
- this.timeoutMinutes = timeoutMinutes;
- }
- public List<VduArtifact> getArtifacts() {
- return artifacts;
- }
- public void setArtifacts(List<VduArtifact> artifacts) {
- this.artifacts = artifacts;
- }
-
-}
\ No newline at end of file diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduStatus.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduStatus.java deleted file mode 100644 index 4d9702f726..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/adapters/vdu/VduStatus.java +++ /dev/null @@ -1,58 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.mso.adapters.vdu;
-
-public class VduStatus {
-
- private VduStateType state;
- private String errorMessage;
- private PluginAction lastAction;
-
- public VduStatus(){}
- public VduStatus( VduStateType state) {
- this.state = state;
- }
- public VduStateType getState() {
- return state;
- }
- public void setState(VduStateType state) {
- this.state = state;
- }
- public String getErrorMessage() {
- return errorMessage;
- }
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
- public PluginAction getLastAction() {
- return lastAction;
- }
- public void setLastAction(PluginAction lastAction) {
- this.lastAction = lastAction;
- }
- public void setLastAction (String action, String status, String rawCloudMessage) {
- lastAction = new PluginAction();
- lastAction.setAction (action);
- lastAction.setStatus (status);
- lastAction.setRawMessage(rawCloudMessage);
- }
-
-}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/aria/AriaVduPlugin.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/aria/AriaVduPlugin.java deleted file mode 100644 index 1c2057df4d..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/aria/AriaVduPlugin.java +++ /dev/null @@ -1,340 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.openecomp.mso.aria; - -import com.gigaspaces.aria.rest.client.AriaClient; -import com.gigaspaces.aria.rest.client.AriaClientFactory; -import com.gigaspaces.aria.rest.client.ExecutionDetails; -import com.gigaspaces.aria.rest.client.Input; -import com.gigaspaces.aria.rest.client.InputImpl; -import com.gigaspaces.aria.rest.client.Output; -import com.gigaspaces.aria.rest.client.Service; -import com.gigaspaces.aria.rest.client.ServiceTemplate; -import com.gigaspaces.aria.rest.client.ServiceTemplateImpl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.openecomp.mso.adapters.vdu.CloudInfo; -import org.openecomp.mso.adapters.vdu.VduException; -import org.openecomp.mso.adapters.vdu.VduInstance; -import org.openecomp.mso.adapters.vdu.VduModelInfo; -import org.openecomp.mso.adapters.vdu.VduPlugin; -import org.openecomp.mso.adapters.vdu.VduStateType; -import org.openecomp.mso.adapters.vdu.VduStatus; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; - -/** - * ARIA VDU Plugin. Pluggable interface for the ARIA REST API to support TOSCA orchestration. - * - * @author DeWayne - */ -public class AriaVduPlugin implements VduPlugin { - private static final String API_VERSION = "0.1"; - private static final MsoLogger logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); - private AriaClient client = null; - private Map<String, Integer> templateIds = new HashMap<>(); - private Map<String, Integer> serviceIds = new HashMap<>(); - private Map<String, Map<String, Object>> inputsCache = new HashMap<>(); - - public AriaVduPlugin() { - super(); - } - - public AriaVduPlugin(String host, int port) { - try { - client = new AriaClientFactory().createRestClient("http", host, port, API_VERSION); - } catch (Exception e) { - logger.error( - MessageEnum.RA_CREATE_VNF_ERR, - "", - "", - "", - "", - "aria", - MsoLogger.ErrorCode.AvailabilityError, - "Connection to ARIA REST API failed", - e); - throw e; - } - } - - /** - * Instantiate VDU in ARIA. <code>instanceName</code> is used for both service template name and - * service name. - */ - @SuppressWarnings("unchecked") - @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(); - - // Currently only support simple CSAR with single main template - byte[] csar = new CSAR(vduModel).create(); - - ServiceTemplate template = new ServiceTemplateImpl(instanceName, csar); - try { - client.install_service_template(template); - } catch (Exception e) { - logger.error( - MessageEnum.RA_CREATE_VNF_ERR, - "", - "", - "", - "", - instanceName, - MsoLogger.ErrorCode.BusinessProcesssError, - "instantiate vdu via csar failed", - e); - throw new VduException(e.getMessage()); - } - - /** Create a service */ - try { - int templateId = -1; - for (ServiceTemplate stemplate : - (List<ServiceTemplate>) client.list_service_templates()) { - if (stemplate.getName().equals(instanceName)) { - templateId = stemplate.getId(); - } - } - List<Input> sinputs = new ArrayList<>(); - for (Map.Entry<String, ? extends Object> entry : inputs.entrySet()) { - Input inp = new InputImpl(entry.getKey(), entry.getValue().toString(), ""); - sinputs.add(inp); - } - client.create_service(templateId, instanceName, sinputs); - } catch (Exception e) { - logger.error( - MessageEnum.RA_CREATE_VNF_ERR, - "", - "", - "", - "", - instanceName, - MsoLogger.ErrorCode.BusinessProcesssError, - "aria service creation failed", - e); - throw new VduException(e.getMessage()); - } - - // Get the service ID and cache it - int sid = getServiceId(instanceName); - serviceIds.put(instanceName, sid); - - /** Run install */ - try { - client.start_execution(sid, "install", new ExecutionDetails()); - } catch (Exception e) { - logger.error( - MessageEnum.RA_CREATE_VNF_ERR, - "", - "", - "", - "", - instanceName, - MsoLogger.ErrorCode.BusinessProcesssError, - "aria install workflow failed", - e); - throw new VduException(e.getMessage()); - } - - /** Get the outputs and return */ - try { - Map<String, Object> voutputs = getOutputs(sid); - - VduInstance vi = new VduInstance(); - vi.setVduInstanceName(instanceName); - vi.setInputs((Map<String, Object>) inputs); - inputsCache.put(instanceName, vi.getInputs()); - vi.setOutputs(voutputs); - vi.setStatus(new VduStatus(VduStateType.INSTANTIATED)); - return vi; - } catch (Exception e) { - logger.error( - MessageEnum.RA_CREATE_VNF_ERR, - "", - "", - "", - "", - instanceName, - MsoLogger.ErrorCode.BusinessProcesssError, - "aria service output fetch failed", - e); - throw new VduException(e.getMessage()); - } - } - - /** - * Queries ARIA for VDU status. instanceId used as template and service name in ARIA (by - * convention). - */ - @Override - public VduInstance queryVdu(CloudInfo cloudInfo, String instanceId) throws VduException { - if (client == null) { - throw new VduException("Internal error: no ARIA connection found"); - } - - VduInstance vif = new VduInstance(); - vif.setVduInstanceId(instanceId); - Integer sid = serviceIds.get(instanceId); - if (sid == null) { - // service doesn't exist - vif.setStatus(new VduStatus(VduStateType.NOTFOUND)); - return vif; - } - Service service = client.get_service(sid); - if (service == null) { - throw new VduException( - String.format("Internal error: cached service id %s not found in ARIA", sid)); - } - Map<String, Object> voutputs = getOutputs(sid); - vif.setOutputs(voutputs); - vif.setInputs(inputsCache.get(instanceId)); - vif.setStatus(new VduStatus(VduStateType.INSTANTIATED)); - return vif; - } - - @Override - public VduInstance deleteVdu(CloudInfo cloudInfo, String instanceId, int timeoutMinutes) - throws VduException { - VduInstance vif = new VduInstance(); - vif.setVduInstanceId(instanceId); - - if (client == null) { - throw new VduException("Internal error: no ARIA connection found"); - } - Integer sid = serviceIds.get(instanceId); - if (sid == null) { - // service doesn't exist - vif.setStatus(new VduStatus(VduStateType.NOTFOUND)); - return vif; - } - - /** Run uninstall */ - try { - client.start_execution(sid, "uninstall", new ExecutionDetails()); - } catch (Exception e) { - logger.error( - MessageEnum.RA_CREATE_VNF_ERR, - "", - "", - "", - "", - instanceId, - MsoLogger.ErrorCode.BusinessProcesssError, - "aria uninstall workflow failed", - e); - throw new VduException(e.getMessage()); - } - - /** Delete the service */ - try { - client.delete_service(sid); - } catch (Exception e) { - logger.error( - MessageEnum.RA_CREATE_VNF_ERR, - "", - "", - "", - "", - instanceId, - MsoLogger.ErrorCode.BusinessProcesssError, - String.format("aria service delete failed. Service id: %d", sid), - e); - throw new VduException(e.getMessage()); - } - - /** Delete the blueprint */ - try { - client.delete_service_template(templateIds.get(instanceId)); - } catch (Exception e) { - logger.error( - MessageEnum.RA_CREATE_VNF_ERR, - "", - "", - "", - "", - instanceId, - MsoLogger.ErrorCode.BusinessProcesssError, - "aria template delete failed", - e); - throw new VduException(e.getMessage()); - } - - vif.setStatus(new VduStatus(VduStateType.DELETED)); - return vif; - } - - /** Deployment update not possible with ARIA */ - @Override - public VduInstance updateVdu( - CloudInfo cloudInfo, - String instanceId, - Map<String, Object> inputs, - VduModelInfo vduModel, - boolean rollbackOnFailure) - throws VduException { - throw new VduException("NOT IMPLEMENTED"); - } - - /** Private */ - - /** - * p Gets and repacks service outputs for internal use - * - * @param sid the service id (ARIA service id) - * @return - */ - private Map<String, Object> getOutputs(int sid) { - @SuppressWarnings("unchecked") - List<Output> outputs = (List<Output>) client.list_service_outputs(sid); - Map<String, Object> voutputs = new HashMap<>(); - for (Output output : outputs) { - voutputs.put(output.getName(), output.getValue()); - } - return voutputs; - } - - @SuppressWarnings("unchecked") - private int getServiceId(String service_name) throws VduException { - int sid = -1; - List<Service> services = (List<Service>) client.list_services(); - for (Service service : services) { - if (service.getName().equals(service_name)) { - sid = service.getId(); - } - } - if (sid == -1) { - throw new VduException( - String.format( - "Internal error: just created service not found: %s", service_name)); - } - return sid; - } -} diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/aria/CSAR.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/aria/CSAR.java deleted file mode 100644 index bb1201fba3..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/aria/CSAR.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * ============LICENSE_START=================================================== - * Copyright (c) 2017 Cloudify.co. All rights reserved. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - * ============LICENSE_END==================================================== -*/ -package org.openecomp.mso.aria; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.Map; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import org.openecomp.mso.adapters.vdu.VduModelInfo; -import org.openecomp.mso.adapters.vdu.VduArtifact; -import org.openecomp.mso.adapters.vdu.VduArtifact.ArtifactType; - -import com.google.common.io.Files; - -/** - * The purpose of this class is to create a CSAR byte array from Vdu inputs for the purpose - * of forwarding to a TOSCA orchestrator. - * - * @author DeWayne - * - */ -public class CSAR { - private static final String MANIFEST_FILENAME = "MANIFEST.MF"; - private VduModelInfo vduModel; - - public CSAR(VduModelInfo model){ - this.vduModel = model; - } - - /** - * Creates a byte array representation of a CSAR corresponding to the VduBlueprint arg in the - * constructor. - * - * @return - */ - public byte[] create() { - File dir = Files.createTempDir(); - - /** - * Create subdir - */ - File metadir = new File(dir.getAbsolutePath() + "/" + "TOSCA-Metadata"); - if (!metadir.mkdir()) { - throw new RuntimeException("CSAR TOSCA-Metadata directory create failed"); - } - - /** - * Organize model info for consumption - */ - VduArtifact mainTemplate = null; - List<VduArtifact> extraFiles = null; - for(VduArtifact artifact: vduModel.getArtifacts()){ - if( artifact.getType() == ArtifactType.MAIN_TEMPLATE ){ - mainTemplate = artifact; - } - else{ - extraFiles.add(artifact); - } - } - - /** - * Write template files - */ - OutputStream ofs = null; - try { - ofs = new FileOutputStream(new File(dir, mainTemplate.getName())); - ofs.write(mainTemplate.getContent()); - ofs.close(); - - /** - * Write other files - */ - if (extraFiles != null) { - for (VduArtifact artifact: extraFiles){ - ofs = new FileOutputStream(new File(dir, artifact.getName())); - ofs.write(artifact.getContent()); - ofs.close(); - } - } - - - /** - * Create manifest - */ - PrintStream mfstream = new PrintStream(new File(metadir.getAbsolutePath() + "/" + MANIFEST_FILENAME)); - mfstream.println("TOSCA-Meta-File-Version: 1.0"); - mfstream.println("CSAR-Version: 1.1"); - mfstream.println("Created-by: ONAP"); - mfstream.println("Entry-Definitions: " + mainTemplate.getName()); - mfstream.close(); - - /** - * ZIP it up - */ - ByteArrayOutputStream zipbytes = new ByteArrayOutputStream(); - ZipOutputStream zos = new ZipOutputStream(zipbytes); - compressTree(zos, "", dir, dir); - zos.close(); - return zipbytes.toByteArray(); - - } catch (Exception e) { - throw new RuntimeException("Failed to create CSAR: " + e.getMessage()); - } finally { - - /** - * Clean up tmpdir - */ - deleteDirectory(dir); - } - } - - /** - * Private methods - */ - - /** - * Compresses (ZIPs) a directory tree - * - * @param dir - * @throws IOException - */ - private void compressTree(ZipOutputStream zos, String path, File basedir, File dir) throws IOException { - if (!dir.isDirectory()) - return; - - for (File f : dir.listFiles()) { - if (f.isDirectory()) { - String newpath = path + f.getName() + "/"; - ZipEntry entry = new ZipEntry(newpath); - zos.putNextEntry(entry); - zos.closeEntry(); - compressTree(zos, newpath, basedir, f); - } else { - ZipEntry ze = new ZipEntry( - f.getAbsolutePath().substring(basedir.getAbsolutePath().length() + 1).replaceAll("\\\\", "/")); - zos.putNextEntry(ze); - // read the file and write to ZipOutputStream - FileInputStream fis = new FileInputStream(f); - byte[] buffer = new byte[1024]; - int len; - while ((len = fis.read(buffer)) > 0) { - zos.write(buffer, 0, len); - } - zos.closeEntry(); - fis.close(); - } - } - } - - private boolean deleteDirectory(File directory) { - if (directory.exists()) { - File[] files = directory.listFiles(); - if (null != files) { - for (int i = 0; i < files.length; i++) { - if (files[i].isDirectory()) { - deleteDirectory(files[i]); - } else { - files[i].delete(); - } - } - } - } - return (directory.delete()); - } -} diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java deleted file mode 100644 index 2c15391c81..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java +++ /dev/null @@ -1,308 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.cloud; - -import java.io.FileReader; -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; - -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.openstack.exceptions.MsoCloudIdentityNotFound; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonRootName; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * 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. - * - * This class also contains methods to query cloud sites and/or identity - * services by ID. - * - */ - -@JsonRootName("cloud_config") -public class CloudConfig { - - private static final String CLOUD_SITE_VERSION = "2.5"; - private static final String DEFAULT_CLOUD_SITE_ID = "default"; - private boolean validCloudConfig = false; - private static ObjectMapper mapper = new ObjectMapper(); - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); - protected String configFilePath; - protected int refreshTimerInMinutes; - @JsonProperty("identity_services") - private Map<String, CloudIdentity> identityServices = new HashMap<>(); - @JsonProperty("cloud_sites") - private Map <String, CloudSite> cloudSites = new HashMap <String, CloudSite> (); - @JsonProperty("cloudify_managers") - private Map <String, CloudifyManager> cloudifyManagers = new HashMap <String, CloudifyManager> (); - - public CloudConfig() { - mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); - mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); - } - - /** - * Get a map of all identity services that have been loaded. - */ - public synchronized Map<String, CloudIdentity> getIdentityServices() { - return identityServices; - } - - /** - * Get a map of all cloud sites that have been loaded. - */ - public Map<String, CloudSite> getCloudSites() { - return Collections.unmodifiableMap(cloudSites); - } - - /** - * Get a Map of all CloudifyManagers that have been loaded. - * @return the Map - */ - public synchronized Map <String, CloudifyManager> getCloudifyManagers () { - return cloudifyManagers; - } - - /** - * 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(); - } - if (cloudSites.containsKey(id)) { - return Optional.ofNullable(cloudSites.get(id)); - } - return null; - } - - private CloudSite getCloudSiteWithClli(String clli) { - Optional <CloudSite> cloudSiteOptional = cloudSites.values().stream().filter(cs -> - cs.getClli() != null && clli.equals(cs.getClli()) && (CLOUD_SITE_VERSION.equals(cs.getAic_version()))) - .findAny(); - return cloudSiteOptional.orElse(getDefaultCloudSite(clli)); - } - - private CloudSite getDefaultCloudSite(String clli) { - Optional<CloudSite> cloudSiteOpt = cloudSites.values().stream() - .filter(cs -> cs.getId().equalsIgnoreCase(DEFAULT_CLOUD_SITE_ID)).findAny(); - if (cloudSiteOpt.isPresent()) { - CloudSite defaultCloudSite = cloudSiteOpt.get(); - defaultCloudSite.setRegionId(clli); - defaultCloudSite.setId(clli); - return defaultCloudSite; - } else { - return null; - } - } - - /** - * Get a specific CloudIdentity, based on an ID. - * - * @param id - * the ID to match - * @return a CloudIdentity, or null of no match found - */ - public synchronized CloudIdentity getIdentityService(String id) { - if (identityServices.containsKey(id)) { - return identityServices.get(id); - } - return null; - } - - /** - * Get a specific CloudifyManager, based on an ID. - * @param id the ID to match - * @return a CloudifyManager, or null of no match found - */ - public synchronized CloudifyManager getCloudifyManager (String id) { - if (cloudifyManagers.containsKey (id)) { - return cloudifyManagers.get (id); - } - return null; - } - - protected synchronized void reloadPropertiesFile() throws IOException, MsoCloudIdentityNotFound { - this.loadCloudConfig(this.configFilePath, this.refreshTimerInMinutes); - } - - protected synchronized void loadCloudConfig(String configFile, int refreshTimer) - throws IOException, MsoCloudIdentityNotFound { - - FileReader reader = null; - configFilePath = configFile; - this.refreshTimerInMinutes = refreshTimer; - this.validCloudConfig=false; - - try { - reader = new FileReader(configFile); - // Parse the JSON input into a CloudConfig - - CloudConfig cloudConfig = mapper.readValue(reader, CloudConfig.class); - - this.cloudSites = cloudConfig.cloudSites; - this.identityServices = cloudConfig.identityServices; - this.cloudifyManagers = cloudConfig.cloudifyManagers; - - // Copy Cloud Identity IDs to CloudIdentity objects - for (Entry<String, CloudIdentity> entry : cloudConfig.getIdentityServices().entrySet()) { - entry.getValue().setId(entry.getKey()); - } - - // Copy Cloduify IDs to CloudifyManager objects - for (Entry <String, CloudifyManager> entry : cloudConfig.getCloudifyManagers ().entrySet ()) { - entry.getValue ().setId (entry.getKey ()); - } - - // Copy Cloud Site IDs to CloudSite objects, and set up internal - // pointers to their corresponding identity service. - for (Entry<String, CloudSite> entry : cloudConfig.getCloudSites().entrySet()) { - CloudSite s = entry.getValue(); - s.setId(entry.getKey()); - CloudIdentity cloudIdentity = cloudConfig.getIdentityService(s.getIdentityServiceId()); - s.setIdentityService(cloudIdentity); - if (cloudIdentity == null) { - throw new MsoCloudIdentityNotFound(s.getId()+" Cloud site refers to a non-existing identity service: "+s.getIdentityServiceId()); - } - CloudifyManager cloudifyManager = cloudConfig.getCloudifyManager(s.getCloudifyId()); - s.setCloudifyManager(cloudifyManager); - } - this.validCloudConfig=true; - - } finally { - try { - if (reader != null) { - reader.close(); - } - } catch (IOException e) { - LOGGER.debug("Exception while closing reader for file:" + configFilePath, e); - } - } - } - - public String getConfigFilePath() { - return configFilePath; - } - - /** - * @return the validCouldConfig - */ - public synchronized boolean isValidCloudConfig() { - return validCloudConfig; - } - - @Override - public synchronized CloudConfig clone() { - CloudConfig ccCopy = new CloudConfig(); - for (Entry<String, CloudIdentity> e : identityServices.entrySet()) { - - ccCopy.identityServices.put(e.getKey(), e.getValue().clone()); - } - - for (Entry<String, CloudSite> e : cloudSites.entrySet()) { - - ccCopy.cloudSites.put(e.getKey(), e.getValue().clone()); - } - - for (Entry<String,CloudifyManager> e:cloudifyManagers.entrySet()) { - - ccCopy.cloudifyManagers.put(e.getKey(), e.getValue().clone()); - } - - ccCopy.configFilePath = this.configFilePath; - ccCopy.refreshTimerInMinutes = this.refreshTimerInMinutes; - ccCopy.validCloudConfig = this.validCloudConfig; - return ccCopy; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((cloudSites == null) ? 0 : cloudSites.hashCode()); - result = prime * result + ((configFilePath == null) ? 0 : configFilePath.hashCode()); - result = prime * result + ((identityServices == null) ? 0 : identityServices.hashCode()); - result = prime * result + refreshTimerInMinutes; - result = prime * result + (validCloudConfig ? 1231 : 1237); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - CloudConfig other = (CloudConfig) obj; - if (cloudSites == null) { - if (other.cloudSites != null) - return false; - } else if (!cloudSites.equals(other.cloudSites)) - return false; - if (configFilePath == null) { - if (other.configFilePath != null) - return false; - } else if (!configFilePath.equals(other.configFilePath)) - return false; - if (identityServices == null) { - if (other.identityServices != null) - return false; - } else if (!identityServices.equals(other.identityServices)) - return false; - if (refreshTimerInMinutes != other.refreshTimerInMinutes) - return false; - if (validCloudConfig != other.validCloudConfig) - return false; - return true; - } - - -} diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfigFactory.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfigFactory.java deleted file mode 100644 index 2b385910d9..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfigFactory.java +++ /dev/null @@ -1,209 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.cloud; - -import java.io.IOException; -import java.io.Serializable; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import javax.ejb.ConcurrencyManagement; -import javax.ejb.ConcurrencyManagementType; -import javax.ejb.LocalBean; -import javax.ejb.Schedule; -import javax.ejb.Singleton; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Response; - -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.openstack.exceptions.MsoCloudIdentityNotFound; -import org.openecomp.mso.openstack.utils.MsoHeatUtils; -import org.openecomp.mso.openstack.utils.MsoKeystoneUtils; -import org.openecomp.mso.openstack.utils.MsoNeutronUtils; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; - -/** - * This class returns a cloud Config instances - */ - -@Singleton(name = "CloudConfigFactory") -@ConcurrencyManagement(ConcurrencyManagementType.BEAN) -@LocalBean -@Path("/cloud") -public class CloudConfigFactory implements Serializable { - - private static final long serialVersionUID = 2956662716453261085L; - - private static CloudConfig cloudConfigCache = new CloudConfig(); - - protected static String prefixMsoPropertiesPath = System.getProperty ("mso.config.path"); - - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); - - private static int refreshTimer; - - private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock (); - - static { - if (prefixMsoPropertiesPath == null) { - prefixMsoPropertiesPath = ""; - } - } - - public void initializeCloudConfig (String filePath, int refreshTimer) throws MsoCloudIdentityNotFound { - rwl.writeLock ().lock (); - try { - cloudConfigCache.loadCloudConfig (prefixMsoPropertiesPath + filePath, refreshTimer); - LOGGER.info (MessageEnum.RA_CONFIG_LOAD, prefixMsoPropertiesPath + filePath, "", ""); - } catch (JsonParseException e) { - LOGGER.error (MessageEnum.RA_CONFIG_EXC, "Error parsing cloud config file " + filePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonParseException", e); - } catch (JsonMappingException e) { - LOGGER.error (MessageEnum.RA_CONFIG_EXC, "Error parsing cloud config file " + filePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonMappingException", e); - } catch (IOException e) { - LOGGER.error (MessageEnum.RA_CONFIG_NOT_FOUND, filePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - config not found", e); - } finally { - rwl.writeLock ().unlock (); - } - } - - public CloudConfig getCloudConfig () { - rwl.readLock ().lock (); - try { - if (!cloudConfigCache.isValidCloudConfig()) { - // Not ideal, but better than returning an invalid object - throw new IllegalStateException("No valid CloudConfig is loaded"); - } - return cloudConfigCache.clone (); - } finally { - rwl.readLock ().unlock (); - } - } - - /** - * This method is not intended to be called, it's used to refresh the config - * automatically - */ - @Schedule(minute = "*/1", hour = "*", persistent = false) - public void reloadCloudConfig () { - - try { - if (!rwl.writeLock ().tryLock () && !rwl.writeLock ().tryLock (30L, TimeUnit.SECONDS)) { - LOGGER.debug ("Busy write lock on mso cloud config factory, skipping the reloading"); - return; - } - } catch (InterruptedException e1) { - LOGGER.debug ("Interrupted while trying to acquire write lock on cloud config factory, skipping the reloading"); - Thread.currentThread ().interrupt (); - return; - } - try { - //LOGGER.debug ("Processing a reload of the mso properties file entries"); - try { - - if (refreshTimer <= 1) { - CloudConfig oldCloudConfig = null; - if (cloudConfigCache.isValidCloudConfig()) { - oldCloudConfig = cloudConfigCache.clone(); - } - cloudConfigCache.reloadPropertiesFile (); - refreshTimer = cloudConfigCache.refreshTimerInMinutes; - if (!cloudConfigCache.equals(oldCloudConfig)) { - LOGGER.info (MessageEnum.RA_CONFIG_LOAD, prefixMsoPropertiesPath + cloudConfigCache.configFilePath, "", ""); - } - - } else { - --refreshTimer; - } - - } catch (JsonParseException e) { - LOGGER.error (MessageEnum.RA_CONFIG_EXC, - "Error parsing cloud config file " + cloudConfigCache.configFilePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonParseException", - e); - } catch (JsonMappingException e) { - LOGGER.error (MessageEnum.RA_CONFIG_EXC, - "Error parsing cloud config file " + cloudConfigCache.configFilePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonMappingException", - e); - } catch (IOException e) { - LOGGER.error (MessageEnum.RA_CONFIG_NOT_FOUND, cloudConfigCache.configFilePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - config not found", e); - } - } catch (Exception e) { - LOGGER.error (MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. Global issue while reloading", "", "", MsoLogger.ErrorCode.DataError, "Exception - Global issue while reloading\"", e); - } finally { - rwl.writeLock ().unlock (); - } - } - - @GET - @Path("/showConfig") - @Produces("text/plain") - public Response showCloudConfig () { - CloudConfig cloudConfig = this.getCloudConfig(); - StringBuffer response = new StringBuffer(); - response.append("Cloud Sites:\n"); - for (CloudSite site : cloudConfig.getCloudSites().values()) { - response.append(site.toString()).append("\n"); - } - response.append("\n\nCloud Identity Services:\n"); - for (CloudIdentity identity : cloudConfig.getIdentityServices().values()) { - response.append(identity.toString()).append("\n"); - } - return Response.status(200).entity(response).build(); - } - - @GET - @Path("/resetClientCaches") - @Produces("text/plain") - public Response resetClientCaches () { - // Reset all cached clients/credentials - MsoKeystoneUtils.adminCacheReset (); - MsoHeatUtils.heatCacheReset (); - MsoNeutronUtils.neutronCacheReset (); - String response = "Client caches reset. All entries removed."; - return Response.status (200).entity (response).build (); - } - - @GET - @Path("/cleanupClientCaches") - @Produces("text/plain") - public Response cleanupClientCaches () { - // Reset all cached clients/credentials - MsoKeystoneUtils.adminCacheCleanup (); - MsoHeatUtils.heatCacheCleanup (); - MsoNeutronUtils.neutronCacheCleanup (); - String response = "Client caches cleaned up. All expired entries removed."; - return Response.status (200).entity (response).build (); - } - - @GET - @Path("/encryptPassword/{pwd}") - @Produces("text/plain") - public Response encryptPassword (@PathParam("pwd") String pwd) { - String encryptedPassword = CloudIdentity.encryptPassword (pwd); - - String response = "Encrypted Password = " + encryptedPassword; - return Response.status (200).entity (response).build (); - } -} diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudIdentity.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudIdentity.java deleted file mode 100644 index 07f0546256..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudIdentity.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * ============LICENSE_START========================================== - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * - * ECOMP and OpenECOMP are trademarks - * and service marks of AT&T Intellectual Property. - * - */ - -package org.openecomp.mso.cloud; - -import java.security.GeneralSecurityException; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.woorea.openstack.keystone.model.Authentication; -import com.woorea.openstack.keystone.model.authentication.UsernamePassword; -import org.openecomp.mso.cloud.authentication.AuthenticationMethodFactory; -import org.openecomp.mso.cloud.authentication.AuthenticationWrapper; -import org.openecomp.mso.cloud.authentication.wrappers.RackspaceAPIKeyWrapper; -import org.openecomp.mso.cloud.authentication.wrappers.UsernamePasswordWrapper; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.openstack.exceptions.MsoException; -import org.openecomp.mso.openstack.utils.MsoKeystoneUtils; -import org.openecomp.mso.openstack.utils.MsoTenantUtils; -import org.openecomp.mso.openstack.utils.MsoTenantUtilsFactory; -import org.openecomp.mso.utils.CryptoUtils; - -/** - * JavaBean JSON class for a CloudIdentity. This bean represents a cloud identity - * service instance (i.e. a DCP node) in the NVP/AIC cloud. It will be loaded via - * CloudConfig object, of which it is a component (a CloudConfig JSON configuration - * file may contain multiple CloudIdentity definitions). - * - * Note that this is only used to access Cloud Configurations loaded from a - * JSON config file, so there are no explicit setters. - * - */ -public class CloudIdentity { - - // This block is needed to trigger the class loader so that static initialization - // of both inner static classes occur. This is required when the Json Deserializer - // gets called and no access to any of these inner classes happened yet. - static { - IdentityServerType.bootstrap(); - IdentityAuthenticationType.bootstrap(); - } - - private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); - - public final static class IdentityServerType extends IdentityServerTypeAbstract { - - public static final IdentityServerType KEYSTONE = new IdentityServerType("KEYSTONE", MsoKeystoneUtils.class); - - public IdentityServerType(String serverType, Class<? extends MsoTenantUtils> utilsClass) { - super(serverType, utilsClass); - } - - public static final void bootstrap() {} - } - - public static final class IdentityAuthenticationType extends IdentityAuthenticationTypeAbstract { - - public static final IdentityAuthenticationType USERNAME_PASSWORD = new IdentityAuthenticationType("USERNAME_PASSWORD", UsernamePasswordWrapper.class); - - public static final IdentityAuthenticationType RACKSPACE_APIKEY = new IdentityAuthenticationType("RACKSPACE_APIKEY", RackspaceAPIKeyWrapper.class); - - public IdentityAuthenticationType(String identityType, Class<? extends AuthenticationWrapper> wrapperClass) { - super(identityType, wrapperClass); - } - - public static final void bootstrap() {} - } - - @JsonProperty - private String id; - @JsonProperty("identity_url") - private String identityUrl; - @JsonProperty("mso_id") - private String msoId; - @JsonProperty("mso_pass") - private String msoPass; - @JsonProperty("admin_tenant") - private String adminTenant; - @JsonProperty("member_role") - private String memberRole; - @JsonProperty("tenant_metadata") - private Boolean tenantMetadata; - @JsonProperty("identity_server_type") - @JsonSerialize(using=IdentityServerTypeJsonSerializer.class) - @JsonDeserialize(using=IdentityServerTypeJsonDeserializer.class) - private IdentityServerType identityServerType; - @JsonProperty("identity_authentication_type") - @JsonSerialize(using=IdentityAuthenticationTypeJsonSerializer.class) - @JsonDeserialize(using=IdentityAuthenticationTypeJsonDeserializer.class) - private IdentityAuthenticationType identityAuthenticationType; - - private static String cloudKey = "aa3871669d893c7fb8abbcda31b88b4f"; - - public CloudIdentity () { - } - - public String getId () { - return id; - } - - public void setId (String id) { - this.id = id; - } - - public String getKeystoneUrl (String regionId, String msoPropID) throws MsoException { - if (IdentityServerType.KEYSTONE.equals(this.identityServerType)) { - return this.identityUrl; - } else { - if (this.identityServerType == null) { - return null; - } - MsoTenantUtils tenantUtils = new MsoTenantUtilsFactory(msoPropID).getTenantUtilsByServerType(this.identityServerType.toString()); - if (tenantUtils != null) { - return tenantUtils.getKeystoneUrl(regionId, msoPropID, this); - } else { - return null; - } - } - } - - public Authentication getAuthentication() { - if (this.getIdentityAuthenticationType() != null) { - return AuthenticationMethodFactory.getAuthenticationFor(this); - } else { - return new UsernamePassword(this.getMsoId(), this.getMsoPass()); - } - } - - public void setKeystoneUrl (String url) { - if (IdentityServerType.KEYSTONE.equals(this.identityServerType)) { - this.identityUrl = url; - } - } - - public String getIdentityUrl() { - return this.identityUrl; - } - public void setIdentityUrl(String url) { - this.identityUrl = url; - } - - public String getMsoId () { - return msoId; - } - - public void setMsoId (String id) { - this.msoId = id; - } - - public String getMsoPass () { - try { - return CryptoUtils.decrypt (msoPass, cloudKey); - } catch (GeneralSecurityException e) { - LOGGER.error (MessageEnum.RA_GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in getMsoPass", e); - return null; - } - } - - public void setMsoPass (String pwd) { - this.msoPass = pwd; - } - - public String getAdminTenant () { - return adminTenant; - } - - public void setAdminTenant (String tenant) { - this.adminTenant = tenant; - } - - public String getMemberRole () { - return memberRole; - } - - public void setMemberRole (String role) { - this.memberRole = role; - } - - public boolean hasTenantMetadata () { - return tenantMetadata; - } - - public void setTenantMetadata (boolean meta) { - this.tenantMetadata = meta; - } - - public IdentityServerType getIdentityServerType() { - return this.identityServerType; - } - public void setIdentityServerType(IdentityServerType ist) { - this.identityServerType = ist; - } - public String getIdentityServerTypeAsString() { - return this.identityServerType.toString(); - } - /** - * @return the identityAuthenticationType - */ - public IdentityAuthenticationType getIdentityAuthenticationType() { - return identityAuthenticationType; - } - - /** - * @param identityAuthenticationType the identityAuthenticationType to set - */ - public void setIdentityAuthenticationType(IdentityAuthenticationType identityAuthenticationType) { - this.identityAuthenticationType = identityAuthenticationType; - } - - @Override - public String toString () { - return "Cloud Identity Service: id=" + id + - ", identityUrl=" + this.identityUrl + - ", msoId=" + msoId + - ", adminTenant=" + adminTenant + - ", memberRole=" + memberRole + - ", tenantMetadata=" + tenantMetadata + - ", identityServerType=" + (identityServerType == null ? "null" : identityServerType.toString()) + - ", identityAuthenticationType=" + (identityAuthenticationType == null ? "null" : identityAuthenticationType.toString()); - } - - public static String encryptPassword (String msoPass) { - try { - return CryptoUtils.encrypt (msoPass, cloudKey); - } catch (GeneralSecurityException e) { - LOGGER.error (MessageEnum.RA_GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in encryptPassword", e); - return null; - } - } - - - @Override - public CloudIdentity clone() { - CloudIdentity cloudIdentityCopy = new CloudIdentity(); - - cloudIdentityCopy.id = this.id; - cloudIdentityCopy.identityUrl = this.identityUrl; - cloudIdentityCopy.msoId = this.msoId; - cloudIdentityCopy.msoPass = this.msoPass; - cloudIdentityCopy.adminTenant = this.adminTenant; - cloudIdentityCopy.memberRole = this.memberRole; - cloudIdentityCopy.tenantMetadata = this.tenantMetadata; - cloudIdentityCopy.identityServerType = this.identityServerType; - cloudIdentityCopy.identityAuthenticationType = this.identityAuthenticationType; - - return cloudIdentityCopy; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((adminTenant == null) ? 0 : adminTenant.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((identityUrl == null) ? 0 : identityUrl.hashCode()); - result = prime * result + ((memberRole == null) ? 0 : memberRole.hashCode()); - result = prime * result + ((msoId == null) ? 0 : msoId.hashCode()); - result = prime * result + ((msoPass == null) ? 0 : msoPass.hashCode()); - result = prime * result + ((tenantMetadata == null) ? 0 : tenantMetadata.hashCode()); - result = prime * result + ((identityServerType == null) ? 0 : identityServerType.hashCode()); - result = prime * result + ((identityAuthenticationType == null) ? 0 : identityAuthenticationType.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - CloudIdentity other = (CloudIdentity) obj; - if (adminTenant == null) { - if (other.adminTenant != null) - return false; - } else if (!adminTenant.equals(other.adminTenant)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (identityUrl == null) { - if (other.identityUrl != null) - return false; - } else if (!identityUrl.equals(other.identityUrl)) - return false; - if (memberRole == null) { - if (other.memberRole != null) - return false; - } else if (!memberRole.equals(other.memberRole)) - return false; - if (msoId == null) { - if (other.msoId != null) - return false; - } else if (!msoId.equals(other.msoId)) - return false; - if (msoPass == null) { - if (other.msoPass != null) - return false; - } else if (!msoPass.equals(other.msoPass)) - return false; - if (tenantMetadata == null) { - if (other.tenantMetadata != null) - return false; - } else if (!tenantMetadata.equals(other.tenantMetadata)) - return false; - if (identityServerType == null) { - if (other.getIdentityServerType() != null) - return false; - } else if (!identityServerType.equals(other.getIdentityServerType())) - return false; - if (identityAuthenticationType == null) { - if (other.getIdentityAuthenticationType() != null) - return false; - } else if (!identityAuthenticationType.equals(other.getIdentityAuthenticationType())) - return false; - - return true; - } -} diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityAuthenticationTypeAbstract.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityAuthenticationTypeAbstract.java deleted file mode 100644 index 41f70e4492..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityAuthenticationTypeAbstract.java +++ /dev/null @@ -1,86 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.openecomp.mso.cloud;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.openecomp.mso.cloud.authentication.AuthenticationWrapper;
-import org.openecomp.mso.logger.MsoLogger;
-
-public abstract class IdentityAuthenticationTypeAbstract {
-
- private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH);
- // This map will prevent duplicates (as if it was an Enum).
- // Without this, using an instance specific field for the class could allow
- // different classes bound to the same entry name.
- private static final Map<String, IdentityAuthenticationTypeAbstract> entries = new ConcurrentHashMap<>();
-
- private String identityType;
-
- private Class<? extends AuthenticationWrapper> wrapperClass;
-
- protected IdentityAuthenticationTypeAbstract(String identityType, Class<? extends AuthenticationWrapper> wrapperClass) {
- try {
- this.identityType = identityType;
- this.wrapperClass = wrapperClass;
- entries.put(identityType, this);
- AuthenticationWrapper.register(this.toString(), wrapperClass);
- } catch (IllegalAccessException | InstantiationException e) {
- LOGGER.debug("Exception in Identity Authentication",e);
- }
- }
-
- public static final IdentityAuthenticationTypeAbstract valueOf(String serverType) {
- return entries.get(serverType);
- }
-
- @Override
- public final String toString() {
- return this.identityType;
- }
-
- public final String name() {
- return this.identityType;
- }
-
- public static final IdentityAuthenticationTypeAbstract[] values() {
- return (IdentityAuthenticationTypeAbstract[]) entries.values().stream().toArray(IdentityAuthenticationTypeAbstract[]::new);
- }
-
- public final Class<? extends AuthenticationWrapper> getWrapperClass() {
- return this.wrapperClass;
- }
-
- @Override
- public final boolean equals(Object other) {
- return (this.identityType != null) && (other != null) && (other instanceof IdentityAuthenticationTypeAbstract) && (this.identityType.equals(other.toString()));
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((identityType == null) ? 0 : identityType.hashCode());
- return result;
- }
-
-}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityAuthenticationTypeJsonDeserializer.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityAuthenticationTypeJsonDeserializer.java deleted file mode 100644 index 2b50c2690c..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityAuthenticationTypeJsonDeserializer.java +++ /dev/null @@ -1,42 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.openecomp.mso.cloud;
-
-import java.io.IOException;
-
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.core.JsonToken;
-import com.fasterxml.jackson.databind.DeserializationContext;
-import com.fasterxml.jackson.databind.JsonDeserializer;
-
-public class IdentityAuthenticationTypeJsonDeserializer extends JsonDeserializer<IdentityAuthenticationTypeAbstract> {
-
- @Override
- public IdentityAuthenticationTypeAbstract deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
- throws IOException, JsonProcessingException {
- JsonToken token = jsonParser.getCurrentToken();
- if (JsonToken.VALUE_STRING.equals(token)) {
- return IdentityAuthenticationTypeAbstract.valueOf(jsonParser.getText());
- } else {
- return null;
- }
- }
-}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityServerTypeAbstract.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityServerTypeAbstract.java deleted file mode 100644 index ad909a73c7..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/IdentityServerTypeAbstract.java +++ /dev/null @@ -1,85 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.openecomp.mso.cloud;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.openecomp.mso.openstack.utils.MsoTenantUtils;
-
-
-public abstract class IdentityServerTypeAbstract {
-
- // This map will prevent duplicates (as if it was an Enum).
- // Without this, using an instance specific field for the class could allow
- // different classes bound to the same entry name.
- private static final Map<String, IdentityServerTypeAbstract> entries = new ConcurrentHashMap<>();
-
- private String serverType;
-
- private Class<? extends MsoTenantUtils> utilsClass;
-
- protected IdentityServerTypeAbstract(String serverType, Class<? extends MsoTenantUtils> utilsClass) {
- if ((serverType == null) || (serverType.isEmpty())) {
- throw new IllegalArgumentException("Server Type name cannot be null or empty, provided value was " + serverType);
- }
- if (entries.containsKey(serverType)) {
- throw new IllegalArgumentException("Duplicate Server Type entry for registration: " + serverType);
- }
- this.serverType = serverType;
- this.utilsClass = utilsClass;
- entries.put(serverType, this);
- }
-
- public static final IdentityServerTypeAbstract valueOf(String serverType) {
- return entries.get(serverType);
- }
-
- @Override
- public final String toString() {
- return this.serverType;
- }
-
- public final String name() {
- return this.serverType;
- }
-
- public static final IdentityServerTypeAbstract[] values() {
- return (IdentityServerTypeAbstract[]) entries.values().stream().toArray(IdentityServerTypeAbstract[]::new);
- }
-
- public final Class<? extends MsoTenantUtils> getMsoTenantUtilsClass() {
- return this.utilsClass;
- }
-
- @Override
- public final boolean equals(Object other) {
- return ((this.serverType != null) && (other != null) && (other instanceof IdentityServerTypeAbstract) && (this.serverType.equals(other.toString())));
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((serverType == null) ? 0 : serverType.hashCode());
- return result;
- }
-}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/AuthenticationMethodFactory.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/AuthenticationMethodFactory.java deleted file mode 100644 index c9be2c7949..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/AuthenticationMethodFactory.java +++ /dev/null @@ -1,71 +0,0 @@ -/*
- * ============LICENSE_START==========================================
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
- * ===================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END============================================
- *
- * ECOMP and OpenECOMP are trademarks
- * and service marks of AT&T Intellectual Property.
- *
- */
-
-package org.openecomp.mso.cloud.authentication;
-
-import com.woorea.openstack.keystone.model.Authentication;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import org.openecomp.mso.cloud.CloudIdentity;
-
-/**
- * This factory manages all the wrappers associated to authentication types.
- */
-public final class AuthenticationMethodFactory {
-
- private static Map<String, AuthenticationWrapper> authWrappers = new ConcurrentHashMap<>();
-
- private AuthenticationMethodFactory() {}
-
- /**
- * Function to be called by classes implementing the abstract {@link AuthenticationWrapper#register(String, Class)}.
- */
- static final synchronized void register(String authenticationType, Class<? extends AuthenticationWrapper> wrapperClass) throws InstantiationException, IllegalAccessException {
- if ((authenticationType == null) || ("".equals(authenticationType))) {
- throw new IllegalArgumentException("Authentication Type to register cannot be null or an empty name string, provided value is " + authenticationType + ".");
- }
- if (wrapperClass == null) {
- throw new IllegalArgumentException("Wrapper Class to register for Authentication cannot be null");
- }
-
- if (!authWrappers.containsKey(authenticationType)) {
- authWrappers.put(authenticationType, wrapperClass.newInstance());
- }
- }
-
- public static final synchronized 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() + ".");
- }
- String authenticationType = cloudIdentity.getIdentityAuthenticationType().toString();
-
- if (authWrappers.containsKey(authenticationType)) {
- return authWrappers.get(authenticationType).getAuthentication(cloudIdentity);
- } else {
- throw new IllegalArgumentException("Provided authentication type (" + authenticationType + ") is not implemented by any wrapper.");
- }
- }
-}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/AuthenticationWrapper.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/AuthenticationWrapper.java deleted file mode 100644 index 77f405a660..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/AuthenticationWrapper.java +++ /dev/null @@ -1,58 +0,0 @@ -/*
- * ============LICENSE_START==========================================
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
- * ===================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END============================================
- *
- * ECOMP and OpenECOMP are trademarks
- * and service marks of AT&T Intellectual Property.
- *
- */
-
-package org.openecomp.mso.cloud.authentication;
-
-import org.openecomp.mso.cloud.CloudIdentity;
-
-import com.woorea.openstack.keystone.model.Authentication;
-
-/**
- * This abstract class provides the necessary method for registering authentication
- * types with wrapper classes, and also defines the contract for providing
- * Openstack-compatible Authentication implementations for said authentication types.
- *
- */
-public abstract class AuthenticationWrapper {
-
- /**
- * Registers the implementing class to the list of Authentication Wrappers.
- *
- * @param authenticationType The authentication type that is provided by the implementing class
- * @param wrapperClass The implementing class Class object
- * @throws InstantiationException If the provided implementing class cannot be instantiated
- * @throws IllegalAccessException If the provided implementing class cannot be instantiated
- */
- public static final void register(String authenticationType, Class<? extends AuthenticationWrapper> wrapperClass) throws InstantiationException, IllegalAccessException {
- AuthenticationMethodFactory.register(authenticationType, wrapperClass);
- }
-
- /**
- * Returns an OpenStack Authentication object for the provided CloudIdentity.
- *
- * @param cloudIdentity The input Cloud Identity instance
- * @return the OpenStack Authentication associated with this cloud identity instance
- */
- protected abstract Authentication getAuthentication(CloudIdentity cloudIdentity);
-
-}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/wrappers/RackspaceAPIKeyWrapper.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/wrappers/RackspaceAPIKeyWrapper.java deleted file mode 100644 index e82306b6cd..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/wrappers/RackspaceAPIKeyWrapper.java +++ /dev/null @@ -1,45 +0,0 @@ -/*
- * ============LICENSE_START==========================================
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
- * ===================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END============================================
- *
- * ECOMP and OpenECOMP are trademarks
- * and service marks of AT&T Intellectual Property.
- *
- */
-
-package org.openecomp.mso.cloud.authentication.wrappers;
-
-import org.openecomp.mso.cloud.CloudIdentity;
-import org.openecomp.mso.cloud.authentication.AuthenticationWrapper;
-import org.openecomp.mso.cloud.authentication.models.RackspaceAuthentication;
-
-import com.woorea.openstack.keystone.model.Authentication;
-
-/**
- * This class implements the authentication wrapper for Rackspace Authentication.
- *
- */
-public class RackspaceAPIKeyWrapper extends AuthenticationWrapper {
-
- @Override
- public Authentication getAuthentication(CloudIdentity cloudIdentity) {
- if (cloudIdentity == null) {
- throw new IllegalArgumentException("Provided cloud identity is null, cannot extract username and password");
- }
- return new RackspaceAuthentication (cloudIdentity.getMsoId (), cloudIdentity.getMsoPass ());
- }
-}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/wrappers/UsernamePasswordWrapper.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/wrappers/UsernamePasswordWrapper.java deleted file mode 100644 index a1beabe564..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/wrappers/UsernamePasswordWrapper.java +++ /dev/null @@ -1,45 +0,0 @@ -/*
- * ============LICENSE_START==========================================
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
- * ===================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END============================================
- *
- * ECOMP and OpenECOMP are trademarks
- * and service marks of AT&T Intellectual Property.
- *
- */
-
-package org.openecomp.mso.cloud.authentication.wrappers;
-
-import org.openecomp.mso.cloud.CloudIdentity;
-import org.openecomp.mso.cloud.authentication.AuthenticationWrapper;
-
-import com.woorea.openstack.keystone.model.Authentication;
-import com.woorea.openstack.keystone.model.authentication.UsernamePassword;
-
-/**
- * This class implements the authentication wrapper for Openstack provided for
- * user name and password authentication.
- */
-public class UsernamePasswordWrapper extends AuthenticationWrapper {
-
- @Override
- public Authentication getAuthentication(CloudIdentity cloudIdentity) {
- if (cloudIdentity == null) {
- throw new IllegalArgumentException("Provided cloud identity is null, cannot extract username and password");
- }
- return new UsernamePassword (cloudIdentity.getMsoId (), cloudIdentity.getMsoPass ());
- }
-}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/CloudConfigInitializer.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/CloudConfigInitializer.java deleted file mode 100644 index 43a6171699..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/CloudConfigInitializer.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.openstack.utils; - - -import javax.ejb.EJB; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.annotation.WebListener; - -import org.openecomp.mso.cloud.CloudConfigFactory; -import org.openecomp.mso.cloud.CloudConfigIdentityMapper; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; - -/** - * This class will attempt to initialize Cloud Config when part of a web application. - * - * - * - */ -@WebListener -public class CloudConfigInitializer implements ServletContextListener -{ - - private CloudConfigFactory cloudConfigFactory=new CloudConfigFactory(); - - public CloudConfigInitializer () { - } - - @Override - public void contextDestroyed(ServletContextEvent event) { - // Nothing to do... - } - - - @Override - public void contextInitialized(ServletContextEvent event) - { - - // Note - this logger may be before or after MSO Logging configuration applied - MsoLogger initLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); - try { - // Look first in the init-parameters - String msoPropConfigParam = event.getServletContext().getInitParameter("mso.cloud_config.configuration"); - - String[] configFileSplit = msoPropConfigParam.split(","); - for (String msoPropConfig:configFileSplit) { - String[] msoPropDecoded = msoPropConfig.split("="); - - try { - cloudConfigFactory.initializeCloudConfig(msoPropDecoded[0], Integer.valueOf(msoPropDecoded[1])); - initLogger.info(MessageEnum.RA_CONFIG_LOAD, msoPropDecoded[0], "", ""); - initLogger.debug("Mso properties successfully loaded:"+msoPropDecoded[0]+"(Timer(mins):"+Integer.valueOf(msoPropDecoded[1])); - } catch (NumberFormatException ne) { - initLogger.error(MessageEnum.RA_CONFIG_EXC, msoPropDecoded[0] + ". MSO Properties failed due to conversion error (in web.xml file)", "", "", MsoLogger.ErrorCode.DataError, "MSO Properties failed due to conversion error (in web.xml file)", ne); - } - } - - // Second, obtain class name that will register all mappings - String msoMapperClassParam = event.getServletContext().getInitParameter("mso.cloud_config.mapper.class"); - if (msoMapperClassParam != null) { - Class<?> mapperClass = Class.forName(msoMapperClassParam); - if (CloudConfigIdentityMapper.class.isAssignableFrom(mapperClass)) { - ((CloudConfigIdentityMapper)mapperClass.newInstance()).registerAllMappings(); - initLogger.info(MessageEnum.RA_CONFIG_LOAD,msoMapperClassParam+"(Openstack authentication mapper class)","",""); - } else { - initLogger.info(MessageEnum.RA_CONFIG_LOAD,msoMapperClassParam+"(Openstack authentication mapper class not an implementation of CloudConfigIdentityMapper)","",""); - } - } else { - initLogger.info(MessageEnum.RA_CONFIG_LOAD,"Openstack authentication mapper class not specified in web.xml (ONLY core authentication mechanisms will be loaded)","",""); - } - - } - catch (Exception e) { - initLogger.error(MessageEnum.RA_CONFIG_EXC, "Unknown. MSO Properties failed to initialize completely", "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception - MSO Properties failed to initialize completely", e); - } - } -} diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntry.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntry.java deleted file mode 100644 index 7046096979..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntry.java +++ /dev/null @@ -1,263 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.openstack.utils; - - -import java.util.HashSet; -import java.util.ArrayList; -import java.util.Set; - -import org.openecomp.mso.db.catalog.beans.HeatTemplateParam; -import org.openecomp.mso.logger.MsoLogger; - -public class MsoHeatEnvironmentEntry { - - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); - - 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)) - 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 + '\'' + - '}'; - } - - 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()); - Set<MsoHeatEnvironmentParameter> hpaParams = yaml.getParameterListFromEnvt(); - for (MsoHeatEnvironmentParameter hpaparam : hpaParams) { - for (MsoHeatEnvironmentParameter param : this.parameters) { - if (param.getName() == hpaparam.getName()) { - param.setValue(hpaparam.getValue()); - } - } - } - } catch (Exception e) { - LOGGER.debug("Exception:", e); - this.errorString = e.getMessage(); - //e.printStackTrace(); - } - } -} diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java deleted file mode 100644 index 49c262268d..0000000000 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.openstack.utils; - -import java.lang.reflect.InvocationTargetException; - -import org.openecomp.mso.cloud.CloudConfig; -import org.openecomp.mso.cloud.CloudConfigFactory; -import org.openecomp.mso.cloud.CloudIdentity; -import org.openecomp.mso.cloud.CloudSite; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound; - - -public class MsoTenantUtilsFactory { - - private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); - private CloudConfigFactory cloudConfigFactory = new CloudConfigFactory(); - private String msoPropID; - - public MsoTenantUtilsFactory (String msoPropID) { - this.msoPropID = msoPropID; - } - - public void setCloudConfigFactory(CloudConfigFactory cloudConfigFactory) { - this.cloudConfigFactory = cloudConfigFactory; - } - - public CloudConfigFactory getCloudConfigFactory() { - return cloudConfigFactory; - } - - //based on Cloud IdentityServerType returns ORM or KEYSTONE Utils - public MsoTenantUtils getTenantUtils(String cloudSiteId) throws MsoCloudSiteNotFound { - // Obtain the cloud site information - CloudConfig cloudConfig = getCloudConfigFactory().getCloudConfig(); - CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( - () -> new MsoCloudSiteNotFound(cloudSiteId)); - return getTenantUtilsByServerType(cloudSite.getIdentityService().getIdentityServerType().toString()); - } - - public MsoTenantUtils getTenantUtilsByServerType(String serverType) { - - MsoTenantUtils tenantU = null; - if (CloudIdentity.IdentityServerType.KEYSTONE.toString().equals(serverType)) { - tenantU = new MsoKeystoneUtils(msoPropID, getCloudConfigFactory()); - } else { - try { - tenantU = CloudIdentity.IdentityServerType.valueOf(serverType).getMsoTenantUtilsClass() - .getConstructor(String.class, CloudConfigFactory.class).newInstance(msoPropID, getCloudConfigFactory()); - } catch (InvocationTargetException | InstantiationException | NoSuchMethodException | IllegalAccessException e) { - throw new RuntimeException("Could not instantiate an MsoTenantUtils class for " + serverType, e); - } - } - return tenantU; - } -} |