diff options
author | 2021-05-13 15:09:28 -0400 | |
---|---|---|
committer | 2021-05-17 10:52:59 -0400 | |
commit | 7845d9b33a89a1c647dfa20bfefee3599783cae7 (patch) | |
tree | 3be5e37a9c916b858002458278a999ca9b8e3974 /adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main | |
parent | 557282a4274b7f2849e2433ff3373b43c6a920b3 (diff) |
Moving IAAS Adaptor from APPC to CCSDK SLI
Issue-ID: CCSDK-3198
Signed-off-by: Singal, Kapil (ks220y) <ks220y@att.com>
Change-Id: I24c21a9bebe87bb87eb14bd903ee558c20b45277
Diffstat (limited to 'adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main')
58 files changed, 10355 insertions, 0 deletions
diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/Constants.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/Constants.java new file mode 100644 index 000000000..6996d1192 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/Constants.java @@ -0,0 +1,261 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Modifications Copyright (C) 2018 Samsung + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + + + +package org.onap.ccsdk.sli.adaptors.iaas; + +/** + * This class contains the definitions of all constant values used in the APPC provider, adapters, and other components. + * These constants define properties, settings, and context variables. The context variables can be referenced from + * within the directed graph(s) to access information placed their by the provider and adapters. + * <p> + * Context properties are set in the graph context by the various adapters and the provider, or by the graph itself. + * These properties may also be accessed by the graph, adapters, or the provider. It is these properties that allow + * communication of state through the directed graph. All context properties have a symbolic name that starts with + * "CONTEXT_". + * </p> + * + */ + +public final class Constants { + + public static final String ADAPTER_NAME = "Appc IaaS Adapter"; + + /** + * The name for the error code attribute to be set in the context + */ + @SuppressWarnings("nls") + public static final String ATTRIBUTE_ERROR_CODE = "error_code"; + + /** + * The name for the error message attribute to be set in the context + */ + @SuppressWarnings("nls") + public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; + + /** + * The name for the error message to be set in the context + */ + @SuppressWarnings("nls") + public static final String CONTEXT_ERROR_MESSAGE = "org.onap.rest.result.message"; + + @SuppressWarnings("nls") + public static final String CONTEXT_AGENT_ERROR_MESSAGE = "org.onap.rest.agent.result.message"; + + /** + * The name for the error code to be set in the context + */ + @SuppressWarnings("nls") + public static final String CONTEXT_ERROR_CODE = "org.onap.rest.result.code"; + + @SuppressWarnings("nls") + public static final String CONTEXT_AGENT_ERROR_CODE = "org.onap.rest.agent.result.code"; + + /** + * The name for the success message attribute to be set in the context + */ + @SuppressWarnings("nls") + public static final String ATTRIBUTE_SUCCESS_MESSAGE = "success-message"; + + public static final String DG_ATTRIBUTE_STATUS = "SvcLogic.status"; + public static final String DG_OUTPUT_STATUS_CODE = "output.status.code"; + public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + + /** + * The property that defines the name of the DG service logic to be loaded + */ + public static final String PROPERTY_MODULE_NAME = "appc.service.logic.module.name"; + + /** + * The property that defines the topology restart DG version to be used + */ + public static final String PROPERTY_TOPOLOGY_VERSION = "appc.topology.dg.version"; + + /** + * The method name of the DG that is used to perform topology restart operations + */ + public static final String PROPERTY_TOPOLOGY_METHOD = "appc.topology.dg.method"; + + /** + * The property that supplies the application name + */ + public static final String PROPERTY_APPLICATION_NAME = "appc.application.name"; + + /** + * The execution mode for the directed graph + */ + public static final String SYNC_MODE = "sync"; + + /** + * The name of the property that contains the service request enumerated value in the graph's context + */ + public static final String CONTEXT_SERVICE = "org.onap.appc.service"; + + /** + * The name of the property that contains the VM id value in the graph's context + */ + public static final String CONTEXT_VMID = "org.onap.appc.vmid"; + + /** + * The name of the property that contains the VM id value in the graph's context + */ + public static final String CONTEXT_IDENTITY_URL = "org.onap.appc.identity.url"; + + /** + * The name of the property that contains the service request id value in the graph's context + */ + public static final String CONTEXT_REQID = "org.onap.appc.reqid"; + + /** + * The name of the property that indicates which method of the IaaS adapter to call + */ + public static final String CONTEXT_ACTION = "org.onap.appc.action"; + + /** + * The enumerated value for restart of a VM. This is a constant for one possible value of CONTEXT_SERVICE. + */ + public static final String SERVICE_RESTART = "RESTART"; + + /** + * The enumerated value for rebuild of a VM. This is a constant for one possible value of CONTEXT_SERVICE. + */ + public static final String SERVICE_REBUILD = "REBUILD"; + + /** + * The name of the adapter. We get the name from a property file so that it can be changed easily if needed. + */ + public static final String PROPERTY_ADAPTER_NAME = "org.onap.appc.provider.adaptor.name"; + + /** + * The minimum number of contexts to cache in each provider/tenant pool + */ + public static final String PROPERTY_MIN_POOL_SIZE = "org.onap.appc.provider.min.pool"; + + /** + * The maximum number of contexts to cache in each provider/tenant pool + */ + public static final String PROPERTY_MAX_POOL_SIZE = "org.onap.appc.provider.max.pool"; + + /** + * The amount of time, in seconds, that the application waits for a change of state of a server to a known valid + * state before giving up and failing the request. + */ + public static final String PROPERTY_SERVER_STATE_CHANGE_TIMEOUT = "org.onap.appc.server.state.change.timeout"; + + /** + * The amount of time, in seconds, between subsequent polls to the openstack provider to update the state of a + * resource + */ + public static final String PROPERTY_OPENSTACK_POLL_INTERVAL = "org.onap.appc.openstack.poll.interval"; + + /** + * The amount of time, in seconds, to wait between retry attempts when a connection to a provider fails. + */ + public static final String PROPERTY_RETRY_DELAY = "org.onap.appc.provider.retry.delay"; + + /** + * The maximum number of times a connection retry will be attempted before the application fails the request + */ + public static final String PROPERTY_RETRY_LIMIT = "org.onap.appc.provider.retry.limit"; + /** + * The amount of time, in seconds, that the application waits for a change of state of a stacj to a known valid + * state before giving up and failing the request. + */ + public static final String PROPERTY_STACK_STATE_CHANGE_TIMEOUT ="org.onap.appc.stack.state.change.timeout" ; + + @SuppressWarnings("nls") + public static final String STATUS_GETTER = "status-getter"; + + @SuppressWarnings("nls") + public static final String VM_FUSION_STATUS_GETTER = "fusion-vm-status-getter"; + + /** + * The name for the status vm attribute to be set in the context when executing a vmstatuscheck. + */ + @SuppressWarnings("nls") + public static final String STATUS_OF_VM = "status-vm"; + + /** + * Yang revision value to be used while generating YANG module + */ + public static final String YANG_REVISION = "2017-03-03"; + /** + * Yang revision format to be used while formatting YANG revision date + */ + public static final String YANG_REVISION_FORMAT = "YYYY-MM-DD"; + + /** + * Base container for yang that is generated to store in MD-SAL datastore + */ + public static final String YANG_BASE_CONTAINER = "vnf-config-repo"; + + /** + *VNF config list for yang that is generated to store in MD-SAL datastore + */ + public static final String YANG_VNF_CONFIG_LIST = "vnf-config-list"; + + /** + *Base container of VNF configuration data for yang that is generated to store in MD-SAL datastore + */ + public static final String YANG_VNF_CONFIG = "vnf-config"; + + public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + public static final String MDC_SERVICE = "service"; + public static final String MDC_ADAPTER = "adapter"; + + /** + * The constant for a left parenthesis + */ + public static final char LPAREN = '('; + + /** + * The constant for a new line control code + */ + public static final char NL = '\n'; + + /** + * The constant for a single quote + */ + public static final char QUOTE = '\''; + + /** + * The constant for a right parenthesis + */ + public static final char RPAREN = ')'; + + /** + * The constant for a space + */ + public static final char SPACE = ' '; + + /** + * default constructor prevents instantiation + */ + Constants() { + throw new IllegalAccessError("Constants"); + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/Property.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/Property.java new file mode 100644 index 000000000..54acab8e3 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/Property.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modification Copyright (C) 2019 IBM + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas; + +/** + * @since September 26, 2016 + */ +public class Property { + + public static final String PROVIDER = "provider"; + public static final String PROVIDER_IDENTITY = "identity"; + public static final String PROVIDER_TENANT = "tenant"; + public static final String PROVIDER_TENANT_DOMAIN = "domain"; + public static final String PROVIDER_TENANT_NAME = "name"; + public static final String PROVIDER_TENANT_PASSWORD = "password"; + public static final String PROVIDER_TENANT_USERID = "userid"; + public static final String PROVIDER_TYPE = "type"; + public static final String SKIP_HYPERVISOR_CHECK = "org.onap.appc.iaas.skiphypervisorcheck"; + public static final String PAYLOAD = "org.onap.appc.payload"; + + private Property() { + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/ProviderAdapter.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/ProviderAdapter.java new file mode 100644 index 000000000..efc54622d --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/ProviderAdapter.java @@ -0,0 +1,270 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Modifications Copyright © 2018 IBM. + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas; + +import com.att.cdp.zones.model.Image; +import com.att.cdp.zones.model.Server; +import com.att.cdp.zones.model.Stack; +import java.util.Map; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +/** + * This interface defines the operations that the provider adapter exposes. + * <p> + * This interface defines static constant property values that can be used to configure the adapter. These constants are + * prefixed with the name PROPERTY_ to indicate that they are configuration properties. These properties are read from + * the configuration file for the adapter and are used to define the providers, identity service URLs, and other + * information needed by the adapter to interface with an IaaS provider. + * </p> + */ +public interface ProviderAdapter extends SvcLogicJavaPlugin { + /** + * The type of provider to be accessed to locate and operate on a virtual machine instance. This is used to load the + * correct provider support through the CDP IaaS abstraction layer and can be OpenStackProvider, BareMetalProvider, + * or any other supported provider type. + */ + static final String PROPERTY_PROVIDER_TYPE = "org.onap.appc.provider.type"; + /** + * The adapter maintains a cache of providers organized by the name of the provider, not its type. This is + * equivalent to the system or installation name. All regions within the same installation are assumed to be the + * same type. + */ + static final String PROPERTY_PROVIDER_NAME = "org.onap.appc.provider.name"; + /** + * The fully-qualified URL of the instance to be manipulated as it is known to the provider. + */ + static final String PROPERTY_INSTANCE_URL = "org.onap.appc.instance.url"; + /** + * The fully-qualified URL of the instance to be manipulated as it is known to the provider. + */ + static final String PROPERTY_IDENTITY_URL = "org.onap.appc.identity.url"; + /** + * The Rebuild VM flag is an optional payload parameter for the Evacuate API. + */ + static final String PROPERTY_REBUILD_VM = "org.onap.appc.rebuildvm"; + /** + * The target host id is an optional payload parameter for the Evacuate API. + */ + static final String PROPERTY_TARGETHOST_ID = "org.onap.appc.targethost.id"; + /** + * heat stack id to perform operation on stack + */ + static final String PROPERTY_STACK_ID = "org.onap.appc.stack.id"; + static final String PROPERTY_SNAPSHOT_ID = "snapshot.id"; + static final String PROPERTY_INPUT_SNAPSHOT_ID = "org.onap.appc.snapshot.id"; + static final String DG_OUTPUT_PARAM_NAMESPACE = "output."; + static final String SKIP_HYPERVISOR_CHECK = "org.onap.appc.skiphypervisorcheck"; + static final String PAYLOAD = "payload"; + static final String VOLUME_ID = "org.onap.appc.volumeid"; + static final String DEVICE = "org.onap.appc.device"; + static final String REBOOT_TYPE = "org.onap.appc.reboot.type"; + static final String PROPERTY_REQUEST_SNAPSHOT_ID = "snapshot-id"; + /** + * This method is used to restart an existing virtual machine given the fully qualified URL of the machine. + * <p> + * This method is invoked from a directed graph as an <code>Executor</code> node. This means that the parameters + * passed to the method are passed as properties in a map. This method expects the following properties to be + * defined: + * <dl> + * <dt>org.onap.appc.provider.type</dt> + * <dd>The appropriate provider type, such as <code>OpenStackProvider</code>. This is used by the CDP IaaS + * abstraction layer to dynamically load and open a connection to the appropriate provider type. All CDP supported + * provider types are legal.</dd> + * <dt>org.onap.appc.instance.url</dt> + * <dd>The fully qualified URL of the instance to be restarted, as it is known to the provider (i.e., the self-link + * URL of the server)</dd> + * </dl> + * </p> + * + * @param properties A map of name-value pairs that supply the parameters needed by this method. The properties + * needed are defined above. + * @param context The service logic context of the graph being executed. + * @return The <code>Server</code> object that represents the VM being restarted. The returned server object can be + * inspected for the final state of the server once the restart has been completed. The method does not + * return until the restart has either completed or has failed. + * @throws SvcLogicException If the server cannot be restarted for some reason + */ + Server restartServer(Map<String, String> properties, SvcLogicContext context) throws SvcLogicException; + /** + * This method is used to stop the indicated server + * <p> + * This method is invoked from a directed graph as an <code>Executor</code> node. This means that the parameters + * passed to the method are passed as properties in a map. This method expects the following properties to be + * defined: + * <dl> + * <dt>org.onap.appc.provider.type</dt> + * <dd>The appropriate provider type, such as <code>OpenStackProvider</code>. This is used by the CDP IaaS + * abstraction layer to dynamically load and open a connection to the appropriate provider type. All CDP supported + * provider types are legal.</dd> + * <dt>org.onap.appc.instance.url</dt> + * <dd>The fully qualified URL of the instance to be stopped, as it is known to the provider (i.e., the self-link + * URL of the server)</dd> + * </dl> + * </p> + * + * @param properties A map of name-value pairs that supply the parameters needed by this method. The properties + * needed are defined above. + * @param context The service logic context of the graph being executed. + * @return The <code>Server</code> object that represents the VM being stopped. The returned server object can be + * inspected for the final state of the server once the stop has been completed. The method does not return + * until the stop has either completed or has failed. + * @throws SvcLogicException If the server cannot be stopped for some reason + */ + Server stopServer(Map<String, String> properties, SvcLogicContext context) throws SvcLogicException; + /** + * This method is used to start the indicated server + * <p> + * This method is invoked from a directed graph as an <code>Executor</code> node. This means that the parameters + * passed to the method are passed as properties in a map. This method expects the following properties to be + * defined: + * <dl> + * <dt>org.onap.appc.provider.type</dt> + * <dd>The appropriate provider type, such as <code>OpenStackProvider</code>. This is used by the CDP IaaS + * abstraction layer to dynamically load and open a connection to the appropriate provider type. All CDP supported + * provider types are legal.</dd> + * <dt>org.onap.appc.instance.url</dt> + * <dd>The fully qualified URL of the instance to be started, as it is known to the provider (i.e., the self-link + * URL of the server)</dd> + * </dl> + * </p> + * + * @param properties A map of name-value pairs that supply the parameters needed by this method. The properties + * needed are defined above. + * @param context The service logic context of the graph being executed. + * @return The <code>Server</code> object that represents the VM being started. The returned server object can be + * inspected for the final state of the server once the start has been completed. The method does not return + * until the start has either completed or has failed. + * @throws SvcLogicException If the server cannot be started for some reason + */ + Server startServer(Map<String, String> properties, SvcLogicContext context) throws SvcLogicException; + /** + * This method is used to rebuild the indicated server + * <p> + * This method is invoked from a directed graph as an <code>Executor</code> node. This means that the parameters + * passed to the method are passed as properties in a map. This method expects the following properties to be + * defined: + * <dl> + * <dt>org.onap.appc.provider.type</dt> + * <dd>The appropriate provider type, such as <code>OpenStackProvider</code>. This is used by the CDP IaaS + * abstraction layer to dynamically load and open a connection to the appropriate provider type. All CDP supported + * provider types are legal.</dd> + * <dt>org.onap.appc.instance.url</dt> + * <dd>The fully qualified URL of the instance to be rebuilt, as it is known to the provider (i.e., the self-link + * URL of the server)</dd> + * </dl> + * </p> + * + * @param properties A map of name-value pairs that supply the parameters needed by this method. The properties + * needed are defined above. + * @param context The service logic context of the graph being executed. + * @return The <code>Server</code> object that represents the VM being rebuilt. The returned server object can be + * inspected for the final state of the server once the rebuild has been completed. The method does not + * return until the rebuild has either completed or has failed. + * @throws SvcLogicException If the server cannot be rebuilt for some reason + */ + Server rebuildServer(Map<String, String> properties, SvcLogicContext context) throws SvcLogicException; + /** + * This method is used to terminate the indicated server + * <p> + * This method is invoked from a directed graph as an <code>Executor</code> node. This means that the parameters + * passed to the method are passed as properties in a map. This method expects the following properties to be + * defined: + * <dl> + * <dt>org.onap.appc.provider.type</dt> + * <dd>The appropriate provider type, such as <code>OpenStackProvider</code>. This is used by the CDP IaaS + * abstraction layer to dynamically load and open a connection to the appropriate provider type. All CDP supported + * provider types are legal.</dd> + * <dt>org.onap.appc.instance.url</dt> + * <dd>The fully qualified URL of the instance to be terminate, as it is known to the provider (i.e., the self-link + * URL of the server)</dd> + * </dl> + * </p> + * + * @param properties A map of name-value pairs that supply the parameters needed by this method. The properties + * needed are defined above. + * @param context The service logic context of the graph being executed. + * @return The <code>Server</code> object that represents the VM being rebuilt. The returned server object can be + * inspected for the final state of the server once the rebuild has been completed. The method does not + * return until the rebuild has either completed or has failed. + * @throws SvcLogicException If the server cannot be terminate for some reason + */ + Server terminateServer(Map<String, String> properties, SvcLogicContext context) throws SvcLogicException; + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + */ + String getAdapterName(); + Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException; + Server migrateServer(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException; + Server vmStatuschecker(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException; + Stack terminateStack(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException; + Stack snapshotStack(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException; + Stack restoreStack(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException; + Server attachVolume(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException; + Server dettachVolume(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException; + /** + * This method is used to do the lookup of the indicated server + * <p> + * This method is invoked from a directed graph as an <code>Executor</code> node. This means that the parameters + * passed to the method are passed as properties in a map. This method expects the following properties to be + * defined: + * <dl> + * <dt>org.onap.appc.provider.type</dt> + * <dd>The appropriate provider type, such as <code>OpenStackProvider</code>. This is used by the CDP IaaS + * abstraction layer to dynamically load and open a connection to the appropriate provider type. All CDP supported + * provider types are legal.</dd> + * <dt>org.onap.appc.instance.url</dt> + * <dd>The fully qualified URL of the instance to be lookup, as it is known to the provider (i.e., the self-link URL + * of the server)</dd> + * </dl> + * </p> + * + * @param properties A map of name-value pairs that supply the parameters needed by this method. The properties + * needed are defined above. + * @param context The service logic context of the graph being executed. + * @return The <code>Server</code> object that represents the VM being rebuilt. The returned server object can be + * inspected for the final state of the server once the rebuild has been completed. The method does not + * return until the rebuild has either completed or has failed. + * @throws SvcLogicException If the server cannot be found for some reason + */ + Server lookupServer(Map<String, String> properties, SvcLogicContext context) throws SvcLogicException; + /** + * The + * + * @param params A map of name-value pairs that supply the parameters needed by this method. The properties needed + * are defined above. + * @param ctx The service logic context of the graph being executed. + * @return The <code>Image</code> object that represents the VM being restarted. The returned server object can be + * inspected for the final state of the server once the restart has been completed. The method does not + * return until the restart has either completed or has failed. + * @throws SvcLogicException If the server cannot be restarted for some reason + */ + Image createSnapshot(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException; + Server rebootServer(Map<String, String> params, SvcLogicContext context) throws SvcLogicException; +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/IdentityURL.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/IdentityURL.java new file mode 100644 index 000000000..51f0cee8b --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/IdentityURL.java @@ -0,0 +1,145 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.impl; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * This class is used to parse the VM URL returned from OpenStack and extract all of the constituent parts. + */ +public class IdentityURL { + /** + * The regular expression pattern used to parse the URL. Capturing groups are used to identify and extract the + * various component parts of the URL. + */ + private static Pattern pattern = Pattern.compile("(\\p{Alnum}+)://([^/:]+)(?::([0-9]+))?(/.*)?/(v[0-9\\.]+)/?"); + + /** + * The URL scheme or protocol, such as HTTP or HTTPS + */ + private String scheme; + + /** + * The host name or ip address + */ + private String host; + + /** + * The path of the service, or null if no path is defined + */ + private String path; + + /** + * The port number, or null if no port is defined + */ + private String port; + + /** + * The version of the service + */ + private String version; + + /** + * A private default constructor prevents instantiation by any method other than the factory method + * + * @see #parseURL(String) + */ + private IdentityURL() { + + } + + /** + * This static method is used to parse the provided server URL string and return a parse results object (VMURL) + * which represents the state of the parse. + * + * @param identUrl The server URL to be parsed + * @return The VMURL parse results object, or null if the URL was not valid or null. + */ + public static IdentityURL parseURL(String identUrl) { + IdentityURL obj = null; + if (identUrl != null) { + Matcher matcher = pattern.matcher(identUrl.trim()); // http://msb.onap.org:80/api/multicloud/v0/cloudowner_region/identity/v3 + if (matcher.matches()) { // (\\p{Alnum}+)://([^/:]+)(?::([0-9]+))?(/.*)?/(v[0-9\\.]+)/?" + obj = new IdentityURL(); + obj.scheme = matcher.group(1); + obj.host = matcher.group(2); + obj.port = matcher.group(3); + obj.path = matcher.group(4); + obj.version = matcher.group(5); + } + } + + return obj; + } + + /** + * @return The URL scheme + */ + public String getScheme() { + return scheme; + } + + /** + * @return The URL host + */ + public String getHost() { + return host; + } + + /** + * @return The URL path, or null if no path was defined + */ + public String getPath() { + return path; + } + + /** + * @return The URL port, or null if no port was defined + */ + public String getPort() { + return port; + } + + public String getVersion() { + return version; + } + + @Override + public String toString() { + StringBuilder str = new StringBuilder(); + + str.append(scheme + "://" + host); + if (port != null) { + str.append(":" + port); + } + if (path != null) { + str.append(path); + } + str.append("/" + version); + + return str.toString(); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ProviderAdapterImpl.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ProviderAdapterImpl.java new file mode 100644 index 000000000..3f031bfc9 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ProviderAdapterImpl.java @@ -0,0 +1,341 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Modifications Copyright (C) 2019 IBM. + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ +package org.onap.ccsdk.sli.adaptors.iaas.impl; + +import com.att.cdp.zones.model.Image; +import com.att.cdp.zones.model.Server; +import com.att.cdp.zones.model.Stack; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.adaptors.iaas.Property; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.api.IProviderOperation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.api.ProviderOperationFactory; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.EvacuateServer; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.StructuredPropertyHelper; +import org.onap.ccsdk.sli.core.utils.StructuredPropertyHelper.Node; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; + +/** + * This class implements the {@link ProviderAdapter} interface. This interface defines the behaviors that our service + * provides. + * + * @since Aug 12, 2015 + * @version $Id$ + */ +@SuppressWarnings("javadoc") +public class ProviderAdapterImpl implements ProviderAdapter { + /** + * The default domain name for authentication + */ + public static final String DEFAULT_DOMAIN_NAME = "Default"; + /** + * A reference to the adapter configuration object. + */ + private Configuration configuration; + /** + * reference to operation factory + */ + private ProviderOperationFactory factory; + /** + * A cache of providers that are predefined. + */ + private Map<String /* provider name */, ProviderCache> providerCache; + /** + * The username, password, and domain to use for dynamically created connections + */ + private static String defaultUser; + private static String defaultPass; + private static String defaultDomain; + + /** + * This default constructor is used as a work around because the activator wasnt getting called + */ + @SuppressWarnings("all") + public ProviderAdapterImpl() { + initialize(); + + } + /** + * This constructor is used primarily in the test cases to bypass initialization of the adapter for isolated, + * disconnected testing + * + * @param initialize True if the adapter is to be initialized, can false if not + */ + @SuppressWarnings("all") + public ProviderAdapterImpl(boolean initialize) { + configuration = ConfigurationFactory.getConfiguration(); + if (initialize) { + initialize(); + } + } + /** + * @param props not used + */ + public ProviderAdapterImpl(@SuppressWarnings("unused") Properties props) { + initialize(); + + } + @Override + public Server restartServer(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.RESTART_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Server) op.doOperation(params, context); + } + @Override + public Server stopServer(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.STOP_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Server) op.doOperation(params, context); + } + @Override + public Server startServer(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.START_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Server) op.doOperation(params, context); + } + @Override + public Server rebuildServer(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.REBUILD_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Server) op.doOperation(params, context); + } + @Override + public Server terminateServer(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.TERMINATE_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Server) op.doOperation(params, context); + } + @Override + public Server evacuateServer(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.EVACUATE_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + // pass this object's reference to EvacuateServer to allow rebuild after evacuate + ((EvacuateServer) op).setProvideAdapterRef(this); + return (Server) op.doOperation(params, context); + } + @Override + public Server migrateServer(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.MIGRATE_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Server) op.doOperation(params, context); + } + @Override + public Server vmStatuschecker(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.VMSTATUSCHECK_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Server) op.doOperation(params, context); + } + @Override + public Stack terminateStack(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.TERMINATE_STACK); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Stack) op.doOperation(params, context); + } + @Override + public Stack snapshotStack(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.SNAPSHOT_STACK); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Stack) op.doOperation(params, context); + } + @Override + public Stack restoreStack(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.RESTORE_STACK); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Stack) op.doOperation(params, context); + } + @Override + public Server lookupServer(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.LOOKUP_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Server) op.doOperation(params, context); + } + @Override + public Image createSnapshot(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.SNAPSHOT_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Image) op.doOperation(params, context); + } + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + * @see ProviderAdapter#getAdapterName() + */ + @Override + public String getAdapterName() { + return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME); + } + /** + * initialize the provider adapter by building the context cache + */ + private void initialize() { + configuration = ConfigurationFactory.getConfiguration(); + /* + * Initialize the provider cache for all defined providers. The definition of the providers uses a structured + * property set, where the names form a hierarchical name space (dotted notation, such as one.two.three). Each + * name in the name space can also be serialized by appending a sequence number. All nodes at the same level + * with the same serial number are grouped together in the namespace hierarchy. This allows a hierarchical + * multi-valued property to be defined, which can then be used to setup the provider and tenant caches. <p> For + * example, the following definitions show how the namespace hierarchy is defined for two providers, with two + * tenants on the first provider and a single tenant for the second provider. <pre> + * provider1.type=OpenStackProvider provider1.name=ILAB provider1.identity=http://provider1:5000/v2.0 + * provider1.tenant1.name=CDP-ONAP-APPC provider1.tenant1.userid=testUser + * provider1.tenant1.password=testPassword provider1.tenant2.name=TEST-TENANT provider1.tenant2.userid=testUser + * provider1.tenant2.password=testPassword provider2.type=OpenStackProvider provider2.name=PDK1 + * provider2.identity=http://provider2:5000/v2.0 provider2.tenant1.name=someName + * provider2.tenant1.userid=someUser provider2.tenant1.password=somePassword </pre> </p> + */ + factory = ProviderOperationFactory.getInstance(); + providerCache = new HashMap<>(); + Properties properties = configuration.getProperties(); + List<Node> providers = StructuredPropertyHelper.getStructuredProperties(properties, Property.PROVIDER); + for (Node provider : providers) { + ProviderCache cache = new ProviderCache(); + List<Node> providerNodes = provider.getChildren(); + for (Node node : providerNodes) { + if (node.getName().equals(Property.PROVIDER_TYPE)) { + cache.setProviderType(node.getValue()); + } else if (node.getName().equals(Property.PROVIDER_IDENTITY)) { + cache.setIdentityURL(node.getValue()); + cache.setProviderName(node.getValue()); + } else if (node.getName().startsWith(Property.PROVIDER_TENANT)) { + String tenantName = null; + String userId = null; + String password = null; + // domain is not required so set a default + String domain = ProviderAdapterImpl.DEFAULT_DOMAIN_NAME; + for (Node node2 : node.getChildren()) { + switch (node2.getName()) { + case Property.PROVIDER_TENANT_NAME: + tenantName = node2.getValue(); + break; + case Property.PROVIDER_TENANT_USERID: + userId = node2.getValue(); + ProviderAdapterImpl.defaultUser = node2.getValue(); + break; + case Property.PROVIDER_TENANT_PASSWORD: + //The passwords are automatically decrpyted by the appc Configuration + //class and require no additional method calls to decrypt. + password = node2.getValue(); + ProviderAdapterImpl.defaultPass = node2.getValue(); + break; + case Property.PROVIDER_TENANT_DOMAIN: + domain = node2.getValue(); + ProviderAdapterImpl.defaultDomain = node2.getValue(); + break; + default: + break; + } + } + cache.addTenant(null, tenantName, userId, password, domain); + } + } + /* + * Add the provider to the set of providers cached + */ + if (cache.getIdentityURL() != null && cache.getProviderType() != null) { + providerCache.put(null, cache); + providerCache.put(cache.getIdentityURL(), cache); + } + /* + * Now, initialize the cache for the loaded provider + */ + cache.initialize(); + } + } + @Override + public Server attachVolume(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.ATTACHVOLUME_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + return (Server) op.doOperation(params, ctx); + } + @Override + public Server dettachVolume(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.DETACHVOLUME_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + return (Server) op.doOperation(params, ctx); + } + @Override + public Server rebootServer(Map<String, String> params, SvcLogicContext context) throws SvcLogicException { + IProviderOperation op = factory.getOperationObject(Operation.REBOOT_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPassword(defaultPass); + op.setDefaultUser(defaultUser); + op.setDefaultDomain(defaultDomain); + return (Server) op.doOperation(params, context); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ProviderCache.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ProviderCache.java new file mode 100644 index 000000000..a154a14d7 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ProviderCache.java @@ -0,0 +1,166 @@ +/* + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.impl; + +import java.util.HashMap; +import java.util.Map; + +/** + * This class maintains a cache of information by provider, where a provider is identified by both a type and an + * identity URL used to connect to that provider. + * <p> + * Providers may be multi-tenant, such as OpenStack, where the available services and resources vary from one tenant to + * another. Therefore, the provider cache maintains a cache of tenants and the service catalogs for each, as well as the + * credentials used to access the tenants, and a pool of Context objects for each tenant. The context pool allows use of + * the CDP abstraction layer to access the services of the provider within the specific tenant. + * </p> + */ +public class ProviderCache { + + /** + * The type of provider (e.g., OpenStackProvider) used to setup the CDP abstraction layer and load the appropriate + * support + */ + private String providerType; + + /** + * The URL of the provider's identity service or whatever service is used to login and authenticate to the provider + */ + private String identityURL; + + /** + * A string used to identify the provider instance + */ + private String providerName; + + /** + * The map of tenant cache objects by tenant id + */ + private Map<String /* tenant id */, TenantCache> tenants = new HashMap<>(); + + /** + * @return the value of providerType + */ + public String getProviderType() { + return providerType; + } + + /** + * This method is called to initialize the provider cache, set up the context pools for each of the tenants, + * discover all of the regions supported on the provider, and load all of the service catalogs for each provider. + */ + public void initialize() { + for (Map.Entry<String, TenantCache> entry : tenants.entrySet()) { + entry.getValue().initialize(); + } + } + + /** + * @param providerType the value for providerType + */ + public void setProviderType(String providerType) { + this.providerType = providerType; + } + + /** + * @return the value of identityURL + */ + public String getIdentityURL() { + return identityURL; + } + + /** + * @param identityURL the value for identityURL + */ + public void setIdentityURL(String identityURL) { + this.identityURL = identityURL; + } + + /** + * @return the value of providerName + */ + public String getProviderName() { + return providerName; + } + + /** + * @param providerName the value for providerName + */ + public void setProviderName(String providerName) { + this.providerName = providerName; + } + + /** + * @return the value of tenants + */ + public Map<String, TenantCache> getTenants() { + return tenants; + } + + /** + * This method is a helper to return a specific TenantCache + * + * @param tenantId + * @return + */ + public TenantCache getTenant(String tenantId) { + return tenants.get(tenantId); + } + + // Previously there was no way to add additional tenants to the tenant cache + /** + * This method is used to add a tenant to the provider cache + * + * @param tenantId + * @param tenantName + * @param userId + * @param password + * @param domain + * @return the new initialized TenantCache or null if unsuccessful + */ + public TenantCache addTenant(String tenantId, String tenantName, String userId, String password, String domain) { + if (tenantId != null || tenantName != null && userId != null && password != null) { + TenantCache tenant = new TenantCache(this); + if (tenantId != null) { + tenant.setTenantId(tenantId); + } + if (tenantName != null) { + tenant.setTenantName(tenantName); + } + tenant.setUserid(userId); + tenant.setPassword(password); + tenant.setDomain(domain); + + if (identityURL != null) { + tenant.initialize(); + } + + if (tenant.isInitialized()) { + tenants.put(tenant.getTenantId(), tenant); + return tenant; + } + } + return null; + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/RequestContext.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/RequestContext.java new file mode 100644 index 000000000..374755a29 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/RequestContext.java @@ -0,0 +1,245 @@ +/* + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.impl; + +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; + +/** + * This class is used to track and maintain recovery and time-to-live information for a request as it is being + * processed. + */ +public class RequestContext { + /** + * The number of seconds of wait time between successive attempts to connect to the provider. This is used to + * recover from provider outages or failures. It is not used to recover from logical errors, such as an invalid + * request, server not found, etc. + */ + private Integer retryDelay; + + /** + * The number of times we will attempt to connect to the provider. This is used to recover from provider outages or + * failures. It is not used to recover from logical errors, such as an invalid request, server not found, etc. + */ + private Integer retryLimit; + + /** + * The total time, in milliseconds, that the provider can have to process this request. If the accumulated time + * exceeds the time to live, then the request is failed with a timeout exception, regardless of the state of the + * provider. Note that the caller may supply this as a value in seconds, in which case it must be converted to + * milliseconds for the request context. + */ + private Long timeToLive; + + /** + * The accumulated time, in milliseconds, that has been used so far to process the request. This is compared to the + * time to live each time it is updated. If the accumulated time exceeds the time to live, then the request is + * failed with a timeout exception, regardless of the state of the provider. + */ + private long accumulatedTime; + + /** + * The total number of retries attempted so far + */ + private int attempt; + + /** + * The time when the stopwatch was started + */ + private long startTime = -1; + + /** + * The service logic (DG) context from the SLI + */ + private SvcLogicContext svcLogicContext; + + /** + * The configuration + */ + private Configuration configuration = ConfigurationFactory.getConfiguration(); + + /** + * Set to true whenever the retry limit has been exceeded, reset to false when reset() is called. + */ + private boolean retryFailed; + + /** + * Creates the request context + * + * @param context The service logic (SLI) context associated with the current DG + */ + public RequestContext(SvcLogicContext context) { + setSvcLogicContext(context); + } + + /** + * @return The retry delay, in seconds. If zero, then no retry is to be performed + */ + public int getRetryDelay() { + if (retryDelay == null) { + int value = configuration.getIntegerProperty(Constants.PROPERTY_RETRY_DELAY); + retryDelay = Integer.valueOf(value); + } + + return retryDelay.intValue(); + } + + /** + * This method is a helper that allows the caller to delay for the retry interval time and not have to handle the + * thread interruption, timer handling, etc. + */ + public void delay() { + long time = getRetryDelay() * 1000L; + long future = System.currentTimeMillis() + time; + if (time != 0) { + while (System.currentTimeMillis() < future && time > 0) { + try { + Thread.sleep(time); + } catch (InterruptedException e) { + /* + * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that + * case, the thread is resumed before the delay time has actually expired, so re-calculate the + * amount of delay time needed and reenter the sleep until we get to the future time. + */ + time = future - System.currentTimeMillis(); + Thread.currentThread().interrupt(); + } + } + } + } + + /** + * @return The number of retries that are allowed per connection + */ + public int getRetryLimit() { + if (retryLimit == null) { + int value = configuration.getIntegerProperty(Constants.PROPERTY_RETRY_LIMIT); + retryLimit = Integer.valueOf(value); + } + + return retryLimit.intValue(); + } + + /** + * Check and count the connection attempt. + * + * @return True if the connection should be attempted. False indicates that the number of retries has been exhausted + * and it should NOT be attempted. + */ + public boolean attempt() { + if (retryFailed || attempt >= getRetryLimit()) { + retryFailed = true; + return false; + } + attempt++; + + return true; + } + + /** + * @return The number of retry attempts so far + */ + public int getAttempts() { + return attempt; + } + + /** + * @return True if the retry limit has been exceeded, false otherwise + */ + public boolean isFailed() { + return retryFailed; + } + + /** + * This method both checks the time to live to see if it has been exceeded and accumulates the total time used so + * far. + * <p> + * Each time this method is called it accumulates the total duration since the last time it was called to the total + * time accumulator. It then checks the total time to the time to live and if greater, it returns false. As long as + * the total time used is less than or equal to the time to live limit, the method returns true. It is important to + * call this method at the very beginning of the process so that all parts of the process are tracked. + * </p> + * + * @return True if the total time to live has not been exceeded. False indicates that the total time to live has + * been exceeded and no further processing should be performed. + */ + public boolean isAlive() { + long now = System.currentTimeMillis(); + if (startTime == -1) { + startTime = now; + return true; + } + accumulatedTime += (now - startTime); + startTime = now; + return accumulatedTime <= timeToLive; + } + + /** + * @return The total amount of time used, in milliseconds. + */ + public long getTotalDuration() { + return accumulatedTime; + } + + /** + * This method is called to reset the retry counters. It has no effect on the time to live accumulator. + */ + public void reset() { + attempt = 0; + } + + /** + * Sets the time to live to the value, expressed in seconds + * + * @param time The time to live, in seconds + */ + public void setTimeToLiveSeconds(int time) { + setTimeToLiveMS(time * 1000L); + } + + /** + * Sets the time to live to the value, expressed in milliseconds + * + * @param time The time to live, in milliseconds + */ + public void setTimeToLiveMS(long time) { + this.timeToLive = time; + } + + /** + * @return The service logic context associated with this request + */ + public SvcLogicContext getSvcLogicContext() { + return svcLogicContext; + } + + /** + * @param svcLogicContext The service logic context to be associated with this request + */ + public void setSvcLogicContext(SvcLogicContext svcLogicContext) { + this.svcLogicContext = svcLogicContext; + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/RequestFailedException.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/RequestFailedException.java new file mode 100644 index 000000000..30bdf218c --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/RequestFailedException.java @@ -0,0 +1,256 @@ +/* + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Modification Copyright (C) 2017 IBM + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.impl; + +import com.att.cdp.zones.model.Server; +import com.att.cdp.zones.model.Stack; +import org.glassfish.grizzly.http.util.HttpStatus; + +/** + * This class is used to capture the exact cause and point of failure for the processing of a request. It is then used + * to encode the reason for the failure, status code, and anything else that needs to be captured and reported for + * diagnostic purposes. + */ +public class RequestFailedException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * The operation that was being requested or performed at the time of the failure. + */ + private String operation; + + /** + * A message that details the reason for the failure + */ + private String reason; + + /** + * The server that was being operated upon + */ + private Server server; + + /** + * The stack that was being operated upon + */ + private Stack stack; + /** + * The id of the server being operated upon if the server object is not available (such as the server was not found) + */ + private String serverId; + + /** + * The id of the stack being operated upon if the stack object is not available (such as the stack was not found) + */ + private String stackId; + /** + * The most appropriate Http Status code that reflects the error + */ + private transient HttpStatus status; + + /** + * + */ + public RequestFailedException() { + // intentionally empty + } + + /** + * @param message The error message + */ + public RequestFailedException(String message) { + super(message); + } + + /** + * Construct the request failed exception with the operation being performed, reason for the failure, http status + * code that is most appropriate, and the server we were processing. + * + * @param operation The operation being performed + * @param reason The reason that the operation was failed + * @param status The http status code that is most appropriate + * @param server The server that we were processing + */ + @SuppressWarnings("nls") + public RequestFailedException(String operation, String reason, HttpStatus status, Server server) { + super(operation + ":" + reason); + this.operation = operation; + this.reason = reason; + this.status = status; + this.server = server; + if (server != null) { + this.serverId = server.getId(); + } + } + + + /** + * Construct the request failed exception with the operation being performed, reason for the failure, http status + * code that is most appropriate, and the stack we were processing. + * + * @param operation The operation being performed + * @param reason The reason that the operation was failed + * @param status The http status code that is most appropriate + * @param stack The stack that we were processing + */ + @SuppressWarnings("nls") + public RequestFailedException(String operation, String reason, HttpStatus status, Stack stack) { + super(operation + ":" + reason); + this.operation = operation; + this.reason = reason; + this.status = status; + this.stack = stack; + if (stack != null) { + this.stackId = stack.getId(); + } + } + + /** + * Construct the request failed exception with the operation being performed, reason for the failure, http status + * code that is most appropriate, and the server we were processing. + * + * @param ex The exception that we are wrapping + * @param operation The operation being performed + * @param reason The reason that the operation was failed + * @param status The http status code that is most appropriate + * @param server The server that we were processing + */ + @SuppressWarnings("nls") + public RequestFailedException(Throwable ex, String operation, String reason, HttpStatus status, Server server) { + super(operation + ":" + reason, ex); + this.operation = operation; + this.reason = reason; + this.status = status; + this.server = server; + if (server != null) { + this.serverId = server.getId(); + } + } + + /** + * @param message The error message + * @param cause A nested exception + */ + public RequestFailedException(String message, Throwable cause) { + super(message, cause); + } + + /** + * @param message The error message + * @param cause A nested exception + * @param enableSuppression whether or not suppression is enabled or disabled + * @param writableStackTrace whether or not the stack trace should be writable + */ + public RequestFailedException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + /** + * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or unknown.) + */ + public RequestFailedException(Throwable cause) { + super(cause); + } + + /** + * @return The operation being performed + */ + public String getOperation() { + return operation; + } + + /** + * @return The reason for the failure + */ + public String getReason() { + return reason; + } + + /** + * @return The server being operated upon + */ + public Server getServer() { + return server; + } + + /** + * @return The id of the server being operated upon + */ + public String getServerId() { + return serverId; + } + + /** + * @return The status code from the operation + */ + public HttpStatus getStatus() { + return status; + } + + /** + * @param operation The operation being performed + */ + public void setOperation(String operation) { + this.operation = operation; + } + + /** + * @param reason The reason for the failure + */ + public void setReason(String reason) { + this.reason = reason; + } + + /** + * @param server The server being operated upon + */ + public void setServer(Server server) { + this.server = server; + if (server != null) { + setServerId(server.getId()); + } + } + + /** + * @param serverId The id of the server being operated upon + */ + public void setServerId(String serverId) { + this.serverId = serverId; + } + + /** + * @param status The status of the request + */ + public void setStatus(HttpStatus status) { + this.status = status; + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ServiceCatalog.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ServiceCatalog.java new file mode 100644 index 000000000..2e4453f4b --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ServiceCatalog.java @@ -0,0 +1,306 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.impl; + +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.spi.AbstractService.State; +import com.att.cdp.zones.spi.RequestState; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * This class is used to capture and cache the service catalog for a specific OpenStack provider. + * <p> + * This is needed because the way the servers are represented in the ECOMP product is as their fully qualified URL's. + * This is very problematic, because we cant identify their region from the URL, URL's change, and we cant identify the + * versions of the service implementations. In otherwords, the URL does not provide us enough information. + * </p> + * <p> + * The zone abstraction layer is designed to detect the versions of the services dynamically, and step up or down to + * match those reported versions. In order to do that, we need to know before hand what region we are accessing (since + * the supported versions may be different by regions). We will need to authenticate to the identity service in order to + * do this, plus we have to duplicate the code supporting proxies and trusted hosts that exists in the abstraction + * layer, but that cant be helped. + * </p> + * <p> + * What we do to circumvent this is connect to the provider using the lowest supported identity api, and read the entire + * service catalog into this object. Then, we parse the vm URL to extract the host and port and match that to the + * compute services defined in the catalog. When we find a compute service that has the same host name and port, + * whatever region that service is supporting is the region for that server. + * </p> + * <p> + * While we really only need to do this for compute nodes, there is no telling what other situations may arise where the + * full service catalog may be needed. Also, there is very little additional cost (additional RAM) associated with + * caching the full service catalog since there is no way to list only a portion of it. + * </p> + */ +public abstract class ServiceCatalog { + /** + * The openstack connector version to use + */ + public static final String CLIENT_CONNECTOR_CLASS = "com.woorea.openstack.connector.JaxRs20Connector"; + + /** + * The service name for the compute service endpoint + */ + public static final String COMPUTE_SERVICE = "compute"; //$NON-NLS-1$ + + /** + * The default domain for authentication + */ + public static final String DEFAULT_DOMAIN = "Default"; + /** + * The service name for the identity service endpoint + */ + public static final String IDENTITY_SERVICE = "identity"; //$NON-NLS-1$ + + /** + * The service name for the compute service endpoint + */ + public static final String IMAGE_SERVICE = "image"; //$NON-NLS-1$ + + /** + * The service name for the metering service endpoint + */ + public static final String METERING_SERVICE = "metering"; //$NON-NLS-1$ + + /** + * The service name for the network service endpoint + */ + public static final String NETWORK_SERVICE = "network"; //$NON-NLS-1$ + + /** + * The service name for the persistent object service endpoint + */ + public static final String OBJECT_SERVICE = "object-store"; //$NON-NLS-1$ + + /** + * The service name for the orchestration service endpoint + */ + public static final String ORCHESTRATION_SERVICE = "orchestration"; //$NON-NLS-1$ + + /** + * The service name for the volume service endpoint + */ + public static final String VOLUME_SERVICE = "volume"; //$NON-NLS-1$ + + /** + * The logger to be used + */ + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(ServiceCatalog.class); + + /** + * The password for authentication + */ + protected String credential; + + /** + * The domain for authentication + */ + protected String domain; + /** + * The time (local) that the token expires and we need to re-authenticate + */ + protected long expiresLocal; + + /** + * The url of the identity service + */ + protected String identityURL; + + /** + * The user id for authentication + */ + protected String principal; + + /** + * The project or tenant identifier + */ + protected String projectIdentifier; + + /** + * Properties for proxy information + */ + protected Properties properties; + + /** + * The set of all regions that have been defined + */ + protected Set<String> regions; + + /** + * The read/write lock used to protect the cache contents + */ + protected ReadWriteLock rwLock; + + /** + * Create the ServiceCatalog cache + * + * @param identityURL The identity service URL to connect to + * @param projectIdentifier The name or id of the tenant to authenticate with. If the ID is a UUID format + * (32-character hexadecimal string), then the authentication is done using the tenant ID, otherwise it is + * done using the name. + * @param principal The user id to authenticate to the provider + * @param credential The password to authenticate to the provider + * @param properties Additional properties used to configure the connection, such as proxy and trusted hosts lists + * @throws ZoneException + * @throws ClassNotFoundException + * @throws IllegalAccessException + * @throws InstantiationException + */ + public ServiceCatalog(String identityURL, String projectIdentifier, String principal, String credential, + String domain, Properties properties) { + this.identityURL = identityURL; + this.projectIdentifier = projectIdentifier; + this.principal = principal; + this.credential = credential; + this.domain = domain; + this.properties = properties; + rwLock = new ReentrantReadWriteLock(); + regions = new HashSet<>(); + } + + /** + * Returns the list of service endpoints for the published service type + * + * @param serviceType The service type to obtain the endpoints for + * @return The list of endpoints for the service type, or null if none exist + */ + public abstract List<?> getEndpoints(String serviceType); + + /** + * @return The project or tenant id + */ + public abstract String getProjectId(); + + /** + * @return The project or tenant name + */ + public abstract String getProjectName(); + + /** + * @return The set of all regions that are defined + */ + public Set<String> getRegions() { + Lock readLock = rwLock.readLock(); + readLock.lock(); + try { + return regions; + } finally { + readLock.unlock(); + } + } + + /** + * @return A list of service types that are published + */ + public abstract List<String> getServiceTypes(); + + /** + * This method accepts a fully qualified compute node URL and uses that to determine which region of the provider + * hosts that compute node. + * + * @param url The parsed URL of the compute node + * @return The region name, or null if no region of this tenant hosts that compute node. + */ + public abstract String getVMRegion(VMURL url); + + /** + * Returns an indication if the specified service type is published by this provider + * + * @param serviceType The service type to check for + * @return True if a service of that type is published + */ + public abstract boolean isServicePublished(String serviceType); + + /** + * Load the Service Catalog from the specified provider + * + * @throws ZoneException + */ + public abstract void init() throws ZoneException; + + /** + * This method is used to provide a diagnostic listing of the service catalog + * + * @see java.lang.Object#toString() + */ + @Override + public abstract String toString(); + + /** + * Initializes the request state for the current requested service. + * <p> + * This method is used to track requests made to the various service implementations and to provide additional + * information for diagnostic purposes. The <code>RequestState</code> class stores the state in thread-local storage + * and is available to all code on that thread. + * </p> + * <p> + * This method first obtains the stack trace and scans the stack backward for the call to this method. It then backs + * up one more call and assumes that method is the request that we are "tracking". + * </p> + * + * @param states A variable argument list of additional state values that the caller wants to add to the request + * state thread-local object to track the context. + */ + protected void trackRequest(State... states) { + RequestState.clear(); + + for (State state : states) { + RequestState.put(state.getName(), state.getValue()); + } + + Thread currentThread = Thread.currentThread(); + StackTraceElement[] stack = currentThread.getStackTrace(); + if (stack != null && stack.length > 0) { + int index = 0; + StackTraceElement element = null; + for (; index < stack.length; index++) { + element = stack[index]; + if ("trackRequest".equals(element.getMethodName())) { //$NON-NLS-1$ + break; + } + } + index++; + + if (index < stack.length) { + element = stack[index]; + RequestState.put(RequestState.METHOD, element.getMethodName()); + RequestState.put(RequestState.CLASS, element.getClassName()); + RequestState.put(RequestState.LINE_NUMBER, Integer.toString(element.getLineNumber())); + RequestState.put(RequestState.THREAD, currentThread.getName()); + // RequestState.put(RequestState.PROVIDER, context.getProvider().getName()); + // RequestState.put(RequestState.TENANT, context.getTenantName()); + // RequestState.put(RequestState.PRINCIPAL, context.getPrincipal()); + } + } + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ServiceCatalogFactory.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ServiceCatalogFactory.java new file mode 100644 index 000000000..2852d0314 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ServiceCatalogFactory.java @@ -0,0 +1,62 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.ccsdk.sli.adaptors.iaas.impl;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import java.util.Properties;
+
+public class ServiceCatalogFactory {
+
+ private static EELFLogger logger = EELFManager.getInstance().getLogger(ServiceCatalogFactory.class);
+
+ /**
+ * This method accepts a fully qualified identity service URL and uses that to determine which version of the
+ * serviceCatalog to load.
+ *
+ * @param url The parsed URL of the identity service
+ * @param projectIdentifier The project or tenant to be used to connect to the service
+ * @param principal The principal or user to be used to connect to the service
+ * @param credential The credential or password to be used to connect to the service
+ * @param properties Properties object for proxy information
+ * @return The serviceCatalog for identity service version specified in the url, null if not supported.
+ */
+ public static ServiceCatalog getServiceCatalog(String url, String projectIdentifier, String principal,
+ String credential, String domain, Properties properties) {
+ IdentityURL idUrl = IdentityURL.parseURL(url);
+ if(idUrl == null){
+ logger.error("Url " + url + " could not be parsed.");
+ return null;
+ }
+ String version = idUrl.getVersion();
+ String prefix = version.split("\\.")[0];
+ if("v2".equals(prefix)){
+ return new ServiceCatalogV2(url, projectIdentifier, principal, credential, properties);
+ }
+ else if("v3".equals(prefix)){
+ return new ServiceCatalogV3(url, projectIdentifier, principal, credential, domain, properties);
+ }
+ return null;
+ }
+}
diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ServiceCatalogV2.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ServiceCatalogV2.java new file mode 100644 index 000000000..37b024b4e --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ServiceCatalogV2.java @@ -0,0 +1,392 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * ================================================================================
+ * Modifications Copyright (C) 2019 Ericsson
+ * =============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.ccsdk.sli.adaptors.iaas.impl;
+
+import com.att.cdp.exceptions.ContextConnectionException;
+import com.att.cdp.exceptions.ZoneException;
+import com.att.cdp.openstack.util.ExceptionMapper;
+import com.att.cdp.pal.util.Time;
+import com.att.cdp.zones.ContextFactory;
+import com.att.cdp.zones.spi.RequestState;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.woorea.openstack.base.client.OpenStackBaseException;
+import com.woorea.openstack.base.client.OpenStackClientConnector;
+import com.woorea.openstack.base.client.OpenStackSimpleTokenProvider;
+import com.woorea.openstack.keystone.Keystone;
+import com.woorea.openstack.keystone.api.TokensResource;
+import com.woorea.openstack.keystone.model.Access;
+import com.woorea.openstack.keystone.model.Access.Service;
+import com.woorea.openstack.keystone.model.Access.Service.Endpoint;
+import com.woorea.openstack.keystone.model.Authentication;
+import com.woorea.openstack.keystone.model.Tenant;
+import com.woorea.openstack.keystone.model.authentication.UsernamePassword;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.locks.Lock;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * This class is used to capture and cache the service catalog for a specific OpenStack provider.
+ * <p>
+ * This is needed because the way the servers are represented in the ECOMP product is as their fully qualified URL's.
+ * This is very problematic, because we cant identify their region from the URL, URL's change, and we cant identify the
+ * versions of the service implementations. In otherwords, the URL does not provide us enough information.
+ * </p>
+ * <p>
+ * The zone abstraction layer is designed to detect the versions of the services dynamically, and step up or down to
+ * match those reported versions. In order to do that, we need to know before hand what region we are accessing (since
+ * the supported versions may be different by regions). We will need to authenticate to the identity service in order to
+ * do this, plus we have to duplicate the code supporting proxies and trusted hosts that exists in the abstraction
+ * layer, but that cant be helped.
+ * </p>
+ * <p>
+ * What we do to circumvent this is connect to the provider using the lowest supported identity api, and read the entire
+ * service catalog into this object. Then, we parse the vm URL to extract the host and port and match that to the
+ * compute services defined in the catalog. When we find a compute service that has the same host name and port,
+ * whatever region that service is supporting is the region for that server.
+ * </p>
+ * <p>
+ * While we really only need to do this for compute nodes, there is no telling what other situations may arise where the
+ * full service catalog may be needed. Also, there is very little additional cost (additional RAM) associated with
+ * caching the full service catalog since there is no way to list only a portion of it.
+ * </p>
+ */
+public class ServiceCatalogV2 extends ServiceCatalog {
+
+ protected static final EELFLogger loggerV2 = EELFManager.getInstance().getLogger(ServiceCatalogV2.class);
+
+ /**
+ * The Openstack Access object that manages the authenticated token and access control
+ */
+ private Access access;
+
+ /**
+ * A map of endpoints for each service organized by service type
+ */
+ private Map<String /* Service Type */, List<Service.Endpoint>> serviceEndpoints;
+
+ /**
+ * A map of service types that are published
+ */
+ private Map<String /* Service Type */, Service> serviceTypes;
+
+ /**
+ * The tenant that we are accessing
+ */
+ private Tenant tenant;
+
+ /**
+ * A "token provider" that manages the authentication token that we obtain when logging in
+ */
+ private OpenStackSimpleTokenProvider tokenProvider;
+
+ public ServiceCatalogV2(String identityURL, String tenantIdentifier, String principal, String credential,
+ Properties properties) {
+ super(identityURL, tenantIdentifier, principal, credential, null, properties);
+ }
+
+ @Override
+ public void init() throws ZoneException {
+ serviceTypes = new HashMap<>();
+ serviceEndpoints = new HashMap<>();
+ Class<?> connectorClass;
+ OpenStackClientConnector connector;
+ try {
+ connectorClass = Class.forName(CLIENT_CONNECTOR_CLASS);
+ connector = (OpenStackClientConnector) connectorClass.newInstance();
+ } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
+ loggerV2.error(e.getMessage());
+ return;
+ }
+ Keystone keystone = getKeystone(identityURL, connector);
+
+ String proxyHost = properties.getProperty(ContextFactory.PROPERTY_PROXY_HOST);
+ String proxyPort = properties.getProperty(ContextFactory.PROPERTY_PROXY_PORT);
+ String trustedHosts = properties.getProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, ""); //$NON-NLS-1$
+ if (proxyHost != null && proxyHost.length() > 0) {
+ keystone.getProperties().setProperty(com.woorea.openstack.common.client.Constants.PROXY_HOST, proxyHost);
+ keystone.getProperties().setProperty(com.woorea.openstack.common.client.Constants.PROXY_PORT, proxyPort);
+ }
+ if (trustedHosts != null) {
+ keystone.getProperties().setProperty(com.woorea.openstack.common.client.Constants.TRUST_HOST_LIST,
+ trustedHosts);
+ }
+
+ Authentication authentication = new UsernamePassword(principal, credential);
+ TokensResource tokens = keystone.tokens();
+ TokensResource.Authenticate authenticate = tokens.authenticate(authentication);
+ if (projectIdentifier.length() == 32 && projectIdentifier.matches("[0-9a-fA-F]+")) { //$NON-NLS-1$
+ authenticate = authenticate.withTenantId(projectIdentifier);
+ } else {
+ authenticate = authenticate.withTenantName(projectIdentifier);
+ }
+
+ /*
+ * We have to set up the TrackRequest TLS collection for the ExceptionMapper
+ */
+ trackRequest();
+ RequestState.put(RequestState.PROVIDER, "OpenStackProvider");
+ RequestState.put(RequestState.TENANT, projectIdentifier);
+ RequestState.put(RequestState.PRINCIPAL, principal);
+
+ try {
+ access = authenticate.execute();
+ //Ensure that access or the access token is not null before
+ //checking local expiration or accessing the tenant information
+ if (access == null || access.getToken() == null) {
+ throw new NullPointerException("The access key used to access the provider or access token is null." +
+ "Failed to init ServiceCatalogV2");
+ }
+ expiresLocal = getLocalExpiration(access);
+ tenant = access.getToken().getTenant();
+ tokenProvider = new OpenStackSimpleTokenProvider(access.getToken().getId());
+ keystone.setTokenProvider(tokenProvider);
+ parseServiceCatalog(access.getServiceCatalog());
+ } catch (OpenStackBaseException e) {
+ ExceptionMapper.mapException(e);
+ } catch (Exception ex) {
+ throw new ContextConnectionException(ex.getMessage());
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<Service.Endpoint> getEndpoints(String serviceType) {
+ Lock readLock = rwLock.readLock();
+ readLock.lock();
+ try {
+ return serviceEndpoints.get(serviceType);
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String getProjectId() {
+ Lock readLock = rwLock.readLock();
+ readLock.lock();
+ try {
+ return tenant.getId();
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String getProjectName() {
+ Lock readLock = rwLock.readLock();
+ readLock.lock();
+ try {
+ return tenant.getName();
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Set<String> getRegions() {
+ Lock readLock = rwLock.readLock();
+ readLock.lock();
+ try {
+ return regions;
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<String> getServiceTypes() {
+ Lock readLock = rwLock.readLock();
+ readLock.lock();
+ try {
+ ArrayList<String> result = new ArrayList<>();
+ result.addAll(serviceTypes.keySet());
+ return result;
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String getVMRegion(VMURL url) {
+ String region = null;
+ if (url == null) {
+ return region;
+ }
+
+ Pattern urlPattern = Pattern.compile("[^:]+://([^:/]+)(?::([0-9]+)).*");
+
+ for (Endpoint endpoint : getEndpoints(ServiceCatalog.COMPUTE_SERVICE)) {
+ String endpointUrl = endpoint.getPublicURL();
+ Matcher matcher = urlPattern.matcher(endpointUrl);
+ if (!matcher.matches() ||
+ !url.getHost().equals(matcher.group(1)) ||
+ (url.getPort() != null && !url.getPort().equals(matcher.group(2))) ) {
+ continue;
+ }
+
+ region = endpoint.getRegion();
+ break;
+ }
+
+ return region;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean isServicePublished(String serviceType) {
+ Lock readLock = rwLock.readLock();
+ readLock.lock();
+ try {
+ return serviceTypes.containsKey(serviceType);
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String toString() {
+
+ StringBuilder builder = new StringBuilder();
+ Lock lock = rwLock.readLock();
+ lock.lock();
+ try {
+ builder.append(String.format("Service Catalog: tenant %s, id[%s], description[%s]%n", tenant.getName(), //$NON-NLS-1$
+ tenant.getId(), tenant.getDescription()));
+ if (regions != null && !regions.isEmpty()) {
+ builder.append(String.format("%d regions:%n", regions.size())); //$NON-NLS-1$
+ for (String region : regions) {
+ builder.append("\t" + region + "%n"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ builder.append(String.format("%d services:%n", serviceEndpoints.size())); //$NON-NLS-1$
+ for(Map.Entry<String, List<Access.Service.Endpoint>> entry : serviceEndpoints.entrySet()){
+ List<Service.Endpoint> endpoints = entry.getValue();
+ Service service = serviceTypes.get(entry.getKey());
+
+ builder.append(String.format("\t%s [%s] - %d endpoints%n", service.getType(), service.getName(), //$NON-NLS-1$
+ endpoints.size()));
+ for (Service.Endpoint endpoint : endpoints) {
+ builder.append(String.format("\t\tRegion [%s], public URL [%s]%n", endpoint.getRegion(), //$NON-NLS-1$
+ endpoint.getPublicURL()));
+ }
+ }
+ } finally {
+ lock.unlock();
+ }
+
+ return builder.toString();
+ }
+
+ /**
+ * Parses the service catalog and caches the results
+ *
+ * @param services The list of services published by this provider
+ */
+ private void parseServiceCatalog(List<Service> services) {
+ Lock lock = rwLock.writeLock();
+ lock.lock();
+ try {
+ serviceTypes.clear();
+ serviceEndpoints.clear();
+ regions.clear();
+
+ for (Service service : services) {
+ String type = service.getType();
+ serviceTypes.put(type, service);
+
+ List<Service.Endpoint> endpoints = service.getEndpoints();
+ for (Service.Endpoint endpoint : endpoints) {
+ List<Service.Endpoint> endpointList = serviceEndpoints.get(type);
+ if (endpointList == null) {
+ endpointList = new ArrayList<>();
+ serviceEndpoints.put(type, endpointList);
+ }
+ endpointList.add(endpoint);
+
+ String region = endpoint.getRegion();
+ if (!regions.contains(region)) {
+ regions.add(region);
+ }
+ }
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * Computes the local time when the access token will expire, after which we will need to re-login to access the
+ * provider.
+ *
+ * @param accessKey The access key used to access the provider
+ * @return The local time the key expires
+ */
+ private static long getLocalExpiration(Access accessKey) {
+ Date now = Time.getCurrentUTCDate();
+ Calendar issued = accessKey.getToken().getIssued_at();
+ Calendar expires = accessKey.getToken().getExpires();
+ if (issued != null && expires != null) {
+ long tokenLife = expires.getTimeInMillis() - issued.getTimeInMillis();
+ return now.getTime() + tokenLife;
+ }
+ return now.getTime();
+ }
+
+ protected Keystone getKeystone(String identityUrl, OpenStackClientConnector connector) {
+ return new Keystone(identityURL, connector);
+ }
+}
diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ServiceCatalogV3.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ServiceCatalogV3.java new file mode 100644 index 000000000..7e4ee167b --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/ServiceCatalogV3.java @@ -0,0 +1,420 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * Modifications Copyright © 2018 IBM.
+ * ================================================================================
+ * Modifications Copyright (C) 2019 Ericsson
+ * =============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.ccsdk.sli.adaptors.iaas.impl;
+
+import com.att.cdp.exceptions.ContextConnectionException;
+import com.att.cdp.exceptions.ZoneException;
+import com.att.cdp.openstack.util.ExceptionMapper;
+import com.att.cdp.pal.util.Time;
+import com.att.cdp.zones.ContextFactory;
+import com.att.cdp.zones.spi.RequestState;
+import com.woorea.openstack.base.client.OpenStackBaseException;
+import com.woorea.openstack.base.client.OpenStackClientConnector;
+import com.woorea.openstack.base.client.OpenStackSimpleTokenProvider;
+import com.woorea.openstack.keystone.v3.Keystone;
+import com.woorea.openstack.keystone.v3.api.TokensResource;
+import com.woorea.openstack.keystone.v3.model.Authentication;
+import com.woorea.openstack.keystone.v3.model.Authentication.Identity;
+import com.woorea.openstack.keystone.v3.model.Authentication.Scope;
+import com.woorea.openstack.keystone.v3.model.Token;
+import com.woorea.openstack.keystone.v3.model.Token.Project;
+import com.woorea.openstack.keystone.v3.model.Token.Service;
+import com.woorea.openstack.keystone.v3.model.Token.Service.Endpoint;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * This class is used to capture and cache the service catalog for a specific OpenStack provider.
+ * <p>
+ * This is needed because the way the servers are represented in the ECOMP product is as their fully qualified URL's.
+ * This is very problematic, because we cant identify their region from the URL, URL's change, and we cant identify the
+ * versions of the service implementations. In otherwords, the URL does not provide us enough information.
+ * </p>
+ * <p>
+ * The zone abstraction layer is designed to detect the versions of the services dynamically, and step up or down to
+ * match those reported versions. In order to do that, we need to know before hand what region we are accessing (since
+ * the supported versions may be different by regions). We will need to authenticate to the identity service in order to
+ * do this, plus we have to duplicate the code supporting proxies and trusted hosts that exists in the abstraction
+ * layer, but that cant be helped.
+ * </p>
+ * <p>
+ * What we do to circumvent this is connect to the provider using the lowest supported identity api, and read the entire
+ * service catalog into this object. Then, we parse the vm URL to extract the host and port and match that to the
+ * compute services defined in the catalog. When we find a compute service that has the same host name and port,
+ * whatever region that service is supporting is the region for that server.
+ * </p>
+ * <p>
+ * While we really only need to do this for compute nodes, there is no telling what other situations may arise where the
+ * full service catalog may be needed. Also, there is very little additional cost (additional RAM) associated with
+ * caching the full service catalog since there is no way to list only a portion of it.
+ * </p>
+ */
+public class ServiceCatalogV3 extends ServiceCatalog {
+
+ /**
+ * The project that we are accessing
+ */
+ private Project project;
+
+ /**
+ * A map of endpoints for each service organized by service type
+ */
+ private Map<String /* Service Type */, List<Service.Endpoint>> serviceEndpoints;
+
+ /**
+ * A map of service types that are published
+ */
+ private Map<String /* Service Type */, Service> serviceTypes;
+
+ /**
+ * The Openstack Access object that manages the authenticated token and access control
+ */
+ private Token token;
+
+ /**
+ * A "token provider" that manages the authentication token that we obtain when logging in
+ */
+ private OpenStackSimpleTokenProvider tokenProvider;
+
+ /**
+ * {@inheritDoc}
+ */
+ public ServiceCatalogV3(String identityURL, String projectIdentifier, String principal, String credential,
+ String domain, Properties properties) {
+ super(identityURL, projectIdentifier, principal, credential, domain, properties);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void init() throws ZoneException {
+ rwLock = new ReentrantReadWriteLock();
+ serviceTypes = new HashMap<>();
+ serviceEndpoints = new HashMap<>();
+ regions = new HashSet<>();
+ Class<?> connectorClass;
+ OpenStackClientConnector connector;
+ try {
+ connectorClass = Class.forName(CLIENT_CONNECTOR_CLASS);
+ connector = (OpenStackClientConnector) connectorClass.newInstance();
+ } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
+ logger.error("An error occurred when initializing ServiceCatalogV3", e);
+ return;
+ }
+ Keystone keystone = getKeystone(identityURL, connector);
+
+ String proxyHost = properties.getProperty(ContextFactory.PROPERTY_PROXY_HOST);
+ String proxyPort = properties.getProperty(ContextFactory.PROPERTY_PROXY_PORT);
+ String trustedHosts = properties.getProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, ""); //$NON-NLS-1$
+ if (proxyHost != null && proxyHost.length() > 0) {
+ keystone.getProperties().setProperty(com.woorea.openstack.common.client.Constants.PROXY_HOST, proxyHost);
+ keystone.getProperties().setProperty(com.woorea.openstack.common.client.Constants.PROXY_PORT, proxyPort);
+ }
+ if (trustedHosts != null) {
+ keystone.getProperties().setProperty(com.woorea.openstack.common.client.Constants.TRUST_HOST_LIST,
+ trustedHosts);
+ }
+
+ // create identity
+ Identity identity = Identity.password(domain, principal, credential);
+
+ // create scope
+ Scope scope = initScope();
+
+ Authentication authentication = new Authentication();
+ authentication.setIdentity(identity);
+ authentication.setScope(scope);
+
+ TokensResource tokens = keystone.tokens();
+ TokensResource.Authenticate authenticate = tokens.authenticate(authentication);
+
+ /*
+ * We have to set up the TrackRequest TLS collection for the ExceptionMapper
+ */
+ trackRequest();
+ RequestState.put(RequestState.PROVIDER, "OpenStackProvider");
+ RequestState.put(RequestState.TENANT, projectIdentifier);
+ RequestState.put(RequestState.PRINCIPAL, principal);
+
+ try {
+ token = authenticate.execute();
+ // Ensure that token is not null before accessing
+ // local expiration or the internal details of token
+ if (token == null) {
+ throw new NullPointerException("Access token is null. Failed to init ServiceCatalogV3");
+ }
+ expiresLocal = getLocalExpiration(token);
+ project = token.getProject();
+ tokenProvider = new OpenStackSimpleTokenProvider(token.getId());
+ keystone.setTokenProvider(tokenProvider);
+ parseServiceCatalog(token.getCatalog());
+ } catch (OpenStackBaseException e) {
+ ExceptionMapper.mapException(e);
+ } catch (Exception e) {
+ throw new ContextConnectionException(e);
+ }
+ }
+
+ private Scope initScope() {
+ if (projectIdentifier.length() == 32 && projectIdentifier.matches("[0-9a-fA-F]+")) { //$NON-NLS-1$
+ return Scope.project(projectIdentifier);
+ } else {
+ return Scope.project(domain, projectIdentifier);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<Service.Endpoint> getEndpoints(String serviceType) {
+ Lock readLock = rwLock.readLock();
+ readLock.lock();
+ try {
+ return serviceEndpoints.get(serviceType);
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String getProjectId() {
+ Lock readLock = rwLock.readLock();
+ readLock.lock();
+ try {
+ return project.getId();
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String getProjectName() {
+ return getProject().getName();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Set<String> getRegions() {
+ Lock readLock = rwLock.readLock();
+ readLock.lock();
+ try {
+ return regions;
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<String> getServiceTypes() {
+ Lock readLock = rwLock.readLock();
+ readLock.lock();
+ try {
+ ArrayList<String> result = new ArrayList<>();
+ result.addAll(serviceTypes.keySet());
+ return result;
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String getVMRegion(VMURL url) {
+ String region = null;
+ Pattern urlPattern = Pattern.compile("[^:]+://([^:/]+)(?::([0-9]+)).*");
+
+ if (url != null) {
+ for (Endpoint endpoint : getEndpoints(COMPUTE_SERVICE)) {
+ String endpointUrl = endpoint.getUrl();
+ Matcher matcher = urlPattern.matcher(endpointUrl);
+ if (validateUrl(url, matcher)) {
+ region = endpoint.getRegion();
+ break;
+ }
+ }
+ }
+ return region;
+ }
+
+ private boolean validateUrl(VMURL url, Matcher matcher) {
+ return matcher.matches()
+ && url.getHost().equals(matcher.group(1))
+ && (url.getPort() == null || url.getPort().equals(matcher.group(2)));
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean isServicePublished(String serviceType) {
+ Lock readLock = rwLock.readLock();
+ readLock.lock();
+ try {
+ return serviceTypes.containsKey(serviceType);
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String toString() {
+
+ StringBuilder builder = new StringBuilder();
+ Lock lock = rwLock.readLock();
+ lock.lock();
+ try {
+ builder.append(String.format("Service Catalog: tenant %s, id[%s]%n", project.getName(), //$NON-NLS-1$
+ project.getId()));
+ if (regions != null && !regions.isEmpty()) {
+ builder.append(String.format("%d regions:%n", regions.size())); //$NON-NLS-1$
+ for (String region : regions) {
+ //$NON-NLS-1$ //$NON-NLS-2$
+ builder
+ .append("\t")
+ .append(region)
+ .append("%n");
+ }
+ }
+ builder.append(String.format("%d services:%n", serviceEndpoints.size())); //$NON-NLS-1$
+
+ for (Map.Entry<String, List<Service.Endpoint>> entry : serviceEndpoints.entrySet()) {
+ Service service = serviceTypes.get(entry.getKey());
+
+ builder.append(String.format("\t%s - %d endpoints%n", service.getType(), //$NON-NLS-1$
+ entry.getValue().size()));
+
+ for (Service.Endpoint endpoint : entry.getValue()) {
+ builder
+ .append(String.format("\t\tRegion [%s], public URL [%s]%n", endpoint.getRegion(), //$NON-NLS-1$
+ endpoint.getUrl()));
+ }
+ }
+ } finally {
+ lock.unlock();
+ }
+
+ return builder.toString();
+ }
+
+ /**
+ * Parses the service catalog and caches the results
+ *
+ * @param services The list of services published by this provider
+ */
+ private void parseServiceCatalog(List<Service> services) {
+ Lock lock = rwLock.writeLock();
+ lock.lock();
+ try {
+ serviceTypes.clear();
+ serviceEndpoints.clear();
+ regions.clear();
+
+ for (Service service : services) {
+ String type = service.getType();
+ serviceTypes.put(type, service);
+ addRegions(service, type);
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private void addRegions(Service service, String type) {
+ List<Endpoint> endpoints = service.getEndpoints();
+ for (Endpoint endpoint : endpoints) {
+ serviceEndpoints.computeIfAbsent(type, val -> new ArrayList<>());
+ serviceEndpoints.get(type).add(endpoint);
+
+ String region = endpoint.getRegion();
+ if (!regions.contains(region)) {
+ regions.add(region);
+ }
+ }
+ }
+
+ /**
+ * Computes the local time when the access token will expire, after which we will need to re-login to access the
+ * provider.
+ *
+ * @param accessToken The access key used to access the provider
+ * @return The local time the key expires
+ */
+ private static long getLocalExpiration(Token accessToken) {
+ Date now = Time.getCurrentUTCDate();
+ Calendar issued = accessToken.getIssuedAt();
+ Calendar expires = accessToken.getExpiresAt();
+ if (issued != null && expires != null) {
+ long tokenLife = expires.getTimeInMillis() - issued.getTimeInMillis();
+ return now.getTime() + tokenLife;
+ }
+ return now.getTime();
+ }
+
+ public Project getProject() {
+ Lock readLock = rwLock.readLock();
+ readLock.lock();
+ try {
+ return project;
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ protected Keystone getKeystone(String identityURL, OpenStackClientConnector connector) {
+ return new Keystone(identityURL, connector);
+ }
+}
\ No newline at end of file diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/TenantCache.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/TenantCache.java new file mode 100644 index 000000000..3b4f47afc --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/TenantCache.java @@ -0,0 +1,375 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.impl; + +import com.att.cdp.exceptions.ContextConnectionException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.ContextFactory; +import com.att.cdp.zones.Provider; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.onap.ccsdk.sli.core.utils.pool.Allocator; +import org.onap.ccsdk.sli.core.utils.pool.Destructor; +import org.onap.ccsdk.sli.core.utils.pool.Pool; +import org.onap.ccsdk.sli.core.utils.pool.PoolSpecificationException; + +/** + * This class maintains a cache of tenants within a specific provider. + * <p> + * Providers may be multi-tenant, such as OpenStack, where the available services and resources vary from one tenant to + * another. Therefore, the provider cache maintains a cache of tenants and the service catalogs for each, as well as the + * credentials used to access the tenants, and a pool of Context objects for each tenant. The context pool allows use of + * the CDP abstraction layer to access the services of the provider within the specific tenant. + * </p> + */ +public class TenantCache implements Allocator<Context>, Destructor<Context> { + + public static final String POOL_PROVIDER_NAME = "pool.provider.name"; + public static final String POOL_TENANT_NAME = "pool.tenant.name"; + public static final String CLIENT_CONNECTOR_CLASS = "com.woorea.openstack.connector.JaxRs20Connector"; + /** + * The domain to use to authenticate + */ + private String domain; + + /** + * The provider we are part of + */ + private ProviderCache provider; + + /** + * The password used to authenticate + */ + private String password; + + /** + * The context pools by region used to access this tenant + */ + private Map<String /* region */, Pool<Context>> pools = new HashMap<>(); + + /** + * The tenant id + */ + private String tenantId; + + /** + * The tenant name + */ + private String tenantName; + + /** + * The user id used to authenticate + */ + private String userid; + + /** + * The configuration of this adapter + */ + private Configuration configuration; + + /** + * The service catalog for this provider + */ + private ServiceCatalog catalog; + + /** + * Set to true when the cache has been initialized + */ + private boolean initialized; + + /** + * The logger to use + */ + private EELFLogger logger; + + /** + * Construct the cache of tenants for the specified provider + * + * @param provider The provider + */ + public TenantCache(ProviderCache provider) { + configuration = ConfigurationFactory.getConfiguration(); + logger = EELFManager.getInstance().getLogger(getClass()); + this.provider = provider; + } + + /** + * @return True when the cache has been initialized. A tenant cache is initialized when the service catalog for the + * tenant on the specified provider has been loaded and processed. + */ + public boolean isInitialized() { + return initialized; + } + + /** + * Initializes the tenant cache. + * <p> + * This method authenticates to the provider and obtains the service catalog. For the service catalog we can + * determine all supported regions for this provider, as well as all published services and their endpoints. We will + * cache and maintain a copy of the service catalog for later queries. + * </p> + * <p> + * Once the catalog has been obtained, we create a context pool for each region defined. The context allows access + * to services of a single region only, so we need a separate context by region. It is possible to operate on + * resources that span regions, but to do so will require acquiring a context for each region of interest. + * </p> + * <p> + * The context pool maintains the reusable context objects and allocates them as needed. This class is registered as + * the allocator and destructor for the pool, so that we can create a new context when needed, and close it when no + * longer used. + * </p> + */ + public void initialize() { + logger.debug("Initializing TenantCache"); + + int min = configuration.getIntegerProperty(Constants.PROPERTY_MIN_POOL_SIZE); + int max = configuration.getIntegerProperty(Constants.PROPERTY_MAX_POOL_SIZE); + int delay = configuration.getIntegerProperty(Constants.PROPERTY_RETRY_DELAY); + int limit = configuration.getIntegerProperty(Constants.PROPERTY_RETRY_LIMIT); + String url = provider.getIdentityURL(); + String tenant = tenantName == null ? tenantId : tenantName; + Properties properties = configuration.getProperties(); + catalog = getServiceCatalogFactory(url, tenant, properties); + if (catalog == null) { + logger.error(Msg.IAAS_UNSUPPORTED_IDENTITY_SERVICE, url); + return; + } + + int attempt = 1; + while (attempt <= limit) { + try { + catalog.init(); + tenantId = catalog.getProjectId(); + tenantName = catalog.getProjectName(); + createPools(min, max, url, properties); + initialized = true; + break; + } catch (ContextConnectionException e) { + if (++attempt <= limit) { + logger.error(Msg.CONNECTION_FAILED_RETRY, provider.getProviderName(), url, tenantName, tenantId, + e.getMessage(), Integer.toString(delay), Integer.toString(attempt), + Integer.toString(limit)); + sleep(delay); + } + } catch (ZoneException e) { + logger.error("An error occurred when initializing cache", e); + break; + } + } + + if (!initialized) { + logger.error(Msg.CONNECTION_FAILED, provider.getProviderName(), url); + } + } + + public ServiceCatalog getServiceCatalogFactory(String url, String tenant, Properties properties) { + return ServiceCatalogFactory.getServiceCatalog(url, tenant, userid, password, domain, properties); + } + + private void createPools(int min, int max, String url, Properties properties) { + for (String region : catalog.getRegions()) { + try { + Pool<Context> pool = new Pool<>(min, max); + pool.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, url); + pool.setProperty(ContextFactory.PROPERTY_TENANT, getTenantName()); + pool.setProperty(ContextFactory.PROPERTY_CLIENT_CONNECTOR_CLASS, CLIENT_CONNECTOR_CLASS); + pool.setProperty(ContextFactory.PROPERTY_RETRY_DELAY, + configuration.getProperty(Constants.PROPERTY_RETRY_DELAY)); + pool.setProperty(ContextFactory.PROPERTY_RETRY_LIMIT, + configuration.getProperty(Constants.PROPERTY_RETRY_LIMIT)); + pool.setProperty(ContextFactory.PROPERTY_REGION, region); + if (properties.getProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS) != null) { + pool.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, + properties.getProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS)); + } + pool.setAllocator(this); + pool.setDestructor(this); + pools.put(region, pool); + logger.debug(String.format("Put pool for region %s", region)); + } catch (PoolSpecificationException e) { + logger.error("Error creating pool", e); + } + } + } + + private void sleep(int delay) { + try { + Thread.sleep(delay * 1000L); + } catch (InterruptedException ie) { + // ignore + } + } + + /** + * This method accepts a fully qualified compute node URL and uses that to determine which region of the provider + * hosts that compute node. + * + * @param url The parsed URL of the compute node + * @return The region name, or null if no region of this tenant hosts that compute node. + */ + public String determineRegion(VMURL url) { + logger.debug(String.format("Attempting to determine VM region for %s", url)); + String region = catalog.getVMRegion(url); + logger.debug(String.format("Region for %s is %s", url, region)); + return region; + } + + /** + * @return the value of the domain + */ + public String getDomain() { + return domain; + } + + /** + * @param domain the value for domain + */ + public void setDomain(String domain) { + this.domain = domain; + } + + /** + * @return the value of provider + */ + public ProviderCache getProvider() { + return provider; + } + + /** + * @param provider the value for provider + */ + public void setProvider(ProviderCache provider) { + this.provider = provider; + } + + /** + * @return the value of password + */ + public String getPassword() { + return password; + } + + /** + * @param password the value for password + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * @return the value of tenantId + */ + public String getTenantId() { + return tenantId; + } + + /** + * @param tenantId the value for tenantId + */ + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + /** + * @return the value of tenantName + */ + public String getTenantName() { + return tenantName; + } + + /** + * @param tenantName the value for tenantName + */ + public void setTenantName(String tenantName) { + this.tenantName = tenantName; + } + + /** + * @return the value of userid + */ + public String getUserid() { + return userid; + } + + /** + * @param userid the value for userid + */ + public void setUserid(String userid) { + this.userid = userid; + } + + /** + * @return the value of pools + */ + public Map<String, Pool<Context>> getPools() { + return pools; + } + + /** + * @see org.onap.ccsdk.sli.core.utils.pool.Allocator#allocate(org.onap.ccsdk.sli.core.utils.pool.Pool) + */ + @SuppressWarnings("unchecked") + @Override + public Context allocate(Pool<Context> pool) { + logger.debug("Allocationg context for pool"); + Class<? extends Provider> providerClass; + try { + providerClass = (Class<? extends Provider>) Class.forName("com.att.cdp.openstack.OpenStackProvider"); + Context context = ContextFactory.getContext(providerClass, pool.getProperties()); + context.login(userid, password); + return context; + } catch (IllegalStateException | IllegalArgumentException | ZoneException | ClassNotFoundException e) { + logger.debug("Failed to allocate context for pool", e); + } + return null; + } + + /** + * @see org.onap.ccsdk.sli.core.utils.pool.Destructor#destroy(java.lang.Object, org.onap.ccsdk.sli.core.utils.pool.Pool) + */ + @Override + public void destroy(Context context, Pool<Context> pool) { + try { + context.close(); + } catch (IOException e) { + logger.error("An error occurred when destroying cache", e); + } + } + + /** + * @return the service catalog for this provider + */ + public ServiceCatalog getServiceCatalog() { + return catalog; + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/VMURL.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/VMURL.java new file mode 100644 index 000000000..5c7dee42c --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/impl/VMURL.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.impl; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * This class is used to parse the VM URL returned from OpenStack and extract all of the constituent parts. + */ +public class VMURL { + + /** + * The regular expression pattern used to parse the URL. Capturing groups are used to identify and extract the + * various component parts of the URL. + */ + private static Pattern pattern = + Pattern.compile("(\\p{Alnum}+)://([^/:]+)(?::([0-9]+))?(/.*)?/(v[0-9\\.]+)/([^/]+)/servers/([^/]+)"); + + /** + * The URL scheme or protocol, such as HTTP or HTTPS + */ + private String scheme; + + /** + * The host name or ip address + */ + private String host; + + /** + * The path, or null if no path is defined + */ + private String path; + + /** + * The port number, or null if no port is defined + */ + private String port; + + /** + * The tenant UUID + */ + private String tenantId; + + /** + * The server UUID + */ + private String serverId; + + /** + * The version of the service + */ + private String version; + + /** + * A private default constructor prevents instantiation by any method other than the factory method + * + * @see #parseURL(String) + */ + private VMURL() { + + } + + /** + * This static method is used to parse the provided server URL string and return a parse results object (VMURL) + * which represents the state of the parse. + * + * @param serverUrl The server URL to be parsed + * @return The VMURL parse results object, or null if the URL was not valid or null. + */ + public static VMURL parseURL(String serverUrl) { + VMURL obj = null; + if (serverUrl != null) { + Matcher matcher = pattern.matcher(serverUrl.trim()); + if (matcher.matches()) { + obj = new VMURL(); + obj.scheme = matcher.group(1); + obj.host = matcher.group(2); + obj.port = matcher.group(3); + obj.path = matcher.group(4); + obj.version = matcher.group(5); + obj.tenantId = matcher.group(6); + obj.serverId = matcher.group(7); + } + } + + return obj; + } + + /** + * @return The URL scheme + */ + public String getScheme() { + return scheme; + } + + /** + * @return The URL host + */ + public String getHost() { + return host; + } + + /** + * @return THe URL path, or null if no path was defined + */ + public String getPath() { + return path; + } + + /** + * @return The URL port, or null if no port was defined + */ + public String getPort() { + return port; + } + + /** + * @return The tenant id + */ + public String getTenantId() { + return tenantId; + } + + /** + * @return The server ID + */ + public String getServerId() { + return serverId; + } + + /** + * @return The version of the service + */ + public String getVersion() { + return version; + } + + @Override + public String toString() { + StringBuilder str = new StringBuilder(); + str.append(scheme + "://" + host); + if (port != null) { + str.append(":" + port); + } + if (path != null) { + str.append(path); + } + str.append("/" + version + "/" + tenantId + "/servers/" + serverId); + return str.toString(); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/api/IProviderOperation.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/api/IProviderOperation.java new file mode 100644 index 000000000..3c82ff612 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/api/IProviderOperation.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.api; + +import com.att.cdp.zones.model.ModelObject; +import java.util.Map; +import org.onap.ccsdk.sli.adaptors.iaas.impl.ProviderCache; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +/** + * @since September 26, 2016 + */ +public interface IProviderOperation { + + /** + * perform specific provider operation + * + * @param params + * @param context + * @return Object represents Stack, Server Or Image + */ + ModelObject doOperation(Map<String, String> params, SvcLogicContext context) throws SvcLogicException; + + /** + * sets a cache of providers that are predefined. + * + * @param providerCache + */ + void setProviderCache(Map<String /* provider name */, ProviderCache> providerCache); + + /** + * should be initialized by user + * + * @param defaultDomain + */ + void setDefaultDomain(String defaultDomain); + + /** + * should be initialized by user + * + * @param defaultUser + */ + void setDefaultUser(String defaultUser); + + /** + * should be initialized by user + * + * @param defaultPassword + */ + void setDefaultPassword(String defaultPassword); +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/api/ProviderOperationFactory.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/api/ProviderOperationFactory.java new file mode 100644 index 000000000..fee9156ae --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/api/ProviderOperationFactory.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.api; + +import java.util.HashMap; +import java.util.Map; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.*; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +/** + * Singleton factory of provider operations objects with cache + * + * @since September 26, 2016 + */ +public class ProviderOperationFactory { + /** + * holds instance of the class + */ + private static ProviderOperationFactory instance; + /** + * holds concrete operations objects + */ + private Map<Operation, IProviderOperation> operations; + /** + * private constructor + */ + private ProviderOperationFactory() { + this.operations = new HashMap<>(); + } + /** + * @return instance of the factory + */ + public static ProviderOperationFactory getInstance() { + if (instance == null) { + instance = new ProviderOperationFactory(); + } + return instance; + } + /** + * @param op + * @return concrete operation impl + */ + public IProviderOperation getOperationObject(Operation op) throws SvcLogicException { + IProviderOperation opObject = operations.get(op); + if (opObject == null) { + switch (op) { + case EVACUATE_SERVICE: + opObject = new EvacuateServer(); + break; + case MIGRATE_SERVICE: + opObject = new MigrateServer(); + break; + case REBUILD_SERVICE: + opObject = new RebuildServer(); + break; + case RESTART_SERVICE: + opObject = new RestartServer(); + break; + case VMSTATUSCHECK_SERVICE: + opObject = new VmStatuschecker(); + break; + case SNAPSHOT_SERVICE: + opObject = new CreateSnapshot(); + break; + case TERMINATE_STACK: + opObject = new TerminateStack(); + break; + case SNAPSHOT_STACK: + opObject = new SnapshotStack(); + break; + case RESTORE_STACK: + opObject = new RestoreStack(); + break; + case START_SERVICE: + opObject = new StartServer(); + break; + case STOP_SERVICE: + opObject = new StopServer(); + break; + case TERMINATE_SERVICE: + opObject = new TerminateServer(); + break; + case LOOKUP_SERVICE: + opObject = new LookupServer(); + break; + case ATTACHVOLUME_SERVICE: + opObject = new AttachVolumeServer(); + break; + case DETACHVOLUME_SERVICE: + opObject = new DettachVolumeServer(); + break; + case REBOOT_SERVICE: + opObject = new RebootServer(); + break; + default: + throw new SvcLogicException("Unsupported provider operation."); + } + operations.put(op, opObject); + } + return opObject; + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/common/enums/Operation.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/common/enums/Operation.java new file mode 100644 index 000000000..28b8a33fa --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/common/enums/Operation.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums; +/** + * @since September 26, 2016 + */ +public enum Operation { + EVACUATE_SERVICE { + @Override + public String toString() { + return "evacuateServer"; + } + }, + MIGRATE_SERVICE { + @Override + public String toString() { + return "migrateServer"; + } + }, + REBUILD_SERVICE { + @Override + public String toString() { + return "rebuildServer"; + } + }, + RESTART_SERVICE { + @Override + public String toString() { + return "restartServer"; + } + }, + VMSTATUSCHECK_SERVICE { + @Override + public String toString() { + return "vmStatuschecker"; + } + }, + SNAPSHOT_SERVICE { + @Override + public String toString() { + return "createSnapshot"; + } + }, + TERMINATE_STACK { + @Override + public String toString() { + return "terminateStack"; + } + }, + SNAPSHOT_STACK { + @Override + public String toString() { + return "snapshotStack"; + } + }, + START_SERVICE { + @Override + public String toString() { + return "startServer"; + } + }, + STOP_SERVICE { + @Override + public String toString() { + return "stopServer"; + } + }, + TERMINATE_SERVICE { + @Override + public String toString() { + return "terminateServer"; + } + }, + LOOKUP_SERVICE { + @Override + public String toString() { + return "lookupServer"; + } + }, + RESTORE_STACK { + @Override + public String toString() { + return "restoreStack"; + } + }, + ATTACHVOLUME_SERVICE { + @Override + public String toString(){ + return "attachVolume"; + } + }, + DETACHVOLUME_SERVICE { + @Override + public String toString(){ + return "dettachVolume"; + } + }, + REBOOT_SERVICE { + @Override + public String toString(){ + return "rebootServer"; + } + }, +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/common/enums/Outcome.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/common/enums/Outcome.java new file mode 100644 index 000000000..5017bff03 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/common/enums/Outcome.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums; + +/** + * @since September 26, 2016 + */ +public enum Outcome { + FAILURE { + @Override + public String toString() { + return "failure"; + } + }, + SUCCESS { + @Override + public String toString() { + return "success"; + } + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/AttachVolumeServer.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/AttachVolumeServer.java new file mode 100644 index 000000000..bea08319f --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/AttachVolumeServer.java @@ -0,0 +1,238 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.TimeoutException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.openstack.util.ExceptionMapper; +import com.att.cdp.zones.ComputeService; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.VolumeService; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.cdp.zones.model.Volume; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import com.woorea.openstack.base.client.OpenStackBaseException; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import org.apache.commons.lang.StringUtils; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.adaptors.iaas.Property; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.utils.logging.Msg; + +public class AttachVolumeServer extends ProviderServerOperation { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(AttachVolumeServer.class); + private static final Configuration config = ConfigurationFactory.getConfiguration(); + + private Server attachVolume(Map<String, String> params, SvcLogicContext ctx) { + Server server = null; + RequestContext requestContext = new RequestContext(ctx); + requestContext.isAlive(); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + String volumeId = params.get(ProviderAdapter.VOLUME_ID); + String device = params.get(ProviderAdapter.DEVICE); + if (StringUtils.isBlank(device)) { + logger.info("Setting device to null"); + device = null; + } + VMURL vm = VMURL.parseURL(vmUrl); + Context context; + final String volumeStatus = "VOLUME_STATUS"; + final String statusFail = "FAILURE"; + final String statusSuccess = "SUCCESS"; + final String statusNotFound = "CONTEXT_NOT_FOUND"; + String tenantName = "Unknown";// to be used also in case of exception + try { + if (validateVM(requestContext, appName, vmUrl, vm)) { + return null; + } + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + context = getContext(requestContext, vmUrl, identStr); + String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK); + if (skipHypervisorCheck == null && ctx != null) { + skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK); + } + if (context != null) { + tenantName = context.getTenantName();// this variable also is + // used in case of + // exception + requestContext.reset(); + server = lookupServer(requestContext, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString()); + Context contx = server.getContext(); + if (!"true".equalsIgnoreCase(skipHypervisorCheck)) { + // Check of the Hypervisor for the VM Server is UP and reachable + checkHypervisor(server); + } + ComputeService service = contx.getComputeService(); + if ((volumeId == null || volumeId.isEmpty()) || (device == null || device.isEmpty())) { + ctx.setAttribute(volumeStatus, statusFail); + doFailure(requestContext, HttpStatus.BAD_REQUEST_400, "Both Device or Volumeid are mandatory"); + } + VolumeService volumeService = contx.getVolumeService(); + logger.info("collecting volume status for volume -id:" + volumeId); + //List<Volume> volumes = volumeService.getVolumes(); + Volume volume = new Volume(); + boolean isAttached = false; + if (validateAttach(service, vm.getServerId(), volumeId, device)) { + String msg = "Volume with volume id " + volumeId + " cannot be attached as it already exists"; + logger.info("Already volumes exists:"); + ctx.setAttribute(volumeStatus, statusFail); + doFailure(requestContext, HttpStatus.METHOD_NOT_ALLOWED_405, msg); + isAttached = false; + } else { + volume.setId(volumeId); + logger.info("Ready to Attach Volume to the server:"); + service.attachVolume(server, volume, device); + isAttached = true; + } + if (isAttached) { + if (validateAttach(requestContext, service, vm.getServerId(), volumeId, device)) { + ctx.setAttribute(volumeStatus, statusSuccess); + doSuccess(requestContext); + } else { + String msg = "Volume with " + volumeId + " unable to attach"; + logger.info("Volume with " + volumeId + " unable to attach"); + ctx.setAttribute(volumeStatus, statusFail); + doFailure(requestContext, HttpStatus.CONFLICT_409, msg); + } + } + context.close(); + } else { + ctx.setAttribute(volumeStatus, statusNotFound); + } + } catch (ZoneException e) { + String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl); + logger.error(msg); + ctx.setAttribute(volumeStatus, statusFail); + doFailure(requestContext, HttpStatus.NOT_FOUND_404, msg); + } catch (RequestFailedException e) { + ctx.setAttribute(volumeStatus, statusFail); + doFailure(requestContext, e.getStatus(), e.getMessage()); + } catch (Exception ex) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, ex, ex.getClass().getSimpleName(), + Operation.ATTACHVOLUME_SERVICE.toString(), vmUrl, tenantName); + ctx.setAttribute(volumeStatus, statusFail); + try { + ExceptionMapper.mapException((OpenStackBaseException) ex); + } catch (ZoneException e1) { + logger.error(e1.getMessage()); + } + doFailure(requestContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + return server; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.ATTACHVOLUME_SERVICE.toString(), "App-C IaaS Adapter:attachVolume", Constants.ADAPTER_NAME); + logOperation(Msg.ATTACHINGVOLUME_SERVER, params, context); + return attachVolume(params, context); + } + + protected boolean validateAttach(ComputeService ser, String vm, String volumeId, String device) + throws ZoneException { + boolean isValid = false; + Map<String, String> map = ser.getAttachments(vm); + Iterator<Entry<String, String>> it = map.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry<String, String> volumes = it.next(); + logger.info("volumes available before attach"); + logger.info("device" + volumes.getKey() + " Values " + volumes.getValue()); + if (StringUtils.isBlank(device)) { + if (volumes.getValue().equals(volumeId)) { + logger.info("Device " + volumes.getKey() + " Volumes " + volumes.getValue()); + isValid = true; + } + } else if (volumes.getKey().equals(device) && (volumes.getValue().equals(volumeId))) { + logger.info("Device " + volumes.getKey() + " Volumes " + volumes.getValue()); + isValid = true; + } + } + logger.info("AttachVolumeFlag " + isValid); + return isValid; + } + + protected boolean validateAttach(RequestContext rc, ComputeService ser, String vm, String volumeId, String device) + throws ZoneException { + boolean isValid = false; + String msg = null; + config.setProperty(Constants.PROPERTY_RETRY_DELAY, "10"); + config.setProperty(Constants.PROPERTY_RETRY_LIMIT, "30"); + while (rc.attempt()) { + Map<String, String> map = ser.getAttachments(vm); + if (map != null && !(map.isEmpty())) { + Iterator<Entry<String, String>> it = map.entrySet().iterator(); + logger.info("volumes available after attach "); + while (it.hasNext()) { + Map.Entry<String, String> volumes = it.next(); + logger.info(" devices " + volumes.getKey() + " volumes " + volumes.getValue()); + if (StringUtils.isBlank(device) && (volumes.getValue().equals(volumeId))) { + logger.info("Device " + volumes.getKey() + "Volumes " + volumes.getValue()); + isValid = true; + break; + } else if (volumes.getKey().equals(device) && (volumes.getValue().equals(volumeId))) { + logger.info("Device " + volumes.getKey() + " Volume " + volumes.getValue()); + isValid = true; + break; + } + } + if (isValid) { + logger.info("AttachVolume " + rc.getAttempts() + " No.of attempts "); + break; + } else { + rc.delay(); + } + } + } + if ((rc.getAttempts() == 30) && (!isValid)) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, Long.toString(rc.getRetryDelay()), + Integer.toString(rc.getAttempts()), Integer.toString(rc.getRetryLimit())); + logger.error(msg); + throw new TimeoutException(msg); + } + logger.info("AttachVolume Flag -->" + isValid); + return isValid; + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/CreateSnapshot.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/CreateSnapshot.java new file mode 100644 index 000000000..55313d0ff --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/CreateSnapshot.java @@ -0,0 +1,227 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Modifications Copyright (C) 2018-2019 IBM. + * ================================================================================ + * Modifications (C) 2019 Ericsson + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ContextConnectionException; +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.ImageService; +import com.att.cdp.zones.Provider; +import com.att.cdp.zones.model.Image; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.utils.logging.LoggingConstants; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.adaptors.iaas.Property; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.slf4j.MDC; + +public class CreateSnapshot extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(CreateSnapshot.class); + private static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + private String generateSnapshotName(String server) { + setTimeForMetricsLogger(); + SimpleDateFormat df = new SimpleDateFormat(Constants.DATE_FORMAT); + metricsLogger.info("Snapshot Name Generated: Snapshot of %s at %s", server, df.format(new Date())); + return String.format("Snapshot of %s at %s", server, df.format(new Date())); + } + + private Image createSnapshot(RequestContext rc, Server server) throws ZoneException, RequestFailedException { + Context context = server.getContext(); + Provider provider = context.getProvider(); + ImageService service = context.getImageService(); // Already checked access by this point + String snapshotName = generateSnapshotName(server.getName()); + setTimeForMetricsLogger(); + logger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(), server.getId(), + snapshotName)); + metricsLogger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(), + server.getId(), snapshotName)); + // Request Snapshot + String msg; + while (rc.attempt()) { + try { + server.createSnapshot(snapshotName); + break; + } catch (ContextConnectionException e) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(), + context.getTenant().getName(), context.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + metricsLogger.error(msg, e); + rc.delay(); + } + } + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server); + } + rc.reset(); + // Locate snapshot image - image names containing colon must be prefixed by in: + // and surrounded with quotes + Image snapshot = null; + while (rc.attempt()) { + try { + snapshot = service.getImageByName("in:\"" + snapshotName + "\""); + if (snapshot != null) { + break; + } + } catch (ContextConnectionException e) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(), + context.getTenant().getName(), context.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + metricsLogger.error(msg, e); + rc.delay(); + } + } + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server); + } + rc.reset(); + // Wait for it to be ready + waitForStateChange(rc, snapshot, Image.Status.ACTIVE); + return snapshot; + } + + private Image createSnapshot(Map<String, String> params, SvcLogicContext ctx) { + Image snapshot = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + setTimeForMetricsLogger(); + try { + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + VMURL vm = VMURL.parseURL(vmUrl); + if (validateVM(rc, appName, vmUrl, vm)) + return null; + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + snapshot = createSnapshotNested(snapshot, rc, vm, vmUrl, identStr,ctx); + } catch (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + } + return snapshot; + } + + private Image createSnapshotNested(Image snapShot, RequestContext rcContext, VMURL vm, String vmUrl, + String identStr, SvcLogicContext ctx){ + String msg; + Context context = null; + String tenantName = "Unknown";// this variable is also used in catch + try { + context = getContext(rcContext, vmUrl, identStr); + if (context != null) { + tenantName = context.getTenantName(); + Server server = lookupServer(rcContext, context, vm.getServerId()); + // Is the skip Hypervisor check attribute populated? + String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK); + if (skipHypervisorCheck == null && ctx != null) { + skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK); + } + // Always perform Hypervisor check + // unless the skip is set to true + if (skipHypervisorCheck == null || (!"true".equalsIgnoreCase(skipHypervisorCheck))) { + // Check of the Hypervisor for the VM Server is UP and reachable + checkHypervisor(server); + } + + logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString()); + if (hasImageAccess(rcContext, context)) { + snapShot = createSnapshot(rcContext, server); + doSuccess(rcContext); + } else { + msg = EELFResourceManager.format(Msg.IMAGE_SERVICE_FAILED, server.getName(), server.getId(), + "Accessing Image Service Failed"); + logger.error(msg); + metricsLogger.error(msg); + doFailure(rcContext, HttpStatus.FORBIDDEN_403, msg); + } + context.close(); + } + } catch (ResourceNotFoundException e) { + msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl); + logger.error(msg); + metricsLogger.error(msg, e); + doFailure(rcContext, HttpStatus.NOT_FOUND_404, msg); + } catch (Exception e1) { + msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), + Operation.SNAPSHOT_SERVICE.toString(), vmUrl, tenantName); + logger.error(msg, e1); + doFailure(rcContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + return snapShot; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.SNAPSHOT_SERVICE.toString(), "App-C IaaS Adapter:Snapshot", Constants.ADAPTER_NAME); + logOperation(Msg.SNAPSHOTING_SERVER, params, context); + setTimeForMetricsLogger(); + metricsLogger.info("Executing Provider Operation: Create Snapshot"); + return createSnapshot(params, context); + } + + private void setTimeForMetricsLogger() { + MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp"); + MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "create snapshot"); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, + "org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.CreateSnapshot"); + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/DettachVolumeServer.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/DettachVolumeServer.java new file mode 100644 index 000000000..e8a2fc7f5 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/DettachVolumeServer.java @@ -0,0 +1,235 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.TimeoutException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.openstack.util.ExceptionMapper; +import com.att.cdp.zones.ComputeService; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.cdp.zones.model.Volume; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import com.woorea.openstack.base.client.OpenStackBaseException; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.adaptors.iaas.Property; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.utils.logging.Msg; + +public class DettachVolumeServer extends ProviderServerOperation { + private final EELFLogger logger = EELFManager.getInstance().getLogger(DettachVolumeServer.class); + private static final Configuration config = ConfigurationFactory.getConfiguration(); + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.DETACHVOLUME_SERVICE.toString(), "App-C IaaS Adapter:dettachVolume", Constants.ADAPTER_NAME); + logOperation(Msg.DETTACHINGVOLUME_SERVER, params, context); + return dettachVolume(params, context); + } + + private Server dettachVolume(Map<String, String> params, SvcLogicContext ctx) { + Server server = null; + RequestContext requestContext = new RequestContext(ctx); + requestContext.isAlive(); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + String volumeId = params.get(ProviderAdapter.VOLUME_ID); + VMURL vm = VMURL.parseURL(vmUrl); + Context context; + String tenantName = "Unknown";// to be used also in case of exception + try { + if (validateVM(requestContext, appName, vmUrl, vm)) { + return null; + } + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + context = getContext(requestContext, vmUrl, identStr); + String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK); + if (skipHypervisorCheck == null && ctx != null) { + skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK); + } + if (context != null) { + tenantName = context.getTenantName();// this variable also is + // used in case of + // exception + requestContext.reset(); + server = lookupServer(requestContext, context, vm.getServerId()); + // Always perform Hypervisor check + // unless the skip is set to true + if (!"true".equalsIgnoreCase(skipHypervisorCheck)) { + // Check of the Hypervisor for the VM Server is UP and reachable + checkHypervisor(server); + } + logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString()); + if (volumeId == null || volumeId.isEmpty()) { + if(ctx != null){ + ctx.setAttribute("VOLUME_STATUS", "FAILURE"); + } + doFailure(requestContext, HttpStatus.BAD_REQUEST_400, "Volumeid is mandatory"); + } + Context contx = server.getContext(); + ComputeService service = contx.getComputeService(); + Volume volume = new Volume(); + boolean flag = false; + if (validateDetach(service, vm.getServerId(), volumeId)) { + volume.setId(volumeId); + logger.info("Ready to Detach Volume from the server:"); + service.detachVolume(server, volume); + flag = true; + } else { + String msg = "Volume with volume id " + volumeId + " cannot be detached as it does not exists"; + logger.info("Volume doesnot exists:"); + if(ctx != null){ + ctx.setAttribute("VOLUME_STATUS", "FAILURE"); + } + doFailure(requestContext, HttpStatus.METHOD_NOT_ALLOWED_405, msg); + flag = false; + } + if (flag) { + if (validateDetach(requestContext, service, vm.getServerId(), volumeId)) { + String msg = "Volume with volume id " + volumeId + " cannot be detached "; + if(ctx != null){ + ctx.setAttribute("VOLUME_STATUS", "FAILURE"); + } + doFailure(requestContext, HttpStatus.CONFLICT_409, msg); + } else { + logger.info("status of detaching volume"); + if(ctx != null){ + ctx.setAttribute("VOLUME_STATUS", "SUCCESS"); + } + doSuccess(requestContext); + } + } + context.close(); + } else { + if(ctx != null){ + ctx.setAttribute("VOLUME_STATUS", "CONTEXT_NOT_FOUND"); + } + } + } catch (ZoneException e) { + String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl); + logger.error(msg); + doFailure(requestContext, HttpStatus.NOT_FOUND_404, msg); + } catch (RequestFailedException e) { + logger.error("An error occurred when processing the request", e); + doFailure(requestContext, e.getStatus(), e.getMessage()); + } catch (Exception e) { + String msg = EELFResourceManager.format(Msg.DETTACHINGVOLUME_SERVER, e, e.getClass().getSimpleName(), + Operation.DETACHVOLUME_SERVICE.toString(), vmUrl, tenantName); + logger.error(msg, e); + try { + ExceptionMapper.mapException((OpenStackBaseException) e); + } catch (ZoneException e1) { + logger.error(e1.getMessage()); + } + + doFailure(requestContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + return server; + } + + protected boolean validateDetach(ComputeService ser, String vm, String volumeId) + throws RequestFailedException, ZoneException { + boolean flag = false; + Map<String, String> map = ser.getAttachments(vm); + if (map != null && !(map.isEmpty())) { + Iterator<Entry<String, String>> it = map.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry<String, String> volumes = it.next(); + logger.info("volumes available in before detach"); + logger.info("device" + volumes.getKey() + "volume" + volumes.getValue()); + if (volumes.getValue().equals(volumeId)) { + flag = true; + } + } + } + logger.info("DettachVolume Flag" + flag); + return flag; + } + + protected boolean validateDetach(RequestContext rc, ComputeService ser, String vm, String volumeId) + throws ZoneException { + boolean flag = false; + String msg = null; + config.setProperty(Constants.PROPERTY_RETRY_DELAY, "10"); + config.setProperty(Constants.PROPERTY_RETRY_LIMIT, "30"); + while (rc.attempt()) { + Map<String, String> map = ser.getAttachments(vm); + if (map != null && !(map.isEmpty())) { + Iterator<Entry<String, String>> it = map.entrySet().iterator(); + logger.info("volumes available after detach "); + while (it.hasNext()) { + Map.Entry<String, String> volumes = it.next(); + logger.info(" devices " + volumes.getKey() + " volumes" + volumes.getValue()); + if (volumes.getValue().equals(volumeId)) { + logger.info("Device" + volumes.getKey() + "Volume" + volumes.getValue()); + flag = true; + break; + } else { + flag = false; + } + logger.info("Dettachvolume flag-->" + flag + "Attempts" + rc.getAttempts()); + } + if (flag) { + rc.delay(); + } else { + break; + } + } else { + flag = false; + logger.info(rc.getAttempts() + "No.of attempts"); + break; + } + } + if ((rc.getAttempts() == 30) && (!flag)) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, Long.toString(rc.getRetryDelay()), + Integer.toString(rc.getAttempts()), Integer.toString(rc.getRetryLimit())); + logger.error(msg); + logger.info(msg); + throw new TimeoutException(msg); + } + logger.info("DettachVolume Flag -->" + flag); + return flag; + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/EvacuateServer.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/EvacuateServer.java new file mode 100644 index 000000000..65415e099 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/EvacuateServer.java @@ -0,0 +1,378 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ============================================================================= + * Modification Copyright (C) 2019 IBM + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ContextConnectionException; +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.ComputeService; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.Provider; +import com.att.cdp.zones.model.Hypervisor; +import com.att.cdp.zones.model.Hypervisor.State; +import com.att.cdp.zones.model.Hypervisor.Status; +import com.att.cdp.zones.model.Image; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import java.io.IOException; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL; +import org.onap.ccsdk.sli.adaptors.iaas.impl.ProviderAdapterImpl; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.utils.logging.LoggingConstants; +import org.onap.ccsdk.sli.core.utils.logging.LoggingUtils; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.slf4j.MDC; + +public class EvacuateServer extends ProviderServerOperation { + + private static final String EVACUATE_STATUS = "EVACUATE_STATUS"; + private static final String EVACUATE_SERVER = "Evacuate Server"; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class); + private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + private ProviderAdapterImpl paImpl = null; + + private void evacuateServer(RequestContext rc, @SuppressWarnings("unused") Server server, String targetHost) + throws ZoneException, RequestFailedException { + Context ctx = server.getContext(); + Provider provider = ctx.getProvider(); + ComputeService service = ctx.getComputeService(); + /* + * Pending is a bit of a special case. If we find the server is in a pending + * state, then the provider is in the process of changing state of the server. + * So, lets try to wait a little bit and see if the state settles down to one we + * can deal with. If not, then we have to fail the request. + */ + try { + if (server.getStatus().equals(Server.Status.PENDING)) { + waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR, + Server.Status.SUSPENDED, Server.Status.PAUSED); + } + } catch (RequestFailedException e) { + // evacuate is a special case. If the server is still in a Pending state, we + // want to + // continue with evacuate + logger.info("Evacuate server - ignore RequestFailedException from waitForStateChange() ...", e); + } + setTimeForMetricsLogger(); + String msg; + try { + evacuateServerNested(rc, service, server, provider, targetHost); + } catch (ZoneException e) { + msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(), + e.getMessage()); + logger.error(msg, e); + metricsLogger.error(msg); + throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server); + } + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server); + } + rc.reset(); + } + + private void evacuateServerNested(RequestContext rcCtx, ComputeService svc, Server server, Provider provider, + String targetHost) throws ZoneException, RequestFailedException { + String msg; + Context ctx = server.getContext(); + rcCtx.reset(); + while (rcCtx.attempt()) { + try { + logger.debug("Calling CDP moveServer - server id = " + server.getId()); + svc.moveServer(server.getId(), targetHost); + // Wait for completion, expecting the server to go to a non pending state + waitForStateChange(rcCtx, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR, + Server.Status.SUSPENDED, Server.Status.PAUSED); + break; + } catch (ContextConnectionException e) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), svc.getURL(), + ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(), + Long.toString(rcCtx.getRetryDelay()), Integer.toString(rcCtx.getAttempts()), + Integer.toString(rcCtx.getRetryLimit())); + logger.error(msg, e); + metricsLogger.error(msg, e); + rcCtx.delay(); + } + } + } + + /** + * @see ProviderAdapter#evacuateServer(java.util.Map, + * org.onap.ccsdk.sli.core.sli.SvcLogicContext) + */ + private Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException { + Server server = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + setTimeForMetricsLogger(); + String msg; + ctx.setAttribute(EVACUATE_STATUS, "ERROR"); + try { + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME); + + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + VMURL vm = VMURL.parseURL(vmUrl); + if (validateVM(rc, appName, vmUrl, vm)) { + return null; + } + server = evacuateServerMapNestedFirst(params, server, rc, ctx, vm, vmUrl); + } catch (RequestFailedException e) { + msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage()); + logger.error(msg, e); + metricsLogger.error(msg); + doFailure(rc, e.getStatus(), e.getMessage()); + } + return server; + } + + private Server evacuateServerMapNestedFirst(Map<String, String> params, Server server, RequestContext rqstCtx, + SvcLogicContext ctx, VMURL vm, String vmUrl) throws SvcLogicException { + String msg; + Context context; + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + // retrieve the optional parameters + String rebuildVm = params.get(ProviderAdapter.PROPERTY_REBUILD_VM); + String targetHostId = params.get(ProviderAdapter.PROPERTY_TARGETHOST_ID); + String tenantName = "Unknown";// to be used also in case of exception + try { + context = getContext(rqstCtx, vmUrl, identStr); + if (context != null) { + tenantName = context.getTenantName();// this variable also is used in case of exception + server = lookupServer(rqstCtx, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString()); + // check target host status + checkHostStatus(server, targetHostId, context); + // save hypervisor name before evacuate + String hypervisor = server.getHypervisor().getHostName(); + evacuateServer(rqstCtx, server, targetHostId); + server.refreshAll(); + String hypervisorAfterEvacuate = server.getHypervisor().getHostName(); + logger.debug( + "Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisorAfterEvacuate); + // check hypervisor host name after evacuate. If it is unchanged, the evacuate + // failed. + checkHypervisor(server, hypervisor, hypervisorAfterEvacuate); + // check VM status after evacuate + checkStatus(server); + context.close(); + doSuccess(rqstCtx); + ctx.setAttribute(EVACUATE_STATUS, "SUCCESS"); + // If a snapshot exists, do a rebuild to apply the latest snapshot to the + // evacuated server. + // This is the default behavior unless the optional parameter is set to FALSE. + if (rebuildVm == null || !"false".equalsIgnoreCase(rebuildVm)) { + List<Image> snapshots = server.getSnapshots(); + if (snapshots == null || snapshots.isEmpty()) { + logger.debug("No snapshots available - skipping rebuild after evacuate"); + } else if (paImpl != null) { + logger.debug("Executing a rebuild after evacuate"); + paImpl.rebuildServer(params, ctx); + // Check error code for rebuild errors. Evacuate had set it to 200 after + // a successful evacuate. Rebuild updates the error code. + evacuateServerMapNestedSecond(server, rqstCtx, ctx, hypervisor, hypervisorAfterEvacuate); + } + } + } + } catch (ResourceNotFoundException e) { + msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl); + logger.error(msg); + metricsLogger.error(msg); + doFailure(rqstCtx, HttpStatus.NOT_FOUND_404, msg); + } catch (RequestFailedException e) { + logger.error("Request failed", e); + doFailure(rqstCtx, e.getStatus(), e.getMessage()); + } catch (IOException | ZoneException e1) { + msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), + Operation.EVACUATE_SERVICE.toString(), vmUrl, tenantName); + logger.error(msg, e1); + metricsLogger.error(msg, e1); + doFailure(rqstCtx, HttpStatus.INTERNAL_SERVER_ERROR_500, e1.getMessage()); + } catch (Exception e1) { + msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), + Operation.EVACUATE_SERVICE.toString(), vmUrl, tenantName); + logger.error(msg, e1); + metricsLogger.error(msg); + doFailure(rqstCtx, HttpStatus.INTERNAL_SERVER_ERROR_500, e1.getMessage()); + } + return server; + } + + private void evacuateServerMapNestedSecond(Server server, RequestContext rc, SvcLogicContext ctx, String hypervisor, + String hypervisorAfterEvacuate) { + String msg; + String rebuildErrorCode = ctx.getAttribute(Constants.ATTRIBUTE_ERROR_CODE); + if (rebuildErrorCode != null) { + try { + int errorCode = Integer.parseInt(rebuildErrorCode); + if (errorCode != HttpStatus.OK_200.getStatusCode()) { + logger.debug("Rebuild after evacuate failed - error code=" + errorCode + ", message=" + + ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED, server.getName(), hypervisor, + hypervisorAfterEvacuate, ctx.getAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE)); + logger.error(msg); + metricsLogger.error(msg); + ctx.setAttribute(EVACUATE_STATUS, "ERROR"); + // update error message while keeping the error code the + // same as before + doFailure(rc, HttpStatus.getHttpStatus(errorCode), msg); + } + } catch (NumberFormatException e) { + // ignore + } + } + } + + private void checkHostStatus(Server server, String targetHostId, Context context) + throws ZoneException, RequestFailedException { + if (isComputeNodeDown(context, targetHostId)) { + String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(), + "Target host " + targetHostId + " status is not UP/ENABLED"); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_REQUEST_400, server); + } + } + + private void checkHypervisor(Server server, String hypervisor, String hypervisorAfterEvacuate) + throws RequestFailedException { + if (hypervisor != null && hypervisor.equals(hypervisorAfterEvacuate)) { + String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(), + "Hypervisor host " + hypervisor + + " after evacuate is the same as before evacuate. Provider (ex. Openstack) recovery actions may be needed."); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server); + } + } + + private void checkStatus(Server server) throws RequestFailedException { + if (server.getStatus() == Server.Status.ERROR) { + String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(), + "VM is in ERROR state after evacuate. Provider (ex. Openstack) recovery actions may be needed."); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server); + } + } + + /** + * Check if a Compute node is down. + * + * This method attempts to find a given host in the list of hypervisors for a + * given context. The only case where a node is considered down is if a matching + * hypervisor is found and it's state and status are not UP/ENABLED. + * + * @param context + * The current context + * + * @param host + * The host name (short or fully qualified) of a compute node + * + * @return true if the node is determined as down, false for all other cases + */ + private boolean isComputeNodeDown(Context context, String host) throws ZoneException { + ComputeService service = context.getComputeService(); + boolean nodeDown = false; + if (host != null && !host.isEmpty()) { + List<Hypervisor> hypervisors = service.getHypervisors(); + logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray())); + for (Hypervisor hv : hypervisors) { + nodeDown = isNodeDown(host, nodeDown, hv); + } + } + return nodeDown; + } + + private boolean isNodeDown(String host, boolean nodeDown, Hypervisor hv) { + if (isHostMatchesHypervisor(host, hv)) { + State hstate = hv.getState(); + Status hstatus = hv.getStatus(); + logger.debug("Host matching hypervisor: " + hv.getHostName() + ", State/Status: " + hstate.toString() + "/" + + hstatus.toString()); + if (hstate != State.UP || hstatus != Status.ENABLED) { + return true; + } + } + return nodeDown; + } + + private boolean isHostMatchesHypervisor(String host, Hypervisor hypervisor) { + return hypervisor.getHostName().startsWith(host); + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", Constants.ADAPTER_NAME); + logOperation(Msg.EVACUATING_SERVER, params, context); + setTimeForMetricsLogger(); + metricsLogger.info("Executing Provider Operation: Evacuate"); + return evacuateServer(params, context); + } + + private void setTimeForMetricsLogger() { + String timestamp = LoggingUtils.generateTimestampStr((new Date()).toInstant()); + MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp); + MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp); + MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0"); + MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE); + MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp"); + MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "evacuate server"); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, + "org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.EvacuateServer"); + } + + public void setProvideAdapterRef(ProviderAdapterImpl pai) { + paImpl = pai; + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/LookupServer.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/LookupServer.java new file mode 100644 index 000000000..7ad1190e2 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/LookupServer.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Modification Copyright (C) 2019 IBM + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import java.io.IOException; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.utils.logging.Msg; + +public class LookupServer extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LookupServer.class); + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + private static final String SERVERFOUND = "serverFound"; + + public Server lookupServer(Map<String, String> params, SvcLogicContext ctx) { + Server server = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); // should we test the return and fail if false? + + String vmUrl = null; + try { + // process vmUrl + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME); + + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + VMURL vm = VMURL.parseURL(vmUrl); + if (validateVM(rc, appName, vmUrl, vm)) { + return null; + } + server = lookupServerNested(params, server, rc, ctx, appName, vm, vmUrl); + } catch (RequestFailedException e) { + // parameters not valid, unable to connect to provider + String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl); + logger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg); + ctx.setAttribute(SERVERFOUND, "failure"); + } + return server; + } + + private Server lookupServerNested(Map<String, String> params, Server server, RequestContext rqstCtx, SvcLogicContext ctx, + String appName, VMURL vm, String vmUrl) { + + // use try with resource to ensure context is closed (returned to pool) + try (Context context = resolveContext(rqstCtx, params, appName, vmUrl)) { + // resloveContext & getContext call doFailure and log errors before returning null + if (context != null) { + rqstCtx.reset(); + server = lookupServer(rqstCtx, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString()); + ctx.setAttribute(SERVERFOUND, "success"); + String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "LookupServer", vmUrl); + ctx.setAttribute(Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + doSuccess(rqstCtx); + } + } catch (ZoneException e) { + // server not found + String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl); + logger.error(msg); + doFailure(rqstCtx, HttpStatus.NOT_FOUND_404, msg); + ctx.setAttribute(SERVERFOUND, "failure"); + } catch (IOException e) { + // exception closing context + String msg = EELFResourceManager.format(Msg.CLOSE_CONTEXT_FAILED, e, vmUrl); + logger.error(msg); + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, + e1.getClass().getSimpleName(), Operation.LOOKUP_SERVICE.toString(), vmUrl, "Unknown"); + logger.error(msg, e1); + doFailure(rqstCtx, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + return server; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.LOOKUP_SERVICE.toString(), "App-C IaaS Adapter:LookupServer", Constants.ADAPTER_NAME); + logOperation(Msg.LOOKING_SERVER_UP, params, context); + return lookupServer(params, context); + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/MigrateServer.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/MigrateServer.java new file mode 100644 index 000000000..cce0a86fa --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/MigrateServer.java @@ -0,0 +1,236 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modification Copyright (C) 2019 IBM + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ContextConnectionException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.ComputeService; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.utils.logging.LoggingConstants; +import org.onap.ccsdk.sli.core.utils.logging.LoggingUtils; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.onap.ccsdk.sli.adaptors.iaas.Property; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.slf4j.MDC; + +public class MigrateServer extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(MigrateServer.class); + private static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + /** + * A list of valid initial VM statuses for a migrate operations + */ + private final Collection<Server.Status> migratableStatuses = Arrays.asList(Server.Status.READY, + Server.Status.RUNNING, Server.Status.SUSPENDED); + + private String getConnectionExceptionMessage(RequestContext rc, Context ctx, ZoneException e) throws ZoneException { + return EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, ctx.getProvider().getName(), + ctx.getComputeService().getURL(), ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + } + + private void migrateServer(RequestContext rc, Server server, SvcLogicContext svcCtx) + throws ZoneException, RequestFailedException { + String msg; + Context ctx = server.getContext(); + ComputeService service = ctx.getComputeService(); + // Init status will equal final status + Server.Status initialStatus = server.getStatus(); + if (initialStatus == null) { + throw new ZoneException("Failed to determine server's starting status"); + } + // We can only migrate certain statuses + if (!migratableStatuses.contains(initialStatus)) { + throw new ZoneException(String.format("Cannot migrate server that is in %s state. Must be in one of [%s]", + initialStatus, migratableStatuses)); + } + setTimeForMetricsLogger(); + // Is the skip Hypervisor check attribute populated? + String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK); + if (skipHypervisorCheck == null && svcCtx != null) { + skipHypervisorCheck = svcCtx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK); + } + // Always perform Hypervisor check + // unless the skip is set to true + if (skipHypervisorCheck == null || (!(("true").equalsIgnoreCase(skipHypervisorCheck)))) { + // Check of the Hypervisor for the VM Server is UP and reachable + checkHypervisor(server); + } + + boolean inConfirmPhase = false; + rc.reset(); + try { + while (rc.attempt()) { + try { + if (!inConfirmPhase) { + // Initial migrate request + service.migrateServer(server.getId()); + // Wait for change to verify resize + waitForStateChange(rc, server, Server.Status.READY); + inConfirmPhase = true; + } + if (server.getStatus() != null && server.getStatus().equals(Server.Status.ERROR)) { + msg = "Cannot Perform 'processResize' in vm_state " + Server.Status.ERROR; + logger.info(msg); + msg = EELFResourceManager.format(Msg.MIGRATE_SERVER_FAILED, service.getURL()); + logger.error(msg); + logger.info(msg); + throw new RequestFailedException("Waiting for State Change", msg, HttpStatus.CONFLICT_409, + server); + } else { + // Verify resize + logger.debug("MigrateServer: Before service.processResize"); + service.processResize(server); + logger.debug("MigrateServer:before 2nd waitForStateChange Current Status:" + server.getStatus() + + " Initail Status: " + initialStatus); + // Wait for complete. will go back to init status + waitForStateChange(rc, server, initialStatus); + logger.info("Completed migrate request successfully"); + metricsLogger.info("Completed migrate request successfully"); + return; + } + } catch (ContextConnectionException e) { + msg = getConnectionExceptionMessage(rc, ctx, e); + if (server.getStatus() != null && server.getStatus().equals(Server.Status.ERROR)) { + throw new RequestFailedException("Migrate Server", msg, HttpStatus.CONFLICT_409, server); + } else { + logger.info("Migrate Server: Going to delay in ConnectionException"); + logger.debug("Server Status: " + server.getStatus()); + rc.delay(); + } + } + + } + + } catch (ZoneException e) { + String phase = inConfirmPhase ? "VERIFY MIGRATE" : "REQUEST MIGRATE"; + msg = EELFResourceManager.format(Msg.MIGRATE_SERVER_FAILED, server.getName(), server.getId(), phase, + e.getMessage()); + + logger.error(msg, e); + throw new RequestFailedException("Migrate Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server); + } + } + + /** + * @see ProviderAdapter#migrateServer(java.util.Map, + * org.onap.ccsdk.sli.core.sli.SvcLogicContext) + */ + private Server migrateServer(Map<String, String> params, SvcLogicContext ctx) { + Server server = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + setTimeForMetricsLogger(); + try { + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME); + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + VMURL vm = VMURL.parseURL(vmUrl); + if (validateVM(rc, appName, vmUrl, vm)) + return null; + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + server = conductServerMigration(rc, vmUrl, identStr, ctx); + } catch (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + } + return server; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.MIGRATE_SERVICE.toString(), "App-C IaaS Adapter:Migrate", Constants.ADAPTER_NAME); + logOperation(Msg.MIGRATING_SERVER, params, context); + setTimeForMetricsLogger(); + metricsLogger.info("Executing Provider Operation: Migrate"); + return migrateServer(params, context); + } + + private void setTimeForMetricsLogger() { + String timestamp = LoggingUtils.generateTimestampStr((new Date()).toInstant()); + MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp); + MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp); + MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0"); + MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE); + MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp"); + MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "migrate server"); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, + "org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.MigrateServer"); + + } + + private Server conductServerMigration(RequestContext rc, String vmUrl, String identStr, SvcLogicContext ctx) + throws RequestFailedException { + String msg; + Context context = getContext(rc, vmUrl, identStr); + VMURL vm = VMURL.parseURL(vmUrl); + Server server = null; + try { + if (context != null) { + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString()); + migrateServer(rc, server, ctx); + server.refreshStatus(); + context.close(); + doSuccess(rc); + } + } catch (IOException | ZoneException e1) { + msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), + Operation.MIGRATE_SERVICE.toString(), vmUrl, context.getTenantName()); + logger.error(msg, e1); + metricsLogger.error(msg); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + return server; + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/RebootServer.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/RebootServer.java new file mode 100644 index 000000000..02a46b71e --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/RebootServer.java @@ -0,0 +1,182 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * Modifications Copyright (C) 2019 IBM + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.exceptions.StateException; +import com.att.cdp.zones.ComputeService; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import java.util.Map; +import java.util.concurrent.TimeoutException; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.onap.ccsdk.sli.adaptors.iaas.Property; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class RebootServer extends ProviderServerOperation { + private final EELFLogger logger = EELFManager.getInstance().getLogger(RebootServer.class); + private static final Configuration config = ConfigurationFactory.getConfiguration(); + private static final Integer NO_OF_ATTEMPTS = 30; + private static final Integer RETRY_INTERVAL = 10; + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.REBOOT_SERVICE.toString(), "App-C IaaS Adapter:rebootServer", Constants.ADAPTER_NAME); + return rebootServer(params, context); + } + + private Server rebootServer(Map<String, String> params, SvcLogicContext ctx){ + Server server = null; + RequestContext requestContext = new RequestContext(ctx); + requestContext.isAlive(); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + String rebooType = params.get(ProviderAdapter.REBOOT_TYPE); + String tenantName = "Unknown"; + if (rebooType.isEmpty()) { + rebooType = "SOFT"; + } + logger.info("reboot type" + rebooType); + if (ctx != null) { + try { + VMURL vm = VMURL.parseURL(vmUrl); + Context context; + // to be used also in case of exception + if (validateVM(requestContext, appName, vmUrl, vm)) { + return null; + } + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + context = getContext(requestContext, vmUrl, identStr); + // Is the skip Hypervisor check attribute populated? + String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK); + if (skipHypervisorCheck == null && ctx != null) { + skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK); + } + if (context != null) { + tenantName = context.getTenantName();// this variable also is + // used in case of exception + requestContext.reset(); + server = lookupServer(requestContext, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString()); + // Always perform Hypervisor check + // unless the skip is set to true + if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) { + // Check of the Hypervisor for the VM Server is UP and reachable + checkHypervisor(server); + } + Context contx = server.getContext(); + ComputeService service = contx.getComputeService(); + logger.info("performing reboot action for " + server.getId() + " rebootype " + rebooType); + service.rebootServer(server.getId(), rebooType); + if (waitForServerStatusChange(requestContext, server, vmUrl, Server.Status.RUNNING)) { + ctx.setAttribute("REBOOT_STATUS", "SUCCESS"); + doSuccess(requestContext); + } else { + ctx.setAttribute("REBOOT_STATUS", "FAILURE"); + } + context.close(); + } else { + ctx.setAttribute("REBOOT_STATUS", "FAILURE"); + } + + } catch (ResourceNotFoundException | StateException ex) { + ctx.setAttribute("REBOOT_STATUS", "FAILURE"); + if (ex instanceof ResourceNotFoundException) { + doFailure(requestContext, HttpStatus.NOT_FOUND_404, ex.getMessage()); + } else { + doFailure(requestContext, HttpStatus.CONFLICT_409, ex.getMessage()); + } + } catch (Exception ex) { + ctx.setAttribute("REBOOT_STATUS", "FAILURE"); + doFailure(requestContext, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.getMessage()); + } + } + return server; + } + + private boolean waitForServerStatusChange(RequestContext rc, Server server, String vmUrl, + Server.Status... desiredStates) throws Exception { + int pollInterval = RETRY_INTERVAL.intValue(); + int timeout = configuration.getIntegerProperty(Constants.PROPERTY_SERVER_STATE_CHANGE_TIMEOUT); + config.setProperty(Constants.PROPERTY_RETRY_DELAY, RETRY_INTERVAL.toString()); + config.setProperty(Constants.PROPERTY_RETRY_LIMIT, NO_OF_ATTEMPTS.toString()); + String msg; + boolean status = false; + while (rc.attempt()) { + if ( Server.Status.ERROR.equals(server.getStatus())) { + msg = "Device status " + Server.Status.ERROR + " cannot proceed further"; + throw new RequestFailedException("Waiting for State Change", msg, HttpStatus.CONFLICT_409, server); + } else { + server.waitForStateChange(pollInterval, timeout, desiredStates); + if (Server.Status.RUNNING.equals(server.getStatus()) + || Server.Status.READY.equals(server.getStatus())) { + status = true; + } + logger.info(server.getStatus() + " status "); + } + if (status) { + logger.info("Done Trying " + rc.getAttempts() + " attempts"); + break; + } else { + rc.delay(); + } + } + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, vmUrl); + logger.info("waitForStateChange Failed"); + logger.error(msg); + throw new RequestFailedException("Waiting for State Change", msg, HttpStatus.BAD_GATEWAY_502, server); + } + if ((rc.getAttempts() == NO_OF_ATTEMPTS) && (!status)) { + + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, Long.toString(rc.getRetryDelay()), + Integer.toString(rc.getAttempts()), Integer.toString(rc.getRetryLimit())); + logger.error(msg); + throw new TimeoutException(msg); + } + rc.reset(); + logger.info("Reboot server status flag --> " + status); + return status; + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/RebuildServer.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/RebuildServer.java new file mode 100644 index 000000000..516b38e23 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/RebuildServer.java @@ -0,0 +1,508 @@ +/* +* ============LICENSE_START======================================================= +* ONAP : APPC +* ================================================================================ +* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. +* ================================================================================ +* Copyright (C) 2017 Amdocs +* ============================================================================= +* Modifications Copyright (C) 2019 IBM +* ============================================================================= +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* ============LICENSE_END========================================================= +*/ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ContextConnectionException; +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.exceptions.StateException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.ComputeService; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.ImageService; +import com.att.cdp.zones.Provider; +import com.att.cdp.zones.model.Image; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.cdp.zones.model.ServerBootSource; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Date; +import java.util.List; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.Property; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Outcome; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.utils.logging.LoggingConstants; +import org.onap.ccsdk.sli.core.utils.logging.LoggingUtils; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.slf4j.MDC; + +public class RebuildServer extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RebuildServer.class); + private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + // the sleep time used by thread.sleep to give "some time for OpenStack to start + // processing the request" + private long rebuildSleepTime = 10L * 1000L; + + /** + * Rebuild the indicated server with the indicated image. This method assumes + * the server has been determined to be in the correct state to do the rebuild. + * + * @param rc + * The request context that manages the state and recovery of the + * request for the life of its processing. + * @param server + * the server to be rebuilt + * @param image + * The image to be used (or snapshot) + * @throws RequestFailedException + * if the server does not change state in the allotted time + */ + @SuppressWarnings("nls") + private void rebuildServer(RequestContext rc, Server server, String image) throws RequestFailedException { + logger.debug(Msg.REBUILD_SERVER, server.getId()); + String msg; + Context context = server.getContext(); + Provider provider = context.getProvider(); + ComputeService service = context.getComputeService(); + /* + * Set Time for Metrics Logger + */ + setTimeForMetricsLogger(); + try { + while (rc.attempt()) { + try { + server.rebuild(image); + break; + } catch (ContextConnectionException e) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(), + context.getTenant().getName(), context.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + metricsLogger.error(msg, e); + rc.delay(); + } + } + /* + * We need to provide some time for OpenStack to start processing the request. + */ + try { + Thread.sleep(rebuildSleepTime); + } catch (InterruptedException e) { + logger.trace("Sleep threw interrupted exception, should never occur"); + metricsLogger.trace("Sleep threw interrupted exception, should never occur"); + Thread.currentThread().interrupt(); + } + } catch (ZoneException e) { + msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(), + e.getMessage()); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server); + } + rc.reset(); + /* + * Once we have started the process, now we wait for the final state of stopped. + * This should be the final state (since we started the rebuild with the server + * stopped). + */ + waitForStateChange(rc, server, Server.Status.READY); + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server); + } + rc.reset(); + } + + /** + * This method is called to rebuild the provided server. + * <p> + * If the server was booted from a volume, then the request is failed + * immediately and no action is taken. Rebuilding a VM from a bootable volume, + * where the bootable volume itself is not rebuilt, serves no purpose. + * </p> + * + * @param rc + * The request context that manages the state and recovery of the + * request for the life of its processing. + * @param server + * The server to be rebuilt + * @throws ZoneException + * When error occurs + * @throws RequestFailedException + * When server status is error + */ + @SuppressWarnings("nls") + private void rebuildServer(RequestContext rc, Server server, SvcLogicContext ctx) + throws ZoneException, RequestFailedException { + ServerBootSource builtFrom = server.getBootSource(); + /* + * Set Time for Metrics Logger + */ + setTimeForMetricsLogger(); + String msg; + // Throw error if boot source is unknown + if (ServerBootSource.UNKNOWN.equals(builtFrom)) { + logger.debug("Boot Source Unknown"); + msg = String.format("Error occured when retrieving server boot source [%s]!!!", server.getId()); + logger.error(msg); + generateEvent(rc, false, msg); + metricsLogger.error(msg); + throw new RequestFailedException("Rebuild Server", msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server); + } + + // Throw exception for non image/snap boot source + if (ServerBootSource.VOLUME.equals(builtFrom)) { + logger.debug("Boot Source Not Supported built from bootable volume"); + msg = String.format("Rebuilding is currently not supported for servers built from bootable volumes [%s]", + server.getId()); + generateEvent(rc, false, msg); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Rebuild Server", msg, HttpStatus.FORBIDDEN_403, server); + } + /* + * Pending is a bit of a special case. If we find the server is in a pending + * state, then the provider is in the process of changing state of the server. + * So, lets try to wait a little bit and see if the state settles down to one we + * can deal with. If not, then we have to fail the request. + */ + Context context = server.getContext(); + Provider provider = context.getProvider(); + ComputeService service = context.getComputeService(); + if (server.getStatus().equals(Server.Status.PENDING)) { + rc.reset(); + waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR, + Server.Status.SUSPENDED, Server.Status.PAUSED); + } + // Is the skip Hypervisor check attribute populated? + String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK); + if (skipHypervisorCheck == null && ctx != null) { + skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK); + } + // Always perform Hypervisor Status checks + // unless the skip is set to true + if (skipHypervisorCheck == null || (!"true".equalsIgnoreCase(skipHypervisorCheck))) { + // Check of the Hypervisor for the VM Server is UP and reachable + checkHypervisor(server); + } + /* + * Get the image to use in this priority order: (1) If snapshot-id provided in + * the request, use this (2) If any snapshots exist, then the latest snapshot is + * used (3) Otherwise the image used to construct the VM is used. + */ + String imageToUse = ""; + try { + ObjectMapper mapper = new ObjectMapper(); + String payloadStr = configuration.getProperty(Property.PAYLOAD); + if (payloadStr == null || payloadStr.isEmpty()) { + payloadStr = ctx.getAttribute(ProviderAdapter.PAYLOAD); + } + JsonNode payloadNode = mapper.readTree(payloadStr); + imageToUse = payloadNode.get(ProviderAdapter.PROPERTY_REQUEST_SNAPSHOT_ID).textValue(); + logger.debug("Pulled snapshot-id " + imageToUse + " from the payload"); + } catch (Exception e) { + logger.debug("Exception attempting to pull snapshot-id from the payload: " + e.toString()); + } + List<Image> snapshots = server.getSnapshots(); + ImageService imageService = server.getContext().getImageService(); + List<Image> imageList = imageService.listImages(); + if (!imageToUse.isEmpty()) { + logger.debug("Using snapshot-id " + imageToUse + " for the rebuild request"); + boolean imgFound = validateSnapshotId(imageToUse, snapshots, imageList); + + if (!imgFound) { + logger.debug("Image Snapshot Not Found"); + msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(), + "Invalid Snapshot-Id"); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Rebuild Server", msg, HttpStatus.FORBIDDEN_403, server); + } + } else if (snapshots != null && !snapshots.isEmpty()) { + logger.debug("Using snapshot-id when image is Empty" + imageToUse + " for the rebuild request"); + imageToUse = snapshots.get(0).getId(); + } else { + imageToUse = server.getImage(); + rc.reset(); + try { + while (rc.attempt()) { + try { + /* + * We are just trying to make sure that the image exists. We arent interested in + * the details at this point. + */ + imageService.getImage(imageToUse); + break; + } catch (ContextConnectionException e) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), + imageService.getURL(), context.getTenant().getName(), context.getTenant().getId(), + e.getMessage(), Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + metricsLogger.error(msg); + rc.delay(); + } + } + } catch (ZoneException e) { + msg = EELFResourceManager.format(Msg.IMAGE_NOT_FOUND, imageToUse, "rebuild"); + generateEvent(rc, false, msg); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server); + } + } + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server); + } + rc.reset(); + /* + * We determine what to do based on the current state of the server + */ + switch (server.getStatus()) { + case DELETED: + // Nothing to do, the server is gone + msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(), server.getTenantId(), + "rebuilt"); + generateEvent(rc, false, msg); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server); + case RUNNING: + // Attempt to stop the server, then rebuild it + stopServer(rc, server); + rc.reset(); + rebuildServer(rc, server, imageToUse); + rc.reset(); + startServer(rc, server); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + metricsLogger.info("Server status: RUNNING"); + break; + case ERROR: + msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(), + server.getTenantId(), "rebuild"); + generateEvent(rc, false, msg); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server); + case READY: + // Attempt to rebuild the server + rebuildServer(rc, server, imageToUse); + rc.reset(); + startServer(rc, server); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + metricsLogger.info("Server status: READY"); + break; + case PAUSED: + // if paused, un-pause it, stop it, and rebuild it + unpauseServer(rc, server); + rc.reset(); + stopServer(rc, server); + rc.reset(); + rebuildServer(rc, server, imageToUse); + rc.reset(); + startServer(rc, server); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + metricsLogger.info("Server status: PAUSED"); + break; + case SUSPENDED: + // Attempt to resume the suspended server, stop it, and rebuild it + resumeServer(rc, server); + rc.reset(); + stopServer(rc, server); + rc.reset(); + rebuildServer(rc, server, imageToUse); + rc.reset(); + startServer(rc, server); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + metricsLogger.info("Server status: SUSPENDED"); + break; + default: + // Hmmm, unknown status, should never occur + msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(), + server.getTenantId(), server.getStatus().name()); + generateEvent(rc, false, msg); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server); + } + } + + /** + * @see ProviderAdapter#rebuildServer(java.util.Map, + * org.onap.ccsdk.sli.core.sli.SvcLogicContext) + */ + @SuppressWarnings("nls") + public Server rebuildServer(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException { + Server server = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + setTimeForMetricsLogger(); + String msg; + try { + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + VMURL vm = VMURL.parseURL(vmUrl); + if (validateVM(rc, appName, vmUrl, vm)) + return null; + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + ctx.setAttribute("REBUILD_STATUS", "ERROR"); + Context context = null; + String tenantName = "Unknown";// to be used also in case of exception + try { + context = getContext(rc, vmUrl, identStr); + if (context != null) { + tenantName = context.getTenantName();// this varaible also is used in case of exception + rc.reset(); + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString()); + // Manually checking image service until new PAL release + if (hasImageAccess(rc, context)) { + rebuildServer(rc, server, ctx); + doSuccess(rc); + ctx.setAttribute("REBUILD_STATUS", "SUCCESS"); + } else { + msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(), + "Accessing Image Service Failed"); + logger.error(msg); + metricsLogger.error(msg); + doFailure(rc, HttpStatus.FORBIDDEN_403, msg); + } + context.close(); + } else { + ctx.setAttribute("REBUILD_STATUS", "CONTEXT_NOT_FOUND"); + } + } catch (StateException ex) { + logger.error(ex.getMessage()); + ctx.setAttribute("REBUILD_STATUS", "ERROR"); + doFailure(rc, HttpStatus.CONFLICT_409, ex.getMessage()); + } catch (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + ctx.setAttribute("REBUILD_STATUS", "ERROR"); + } catch (ResourceNotFoundException e) { + msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl); + ctx.setAttribute("REBUILD_STATUS", "ERROR"); + logger.error(msg); + metricsLogger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg); + } catch (Exception e1) { + msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), + Operation.STOP_SERVICE.toString(), vmUrl, tenantName); + ctx.setAttribute("REBUILD_STATUS", "ERROR"); + logger.error(msg, e1); + metricsLogger.error(msg); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + } catch (RequestFailedException e) { + ctx.setAttribute("REBUILD_STATUS", "ERROR"); + doFailure(rc, e.getStatus(), e.getMessage()); + } + return server; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.REBUILD_SERVICE.toString(), "App-C IaaS Adapter:Rebuild", Constants.ADAPTER_NAME); + logOperation(Msg.REBUILDING_SERVER, params, context); + setTimeForMetricsLogger(); + metricsLogger.info("Executing Provider Operation: Rebuild"); + return rebuildServer(params, context); + } + + private void setTimeForMetricsLogger() { + String timestamp = LoggingUtils.generateTimestampStr(((Date) new Date()).toInstant()); + MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp); + MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp); + MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0"); + MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE); + MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp"); + MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "rebuild server"); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, + "org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.RebuildServer"); + + } + + /** + * Sets the sleep time used by thread.sleep to give "some time for OpenStack to + * start processing the request". + * + * @param millis + * Time to sleep in milliseconds + */ + public void setRebuildSleepTime(long millis) { + this.rebuildSleepTime = millis; + } + + private boolean validateSnapshotId(String imageToUse, List<Image> snapshotList, List<Image> imageList) { + + logger.debug("Validating snapshot-id " + imageToUse + " for the rebuild request from payload"); + boolean imageFound = false; + // If image is empty , the validation si not required . Hence return false. + // Ideally function should not be called with empty image Id + if (imageToUse.isEmpty()) { + return imageFound; + } else { + // The supplied snapshot id can be a snapshot id or an image Id. Check both + // available for the vnf. + // Check against snapshot id list and image list + return findImageExists(snapshotList, imageToUse, "snapshotidList") + || findImageExists(imageList, imageToUse, "imageidList"); + } + } + + boolean findImageExists(List<Image> list, String imageToUse, String source) { + boolean imageExists = false; + logger.debug("Available Image-ids from :" + source + "Start\n"); + for (Image img : list) { + String imgId = img.getId(); + logger.debug("Image Id - " + imgId + "\n"); + if (imgId.equals(imageToUse)) { + logger.debug("Image found in available " + source); + imageExists = true; + break; + } + } + return imageExists; + + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/RestartServer.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/RestartServer.java new file mode 100644 index 000000000..03bcf2ad0 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/RestartServer.java @@ -0,0 +1,258 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import java.util.Date; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.logging.LoggingConstants; +import org.onap.ccsdk.sli.core.utils.logging.LoggingUtils; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.onap.ccsdk.sli.adaptors.iaas.Property; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Outcome; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.slf4j.MDC; + +public class RestartServer extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestartServer.class); + private static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + + /** + * This method handles the case of restarting a server once we have found the + * server and have obtained the abstract representation of the server via the + * context (i.e., the "Server" object from the CDP-Zones abstraction). + * + * @param rc + * The request context that manages the state and recovery of the + * request for the life of its processing. + * @param server + * The server object representing the server we want to operate on + * @throws ZoneException + * when error occurs. + * @throws RequestFailedException + * when server status is error. + */ + @SuppressWarnings("nls") + private void restartServer(RequestContext rc, Server server, SvcLogicContext ctx) + throws ZoneException, RequestFailedException { + /* + * Pending is a bit of a special case. If we find the server is in a pending + * state, then the provider is in the process of changing state of the server. + * So, lets try to wait a little bit and see if the state settles down to one we + * can deal with. If not, then we have to fail the request. + */ + String msg; + if (server.getStatus().equals(Server.Status.PENDING)) { + waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR, + Server.Status.SUSPENDED, Server.Status.PAUSED); + } + setTimeForMetricsLogger("restart server"); + String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK); + if (skipHypervisorCheck == null && ctx != null) { + skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK); + } + // Always perform Virtual Machine/Hypervisor Status/Network checks + // unless the skip is set to true + if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) { + // Check of the Hypervisor for the VM Server is UP and reachable + checkHypervisor(server); + } + /* + * We determine what to do based on the current state of the server + */ + switch (server.getStatus()) { + case DELETED: + // Nothing to do, the server is gone + msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(), server.getTenantId(), + "restarted"); + generateEvent(rc, false, msg); + logger.error(msg); + metricsLogger.error(msg); + break; + case RUNNING: + // Attempt to stop and start the server + stopServer(rc, server); + startServer(rc, server); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + metricsLogger.info("Server status: RUNNING"); + break; + case ERROR: + msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(), + server.getTenantId(), "restart"); + generateEvent(rc, false, msg); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Restart Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server); + case READY: + // Attempt to start the server + startServer(rc, server); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + metricsLogger.info("Server status: READY"); + break; + case PAUSED: + // if paused, un-pause it + unpauseServer(rc, server); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + metricsLogger.info("Server status: PAUSED"); + break; + case SUSPENDED: + // Attempt to resume the suspended server + resumeServer(rc, server); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + metricsLogger.info("Server status: SUSPENDED"); + break; + default: + // Hmmm, unknown status, should never occur + msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(), + server.getTenantId(), server.getStatus().name()); + generateEvent(rc, false, msg); + logger.error(msg); + metricsLogger.error(msg); + break; + } + } + + /** + * This method is used to restart an existing virtual machine given the fully + * qualified URL of the machine. + * <p> + * The fully qualified URL contains enough information to locate the appropriate + * server. The URL is of the form + * + * <pre> + * [scheme]://[host[:port]] / [path] / [tenant_id] / servers / [vm_id] + * </pre> + * + * Where the various parts of the URL can be parsed and extracted and used to + * locate the appropriate service in the provider service catalog. This then + * allows us to open a context using the CDP abstraction, obtain the server by + * its UUID, and then perform the restart. + * </p> + * + * @throws SvcLogicException + * If the provider cannot be found + * @throws IllegalArgumentException + * if the expected argument(s) are not defined or are invalid + * @see ProviderAdapter#restartServer(java.util.Map, + * org.onap.ccsdk.sli.core.sli.SvcLogicContext) + */ + @SuppressWarnings("nls") + private Server restartServer(Map<String, String> params, SvcLogicContext ctx) + throws SvcLogicException, IllegalArgumentException { + Server server = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + /* + * Set Time for Metrics Logger + */ + setTimeForMetricsLogger("GET server status"); + ctx.setAttribute("RESTART_STATUS", "ERROR"); + try { + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME); + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + VMURL vm = VMURL.parseURL(vmUrl); + if (validateVM(rc, appName, vmUrl, vm)) + return null; + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + Context context = null; + String tenantName = "Unknown";// to be used also in case of exception + try { + context = getContext(rc, vmUrl, identStr); + if (context != null) { + tenantName = context.getTenantName();// this varaible also is used in case of exception + rc.reset(); + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString()); + rc.reset(); + restartServer(rc, server, ctx); + context.close(); + doSuccess(rc); + ctx.setAttribute("RESTART_STATUS", "SUCCESS"); + String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "RestartServer", vmUrl); + ctx.setAttribute(Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + } + } catch (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + } catch (ResourceNotFoundException e) { + String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl); + logger.error(msg); + metricsLogger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg); + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, + e1.getClass().getSimpleName(), Operation.RESTART_SERVICE.toString(), vmUrl, tenantName); + logger.error(msg, e1); + metricsLogger.error(msg, e1); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + } catch (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + } + return server; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.RESTART_SERVICE.toString(), "App-C IaaS Adapter:Restart", Constants.ADAPTER_NAME); + logOperation(Msg.RESTARTING_SERVER, params, context); + setTimeForMetricsLogger("execute restart"); + metricsLogger.info("Executing Provider Operation: Restart"); + return restartServer(params, context); + } + + private void setTimeForMetricsLogger(String targetServiceName) { + String timestamp = LoggingUtils.generateTimestampStr(((Date) new Date()).toInstant()); + MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp); + MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp); + MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0"); + MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE); + MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp"); + MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, targetServiceName); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, + "org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.RestartServer"); + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/RestoreStack.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/RestoreStack.java new file mode 100644 index 000000000..5345bdb4d --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/RestoreStack.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.openstack.OpenStackContext; +import com.att.cdp.openstack.connectors.HeatConnector; +import com.att.cdp.openstack.util.ExceptionMapper; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Stack; +import com.att.cdp.zones.spi.RequestState; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.heat.Heat; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderStackOperation; +import org.onap.ccsdk.sli.adaptors.openstack.heat.SnapshotResource; +import org.onap.ccsdk.sli.adaptors.openstack.heat.StackResource; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.logging.Msg; + +public class RestoreStack extends ProviderStackOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestoreStack.class); + + private void restoreStack(Stack stack, String snapshotId) throws ZoneException, RequestFailedException { + Context context = stack.getContext(); + + OpenStackContext osContext = (OpenStackContext) context; + + final HeatConnector heatConnector = osContext.getHeatConnector(); + ((OpenStackContext) context).refreshIfStale(heatConnector); + + trackRequest(context); + RequestState.put("SERVICE", "Orchestration"); + RequestState.put("SERVICE_URL", heatConnector.getEndpoint()); + + Heat heat = heatConnector.getClient(); + + SnapshotResource snapshotResource = new SnapshotResource(heat); + + try { + + snapshotResource.restore(stack.getName(), stack.getId(), snapshotId).execute(); + + // wait for the snapshot restore + StackResource stackResource = new StackResource(heat); + if (!waitForStack(stack, stackResource, "RESTORE_COMPLETE")) { + throw new RequestFailedException("Snapshot restore failed."); + } + + } catch (OpenStackBaseException e) { + ExceptionMapper.mapException(e); + } + + } + + public Stack restoreStack(Map<String, String> params, SvcLogicContext ctx) + throws SvcLogicException { + Stack stack = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + ctx.setAttribute("SNAPSHOT_STATUS", "STACK_NOT_FOUND"); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + + String vmUrl = null; + Context context = null; + String tenantName = "Unknown";//to be used also in case of exception + try { + + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME, ProviderAdapter.PROPERTY_STACK_ID, + ProviderAdapter.PROPERTY_INPUT_SNAPSHOT_ID); + + String stackId = params.get(ProviderAdapter.PROPERTY_STACK_ID); + vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + String snapshotId = params.get(ProviderAdapter.PROPERTY_INPUT_SNAPSHOT_ID); + + context = resolveContext(rc, params, appName, vmUrl); + + if (context != null) { + tenantName = context.getTenantName();//this varaible also is used in case of exception + stack = lookupStack(rc, context, stackId); + logger.debug(Msg.STACK_FOUND, vmUrl, tenantName, stack.getStatus().toString()); + logger.info(EELFResourceManager.format(Msg.TERMINATING_STACK, stack.getName())); + restoreStack(stack, snapshotId); + logger.info(EELFResourceManager.format(Msg.TERMINATE_STACK, stack.getName())); + context.close(); + doSuccess(rc); + } else { + ctx.setAttribute(Constants.DG_ATTRIBUTE_STATUS, "failure"); + } + + } catch (ResourceNotFoundException e) { + String msg = EELFResourceManager.format(Msg.STACK_NOT_FOUND, e, vmUrl); + logger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg, e); + } catch (RequestFailedException e) { + logger.error(EELFResourceManager.format(Msg.MISSING_PARAMETER_IN_REQUEST, e.getReason(), "restoreStack")); + doFailure(rc, e.getStatus(), e.getMessage(), e); + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), + "restoreStack", vmUrl, tenantName); + logger.error(msg, e1); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, e1); + } + return stack; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.RESTORE_STACK.toString(), "App-C IaaS Adapter:Restore-Stack", Constants.ADAPTER_NAME); + logOperation(Msg.RESTORING_STACK, params, context); + return restoreStack(params, context); + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/SnapshotStack.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/SnapshotStack.java new file mode 100644 index 000000000..efd4fe02b --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/SnapshotStack.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.openstack.OpenStackContext; +import com.att.cdp.openstack.connectors.HeatConnector; +import com.att.cdp.openstack.util.ExceptionMapper; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Stack; +import com.att.cdp.zones.spi.RequestState; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.heat.Heat; +import java.util.Date; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderStackOperation; +import org.onap.ccsdk.sli.adaptors.openstack.heat.SnapshotResource; +import org.onap.ccsdk.sli.adaptors.openstack.heat.StackResource; +import org.onap.ccsdk.sli.adaptors.openstack.heat.model.CreateSnapshotParams; +import org.onap.ccsdk.sli.adaptors.openstack.heat.model.Snapshot; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.logging.LoggingConstants; +import org.onap.ccsdk.sli.core.utils.logging.LoggingUtils; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.slf4j.MDC; + +public class SnapshotStack extends ProviderStackOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(SnapshotStack.class); + private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + + private Snapshot snapshotStack(@SuppressWarnings("unused") RequestContext rc, Stack stack) + throws ZoneException, RequestFailedException { + Snapshot snapshot = new Snapshot(); + Context context = stack.getContext(); + OpenStackContext osContext = (OpenStackContext) context; + final HeatConnector heatConnector = osContext.getHeatConnector(); + ((OpenStackContext) context).refreshIfStale(heatConnector); + trackRequest(context); + RequestState.put("SERVICE", "Orchestration"); + RequestState.put("SERVICE_URL", heatConnector.getEndpoint()); + Heat heat = heatConnector.getClient(); + SnapshotResource snapshotResource = new SnapshotResource(heat); + setTimeForMetricsLogger(); + try { + snapshot = snapshotResource.create(stack.getName(), stack.getId(), new CreateSnapshotParams()).execute(); + // wait for the stack deletion + StackResource stackResource = new StackResource(heat); + if (!waitForStack(stack, stackResource, "SNAPSHOT_COMPLETE")) { + throw new RequestFailedException("Stack Snapshot failed."); + } + } catch (OpenStackBaseException e) { + ExceptionMapper.mapException(e); + } + return snapshot; + } + + public Stack snapshotStack(Map<String, String> params, SvcLogicContext ctx) + throws IllegalArgumentException, SvcLogicException { + Stack stack = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + ctx.setAttribute("SNAPSHOT_STATUS", "STACK_NOT_FOUND"); + setTimeForMetricsLogger(); + String vmUrl = null; + Context context = null; + String tenantName = "Unknown";// to be used also in case of exception + try { + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME, ProviderAdapter.PROPERTY_STACK_ID); + String stackId = params.get(ProviderAdapter.PROPERTY_STACK_ID); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + context = resolveContext(rc, params, appName, vmUrl); + if (context != null) { + tenantName = context.getTenantName();// this varaible also is used in case of exception + stack = lookupStack(rc, context, stackId); + logger.debug(Msg.STACK_FOUND, vmUrl, tenantName, stack.getStatus().toString()); + logger.info(EELFResourceManager.format(Msg.SNAPSHOTING_STACK, stack.getName())); + metricsLogger.info(EELFResourceManager.format(Msg.SNAPSHOTING_STACK, stack.getName())); + Snapshot snapshot = snapshotStack(rc, stack); + ctx.setAttribute(ProviderAdapter.DG_OUTPUT_PARAM_NAMESPACE + ProviderAdapter.PROPERTY_SNAPSHOT_ID, + snapshot.getId()); + logger.info(EELFResourceManager.format(Msg.STACK_SNAPSHOTED, stack.getName(), snapshot.getId())); + metricsLogger.info(EELFResourceManager.format(Msg.STACK_SNAPSHOTED, stack.getName(), snapshot.getId())); + context.close(); + doSuccess(rc); + } else { + ctx.setAttribute(Constants.DG_ATTRIBUTE_STATUS, "failure"); + } + } catch (ResourceNotFoundException e) { + String msg = EELFResourceManager.format(Msg.STACK_NOT_FOUND, e, vmUrl); + logger.error(msg); + metricsLogger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg, e); + } catch (RequestFailedException e) { + logger.error(EELFResourceManager.format(Msg.MISSING_PARAMETER_IN_REQUEST, e.getReason(), "snapshotStack")); + metricsLogger.error( + EELFResourceManager.format(Msg.MISSING_PARAMETER_IN_REQUEST, e.getReason(), "snapshotStack")); + doFailure(rc, e.getStatus(), e.getMessage(), e); + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), + "snapshotStack", vmUrl, tenantName); + logger.error(msg, e1); + metricsLogger.error(msg); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, e1); + } + return stack; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.SNAPSHOT_STACK.toString(), "App-C IaaS Adapter:Snapshot-Stack", Constants.ADAPTER_NAME); + logOperation(Msg.SNAPSHOTING_STACK, params, context); + setTimeForMetricsLogger(); + metricsLogger.info("Executing Provider Operation: Snapshot Stack"); + return snapshotStack(params, context); + } + + private void setTimeForMetricsLogger() { + String timestamp = LoggingUtils.generateTimestampStr(((Date) new Date()).toInstant()); + MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp); + MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp); + MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0"); + MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE); + MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp"); + MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "snapshot stack"); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, + "org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.SnapshotStack"); + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/StartServer.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/StartServer.java new file mode 100644 index 000000000..a67bfcf57 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/StartServer.java @@ -0,0 +1,182 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.onap.ccsdk.sli.adaptors.iaas.Property; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class StartServer extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(StartServer.class); + + /** + * @see ProviderAdapter#startServer(java.util.Map, + * org.onap.ccsdk.sli.core.sli.SvcLogicContext) + */ + @SuppressWarnings("nls") + public Server startServer(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException { + Server server = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + try { + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME); + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + VMURL vm = VMURL.parseURL(vmUrl); + if (validateVM(rc, appName, vmUrl, vm)) + return null; + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + Context context = null; + String tenantName = "Unknown";// to be used also in case of exception + ctx.setAttribute("START_STATUS", "ERROR"); + // Is the skip Hypervisor check attribute populated? + String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK); + if (skipHypervisorCheck == null && ctx != null) { + skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK); + } + try { + context = getContext(rc, vmUrl, identStr); + if (context != null) { + tenantName = context.getTenantName();// this varaible also is used in case of exception + rc.reset(); + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString()); + if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) { + // Check of the Hypervisor for the VM Server is UP and reachable + checkHypervisor(server); + } + String msg; + /* + * We determine what to do based on the current state of the server + */ + + /* + * Pending is a bit of a special case. If we find the server is in a pending + * state, then the provider is in the process of changing state of the server. + * So, lets try to wait a little bit and see if the state settles down to one we + * can deal with. If not, then we have to fail the request. + */ + + if (server.getStatus().equals(Server.Status.PENDING)) { + waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR, + Server.Status.SUSPENDED, Server.Status.PAUSED, Server.Status.DELETED); + } + switch (server.getStatus()) { + case DELETED: + // Nothing to do, the server is gone + msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(), + server.getTenantId(), "started"); + logger.error(msg); + throw new RequestFailedException("Start Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, + server); + case RUNNING: + // Nothing to do, the server is already running + logger.info("Server was already running"); + break; + case ERROR: + // Server is in error state + msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(), + server.getTenantId(), "start"); + logger.error(msg); + throw new RequestFailedException("Start Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, + server); + + case READY: + // Server is stopped attempt to start the server + rc.reset(); + startServer(rc, server); + break; + + case PAUSED: + // if paused, un-pause it + rc.reset(); + unpauseServer(rc, server); + break; + + case SUSPENDED: + // Attempt to resume the suspended server + rc.reset(); + resumeServer(rc, server); + break; + + default: + // Hmmm, unknown status, should never occur + msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(), + server.getTenantId(), server.getStatus().name()); + generateEvent(rc, false, msg); + logger.error(msg); + throw new RequestFailedException("Start Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, + server); + } + context.close(); + doSuccess(rc); + ctx.setAttribute("START_STATUS", "SUCCESS"); + } else { + ctx.setAttribute("START_STATUS", "CONTEXT_NOT_FOUND"); + } + } catch (ResourceNotFoundException e) { + String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl); + logger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg); + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, + e1.getClass().getSimpleName(), Operation.START_SERVICE.toString(), vmUrl, tenantName); + logger.error(msg, e1); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + } catch (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + } + return server; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.START_SERVICE.toString(), "App-C IaaS Adapter:Start", Constants.ADAPTER_NAME); + logOperation(Msg.STARTING_SERVER, params, context); + return startServer(params, context); + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/StopServer.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/StopServer.java new file mode 100644 index 000000000..5ba36bec9 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/StopServer.java @@ -0,0 +1,207 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (c) 2019 IBM + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import java.util.Date; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.Property; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Outcome; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.logging.LoggingConstants; +import org.onap.ccsdk.sli.core.utils.logging.LoggingUtils; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.slf4j.MDC; + +public class StopServer extends ProviderServerOperation { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(StopServer.class); + private final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + + @SuppressWarnings("nls") + private Server stopServer(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException { + Server server = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + setTimeForMetricsLogger(); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + try { + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME); + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + ctx.setAttribute("STOP_STATUS", "SUCCESS"); + VMURL vm = VMURL.parseURL(vmUrl); + if (validateVM(rc, appName, vmUrl, vm)) + return null; + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + Context context = null; + ctx.setAttribute("STOP_STATUS", "ERROR"); + // Is the skip Hypervisor check attribute populated? + String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK); + if (skipHypervisorCheck == null && ctx != null) { + skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK); + } + try { + context = getContext(rc, vmUrl, identStr); + if (context != null) { + rc.reset(); + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString()); + // Always perform Hypervisor check + // unless the skip is set to true + if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) { + // Check of the Hypervisor for the VM Server is UP and reachable + checkHypervisor(server); + } + String msg; + /* + * We determine what to do based on the current state of the server + */ + /* + * Pending is a bit of a special case. If we find the server is in a pending + * state, then the provider is in the process of changing state of the server. + * So, lets try to wait a little bit and see if the state settles down to one we + * can deal with. If not, then we have to fail the request. + */ + if (server.getStatus().equals(Server.Status.PENDING)) { + waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR, + Server.Status.SUSPENDED, Server.Status.PAUSED, Server.Status.DELETED); + } + switch (server.getStatus()) { + case DELETED: + // Nothing to do, the server is gone + msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(), + server.getTenantId(), "stopped"); + generateEvent(rc, false, msg); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server); + case RUNNING: + // Attempt to stop the server + rc.reset(); + stopServer(rc, server); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + break; + case ERROR: + // Server is in error state + msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(), + server.getTenantId(), "stop"); + generateEvent(rc, false, msg); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server); + case READY: + // Nothing to do, the server was already stopped + logger.info("Server was already stopped"); + break; + case PAUSED: + // if paused, un-pause it and then stop it + rc.reset(); + unpauseServer(rc, server); + rc.reset(); + stopServer(rc, server); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + break; + case SUSPENDED: + // Attempt to resume the suspended server and after that stop it + rc.reset(); + resumeServer(rc, server); + rc.reset(); + stopServer(rc, server); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + break; + default: + // Hmmm, unknown status, should never occur + msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(), + server.getTenantId(), server.getStatus().name()); + generateEvent(rc, false, msg); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server); + } + context.close(); + doSuccess(rc); + ctx.setAttribute("STOP_STATUS", "SUCCESS"); + msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "StopServer", vmUrl); + ctx.setAttribute(Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + } else { + ctx.setAttribute("STOP_STATUS", "CONTEXT_NOT_FOUND"); + } + } catch (ResourceNotFoundException e) { + String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl); + logger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg); + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, + e1.getClass().getSimpleName(), Operation.STOP_SERVICE.toString(), vmUrl, + context == null ? "Unknown" : context.getTenantName()); + logger.error(msg, e1); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + } catch (RequestFailedException e) { + logger.error(EELFResourceManager.format(Msg.STOP_SERVER_FAILED, appName, "n/a", "n/a", e.getMessage())); + doFailure(rc, e.getStatus(), e.getMessage()); + } + return server; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.STOP_SERVICE.toString(), "App-C IaaS Adapter:Stop", Constants.ADAPTER_NAME); + logOperation(Msg.STOPPING_SERVER, params, context); + return stopServer(params, context); + } + + private void setTimeForMetricsLogger() { + String timestamp = LoggingUtils.generateTimestampStr((new Date()).toInstant()); + MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp); + MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp); + MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0"); + MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE); + MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp"); + MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "stop server"); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, "org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.StopServer"); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/TerminateServer.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/TerminateServer.java new file mode 100644 index 000000000..6868f9266 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/TerminateServer.java @@ -0,0 +1,244 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ContextConnectionException; +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.ComputeService; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.Provider; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Outcome; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.logging.Msg; + +public class TerminateServer extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class); + + /** + * Start the server and wait for it to enter a running state + * + * @param rc The request context that manages the state and recovery of the request for the life of its processing. + * @param server The server to be started + * @throws ZoneException when error occurs + * @throws RequestFailedException when request failed + */ + @SuppressWarnings("nls") + private void deleteServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException { + String msg; + Context context = server.getContext(); + Provider provider = context.getProvider(); + ComputeService service = context.getComputeService(); + while (rc.attempt()) { + try { + logger.info("deleting SERVER"); + server.delete(); + break; + } catch (ContextConnectionException e) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(), + context.getTenant().getName(), context.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + rc.delay(); + } + } + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + throw new RequestFailedException("Delete Server", msg, HttpStatus.BAD_GATEWAY_502, server); + } + rc.reset(); + } + + /** + * This method handles the case of restarting a server once we have found the server and have obtained the abstract + * representation of the server via the context (i.e., the "Server" object from the CDP-Zones abstraction). + * + * @param rc The request context that manages the state and recovery of the request for the life of its processing. + * @param server The server object representing the server we want to operate on + * @throws ZoneException when error occurs + */ + @SuppressWarnings("nls") + private void terminateServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException { + /* + * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the + * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down + * to one we can deal with. If not, then we have to fail the request. + */ + String msg; + if (server.getStatus().equals(Server.Status.PENDING)) { + waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR, + Server.Status.SUSPENDED, Server.Status.PAUSED); + } + + /* + * We determine what to do based on the current state of the server + */ + switch (server.getStatus()) { + case DELETED: + // Nothing to do, the server is gone + msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(), + server.getTenantId(), "restarted"); + generateEvent(rc, false, msg); + logger.error(msg); + break; + + case RUNNING: + // Attempt to stop and start the server + logger.info("stopping SERVER"); + stopServer(rc, server); + deleteServer(rc, server); + logger.info("after delete SERVER"); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + break; + + case ERROR: + + case READY: + + case PAUSED: + + case SUSPENDED: + // Attempt to delete the suspended server + deleteServer(rc, server); + generateEvent(rc, true, Outcome.SUCCESS.toString()); + break; + + default: + // Hmmm, unknown status, should never occur + msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(), + server.getTenantId(), server.getStatus().name()); + generateEvent(rc, false, msg); + logger.error(msg); + break; + } + + } + + /** + * This method is used to delete an existing virtual machine given the fully qualified URL of the machine. + * <p> + * The fully qualified URL contains enough information to locate the appropriate server. The URL is of the form + * + * <pre> + * [scheme]://[host[:port]] / [path] / [tenant_id] / servers / [vm_id] + * </pre> + * + * Where the various parts of the URL can be parsed and extracted and used to locate the appropriate service in the + * provider service catalog. This then allows us to open a context using the CDP abstraction, obtain the server by + * its UUID, and then perform the restart. + * </p> + * + * @throws SvcLogicException If the provider cannot be found + * @throws IllegalArgumentException if the expected argument(s) are not defined or are invalid + * @see ProviderAdapter#terminateServer(java.util.Map, + * org.onap.ccsdk.sli.core.sli.SvcLogicContext) + */ + @SuppressWarnings("nls") + public Server terminateServer(Map<String, String> params, SvcLogicContext ctx) + throws SvcLogicException, IllegalArgumentException { + Server server = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + + try { + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME); + + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + ctx.setAttribute("TERMINATE_STATUS", "SUCCESS"); + + VMURL vm = VMURL.parseURL(vmUrl); + if (validateVM(rc, appName, vmUrl, vm)) + return null; + + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + + Context context = null; + String tenantName = "Unknown";//to be used also in case of exception + try { + context = getContext(rc, vmUrl, identStr); + if (context != null) { + tenantName = context.getTenantName();//this varaible also is used in case of exception + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString()); + logger.info(EELFResourceManager.format(Msg.TERMINATING_SERVER, server.getName())); + terminateServer(rc, server); + logger.info(EELFResourceManager.format(Msg.TERMINATE_SERVER, server.getName())); + context.close(); + doSuccess(rc); + } else { + ctx.setAttribute("TERMINATE_STATUS", "SERVER_NOT_FOUND"); + } + } catch (ResourceNotFoundException e) { + String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl); + logger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg); + ctx.setAttribute("TERMINATE_STATUS", "SERVER_NOT_FOUND"); + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, + e1.getClass().getSimpleName(), Operation.RESTART_SERVICE.toString(), vmUrl, + tenantName); + logger.error(msg, e1); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + } catch (RequestFailedException e) { + logger.error( + EELFResourceManager.format(Msg.TERMINATE_SERVER_FAILED, appName, "n/a", "n/a", e.getMessage())); + doFailure(rc, e.getStatus(), e.getMessage()); + ctx.setAttribute("TERMINATE_STATUS", "ERROR"); + } + + return server; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.TERMINATE_SERVICE.toString(), "App-C IaaS Adapter:Terminate", Constants.ADAPTER_NAME); + logOperation(Msg.TERMINATING_SERVER, params, context); + return terminateServer(params, context); + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/TerminateStack.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/TerminateStack.java new file mode 100644 index 000000000..c3c8087d5 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/TerminateStack.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * + * Modifications Copyright (C) 2019 IBM. + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.StackService; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Stack; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderStackOperation; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class TerminateStack extends ProviderStackOperation { + + private static final String TERMINATE_STATUS = "TERMINATE_STATUS"; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class); + + private void deleteStack(RequestContext rc, Stack stack) throws ZoneException, RequestFailedException { + SvcLogicContext ctx = rc.getSvcLogicContext(); + Context context = stack.getContext(); + StackService stackService = context.getStackService(); + logger.debug("Deleting Stack: " + "id:{ " + stack.getId() + "}"); + stackService.deleteStack(stack); + + // wait for the stack deletion + boolean success = waitForStackStatus(rc, stack, Stack.Status.DELETED); + if (success) { + ctx.setAttribute(TERMINATE_STATUS, "SUCCESS"); + } else { + ctx.setAttribute(TERMINATE_STATUS, "ERROR"); + throw new RequestFailedException("Delete Stack failure : " + Msg.STACK_OPERATION_EXCEPTION.toString()); + } + } + + @SuppressWarnings("nls") + public Stack terminateStack(Map<String, String> params, SvcLogicContext ctx) { + Stack stack = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + ctx.setAttribute(TERMINATE_STATUS, "STACK_NOT_FOUND"); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + + try { + + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME, ProviderAdapter.PROPERTY_STACK_ID); + + String stackId = params.get(ProviderAdapter.PROPERTY_STACK_ID); + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + + Context context = resolveContext(rc, params, appName,vmUrl ); + + try { + if (context != null) { + rc.reset(); + stack = lookupStack(rc, context, stackId); + logger.debug(Msg.STACK_FOUND, vmUrl, context.getTenantName(), stack.getStatus().toString()); + logger.info(EELFResourceManager.format(Msg.TERMINATING_STACK, stack.getName())); + deleteStack(rc, stack); + logger.info(EELFResourceManager.format(Msg.TERMINATE_STACK, stack.getName())); + context.close(); + doSuccess(rc); + String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "TerminateStack", vmUrl); + ctx.setAttribute(Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + } + } catch (ResourceNotFoundException e) { + String msg = EELFResourceManager.format(Msg.STACK_NOT_FOUND, e, vmUrl); + logger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg); + } catch (Exception e1) { + String msg = + EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), + Operation.TERMINATE_STACK.toString(), vmUrl, context.getTenantName()); + logger.error(msg, e1); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + } catch (RequestFailedException e) { + logger.error(EELFResourceManager.format(Msg.TERMINATE_STACK_FAILED, appName, "n/a", "n/a")); + doFailure(rc, e.getStatus(), e.getMessage()); + } + return stack; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.TERMINATE_STACK.toString(), "App-C IaaS Adapter:Terminate-Stack", Constants.ADAPTER_NAME); + logOperation(Msg.TERMINATING_STACK, params, context); + return terminateStack(params, context); + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/VmStatuschecker.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/VmStatuschecker.java new file mode 100644 index 000000000..aca6d6af0 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/VmStatuschecker.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl; + +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.model.ModelObject; +import com.att.cdp.zones.model.Server; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import java.util.Map; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.core.utils.configuration.Configuration; +import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter; +import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Operation; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Outcome; +import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class VmStatuschecker extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(VmStatuschecker.class); + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + /** + * to check the status of the VM + */ + public Server vmStatuschecker(Map<String, String> params, SvcLogicContext ctx) + throws SvcLogicException, IllegalArgumentException { + Server server = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + + try { + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME); + + String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + + VMURL vm = VMURL.parseURL(vmUrl); + if (validateVM(rc, appName, vmUrl, vm)) + return null; + + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + + Context context = null; + String tenantName = "Unknown";//to be used also in case of exception + try { + context = getContext(rc, vmUrl, identStr); + if (context != null) { + tenantName = context.getTenantName();//this varaible also is used in case of exception + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString()); + + String statusvm; + switch (server.getStatus()) { + case DELETED: + statusvm = "deleted"; + break; + + case RUNNING: + statusvm = "running"; + break; + + case ERROR: + statusvm = "error"; + break; + + case READY: + statusvm = "ready"; + break; + + case PAUSED: + statusvm = "paused"; + break; + + case SUSPENDED: + statusvm = "suspended"; + break; + + case PENDING: + statusvm = "pending"; + break; + + default: + statusvm = "default-unknown state-should never occur"; + break; + } + + + String statusofVM = statusvm; + context.close(); + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setStatus(Outcome.SUCCESS.toString()); + svcLogic.setAttribute("org.openecomp.statusofvm", statusofVM); + svcLogic.setAttribute(Constants.STATUS_OF_VM, statusofVM); + svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, + Integer.toString(HttpStatus.OK_200.getStatusCode())); + } + } catch (ResourceNotFoundException e) { + String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl); + logger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg); + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, + e1.getClass().getSimpleName(), Operation.RESTART_SERVICE.toString(), vmUrl, + tenantName); + logger.error(msg, e1); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + } catch (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + } + + return server; + } + + @Override + protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) + throws SvcLogicException { + setMDC(Operation.VMSTATUSCHECK_SERVICE.toString(), "App-C IaaS Adapter:VmStatusCheck", Constants.ADAPTER_NAME); + logOperation(Msg.CHECKING_SERVER, params, context); + return vmStatuschecker(params, context); + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/base/ProviderOperation.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/base/ProviderOperation.java new file mode 100644 index 000000000..8562c1ad6 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/base/ProviderOperation.java @@ -0,0 +1,430 @@ +/*
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base;
+
+import com.att.cdp.exceptions.ZoneException;
+import com.att.cdp.zones.Context;
+import com.att.cdp.zones.model.ModelObject;
+import com.att.cdp.zones.model.Server;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.att.eelf.i18n.EELFResourceManager;
+import java.net.URI;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.regex.Pattern;
+import org.glassfish.grizzly.http.util.HttpStatus;
+import org.onap.ccsdk.sli.adaptors.iaas.Constants;
+import org.onap.ccsdk.sli.adaptors.iaas.ProviderAdapter;
+import org.onap.ccsdk.sli.adaptors.iaas.impl.IdentityURL;
+import org.onap.ccsdk.sli.adaptors.iaas.impl.ProviderCache;
+import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext;
+import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException;
+import org.onap.ccsdk.sli.adaptors.iaas.impl.TenantCache;
+import org.onap.ccsdk.sli.adaptors.iaas.impl.VMURL;
+import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.api.IProviderOperation;
+import org.onap.ccsdk.sli.adaptors.iaas.provider.operation.common.enums.Outcome;
+import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
+import org.onap.ccsdk.sli.core.sli.SvcLogicException;
+import org.onap.ccsdk.sli.core.utils.configuration.Configuration;
+import org.onap.ccsdk.sli.core.utils.configuration.ConfigurationFactory;
+import org.onap.ccsdk.sli.core.utils.logging.Msg;
+import org.onap.ccsdk.sli.core.utils.pool.Pool;
+import org.onap.ccsdk.sli.core.utils.pool.PoolExtensionException;
+import org.slf4j.MDC;
+
+import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
+
+public abstract class ProviderOperation implements IProviderOperation {
+
+ private static final String palos = "PALOS";
+ private static final EELFLogger logger = EELFManager.getInstance().getLogger(ProviderOperation.class);
+ protected static final Configuration configuration = ConfigurationFactory.getConfiguration();
+
+
+ /**
+ * A cache of providers that are predefined.
+ */
+ private Map<String /* provider name */, ProviderCache> providerCache;
+
+ /**
+ * The username and password to use for dynamically created connections
+ */
+ private String defaultUser;
+ private String defaultPassword;
+ private String defaultDomain;
+
+ @Override
+ public void setDefaultUser(String defaultUser) {
+ this.defaultUser = defaultUser;
+ }
+
+ @Override
+ public void setDefaultPassword(String defaultPassword) {
+ this.defaultPassword = defaultPassword;
+ }
+
+ @Override
+ public void setProviderCache(Map<String, ProviderCache> providerCache) {
+ this.providerCache = providerCache;
+ }
+
+ @Override
+ public void setDefaultDomain(String defaultDomain) {
+ this.defaultDomain = defaultDomain;
+ }
+
+ /**
+ * set MDC props
+ */
+ protected void setMDC(String service, String serviceName, String adapterName) {
+ MDC.put(Constants.MDC_ADAPTER, adapterName);
+ MDC.put(Constants.MDC_SERVICE, service);
+ MDC.put(MDC_SERVICE_NAME, serviceName);
+ }
+
+ /**
+ * initial log of the operation
+ */
+ protected void logOperation(Msg msg, Map<String, String> params, SvcLogicContext context) {
+
+ String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
+ logger.info(msg, appName);
+
+ debugParameters(params);
+ debugContext(context);
+ }
+ /**
+ * This method is used to dump the value of the parameters to the log for debugging purposes.
+ *
+ * @param parameters The parameters to be printed to the log
+ */
+ private void debugParameters(Map<String, String> parameters) {
+ for (Entry<String, String> entry : parameters.entrySet()) {
+ logger.debug(Msg.PROPERTY_VALUE, entry.getKey(), entry.getValue());
+ }
+ }
+ /**
+ * This method is used to create a diagnostic dump of the context for the log
+ *
+ * @param context The context to be dumped
+ */
+ @SuppressWarnings({"nls", "static-method"})
+ private void debugContext(SvcLogicContext context) {
+ Set<String> keys = context.getAttributeKeySet();
+ StringBuilder builder = new StringBuilder();
+ builder.append("Service Logic Context: Status ");
+ builder.append(Constants.LPAREN);
+ builder.append(context.getStatus());
+ builder.append(Constants.RPAREN);
+ builder.append(", Attribute count ");
+ builder.append(Constants.LPAREN);
+ builder.append(keys == null ? "none" : Integer.toString(keys.size()));
+ builder.append(Constants.RPAREN);
+ if (keys != null && !keys.isEmpty()) {
+ builder.append(Constants.NL);
+ for (String key : keys) {
+ String value = context.getAttribute(key);
+ builder.append("Attribute ");
+ builder.append(Constants.LPAREN);
+ builder.append(key);
+ builder.append(Constants.RPAREN);
+ builder.append(", value ");
+ builder.append(Constants.LPAREN);
+ builder.append(value == null ? "" : value);
+ builder.append(Constants.RPAREN);
+ builder.append(Constants.NL);
+ }
+ }
+ logger.debug(builder.toString());
+ }
+
+
+ /**
+ * This method is used to validate that the parameters contain all required property names, and that the values are
+ * non-null and non-empty strings. We are still not ensured that the value is valid, but at least it exists.
+ *
+ * @param parameters The parameters to be checked
+ * @param propertyNames The list of property names that are required to be present.
+ * @throws RequestFailedException If the parameters are not valid
+ */
+ protected void validateParametersExist(Map<String, String> parameters, String... propertyNames)
+ throws RequestFailedException {
+ boolean success = true;
+ StringBuilder msg =
+ new StringBuilder(EELFResourceManager.format(Msg.MISSING_REQUIRED_PROPERTIES, MDC.get(Constants.MDC_SERVICE)));
+ msg.append(Constants.NL);
+ for (String propertyName : propertyNames) {
+ String value = parameters.get(propertyName);
+ if (value == null || value.trim().length() == 0) {
+ success = false;
+ msg.append(Constants.QUOTE);
+ msg.append(propertyName);
+ msg.append(Constants.QUOTE);
+ msg.append(Constants.SPACE);
+ }
+ }
+
+ if (!success) {
+ logger.error(msg.toString());
+ throw new RequestFailedException("Check Parameters", msg.toString(), HttpStatus.BAD_REQUEST_400,
+ (Server) null);
+ }
+ }
+
+ /**
+ * @param rc The request context that manages the state and recovery of the request for the life of its processing.
+ */
+ protected void doFailure(RequestContext rc, HttpStatus code, String message) {
+ try {
+ doFailure(rc, code, message, null);
+ } catch (SvcLogicException e) {
+ logger.error("An APPC exception caught. Should never happen", e);
+ }
+ }
+
+ protected void doFailure(RequestContext rc, HttpStatus code, String message, Throwable cause) throws SvcLogicException {
+ SvcLogicContext svcLogic = rc.getSvcLogicContext();
+ String msg = (message == null) ? code.getReasonPhrase() : message;
+ if ((msg.contains(palos))) {
+ msg = msg.substring(msg.indexOf(palos), msg.length());
+ msg = msg.substring(msg.indexOf(palos), msg.indexOf("\n"));
+ } else {
+ if (msg.contains("\n")) {
+ msg = msg.substring(0, msg.indexOf('\n'));
+ }
+ }
+ String status;
+ try {
+ status = Integer.toString(code.getStatusCode());
+ } catch (Exception e) {
+ logger.error("Error when parsing status code", e);
+ status = "500";
+ }
+ svcLogic.setStatus(Outcome.FAILURE.toString());
+ svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, status);
+ svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
+ if (null != cause) {
+ throw new SvcLogicException(msg, cause);
+ }
+ }
+
+ /**
+ * @param rc The request context that manages the state and recovery of the request for the life of its processing.
+ */
+ @SuppressWarnings("static-method")
+ protected void doSuccess(RequestContext rc) {
+ SvcLogicContext svcLogic = rc.getSvcLogicContext();
+ svcLogic.setStatus(Outcome.SUCCESS.toString());
+ svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE,
+ Integer.toString(HttpStatus.OK_200.getStatusCode()));
+ }
+
+ protected boolean validateVM(RequestContext rc, String appName, String vmUrl, VMURL vm)
+ throws RequestFailedException {
+ String msg;
+ if (vm == null) {
+ msg = EELFResourceManager.format(Msg.INVALID_SELF_LINK_URL, appName, vmUrl);
+ logger.error(msg);
+ doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
+ return true;
+ }
+ validateVMURL(vm);
+ return false;
+ }
+
+ protected void validateVMURL(VMURL vm) throws RequestFailedException {
+ String name = "vm-id";
+ if (vm == null) {
+ throw new RequestFailedException(String.format("The value %s cannot be null.", name));
+ }
+ // Check that its a good uri
+ // This will probably never get hit bc of an earlier check while parsing
+ // the string to a VMURL
+ try {
+ // noinspection ResultOfMethodCallIgnored
+ URI.create(vm.toString());
+ } catch (Exception e) {
+ logger.error("An error occurred when validating vm url", e);
+ throw new RequestFailedException(
+ String.format("The value %s is not well formed [%s].", name, vm.toString()));
+ }
+ // Check the tenant and vmid segments
+ String patternRegex = "([0-9a-f]{8}(-)?[0-9a-f]{4}(-)?[0-9a-f]{4}(-)?[0-9a-f]{4}(-)?[0-9a-f]{12})";
+ Pattern pattern = Pattern.compile(patternRegex, Pattern.CASE_INSENSITIVE);
+ if (!pattern.matcher(vm.getTenantId()).matches()) {
+ throw new RequestFailedException(
+ String.format("The value %s has an invalid tenantId [%s].", name, vm.getTenantId()));
+ }
+ if (!pattern.matcher(vm.getServerId()).matches()) {
+ throw new RequestFailedException(
+ String.format("The value %s has an invalid serverId [%s].", name, vm.getServerId()));
+ }
+ }
+
+ private ProviderCache createProviderCache(VMURL vm, IdentityURL ident) {
+ if (vm != null && ident != null) {
+ ProviderCache cache = new ProviderCache();
+ cache.setIdentityURL(ident.toString());
+ cache.setProviderName(ident.toString());
+ TenantCache tenant = cache.addTenant(vm.getTenantId(), null, defaultUser, defaultPassword, defaultDomain);
+ // Make sure we could initialize the the cache otherwise return null
+ if (tenant != null && tenant.isInitialized()) {
+ return cache;
+ }
+ }
+ return null;
+ }
+ /**
+ * This method is a general helper method used to locate a server given its fully-qualified self-link URL on a
+ * supported provider, regardless of region(s), and to return an opened context that can be used to access that
+ * server.
+ *
+ * @param rc The request context that wraps and manages the state of the request
+ * @param selfLinkURL The fully-qualified self-link URL of the server
+ * @param providerName The name of the provider to be searched
+ * @return The context that can be used to access the server, or null if not found.
+ */
+ @SuppressWarnings("nls")
+ protected Context getContext(RequestContext rc, String selfLinkURL, String providerName) {
+ VMURL vm = VMURL.parseURL(selfLinkURL);
+ IdentityURL ident = IdentityURL.parseURL(providerName);
+ String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
+ if (vm == null) {
+ String msg = EELFResourceManager.format(Msg.INVALID_SELF_LINK_URL, appName, selfLinkURL);
+ logger.error(msg);
+ doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
+ return null;
+ }
+ /*
+ * Get the cache of tenants and contexts for the named provider, if one exists
+ */
+ ProviderCache cache = providerCache.get(providerName);
+ /*
+ * If one doesn't exist, try and create it. If we have enough information to create it successfully, add it to
+ * the cache and continue, otherwise fail the request.
+ */
+ if (cache == null) {
+ if (ident != null) {
+ cache = createProviderCache(vm, ident);
+ }
+ if (cache != null) {
+ providerCache.put(cache.getProviderName(), cache);
+ } else {
+ String msg = EELFResourceManager.format(Msg.UNKNOWN_PROVIDER, providerName,
+ providerCache.keySet().toString());
+ logger.error(msg);
+ doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
+ return null;
+ }
+ }
+ if (providerName == null) {
+ logger.debug(
+ String.format("Using the default provider cache [%s] since no valid identity url was passed in.",
+ cache.getIdentityURL()));
+ }
+ // get the tenant cache for the vm
+ String identityURL = cache.getIdentityURL();
+ TenantCache tenantCache = cache.getTenant(vm.getTenantId());
+ if (tenantCache == null) {
+ // no tenantCache matching tenant, add tenant to the provider cache
+ tenantCache = cache.addTenant(vm.getTenantId(), null, defaultUser, defaultPassword, defaultDomain);
+ if (tenantCache == null) {
+ // tenant not found
+ String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, selfLinkURL);
+ logger.error(msg);
+ doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
+ return null;
+ }
+ }
+ // reserve the context
+ String tenantName = tenantCache.getTenantName();
+ String tenantId = tenantCache.getTenantId();
+ String region = tenantCache.determineRegion(vm);
+
+ if (region != null) {
+ Pool<Context> pool = tenantCache.getPools().get(region);
+ while (rc.attempt()) {
+ try {
+ Context context = pool.reserve();
+ /*
+ * Insert logic here to test the context for connectivity because we may have gotten one from the
+ * pool that was previously created.
+ */
+ reloginIfNeeded(context);
+ return context;
+ } catch (PoolExtensionException e) {
+ String msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, providerName, identityURL,
+ tenantName, tenantId, e.getMessage(), Long.toString(rc.getRetryDelay()),
+ Integer.toString(rc.getAttempts()), Integer.toString(rc.getRetryLimit()));
+ logger.error(msg, e);
+ rc.delay();
+ } catch (Exception e) {
+ String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e,
+ e.getClass().getSimpleName(), "find", selfLinkURL, tenantCache.getTenantName());
+ logger.error(msg, e);
+ doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
+ return null;
+ }
+ }
+ String msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, providerName, identityURL);
+ logger.error(msg);
+ doFailure(rc, HttpStatus.BAD_GATEWAY_502, msg);
+ return null;
+ }
+ String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, selfLinkURL);
+ logger.error(msg);
+ doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
+ return null;
+ }
+
+ private void reloginIfNeeded(Context context) throws ZoneException {
+ if (context.isStale()) {
+ context.relogin();
+ }
+ }
+
+ protected Context resolveContext(RequestContext rc, Map<String, String> params, String appName, String vmUrl)
+ throws RequestFailedException {
+ VMURL vm = VMURL.parseURL(vmUrl);
+ if (vm == null) {
+ String msg = EELFResourceManager.format(Msg.INVALID_SELF_LINK_URL, appName, vmUrl);
+ doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
+ logger.error(msg);
+ return null;
+ }
+ validateVMURL(vm);
+ IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
+ String identStr = (ident == null) ? null : ident.toString();
+ return getContext(rc, vmUrl, identStr);
+ }
+
+ protected abstract ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
+ throws SvcLogicException;
+ @Override
+ public ModelObject doOperation(Map<String, String> params, SvcLogicContext context) throws SvcLogicException {
+ return executeProviderOperation(params, context);
+ }
+}
diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/base/ProviderServerOperation.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/base/ProviderServerOperation.java new file mode 100644 index 000000000..49c312a33 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/base/ProviderServerOperation.java @@ -0,0 +1,512 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base; + +import com.att.cdp.exceptions.ContextConnectionException; +import com.att.cdp.exceptions.NotLoggedInException; +import com.att.cdp.exceptions.TimeoutException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.pal.util.StringHelper; +import com.att.cdp.zones.ComputeService; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.ImageService; +import com.att.cdp.zones.NetworkService; +import com.att.cdp.zones.Provider; +import com.att.cdp.zones.model.Hypervisor; +import com.att.cdp.zones.model.Image; +import com.att.cdp.zones.model.Network; +import com.att.cdp.zones.model.Port; +import com.att.cdp.zones.model.Server; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import java.util.ArrayList; +import java.util.List; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; + +/** + * @since September 29, 2016 + */ +public abstract class ProviderServerOperation extends ProviderOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ProviderServerOperation.class); + + /** + * Looks up the indicated server using the provided context and returns the server to the caller + * + * @param rc The request context + * @param context The provider context + * @param id The id of the server + * @return The server, or null if there is a problem + * @throws ZoneException If the server cannot be found + * @throws RequestFailedException If the server cannot be found because we cant connect to the provider + */ + @SuppressWarnings("nls") + protected Server lookupServer(RequestContext rc, Context context, String id) + throws ZoneException, RequestFailedException { + ComputeService service = context.getComputeService(); + Server server = null; + String msg; + Provider provider = context.getProvider(); + + while (rc.attempt()) { + try { + server = service.getServer(id); + break; + } catch (ContextConnectionException e) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(), + context.getTenant().getName(), context.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + rc.delay(); + } + } + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + doFailure(rc, HttpStatus.BAD_GATEWAY_502, msg); + throw new RequestFailedException("Lookup Server", msg, HttpStatus.BAD_GATEWAY_502, server); + } + return server; + } + + + /** + * Resume a suspended server and wait for it to enter a running state + * + * @param rc The request context that manages the state and recovery of the request for the life of its processing. + * @param server The server to be resumed + */ + @SuppressWarnings("nls") + protected void resumeServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException { + logger.debug(Msg.RESUME_SERVER, server.getId()); + + Context context = server.getContext(); + String msg; + Provider provider = context.getProvider(); + ComputeService service = context.getComputeService(); + while (rc.attempt()) { + try { + server.resume(); + break; + } catch (ContextConnectionException e) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(), + context.getTenant().getName(), context.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + rc.delay(); + } + } + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + throw new RequestFailedException("Resume Server", msg, HttpStatus.BAD_GATEWAY_502, server); + } + rc.reset(); + waitForStateChange(rc, server, Server.Status.RUNNING); + } + + + protected boolean hasImageAccess(@SuppressWarnings("unused") RequestContext rc, Context context) { + logger.info("Checking permissions for image service."); + try { + ImageService service = context.getImageService(); + service.getImageByName("CHECK_IMAGE_ACCESS"); + logger.info("Image service is accessible."); + return true; + } catch (ZoneException e) { + logger.warn("Image service could not be accessed. Some operations may fail.", e); + return false; + } + } + + + /** + * Enter a pool-wait loop checking the server state to see if it has entered one of the desired states or not. <p> + * This method checks the state of the server periodically for one of the desired states. When the server enters one + * of the desired states, the method returns a successful indication (true). If the server never enters one of the + * desired states within the allocated timeout period, then the method returns a failed response (false). No + * exceptions are thrown from this method. </p> + * + * @param rc The request context that manages the state and recovery of the request for the life of its processing. + * @param image The server to wait on + * @param desiredStates A variable list of desired states, any one of which is allowed. + * @throws RequestFailedException If the request times out or fails for some reason + */ + @SuppressWarnings("nls") + protected void waitForStateChange(RequestContext rc, Image image, Image.Status... desiredStates) + throws RequestFailedException, NotLoggedInException { + int pollInterval = configuration.getIntegerProperty(Constants.PROPERTY_OPENSTACK_POLL_INTERVAL); + int timeout = configuration.getIntegerProperty(Constants.PROPERTY_SERVER_STATE_CHANGE_TIMEOUT); + Context context = image.getContext(); + Provider provider = context.getProvider(); + ImageService service = context.getImageService(); + String msg; + + long endTime = System.currentTimeMillis() + (timeout * 1000); // + + while (rc.attempt()) { + try { + try { + image.waitForStateChange(pollInterval, timeout, desiredStates); + break; + } catch (TimeoutException e) { + @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") + List<String> list = new ArrayList<>(); + for (Image.Status desiredState : desiredStates) { + list.add(desiredState.name()); + } + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(), + context.getTenant().getName(), context.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + rc.delay(); + } + } catch (ZoneException e) { + List<String> list = new ArrayList<>(); + for (Image.Status desiredState : desiredStates) { + list.add(desiredState.name()); + } + String reason = EELFResourceManager.format(Msg.STATE_CHANGE_EXCEPTION, e.getClass().getSimpleName(), + "server", image.getName(), image.getId(), StringHelper.asList(list), image.getStatus().name(), + e.getMessage()); + logger.error(reason); + logger.error(EELFResourceManager.format(e)); + + // Instead of failing we are going to wait and try again. + // Timeout is reduced by delay time + logger.info(String.format("Retrying in %ds", rc.getRetryDelay())); + rc.delay(); + timeout = (int) (endTime - System.currentTimeMillis()) / 1000; + // throw new RequestFailedException(e, operation, reason, + } + } + + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + throw new RequestFailedException("Waiting for State Change", msg, HttpStatus.BAD_GATEWAY_502, new Server()); + } + rc.reset(); + } + + + /** + * Enter a pool-wait loop checking the server state to see if it has entered one of the desired states or not. <p> + * This method checks the state of the server periodically for one of the desired states. When the server enters one + * of the desired states, the method returns a successful indication (true). If the server never enters one of the + * desired states within the allocated timeout period, then the method returns a failed response (false). No + * exceptions are thrown from this method. </p> + * + * @param rc The request context that manages the state and recovery of the request for the life of its processing. + * @param server The server to wait on + * @param desiredStates A variable list of desired states, any one of which is allowed. + * @throws RequestFailedException If the request times out or fails for some reason + */ + @SuppressWarnings("nls") + protected void waitForStateChange(RequestContext rc, Server server, Server.Status... desiredStates) + throws RequestFailedException { + int pollInterval = configuration.getIntegerProperty(Constants.PROPERTY_OPENSTACK_POLL_INTERVAL); + int timeout = configuration.getIntegerProperty(Constants.PROPERTY_SERVER_STATE_CHANGE_TIMEOUT); + Context context = server.getContext(); + Provider provider = context.getProvider(); + ComputeService service = context.getComputeService(); + String msg; + + long endTime = System.currentTimeMillis() + (timeout * 1000); // + + while (rc.attempt()) { + try { + try { + server.waitForStateChange(pollInterval, timeout, desiredStates); + break; + } catch (TimeoutException e) { + @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") + List<String> list = new ArrayList<>(); + for (Server.Status desiredState : desiredStates) { + list.add(desiredState.name()); + } + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(), + context.getTenant().getName(), context.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + rc.delay(); + } + } catch (ZoneException e) { + List<String> list = new ArrayList<>(); + for (Server.Status desiredState : desiredStates) { + list.add(desiredState.name()); + } + String reason = EELFResourceManager.format(Msg.STATE_CHANGE_EXCEPTION, e.getClass().getSimpleName(), + "server", server.getName(), server.getId(), StringHelper.asList(list), + server.getStatus().name(), e.getMessage()); + logger.error(reason); + logger.error(EELFResourceManager.format(e)); + + // Instead of failing we are going to wait and try again. + // Timeout is reduced by delay time + logger.info(String.format("Retrying in %ds", rc.getRetryDelay())); + rc.delay(); + timeout = (int) (endTime - System.currentTimeMillis()) / 1000; + // throw new RequestFailedException(e, operation, reason, + } + } + + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + throw new RequestFailedException("Waiting for State Change", msg, HttpStatus.BAD_GATEWAY_502, server); + } + rc.reset(); + } + + /** + * Stop the specified server and wait for it to stop + * + * @param rc The request context that manages the state and recovery of the request for the life of its processing. + * @param server The server to be stopped + */ + @SuppressWarnings("nls") + protected void stopServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException { + logger.debug(Msg.STOP_SERVER, server.getId()); + + String msg; + Context context = server.getContext(); + Provider provider = context.getProvider(); + ComputeService service = context.getComputeService(); + while (rc.attempt()) { + try { + server.stop(); + break; + } catch (ContextConnectionException e) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(), + context.getTenant().getName(), context.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + rc.delay(); + } + } + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server); + } + rc.reset(); + waitForStateChange(rc, server, Server.Status.READY, Server.Status.ERROR); + } + + /** + * Start the server and wait for it to enter a running state + * + * @param rc The request context that manages the state and recovery of the request for the life of its processing. + * @param server The server to be started + */ + @SuppressWarnings("nls") + protected void startServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException { + logger.debug(Msg.START_SERVER, server.getId()); + String msg; + Context context = server.getContext(); + Provider provider = context.getProvider(); + ComputeService service = context.getComputeService(); + while (rc.attempt()) { + try { + server.start(); + break; + } catch (ContextConnectionException e) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(), + context.getTenant().getName(), context.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + rc.delay(); + } + } + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + throw new RequestFailedException("Start Server", msg, HttpStatus.BAD_GATEWAY_502, server); + } + rc.reset(); + waitForStateChange(rc, server, Server.Status.RUNNING); + } + + + /** + * Un-Pause a paused server and wait for it to enter a running state + * + * @param rc The request context that manages the state and recovery of the request for the life of its processing. + * @param server The server to be un-paused + */ + @SuppressWarnings("nls") + protected void unpauseServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException { + logger.debug(Msg.UNPAUSE_SERVER, server.getId()); + + String msg; + Context context = server.getContext(); + Provider provider = context.getProvider(); + ComputeService service = context.getComputeService(); + while (rc.attempt()) { + try { + server.unpause(); + break; + } catch (ContextConnectionException e) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(), + context.getTenant().getName(), context.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + rc.delay(); + } + } + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL()); + logger.error(msg); + throw new RequestFailedException("Unpause Server", msg, HttpStatus.BAD_GATEWAY_502, server); + } + rc.reset(); + waitForStateChange(rc, server, Server.Status.RUNNING, Server.Status.READY); + } + + + /** + * Generates the event indicating what happened + * + * @param rc The request context that manages the state and recovery of the request for the life of its processing. + * @param success True if the event represents a successful outcome + * @param msg The detailed message + */ + protected void generateEvent(@SuppressWarnings("unused") RequestContext rc, + @SuppressWarnings("unused") boolean success, @SuppressWarnings("unused") String msg) { + // indication to the DG to generate the event? + } + + /** + * Checks if the VM is connected to the Virtual Network and reachable + * + * @param rc The request context that manages the state and recovery of the request for the life of its processing. + * @param server The server object representing the server we want to operate on + * @param context The interface cloud service provider to access services or the object model, or both + */ + protected void checkVirtualMachineNetworkStatus(RequestContext rc, Server server, Context context) + throws ZoneException, RequestFailedException { + + logger.info("Performing the VM Server networking status checks..."); + List<Port> ports = server.getPorts(); + + NetworkService netSvc = context.getNetworkService(); + + String msg; + for (Port port : ports) { + switch (port.getPortState().toString().toUpperCase()) { + case "ONLINE": + /* The port is connected, configured, and usable for communication */ + Network network = netSvc.getNetworkById(port.getNetwork()); + validateNetwork(rc, server, port, network); + break; + case "OFFLINE": + /* The port is disconnected or powered-off and cannot be used for communication */ + msg = createErrorMessage(rc, server, port); + throw new RequestFailedException("VM Server Port status is OFFLINE", msg, + HttpStatus.PRECONDITION_FAILED_412, server); + case "PENDING": + /* The port's status is changing because of some event or operation. The final state is yet to be determined. */ + msg = createErrorMessage(rc, server, port); + throw new RequestFailedException("VM Server Port status is PENDING", msg, + HttpStatus.PRECONDITION_FAILED_412, server); + case "UNKNOWN": + /* The port is in an unknown state and cannot be used. */ + msg = createErrorMessage(rc, server, port); + throw new RequestFailedException("VM Server Port status is UNKNOWN", msg, + HttpStatus.PRECONDITION_FAILED_412, server); + default: + logger.error("Invalid port state"); + break; + } + + } + logger.info("Passed the VM Server the Hypervisor status checks.."); + } + + private String createErrorMessage(RequestContext rc, Server server, Port port) { + String msg; + msg = EELFResourceManager.format(Msg.SERVER_NETWORK_ERROR, server.getName(), port.getId()); + logger.error(msg); + doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg); + return msg; + } + + private void validateNetwork(RequestContext rc, Server server, Port port, Network network) + throws RequestFailedException { + String msg; + if (!network.getStatus().equals(Network.Status.ACTIVE.toString())) { + msg = createErrorMessage(rc, server, port); + throw new RequestFailedException("VM Server Network is DOWN", msg, + HttpStatus.PRECONDITION_FAILED_412, server); + } + } + + /** + * Checks if the VM is connected to the Virtual Network and reachable + * + * @param server The server object representing the server we want to operate on + */ + protected void checkHypervisor(Server server) throws ZoneException, RequestFailedException { + + logger.info("Performing the Hypervisor status checks.."); + + String msg; + if (server.getHypervisor() != null && server.getHypervisor().getStatus() != null + && server.getHypervisor().getState() != null) { + String status; + String state; + + status = server.getHypervisor().getStatus().toString(); + state = server.getHypervisor().getState().toString(); + + if (!status.equals(Hypervisor.Status.ENABLED.toString()) || !state.equals(Hypervisor.State.UP.toString())) { + msg = EELFResourceManager.format(Msg.HYPERVISOR_DOWN_ERROR, server.getHypervisor().getHostName(), + server.getName()); + logger.error(msg); + throw new RequestFailedException("Hypervisor status DOWN or NOT ENABLED", msg, + HttpStatus.PRECONDITION_FAILED_412, server); + } + } else { + msg = EELFResourceManager.format(Msg.HYPERVISOR_STATUS_UKNOWN, server.getName()); + logger.error(msg); + + throw new RequestFailedException("Unable to determine Hypervisor status", msg, + HttpStatus.PRECONDITION_FAILED_412, server); + } + logger.info("Passed the Hypervisor status checks.."); + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/base/ProviderStackOperation.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/base/ProviderStackOperation.java new file mode 100644 index 000000000..873f9689b --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/iaas/provider/operation/impl/base/ProviderStackOperation.java @@ -0,0 +1,197 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * Modifications Copyright (C) 2019 IBM. + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.iaas.provider.operation.impl.base; + +import com.att.cdp.exceptions.ContextConnectionException; +import com.att.cdp.exceptions.ResourceNotFoundException; +import com.att.cdp.exceptions.TimeoutException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.Provider; +import com.att.cdp.zones.StackService; +import com.att.cdp.zones.model.Stack; +import com.att.cdp.zones.spi.AbstractService; +import com.att.cdp.zones.spi.RequestState; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import com.woorea.openstack.base.client.OpenStackBaseException; +import java.util.List; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.ccsdk.sli.adaptors.iaas.Constants; +import org.onap.ccsdk.sli.core.utils.logging.Msg; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestContext; +import org.onap.ccsdk.sli.adaptors.iaas.impl.RequestFailedException; +import org.onap.ccsdk.sli.adaptors.openstack.heat.StackResource; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public abstract class ProviderStackOperation extends ProviderOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ProviderStackOperation.class); + + + protected void trackRequest(Context context, AbstractService.State... states) { + RequestState.clear(); + + if (null == states) + return; + for (AbstractService.State state : states) { + RequestState.put(state.getName(), state.getValue()); + } + + Thread currentThread = Thread.currentThread(); + StackTraceElement[] stack = currentThread.getStackTrace(); + if (stack != null && stack.length > 0) { + int index = 0; + StackTraceElement element; + for (; index < stack.length; index++) { + element = stack[index]; + if ("trackRequest".equals(element.getMethodName())) { //$NON-NLS-1$ + break; + } + } + index++; + + if (index < stack.length) { + element = stack[index]; + RequestState.put(RequestState.METHOD, element.getMethodName()); + RequestState.put(RequestState.CLASS, element.getClassName()); + RequestState.put(RequestState.LINE_NUMBER, Integer.toString(element.getLineNumber())); + RequestState.put(RequestState.THREAD, currentThread.getName()); + RequestState.put(RequestState.PROVIDER, context.getProvider().getName()); + RequestState.put(RequestState.TENANT, context.getTenantName()); + RequestState.put(RequestState.PRINCIPAL, context.getPrincipal()); + } + } + } + + /* + * Changed the 'pollInterval' type as long. Thread.sleep method needs 'long millis' as an argument + */ + private boolean checkStatus(String expectedStatus, long pollInterval, String actualStatus) { + if (actualStatus.equalsIgnoreCase(expectedStatus)) { + return true; + } else { + try { + Thread.sleep(pollInterval * 1000); + } catch (InterruptedException ex) { + logger.trace(ex.getMessage(), ex); + Thread.currentThread().interrupt(); + } + } + return false; + } + + protected boolean waitForStack(Stack stack, StackResource stackResource, String expectedStatus) + throws OpenStackBaseException, TimeoutException { + int pollInterval = configuration.getIntegerProperty(Constants.PROPERTY_OPENSTACK_POLL_INTERVAL); + int timeout = configuration.getIntegerProperty(Constants.PROPERTY_STACK_STATE_CHANGE_TIMEOUT); + long maxTimeToWait = System.currentTimeMillis() + (long) timeout * 1000; + + while (System.currentTimeMillis() < maxTimeToWait) { + String stackStatus = stackResource.show(stack.getName(), stack.getId()).execute().getStackStatus(); + logger.debug("Stack status : " + stackStatus); + if (stackStatus.toUpperCase().contains("FAILED")) + return false; + if (checkStatus(expectedStatus, pollInterval, stackStatus)) + return true; + } + throw new TimeoutException("Timeout waiting for stack status change"); + } + + protected Stack lookupStack(RequestContext rc, Context context, String id) + throws ZoneException, RequestFailedException { + StackService stackService = context.getStackService(); + Stack stack = null; + String msg; + Provider provider = context.getProvider(); + while (rc.attempt()) { + try { + List<Stack> stackList = stackService.getStacks(); + for (Stack stackObj : stackList) { + if (stackObj.getId().equals(id)) { + stack = stackObj; + break; + } + } + break; + } catch (ContextConnectionException e) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), stackService.getURL(), + context.getTenant().getName(), context.getTenant().getId(), e.getMessage(), + Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()), + Integer.toString(rc.getRetryLimit())); + logger.error(msg, e); + rc.delay(); + } + + } + if (rc.isFailed()) { + msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), stackService.getURL()); + logger.error(msg); + doFailure(rc, HttpStatus.BAD_GATEWAY_502, msg); + throw new RequestFailedException("Lookup Stack", msg, HttpStatus.BAD_GATEWAY_502, stack); + } + + if (stack == null) { + throw new ResourceNotFoundException("Stack not found with Id : {" + id + "}"); + } + return stack; + } + + + protected boolean waitForStackStatus(RequestContext rc, Stack stack, Stack.Status expectedStatus) + throws ZoneException, RequestFailedException { + SvcLogicContext ctx = rc.getSvcLogicContext(); + Context context = stack.getContext(); + StackService stackService = context.getStackService(); + /* + * Changed the 'pollInterval' type as long. Thread.sleep method needs 'long millis' as an argument + */ + long pollInterval = configuration.getIntegerProperty(Constants.PROPERTY_OPENSTACK_POLL_INTERVAL); + int timeout = configuration.getIntegerProperty(Constants.PROPERTY_STACK_STATE_CHANGE_TIMEOUT); + long maxTimeToWait = System.currentTimeMillis() + (long) timeout * 1000; + Stack.Status stackStatus; + while (System.currentTimeMillis() < maxTimeToWait) { + stackStatus = stackService.getStack(stack.getName(), stack.getId()).getStatus(); + logger.debug("Stack status : " + stackStatus.toString()); + if (stackStatus == expectedStatus) { + return true; + } else if (stackStatus == Stack.Status.FAILED) { + return false; + } else { + try { + Thread.sleep(pollInterval * 1000); + } catch (InterruptedException e) { + logger.trace("Sleep threw interrupted exception, should never occur", e); + Thread.currentThread().interrupt(); + } + } + } + + ctx.setAttribute("TERMINATE_STATUS", "ERROR"); + throw new TimeoutException("Timeout waiting for stack status change"); + + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/SnapshotResource.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/SnapshotResource.java new file mode 100644 index 000000000..0a75a313e --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/SnapshotResource.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat; + +import com.woorea.openstack.base.client.Entity; +import com.woorea.openstack.base.client.HttpMethod; +import com.woorea.openstack.base.client.OpenStackClient; +import com.woorea.openstack.base.client.OpenStackRequest; +import org.onap.ccsdk.sli.adaptors.openstack.heat.model.CreateSnapshotParams; +import org.onap.ccsdk.sli.adaptors.openstack.heat.model.Snapshot; + +public class SnapshotResource { + + private final OpenStackClient client; + + public SnapshotResource(OpenStackClient client) { + this.client = client; + } + + public CreateSnapshot create(String stackName, String stackID, CreateSnapshotParams params) { + return new CreateSnapshot(stackName, stackID, params); + } + + public RestoreSnapshot restore(String stackName, String stackID, String snapshotID) { + return new RestoreSnapshot(stackName, stackID, snapshotID); + } + + public ShowSnapshot show(String stackName, String stackID, String snapshotID) { + return new ShowSnapshot(stackName, stackID, snapshotID); + } + + public class CreateSnapshot extends OpenStackRequest<Snapshot> { + public CreateSnapshot(String stackName, String stackID, CreateSnapshotParams params) { + super(client, HttpMethod.POST, "/stacks/" + stackName + "/" + stackID + "/snapshots", Entity.json(params), + Snapshot.class); + } + } + + public class RestoreSnapshot extends OpenStackRequest<Void> { + public RestoreSnapshot(String stackName, String stackID, String snapshotID) { + super(client, HttpMethod.POST, + "/stacks/" + stackName + "/" + stackID + "/snapshots/" + snapshotID + "/restore", null, Void.class); + } + } + + public class ShowSnapshot extends OpenStackRequest<Snapshot> { + public ShowSnapshot(String stackName, String stackID, String snapshotID) { + super(client, HttpMethod.GET, "/stacks/" + stackName + "/" + stackID + "/snapshots/" + snapshotID, null, + Snapshot.class); + } + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/StackResource.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/StackResource.java new file mode 100644 index 000000000..d7b76c630 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/StackResource.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat; + +import com.woorea.openstack.base.client.HttpMethod; +import com.woorea.openstack.base.client.OpenStackClient; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.heat.model.Stack; + + +public class StackResource { + + private final OpenStackClient client; + + public StackResource(OpenStackClient client) { + this.client = client; + } + + public ShowStack show(String stackName, String stackID) { + return new ShowStack(stackName, stackID); + } + + public class ShowStack extends OpenStackRequest<Stack> { + public ShowStack(String stackName, String stackID) { + super(client, HttpMethod.GET, "/stacks/" + stackName + "/" + stackID, null, Stack.class); + } + } +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/CreateSnapshotParams.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/CreateSnapshotParams.java new file mode 100644 index 000000000..4f2132b56 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/CreateSnapshotParams.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"name"}) +public class CreateSnapshotParams { + + @JsonProperty("name") + private String name; + + /** + * @return The name + */ + @JsonProperty("name") + public String getName() { + return name; + } + + /** + * @param name The name + */ + @JsonProperty("name") + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Data.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Data.java new file mode 100644 index 000000000..0a8ba8a3f --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Data.java @@ -0,0 +1,203 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"status", "name", "stack_user_project_id", "environment", "template", "action", "project_id", "id", "resources"}) +public class Data { + + @JsonProperty("status") + private String status; + @JsonProperty("name") + private String name; + @JsonProperty("stack_user_project_id") + private String stackUserProjectId; + @JsonProperty("environment") + private Environment environment; + @JsonProperty("template") + private Template template; + @JsonProperty("action") + private String action; + @JsonProperty("project_id") + private String projectId; + @JsonProperty("id") + private String id; + @JsonProperty("resources") + private Resources__ resources; + + /** + * @return The status + */ + @JsonProperty("status") + public String getStatus() { + return status; + } + + /** + * @param status The status + */ + @JsonProperty("status") + public void setStatus(String status) { + this.status = status; + } + + /** + * @return The name + */ + @JsonProperty("name") + public String getName() { + return name; + } + + /** + * @param name The name + */ + @JsonProperty("name") + public void setName(String name) { + this.name = name; + } + + /** + * @return The stackUserProjectId + */ + @JsonProperty("stack_user_project_id") + public String getStackUserProjectId() { + return stackUserProjectId; + } + + /** + * @param stackUserProjectId The stack_user_project_id + */ + @JsonProperty("stack_user_project_id") + public void setStackUserProjectId(String stackUserProjectId) { + this.stackUserProjectId = stackUserProjectId; + } + + /** + * @return The environment + */ + @JsonProperty("environment") + public Environment getEnvironment() { + return environment; + } + + /** + * @param environment The environment + */ + @JsonProperty("environment") + public void setEnvironment(Environment environment) { + this.environment = environment; + } + + /** + * @return The template + */ + @JsonProperty("template") + public Template getTemplate() { + return template; + } + + /** + * @param template The template + */ + @JsonProperty("template") + public void setTemplate(Template template) { + this.template = template; + } + + /** + * @return The action + */ + @JsonProperty("action") + public String getAction() { + return action; + } + + /** + * @param action The action + */ + @JsonProperty("action") + public void setAction(String action) { + this.action = action; + } + + /** + * @return The projectId + */ + @JsonProperty("project_id") + public String getProjectId() { + return projectId; + } + + /** + * @param projectId The project_id + */ + @JsonProperty("project_id") + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + /** + * @return The id + */ + @JsonProperty("id") + public String getId() { + return id; + } + + /** + * @param id The id + */ + @JsonProperty("id") + public void setId(String id) { + this.id = id; + } + + /** + * @return The resources + */ + @JsonProperty("resources") + public Resources__ getResources() { + return resources; + } + + /** + * @param resources The resources + */ + @JsonProperty("resources") + public void setResources(Resources__ resources) { + this.resources = resources; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Environment.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Environment.java new file mode 100644 index 000000000..5473bab66 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Environment.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"parameters", "resource_registry"}) +public class Environment { + + @JsonProperty("parameters") + private Parameters parameters; + @JsonProperty("resource_registry") + private ResourceRegistry resourceRegistry; + + /** + * @return The parameters + */ + @JsonProperty("parameters") + public Parameters getParameters() { + return parameters; + } + + /** + * @param parameters The parameters + */ + @JsonProperty("parameters") + public void setParameters(Parameters parameters) { + this.parameters = parameters; + } + + /** + * @return The resourceRegistry + */ + @JsonProperty("resource_registry") + public ResourceRegistry getResourceRegistry() { + return resourceRegistry; + } + + /** + * @param resourceRegistry The resource_registry + */ + @JsonProperty("resource_registry") + public void setResourceRegistry(ResourceRegistry resourceRegistry) { + this.resourceRegistry = resourceRegistry; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Metadata.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Metadata.java new file mode 100644 index 000000000..2c88d528c --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Metadata.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder() +public class Metadata { + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Parameters.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Parameters.java new file mode 100644 index 000000000..b3c2a76ec --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Parameters.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder() +public class Parameters { + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Properties.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Properties.java new file mode 100644 index 000000000..62ab71666 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Properties.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"size"}) +public class Properties { + + @JsonProperty("size") + private int size; + + /** + * @return The size + */ + @JsonProperty("size") + public int getSize() { + return size; + } + + /** + * @param size The size + */ + @JsonProperty("size") + public void setSize(int size) { + this.size = size; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/ResourceData.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/ResourceData.java new file mode 100644 index 000000000..902ed035f --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/ResourceData.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"backup_id"}) +public class ResourceData { + + @JsonProperty("backup_id") + private String backupId; + + /** + * @return The backupId + */ + @JsonProperty("backup_id") + public String getBackupId() { + return backupId; + } + + /** + * @param backupId The backup_id + */ + @JsonProperty("backup_id") + public void setBackupId(String backupId) { + this.backupId = backupId; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/ResourceRegistry.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/ResourceRegistry.java new file mode 100644 index 000000000..a9f3ff4b4 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/ResourceRegistry.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"resources"}) +public class ResourceRegistry { + + @JsonProperty("resources") + private Resources resources; + + /** + * @return The resources + */ + @JsonProperty("resources") + public Resources getResources() { + return resources; + } + + /** + * @param resources The resources + */ + @JsonProperty("resources") + public void setResources(Resources resources) { + this.resources = resources; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Resources.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Resources.java new file mode 100644 index 000000000..07457d70c --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Resources.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder() +public class Resources { + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Resources_.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Resources_.java new file mode 100644 index 000000000..63798ef0d --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Resources_.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"volume"}) +public class Resources_ { + + @JsonProperty("volume") + private Volume volume; + + /** + * @return The volume + */ + @JsonProperty("volume") + public Volume getVolume() { + return volume; + } + + /** + * @param volume The volume + */ + @JsonProperty("volume") + public void setVolume(Volume volume) { + this.volume = volume; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Resources__.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Resources__.java new file mode 100644 index 000000000..6a6b30050 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Resources__.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"volume"}) +public class Resources__ { + + @JsonProperty("volume") + private Volume_ volume; + + /** + * @return The volume + */ + @JsonProperty("volume") + public Volume_ getVolume() { + return volume; + } + + /** + * @param volume The volume + */ + @JsonProperty("volume") + public void setVolume(Volume_ volume) { + this.volume = volume; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Snapshot.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Snapshot.java new file mode 100644 index 000000000..93d1088c9 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Snapshot.java @@ -0,0 +1,149 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"id", "name", "status", "status_reason", "creation_time", "data"}) +public class Snapshot { + + @JsonProperty("id") + private String id; + @JsonProperty("name") + private String name; + @JsonProperty("status") + private String status; + @JsonProperty("status_reason") + private String statusReason; + @JsonProperty("creation_time") + private String creationTime; + @JsonProperty("data") + private Data data; + + /** + * @return The id + */ + @JsonProperty("id") + public String getId() { + return id; + } + + /** + * @param id The id + */ + @JsonProperty("id") + public void setId(String id) { + this.id = id; + } + + /** + * @return The name + */ + @JsonProperty("name") + public String getName() { + return name; + } + + /** + * @param name The name + */ + @JsonProperty("name") + public void setName(String name) { + this.name = name; + } + + /** + * @return The status + */ + @JsonProperty("status") + public String getStatus() { + return status; + } + + /** + * @param status The status + */ + @JsonProperty("status") + public void setStatus(String status) { + this.status = status; + } + + /** + * @return The statusReason + */ + @JsonProperty("status_reason") + public String getStatusReason() { + return statusReason; + } + + /** + * @param statusReason The status_reason + */ + @JsonProperty("status_reason") + public void setStatusReason(String statusReason) { + this.statusReason = statusReason; + } + + /** + * @return The creationTime + */ + @JsonProperty("creation_time") + public String getCreationTime() { + return creationTime; + } + + /** + * @param creationTime The creation_time + */ + @JsonProperty("creation_time") + public void setCreationTime(String creationTime) { + this.creationTime = creationTime; + } + + /** + * @return The data + */ + @JsonProperty("data") + public Data getData() { + return data; + } + + /** + * @param data The data + */ + @JsonProperty("data") + public void setData(Data data) { + this.data = data; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/SnapshotDetails.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/SnapshotDetails.java new file mode 100644 index 000000000..00b8920e9 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/SnapshotDetails.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"snapshot"}) +public class SnapshotDetails { + + @JsonProperty("snapshot") + private Snapshot snapshot; + + /** + * @return The snapshot + */ + @JsonProperty("snapshot") + public Snapshot getSnapshot() { + return snapshot; + } + + /** + * @param snapshot The snapshot + */ + @JsonProperty("snapshot") + public void setSnapshot(Snapshot snapshot) { + this.snapshot = snapshot; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/SnapshotRestoreResponse.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/SnapshotRestoreResponse.java new file mode 100644 index 000000000..a3023d00e --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/SnapshotRestoreResponse.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"code", "message", "title"}) +public class SnapshotRestoreResponse { + + @JsonProperty("code") + private String code; + @JsonProperty("message") + private String message; + @JsonProperty("title") + private String title; + + /** + * @return The code + */ + @JsonProperty("code") + public String getCode() { + return code; + } + + /** + * @param code The code + */ + @JsonProperty("code") + public void setCode(String code) { + this.code = code; + } + + /** + * @return The message + */ + @JsonProperty("message") + public String getMessage() { + return message; + } + + /** + * @param message The message + */ + @JsonProperty("message") + public void setMessage(String message) { + this.message = message; + } + + /** + * @return The title + */ + @JsonProperty("title") + public String getTitle() { + return title; + } + + /** + * @param title The title + */ + @JsonProperty("title") + public void setTitle(String title) { + this.title = title; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Template.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Template.java new file mode 100644 index 000000000..42245c70f --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Template.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"heat_template_version", "resources"}) +public class Template { + + @JsonProperty("heat_template_version") + private String heatTemplateVersion; + @JsonProperty("resources") + private Resources_ resources; + + /** + * @return The heatTemplateVersion + */ + @JsonProperty("heat_template_version") + public String getHeatTemplateVersion() { + return heatTemplateVersion; + } + + /** + * @param heatTemplateVersion The heat_template_version + */ + @JsonProperty("heat_template_version") + public void setHeatTemplateVersion(String heatTemplateVersion) { + this.heatTemplateVersion = heatTemplateVersion; + } + + /** + * @return The resources + */ + @JsonProperty("resources") + public Resources_ getResources() { + return resources; + } + + /** + * @param resources The resources + */ + @JsonProperty("resources") + public void setResources(Resources_ resources) { + this.resources = resources; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Volume.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Volume.java new file mode 100644 index 000000000..83c84db38 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Volume.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"type", "properties"}) +public class Volume { + + @JsonProperty("type") + private String type; + @JsonProperty("properties") + private Properties properties; + + /** + * @return The type + */ + @JsonProperty("type") + public String getType() { + return type; + } + + /** + * @param type The type + */ + @JsonProperty("type") + public void setType(String type) { + this.type = type; + } + + /** + * @return The properties + */ + @JsonProperty("properties") + public Properties getProperties() { + return properties; + } + + /** + * @param properties The properties + */ + @JsonProperty("properties") + public void setProperties(Properties properties) { + this.properties = properties; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Volume_.java b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Volume_.java new file mode 100644 index 000000000..d241b0814 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/java/org/onap/ccsdk/sli/adaptors/openstack/heat/model/Volume_.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.openstack.heat.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"status", "name", "resource_data", "resource_id", "action", "type", "metadata"}) +public class Volume_ { + + @JsonProperty("status") + private String status; + @JsonProperty("name") + private String name; + @JsonProperty("resource_data") + private ResourceData resourceData; + @JsonProperty("resource_id") + private String resourceId; + @JsonProperty("action") + private String action; + @JsonProperty("type") + private String type; + @JsonProperty("metadata") + private Metadata metadata; + + /** + * @return The status + */ + @JsonProperty("status") + public String getStatus() { + return status; + } + + /** + * @param status The status + */ + @JsonProperty("status") + public void setStatus(String status) { + this.status = status; + } + + /** + * @return The name + */ + @JsonProperty("name") + public String getName() { + return name; + } + + /** + * @param name The name + */ + @JsonProperty("name") + public void setName(String name) { + this.name = name; + } + + /** + * @return The resourceData + */ + @JsonProperty("resource_data") + public ResourceData getResourceData() { + return resourceData; + } + + /** + * @param resourceData The resource_data + */ + @JsonProperty("resource_data") + public void setResourceData(ResourceData resourceData) { + this.resourceData = resourceData; + } + + /** + * @return The resourceId + */ + @JsonProperty("resource_id") + public String getResourceId() { + return resourceId; + } + + /** + * @param resourceId The resource_id + */ + @JsonProperty("resource_id") + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + + /** + * @return The action + */ + @JsonProperty("action") + public String getAction() { + return action; + } + + /** + * @param action The action + */ + @JsonProperty("action") + public void setAction(String action) { + this.action = action; + } + + /** + * @return The type + */ + @JsonProperty("type") + public String getType() { + return type; + } + + /** + * @param type The type + */ + @JsonProperty("type") + public void setType(String type) { + this.type = type; + } + + /** + * @return The metadata + */ + @JsonProperty("metadata") + public Metadata getMetadata() { + return metadata; + } + + /** + * @param metadata The metadata + */ + @JsonProperty("metadata") + public void setMetadata(Metadata metadata) { + this.metadata = metadata; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/resources/cdp.properties b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/resources/cdp.properties new file mode 100644 index 000000000..8936f0c51 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/resources/cdp.properties @@ -0,0 +1,160 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ============LICENSE_END========================================================= +### + +# +# Default Properties - Configured for integration of CDP into APPC +# +#-------------------------------------------------------------------------------------------- +# The path and file used to load configuration settings, if any +com.att.cdp.bootstrap.path=${user.home},src/main/config,/etc/aft/scld/,/opt/app/aft/scld/etc/,/opt/app/aft/cdp/etc/,C:/Program Files/aft/scld/etc/,etc,../etc,. +com.att.cdp.bootstrap.file=cdp.properties +# com.att.cdp.system.admins= +# +# AFT properties for lat/long/environment and platform +# +AFT_LATITUDE=12.3456 +AFT_LONGITUDE=-12.3456 +AFT_ENVIRONMENT=AFT-ENVIRONMENT +SCLD_PLATFORM=OPEN-SOURCE +# +# The versions of CDP API, CDP itself, and the build number +# +API_VERSION=${version} +CDP_VERSION=${version} +CDP_BUILD=${buildNumber} +# +# The path to search for logging configuration document, and the name of the document +# +com.att.cdp.logging.path=${user.home},src/main/config,etc,../etc,. +com.att.cdp.logging.file=logback.xml +# +# The resource bundle base name to be loaded for message resources. This property can be a comma delimited list of resources to be +# loaded, allowing multiple resource bundles to be loaded simultaneously (for the same locale). +# +com.att.cdp.resources=com/att/cdp/StrategyServiceMessages +# +# Logger names used in the application +# +com.att.cdp.logger=org.onap.appc +com.att.cdp.security.logger=org.onap.appc.security +com.att.cdp.perf.logger=org.onap.appc.perf +com.att.cdp.gui.logger=org.onap.appc.gui +com.att.cdp.server.logger=org.onap.appc.server +com.att.cdp.coordinator.logger=org.onap.appc.coordinator +com.att.cdp.policy.logger=org.onap.appc.policy + +# +# This property allows to 'simulate' SSH processes within engine. +# By default, it is set to 'false' - So that it allows to actually execute SSH process. If 'true', it will 'simulate' SSH processes +# +com.att.cdp.ssh.simulate=false +# +# These properties are used to specify the default stack metadata path and file names written and read on each server node +# +com.att.cdp.metadata.path=/etc/cdp/metadata +com.att.cdp.metadata.export.filename=stack.xml +com.att.cdp.metadata.import.filename=stack.xml +# +#Below properties are to specify minimum and maximum bootstrap time in minutes. +#These properties are ONLY supposed to be used in tandem with SSH simulation.(testing purpose) +com.att.cdp.ssh.simulate.minBootstrapTime=6 +com.att.cdp.ssh.simulate.maxBootstrapTime=12 +# +# +# These properties are used to configure the AAF security interface +# +# com.att.cdp.aaf.connection.url = dme2 url to connect to aaf service +# com.att.cdp.aaf.connection.timeout = connection timeout, in seconds +# com.att.cdp.aaf.cache.flush = cache flush interval in minutes +# com.att.cdp.aaf.cache.size = the maximum number of cache entries +# com.att.cdp.aaf.auth.principal = The principal id we use to authenticate ourself to AAF +# com.att.cdp.aaf.auth.credentials = The credentials (password) we use to authenticate ourself to AAF +# +com.att.cdp.aaf.connection.url=https://DME2SITE/service=com.att.authz.AuthorizationService/version=2.0/envContext=TEST/routeOffer=BAU_SE +com.att.cdp.aaf.connection.timeout=10 +com.att.cdp.aaf.cache.flush=5 +com.att.cdp.aaf.cache.size=400 +com.att.cdp.aaf.auth.principal=emailaddress@example.com +com.att.cdp.aaf.auth.credentials=MyPassw0rd +# +# ---------------------------------------------------------------------------------------------------- +# These properties are used to configure the operation of the StackBuilder engine +# +# maximum number of build manager threads in the thread pool +com.att.cdp.engine.maxManagerPool=30 +# max number of worker threads in the pool for use by workers +com.att.cdp.engine.MaxWorkerPool=300 + +# max number of workers that can be created per build request (set to 1 to single-thread a build) +com.att.cdp.engine.maxWorkers=10 +# Maximum amount of time to wait for a provider to complete any requested operation, in minutes. Such +# as creating a server or a volume. +com.att.cdp.engine.maxWaitTime=15 +# +# ---------------------------------------------------------------------------------------------------- +# These properties are used to configure the managed node hostname generation/resolution process +# +com.att.cdp.managed.hostname.resolve.retry=3 +# ---------------------------------------------------------------------------------------------------- +# +# Cassandra Connection Configuration Properties +# +cassandra.userName=cassandra +cassandra.password=cassandra +#cassandra.dataCenter= +cassandra.hosts=127.0.0.1 +cassandra.port=9042 +cassandra.keyspace=cdp +cassandra.minPoolSize=8 +cassandra.maxPoolSize=8 +cassandra.readtimeout=180000 +# +# Cassandra data Migration toggle +com.att.cdp.db.migration=true +com.att.cdp.db.update=true + +#Default Values for Image Attributes Configuration.These SHOULD NOT be removed. +image.default.namepattern=.* +image.default.user=root +image.default.sudo=false + +# ---------------------------------------------------------------------------------------------------- +# +# The path OSSupport will search for OS configuration properties files +# +com.att.cdp.OSType.path=/etc/os/ +# ---------------------------------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------------------------------- +# +# The properties used in ConnectivityBuilder +internet_url=www.google.com +ubuntu_sat_access_url=example.com +grm_server_url=example.com +# +# ---------------------------------------------------------------------------------------------------- +com.att.cdp.ptr.cleanup=true + +# ---------------------------------------------------------------------------------------------------- +# The maximum amount of time in seconds that we should wait for input from the shell +com.att.cdp.ssh.timeout=1800 diff --git a/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/resources/default.properties b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/resources/default.properties new file mode 100644 index 000000000..06f6950b6 --- /dev/null +++ b/adaptors/iaas-adaptor/iaas-adaptor-bundle/src/main/resources/default.properties @@ -0,0 +1,111 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ============LICENSE_END========================================================= +### + +# +# Default properties for the APP-C Provider Adapter +# +# ------------------------------------------------------------------------------------------------- +# +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded +# to supply configuration options +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/onap/appc/data/properties,${user.home},. + +appc.application.name=APPC + +# +# Define the message resource bundle name to be loaded +org.onap.appc.resources=org/onap/appc/i18n/MessageResources +# +# The name of the adapter. +org.onap.appc.provider.adaptor.name=org.onap.appc.appc_provider_adapter +# +# Set up the logging environment +# +org.onap.appc.logging.file=org/onap/appc/logback.xml +org.onap.appc.logging.path=${user.home};etc;../etc +org.onap.appc.logger=org.onap.appc +org.onap.appc.security.logger=org.onap.appc.security +# +# The minimum and maximum provider/tenant context pool sizes. Min=1 means that as soon +# as the provider/tenant is referenced a Context is opened and added to the pool. Max=0 +# means that the upper bound on the pool is unbounded. +org.onap.appc.provider.min.pool=1 +org.onap.appc.provider.max.pool=0 + +# +# The following properties are used to configure the retry logic for connection to the +# IaaS provider(s). The retry delay property is the amount of time, in seconds, the +# application waits between retry attempts. The retry limit is the number of retries +# that are allowed before the request is failed. +org.onap.appc.provider.retry.delay = 30 +org.onap.appc.provider.retry.limit = 10 + +# +# The trusted hosts list for SSL access when a certificate is not provided. +# +provider.trusted.hosts=* +# +# The amount of time, in seconds, to wait for a server state change (start->stop, stop->start, etc). +# If the server does not change state to a valid state within the alloted time, the operation +# fails. +org.onap.appc.server.state.change.timeout=300 +# +# The amount of time to wait, in seconds, between subsequent polls to the OpenStack provider +# to refresh the status of a resource we are waiting on. +# +org.onap.appc.openstack.poll.interval=20 + + # + #The amount of time, in seconds, that the application waits for a change of state of a stacj to a known valid + #sate before giving up and failing the request. + # +org.onap.appc.stack.state.change.timeout=100 + + + +# +# The connection information to connect to the provider we are using. These properties +# are "structured" properties, in that the name is a compound name, where the nodes +# of the name can be ordered (1, 2, 3, ...). All of the properties with the same ordinal +# position are defining the same entity. For example, provider1.type and provider1.name +# are defining the same provider, whereas provider2.name and provider2.type are defining +# the values for a different provider. Any number of providers can be defined in this +# way. +# +# Don't change these 2 right now since they are hard coded in the DG +provider1.type=appc +provider1.name=appc + +#These you can change +provider1.identity=appc +provider1.tenant1.name=appc +provider1.tenant1.userid=appc +provider1.tenant1.password=appc + +#Your OpenStack IP +test.ip=192.168.1.2 +# Your OpenStack Platform's Keystone Port (default is 5000) +test.port=5000 +test.tenantid=abcde12345fghijk6789lmnopq123rst +test.vmid=abc12345-1234-5678-890a-abcdefg12345 |