diff options
author | Patrick Brady <pb071s@att.com> | 2017-02-15 23:11:26 -0800 |
---|---|---|
committer | Patrick Brady <pb071s@att.com> | 2017-02-15 23:13:06 -0800 |
commit | 1c192d2dd68724e292b6a30f463085a262e1e813 (patch) | |
tree | d0e2b3a396e169863cd0efaa835c8675e9d5aaac /appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src | |
parent | c69ba05c7508aa7d7f675189a45c8c87569369ef (diff) |
Moving all files to root directory
Change-Id: Ica5535fd6ec85f350fe1640b42137b49f83f10f0
Signed-off-by: Patrick Brady <pb071s@att.com>
Diffstat (limited to 'appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src')
10 files changed, 2333 insertions, 0 deletions
diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RestActivator.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RestActivator.java new file mode 100644 index 000000000..d1515c418 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RestActivator.java @@ -0,0 +1,143 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.adapter.rest; + +import org.openecomp.appc.Constants; +import org.openecomp.appc.adapter.rest.impl.RestAdapterImpl; +import org.openecomp.appc.configuration.Configuration; +import org.openecomp.appc.configuration.ConfigurationFactory; +import org.openecomp.appc.i18n.Msg; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +/** + * This activator is used to initialize and terminate the connection pool to one or more providers. + * <p> + * The CDP abstraction layer supports multiple types of providers, with each provider supporting multiple tenants. The + * "connection" to a specific tenant on a specific provider is represented by a "context" object. These context objects + * are authenticated to a specific tenant on the provider, but can be reused from one request to another. Contexts are + * slow to set up and are resource intensive, so they are cached. However, the contexts for a specific tenant on a + * specific provider must be cached separately. + * </p> + * <p> + * Activation of the bundle creates an empty cache which is organized first by provider type, then by tenant name, with + * the contents being an empty pool of contexts for that provider/tenant combination. The pool is created on first use, + * and retained for as long as the bundle is active. + * </p> + * <p> + * When the bundle is deactivated, the cache is torn down with all contexts being closed. + * </p> + */ +public class RestActivator implements BundleActivator { + + /** + * The bundle registration + */ + private ServiceRegistration registration = null; + + /** + * The reference to the actual implementation object that implements the services + */ + private RestAdapter adapter; + + /** + * The logger to be used + */ + // private static final Logger LOG = LoggerFactory.getLogger(RestActivator.class); + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestActivator.class); + + /** + * The configuration object used to configure this bundle + */ + private Configuration configuration; + + /** + * Called when this bundle is started so the Framework can perform the bundle-specific activities necessary to start + * this bundle. This method can be used to register services or to allocate any resources that this bundle needs. + * <p> + * This method must complete and return to its caller in a timely manner. + * </p> + * + * @param context + * The execution context of the bundle being started. + * @throws java.lang.Exception + * If this method throws an exception, this bundle is marked as stopped and the Framework will remove + * this bundle's listeners, unregister all services registered by this bundle, and release all services + * used by this bundle. + * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) + */ + @Override + public void start(BundleContext context) throws Exception { + logger.info("Starting bundle " + getName()); + + configuration = ConfigurationFactory.getConfiguration(); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + logger.info(Msg.COMPONENT_INITIALIZING, appName, "rest adapter"); + adapter = new RestAdapterImpl(configuration.getProperties()); + if (registration == null) { + logger.info(Msg.REGISTERING_SERVICE, appName, adapter.getAdapterName(), + RestAdapter.class.getSimpleName()); + registration = context.registerService(RestAdapter.class, adapter, null); + } + + logger.info(Msg.COMPONENT_INITIALIZED, appName, "REST adapter"); + } + + /** + * Called when this bundle is stopped so the Framework can perform the bundle-specific activities necessary to stop + * the bundle. In general, this method should undo the work that the BundleActivator.start method started. There + * should be no active threads that were started by this bundle when this bundle returns. A stopped bundle must not + * call any Framework objects. + * <p> + * This method must complete and return to its caller in a timely manner. + * </p> + * + * @param context + * The execution context of the bundle being stopped. + * @throws java.lang.Exception + * If this method throws an exception, the bundle is still marked as stopped, and the Framework will + * remove the bundle's listeners, unregister all services registered by the bundle, and release all + * services used by the bundle. * + * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) + */ + @Override + public void stop(BundleContext context) throws Exception { + logger.info("Stopping bundle " + getName()); + + if (registration != null) { + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + logger.info(Msg.COMPONENT_TERMINATING, appName, "REST adapter"); + logger.info(Msg.UNREGISTERING_SERVICE, appName, adapter.getAdapterName()); + registration.unregister(); + registration = null; + logger.info(Msg.COMPONENT_TERMINATED, appName, "REST adapter"); + } + } + + public String getName() { + return "APPC IaaS adapter"; + } + +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RestAdapter.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RestAdapter.java new file mode 100644 index 000000000..0d4a19709 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RestAdapter.java @@ -0,0 +1,205 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.adapter.rest; + +import java.util.Map; + +import org.openecomp.appc.exceptions.APPCException; +import com.att.cdp.zones.model.Server; +import org.openecomp.sdnc.sli.SvcLogicContext; +import org.openecomp.sdnc.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 RestAdapter 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.openecomp.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.openecomp.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.openecomp.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.openecomp.appc.identity.url"; + + /** + * 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.openecomp.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.openecomp.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 APPCException + * If the server cannot be restarted for some reason + */ + // Server restartServer(Map<String, String> properties, SvcLogicContext context) throws APPCException; + + /** + * 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.openecomp.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.openecomp.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 APPCException + * If the server cannot be stopped for some reason + */ + //Server stopServer(Map<String, String> properties, SvcLogicContext context) throws APPCException; + + /** + * 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.openecomp.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.openecomp.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 APPCException + * If the server cannot be started for some reason + */ + // Server startServer(Map<String, String> properties, SvcLogicContext context) throws APPCException; + + /** + * 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.openecomp.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.openecomp.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 APPCException + * If the server cannot be rebuilt for some reason + */ + // Server rebuildServer(Map<String, String> properties, SvcLogicContext context) throws APPCException; + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + */ + String getAdapterName(); + + // Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException; + + //Server migrateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException; + + void commonGet(Map<String, String> params, SvcLogicContext ctx) ; + + void commonPost(Map<String, String> params, SvcLogicContext ctx) ; + + void commonPut(Map<String, String> params, SvcLogicContext ctx) ; + + void commonDelete(Map<String, String> params, SvcLogicContext ctx) ; + +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RequestContext.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RequestContext.java new file mode 100644 index 000000000..c4b852317 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RequestContext.java @@ -0,0 +1,251 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + + +package org.openecomp.appc.adapter.rest.impl; + +import org.openecomp.appc.Constants; +import org.openecomp.appc.configuration.Configuration; +import org.openecomp.appc.configuration.ConfigurationFactory; +import org.openecomp.sdnc.sli.SvcLogicContext; + +/** + * 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(); + } + } + } + } + + /** + * @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; + if (accumulatedTime > timeToLive) { + return false; + } + return true; + } + + /** + * @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/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RequestFailedException.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RequestFailedException.java new file mode 100644 index 000000000..eff1597c1 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RequestFailedException.java @@ -0,0 +1,244 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + + +package org.openecomp.appc.adapter.rest.impl; + +import org.glassfish.grizzly.http.util.HttpStatus; +import com.att.cdp.zones.model.Server; + +/** + * 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 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 most appropriate Http Status code that reflects the error + */ + private 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 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/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RestAdapterImpl.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RestAdapterImpl.java new file mode 100644 index 000000000..82aad7d6f --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RestAdapterImpl.java @@ -0,0 +1,491 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.adapter.rest.impl; + +import java.net.URI; +import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.regex.Pattern; + +import org.openecomp.appc.Constants; +import org.openecomp.appc.adapter.rest.RestAdapter; +import org.openecomp.appc.configuration.Configuration; +import org.openecomp.appc.configuration.ConfigurationFactory; +import org.openecomp.appc.exceptions.APPCException; +import org.openecomp.appc.exceptions.UnknownProviderException; +import org.openecomp.appc.i18n.Msg; +import org.openecomp.appc.pool.Pool; +import org.openecomp.appc.pool.PoolExtensionException; +import org.openecomp.appc.util.StructuredPropertyHelper; +import org.openecomp.appc.util.StructuredPropertyHelper.Node; +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.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.Provider; +import com.att.cdp.zones.model.Image; +import com.att.cdp.zones.model.Server; +import com.att.cdp.zones.model.Server.Status; +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 org.openecomp.sdnc.sli.SvcLogicContext; + +import org.glassfish.grizzly.http.util.HttpStatus; +import org.slf4j.MDC; + +import java.net.InetAddress; +import java.util.Locale; +import java.util.UUID; +import static com.att.eelf.configuration.Configuration.*; + +import org.apache.http.*; +import org.apache.http.client.*; +import org.apache.http.client.methods.*; +import org.apache.http.impl.client.*; +import org.apache.http.util.EntityUtils; +import java.io.IOException; +import org.apache.http.entity.StringEntity; + +import java.net.InetAddress; +import org.json.*; + +/** + * This class implements the {@link RestAdapter} interface. This interface + * defines the behaviors that our service provides. + */ +public class RestAdapterImpl implements RestAdapter { + + /** + * The constant used to define the adapter name in the mapped diagnostic + * context + */ + + + @SuppressWarnings("nls") + public static final String MDC_ADAPTER = "adapter"; + + /** + * The constant used to define the service name in the mapped diagnostic + * context + */ + @SuppressWarnings("nls") + public static final String MDC_SERVICE = "service"; + + /** + * The constant for the status code for a failed outcome + */ + @SuppressWarnings("nls") + public static final String OUTCOME_FAILURE = "failure"; + + /** + * The constant for the status code for a successful outcome + */ + @SuppressWarnings("nls") + public static final String OUTCOME_SUCCESS = "success"; + + /** + * A constant for the property token "provider" used in the structured + * property specifications + */ + @SuppressWarnings("nls") + public static final String PROPERTY_PROVIDER = "provider"; + + /** + * A constant for the property token "identity" used in the structured + * property specifications + */ + @SuppressWarnings("nls") + public static final String PROPERTY_PROVIDER_IDENTITY = "identity"; + + /** + * A constant for the property token "name" used in the structured property + * specifications + */ + @SuppressWarnings("nls") + public static final String PROPERTY_PROVIDER_NAME = "name"; + + /** + * A constant for the property token "tenant" used in the structured + * property specifications + */ + @SuppressWarnings("nls") + public static final String PROPERTY_PROVIDER_TENANT = "tenant"; + + /** + * A constant for the property token "tenant name" used in the structured + * property specifications + */ + @SuppressWarnings("nls") + public static final String PROPERTY_PROVIDER_TENANT_NAME = "name"; + + /** + * A constant for the property token "password" used in the structured + * property specifications + */ + @SuppressWarnings("nls") + public static final String PROPERTY_PROVIDER_TENANT_PASSWORD = "password"; // NOSONAR + + /** + * A constant for the property token "userid" used in the structured + * property specifications + */ + @SuppressWarnings("nls") + public static final String PROPERTY_PROVIDER_TENANT_USERID = "userid"; + + /** + * A constant for the property token "type" used in the structured property + * specifications + */ + @SuppressWarnings("nls") + public static final String PROPERTY_PROVIDER_TYPE = "type"; + + /** + * The name of the service to restart a server + */ + @SuppressWarnings("nls") + public static final String PING_SERVICE = "pingServer"; + + /** + * The logger to be used + */ + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestAdapterImpl.class); + + /** + * The constant for a left parenthesis + */ + private static final char LPAREN = '('; + + /** + * The constant for a new line control code + */ + private static final char NL = '\n'; + + /** + * The constant for a single quote + */ + private static final char QUOTE = '\''; + + /** + * The constant for a right parenthesis + */ + private static final char RPAREN = ')'; + + /** + * The constant for a space + */ + private static final char SPACE = ' '; + + /** + * A reference to the adapter configuration object. + */ + private Configuration configuration; + + /** + * A cache of providers that are predefined. + */ + // private Map<String /* provider name */, ProviderCache> providerCache; + + /** + * This default constructor is used as a work around because the activator + * wasnt getting called + */ + /** + * A cache of providers that are predefined. + */ + // private Map<String /* provider name */, ProviderCache> providerCache; + + /** + * This default constructor is used as a work around because the activator + * wasnt getting called + */ + public RestAdapterImpl() { + 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 + */ + public RestAdapterImpl(boolean initialize) { + configuration = ConfigurationFactory.getConfiguration(); + if (initialize) { + initialize(); + + } + } + + /** + * @param props + * not used + */ + public RestAdapterImpl(Properties props) { + initialize(); + + } + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + * @see org.openecomp.appc.adapter.rest.RestAdapter#getAdapterName() + */ + @Override + public String getAdapterName() { + return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME); + } + + public HttpRequestBase addHeaders(HttpRequestBase method,String headers){ + if(headers.length()==0) + { + return method; + }else{ + JSONObject JsonHeaders= new JSONObject(headers); + Iterator keys = JsonHeaders.keys(); + while(keys.hasNext()) { + String String1 = (String)keys.next(); + String String2 = JsonHeaders.getString(String1); + method.addHeader(String1,String2); + } + return method; + } + } + + + public void commonGet(Map<String, String> params, SvcLogicContext ctx) { + logger.info("Run get method"); + String haveHeader="false"; + String tUrl=params.get("org.openecomp.appc.instance.URI"); + haveHeader=params.get("org.openecomp.appc.instance.haveHeader"); + String headers=params.get("org.openecomp.appc.instance.headers"); + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + try { + HttpGet httpGet = new HttpGet(tUrl); + + if(haveHeader.equals("true")) + { + JSONObject JsonHeaders= new JSONObject(headers); + Iterator keys = JsonHeaders.keys(); + while(keys.hasNext()) { + String String1 = (String)keys.next(); + String String2 = JsonHeaders.getString(String1); + httpGet.addHeader(String1,String2); + } + + } + + HttpClient httpClient = HttpClients.createDefault(); + HttpResponse response = null; + response = httpClient.execute(httpGet); + int responseCode=response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String responseOutput=EntityUtils.toString(entity); + doSuccess(rc,responseCode,responseOutput); + } catch (Exception ex) { + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); + } + } + + + public void commonDelete(Map<String, String> params, SvcLogicContext ctx) { + logger.info("Run Delete method"); + String haveHeader="false"; + String tUrl=params.get("org.openecomp.appc.instance.URI"); + haveHeader=params.get("org.openecomp.appc.instance.haveHeader"); + String headers=params.get("org.openecomp.appc.instance.headers"); + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + try { + HttpDelete httpDelete = new HttpDelete(tUrl); + if(haveHeader.equals("true")) + { + JSONObject JsonHeaders= new JSONObject(headers); + Iterator keys = JsonHeaders.keys(); + while(keys.hasNext()) { + String String1 = (String)keys.next(); + String String2 = JsonHeaders.getString(String1); + httpDelete.addHeader(String1,String2); + } + + } + HttpClient httpClient = HttpClients.createDefault(); + HttpResponse response = null; + response = httpClient.execute(httpDelete); + int responseCode=response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String responseOutput=EntityUtils.toString(entity); + doSuccess(rc,responseCode,responseOutput); + } catch (Exception ex) { + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); + } + } + + + + public void commonPost(Map<String, String> params, SvcLogicContext ctx) { + logger.info("Run post method"); + String haveHeader="false"; + String tUrl=params.get("org.openecomp.appc.instance.URI"); + String body=params.get("org.openecomp.appc.instance.requestBody"); + haveHeader=params.get("org.openecomp.appc.instance.haveHeader"); + String headers=params.get("org.openecomp.appc.instance.headers"); + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + try { + HttpPost httpPost = new HttpPost(tUrl); + if(haveHeader.equals("true")) + { + JSONObject JsonHeaders= new JSONObject(headers); + Iterator keys = JsonHeaders.keys(); + while(keys.hasNext()) { + String String1 = (String)keys.next(); + String String2 = JsonHeaders.getString(String1); + httpPost.addHeader(String1,String2); + } + + } + StringEntity bodyParams =new StringEntity (body,"UTF-8"); + httpPost.setEntity(bodyParams); + HttpClient httpClient = HttpClients.createDefault(); + HttpResponse response = null; + response = httpClient.execute(httpPost); + int responseCode=response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String responseOutput=EntityUtils.toString(entity); + doSuccess(rc,responseCode,responseOutput); + } catch (Exception ex) { + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); + } + } + + public void commonPut(Map<String, String> params, SvcLogicContext ctx) { + logger.info("Run put method"); + String haveHeader="false"; + String tUrl=params.get("org.openecomp.appc.instance.URI"); + String body=params.get("org.openecomp.appc.instance.requestBody"); + haveHeader=params.get("org.openecomp.appc.instance.haveHeader"); + String headers=params.get("org.openecomp.appc.instance.headers"); + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + try { + HttpPut httpPut = new HttpPut(tUrl); + if(haveHeader.equals("true")) + { + JSONObject JsonHeaders= new JSONObject(headers); + Iterator keys = JsonHeaders.keys(); + while(keys.hasNext()) { + String String1 = (String)keys.next(); + String String2 = JsonHeaders.getString(String1); + httpPut.addHeader(String1,String2); + } + + } + StringEntity bodyParams =new StringEntity (body,"UTF-8"); + httpPut.setEntity(bodyParams); + HttpClient httpClient = HttpClients.createDefault(); + HttpResponse response = null; + response = httpClient.execute(httpPut); + int responseCode=response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String responseOutput=EntityUtils.toString(entity); + if(responseCode == 200){ + doSuccess(rc,responseCode,responseOutput); + } else { + doFailure(rc, HttpStatus.getHttpStatus(responseCode), response.getStatusLine().getReasonPhrase()); + } + } + catch (Exception ex) { + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); + } +/* } catch (Exception ex) { + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.getMessage()); + }*/ + } + + @SuppressWarnings("static-method") + private void doFailure(RequestContext rc, HttpStatus code, String message) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + String msg = (message == null) ? code.getReasonPhrase() : message; + if (msg.contains("\n")) { + msg = msg.substring(msg.indexOf("\n")); + } + + String status; + try { + status = Integer.toString(code.getStatusCode()); + } catch (Exception e) { + status = "500"; + } + svcLogic.setStatus(OUTCOME_FAILURE); + svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, status); + svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + svcLogic.setAttribute("org.openecomp.rest.result.code", status); + svcLogic.setAttribute("org.openecomp.rest.result.message", msg); + } + + + /** + * @param rc + * The request context that manages the state and recovery of the + * request for the life of its processing. + */ + @SuppressWarnings("static-method") + private void doSuccess(RequestContext rc, int code, String message) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setStatus(OUTCOME_SUCCESS); + svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, Integer.toString(HttpStatus.OK_200.getStatusCode())); + svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, message); + svcLogic.setAttribute("org.openecomp.rest.agent.result.code",Integer.toString(code)); + svcLogic.setAttribute("org.openecomp.rest.agent.result.message",message); + svcLogic.setAttribute("org.openecomp.rest.result.code",Integer.toString(HttpStatus.OK_200.getStatusCode())); + } + + + /** + * initialize the provider adapter by building the context cache + */ + private void initialize() { + configuration = ConfigurationFactory.getConfiguration(); + + logger.info("init rest adapter!!!!!"); + } + +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties new file mode 100644 index 000000000..3d4f9b373 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties @@ -0,0 +1,93 @@ +### +# ============LICENSE_START======================================================= +# openECOMP : APP-C +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights +# reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +# +# 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.openecomp.appc.bootstrap.file=appc.properties +org.openecomp.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +appc.application.name=APPC + +# +# Define the message resource bundle name to be loaded +org.openecomp.appc.resources=org/openecomp/appc/i18n/MessageResources +# +# The name of the adapter. +org.openecomp.appc.provider.adaptor.name=org.openecomp.appc.appc_provider_adapter +# +# Set up the logging environment +# +org.openecomp.appc.logging.file=org/openecomp/appc/logback.xml +org.openecomp.appc.logging.path=${user.home};etc;../etc +org.openecomp.appc.logger=org.openecomp.appc +org.openecomp.appc.security.logger=org.openecomp.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.openecomp.appc.provider.min.pool=1 +org.openecomp.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.openecomp.appc.provider.retry.delay = 30 +org.openecomp.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.openecomp.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.openecomp.appc.openstack.poll.interval=20 +# +# The connection information to connect to the provider we are using. These properties +# are "structured" properties, in that the name is a compound name, where the nodes +# of the name can be ordered (1, 2, 3, ...). All of the properties with the same ordinal +# position are defining the same entity. For example, provider1.type and provider1.name +# are defining the same provider, whereas provider2.name and provider2.type are defining +# the values for a different provider. Any number of providers can be defined in this +# way. +# +# Don't change these 2 right now since they are hard coded in the DG +#provider1.type=appc +#provider1.name=appc + +#These you can change +#provider1.identity=appc +#provider1.tenant1.name=appc +#provider1.tenant1.userid=appc +#provider1.tenant1.password=appc diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/adapter/rest/impl/TestRestAdapterImpl.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/adapter/rest/impl/TestRestAdapterImpl.java new file mode 100644 index 000000000..daa379413 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/adapter/rest/impl/TestRestAdapterImpl.java @@ -0,0 +1,161 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.adapter.rest.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.slf4j.MDC; + +import org.openecomp.appc.Constants; +import org.openecomp.appc.adapter.rest.RestAdapter; +import org.openecomp.appc.configuration.ConfigurationFactory; +import org.openecomp.appc.exceptions.APPCException; +import org.openecomp.appc.exceptions.UnknownProviderException; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.ComputeService; +import com.att.cdp.zones.Context; +import com.att.cdp.zones.ContextFactory; +import com.att.cdp.zones.model.Server; +import com.att.cdp.zones.model.Server.Status; +import org.openecomp.sdnc.sli.SvcLogicContext; + + +/** + * Test the ProviderAdapter implementation. + */ + +@Ignore +public class TestRestAdapterImpl { + + @SuppressWarnings("nls") + private static final String PROVIDER_NAME = "APPC"; + + @SuppressWarnings("nls") + private static final String PROVIDER_TYPE = "OpenStackProvider"; + + private static String IDENTITY_URL; + + private static String PRINCIPAL; + + private static String CREDENTIAL; + + private static String TENANT_NAME; + + private static String TENANT_ID; + + private static String USER_ID; + + private static String REGION_NAME; + + private static String SERVER_URL; + + private static Class<?> providerAdapterImplClass; + private static Class<?> configurationFactoryClass; + private static Field providerCacheField; + private static Field configField; + + private RestAdapterImpl adapter; + + + @SuppressWarnings("nls") + @BeforeClass + public static void once() throws NoSuchFieldException, SecurityException, NoSuchMethodException { + + } + + @Before + public void setup() throws IllegalArgumentException, IllegalAccessException { + + adapter = new RestAdapterImpl(); + } + + @Test + public void testCommonGet() throws IOException, IllegalStateException, IllegalArgumentException, + ZoneException, APPCException { + + Map<String, String> params = new HashMap<>(); + params.put("org.openecomp.appc.instance.URI", "http://example.com:8080/about/health"); + params.put("org.openecomp.appc.instance.haveHeader","false"); + SvcLogicContext svcContext = new SvcLogicContext(); + adapter.commonGet(params, svcContext); + String statusCode=svcContext.getAttribute("org.openecomp.rest.agent.result.code"); + assertEquals("200",statusCode); + } + + @Test + public void testCommonPost() throws IOException, IllegalStateException, IllegalArgumentException, + ZoneException, APPCException { + + Map<String, String> params = new HashMap<>(); + params.put("org.openecomp.appc.instance.URI", "http://example.com:8081/posttest"); + params.put("org.openecomp.appc.instance.haveHeader","false"); + params.put("org.openecomp.appc.instance.requestBody", "{\"name\":\"MyNode\", \"width\":200, \"height\":100}"); + SvcLogicContext svcContext = new SvcLogicContext(); + adapter.commonPost(params, svcContext); + String statusCode=svcContext.getAttribute("org.openecomp.rest.agent.result.code"); + assertEquals("200",statusCode); + } + + @Test + public void testCommonPut() throws IOException, IllegalStateException, IllegalArgumentException, + ZoneException, APPCException { + + Map<String, String> params = new HashMap<>(); + params.put("org.openecomp.appc.instance.URI", "http://example.com:8081/puttest"); + params.put("org.openecomp.appc.instance.haveHeader","false"); + params.put("org.openecomp.appc.instance.requestBody", "{\"name\":\"MyNode2\", \"width\":300, \"height\":300}"); + SvcLogicContext svcContext = new SvcLogicContext(); + adapter.commonPut(params, svcContext); + String statusCode=svcContext.getAttribute("org.openecomp.rest.agent.result.code"); + assertEquals("200",statusCode); + } + + @Test + public void testCommonDelete() throws IOException, IllegalStateException, IllegalArgumentException, + ZoneException, APPCException { + + Map<String, String> params = new HashMap<>(); + params.put("org.openecomp.appc.instance.URI", "http://example.com:8081/deletetest"); + params.put("org.openecomp.appc.instance.haveHeader","false"); + SvcLogicContext svcContext = new SvcLogicContext(); + adapter.commonDelete(params, svcContext); + String statusCode=svcContext.getAttribute("org.openecomp.rest.agent.result.code"); + assertEquals("200",statusCode); + } + + +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java new file mode 100644 index 000000000..c21435d2e --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java @@ -0,0 +1,180 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + +package org.openecomp.appc.test; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.appc.test.InterceptLogger; + +import org.openecomp.sdnc.sli.SvcLogicContext; +import org.openecomp.sdnc.sli.SvcLogicJavaPlugin; + +/** + * This class is used as a test harness to wrap the call to an executor node. + */ + +public class ExecutorHarness { + + /** + * The executor to be tested + */ + private SvcLogicJavaPlugin executor; + + /** + * The collection of all exec methods found on the class + */ + private Map<String, Method> methods; + + /** + * The field of the class being tested that contains the reference to the logger to be used. This is modified to + * point to our interception logger for the test. + */ + private Field contextLogger; + + /** + * The interception logger that buffers all messages logged and allows us to look at them as part of the test case. + */ + private InterceptLogger logger; + + /** + * Create the harness and initialize it + * + * @throws SecurityException + * If a security manager, s, is present and any of the following conditions is met: + * <ul> + * <li>invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field</li> + * <li>the caller's class loader is not the same as or an ancestor of the class loader for the current + * class and invocation of s.checkPackageAccess() denies access to the package of this class</li> + * </ul> + * @throws NoSuchFieldException + * if a field with the specified name is not found. + * @throws IllegalAccessException + * if this Field object is enforcing Java language access control and the underlying field is either + * inaccessible or final. + * @throws IllegalArgumentException + * if the specified object is not an instance of the class or interface declaring the underlying field + * (or a subclass or implementor thereof), or if an unwrapping conversion fails. + */ + @SuppressWarnings("nls") + public ExecutorHarness() throws NoSuchFieldException, SecurityException, IllegalArgumentException, + IllegalAccessException { + methods = new HashMap<>(); + new SvcLogicContext(); + + Class<?> contextClass = SvcLogicContext.class; + contextLogger = contextClass.getDeclaredField("LOG"); + contextLogger.setAccessible(true); + logger = new InterceptLogger(); + contextLogger.set(null, logger); + } + + /** + * Convenience constructor + * + * @param executor + * The executor to be tested by the harness + * @throws SecurityException + * If a security manager, s, is present and any of the following conditions is met: + * <ul> + * <li>invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field</li> + * <li>the caller's class loader is not the same as or an ancestor of the class loader for the current + * class and invocation of s.checkPackageAccess() denies access to the package of this class</li> + * </ul> + * @throws NoSuchFieldException + * if a field with the specified name is not found. + * @throws IllegalAccessException + * if this Field object is enforcing Java language access control and the underlying field is either + * inaccessible or final. + * @throws IllegalArgumentException + * if the specified object is not an instance of the class or interface declaring the underlying field + * (or a subclass or implementor thereof), or if an unwrapping conversion fails. + */ + public ExecutorHarness(SvcLogicJavaPlugin executor) throws NoSuchFieldException, SecurityException, + IllegalArgumentException, IllegalAccessException { + this(); + setExecutor(executor); + } + + /** + * @param executor + * The java plugin class to be executed + */ + public void setExecutor(SvcLogicJavaPlugin executor) { + this.executor = executor; + scanExecutor(); + } + + /** + * @return The java plugin class to be executed + */ + public SvcLogicJavaPlugin getExecutor() { + return executor; + } + + /** + * @return The set of all methods that meet the signature requirements + */ + public List<String> getExecMethodNames() { + List<String> names = new ArrayList<>(); + names.addAll(methods.keySet()); + return names; + } + + /** + * Returns an indication if the named method is a valid executor method that could be called from a DG execute node + * + * @param methodName + * The method name to be validated + * @return True if the method name meets the signature requirements, false if the method either does not exist or + * does not meet the requirements. + */ + public boolean isExecMethod(String methodName) { + return methods.containsKey(methodName); + } + + /** + * This method scans the executor class hierarchy to locate all methods that match the required signature of the + * executor and records these methods in a map. + */ + private void scanExecutor() { + methods.clear(); + Class<?> executorClass = executor.getClass(); + Method[] publicMethods = executorClass.getMethods(); + for (Method method : publicMethods) { + if (method.getReturnType().equals(Void.class)) { + Class<?>[] paramTypes = method.getParameterTypes(); + if (paramTypes.length == 2) { + if (Map.class.isAssignableFrom(paramTypes[0]) + && SvcLogicContext.class.isAssignableFrom(paramTypes[1])) { + methods.put(method.getName(), method); + } + } + } + } + } +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java new file mode 100644 index 000000000..acb122914 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java @@ -0,0 +1,452 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : APP-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + + +package org.openecomp.appc.test; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Marker; + +import ch.qos.logback.classic.Level; + +/** + * This class is used as an intercept logger that can be used in testing to intercept and record all messages that are + * logged, thus allowing a junit test case to examine the log output and make assertions. + */ +public class InterceptLogger implements org.slf4j.Logger { + + /** + * This inner class represents an intercepted log event. + */ + public class LogRecord { + private Level level; + private String message; + private long timestamp; + private Throwable t; + + public LogRecord(Level level, String message) { + setLevel(level); + setTimestamp(System.currentTimeMillis()); + setMessage(message); + } + + public LogRecord(Level level, String message, Throwable t) { + this(level, message); + setThrowable(t); + } + + /** + * @return the value of level + */ + public Level getLevel() { + return level; + } + + /** + * @return the value of message + */ + public String getMessage() { + return message; + } + + /** + * @return the value of timestamp + */ + public long getTimestamp() { + return timestamp; + } + + /** + * @param level + * the value for level + */ + public void setLevel(Level level) { + this.level = level; + } + + /** + * @param message + * the value for message + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * @param timestamp + * the value for timestamp + */ + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + /** + * @return the value of t + */ + public Throwable getThrowable() { + return t; + } + + /** + * @param t + * the value for t + */ + public void setThrowable(Throwable t) { + this.t = t; + } + + } + + /** + * The list of all intercepted log events + */ + private List<LogRecord> events; + + /** + * Create the intercept logger + */ + public InterceptLogger() { + events = new ArrayList<LogRecord>(1000); + } + + /** + * @return Returns all intercepted log events + */ + public List<LogRecord> getLogRecords() { + return events; + } + + /** + * Clears all log events + */ + public void clear() { + events.clear(); + } + + @Override + public void debug(Marker marker, String msg) { + debug(msg); + } + + @Override + public void debug(Marker marker, String format, Object arg) { + debug(MessageFormat.format(format, arg)); + } + + @Override + public void debug(Marker marker, String format, Object... arguments) { + debug(MessageFormat.format(format, arguments)); + } + + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) { + debug(MessageFormat.format(format, arg1, arg2)); + } + + @Override + public void debug(Marker marker, String msg, Throwable t) { + debug(msg, t); + } + + @Override + public void debug(String msg) { + events.add(new LogRecord(Level.DEBUG, msg)); + } + + @Override + public void debug(String format, Object arg) { + events.add(new LogRecord(Level.DEBUG, MessageFormat.format(format, arg))); + } + + @Override + public void debug(String format, Object... arguments) { + events.add(new LogRecord(Level.DEBUG, MessageFormat.format(format, arguments))); + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + events.add(new LogRecord(Level.DEBUG, MessageFormat.format(format, arg1, arg2))); + } + + @Override + public void debug(String msg, Throwable t) { + events.add(new LogRecord(Level.DEBUG, msg, t)); + } + + @Override + public void error(Marker marker, String msg) { + error(msg); + } + + @Override + public void error(Marker marker, String format, Object arg) { + error(format, arg); + } + + @Override + public void error(Marker marker, String format, Object... arguments) { + error(format, arguments); + } + + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) { + error(format, arg1, arg2); + } + + @Override + public void error(Marker marker, String msg, Throwable t) { + events.add(new LogRecord(Level.ERROR, msg, t)); + } + + @Override + public void error(String msg) { + events.add(new LogRecord(Level.ERROR, msg)); + } + + @Override + public void error(String format, Object arg) { + events.add(new LogRecord(Level.ERROR, MessageFormat.format(format, arg))); + } + + @Override + public void error(String format, Object... arguments) { + events.add(new LogRecord(Level.ERROR, MessageFormat.format(format, arguments))); + } + + @Override + public void error(String format, Object arg1, Object arg2) { + events.add(new LogRecord(Level.ERROR, MessageFormat.format(format, arg1, arg2))); + } + + @Override + public void error(String msg, Throwable t) { + events.add(new LogRecord(Level.ERROR, msg, t)); + } + + @Override + public String getName() { + return null; + } + + @Override + public void info(Marker marker, String msg) { + info(msg); + } + + @Override + public void info(Marker marker, String format, Object arg) { + info(format, arg); + } + + @Override + public void info(Marker marker, String format, Object... arguments) { + info(format, arguments); + } + + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) { + info(format, arg1, arg2); + } + + @Override + public void info(Marker marker, String msg, Throwable t) { + events.add(new LogRecord(Level.INFO, msg, t)); + } + + @Override + public void info(String msg) { + events.add(new LogRecord(Level.INFO, msg)); + } + + @Override + public void info(String format, Object arg) { + events.add(new LogRecord(Level.INFO, MessageFormat.format(format, arg))); + } + + @Override + public void info(String format, Object... arguments) { + events.add(new LogRecord(Level.INFO, MessageFormat.format(format, arguments))); + } + + @Override + public void info(String format, Object arg1, Object arg2) { + events.add(new LogRecord(Level.INFO, MessageFormat.format(format, arg1, arg2))); + } + + @Override + public void info(String msg, Throwable t) { + events.add(new LogRecord(Level.INFO, msg, t)); + } + + @Override + public boolean isDebugEnabled() { + return true; + } + + @Override + public boolean isDebugEnabled(Marker marker) { + return true; + } + + @Override + public boolean isErrorEnabled() { + return true; + } + + @Override + public boolean isErrorEnabled(Marker marker) { + return true; + } + + @Override + public boolean isInfoEnabled() { + return true; + } + + @Override + public boolean isInfoEnabled(Marker marker) { + return true; + } + + @Override + public boolean isTraceEnabled() { + return true; + } + + @Override + public boolean isTraceEnabled(Marker marker) { + return true; + } + + @Override + public boolean isWarnEnabled() { + return true; + } + + @Override + public boolean isWarnEnabled(Marker marker) { + return true; + } + + @Override + public void trace(Marker marker, String msg) { + trace(msg); + } + + @Override + public void trace(Marker marker, String format, Object arg) { + trace(format, arg); + } + + @Override + public void trace(Marker marker, String format, Object... argArray) { + trace(format, argArray); + } + + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) { + trace(format, arg1, arg2); + } + + @Override + public void trace(Marker marker, String msg, Throwable t) { + trace(msg, t); + } + + @Override + public void trace(String msg) { + events.add(new LogRecord(Level.TRACE, msg)); + } + + @Override + public void trace(String format, Object arg) { + events.add(new LogRecord(Level.TRACE, MessageFormat.format(format, arg))); + } + + @Override + public void trace(String format, Object... arguments) { + events.add(new LogRecord(Level.TRACE, MessageFormat.format(format, arguments))); + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + events.add(new LogRecord(Level.TRACE, MessageFormat.format(format, arg1, arg2))); + } + + @Override + public void trace(String msg, Throwable t) { + events.add(new LogRecord(Level.TRACE, msg, t)); + } + + @Override + public void warn(Marker marker, String msg) { + warn(msg); + } + + @Override + public void warn(Marker marker, String format, Object arg) { + warn(format, arg); + } + + @Override + public void warn(Marker marker, String format, Object... arguments) { + warn(format, arguments); + } + + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) { + warn(format, arg1, arg2); + } + + @Override + public void warn(Marker marker, String msg, Throwable t) { + events.add(new LogRecord(Level.WARN, msg, t)); + } + + @Override + public void warn(String msg) { + events.add(new LogRecord(Level.WARN, msg)); + } + + @Override + public void warn(String format, Object arg) { + events.add(new LogRecord(Level.WARN, MessageFormat.format(format, arg))); + } + + @Override + public void warn(String format, Object... arguments) { + events.add(new LogRecord(Level.WARN, MessageFormat.format(format, arguments))); + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + events.add(new LogRecord(Level.WARN, MessageFormat.format(format, arg1, arg2))); + } + + @Override + public void warn(String msg, Throwable t) { + events.add(new LogRecord(Level.WARN, msg, t)); + } +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties new file mode 100644 index 000000000..996730239 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties @@ -0,0 +1,113 @@ +### +# ============LICENSE_START======================================================= +# openECOMP : APP-C +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights +# reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +# +# 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.openecomp.appc.bootstrap.file=appc.properties +org.openecomp.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +appc.application.name=APPC + +# +# Define the message resource bundle name to be loaded +org.openecomp.appc.resources=org/openecomp/appc/i18n/MessageResources +# +# The name of the adapter. +org.openecomp.appc.provider.adaptor.name=org.openecomp.appc.appc_provider_adapter +# +# Set up the logging environment +# +org.openecomp.appc.logging.file=org/openecomp/appc/logback.xml +org.openecomp.appc.logging.path=${user.home};etc;../etc +org.openecomp.appc.logger=org.openecomp.appc +org.openecomp.appc.security.logger=org.openecomp.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.openecomp.appc.provider.min.pool=1 +org.openecomp.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.openecomp.appc.provider.retry.delay = 30 +org.openecomp.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.openecomp.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.openecomp.appc.openstack.poll.interval=20 +# +# The connection information to connect to the provider we are using. These properties +# are "structured" properties, in that the name is a compound name, where the nodes +# of the name can be ordered (1, 2, 3, ...). All of the properties with the same ordinal +# position are defining the same entity. For example, provider1.type and provider1.name +# are defining the same provider, whereas provider2.name and provider2.type are defining +# the values for a different provider. Any number of providers can be defined in this +# way. +# + + +### ### +### Properties commented out below provided in appc.properties ### +### ### + +# Don't change these 2 right now since they are hard coded in the DG +#provider1.type=appc +#provider1.name=appc + +#These you can change +#provider1.identity=appc +#provider1.tenant1.name=appc +#provider1.tenant1.userid=appc +#provider1.tenant1.password=appc + +# After a change to the provider make sure to recheck these values with an api call to provider1.identity/tokens +test.expected-regions=1 +test.expected-endpoints=1 + +#Your OpenStack IP +#test.ip=192.168.1.2 +# Your OpenStack Platform's Keystone Port (default is 5000) +#test.port=5000 +#test.tenantid=abcde12345fghijk6789lmnopq123rst +#test.vmid=abc12345-1234-5678-890a-abcdefg12345 +# Port 8774 below is default port for OpenStack's Nova API Service +#test.url=http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345 + |