From 161df8a94bb3b0c34ed16fd4fdba078bd1eeef9a Mon Sep 17 00:00:00 2001 From: Patrick Brady Date: Wed, 13 Dec 2017 11:14:21 -0800 Subject: Second part of onap rename This is the second commit of the rename. The folder structure is renamed for appc-adapters and appc-config in this commit. Change-Id: Iaa2b8c937ff1ca1b5d1178128961fb115ee65d9b Signed-off-by: Patrick Brady Issue-ID: APPC-13 --- .../appc/adapter/ansible/AnsibleActivator.java | 126 +++ .../onap/appc/adapter/ansible/AnsibleAdapter.java | 60 ++ .../adapter/ansible/impl/AnsibleAdapterImpl.java | 501 ++++++++++++ .../adapter/ansible/impl/ConnectionBuilder.java | 224 +++++ .../ansible/model/AnsibleMessageParser.java | 364 +++++++++ .../appc/adapter/ansible/model/AnsibleResult.java | 87 ++ .../adapter/ansible/model/AnsibleResultCodes.java | 122 +++ .../ansible/model/AnsibleServerEmulator.java | 148 ++++ .../appc/adapter/ansible/AnsibleActivator.java | 126 --- .../appc/adapter/ansible/AnsibleAdapter.java | 60 -- .../adapter/ansible/impl/AnsibleAdapterImpl.java | 501 ------------ .../adapter/ansible/impl/ConnectionBuilder.java | 224 ----- .../ansible/model/AnsibleMessageParser.java | 364 --------- .../appc/adapter/ansible/model/AnsibleResult.java | 87 -- .../adapter/ansible/model/AnsibleResultCodes.java | 122 --- .../ansible/model/AnsibleServerEmulator.java | 148 ---- .../resources/org/onap/appc/default.properties | 48 ++ .../org/openecomp/appc/default.properties | 48 -- .../ansible/impl/TestAnsibleAdapterImpl.java | 137 ++++ .../java/org/onap/appc/test/ExecutorHarness.java | 182 +++++ .../java/org/onap/appc/test/InterceptLogger.java | 454 +++++++++++ .../ansible/impl/TestAnsibleAdapterImpl.java | 137 ---- .../org/openecomp/appc/test/ExecutorHarness.java | 182 ----- .../org/openecomp/appc/test/InterceptLogger.java | 454 ----------- .../resources/org/onap/appc/default.properties | 111 +++ .../org/openecomp/appc/default.properties | 111 --- .../org/onap/appc/adapter/chef/ChefActivator.java | 144 ++++ .../org/onap/appc/adapter/chef/ChefAdapter.java | 220 +++++ .../onap/appc/adapter/chef/chefapi/ApiMethod.java | 167 ++++ .../org/onap/appc/adapter/chef/chefapi/Delete.java | 36 + .../org/onap/appc/adapter/chef/chefapi/Get.java | 35 + .../org/onap/appc/adapter/chef/chefapi/Post.java | 46 ++ .../org/onap/appc/adapter/chef/chefapi/Put.java | 46 ++ .../adapter/chef/chefclient/ChefApiClient.java | 87 ++ .../onap/appc/adapter/chef/chefclient/Utils.java | 102 +++ .../appc/adapter/chef/impl/ChefAdapterImpl.java | 469 +++++++++++ .../appc/adapter/chef/impl/RequestContext.java | 252 ++++++ .../openecomp/appc/adapter/chef/ChefActivator.java | 144 ---- .../openecomp/appc/adapter/chef/ChefAdapter.java | 220 ----- .../appc/adapter/chef/chefapi/ApiMethod.java | 167 ---- .../appc/adapter/chef/chefapi/Delete.java | 36 - .../openecomp/appc/adapter/chef/chefapi/Get.java | 35 - .../openecomp/appc/adapter/chef/chefapi/Post.java | 46 -- .../openecomp/appc/adapter/chef/chefapi/Put.java | 46 -- .../adapter/chef/chefclient/ChefApiClient.java | 87 -- .../appc/adapter/chef/chefclient/Utils.java | 102 --- .../appc/adapter/chef/impl/ChefAdapterImpl.java | 469 ----------- .../appc/adapter/chef/impl/RequestContext.java | 252 ------ .../resources/org/onap/appc/default.properties | 96 +++ .../org/openecomp/appc/default.properties | 96 --- .../adapter/chef/chefclient/TestChefApiClient.java | 107 +++ .../adapter/chef/impl/TestChefAdapterImpl.java | 113 +++ .../java/org/onap/appc/test/ExecutorHarness.java | 182 +++++ .../java/org/onap/appc/test/InterceptLogger.java | 454 +++++++++++ .../adapter/chef/chefclient/TestChefApiClient.java | 107 --- .../adapter/chef/impl/TestChefAdapterImpl.java | 113 --- .../org/openecomp/appc/test/ExecutorHarness.java | 182 ----- .../org/openecomp/appc/test/InterceptLogger.java | 454 ----------- .../resources/org/onap/appc/default.properties | 111 +++ .../org/openecomp/appc/default.properties | 111 --- .../messaging/dmaap/AppcDmaapAdapterActivator.java | 106 +++ .../messaging/dmaap/http/CommonHttpClient.java | 108 +++ .../dmaap/http/HttpDmaapConsumerImpl.java | 167 ++++ .../dmaap/http/HttpDmaapProducerImpl.java | 138 ++++ .../messaging/dmaap/impl/DmaapConsumerImpl.java | 234 ++++++ .../messaging/dmaap/impl/DmaapProducerImpl.java | 223 +++++ .../adapter/messaging/dmaap/impl/DmaapUtil.java | 86 ++ .../messaging/dmaap/impl/EventSenderDmaapImpl.java | 178 ++++ .../messaging/dmaap/AppcDmaapAdapterActivator.java | 106 --- .../messaging/dmaap/http/CommonHttpClient.java | 108 --- .../dmaap/http/HttpDmaapConsumerImpl.java | 167 ---- .../dmaap/http/HttpDmaapProducerImpl.java | 138 ---- .../messaging/dmaap/impl/DmaapConsumerImpl.java | 234 ------ .../messaging/dmaap/impl/DmaapProducerImpl.java | 223 ----- .../adapter/messaging/dmaap/impl/DmaapUtil.java | 86 -- .../messaging/dmaap/impl/EventSenderDmaapImpl.java | 178 ---- .../resources/org/onap/appc/default.properties | 28 + .../org/openecomp/appc/default.properties | 28 - .../messaging/dmaap/SimpleExamplePublisher.java | 137 ++++ .../dmaap/TestAppcDmaapAdapterActivator.java | 50 ++ .../messaging/dmaap/TestDmaapConsuming.java | 87 ++ .../messaging/dmaap/TestDmaapEventSender.java | 172 ++++ .../messaging/dmaap/TestDmaapProducing.java | 83 ++ .../dmaap/impl/TestConsumerProducerImpl.java | 245 ++++++ .../messaging/dmaap/SimpleExamplePublisher.java | 137 ---- .../dmaap/TestAppcDmaapAdapterActivator.java | 50 -- .../messaging/dmaap/TestDmaapConsuming.java | 87 -- .../messaging/dmaap/TestDmaapEventSender.java | 172 ---- .../messaging/dmaap/TestDmaapProducing.java | 83 -- .../dmaap/impl/TestConsumerProducerImpl.java | 245 ------ .../resources/org/onap/appc/default.properties | 39 + .../org/openecomp/appc/default.properties | 39 - .../appc/adapter/message/CallableConsumer.java | 61 ++ .../org/onap/appc/adapter/message/Consumer.java | 73 ++ .../org/onap/appc/adapter/message/EventSender.java | 39 + .../org/onap/appc/adapter/message/Manager.java | 48 ++ .../adapter/message/MessageAdapterFactory.java | 42 + .../appc/adapter/message/MessageDestination.java | 29 + .../org/onap/appc/adapter/message/Producer.java | 54 ++ .../appc/adapter/message/event/EventHeader.java | 66 ++ .../appc/adapter/message/event/EventMessage.java | 100 +++ .../appc/adapter/message/event/EventStatus.java | 58 ++ .../appc/adapter/message/CallableConsumer.java | 61 -- .../openecomp/appc/adapter/message/Consumer.java | 73 -- .../appc/adapter/message/EventSender.java | 39 - .../openecomp/appc/adapter/message/Manager.java | 48 -- .../adapter/message/MessageAdapterFactory.java | 42 - .../appc/adapter/message/MessageDestination.java | 29 - .../openecomp/appc/adapter/message/Producer.java | 54 -- .../appc/adapter/message/event/EventHeader.java | 66 -- .../appc/adapter/message/event/EventMessage.java | 100 --- .../appc/adapter/message/event/EventStatus.java | 58 -- .../resources/org/onap/appc/default.properties | 26 + .../org/openecomp/appc/default.properties | 26 - .../DmaapMessageAdapterFactoryActivator.java | 47 ++ .../factory/DmaapMessageAdapterFactoryImpl.java | 58 ++ .../onap/appc/adapter/factory/MessageService.java | 59 ++ .../DmaapMessageAdapterFactoryActivator.java | 47 -- .../factory/DmaapMessageAdapterFactoryImpl.java | 58 -- .../appc/adapter/factory/MessageService.java | 59 -- .../resources/org/onap/appc/default.properties | 26 + .../org/openecomp/appc/default.properties | 26 - .../adapter/iaas/AppcProviderAdapterActivator.java | 147 ++++ .../onap/appc/adapter/iaas/ProviderAdapter.java | 288 +++++++ .../onap/appc/adapter/iaas/impl/IdentityURL.java | 146 ++++ .../adapter/iaas/impl/ProviderAdapterImpl.java | 359 ++++++++ .../onap/appc/adapter/iaas/impl/ProviderCache.java | 165 ++++ .../appc/adapter/iaas/impl/RequestContext.java | 249 ++++++ .../adapter/iaas/impl/RequestFailedException.java | 255 ++++++ .../appc/adapter/iaas/impl/ServiceCatalog.java | 310 +++++++ .../adapter/iaas/impl/ServiceCatalogFactory.java | 70 ++ .../appc/adapter/iaas/impl/ServiceCatalogV2.java | 380 +++++++++ .../appc/adapter/iaas/impl/ServiceCatalogV3.java | 402 +++++++++ .../onap/appc/adapter/iaas/impl/TenantCache.java | 382 +++++++++ .../org/onap/appc/adapter/iaas/impl/VMURL.java | 175 ++++ .../provider/operation/api/IProviderOperation.java | 74 ++ .../operation/api/ProviderOperationFactory.java | 122 +++ .../operation/common/constants/Constants.java | 61 ++ .../operation/common/constants/Property.java | 41 + .../provider/operation/common/enums/Operation.java | 96 +++ .../provider/operation/common/enums/Outcome.java | 41 + .../provider/operation/impl/CreateSnapshot.java | 233 ++++++ .../provider/operation/impl/EvacuateServer.java | 355 ++++++++ .../iaas/provider/operation/impl/LookupServer.java | 121 +++ .../provider/operation/impl/MigrateServer.java | 240 ++++++ .../provider/operation/impl/RebuildServer.java | 434 ++++++++++ .../provider/operation/impl/RestartServer.java | 275 +++++++ .../iaas/provider/operation/impl/RestoreStack.java | 151 ++++ .../provider/operation/impl/SnapshotStack.java | 193 +++++ .../iaas/provider/operation/impl/StartServer.java | 184 +++++ .../iaas/provider/operation/impl/StopServer.java | 202 +++++ .../provider/operation/impl/TerminateServer.java | 245 ++++++ .../provider/operation/impl/TerminateStack.java | 128 +++ .../provider/operation/impl/VmStatuschecker.java | 159 ++++ .../operation/impl/base/ProviderOperation.java | 453 +++++++++++ .../impl/base/ProviderServerOperation.java | 560 +++++++++++++ .../impl/base/ProviderStackOperation.java | 194 +++++ .../adapter/openstack/heat/SnapshotResource.java | 75 ++ .../appc/adapter/openstack/heat/StackResource.java | 53 ++ .../openstack/heat/model/CreateSnapshotParams.java | 64 ++ .../appc/adapter/openstack/heat/model/Data.java | 229 ++++++ .../adapter/openstack/heat/model/Environment.java | 87 ++ .../adapter/openstack/heat/model/Metadata.java | 45 + .../adapter/openstack/heat/model/Parameters.java | 45 + .../adapter/openstack/heat/model/Properties.java | 64 ++ .../adapter/openstack/heat/model/ResourceData.java | 64 ++ .../openstack/heat/model/ResourceRegistry.java | 66 ++ .../adapter/openstack/heat/model/Resources.java | 45 + .../adapter/openstack/heat/model/Resources_.java | 66 ++ .../adapter/openstack/heat/model/Resources__.java | 66 ++ .../adapter/openstack/heat/model/Snapshot.java | 166 ++++ .../openstack/heat/model/SnapshotDetails.java | 66 ++ .../heat/model/SnapshotRestoreResponse.java | 104 +++ .../adapter/openstack/heat/model/Template.java | 86 ++ .../appc/adapter/openstack/heat/model/Volume.java | 86 ++ .../appc/adapter/openstack/heat/model/Volume_.java | 187 +++++ .../org/onap/appc/adapter/utils/Constants.java | 34 + .../adapter/iaas/AppcProviderAdapterActivator.java | 147 ---- .../appc/adapter/iaas/ProviderAdapter.java | 288 ------- .../appc/adapter/iaas/impl/IdentityURL.java | 146 ---- .../adapter/iaas/impl/ProviderAdapterImpl.java | 359 -------- .../appc/adapter/iaas/impl/ProviderCache.java | 165 ---- .../appc/adapter/iaas/impl/RequestContext.java | 249 ------ .../adapter/iaas/impl/RequestFailedException.java | 255 ------ .../appc/adapter/iaas/impl/ServiceCatalog.java | 310 ------- .../adapter/iaas/impl/ServiceCatalogFactory.java | 70 -- .../appc/adapter/iaas/impl/ServiceCatalogV2.java | 380 --------- .../appc/adapter/iaas/impl/ServiceCatalogV3.java | 402 --------- .../appc/adapter/iaas/impl/TenantCache.java | 382 --------- .../openecomp/appc/adapter/iaas/impl/VMURL.java | 175 ---- .../provider/operation/api/IProviderOperation.java | 74 -- .../operation/api/ProviderOperationFactory.java | 122 --- .../operation/common/constants/Constants.java | 61 -- .../operation/common/constants/Property.java | 41 - .../provider/operation/common/enums/Operation.java | 96 --- .../provider/operation/common/enums/Outcome.java | 41 - .../provider/operation/impl/CreateSnapshot.java | 233 ------ .../provider/operation/impl/EvacuateServer.java | 355 -------- .../iaas/provider/operation/impl/LookupServer.java | 121 --- .../provider/operation/impl/MigrateServer.java | 240 ------ .../provider/operation/impl/RebuildServer.java | 434 ---------- .../provider/operation/impl/RestartServer.java | 275 ------- .../iaas/provider/operation/impl/RestoreStack.java | 151 ---- .../provider/operation/impl/SnapshotStack.java | 193 ----- .../iaas/provider/operation/impl/StartServer.java | 184 ----- .../iaas/provider/operation/impl/StopServer.java | 202 ----- .../provider/operation/impl/TerminateServer.java | 245 ------ .../provider/operation/impl/TerminateStack.java | 128 --- .../provider/operation/impl/VmStatuschecker.java | 159 ---- .../operation/impl/base/ProviderOperation.java | 453 ----------- .../impl/base/ProviderServerOperation.java | 560 ------------- .../impl/base/ProviderStackOperation.java | 194 ----- .../adapter/openstack/heat/SnapshotResource.java | 75 -- .../appc/adapter/openstack/heat/StackResource.java | 53 -- .../openstack/heat/model/CreateSnapshotParams.java | 64 -- .../appc/adapter/openstack/heat/model/Data.java | 229 ------ .../adapter/openstack/heat/model/Environment.java | 87 -- .../adapter/openstack/heat/model/Metadata.java | 45 - .../adapter/openstack/heat/model/Parameters.java | 45 - .../adapter/openstack/heat/model/Properties.java | 64 -- .../adapter/openstack/heat/model/ResourceData.java | 64 -- .../openstack/heat/model/ResourceRegistry.java | 66 -- .../adapter/openstack/heat/model/Resources.java | 45 - .../adapter/openstack/heat/model/Resources_.java | 66 -- .../adapter/openstack/heat/model/Resources__.java | 66 -- .../adapter/openstack/heat/model/Snapshot.java | 166 ---- .../openstack/heat/model/SnapshotDetails.java | 66 -- .../heat/model/SnapshotRestoreResponse.java | 104 --- .../adapter/openstack/heat/model/Template.java | 86 -- .../appc/adapter/openstack/heat/model/Volume.java | 86 -- .../appc/adapter/openstack/heat/model/Volume_.java | 187 ----- .../openecomp/appc/adapter/utils/Constants.java | 34 - .../resources/org/onap/appc/default.properties | 112 +++ .../org/openecomp/appc/default.properties | 112 --- .../appc/adapter/iaas/impl/TestIdentityUrl.java | 102 +++ .../adapter/iaas/impl/TestProviderAdapterImpl.java | 901 +++++++++++++++++++++ .../adapter/iaas/impl/TestProviderOperation.java | 162 ++++ .../appc/adapter/iaas/impl/TestRequestContext.java | 162 ++++ .../appc/adapter/iaas/impl/TestServiceCatalog.java | 105 +++ .../iaas/impl/TestServiceCatalogFactory.java | 89 ++ .../adapter/iaas/impl/TestServiceCatalogV2.java | 174 ++++ .../adapter/iaas/impl/TestServiceCatalogV3.java | 167 ++++ .../org/onap/appc/adapter/iaas/impl/TestVMURL.java | 130 +++ .../java/org/onap/appc/test/ExecutorHarness.java | 181 +++++ .../java/org/onap/appc/test/InterceptLogger.java | 449 ++++++++++ .../appc/adapter/iaas/impl/TestIdentityUrl.java | 102 --- .../adapter/iaas/impl/TestProviderAdapterImpl.java | 901 --------------------- .../adapter/iaas/impl/TestProviderOperation.java | 162 ---- .../appc/adapter/iaas/impl/TestRequestContext.java | 162 ---- .../appc/adapter/iaas/impl/TestServiceCatalog.java | 105 --- .../iaas/impl/TestServiceCatalogFactory.java | 89 -- .../adapter/iaas/impl/TestServiceCatalogV2.java | 174 ---- .../adapter/iaas/impl/TestServiceCatalogV3.java | 167 ---- .../appc/adapter/iaas/impl/TestVMURL.java | 130 --- .../org/openecomp/appc/test/ExecutorHarness.java | 181 ----- .../org/openecomp/appc/test/InterceptLogger.java | 449 ---------- .../resources/org/onap/appc/default.properties | 112 +++ .../org/openecomp/appc/default.properties | 112 --- .../netconf/AppcNetconfAdapterActivator.java | 139 ++++ .../appc/adapter/netconf/ConnectionDetails.java | 67 ++ .../netconf/MockOperationalStateValidatorImpl.java | 48 ++ .../onap/appc/adapter/netconf/NetconfClient.java | 64 ++ .../appc/adapter/netconf/NetconfClientFactory.java | 43 + .../adapter/netconf/NetconfClientRestconf.java | 68 ++ .../appc/adapter/netconf/NetconfClientType.java | 31 + .../adapter/netconf/NetconfConnectionDetails.java | 95 +++ .../adapter/netconf/NetconfDataAccessService.java | 85 ++ .../adapter/netconf/OperationalStateValidator.java | 35 + .../netconf/OperationalStateValidatorFactory.java | 55 ++ .../netconf/VNFOperationalStateValidatorImpl.java | 132 +++ .../org/onap/appc/adapter/netconf/VnfType.java | 58 ++ .../netconf/exception/DataAccessException.java | 47 ++ .../netconf/exception/NetconfDAOException.java | 47 ++ .../adapter/netconf/internal/NetconfAdapter.java | 132 +++ .../adapter/netconf/internal/NetconfAdapter2.java | 105 +++ .../netconf/internal/NetconfConstMessages.java | 56 ++ .../internal/NetconfDataAccessServiceImpl.java | 147 ++++ .../adapter/netconf/internal/NetconfMessage.java | 97 +++ .../onap/appc/adapter/netconf/jsch/JSchLogger.java | 63 ++ .../adapter/netconf/jsch/NetconfClientJsch.java | 170 ++++ .../odlconnector/NetconfClientRestconfImpl.java | 236 ++++++ .../onap/appc/adapter/netconf/util/Constants.java | 68 ++ .../netconf/AppcNetconfAdapterActivator.java | 139 ---- .../appc/adapter/netconf/ConnectionDetails.java | 67 -- .../netconf/MockOperationalStateValidatorImpl.java | 48 -- .../appc/adapter/netconf/NetconfClient.java | 64 -- .../appc/adapter/netconf/NetconfClientFactory.java | 43 - .../adapter/netconf/NetconfClientRestconf.java | 68 -- .../appc/adapter/netconf/NetconfClientType.java | 31 - .../adapter/netconf/NetconfConnectionDetails.java | 95 --- .../adapter/netconf/NetconfDataAccessService.java | 85 -- .../adapter/netconf/OperationalStateValidator.java | 35 - .../netconf/OperationalStateValidatorFactory.java | 55 -- .../netconf/VNFOperationalStateValidatorImpl.java | 132 --- .../openecomp/appc/adapter/netconf/VnfType.java | 58 -- .../netconf/exception/DataAccessException.java | 47 -- .../netconf/exception/NetconfDAOException.java | 47 -- .../adapter/netconf/internal/NetconfAdapter.java | 132 --- .../adapter/netconf/internal/NetconfAdapter2.java | 105 --- .../netconf/internal/NetconfConstMessages.java | 56 -- .../internal/NetconfDataAccessServiceImpl.java | 147 ---- .../adapter/netconf/internal/NetconfMessage.java | 97 --- .../appc/adapter/netconf/jsch/JSchLogger.java | 63 -- .../adapter/netconf/jsch/NetconfClientJsch.java | 170 ---- .../odlconnector/NetconfClientRestconfImpl.java | 236 ------ .../appc/adapter/netconf/util/Constants.java | 68 -- .../resources/org/onap/appc/default.properties | 44 + .../org/openecomp/appc/default.properties | 44 - .../netconf/internal/TestNetconfAdapter.java | 91 +++ .../adapter/netconf/jsch/TestGetRunningConfig.java | 63 ++ .../adapter/netconf/jsch/TestModifyConfig.java | 96 +++ .../adapter/netconf/jsch/TestModifyConfigMock.java | 96 +++ .../netconf/jsch/TestModifyConfigRouterMock.java | 94 +++ .../netconf/jsch/TestOperationalStates.java | 90 ++ .../netconf/internal/TestNetconfAdapter.java | 91 --- .../adapter/netconf/jsch/TestGetRunningConfig.java | 63 -- .../adapter/netconf/jsch/TestModifyConfig.java | 96 --- .../adapter/netconf/jsch/TestModifyConfigMock.java | 96 --- .../netconf/jsch/TestModifyConfigRouterMock.java | 94 --- .../netconf/jsch/TestOperationalStates.java | 90 -- .../org/onap/appc/adapter/rest/RequestFactory.java | 60 ++ .../org/onap/appc/adapter/rest/RestActivator.java | 145 ++++ .../org/onap/appc/adapter/rest/RestAdapter.java | 208 +++++ .../appc/adapter/rest/impl/RequestContext.java | 254 ++++++ .../adapter/rest/impl/RequestFailedException.java | 247 ++++++ .../appc/adapter/rest/impl/RestAdapterImpl.java | 244 ++++++ .../appc/adapter/rest/RequestFactory.java | 60 -- .../openecomp/appc/adapter/rest/RestActivator.java | 145 ---- .../openecomp/appc/adapter/rest/RestAdapter.java | 208 ----- .../appc/adapter/rest/impl/RequestContext.java | 254 ------ .../adapter/rest/impl/RequestFailedException.java | 247 ------ .../appc/adapter/rest/impl/RestAdapterImpl.java | 244 ------ .../resources/org/onap/appc/default.properties | 96 +++ .../org/openecomp/appc/default.properties | 96 --- .../adapter/rest/impl/TestRestAdapterImpl.java | 140 ++++ .../java/org/onap/appc/test/ExecutorHarness.java | 183 +++++ .../java/org/onap/appc/test/InterceptLogger.java | 455 +++++++++++ .../adapter/rest/impl/TestRestAdapterImpl.java | 140 ---- .../org/openecomp/appc/test/ExecutorHarness.java | 183 ----- .../org/openecomp/appc/test/InterceptLogger.java | 455 ----------- .../resources/org/onap/appc/default.properties | 116 +++ .../org/openecomp/appc/default.properties | 116 --- .../restHealthcheck/RestHealthcheckActivator.java | 116 +++ .../restHealthcheck/RestHealthcheckAdapter.java | 51 ++ .../restHealthcheck/impl/RequestContext.java | 249 ++++++ .../impl/RequestFailedException.java | 244 ++++++ .../impl/RestHealthcheckAdapterImpl.java | 311 +++++++ .../restHealthcheck/RestHealthcheckActivator.java | 116 --- .../restHealthcheck/RestHealthcheckAdapter.java | 51 -- .../restHealthcheck/impl/RequestContext.java | 249 ------ .../impl/RequestFailedException.java | 244 ------ .../impl/RestHealthcheckAdapterImpl.java | 311 ------- .../resources/org/onap/appc/default.properties | 79 ++ .../org/openecomp/appc/default.properties | 79 -- .../impl/TestRestHealthcheckAdapterImpl.java | 119 +++ .../java/org/onap/appc/test/ExecutorHarness.java | 183 +++++ .../java/org/onap/appc/test/InterceptLogger.java | 455 +++++++++++ .../impl/TestRestHealthcheckAdapterImpl.java | 119 --- .../org/openecomp/appc/test/ExecutorHarness.java | 183 ----- .../org/openecomp/appc/test/InterceptLogger.java | 455 ----------- .../resources/org/onap/appc/default.properties | 98 +++ .../org/openecomp/appc/default.properties | 98 --- .../java/org/onap/appc/adapter/ssh/Constants.java | 120 +++ .../java/org/onap/appc/adapter/ssh/SshAdapter.java | 42 + .../org/onap/appc/adapter/ssh/SshConnection.java | 75 ++ .../appc/adapter/ssh/SshConnectionDetails.java | 75 ++ .../appc/adapter/ssh/SshDataAccessException.java | 48 ++ .../appc/adapter/ssh/SshDataAccessService.java | 61 ++ .../org/onap/appc/adapter/ssh/SshException.java | 49 ++ .../org/openecomp/appc/adapter/ssh/Constants.java | 120 --- .../org/openecomp/appc/adapter/ssh/SshAdapter.java | 42 - .../openecomp/appc/adapter/ssh/SshConnection.java | 75 -- .../appc/adapter/ssh/SshConnectionDetails.java | 75 -- .../appc/adapter/ssh/SshDataAccessException.java | 48 -- .../appc/adapter/ssh/SshDataAccessService.java | 61 -- .../openecomp/appc/adapter/ssh/SshException.java | 49 -- .../onap/appc/adapter/ssh/sshd/SshAdapterSshd.java | 36 + .../appc/adapter/ssh/sshd/SshConnectionSshd.java | 236 ++++++ .../adapter/ssh/sshd/SshdDataAccessService.java | 106 +++ .../appc/adapter/ssh/sshd/SshAdapterSshd.java | 36 - .../appc/adapter/ssh/sshd/SshConnectionSshd.java | 236 ------ .../adapter/ssh/sshd/SshdDataAccessService.java | 106 --- .../appc/adapter/ssh/sshd/SshAdapterSample.java | 59 ++ .../onap/appc/adapter/ssh/sshd/SshAdapterTest.java | 250 ++++++ .../appc/adapter/ssh/sshd/SshAdapterSample.java | 59 -- .../appc/adapter/ssh/sshd/SshAdapterTest.java | 250 ------ .../org/onap/appc/adapter/ssh/SshAdapterMock.java | 75 ++ .../onap/appc/adapter/ssh/SshConnectionMock.java | 163 ++++ .../openecomp/appc/adapter/ssh/SshAdapterMock.java | 75 -- .../appc/adapter/ssh/SshConnectionMock.java | 163 ---- 390 files changed, 28642 insertions(+), 28642 deletions(-) create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/AnsibleActivator.java create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/AnsibleAdapter.java create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/impl/AnsibleAdapterImpl.java create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/impl/ConnectionBuilder.java create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleMessageParser.java create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResult.java create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResultCodes.java create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleServerEmulator.java delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/AnsibleActivator.java delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/AnsibleAdapter.java delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/impl/AnsibleAdapterImpl.java delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/impl/ConnectionBuilder.java delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleMessageParser.java delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleResult.java delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleResultCodes.java delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleServerEmulator.java create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/adapter/ansible/impl/TestAnsibleAdapterImpl.java create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/openecomp/appc/adapter/ansible/impl/TestAnsibleAdapterImpl.java delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java create mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/ChefActivator.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/ChefAdapter.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/ApiMethod.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Delete.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Get.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Post.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Put.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefclient/ChefApiClient.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefclient/Utils.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/impl/ChefAdapterImpl.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/impl/RequestContext.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefActivator.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefAdapter.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/ApiMethod.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Delete.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Get.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Post.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Put.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/ChefApiClient.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/Utils.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/ChefAdapterImpl.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/RequestContext.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/chefclient/TestChefApiClient.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/impl/TestChefAdapterImpl.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/adapter/chef/chefclient/TestChefApiClient.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/adapter/chef/impl/TestChefAdapterImpl.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java create mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/AppcDmaapAdapterActivator.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/http/CommonHttpClient.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/http/HttpDmaapConsumerImpl.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/http/HttpDmaapProducerImpl.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/DmaapConsumerImpl.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/DmaapProducerImpl.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/DmaapUtil.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/EventSenderDmaapImpl.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/AppcDmaapAdapterActivator.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/CommonHttpClient.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/HttpDmaapConsumerImpl.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/HttpDmaapProducerImpl.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/DmaapConsumerImpl.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/DmaapProducerImpl.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/DmaapUtil.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/EventSenderDmaapImpl.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/SimpleExamplePublisher.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestAppcDmaapAdapterActivator.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestDmaapConsuming.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestDmaapEventSender.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestDmaapProducing.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/impl/TestConsumerProducerImpl.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/SimpleExamplePublisher.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestAppcDmaapAdapterActivator.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestDmaapConsuming.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestDmaapEventSender.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestDmaapProducing.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/impl/TestConsumerProducerImpl.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/CallableConsumer.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/Consumer.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/EventSender.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/Manager.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/MessageAdapterFactory.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/MessageDestination.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/Producer.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/event/EventHeader.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/event/EventMessage.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/event/EventStatus.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/CallableConsumer.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/Consumer.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/EventSender.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/Manager.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/MessageAdapterFactory.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/MessageDestination.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/Producer.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/event/EventHeader.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/event/EventMessage.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/event/EventStatus.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/onap/appc/adapter/factory/DmaapMessageAdapterFactoryActivator.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/onap/appc/adapter/factory/DmaapMessageAdapterFactoryImpl.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/onap/appc/adapter/factory/MessageService.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/DmaapMessageAdapterFactoryActivator.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/DmaapMessageAdapterFactoryImpl.java delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/MessageService.java create mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/AppcProviderAdapterActivator.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/ProviderAdapter.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/IdentityURL.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderAdapterImpl.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderCache.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/RequestContext.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/RequestFailedException.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalog.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogFactory.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV2.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV3.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/TenantCache.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/VMURL.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/api/IProviderOperation.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/api/ProviderOperationFactory.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/constants/Constants.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/constants/Property.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/enums/Operation.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/enums/Outcome.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/LookupServer.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/MigrateServer.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RebuildServer.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RestartServer.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RestoreStack.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/StartServer.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/StopServer.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/TerminateServer.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/TerminateStack.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/VmStatuschecker.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/base/ProviderOperation.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/base/ProviderServerOperation.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/base/ProviderStackOperation.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/SnapshotResource.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/StackResource.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/CreateSnapshotParams.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Data.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Environment.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Metadata.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Parameters.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Properties.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/ResourceData.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/ResourceRegistry.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Resources.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Resources_.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Resources__.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Snapshot.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/SnapshotDetails.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/SnapshotRestoreResponse.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Template.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Volume.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Volume_.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/utils/Constants.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/AppcProviderAdapterActivator.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/ProviderAdapter.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/IdentityURL.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ProviderAdapterImpl.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ProviderCache.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/RequestContext.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/RequestFailedException.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalog.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogFactory.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogV2.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogV3.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/TenantCache.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/VMURL.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/api/IProviderOperation.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/api/ProviderOperationFactory.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/constants/Constants.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/constants/Property.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/enums/Operation.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/enums/Outcome.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/LookupServer.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/MigrateServer.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RebuildServer.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestartServer.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestoreStack.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StartServer.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StopServer.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateServer.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateStack.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/VmStatuschecker.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderOperation.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderServerOperation.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderStackOperation.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/SnapshotResource.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/StackResource.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/CreateSnapshotParams.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Data.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Environment.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Metadata.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Parameters.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Properties.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/ResourceData.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/ResourceRegistry.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Resources.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Resources_.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Resources__.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Snapshot.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/SnapshotDetails.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/SnapshotRestoreResponse.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Template.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Volume.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Volume_.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/utils/Constants.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestIdentityUrl.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderAdapterImpl.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderOperation.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestRequestContext.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalog.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogFactory.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV2.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV3.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestVMURL.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestIdentityUrl.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestProviderAdapterImpl.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestProviderOperation.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestRequestContext.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalog.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalogFactory.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalogV2.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalogV3.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestVMURL.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/AppcNetconfAdapterActivator.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/ConnectionDetails.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/MockOperationalStateValidatorImpl.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClient.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClientFactory.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClientRestconf.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClientType.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfConnectionDetails.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfDataAccessService.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/OperationalStateValidator.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/OperationalStateValidatorFactory.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/VNFOperationalStateValidatorImpl.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/VnfType.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/exception/DataAccessException.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/exception/NetconfDAOException.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfAdapter.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfAdapter2.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfConstMessages.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfDataAccessServiceImpl.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfMessage.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/jsch/JSchLogger.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/jsch/NetconfClientJsch.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/odlconnector/NetconfClientRestconfImpl.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/util/Constants.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/AppcNetconfAdapterActivator.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/ConnectionDetails.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/MockOperationalStateValidatorImpl.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClient.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClientFactory.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClientRestconf.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClientType.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfConnectionDetails.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfDataAccessService.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/OperationalStateValidator.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/OperationalStateValidatorFactory.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/VNFOperationalStateValidatorImpl.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/VnfType.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/exception/DataAccessException.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/exception/NetconfDAOException.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfAdapter.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfAdapter2.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfConstMessages.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfDataAccessServiceImpl.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfMessage.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/jsch/JSchLogger.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/jsch/NetconfClientJsch.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/odlconnector/NetconfClientRestconfImpl.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/util/Constants.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/internal/TestNetconfAdapter.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestGetRunningConfig.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestModifyConfig.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestModifyConfigMock.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestModifyConfigRouterMock.java create mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestOperationalStates.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/internal/TestNetconfAdapter.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestGetRunningConfig.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestModifyConfig.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestModifyConfigMock.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestModifyConfigRouterMock.java delete mode 100644 appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestOperationalStates.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RequestFactory.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestActivator.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestAdapter.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestContext.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestFailedException.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RestAdapterImpl.java delete mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RequestFactory.java delete mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RestActivator.java delete mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RestAdapter.java delete mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RequestContext.java delete mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RequestFailedException.java delete mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RestAdapterImpl.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/onap/appc/adapter/rest/impl/TestRestAdapterImpl.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java delete mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/adapter/rest/impl/TestRestAdapterImpl.java delete mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java delete mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/RestHealthcheckActivator.java create mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/RestHealthcheckAdapter.java create mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/impl/RequestContext.java create mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/impl/RequestFailedException.java create mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/impl/RestHealthcheckAdapterImpl.java delete mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/RestHealthcheckActivator.java delete mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/RestHealthcheckAdapter.java delete mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/impl/RequestContext.java delete mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/impl/RequestFailedException.java delete mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/impl/RestHealthcheckAdapterImpl.java create mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/onap/appc/adapter/restHealthcheck/impl/TestRestHealthcheckAdapterImpl.java create mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java create mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java delete mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/adapter/restHealthcheck/impl/TestRestHealthcheckAdapterImpl.java delete mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java delete mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java create mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/Constants.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshAdapter.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshConnection.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshConnectionDetails.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshDataAccessException.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshDataAccessService.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshException.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/Constants.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshAdapter.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshConnection.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshConnectionDetails.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshDataAccessException.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshDataAccessService.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshException.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/onap/appc/adapter/ssh/sshd/SshAdapterSshd.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/onap/appc/adapter/ssh/sshd/SshConnectionSshd.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/onap/appc/adapter/ssh/sshd/SshdDataAccessService.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/openecomp/appc/adapter/ssh/sshd/SshAdapterSshd.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/openecomp/appc/adapter/ssh/sshd/SshConnectionSshd.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/openecomp/appc/adapter/ssh/sshd/SshdDataAccessService.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/onap/appc/adapter/ssh/sshd/SshAdapterSample.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/onap/appc/adapter/ssh/sshd/SshAdapterTest.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/openecomp/appc/adapter/ssh/sshd/SshAdapterSample.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/openecomp/appc/adapter/ssh/sshd/SshAdapterTest.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/onap/appc/adapter/ssh/SshAdapterMock.java create mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/onap/appc/adapter/ssh/SshConnectionMock.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/openecomp/appc/adapter/ssh/SshAdapterMock.java delete mode 100644 appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/openecomp/appc/adapter/ssh/SshConnectionMock.java (limited to 'appc-adapters') diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/AnsibleActivator.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/AnsibleActivator.java new file mode 100644 index 000000000..d76cd50f1 --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/AnsibleActivator.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ansible; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.ansible.impl.AnsibleAdapterImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.i18n.Msg; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** + * This activator is used to initialize and terminate an instance of AnsibleAdapter class + */ +public class AnsibleActivator implements BundleActivator { + + /** + * The bundle registration + */ + private ServiceRegistration registration = null; + + /** + * The reference to the actual implementation object that implements the services + */ + private AnsibleAdapter adapter; + + /** + * The logger to be used + */ + private final EELFLogger logger = EELFManager.getInstance().getLogger(AnsibleActivator.class); + + /** + * The configuration object used to configure this bundle + */ + private final Configuration configuration = ConfigurationFactory.getConfiguration(); + + /** + * 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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @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()); + String appName = "APPC: "; + logger.info(Msg.COMPONENT_INITIALIZING, appName, "Ansible Adapter"); + adapter = new AnsibleAdapterImpl(); + + if (registration == null) { + logger.info(Msg.REGISTERING_SERVICE, appName, adapter.getAdapterName(), + AnsibleAdapter.class.getSimpleName()); + registration = context.registerService(AnsibleAdapter.class, adapter, null); + } + + logger.info(Msg.COMPONENT_INITIALIZED, appName, "Ansible 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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @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, "Ansible adapter"); + logger.info(Msg.UNREGISTERING_SERVICE, appName, adapter.getAdapterName()); + registration.unregister(); + registration = null; + logger.info(Msg.COMPONENT_TERMINATED, appName, "Ansible adapter"); + } + } + + public String getName() { + return "APPC Ansible Adapter"; + } +} diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/AnsibleAdapter.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/AnsibleAdapter.java new file mode 100644 index 000000000..7bff184bc --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/AnsibleAdapter.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ansible; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +/** + * This interface defines the operations that the Ansible adapter exposes. + * + */ +public interface AnsibleAdapter extends SvcLogicJavaPlugin { + + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + */ + String getAdapterName(); + + + /* Method to post request for execution of Playbook */ + void reqExec(Map params, SvcLogicContext ctx) throws SvcLogicException; + + /* Method to get result of a playbook execution request */ + void reqExecResult(Map params, SvcLogicContext ctx) throws SvcLogicException; + + + /* Method to get log of a playbook execution request */ + void reqExecLog(Map params, SvcLogicContext ctx) throws SvcLogicException; + + +} diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/impl/AnsibleAdapterImpl.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/impl/AnsibleAdapterImpl.java new file mode 100644 index 000000000..0b426bb26 --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/impl/AnsibleAdapterImpl.java @@ -0,0 +1,501 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ansible.impl; + +import java.util.Map; +import java.util.Properties; +import java.lang.*; + + +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + + + +import org.json.JSONObject; +import org.json.JSONArray; +import org.json.JSONException; + + + +import org.onap.appc.adapter.ansible.AnsibleAdapter; + +import org.onap.appc.adapter.ansible.model.AnsibleResult; +import org.onap.appc.adapter.ansible.model.AnsibleMessageParser; +import org.onap.appc.adapter.ansible.model.AnsibleResultCodes; +import org.onap.appc.adapter.ansible.model.AnsibleServerEmulator; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import static com.att.eelf.configuration.Configuration.*; + + +/** + * This class implements the {@link AnsibleAdapter} interface. This interface + * defines the behaviors that our service provides. + * + */ +public class AnsibleAdapterImpl implements AnsibleAdapter { + + /** + * The constant used to define the adapter name in the mapped diagnostic + * context + */ + + + @SuppressWarnings("nls") + public static final String MDC_ADAPTER = "Ansible 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"; + + /** + Adapter Name + **/ + private static final String ADAPTER_NAME = "Ansible Adapter"; + + + /** + * The logger to be used + */ + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AnsibleAdapterImpl.class); + + /** + * A reference to the adapter configuration object. + */ + private Configuration configuration;; + + /** can Specify a X509 certificate file for use if required ... + Must be initialized with setCertFile + **/ + private String certFile = ""; + + + /** + * Connection object + **/ + ConnectionBuilder http_client ; + + /** + * Ansible API Message Handlers + **/ + private AnsibleMessageParser messageProcessor; + + /** + indicator whether in test mode + **/ + private boolean testMode = false; + + /** + server emulator object to be used if in test mode + **/ + private AnsibleServerEmulator testServer; + + /** + * This default constructor is used as a work around because the activator + * wasnt getting called + */ + public AnsibleAdapterImpl() { + initialize(); + } + + + /** + * @param props + * not used + */ + public AnsibleAdapterImpl(Properties props) { + initialize(); + } + + + + /** + Used for jUnit test and testing interface + **/ + public AnsibleAdapterImpl(boolean Mode){ + testMode = Mode; + testServer = new AnsibleServerEmulator(); + messageProcessor = new AnsibleMessageParser(); + } + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + * @see org.onap.appc.adapter.rest.AnsibleAdapter#getAdapterName() + */ + @Override + public String getAdapterName() { + return ADAPTER_NAME; + } + + + + /** + * @param rc + * Method posts info to Context memory in case of an error + * and throws a SvcLogicException causing SLI to register this as a failure + */ + @SuppressWarnings("static-method") + private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException { + + svcLogic.setStatus(OUTCOME_FAILURE); + svcLogic.setAttribute("org.onap.appc.adapter.ansible.result.code",Integer.toString(code)); + svcLogic.setAttribute("org.onap.appc.adapter.ansible.message",message); + + throw new SvcLogicException("Ansible Adapter Error = " + message ); + } + + + /** + * initialize the Ansible adapter based on default and over-ride configuration data + */ + private void initialize() { + + configuration = ConfigurationFactory.getConfiguration(); + Properties props = configuration.getProperties(); + + // Create the message processor instance + messageProcessor = new AnsibleMessageParser(); + + // Create the http client instance + // type of client is extracted from the property file parameter + // org.onap.appc.adapter.ansible.clientType + // It can be : + // 1. TRUST_ALL (trust all SSL certs). To be used ONLY in dev + // 2. TRUST_CERT (trust only those whose certificates have been stored in the trustStore file) + // 3. DEFAULT (trust only well known certificates). This is standard behaviour to which it will + // revert. To be used in PROD + + try{ + String clientType = props.getProperty("org.onap.appc.adapter.ansible.clientType"); + logger.info("Ansible http client type set to " + clientType); + + if (clientType.equals("TRUST_ALL")){ + logger.info("Creating http client to trust ALL ssl certificates. WARNING. This should be done only in dev environments"); + http_client = new ConnectionBuilder(1); + } + else if (clientType.equals("TRUST_CERT")){ + // set path to keystore file + String trustStoreFile = props.getProperty("org.onap.appc.adapter.ansible.trustStore"); + String key = props.getProperty("org.onap.appc.adapter.ansible.trustStore.trustPasswd"); + char [] trustStorePasswd = key.toCharArray(); + String trustStoreType = "JKS"; + logger.info("Creating http client with trustmanager from " + trustStoreFile); + http_client = new ConnectionBuilder(trustStoreFile, trustStorePasswd); + } + else{ + logger.info("Creating http client with default behaviour"); + http_client = new ConnectionBuilder(0); + } + } + catch (Exception e){ + logger.error("Error Initializing Ansible Adapter due to Unknown Exception: reason = " + e.getMessage()); + } + + logger.info("Intitialized Ansible Adapter"); + + } + + + /** set the certificate file if not a trusted/known CA **/ + private void setCertFile(String CertFile){ + this.certFile = CertFile; + } + + + + // Public Method to post request to execute playbook. Posts the following back + // to Svc context memory + // org.onap.appc.adapter.ansible.req.code : 100 if successful + // org.onap.appc.adapter.ansible.req.messge : any message + // org.onap.appc.adapter.ansible.req.Id : a unique uuid to reference the request + + public void reqExec(Map params, SvcLogicContext ctx) throws SvcLogicException { + + String PlaybookName = ""; + String payload = ""; + String AgentUrl = ""; + String User = ""; + String Password = ""; + String Id = ""; + + JSONObject JsonPayload; + + try{ + // create json object to send request + JsonPayload = messageProcessor.ReqMessage(params); + + AgentUrl = (String) JsonPayload.remove("AgentUrl"); + User = (String) JsonPayload.remove("User"); + Password = (String) JsonPayload.remove("Password"); + Id = (String)JsonPayload.getString("Id"); + payload = JsonPayload.toString(); + logger.info("Updated Payload = " + payload); + } + catch(APPCException e){ + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request for execution of playbook due to missing mandatory parameters. Reason = " + e.getMessage()); + } + catch(JSONException e){ + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request for execution of playbook due to invalid JSON block. Reason = " + e.getMessage()); + } + catch(NumberFormatException e){ + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request for execution of playbook due to invalid parameter values. Reason = " + e.getMessage()); + } + + + + int code = -1; + String message = ""; + + try{ + + // post the test request + //--------------------------------------- + logger.info("Posting request = " + payload + " to url = " + AgentUrl ); + AnsibleResult testresult = postExecRequest(AgentUrl, payload, User, Password); + + + // Process if HTTP was successfull + if(testresult.getStatusCode() == 200){ + testresult = messageProcessor.parsePostResponse(testresult.getStatusMessage()); + } + else{ + doFailure(ctx, testresult.getStatusCode(), "Error posting request. Reason = " + testresult.getStatusMessage()); + } + + + code = testresult.getStatusCode(); + message = testresult.getStatusMessage(); + + + // Check status of test request returned by Agent + //----------------------------------------------- + if (code == AnsibleResultCodes.PENDING.getValue()){ + logger.info(String.format("Submission of Test %s successful.", PlaybookName)); + // test request accepted. We are in asynchronous case + } + else{ + doFailure(ctx, code, "Request for execution of playbook rejected. Reason = " + message); + } + } + + catch(APPCException e){ + doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), "Exception encountered when posting request for execution of playbook. Reason = " + e.getMessage()); + } + + + ctx.setAttribute("org.onap.appc.adapter.ansible.result.code", Integer.toString(code)); + ctx.setAttribute("org.onap.appc.adapter.ansible.message", message ); + ctx.setAttribute("org.onap.appc.adapter.ansible.Id", Id); + + } + + + // Public method to query status of a specific request + // It blocks till the Ansible Server responds or the session times out + + public void reqExecResult(Map params, SvcLogicContext ctx) throws SvcLogicException { + + + // Get uri + String ReqUri = ""; + + try{ + ReqUri = messageProcessor.ReqUri_Result(params); + System.out.println("Got uri = " + ReqUri); + } + catch(APPCException e){ + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request to retreive result due to missing parameters. Reason = " + e.getMessage()); + return; + } + catch(NumberFormatException e){ + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request to retreive result due to invalid parameters value. Reason = " + e.getMessage()); + return; + } + + int code = -1; + String message = ""; + String results = ""; + + try{ + // Try to retreive the test results (modify the url for that) + AnsibleResult testresult = queryServer(ReqUri, params.get("User"), params.get("Password")); + code = testresult.getStatusCode(); + message = testresult.getStatusMessage(); + + if(code == 200){ + logger.info("Parsing response from Server = " + message); + // Valid HTTP. process the Ansible message + testresult = messageProcessor.parseGetResponse(message); + code = testresult.getStatusCode(); + message = testresult.getStatusMessage(); + results = testresult.getResults(); + + } + + logger.info("Request response = " + message); + + } + catch (APPCException e){ + doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), "Exception encountered retreiving result : " + e.getMessage()); + return; + } + + // We were able to get and process the results. Determine if playbook succeeded + + if (code == AnsibleResultCodes.FINAL_SUCCESS.getValue()){ + message = String.format("Ansible Request %s finished with Result = %s, Message = %s", params.get("Id"), OUTCOME_SUCCESS, message); + logger.info(message); + } + else { + logger.info(String.format("Ansible Request %s finished with Result %s, Message = %s", params.get("Id"), OUTCOME_FAILURE, message)); + ctx.setAttribute("org.onap.appc.adapter.ansible.results", results); + doFailure(ctx, code, message ); + return; + } + + + ctx.setAttribute("org.onap.appc.adapter.ansible.result.code", Integer.toString(400)); + ctx.setAttribute("org.onap.appc.adapter.ansible.message",message); + ctx.setAttribute("org.onap.appc.adapter.ansible.results", results); + ctx.setStatus(OUTCOME_SUCCESS); + } + + + // Public method to get logs from plyabook execution for a specifcic request + // It blocks till the Ansible Server responds or the session times out + // very similar to reqExecResult + // logs are returned in the DG context variable org.onap.appc.adapter.ansible.log + + public void reqExecLog(Map params, SvcLogicContext ctx) throws SvcLogicException{ + + + // Get uri + String ReqUri = ""; + try{ + ReqUri = messageProcessor.ReqUri_Log(params); + logger.info("Retreiving results from " + ReqUri); + } + catch(Exception e){ + doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), e.getMessage()); + } + + int code = -1; + String message = ""; + float Duration = -1; + + try{ + // Try to retreive the test results (modify the url for that) + AnsibleResult testresult = queryServer(ReqUri, params.get("User"), params.get("Password")); + code = testresult.getStatusCode(); + message = testresult.getStatusMessage(); + + logger.info("Request output = " + message); + + } + catch (Exception e){ + doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), "Exception encountered retreiving output : " + e.getMessage()); + } + + ctx.setAttribute("org.onap.appc.adapter.ansible.log",message); + ctx.setStatus(OUTCOME_SUCCESS); + } + + + + + + /** + * Method that posts the request + **/ + + private AnsibleResult postExecRequest(String AgentUrl, String Payload, String User, String Password) { + + String reqOutput = "UNKNOWN"; + int reqStatus = -1; + + AnsibleResult testresult; + + if (!testMode){ + http_client.setHttpContext(User, Password); + testresult = http_client.Post(AgentUrl, Payload); + } + else{ + testresult = testServer.Post(AgentUrl, Payload); + } + + return testresult; + } + + + /* + Method to query Ansible server + + */ + private AnsibleResult queryServer(String AgentUrl, String User, String Password) { + + String testOutput = "UNKNOWN"; + int testStatus = -1; + AnsibleResult testresult; + + logger.info("Querying url = " + AgentUrl); + + if (!testMode){ + testresult = http_client.Get(AgentUrl); + } + else{ + testresult = testServer.Get(AgentUrl); + } + + return testresult; + + } + + + +} diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/impl/ConnectionBuilder.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/impl/ConnectionBuilder.java new file mode 100644 index 000000000..e84a85a0c --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/impl/ConnectionBuilder.java @@ -0,0 +1,224 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ansible.impl; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.auth.AuthScope; +import org.apache.http.entity.StringEntity; + +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.cert.CertificateException; +import java.security.KeyManagementException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.NoSuchAlgorithmException; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLContext; + +import java.io.FileInputStream; +import java.io.IOException; + + +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContexts; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; + + +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.adapter.ansible.model.AnsibleResult; +import org.onap.appc.adapter.ansible.model.AnsibleResultCodes; + + +/** + * Returns custom http client + - based on options + - can create one with ssl using an X509 certificate that does NOT have a known CA + - create one which trusts ALL SSL certificates + - return default httpclient (which only trusts known CAs from default cacerts file for process) -- this is the default option + +**/ + + +public class ConnectionBuilder { + + + + private CloseableHttpClient http_client = null; + private HttpClientContext http_context = new HttpClientContext(); + + + + + // Various constructors depending on how we want to instantiate the http ConnectionBuilder instance + + + /** + * Constructor that initializes an http client based on certificate + **/ + public ConnectionBuilder(String CertFile) throws KeyStoreException, CertificateException, IOException, KeyManagementException, NoSuchAlgorithmException, APPCException{ + + + /* Point to the certificate */ + FileInputStream fs = new FileInputStream(CertFile); + + /* Generate a certificate from the X509 */ + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + X509Certificate cert = (X509Certificate)cf.generateCertificate(fs); + + /* Create a keystore object and load the certificate there */ + KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); + keystore.load(null, null); + keystore.setCertificateEntry("cacert", cert); + + + SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build(); + SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); + + http_client = HttpClients.custom().setSSLSocketFactory(factory).build(); + }; + + + /** + * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS file) + **/ + public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException, KeyManagementException, NoSuchAlgorithmException, CertificateException { + + + /* Load the specified trustStore */ + KeyStore keystore = KeyStore.getInstance("JKS"); + FileInputStream readStream = new FileInputStream(trustStoreFile); + keystore.load(readStream,trustStorePasswd); + + SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build(); + SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); + + http_client = HttpClients.custom().setSSLSocketFactory(factory).build(); + }; + + /** + * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1 + or Default if Mode == 0 + */ + public ConnectionBuilder(int Mode) throws SSLException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException{ + if (Mode == 1){ + SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); + SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); + + http_client = HttpClients.custom().setSSLSocketFactory(factory).build(); + } + + else{ + http_client = HttpClients.createDefault(); + } + + }; + + + // Use to create an http context with auth headers + public void setHttpContext(String User, String MyPassword){ + + // Are credential provided ? If so, set the context to be used + if (User != null && ! User.isEmpty() && MyPassword != null && ! MyPassword.isEmpty()){ + UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(User, MyPassword); + AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); + BasicCredentialsProvider credsprovider = new BasicCredentialsProvider(); + credsprovider.setCredentials(authscope, credentials); + http_context.setCredentialsProvider(credsprovider); + } + + + }; + + + // Method posts to the ansible server and writes out response to + // Ansible result object + public AnsibleResult Post(String AgentUrl, String Payload){ + + AnsibleResult result = new AnsibleResult(); + try{ + + HttpPost postObj = new HttpPost(AgentUrl); + StringEntity bodyParams = new StringEntity(Payload, "UTF-8"); + postObj.setEntity(bodyParams); + postObj.addHeader("Content-type", "application/json"); + + HttpResponse response = http_client.execute(postObj, http_context); + + HttpEntity entity = response.getEntity(); + String responseOutput = entity != null ? EntityUtils.toString(entity) : null; + int responseCode = response.getStatusLine().getStatusCode(); + result.setStatusCode(responseCode); + result.setStatusMessage(responseOutput); + } + + catch(IOException io){ + result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue()); + result.setStatusMessage(io.getMessage()); + } + + + + return result; + + } + + // Method gets information from an Ansible server and writes out response to + // Ansible result object + + public AnsibleResult Get(String AgentUrl){ + + AnsibleResult result = new AnsibleResult(); + + try{ + HttpGet getObj = new HttpGet(AgentUrl ); + HttpResponse response = http_client.execute(getObj, http_context); + + + HttpEntity entity = response.getEntity(); + String responseOutput = entity != null ? EntityUtils.toString(entity) : null; + int responseCode = response.getStatusLine().getStatusCode(); + result.setStatusCode(responseCode); + result.setStatusMessage(responseOutput); + + } + catch(IOException io){ + result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue()); + result.setStatusMessage(io.getMessage()); + } + + return result; + }; + +} diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleMessageParser.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleMessageParser.java new file mode 100644 index 000000000..6bebd73fe --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleMessageParser.java @@ -0,0 +1,364 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ansible.model; + +/** + * This module imples the APP-C/Ansible Server interface + * based on the REST API specifications + */ + +import java.lang.NumberFormatException ; +import java.util.*; +import com.google.common.base.Strings; + +import org.json.JSONObject; +import org.json.JSONArray; +import org.json.JSONException; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.adapter.ansible.model.AnsibleResult; + + +/** + * Class that validates and constructs requests sent/received from + * Ansible Server + * + */ +public class AnsibleMessageParser { + + + + + // Accepts a map of strings and + // a) validates if all parameters are appropriate (else, throws an exception) + // and b) if correct returns a JSON object with appropriate key-value + // pairs to send to the server. + public JSONObject ReqMessage(Map params) throws APPCException, NumberFormatException, JSONException{ + + // Mandatory parameters, that must be in the supplied information to the Ansible Adapter + // 1. URL to connect to + // 2. credentials for URL (assume username password for now) + // 3. Playbook name + String[] mandatoryTestParams = {"AgentUrl", "PlaybookName", "User", "Password"}; + + // Optional testService parameters that may be provided in the request + String[] optionalTestParams = {"EnvParameters", "NodeList", "LocalParameters", "Timeout", "Version", "FileParameters", "Action"}; + + JSONObject JsonPayload = new JSONObject(); + String payload = ""; + JSONObject paramsJson; + + + // Verify all the mandatory parameters are there + for (String key: mandatoryTestParams){ + if (! params.containsKey(key)){ + throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); + } + payload = params.get(key); + if (Strings.isNullOrEmpty(payload)){ + throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key % value is Null or Emtpy", key)); + } + + JsonPayload.put(key, payload); + } + + // Iterate through optional parameters + // If null or empty omit it + for (String key : optionalTestParams){ + if (params.containsKey(key)){ + payload = params.get(key); + if(!Strings.isNullOrEmpty(payload)){ + + // different cases require different treatment + switch (key){ + case "Timeout": + int Timeout = Integer.parseInt(payload); + if (Timeout < 0){ + throw new NumberFormatException(" : specified negative integer for timeout = " + payload); + } + JsonPayload.put(key, payload); + break; + + case "Version": + JsonPayload.put(key, payload); + break; + + case "LocalParameters": + paramsJson = new JSONObject(payload); + JsonPayload.put(key, paramsJson); + break; + + case "EnvParameters": + paramsJson = new JSONObject(payload); + JsonPayload.put(key, paramsJson); + break; + + case "NodeList": + JSONArray paramsArray = new JSONArray(payload); + JsonPayload.put(key, paramsArray); + break; + + case "FileParameters": + // Files may have strings with newlines. Escape them as appropriate + String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r"); + JSONObject fileParams = new JSONObject(formattedPayload); + JsonPayload.put(key, fileParams); + break; + + } + } + } + } + + + // Generate a unique uuid for the test + String ReqId = UUID.randomUUID().toString(); + JsonPayload.put("Id", ReqId); + + return JsonPayload; + + } + + + + // method that validates that the Map has enough information + // to query Ansible server for a result . If so, it + // returns the appropriate url, else an empty string + public String ReqUri_Result(Map params) throws APPCException, NumberFormatException{ + + // Mandatory parameters, that must be in the request + String[] mandatoryTestParams = {"AgentUrl", "Id", "User", "Password" }; + + // Verify all the mandatory parameters are there + String payload = ""; + String Uri = ""; + + for (String key: mandatoryTestParams){ + if (! params.containsKey(key)){ + throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); + } + + payload = params.get(key); + if (Strings.isNullOrEmpty(payload)){ + throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); + } + + } + + Uri = params.get("AgentUrl") + "?Id=" + params.get("Id") + "&Type=GetResult"; + + return Uri; + + } + + + + // method that validates that the Map has enough information + // to query Ansible server for logs. If so, it populates the appropriate + // returns the appropriate url, else an empty string + public String ReqUri_Output(Map params) throws APPCException, NumberFormatException{ + + + // Mandatory parameters, that must be in the request + String[] mandatoryTestParams = {"AgentUrl", "Id", "User", "Password" }; + + // Verify all the mandatory parameters are there + String payload = ""; + String Uri = ""; + + for (String key: mandatoryTestParams){ + if (! params.containsKey(key)){ + throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); + } + payload = params.get(key); + if (Strings.isNullOrEmpty(payload)){ + throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); + } + + } + + Uri = params.get("AgentUrl") + "?Id=" + params.get("Id") + "&Type=GetOutput"; + return Uri; + + } + + // method that validates that the Map has enough information + // to query Ansible server for logs. If so, it populates the appropriate + // returns the appropriate url, else an empty string + public String ReqUri_Log(Map params) throws APPCException, NumberFormatException{ + + + // Mandatory parameters, that must be in the request + String[] mandatoryTestParams = {"AgentUrl", "Id", "User", "Password" }; + + // Verify all the mandatory parameters are there + String payload = ""; + String Uri = ""; + + for (String key: mandatoryTestParams){ + if (! params.containsKey(key)){ + throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); + } + payload = params.get(key); + if (Strings.isNullOrEmpty(payload)){ + throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); + } + + } + + Uri = params.get("AgentUrl") + "?Id=" + params.get("Id") + "&Type=GetLog"; + return Uri; + + } + + + /** + This method parses response from the + Ansible Server when we do a post + and returns an AnsibleResult object + **/ + + public AnsibleResult parsePostResponse(String Input) throws APPCException{ + + AnsibleResult ansibleResult = new AnsibleResult(); + + try{ + //Jsonify it + JSONObject postResponse = new JSONObject(Input); + + // Mandatory keys required are StatusCode and StatusMessage + int Code = postResponse.getInt("StatusCode"); + String Message = postResponse.getString("StatusMessage"); + + + // Status code must must be either 100 (accepted) or 101 (rejected) + boolean valCode = AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.INITRESPONSE.getValue(), Code); + if(!valCode){ + throw new APPCException("Invalid InitResponse code = " + Code + " received. MUST be one of " + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.INITRESPONSE.getValue()) ); + } + + ansibleResult.setStatusCode(Code); + ansibleResult.setStatusMessage(Message); + + } + catch(JSONException e){ + ansibleResult = new AnsibleResult(600, "Error parsing response = " + Input + ". Error = " + e.getMessage(), ""); + } + + + return ansibleResult; + } + + + /** This method parses response from an Ansible server when we do a GET for a result + and returns an AnsibleResult object + **/ + public AnsibleResult parseGetResponse(String Input) throws APPCException { + + AnsibleResult ansibleResult = new AnsibleResult(); + int FinalCode = AnsibleResultCodes.FINAL_SUCCESS.getValue(); + + + try{ + + //Jsonify it + JSONObject postResponse = new JSONObject(Input); + + // Mandatory keys required are Status and Message + int Code = postResponse.getInt("StatusCode"); + String Message = postResponse.getString("StatusMessage"); + + // Status code must be valid + // Status code must must be either 100 (accepted) or 101 (rejected) + boolean valCode = AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.FINALRESPONSE.getValue(), Code); + + if(!valCode){ + throw new APPCException("Invalid FinalResponse code = " + Code + " received. MUST be one of " + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.FINALRESPONSE.getValue())); + } + + + ansibleResult.setStatusCode(Code); + ansibleResult.setStatusMessage(Message); + System.out.println("Received response with code = " + Integer.toString(Code) + " Message = " + Message); + + if(! postResponse.isNull("Results")){ + + // Results are available. process them + // Results is a dictionary of the form + // {host :{status:s, group:g, message:m, hostname:h}, ...} + System.out.println("Processing results in response"); + JSONObject results = postResponse.getJSONObject("Results"); + System.out.println("Get JSON dictionary from Results .."); + Iterator hosts = results.keys(); + System.out.println("Iterating through hosts"); + + while(hosts.hasNext()){ + String host = hosts.next(); + System.out.println("Processing host = " + host); + + try{ + JSONObject host_response = results.getJSONObject(host); + int subCode = host_response.getInt("StatusCode"); + String message = host_response.getString("StatusMessage"); + + System.out.println("Code = " + Integer.toString(subCode) + " Message = " + message); + + if(subCode != 200 || ! message.equals("SUCCESS")){ + FinalCode = AnsibleResultCodes.REQ_FAILURE.getValue(); + } + } + catch(JSONException e){ + ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue()); + ansibleResult.setStatusMessage(String.format("Error processing response message = %s from host %s", results.getString(host), host)); + break; + } + } + + ansibleResult.setStatusCode(FinalCode); + + // We return entire Results object as message + ansibleResult.setResults(results.toString()); + + } + else{ + ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue()); + ansibleResult.setStatusMessage("Results not found in GET for response"); + } + + + } + catch(JSONException e){ + ansibleResult = new AnsibleResult(AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error parsing response = " + Input + ". Error = " + e.getMessage(), ""); + } + + + return ansibleResult; + } + + + +}; + + + diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResult.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResult.java new file mode 100644 index 000000000..a4bbcbef8 --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResult.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ansible.model; + + +/* Simple class to store code and message returned by POST/GET to an Ansible Server */ +public class AnsibleResult{ + private int StatusCode; + private String StatusMessage; + private String Results; + + + public AnsibleResult(){ + StatusCode = -1; + StatusMessage = "UNKNOWN"; + Results = "UNKNOWN"; + + } + + // constructor + public AnsibleResult(int code, String message, String result){ + StatusCode = code; + StatusMessage = message; + Results = result; + } + + //************************************************* + // Various set methods + public void setStatusCode(int code){ + this.StatusCode = code; + } + + public void setStatusMessage(String message){ + this.StatusMessage = message; + } + + public void setResults(String results){ + this.Results = results; + } + + + void set(int code, String message, String results){ + this.StatusCode = code; + this.StatusMessage = message; + this.Results = results; + + } + + //********************************************* + // Various get methods + public int getStatusCode(){ + return this.StatusCode; + } + + public String getStatusMessage(){ + return this.StatusMessage; + } + + public String getResults(){ + return this.Results; + } + + +} + diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResultCodes.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResultCodes.java new file mode 100644 index 000000000..986ad3e6a --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResultCodes.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ansible.model; + + +import java.util.*; + +/** + * enum of the various codes that APP-C uses to resolve different + * status of response from Ansible Server + **/ + +public enum AnsibleResultCodes{ + + SUCCESS(400), + KEYSTORE_EXCEPTION(622), + CERTIFICATE_ERROR(610), + IO_EXCEPTION (611), + HOST_UNKNOWN(625), + USER_UNAUTHORIZED(613), + UNKNOWN_EXCEPTION(699), + SSL_EXCEPTION(697), + INVALID_PAYLOAD(698), + INVALID_RESPONSE(601), + PENDING(100), + REJECTED(101), + FINAL_SUCCESS(200), + REQ_FAILURE(401), + MESSAGE(1), + CODE(0), + INITRESPONSE(0), + FINALRESPONSE(1); + + private final Set InitCodes = new HashSet(Arrays.asList(100, 101)); + private final Set FinalCodes = new HashSet(Arrays.asList(200, 500)); + private final ArrayList>CodeSets = new ArrayList>(Arrays.asList(InitCodes, FinalCodes)); + + private final Set MessageSet = new HashSet(Arrays.asList("PENDING", "FINISHED", "TERMINATED")); + + private final int value; + + AnsibleResultCodes(int value){ + this.value = value; + }; + + + public int getValue(){ + return this.value; + } + + + public boolean checkValidCode(int Type, int Code){ + SetCodeSet = CodeSets.get(Type); + if (CodeSet.contains(Code)){ + return true; + } + else{ + return false; + } + } + + + public String getValidCodes(int Type){ + SetCodeSet = CodeSets.get(Type); + + Iterator iter = CodeSet.iterator(); + String ValidCodes = "[ "; + while(iter.hasNext()){ + ValidCodes = ValidCodes + iter.next().toString() + ","; + } + + ValidCodes = ValidCodes + "]"; + return ValidCodes; + } + + + public boolean checkValidMessage(String Message){ + if (MessageSet.contains(Message)){ + return true; + } + else{ + return false; + } + } + + + + public String getValidMessages(){ + Iterator iter = MessageSet.iterator(); + String ValidMessage = "[ "; + while(iter.hasNext()){ + ValidMessage = ValidMessage + iter.next() + ","; + } + + ValidMessage = ValidMessage + "]"; + return ValidMessage; + } + + +}; diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleServerEmulator.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleServerEmulator.java new file mode 100644 index 000000000..c430743ad --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleServerEmulator.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + + +/* Class to emulate responses from the Ansible Server that is compliant with the APP-C Ansible Server + Interface. Used for jUnit tests to verify code is working. In tests it can be used + as a replacement for methods from ConnectionBuilder class +*/ + +package org.onap.appc.adapter.ansible.model; + +import java.util.*; +import java.util.regex.Pattern; +import java.util.regex.Matcher; +import com.google.common.base.Strings; + +import org.json.JSONObject; +import org.json.JSONArray; +import org.json.JSONException; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.adapter.ansible.model.AnsibleResult; + +public class AnsibleServerEmulator { + + + private String playbookName = "test_playbook.yaml"; + private String TestId; + + /** + * Method that emulates the response from an Ansible Server + when presented with a request to execute a playbook + Returns an ansible object result. The response code is always the http code 200 (i.e connection successful) + payload is json string as would be sent back by Ansible Server + **/ + + public AnsibleResult Post(String AgentUrl, String payload){ + AnsibleResult result = new AnsibleResult() ; + + try{ + // Request must be a JSON object + + JSONObject message = new JSONObject(payload); + if (message.isNull("Id")){ + RejectRequest(result, "Must provide a valid Id"); + } + else if(message.isNull("PlaybookName")){ + RejectRequest(result, "Must provide a playbook Name"); + } + else if(!message.getString("PlaybookName").equals(playbookName)){ + RejectRequest(result, "Playbook " + message.getString("PlaybookName") + " not found in catalog"); + } + else{ + AcceptRequest(result); + } + } + catch (JSONException e){ + RejectRequest(result, e.getMessage()); + } + + return result; + } + + + /** Method to emulate response from an Ansible + Server when presented with a GET request + Returns an ansibl object result. The response code is always the http code 200 (i.e connection successful) + payload is json string as would be sent back by Ansible Server + + **/ + public AnsibleResult Get(String AgentUrl){ + + // Extract id + Pattern pattern = Pattern.compile(".*?\\?Id=(.*?)&Type.*"); + Matcher matcher = pattern.matcher(AgentUrl); + String Id = ""; + + if (matcher.find()){ + Id = matcher.group(1); + } + + AnsibleResult get_result = new AnsibleResult(); + + JSONObject response = new JSONObject(); + response.put("StatusCode", 200); + response.put("StatusMessage", "FINISHED"); + + JSONObject results = new JSONObject(); + + JSONObject vm_results = new JSONObject(); + vm_results.put("StatusCode", 200); + vm_results.put("StatusMessage", "SUCCESS"); + vm_results.put("Id", Id); + results.put("192.168.1.10", vm_results); + + + response.put("Results", results); + + get_result.setStatusCode(200); + get_result.setStatusMessage(response.toString()); + + return get_result; + + } + + + private void RejectRequest(AnsibleResult result, String Message){ + result.setStatusCode(200); + JSONObject response = new JSONObject(); + response.put("StatusCode", AnsibleResultCodes.REJECTED.getValue()); + response.put("StatusMessage", Message); + result.setStatusMessage(response.toString()); + + } + + private void AcceptRequest(AnsibleResult result){ + result.setStatusCode(200); + JSONObject response = new JSONObject(); + response.put("StatusCode", AnsibleResultCodes.PENDING.getValue()); + response.put("StatusMessage", "PENDING"); + result.setStatusMessage(response.toString()); + + } + +}; + diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/AnsibleActivator.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/AnsibleActivator.java deleted file mode 100644 index d76cd50f1..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/AnsibleActivator.java +++ /dev/null @@ -1,126 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ansible; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.ansible.impl.AnsibleAdapterImpl; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.i18n.Msg; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -/** - * This activator is used to initialize and terminate an instance of AnsibleAdapter class - */ -public class AnsibleActivator implements BundleActivator { - - /** - * The bundle registration - */ - private ServiceRegistration registration = null; - - /** - * The reference to the actual implementation object that implements the services - */ - private AnsibleAdapter adapter; - - /** - * The logger to be used - */ - private final EELFLogger logger = EELFManager.getInstance().getLogger(AnsibleActivator.class); - - /** - * The configuration object used to configure this bundle - */ - private final Configuration configuration = ConfigurationFactory.getConfiguration(); - - /** - * 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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @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()); - String appName = "APPC: "; - logger.info(Msg.COMPONENT_INITIALIZING, appName, "Ansible Adapter"); - adapter = new AnsibleAdapterImpl(); - - if (registration == null) { - logger.info(Msg.REGISTERING_SERVICE, appName, adapter.getAdapterName(), - AnsibleAdapter.class.getSimpleName()); - registration = context.registerService(AnsibleAdapter.class, adapter, null); - } - - logger.info(Msg.COMPONENT_INITIALIZED, appName, "Ansible 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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @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, "Ansible adapter"); - logger.info(Msg.UNREGISTERING_SERVICE, appName, adapter.getAdapterName()); - registration.unregister(); - registration = null; - logger.info(Msg.COMPONENT_TERMINATED, appName, "Ansible adapter"); - } - } - - public String getName() { - return "APPC Ansible Adapter"; - } -} diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/AnsibleAdapter.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/AnsibleAdapter.java deleted file mode 100644 index 7bff184bc..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/AnsibleAdapter.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ansible; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; - -/** - * This interface defines the operations that the Ansible adapter exposes. - * - */ -public interface AnsibleAdapter extends SvcLogicJavaPlugin { - - - /** - * Returns the symbolic name of the adapter - * - * @return The adapter name - */ - String getAdapterName(); - - - /* Method to post request for execution of Playbook */ - void reqExec(Map params, SvcLogicContext ctx) throws SvcLogicException; - - /* Method to get result of a playbook execution request */ - void reqExecResult(Map params, SvcLogicContext ctx) throws SvcLogicException; - - - /* Method to get log of a playbook execution request */ - void reqExecLog(Map params, SvcLogicContext ctx) throws SvcLogicException; - - -} diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/impl/AnsibleAdapterImpl.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/impl/AnsibleAdapterImpl.java deleted file mode 100644 index 0b426bb26..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/impl/AnsibleAdapterImpl.java +++ /dev/null @@ -1,501 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ansible.impl; - -import java.util.Map; -import java.util.Properties; -import java.lang.*; - - -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; - - - -import org.json.JSONObject; -import org.json.JSONArray; -import org.json.JSONException; - - - -import org.onap.appc.adapter.ansible.AnsibleAdapter; - -import org.onap.appc.adapter.ansible.model.AnsibleResult; -import org.onap.appc.adapter.ansible.model.AnsibleMessageParser; -import org.onap.appc.adapter.ansible.model.AnsibleResultCodes; -import org.onap.appc.adapter.ansible.model.AnsibleServerEmulator; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import static com.att.eelf.configuration.Configuration.*; - - -/** - * This class implements the {@link AnsibleAdapter} interface. This interface - * defines the behaviors that our service provides. - * - */ -public class AnsibleAdapterImpl implements AnsibleAdapter { - - /** - * The constant used to define the adapter name in the mapped diagnostic - * context - */ - - - @SuppressWarnings("nls") - public static final String MDC_ADAPTER = "Ansible 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"; - - /** - Adapter Name - **/ - private static final String ADAPTER_NAME = "Ansible Adapter"; - - - /** - * The logger to be used - */ - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AnsibleAdapterImpl.class); - - /** - * A reference to the adapter configuration object. - */ - private Configuration configuration;; - - /** can Specify a X509 certificate file for use if required ... - Must be initialized with setCertFile - **/ - private String certFile = ""; - - - /** - * Connection object - **/ - ConnectionBuilder http_client ; - - /** - * Ansible API Message Handlers - **/ - private AnsibleMessageParser messageProcessor; - - /** - indicator whether in test mode - **/ - private boolean testMode = false; - - /** - server emulator object to be used if in test mode - **/ - private AnsibleServerEmulator testServer; - - /** - * This default constructor is used as a work around because the activator - * wasnt getting called - */ - public AnsibleAdapterImpl() { - initialize(); - } - - - /** - * @param props - * not used - */ - public AnsibleAdapterImpl(Properties props) { - initialize(); - } - - - - /** - Used for jUnit test and testing interface - **/ - public AnsibleAdapterImpl(boolean Mode){ - testMode = Mode; - testServer = new AnsibleServerEmulator(); - messageProcessor = new AnsibleMessageParser(); - } - - /** - * Returns the symbolic name of the adapter - * - * @return The adapter name - * @see org.onap.appc.adapter.rest.AnsibleAdapter#getAdapterName() - */ - @Override - public String getAdapterName() { - return ADAPTER_NAME; - } - - - - /** - * @param rc - * Method posts info to Context memory in case of an error - * and throws a SvcLogicException causing SLI to register this as a failure - */ - @SuppressWarnings("static-method") - private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException { - - svcLogic.setStatus(OUTCOME_FAILURE); - svcLogic.setAttribute("org.onap.appc.adapter.ansible.result.code",Integer.toString(code)); - svcLogic.setAttribute("org.onap.appc.adapter.ansible.message",message); - - throw new SvcLogicException("Ansible Adapter Error = " + message ); - } - - - /** - * initialize the Ansible adapter based on default and over-ride configuration data - */ - private void initialize() { - - configuration = ConfigurationFactory.getConfiguration(); - Properties props = configuration.getProperties(); - - // Create the message processor instance - messageProcessor = new AnsibleMessageParser(); - - // Create the http client instance - // type of client is extracted from the property file parameter - // org.onap.appc.adapter.ansible.clientType - // It can be : - // 1. TRUST_ALL (trust all SSL certs). To be used ONLY in dev - // 2. TRUST_CERT (trust only those whose certificates have been stored in the trustStore file) - // 3. DEFAULT (trust only well known certificates). This is standard behaviour to which it will - // revert. To be used in PROD - - try{ - String clientType = props.getProperty("org.onap.appc.adapter.ansible.clientType"); - logger.info("Ansible http client type set to " + clientType); - - if (clientType.equals("TRUST_ALL")){ - logger.info("Creating http client to trust ALL ssl certificates. WARNING. This should be done only in dev environments"); - http_client = new ConnectionBuilder(1); - } - else if (clientType.equals("TRUST_CERT")){ - // set path to keystore file - String trustStoreFile = props.getProperty("org.onap.appc.adapter.ansible.trustStore"); - String key = props.getProperty("org.onap.appc.adapter.ansible.trustStore.trustPasswd"); - char [] trustStorePasswd = key.toCharArray(); - String trustStoreType = "JKS"; - logger.info("Creating http client with trustmanager from " + trustStoreFile); - http_client = new ConnectionBuilder(trustStoreFile, trustStorePasswd); - } - else{ - logger.info("Creating http client with default behaviour"); - http_client = new ConnectionBuilder(0); - } - } - catch (Exception e){ - logger.error("Error Initializing Ansible Adapter due to Unknown Exception: reason = " + e.getMessage()); - } - - logger.info("Intitialized Ansible Adapter"); - - } - - - /** set the certificate file if not a trusted/known CA **/ - private void setCertFile(String CertFile){ - this.certFile = CertFile; - } - - - - // Public Method to post request to execute playbook. Posts the following back - // to Svc context memory - // org.onap.appc.adapter.ansible.req.code : 100 if successful - // org.onap.appc.adapter.ansible.req.messge : any message - // org.onap.appc.adapter.ansible.req.Id : a unique uuid to reference the request - - public void reqExec(Map params, SvcLogicContext ctx) throws SvcLogicException { - - String PlaybookName = ""; - String payload = ""; - String AgentUrl = ""; - String User = ""; - String Password = ""; - String Id = ""; - - JSONObject JsonPayload; - - try{ - // create json object to send request - JsonPayload = messageProcessor.ReqMessage(params); - - AgentUrl = (String) JsonPayload.remove("AgentUrl"); - User = (String) JsonPayload.remove("User"); - Password = (String) JsonPayload.remove("Password"); - Id = (String)JsonPayload.getString("Id"); - payload = JsonPayload.toString(); - logger.info("Updated Payload = " + payload); - } - catch(APPCException e){ - doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request for execution of playbook due to missing mandatory parameters. Reason = " + e.getMessage()); - } - catch(JSONException e){ - doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request for execution of playbook due to invalid JSON block. Reason = " + e.getMessage()); - } - catch(NumberFormatException e){ - doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request for execution of playbook due to invalid parameter values. Reason = " + e.getMessage()); - } - - - - int code = -1; - String message = ""; - - try{ - - // post the test request - //--------------------------------------- - logger.info("Posting request = " + payload + " to url = " + AgentUrl ); - AnsibleResult testresult = postExecRequest(AgentUrl, payload, User, Password); - - - // Process if HTTP was successfull - if(testresult.getStatusCode() == 200){ - testresult = messageProcessor.parsePostResponse(testresult.getStatusMessage()); - } - else{ - doFailure(ctx, testresult.getStatusCode(), "Error posting request. Reason = " + testresult.getStatusMessage()); - } - - - code = testresult.getStatusCode(); - message = testresult.getStatusMessage(); - - - // Check status of test request returned by Agent - //----------------------------------------------- - if (code == AnsibleResultCodes.PENDING.getValue()){ - logger.info(String.format("Submission of Test %s successful.", PlaybookName)); - // test request accepted. We are in asynchronous case - } - else{ - doFailure(ctx, code, "Request for execution of playbook rejected. Reason = " + message); - } - } - - catch(APPCException e){ - doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), "Exception encountered when posting request for execution of playbook. Reason = " + e.getMessage()); - } - - - ctx.setAttribute("org.onap.appc.adapter.ansible.result.code", Integer.toString(code)); - ctx.setAttribute("org.onap.appc.adapter.ansible.message", message ); - ctx.setAttribute("org.onap.appc.adapter.ansible.Id", Id); - - } - - - // Public method to query status of a specific request - // It blocks till the Ansible Server responds or the session times out - - public void reqExecResult(Map params, SvcLogicContext ctx) throws SvcLogicException { - - - // Get uri - String ReqUri = ""; - - try{ - ReqUri = messageProcessor.ReqUri_Result(params); - System.out.println("Got uri = " + ReqUri); - } - catch(APPCException e){ - doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request to retreive result due to missing parameters. Reason = " + e.getMessage()); - return; - } - catch(NumberFormatException e){ - doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error constructing request to retreive result due to invalid parameters value. Reason = " + e.getMessage()); - return; - } - - int code = -1; - String message = ""; - String results = ""; - - try{ - // Try to retreive the test results (modify the url for that) - AnsibleResult testresult = queryServer(ReqUri, params.get("User"), params.get("Password")); - code = testresult.getStatusCode(); - message = testresult.getStatusMessage(); - - if(code == 200){ - logger.info("Parsing response from Server = " + message); - // Valid HTTP. process the Ansible message - testresult = messageProcessor.parseGetResponse(message); - code = testresult.getStatusCode(); - message = testresult.getStatusMessage(); - results = testresult.getResults(); - - } - - logger.info("Request response = " + message); - - } - catch (APPCException e){ - doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), "Exception encountered retreiving result : " + e.getMessage()); - return; - } - - // We were able to get and process the results. Determine if playbook succeeded - - if (code == AnsibleResultCodes.FINAL_SUCCESS.getValue()){ - message = String.format("Ansible Request %s finished with Result = %s, Message = %s", params.get("Id"), OUTCOME_SUCCESS, message); - logger.info(message); - } - else { - logger.info(String.format("Ansible Request %s finished with Result %s, Message = %s", params.get("Id"), OUTCOME_FAILURE, message)); - ctx.setAttribute("org.onap.appc.adapter.ansible.results", results); - doFailure(ctx, code, message ); - return; - } - - - ctx.setAttribute("org.onap.appc.adapter.ansible.result.code", Integer.toString(400)); - ctx.setAttribute("org.onap.appc.adapter.ansible.message",message); - ctx.setAttribute("org.onap.appc.adapter.ansible.results", results); - ctx.setStatus(OUTCOME_SUCCESS); - } - - - // Public method to get logs from plyabook execution for a specifcic request - // It blocks till the Ansible Server responds or the session times out - // very similar to reqExecResult - // logs are returned in the DG context variable org.onap.appc.adapter.ansible.log - - public void reqExecLog(Map params, SvcLogicContext ctx) throws SvcLogicException{ - - - // Get uri - String ReqUri = ""; - try{ - ReqUri = messageProcessor.ReqUri_Log(params); - logger.info("Retreiving results from " + ReqUri); - } - catch(Exception e){ - doFailure(ctx, AnsibleResultCodes.INVALID_PAYLOAD.getValue(), e.getMessage()); - } - - int code = -1; - String message = ""; - float Duration = -1; - - try{ - // Try to retreive the test results (modify the url for that) - AnsibleResult testresult = queryServer(ReqUri, params.get("User"), params.get("Password")); - code = testresult.getStatusCode(); - message = testresult.getStatusMessage(); - - logger.info("Request output = " + message); - - } - catch (Exception e){ - doFailure(ctx, AnsibleResultCodes.UNKNOWN_EXCEPTION.getValue(), "Exception encountered retreiving output : " + e.getMessage()); - } - - ctx.setAttribute("org.onap.appc.adapter.ansible.log",message); - ctx.setStatus(OUTCOME_SUCCESS); - } - - - - - - /** - * Method that posts the request - **/ - - private AnsibleResult postExecRequest(String AgentUrl, String Payload, String User, String Password) { - - String reqOutput = "UNKNOWN"; - int reqStatus = -1; - - AnsibleResult testresult; - - if (!testMode){ - http_client.setHttpContext(User, Password); - testresult = http_client.Post(AgentUrl, Payload); - } - else{ - testresult = testServer.Post(AgentUrl, Payload); - } - - return testresult; - } - - - /* - Method to query Ansible server - - */ - private AnsibleResult queryServer(String AgentUrl, String User, String Password) { - - String testOutput = "UNKNOWN"; - int testStatus = -1; - AnsibleResult testresult; - - logger.info("Querying url = " + AgentUrl); - - if (!testMode){ - testresult = http_client.Get(AgentUrl); - } - else{ - testresult = testServer.Get(AgentUrl); - } - - return testresult; - - } - - - -} diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/impl/ConnectionBuilder.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/impl/ConnectionBuilder.java deleted file mode 100644 index e84a85a0c..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/impl/ConnectionBuilder.java +++ /dev/null @@ -1,224 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ansible.impl; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.auth.AuthScope; -import org.apache.http.entity.StringEntity; - -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.cert.CertificateException; -import java.security.KeyManagementException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.security.NoSuchAlgorithmException; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLContext; - -import java.io.FileInputStream; -import java.io.IOException; - - -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLContexts; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; - - -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.adapter.ansible.model.AnsibleResult; -import org.onap.appc.adapter.ansible.model.AnsibleResultCodes; - - -/** - * Returns custom http client - - based on options - - can create one with ssl using an X509 certificate that does NOT have a known CA - - create one which trusts ALL SSL certificates - - return default httpclient (which only trusts known CAs from default cacerts file for process) -- this is the default option - -**/ - - -public class ConnectionBuilder { - - - - private CloseableHttpClient http_client = null; - private HttpClientContext http_context = new HttpClientContext(); - - - - - // Various constructors depending on how we want to instantiate the http ConnectionBuilder instance - - - /** - * Constructor that initializes an http client based on certificate - **/ - public ConnectionBuilder(String CertFile) throws KeyStoreException, CertificateException, IOException, KeyManagementException, NoSuchAlgorithmException, APPCException{ - - - /* Point to the certificate */ - FileInputStream fs = new FileInputStream(CertFile); - - /* Generate a certificate from the X509 */ - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - X509Certificate cert = (X509Certificate)cf.generateCertificate(fs); - - /* Create a keystore object and load the certificate there */ - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(null, null); - keystore.setCertificateEntry("cacert", cert); - - - SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build(); - SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - - http_client = HttpClients.custom().setSSLSocketFactory(factory).build(); - }; - - - /** - * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS file) - **/ - public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException, KeyManagementException, NoSuchAlgorithmException, CertificateException { - - - /* Load the specified trustStore */ - KeyStore keystore = KeyStore.getInstance("JKS"); - FileInputStream readStream = new FileInputStream(trustStoreFile); - keystore.load(readStream,trustStorePasswd); - - SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build(); - SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - - http_client = HttpClients.custom().setSSLSocketFactory(factory).build(); - }; - - /** - * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1 - or Default if Mode == 0 - */ - public ConnectionBuilder(int Mode) throws SSLException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException{ - if (Mode == 1){ - SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); - SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - - http_client = HttpClients.custom().setSSLSocketFactory(factory).build(); - } - - else{ - http_client = HttpClients.createDefault(); - } - - }; - - - // Use to create an http context with auth headers - public void setHttpContext(String User, String MyPassword){ - - // Are credential provided ? If so, set the context to be used - if (User != null && ! User.isEmpty() && MyPassword != null && ! MyPassword.isEmpty()){ - UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(User, MyPassword); - AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); - BasicCredentialsProvider credsprovider = new BasicCredentialsProvider(); - credsprovider.setCredentials(authscope, credentials); - http_context.setCredentialsProvider(credsprovider); - } - - - }; - - - // Method posts to the ansible server and writes out response to - // Ansible result object - public AnsibleResult Post(String AgentUrl, String Payload){ - - AnsibleResult result = new AnsibleResult(); - try{ - - HttpPost postObj = new HttpPost(AgentUrl); - StringEntity bodyParams = new StringEntity(Payload, "UTF-8"); - postObj.setEntity(bodyParams); - postObj.addHeader("Content-type", "application/json"); - - HttpResponse response = http_client.execute(postObj, http_context); - - HttpEntity entity = response.getEntity(); - String responseOutput = entity != null ? EntityUtils.toString(entity) : null; - int responseCode = response.getStatusLine().getStatusCode(); - result.setStatusCode(responseCode); - result.setStatusMessage(responseOutput); - } - - catch(IOException io){ - result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue()); - result.setStatusMessage(io.getMessage()); - } - - - - return result; - - } - - // Method gets information from an Ansible server and writes out response to - // Ansible result object - - public AnsibleResult Get(String AgentUrl){ - - AnsibleResult result = new AnsibleResult(); - - try{ - HttpGet getObj = new HttpGet(AgentUrl ); - HttpResponse response = http_client.execute(getObj, http_context); - - - HttpEntity entity = response.getEntity(); - String responseOutput = entity != null ? EntityUtils.toString(entity) : null; - int responseCode = response.getStatusLine().getStatusCode(); - result.setStatusCode(responseCode); - result.setStatusMessage(responseOutput); - - } - catch(IOException io){ - result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue()); - result.setStatusMessage(io.getMessage()); - } - - return result; - }; - -} diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleMessageParser.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleMessageParser.java deleted file mode 100644 index 6bebd73fe..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleMessageParser.java +++ /dev/null @@ -1,364 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ansible.model; - -/** - * This module imples the APP-C/Ansible Server interface - * based on the REST API specifications - */ - -import java.lang.NumberFormatException ; -import java.util.*; -import com.google.common.base.Strings; - -import org.json.JSONObject; -import org.json.JSONArray; -import org.json.JSONException; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.adapter.ansible.model.AnsibleResult; - - -/** - * Class that validates and constructs requests sent/received from - * Ansible Server - * - */ -public class AnsibleMessageParser { - - - - - // Accepts a map of strings and - // a) validates if all parameters are appropriate (else, throws an exception) - // and b) if correct returns a JSON object with appropriate key-value - // pairs to send to the server. - public JSONObject ReqMessage(Map params) throws APPCException, NumberFormatException, JSONException{ - - // Mandatory parameters, that must be in the supplied information to the Ansible Adapter - // 1. URL to connect to - // 2. credentials for URL (assume username password for now) - // 3. Playbook name - String[] mandatoryTestParams = {"AgentUrl", "PlaybookName", "User", "Password"}; - - // Optional testService parameters that may be provided in the request - String[] optionalTestParams = {"EnvParameters", "NodeList", "LocalParameters", "Timeout", "Version", "FileParameters", "Action"}; - - JSONObject JsonPayload = new JSONObject(); - String payload = ""; - JSONObject paramsJson; - - - // Verify all the mandatory parameters are there - for (String key: mandatoryTestParams){ - if (! params.containsKey(key)){ - throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); - } - payload = params.get(key); - if (Strings.isNullOrEmpty(payload)){ - throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key % value is Null or Emtpy", key)); - } - - JsonPayload.put(key, payload); - } - - // Iterate through optional parameters - // If null or empty omit it - for (String key : optionalTestParams){ - if (params.containsKey(key)){ - payload = params.get(key); - if(!Strings.isNullOrEmpty(payload)){ - - // different cases require different treatment - switch (key){ - case "Timeout": - int Timeout = Integer.parseInt(payload); - if (Timeout < 0){ - throw new NumberFormatException(" : specified negative integer for timeout = " + payload); - } - JsonPayload.put(key, payload); - break; - - case "Version": - JsonPayload.put(key, payload); - break; - - case "LocalParameters": - paramsJson = new JSONObject(payload); - JsonPayload.put(key, paramsJson); - break; - - case "EnvParameters": - paramsJson = new JSONObject(payload); - JsonPayload.put(key, paramsJson); - break; - - case "NodeList": - JSONArray paramsArray = new JSONArray(payload); - JsonPayload.put(key, paramsArray); - break; - - case "FileParameters": - // Files may have strings with newlines. Escape them as appropriate - String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r"); - JSONObject fileParams = new JSONObject(formattedPayload); - JsonPayload.put(key, fileParams); - break; - - } - } - } - } - - - // Generate a unique uuid for the test - String ReqId = UUID.randomUUID().toString(); - JsonPayload.put("Id", ReqId); - - return JsonPayload; - - } - - - - // method that validates that the Map has enough information - // to query Ansible server for a result . If so, it - // returns the appropriate url, else an empty string - public String ReqUri_Result(Map params) throws APPCException, NumberFormatException{ - - // Mandatory parameters, that must be in the request - String[] mandatoryTestParams = {"AgentUrl", "Id", "User", "Password" }; - - // Verify all the mandatory parameters are there - String payload = ""; - String Uri = ""; - - for (String key: mandatoryTestParams){ - if (! params.containsKey(key)){ - throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); - } - - payload = params.get(key); - if (Strings.isNullOrEmpty(payload)){ - throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); - } - - } - - Uri = params.get("AgentUrl") + "?Id=" + params.get("Id") + "&Type=GetResult"; - - return Uri; - - } - - - - // method that validates that the Map has enough information - // to query Ansible server for logs. If so, it populates the appropriate - // returns the appropriate url, else an empty string - public String ReqUri_Output(Map params) throws APPCException, NumberFormatException{ - - - // Mandatory parameters, that must be in the request - String[] mandatoryTestParams = {"AgentUrl", "Id", "User", "Password" }; - - // Verify all the mandatory parameters are there - String payload = ""; - String Uri = ""; - - for (String key: mandatoryTestParams){ - if (! params.containsKey(key)){ - throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); - } - payload = params.get(key); - if (Strings.isNullOrEmpty(payload)){ - throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); - } - - } - - Uri = params.get("AgentUrl") + "?Id=" + params.get("Id") + "&Type=GetOutput"; - return Uri; - - } - - // method that validates that the Map has enough information - // to query Ansible server for logs. If so, it populates the appropriate - // returns the appropriate url, else an empty string - public String ReqUri_Log(Map params) throws APPCException, NumberFormatException{ - - - // Mandatory parameters, that must be in the request - String[] mandatoryTestParams = {"AgentUrl", "Id", "User", "Password" }; - - // Verify all the mandatory parameters are there - String payload = ""; - String Uri = ""; - - for (String key: mandatoryTestParams){ - if (! params.containsKey(key)){ - throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); - } - payload = params.get(key); - if (Strings.isNullOrEmpty(payload)){ - throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); - } - - } - - Uri = params.get("AgentUrl") + "?Id=" + params.get("Id") + "&Type=GetLog"; - return Uri; - - } - - - /** - This method parses response from the - Ansible Server when we do a post - and returns an AnsibleResult object - **/ - - public AnsibleResult parsePostResponse(String Input) throws APPCException{ - - AnsibleResult ansibleResult = new AnsibleResult(); - - try{ - //Jsonify it - JSONObject postResponse = new JSONObject(Input); - - // Mandatory keys required are StatusCode and StatusMessage - int Code = postResponse.getInt("StatusCode"); - String Message = postResponse.getString("StatusMessage"); - - - // Status code must must be either 100 (accepted) or 101 (rejected) - boolean valCode = AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.INITRESPONSE.getValue(), Code); - if(!valCode){ - throw new APPCException("Invalid InitResponse code = " + Code + " received. MUST be one of " + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.INITRESPONSE.getValue()) ); - } - - ansibleResult.setStatusCode(Code); - ansibleResult.setStatusMessage(Message); - - } - catch(JSONException e){ - ansibleResult = new AnsibleResult(600, "Error parsing response = " + Input + ". Error = " + e.getMessage(), ""); - } - - - return ansibleResult; - } - - - /** This method parses response from an Ansible server when we do a GET for a result - and returns an AnsibleResult object - **/ - public AnsibleResult parseGetResponse(String Input) throws APPCException { - - AnsibleResult ansibleResult = new AnsibleResult(); - int FinalCode = AnsibleResultCodes.FINAL_SUCCESS.getValue(); - - - try{ - - //Jsonify it - JSONObject postResponse = new JSONObject(Input); - - // Mandatory keys required are Status and Message - int Code = postResponse.getInt("StatusCode"); - String Message = postResponse.getString("StatusMessage"); - - // Status code must be valid - // Status code must must be either 100 (accepted) or 101 (rejected) - boolean valCode = AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.FINALRESPONSE.getValue(), Code); - - if(!valCode){ - throw new APPCException("Invalid FinalResponse code = " + Code + " received. MUST be one of " + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.FINALRESPONSE.getValue())); - } - - - ansibleResult.setStatusCode(Code); - ansibleResult.setStatusMessage(Message); - System.out.println("Received response with code = " + Integer.toString(Code) + " Message = " + Message); - - if(! postResponse.isNull("Results")){ - - // Results are available. process them - // Results is a dictionary of the form - // {host :{status:s, group:g, message:m, hostname:h}, ...} - System.out.println("Processing results in response"); - JSONObject results = postResponse.getJSONObject("Results"); - System.out.println("Get JSON dictionary from Results .."); - Iterator hosts = results.keys(); - System.out.println("Iterating through hosts"); - - while(hosts.hasNext()){ - String host = hosts.next(); - System.out.println("Processing host = " + host); - - try{ - JSONObject host_response = results.getJSONObject(host); - int subCode = host_response.getInt("StatusCode"); - String message = host_response.getString("StatusMessage"); - - System.out.println("Code = " + Integer.toString(subCode) + " Message = " + message); - - if(subCode != 200 || ! message.equals("SUCCESS")){ - FinalCode = AnsibleResultCodes.REQ_FAILURE.getValue(); - } - } - catch(JSONException e){ - ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue()); - ansibleResult.setStatusMessage(String.format("Error processing response message = %s from host %s", results.getString(host), host)); - break; - } - } - - ansibleResult.setStatusCode(FinalCode); - - // We return entire Results object as message - ansibleResult.setResults(results.toString()); - - } - else{ - ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue()); - ansibleResult.setStatusMessage("Results not found in GET for response"); - } - - - } - catch(JSONException e){ - ansibleResult = new AnsibleResult(AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error parsing response = " + Input + ". Error = " + e.getMessage(), ""); - } - - - return ansibleResult; - } - - - -}; - - - diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleResult.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleResult.java deleted file mode 100644 index a4bbcbef8..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleResult.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ansible.model; - - -/* Simple class to store code and message returned by POST/GET to an Ansible Server */ -public class AnsibleResult{ - private int StatusCode; - private String StatusMessage; - private String Results; - - - public AnsibleResult(){ - StatusCode = -1; - StatusMessage = "UNKNOWN"; - Results = "UNKNOWN"; - - } - - // constructor - public AnsibleResult(int code, String message, String result){ - StatusCode = code; - StatusMessage = message; - Results = result; - } - - //************************************************* - // Various set methods - public void setStatusCode(int code){ - this.StatusCode = code; - } - - public void setStatusMessage(String message){ - this.StatusMessage = message; - } - - public void setResults(String results){ - this.Results = results; - } - - - void set(int code, String message, String results){ - this.StatusCode = code; - this.StatusMessage = message; - this.Results = results; - - } - - //********************************************* - // Various get methods - public int getStatusCode(){ - return this.StatusCode; - } - - public String getStatusMessage(){ - return this.StatusMessage; - } - - public String getResults(){ - return this.Results; - } - - -} - diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleResultCodes.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleResultCodes.java deleted file mode 100644 index 986ad3e6a..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleResultCodes.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ansible.model; - - -import java.util.*; - -/** - * enum of the various codes that APP-C uses to resolve different - * status of response from Ansible Server - **/ - -public enum AnsibleResultCodes{ - - SUCCESS(400), - KEYSTORE_EXCEPTION(622), - CERTIFICATE_ERROR(610), - IO_EXCEPTION (611), - HOST_UNKNOWN(625), - USER_UNAUTHORIZED(613), - UNKNOWN_EXCEPTION(699), - SSL_EXCEPTION(697), - INVALID_PAYLOAD(698), - INVALID_RESPONSE(601), - PENDING(100), - REJECTED(101), - FINAL_SUCCESS(200), - REQ_FAILURE(401), - MESSAGE(1), - CODE(0), - INITRESPONSE(0), - FINALRESPONSE(1); - - private final Set InitCodes = new HashSet(Arrays.asList(100, 101)); - private final Set FinalCodes = new HashSet(Arrays.asList(200, 500)); - private final ArrayList>CodeSets = new ArrayList>(Arrays.asList(InitCodes, FinalCodes)); - - private final Set MessageSet = new HashSet(Arrays.asList("PENDING", "FINISHED", "TERMINATED")); - - private final int value; - - AnsibleResultCodes(int value){ - this.value = value; - }; - - - public int getValue(){ - return this.value; - } - - - public boolean checkValidCode(int Type, int Code){ - SetCodeSet = CodeSets.get(Type); - if (CodeSet.contains(Code)){ - return true; - } - else{ - return false; - } - } - - - public String getValidCodes(int Type){ - SetCodeSet = CodeSets.get(Type); - - Iterator iter = CodeSet.iterator(); - String ValidCodes = "[ "; - while(iter.hasNext()){ - ValidCodes = ValidCodes + iter.next().toString() + ","; - } - - ValidCodes = ValidCodes + "]"; - return ValidCodes; - } - - - public boolean checkValidMessage(String Message){ - if (MessageSet.contains(Message)){ - return true; - } - else{ - return false; - } - } - - - - public String getValidMessages(){ - Iterator iter = MessageSet.iterator(); - String ValidMessage = "[ "; - while(iter.hasNext()){ - ValidMessage = ValidMessage + iter.next() + ","; - } - - ValidMessage = ValidMessage + "]"; - return ValidMessage; - } - - -}; diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleServerEmulator.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleServerEmulator.java deleted file mode 100644 index c430743ad..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleServerEmulator.java +++ /dev/null @@ -1,148 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - - -/* Class to emulate responses from the Ansible Server that is compliant with the APP-C Ansible Server - Interface. Used for jUnit tests to verify code is working. In tests it can be used - as a replacement for methods from ConnectionBuilder class -*/ - -package org.onap.appc.adapter.ansible.model; - -import java.util.*; -import java.util.regex.Pattern; -import java.util.regex.Matcher; -import com.google.common.base.Strings; - -import org.json.JSONObject; -import org.json.JSONArray; -import org.json.JSONException; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.adapter.ansible.model.AnsibleResult; - -public class AnsibleServerEmulator { - - - private String playbookName = "test_playbook.yaml"; - private String TestId; - - /** - * Method that emulates the response from an Ansible Server - when presented with a request to execute a playbook - Returns an ansible object result. The response code is always the http code 200 (i.e connection successful) - payload is json string as would be sent back by Ansible Server - **/ - - public AnsibleResult Post(String AgentUrl, String payload){ - AnsibleResult result = new AnsibleResult() ; - - try{ - // Request must be a JSON object - - JSONObject message = new JSONObject(payload); - if (message.isNull("Id")){ - RejectRequest(result, "Must provide a valid Id"); - } - else if(message.isNull("PlaybookName")){ - RejectRequest(result, "Must provide a playbook Name"); - } - else if(!message.getString("PlaybookName").equals(playbookName)){ - RejectRequest(result, "Playbook " + message.getString("PlaybookName") + " not found in catalog"); - } - else{ - AcceptRequest(result); - } - } - catch (JSONException e){ - RejectRequest(result, e.getMessage()); - } - - return result; - } - - - /** Method to emulate response from an Ansible - Server when presented with a GET request - Returns an ansibl object result. The response code is always the http code 200 (i.e connection successful) - payload is json string as would be sent back by Ansible Server - - **/ - public AnsibleResult Get(String AgentUrl){ - - // Extract id - Pattern pattern = Pattern.compile(".*?\\?Id=(.*?)&Type.*"); - Matcher matcher = pattern.matcher(AgentUrl); - String Id = ""; - - if (matcher.find()){ - Id = matcher.group(1); - } - - AnsibleResult get_result = new AnsibleResult(); - - JSONObject response = new JSONObject(); - response.put("StatusCode", 200); - response.put("StatusMessage", "FINISHED"); - - JSONObject results = new JSONObject(); - - JSONObject vm_results = new JSONObject(); - vm_results.put("StatusCode", 200); - vm_results.put("StatusMessage", "SUCCESS"); - vm_results.put("Id", Id); - results.put("192.168.1.10", vm_results); - - - response.put("Results", results); - - get_result.setStatusCode(200); - get_result.setStatusMessage(response.toString()); - - return get_result; - - } - - - private void RejectRequest(AnsibleResult result, String Message){ - result.setStatusCode(200); - JSONObject response = new JSONObject(); - response.put("StatusCode", AnsibleResultCodes.REJECTED.getValue()); - response.put("StatusMessage", Message); - result.setStatusMessage(response.toString()); - - } - - private void AcceptRequest(AnsibleResult result){ - result.setStatusCode(200); - JSONObject response = new JSONObject(); - response.put("StatusCode", AnsibleResultCodes.PENDING.getValue()); - response.put("StatusMessage", "PENDING"); - result.setStatusMessage(response.toString()); - - } - -}; - diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/resources/org/onap/appc/default.properties b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..d49c0396c --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,48 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# +# Default properties for the APP-C TestService 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=${user.home},/opt/opendaylight/current/properties + +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_ansible_adapter + + +# Default truststore path and password +org.onap.appc.adapter.ansible.trustStore=/opt/opendaylight/tls-client/mykeystore.js +org.onap.appc.adapter.ansible.trustStore.trustPasswd=changeit +org.onap.appc.adapter.ansible.clientType=DEFAULT diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index d49c0396c..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,48 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# -# Default properties for the APP-C TestService 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=${user.home},/opt/opendaylight/current/properties - -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_ansible_adapter - - -# Default truststore path and password -org.onap.appc.adapter.ansible.trustStore=/opt/opendaylight/tls-client/mykeystore.js -org.onap.appc.adapter.ansible.trustStore.trustPasswd=changeit -org.onap.appc.adapter.ansible.clientType=DEFAULT diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/adapter/ansible/impl/TestAnsibleAdapterImpl.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/adapter/ansible/impl/TestAnsibleAdapterImpl.java new file mode 100644 index 000000000..88425700e --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/adapter/ansible/impl/TestAnsibleAdapterImpl.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ansible.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.File; +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.onap.appc.Constants; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.slf4j.MDC; + +import org.onap.appc.adapter.ansible.AnsibleAdapter; +import org.onap.appc.adapter.ansible.impl.AnsibleAdapterImpl; + +public class TestAnsibleAdapterImpl { + + + private AnsibleAdapterImpl adapter; + private String TestId; + private boolean testMode = true; + + @SuppressWarnings("nls") + @BeforeClass + public static void once() throws NoSuchFieldException, SecurityException, NoSuchMethodException { + + } + + @Before + public void setup() throws IllegalArgumentException, IllegalAccessException { + testMode = true; + adapter = new AnsibleAdapterImpl(testMode); + } + + @Test + public void testA() throws IOException, IllegalStateException, IllegalArgumentException, + APPCException { + + Map params = new HashMap<>(); + params.put("AgentUrl", "https://192.168.1.1"); + params.put("User", "test"); + params.put("Password", "test"); + params.put("PlaybookName", "test_playbook.yaml"); + + SvcLogicContext svcContext = new SvcLogicContext(); + try{ + String Pending = "100"; + adapter.reqExec(params, svcContext); + String status=svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); + TestId=svcContext.getAttribute("org.onap.appc.adapter.ansible.result.Id"); + System.out.println("Comparing " + Pending + " and " + status); + assertEquals(Pending,status); + } + catch(SvcLogicException e){ + String message =svcContext.getAttribute("org.onap.appc.adapter.ansible.result.message"); + String status=svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); + fail(e.getMessage() + " Code = " + status); + } + catch(Exception e){ + fail(e.getMessage() + " Unknown exception encountered " ); + } + + } + + @Test + public void testB() throws IOException, IllegalStateException, IllegalArgumentException, + APPCException { + + Map params = new HashMap<>(); + + params.put("AgentUrl", "https://192.168.1.1"); + params.put("User", "test"); + params.put("Password", "test"); + params.put("Id", "100"); + + for (String ukey: params.keySet()){ + System.out.println(String.format("Ansible Parameter %s = %s", ukey, params.get(ukey))); + } + + SvcLogicContext svcContext = new SvcLogicContext(); + + try{ + adapter.reqExecResult(params, svcContext); + String status=svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); + assertEquals("400",status); + } + catch(SvcLogicException e){ + String message = svcContext.getAttribute("org.onap.appc.adapter.ansible.result.message"); + String status=svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); + fail(e.getMessage() + " Code = " + status); + } + catch(Exception e){ + fail(e.getMessage() + " Unknown exception encountered " ); + } + + } + +} diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java new file mode 100644 index 000000000..13b5fdfb3 --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java @@ -0,0 +1,182 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.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.onap.appc.test.InterceptLogger; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.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 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: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • + *
  • 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
  • + *
+ * @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: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • + *
  • 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
  • + *
+ * @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 getExecMethodNames() { + List 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-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java new file mode 100644 index 000000000..b101ecee4 --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java @@ -0,0 +1,454 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.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 events; + + /** + * Create the intercept logger + */ + public InterceptLogger() { + events = new ArrayList(1000); + } + + /** + * @return Returns all intercepted log events + */ + public List 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-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/openecomp/appc/adapter/ansible/impl/TestAnsibleAdapterImpl.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/openecomp/appc/adapter/ansible/impl/TestAnsibleAdapterImpl.java deleted file mode 100644 index 88425700e..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/openecomp/appc/adapter/ansible/impl/TestAnsibleAdapterImpl.java +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ansible.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.File; -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.onap.appc.Constants; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.slf4j.MDC; - -import org.onap.appc.adapter.ansible.AnsibleAdapter; -import org.onap.appc.adapter.ansible.impl.AnsibleAdapterImpl; - -public class TestAnsibleAdapterImpl { - - - private AnsibleAdapterImpl adapter; - private String TestId; - private boolean testMode = true; - - @SuppressWarnings("nls") - @BeforeClass - public static void once() throws NoSuchFieldException, SecurityException, NoSuchMethodException { - - } - - @Before - public void setup() throws IllegalArgumentException, IllegalAccessException { - testMode = true; - adapter = new AnsibleAdapterImpl(testMode); - } - - @Test - public void testA() throws IOException, IllegalStateException, IllegalArgumentException, - APPCException { - - Map params = new HashMap<>(); - params.put("AgentUrl", "https://192.168.1.1"); - params.put("User", "test"); - params.put("Password", "test"); - params.put("PlaybookName", "test_playbook.yaml"); - - SvcLogicContext svcContext = new SvcLogicContext(); - try{ - String Pending = "100"; - adapter.reqExec(params, svcContext); - String status=svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); - TestId=svcContext.getAttribute("org.onap.appc.adapter.ansible.result.Id"); - System.out.println("Comparing " + Pending + " and " + status); - assertEquals(Pending,status); - } - catch(SvcLogicException e){ - String message =svcContext.getAttribute("org.onap.appc.adapter.ansible.result.message"); - String status=svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); - fail(e.getMessage() + " Code = " + status); - } - catch(Exception e){ - fail(e.getMessage() + " Unknown exception encountered " ); - } - - } - - @Test - public void testB() throws IOException, IllegalStateException, IllegalArgumentException, - APPCException { - - Map params = new HashMap<>(); - - params.put("AgentUrl", "https://192.168.1.1"); - params.put("User", "test"); - params.put("Password", "test"); - params.put("Id", "100"); - - for (String ukey: params.keySet()){ - System.out.println(String.format("Ansible Parameter %s = %s", ukey, params.get(ukey))); - } - - SvcLogicContext svcContext = new SvcLogicContext(); - - try{ - adapter.reqExecResult(params, svcContext); - String status=svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); - assertEquals("400",status); - } - catch(SvcLogicException e){ - String message = svcContext.getAttribute("org.onap.appc.adapter.ansible.result.message"); - String status=svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); - fail(e.getMessage() + " Code = " + status); - } - catch(Exception e){ - fail(e.getMessage() + " Unknown exception encountered " ); - } - - } - -} diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java deleted file mode 100644 index 13b5fdfb3..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java +++ /dev/null @@ -1,182 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.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.onap.appc.test.InterceptLogger; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.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 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: - *
    - *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • - *
  • 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
  • - *
- * @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: - *
    - *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • - *
  • 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
  • - *
- * @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 getExecMethodNames() { - List 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-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java deleted file mode 100644 index b101ecee4..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java +++ /dev/null @@ -1,454 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.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 events; - - /** - * Create the intercept logger - */ - public InterceptLogger() { - events = new ArrayList(1000); - } - - /** - * @return Returns all intercepted log events - */ - public List 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-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/onap/appc/default.properties b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..bb888132a --- /dev/null +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,111 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============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/openecomp/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 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 + +# 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 + diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties deleted file mode 100644 index bb888132a..000000000 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,111 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============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/openecomp/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 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 - -# 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 - diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/ChefActivator.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/ChefActivator.java new file mode 100644 index 000000000..6c798b4b2 --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/ChefActivator.java @@ -0,0 +1,144 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.chef; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.chef.impl.ChefAdapterImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.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. + *

+ * 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. + *

+ *

+ * 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. + *

+ *

+ * When the bundle is deactivated, the cache is torn down with all contexts being closed. + *

+ */ +public class ChefActivator implements BundleActivator { + + /** + * The bundle registration + */ + private ServiceRegistration registration = null; + + /** + * The reference to the actual implementation object that implements the services + */ + private ChefAdapter adapter; + + /** + * The logger to be used + */ + private final EELFLogger logger = EELFManager.getInstance().getLogger(ChefActivator.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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @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, "chef adapter"); + adapter = new ChefAdapterImpl(); + if (registration == null) { + logger.info(Msg.REGISTERING_SERVICE, appName, adapter.getAdapterName(), + ChefAdapter.class.getSimpleName()); + registration = context.registerService(ChefAdapter.class, adapter, null); + } + + logger.info(Msg.COMPONENT_INITIALIZED, appName, "CHEF 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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @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, "CHEF adapter"); + logger.info(Msg.UNREGISTERING_SERVICE, appName, adapter.getAdapterName()); + registration.unregister(); + registration = null; + logger.info(Msg.COMPONENT_TERMINATED, appName, "CHEF adapter"); + } + } + + public String getName() { + return "APPC IaaS adapter"; + } + +} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/ChefAdapter.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/ChefAdapter.java new file mode 100644 index 000000000..d11db1c14 --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/ChefAdapter.java @@ -0,0 +1,220 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.chef; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import com.att.cdp.zones.model.Server; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +/** + * This interface defines the operations that the provider adapter exposes. + *

+ * 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. + *

+ */ +public interface ChefAdapter 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"; + + /** + * This method is used to restart an existing virtual machine given the fully qualified URL of the machine. + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to stop the indicated server + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to start the indicated server + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to rebuild the indicated server + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 properties, SvcLogicContext context) throws APPCException; + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + */ + String getAdapterName(); + + // Server evacuateServer(Map params, SvcLogicContext ctx) throws APPCException; + + //Server migrateServer(Map params, SvcLogicContext ctx) throws APPCException; + + void trigger(Map params, SvcLogicContext ctx) ; + + void chefGet(Map params, SvcLogicContext ctx) ; + + void chefPut(Map params, SvcLogicContext ctx) ; + + void chefPost(Map params, SvcLogicContext ctx) ; + + void chefDelete(Map params, SvcLogicContext ctx) ; + + void nodeObejctBuilder(Map params, SvcLogicContext ctx) ; + + void checkPushJob(Map params, SvcLogicContext ctx) ; + + void pushJob(Map params, SvcLogicContext ctx) ; + + void retrieveData (Map params, SvcLogicContext ctx) ; + + void combineStrings (Map params, SvcLogicContext ctx) ; + +} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/ApiMethod.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/ApiMethod.java new file mode 100644 index 000000000..38c4dd354 --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/ApiMethod.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.chef.chefapi; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +import org.apache.http.HttpResponse; +import org.apache.http.Header; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.util.EntityUtils; +import org.onap.appc.adapter.chef.chefclient.Utils; + +import org.apache.http.HttpEntity; +import org.apache.http.impl.client.HttpClients; + +public class ApiMethod { + private HttpClient client = null; + protected HttpRequestBase method = null; + protected HttpResponse response = null; + protected String reqBody = ""; + protected String userId = ""; + protected String pemPath = ""; + protected String chefPath = ""; + protected String organizations = ""; + protected int resCode=0; + protected String responseBody=""; + private String methodName = "GET"; + public String test = ""; + private int returnCode; + + public ApiMethod(String methodName) { + client=HttpClients.createDefault(); + this.methodName = methodName; + } + + public ApiMethod createRequest(){ + String hashedPath = Utils.sha1AndBase64("/organizations/"+organizations+chefPath); + String hashedBody = Utils.sha1AndBase64(reqBody); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + String timeStamp = sdf.format(new Date()); + timeStamp = timeStamp.replace(" ", "T"); + timeStamp = timeStamp + "Z"; + + StringBuilder sb = new StringBuilder(); + sb.append("Method:").append(methodName).append("\n"); + sb.append("Hashed Path:").append(hashedPath).append("\n"); + sb.append("X-Ops-Content-Hash:").append(hashedBody).append("\n"); + sb.append("X-Ops-Timestamp:").append(timeStamp).append("\n"); + sb.append("X-Ops-UserId:").append(userId); + test = test + "sb " + sb + "\n"; + + String auth_String = Utils.signWithRSA(sb.toString(), pemPath); + String[] auth_headers = Utils.splitAs60(auth_String); + + method.addHeader("Content-type", "application/json"); + method.addHeader("X-Ops-Timestamp", timeStamp); + method.addHeader("X-Ops-Userid", userId); + method.addHeader("X-Chef-Version", "12.4.1"); + method.addHeader("Accept", "application/json"); + method.addHeader("X-Ops-Content-Hash", hashedBody); + method.addHeader("X-Ops-Sign", "version=1.0"); + + for (int i = 0; i < auth_headers.length; i++) { + method.addHeader("X-Ops-Authorization-" + (i + 1), auth_headers[i]); + } + /* + * test=test+this.method.getMethod()+"\n"; Header[] + * RHS=this.method.getHeaders(); for (int i = 0; i < RHS.length; i++) { + * test=test+RHS[i]+"\n"; } test=test+this.reqBody+"\n"; + */ + return this; + } + + public ApiMethod execute() { + try{ + response = client.execute(method); + resCode = response.getStatusLine().getStatusCode(); + HttpEntity entity1 = response.getEntity(); + responseBody = EntityUtils.toString(entity1);} + catch(Exception ex){ + resCode=500; + responseBody=ex.getMessage(); + } + return this; + } + + public void setHeaders(Header[] headers) { + for (Header header : headers) { + this.method.addHeader(header); + } + } + + public String getResponseBodyAsString() { + return responseBody; + } + + public int getReturnCode() { + return resCode; + } + + public String getReqBody() { + return reqBody; + } + + public void setReqBody(String body) { + this.reqBody = body; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getPemPath() { + return pemPath; + } + + public void setPemPath(String pemPath) { + this.pemPath = pemPath; + } + + public String getChefPath() { + return chefPath; + } + + public void setChefPath(String chefPath) { + this.chefPath = chefPath; + } + + public String getOrganizations() { + return organizations; + } + + public void setOrganizations(String organizations) { + this.organizations = organizations; + } +} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Delete.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Delete.java new file mode 100644 index 000000000..5fa8a3fae --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Delete.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.chef.chefapi; + +import org.apache.http.client.methods.HttpDelete; + +public class Delete extends ApiMethod{ + + public Delete(HttpDelete method) { + super("DELETE"); + this.method = method; + } + +} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Get.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Get.java new file mode 100644 index 000000000..da37236a7 --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Get.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.chef.chefapi; + +import org.apache.http.client.methods.HttpGet; + +public class Get extends ApiMethod{ + + public Get(HttpGet method) { + super("GET"); + this.method = method; + } +} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Post.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Post.java new file mode 100644 index 000000000..3234eeefa --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Post.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.chef.chefapi; + +import org.apache.http.client.methods.*; +import org.apache.http.entity.StringEntity; + +public class Post extends ApiMethod{ + + public Post(HttpRequestBase method) { + super("POST"); + this.method = method; + } + + public ApiMethod body(String body){ + this.reqBody = body; + StringEntity params =new StringEntity (body,"UTF-8"); + params.setContentType("application/json"); + HttpPost post = (HttpPost) method; + post.setEntity(params); + return this; + } + +} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Put.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Put.java new file mode 100644 index 000000000..c96fc64d1 --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefapi/Put.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.chef.chefapi; + +import org.apache.http.client.methods.*; +import org.apache.http.entity.StringEntity; + +public class Put extends ApiMethod{ + + public Put(HttpRequestBase method) { + super("PUT"); + this.method = method; + } + + public ApiMethod body(String body){ + this.reqBody = body; + StringEntity params =new StringEntity (body,"UTF-8"); + params.setContentType("application/json"); + HttpPut put = (HttpPut) method; + put.setEntity(params); + return this; + } + +} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefclient/ChefApiClient.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefclient/ChefApiClient.java new file mode 100644 index 000000000..d7080fc12 --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefclient/ChefApiClient.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.chef.chefclient; +import org.apache.http.client.methods.*; +import org.onap.appc.adapter.chef.chefapi.*; + +public class ChefApiClient { + private String endpoint; + private String userId; + private String pemPath; + private String organizations; + + /** + * + * @param userId user name correspond to the pem key + * @param pemPath path of the auth key + * @param endpoint chef api server address + */ + public ChefApiClient(String userId, String pemPath, String endpoint,String organizations){ + this.userId = userId; + this.pemPath = pemPath; + this.endpoint = endpoint; + this.organizations=organizations; + } + + /** + * + * @param path in the endpoint. e.g /clients + * @return + */ + public Get get(String path){ + Get get = new Get(new HttpGet(endpoint+path)); + get.setPemPath(pemPath); + get.setUserId(userId); + get.setOrganizations(organizations); + get.setChefPath(path); + return get; + } + + public Put put(String path){ + Put put = new Put(new HttpPut(endpoint+path)); + put.setPemPath(pemPath); + put.setUserId(userId); + put.setOrganizations(organizations); + put.setChefPath(path); + return put; + } + public Post post(String path){ + Post post = new Post(new HttpPost(endpoint+path)); + post.setPemPath(pemPath); + post.setUserId(userId); + post.setOrganizations(organizations); + post.setChefPath(path); + return post; + } + + public Delete delete(String path){ + Delete del = new Delete(new HttpDelete(endpoint+path)); + del.setPemPath(pemPath); + del.setUserId(userId); + del.setOrganizations(organizations); + del.setChefPath(path); + return del; + } +} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefclient/Utils.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefclient/Utils.java new file mode 100644 index 000000000..71182c497 --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefclient/Utils.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.chef.chefclient; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.KeyPair; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.Security; +import java.security.Signature; +import java.security.SignatureException; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openssl.PEMParser; +import org.bouncycastle.util.encoders.Base64; +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; +import org.bouncycastle.openssl.PEMKeyPair; + +public class Utils { + private Utils(){} + + public static String sha1AndBase64(String inStr) { + MessageDigest md = null; + String outStr = null; + byte[] outbty = null; + try { + md = MessageDigest.getInstance("SHA-1"); + byte[] digest = md.digest(inStr.getBytes()); + outbty = Base64.encode(digest); + } catch (NoSuchAlgorithmException nsae) { + nsae.printStackTrace(); + } + return new String(outbty); + } + + public static String signWithRSA(String inStr, String pemPath) { + byte[] outStr = null; + try ( BufferedReader br = new BufferedReader(new FileReader(pemPath))) { + Security.addProvider(new BouncyCastleProvider()); + PEMParser pemParser = new PEMParser(br); + JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); + Object object = pemParser.readObject(); + KeyPair kp = converter.getKeyPair((PEMKeyPair) object);; + PrivateKey privateKey = kp.getPrivate(); + Signature instance = Signature.getInstance("RSA"); + instance.initSign(privateKey); + instance.update(inStr.getBytes()); + byte[] signature = instance.sign(); + outStr = Base64.encode(signature); + } catch (InvalidKeyException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (SignatureException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return new String(outStr); + } + + public static String[] splitAs60(String inStr) { + int count = inStr.length() / 60; + String[] out = new String[count + 1]; + + for (int i = 0; i < count; i++) { + String tmp = inStr.substring(i * 60, i * 60 + 60); + out[i] = tmp; + } + if (inStr.length() > count * 60) { + String tmp = inStr.substring(count * 60, inStr.length()); + out[count] = tmp; + } + return out; + } +} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/impl/ChefAdapterImpl.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/impl/ChefAdapterImpl.java new file mode 100644 index 000000000..824a6af95 --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/impl/ChefAdapterImpl.java @@ -0,0 +1,469 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.chef.impl; + +import java.io.File; +import java.util.Map; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.json.JSONObject; +import org.onap.appc.Constants; +import org.onap.appc.adapter.chef.ChefAdapter; +import org.onap.appc.adapter.chef.chefapi.ApiMethod; +import org.onap.appc.adapter.chef.chefclient.ChefApiClient; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** + * This class implements the {@link ChefAdapter} interface. This interface + * defines the behaviors that our service provides. + */ +public class ChefAdapterImpl implements ChefAdapter { + // chef server Initialize variable + private String clientName = ""; + private String clientPrivatekey = ""; + private String chefserver = ""; + private String serverAddress = ""; + private String organizations = ""; + + + /** + * The constant for the status code for a successful outcome + */ + private static final String OUTCOME_SUCCESS = "success"; + + /** + * The logger to be used + */ + private final EELFLogger logger = EELFManager.getInstance().getLogger(ChefAdapterImpl.class); + + private final String CANNOT_FIND_PRIVATE_KEY_STR = "Cannot find the private key in the APPC file system, please load the private key to "; + private final String CHEF_ACTION_STR = "org.onap.appc.instance.chefAction"; + private final String ORGANIZATIONS_STR = "/organizations/"; + /** + * A reference to the adapter configuration object. + */ + private Configuration configuration; + + /** + * This default constructor is used as a work around because the activator wasnt + * getting called + */ + public ChefAdapterImpl() { + 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 ChefAdapterImpl(boolean initialize) { + configuration = ConfigurationFactory.getConfiguration(); + if (initialize) { + initialize(); + } + } + + public ChefAdapterImpl(String key) { + initialize(key); + } + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + * @see org.onap.appc.adapter.chef.ChefAdapter#getAdapterName() + */ + @Override + public String getAdapterName() { + return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME); + } + + /** + * build node object + */ + @Override + public void nodeObejctBuilder(Map params, SvcLogicContext ctx) { + logger.info("nodeObejctBuilder"); + String name = params.get("org.onap.appc.instance.nodeobject.name"); + String normal = params.get("org.onap.appc.instance.nodeobject.normal"); + String overrides = params.get("org.onap.appc.instance.nodeobject.overrides"); + String defaults = params.get("org.onap.appc.instance.nodeobject.defaults"); + String runList = params.get("org.onap.appc.instance.nodeobject.run_list"); + String chefEnvironment = params.get("org.onap.appc.instance.nodeobject.chef_environment"); + String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults + + "},\"chef_type\":\"node\",\"run_list\":[" + runList + "],\"override\":{" + overrides + + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\"" + + chefEnvironment + "\"}"; + logger.info(nodeObject); + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setAttribute("org.onap.appc.chef.nodeObject", nodeObject); + } + + /** + * send get request to chef server + */ + public void chefInfo(Map params) { + clientName = params.get("org.onap.appc.instance.username"); + serverAddress = params.get("org.onap.appc.instance.serverAddress"); + organizations = params.get("org.onap.appc.instance.organizations"); + chefserver = "https://" + serverAddress + ORGANIZATIONS_STR + organizations; + if (params.containsKey("org.onap.appc.instance.pemPath")) { + clientPrivatekey = params.get("org.onap.appc.instance.pemPath"); + } else { + clientPrivatekey = "/opt/app/bvc/chef/" + serverAddress + "/" + organizations + "/" + clientName + ".pem"; + } + } + + public Boolean privateKeyCheck() { + File f = new File(clientPrivatekey); + return f.exists(); + } + + @Override + public void retrieveData(Map params, SvcLogicContext ctx) { + String allConfigData = params.get("org.onap.appc.instance.allConfig"); + String key = params.get("org.onap.appc.instance.key"); + String dgContext = params.get("org.onap.appc.instance.dgContext"); + JSONObject josnConfig = new JSONObject(allConfigData); + + String contextData; + try { + contextData = josnConfig.getString(key); + } catch (Exception ex) { + try { + contextData = josnConfig.getJSONObject(key).toString(); + } catch (Exception exc) { + contextData = josnConfig.getJSONArray(key).toString(); + } + } + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setAttribute(dgContext, contextData); + } + + @Override + public void combineStrings(Map params, SvcLogicContext ctx) { + + String string1 = params.get("org.onap.appc.instance.String1"); + String string2 = params.get("org.onap.appc.instance.String2"); + String dgContext = params.get("org.onap.appc.instance.dgContext"); + String contextData = string1 + string2; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setAttribute(dgContext, contextData); + } + + /** + * Send GET request to chef server + */ + @Override + public void chefGet(Map params, SvcLogicContext ctx) { + logger.info("chef get method"); + chefInfo(params); + String chefAction = params.get(CHEF_ACTION_STR); + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + int code; + String message; + if (privateKeyCheck()) { + ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); + ApiMethod am = cac.get(chefAction); + am.execute(); + code = am.getReturnCode(); + message = am.getResponseBodyAsString(); + } else { + code = 500; + message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey; + } + chefServerResult(rc, Integer.toString(code), message); + } + + /** + * Send PUT request to chef server + */ + @Override + public void chefPut(Map params, SvcLogicContext ctx) { + chefInfo(params); + String chefAction = params.get(CHEF_ACTION_STR); + String chefNodeStr = params.get("org.onap.appc.instance.chefRequestBody"); + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + int code; + String message; + if (privateKeyCheck()) { + ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); + + ApiMethod am = cac.put(chefAction).body(chefNodeStr); + am.execute(); + code = am.getReturnCode(); + message = am.getResponseBodyAsString(); + } else { + code = 500; + message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey; + } + logger.info(code + " " + message); + chefServerResult(rc, Integer.toString(code), message); + } + + /** + * send Post request to chef server + */ + @Override + public void chefPost(Map params, SvcLogicContext ctx) { + chefInfo(params); + logger.info("chef Post method"); + logger.info(clientName + " " + clientPrivatekey + " " + chefserver + " " + organizations); + String chefNodeStr = params.get("org.onap.appc.instance.chefRequestBody"); + String chefAction = params.get(CHEF_ACTION_STR); + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + int code; + String message; + // should load pem from somewhere else + if (privateKeyCheck()) { + ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); + + // need pass path into it + // "/nodes/testnode" + ApiMethod am = cac.post(chefAction).body(chefNodeStr); + am.execute(); + code = am.getReturnCode(); + message = am.getResponseBodyAsString(); + } else { + code = 500; + message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey; + } + logger.info(code + " " + message); + chefServerResult(rc, Integer.toString(code), message); + } + + /** + * send delete request to chef server + */ + @Override + public void chefDelete(Map params, SvcLogicContext ctx) { + logger.info("chef delete method"); + chefInfo(params); + String chefAction = params.get(CHEF_ACTION_STR); + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + int code; + String message; + if (privateKeyCheck()) { + ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); + ApiMethod am = cac.delete(chefAction); + am.execute(); + code = am.getReturnCode(); + message = am.getResponseBodyAsString(); + } else { + code = 500; + message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey; + } + logger.info(code + " " + message); + chefServerResult(rc, Integer.toString(code), message); + } + + /** + * Trigger target vm run chef + */ + @Override + public void trigger(Map params, SvcLogicContext ctx) { + logger.info("Run trigger method"); + String tVmIp = params.get("org.onap.appc.instance.ip"); + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + try (CloseableHttpClient httpClient = HttpClients.createDefault()) { + HttpGet httpGet = new HttpGet(tVmIp); + HttpResponse response; + response = httpClient.execute(httpGet); + int responseCode = response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String responseOutput = EntityUtils.toString(entity); + chefClientResult(rc, Integer.toString(responseCode), responseOutput); + doSuccess(rc); + } catch (Exception ex) { + doFailure(rc, 500, ex.toString()); + } + } + + @Override + public void checkPushJob(Map params, SvcLogicContext ctx) { + chefInfo(params); + String jobID = params.get("org.onap.appc.instance.jobid"); + int retryTimes = Integer.parseInt(params.get("org.onap.appc.instance.retryTimes")); + int retryInterval = Integer.parseInt(params.get("org.onap.appc.instance.retryInterval")); + String chefAction = "/pushy/jobs/" + jobID; + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + String message = ""; + String status = ""; + for (int i = 0; i < retryTimes; i++) { + try { + Thread.sleep(retryInterval); // 1000 milliseconds is one second. + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); + ApiMethod am = cac.get(chefAction); + am.execute(); + int code = am.getReturnCode(); + message = am.getResponseBodyAsString(); + JSONObject obj = new JSONObject(message); + status = obj.getString("status"); + if (!"running".equals(status)) { + logger.info(i + " time " + code + " " + status); + break; + } + + } + if ("complete".equals(status)) { + svcLogic.setAttribute("org.onap.appc.chefServerResult.code", "200"); + svcLogic.setAttribute("org.onap.appc.chefServerResult.message", message); + } else { + if ("running".equals(status)) { + svcLogic.setAttribute("org.onap.appc.chefServerResult.code", "202"); + svcLogic.setAttribute("org.onap.appc.chefServerResult.message", "chef client runtime out"); + } else { + svcLogic.setAttribute("org.onap.appc.chefServerResult.code", "500"); + svcLogic.setAttribute("org.onap.appc.chefServerResult.message", message); + } + } + } + + @Override + public void pushJob(Map params, SvcLogicContext ctx) { + chefInfo(params); + String pushRequest = params.get("org.onap.appc.instance.pushRequest"); + String chefAction = "/pushy/jobs"; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); + ApiMethod am = cac.post(chefAction).body(pushRequest); + + am.execute(); + int code = am.getReturnCode(); + String message = am.getResponseBodyAsString(); + if (code == 201) { + int startIndex = message.indexOf("jobs") + 6; + int endIndex = message.length() - 2; + String jobID = message.substring(startIndex, endIndex); + svcLogic.setAttribute("org.onap.appc.jobID", jobID); + logger.info(jobID); + } + chefServerResult(rc, Integer.toString(code), message); + } + + private void doFailure(RequestContext rc, int code, String message) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + String msg = (message == null) ? Integer.toString(code) : message; + if (msg.contains("\n")) { + msg = msg.substring(msg.indexOf("\n")); + } + + String status; + try { + status = Integer.toString(code); + } catch (Exception e) { + logger.info("Couldn't covert " + code + " to an Integer, defaulting status to 500", e); + status = "500"; + } + svcLogic.setAttribute("org.onap.appc.chefAgent.code", status); + svcLogic.setAttribute("org.onap.appc.chefAgent.message", msg); + } + + /** + * @param rc + * The request context that manages the state and recovery of the + * request for the life of its processing. + */ + private void doSuccess(RequestContext rc) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setAttribute("org.onap.appc.chefAgent.code", "200"); + } + + private void chefServerResult(RequestContext rc, String code, String message) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setStatus(OUTCOME_SUCCESS); + svcLogic.setAttribute("org.onap.appc.chefServerResult.code", code); + svcLogic.setAttribute("org.onap.appc.chefServerResult.message", message); + } + + private void chefClientResult(RequestContext rc, String code, String message) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setStatus(OUTCOME_SUCCESS); + svcLogic.setAttribute("org.onap.appc.chefClientResult.code", code); + svcLogic.setAttribute("org.onap.appc.chefClientResult.message", message); + } + + /** + * initialize the provider adapter by building the context cache + */ + private void initialize() { + configuration = ConfigurationFactory.getConfiguration(); + // need to fetch data from appc configurator or form some file in the appc vms + clientName = "testnode"; + clientPrivatekey = System.getProperty("user.dir") + "/src/test/resources/testclient.pem"; + serverAddress = "http://example.com"; + organizations = "test"; + chefserver = serverAddress + ORGANIZATIONS_STR + organizations; + logger.info("Initialize Chef Adapter"); + } + + private void initialize(String key) { + configuration = ConfigurationFactory.getConfiguration(); + // need to fetch data from appc configurator or form some file in the appc vms + clientName = "testnode"; + clientPrivatekey = key; + serverAddress = "http://example.com"; + organizations = "test"; + chefserver = serverAddress + ORGANIZATIONS_STR + organizations; + logger.info("Initialize Chef Adapter"); + } + +} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/impl/RequestContext.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/impl/RequestContext.java new file mode 100644 index 000000000..3c0e00a6a --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/impl/RequestContext.java @@ -0,0 +1,252 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.chef.impl; + +import org.onap.appc.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.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. + *

+ * 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. + *

+ * + * @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-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefActivator.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefActivator.java deleted file mode 100644 index 6c798b4b2..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefActivator.java +++ /dev/null @@ -1,144 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.chef; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.chef.impl.ChefAdapterImpl; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.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. - *

- * 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. - *

- *

- * 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. - *

- *

- * When the bundle is deactivated, the cache is torn down with all contexts being closed. - *

- */ -public class ChefActivator implements BundleActivator { - - /** - * The bundle registration - */ - private ServiceRegistration registration = null; - - /** - * The reference to the actual implementation object that implements the services - */ - private ChefAdapter adapter; - - /** - * The logger to be used - */ - private final EELFLogger logger = EELFManager.getInstance().getLogger(ChefActivator.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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @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, "chef adapter"); - adapter = new ChefAdapterImpl(); - if (registration == null) { - logger.info(Msg.REGISTERING_SERVICE, appName, adapter.getAdapterName(), - ChefAdapter.class.getSimpleName()); - registration = context.registerService(ChefAdapter.class, adapter, null); - } - - logger.info(Msg.COMPONENT_INITIALIZED, appName, "CHEF 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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @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, "CHEF adapter"); - logger.info(Msg.UNREGISTERING_SERVICE, appName, adapter.getAdapterName()); - registration.unregister(); - registration = null; - logger.info(Msg.COMPONENT_TERMINATED, appName, "CHEF adapter"); - } - } - - public String getName() { - return "APPC IaaS adapter"; - } - -} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefAdapter.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefAdapter.java deleted file mode 100644 index d11db1c14..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefAdapter.java +++ /dev/null @@ -1,220 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.chef; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import com.att.cdp.zones.model.Server; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -/** - * This interface defines the operations that the provider adapter exposes. - *

- * 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. - *

- */ -public interface ChefAdapter 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"; - - /** - * This method is used to restart an existing virtual machine given the fully qualified URL of the machine. - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 properties, SvcLogicContext context) throws APPCException; - - /** - * This method is used to stop the indicated server - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 properties, SvcLogicContext context) throws APPCException; - - /** - * This method is used to start the indicated server - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 properties, SvcLogicContext context) throws APPCException; - - /** - * This method is used to rebuild the indicated server - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 properties, SvcLogicContext context) throws APPCException; - - /** - * Returns the symbolic name of the adapter - * - * @return The adapter name - */ - String getAdapterName(); - - // Server evacuateServer(Map params, SvcLogicContext ctx) throws APPCException; - - //Server migrateServer(Map params, SvcLogicContext ctx) throws APPCException; - - void trigger(Map params, SvcLogicContext ctx) ; - - void chefGet(Map params, SvcLogicContext ctx) ; - - void chefPut(Map params, SvcLogicContext ctx) ; - - void chefPost(Map params, SvcLogicContext ctx) ; - - void chefDelete(Map params, SvcLogicContext ctx) ; - - void nodeObejctBuilder(Map params, SvcLogicContext ctx) ; - - void checkPushJob(Map params, SvcLogicContext ctx) ; - - void pushJob(Map params, SvcLogicContext ctx) ; - - void retrieveData (Map params, SvcLogicContext ctx) ; - - void combineStrings (Map params, SvcLogicContext ctx) ; - -} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/ApiMethod.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/ApiMethod.java deleted file mode 100644 index 38c4dd354..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/ApiMethod.java +++ /dev/null @@ -1,167 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.chef.chefapi; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import org.apache.http.HttpResponse; -import org.apache.http.Header; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.util.EntityUtils; -import org.onap.appc.adapter.chef.chefclient.Utils; - -import org.apache.http.HttpEntity; -import org.apache.http.impl.client.HttpClients; - -public class ApiMethod { - private HttpClient client = null; - protected HttpRequestBase method = null; - protected HttpResponse response = null; - protected String reqBody = ""; - protected String userId = ""; - protected String pemPath = ""; - protected String chefPath = ""; - protected String organizations = ""; - protected int resCode=0; - protected String responseBody=""; - private String methodName = "GET"; - public String test = ""; - private int returnCode; - - public ApiMethod(String methodName) { - client=HttpClients.createDefault(); - this.methodName = methodName; - } - - public ApiMethod createRequest(){ - String hashedPath = Utils.sha1AndBase64("/organizations/"+organizations+chefPath); - String hashedBody = Utils.sha1AndBase64(reqBody); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeStamp = sdf.format(new Date()); - timeStamp = timeStamp.replace(" ", "T"); - timeStamp = timeStamp + "Z"; - - StringBuilder sb = new StringBuilder(); - sb.append("Method:").append(methodName).append("\n"); - sb.append("Hashed Path:").append(hashedPath).append("\n"); - sb.append("X-Ops-Content-Hash:").append(hashedBody).append("\n"); - sb.append("X-Ops-Timestamp:").append(timeStamp).append("\n"); - sb.append("X-Ops-UserId:").append(userId); - test = test + "sb " + sb + "\n"; - - String auth_String = Utils.signWithRSA(sb.toString(), pemPath); - String[] auth_headers = Utils.splitAs60(auth_String); - - method.addHeader("Content-type", "application/json"); - method.addHeader("X-Ops-Timestamp", timeStamp); - method.addHeader("X-Ops-Userid", userId); - method.addHeader("X-Chef-Version", "12.4.1"); - method.addHeader("Accept", "application/json"); - method.addHeader("X-Ops-Content-Hash", hashedBody); - method.addHeader("X-Ops-Sign", "version=1.0"); - - for (int i = 0; i < auth_headers.length; i++) { - method.addHeader("X-Ops-Authorization-" + (i + 1), auth_headers[i]); - } - /* - * test=test+this.method.getMethod()+"\n"; Header[] - * RHS=this.method.getHeaders(); for (int i = 0; i < RHS.length; i++) { - * test=test+RHS[i]+"\n"; } test=test+this.reqBody+"\n"; - */ - return this; - } - - public ApiMethod execute() { - try{ - response = client.execute(method); - resCode = response.getStatusLine().getStatusCode(); - HttpEntity entity1 = response.getEntity(); - responseBody = EntityUtils.toString(entity1);} - catch(Exception ex){ - resCode=500; - responseBody=ex.getMessage(); - } - return this; - } - - public void setHeaders(Header[] headers) { - for (Header header : headers) { - this.method.addHeader(header); - } - } - - public String getResponseBodyAsString() { - return responseBody; - } - - public int getReturnCode() { - return resCode; - } - - public String getReqBody() { - return reqBody; - } - - public void setReqBody(String body) { - this.reqBody = body; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getPemPath() { - return pemPath; - } - - public void setPemPath(String pemPath) { - this.pemPath = pemPath; - } - - public String getChefPath() { - return chefPath; - } - - public void setChefPath(String chefPath) { - this.chefPath = chefPath; - } - - public String getOrganizations() { - return organizations; - } - - public void setOrganizations(String organizations) { - this.organizations = organizations; - } -} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Delete.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Delete.java deleted file mode 100644 index 5fa8a3fae..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Delete.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.chef.chefapi; - -import org.apache.http.client.methods.HttpDelete; - -public class Delete extends ApiMethod{ - - public Delete(HttpDelete method) { - super("DELETE"); - this.method = method; - } - -} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Get.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Get.java deleted file mode 100644 index da37236a7..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Get.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.chef.chefapi; - -import org.apache.http.client.methods.HttpGet; - -public class Get extends ApiMethod{ - - public Get(HttpGet method) { - super("GET"); - this.method = method; - } -} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Post.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Post.java deleted file mode 100644 index 3234eeefa..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Post.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.chef.chefapi; - -import org.apache.http.client.methods.*; -import org.apache.http.entity.StringEntity; - -public class Post extends ApiMethod{ - - public Post(HttpRequestBase method) { - super("POST"); - this.method = method; - } - - public ApiMethod body(String body){ - this.reqBody = body; - StringEntity params =new StringEntity (body,"UTF-8"); - params.setContentType("application/json"); - HttpPost post = (HttpPost) method; - post.setEntity(params); - return this; - } - -} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Put.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Put.java deleted file mode 100644 index c96fc64d1..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Put.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.chef.chefapi; - -import org.apache.http.client.methods.*; -import org.apache.http.entity.StringEntity; - -public class Put extends ApiMethod{ - - public Put(HttpRequestBase method) { - super("PUT"); - this.method = method; - } - - public ApiMethod body(String body){ - this.reqBody = body; - StringEntity params =new StringEntity (body,"UTF-8"); - params.setContentType("application/json"); - HttpPut put = (HttpPut) method; - put.setEntity(params); - return this; - } - -} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/ChefApiClient.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/ChefApiClient.java deleted file mode 100644 index d7080fc12..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/ChefApiClient.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.chef.chefclient; -import org.apache.http.client.methods.*; -import org.onap.appc.adapter.chef.chefapi.*; - -public class ChefApiClient { - private String endpoint; - private String userId; - private String pemPath; - private String organizations; - - /** - * - * @param userId user name correspond to the pem key - * @param pemPath path of the auth key - * @param endpoint chef api server address - */ - public ChefApiClient(String userId, String pemPath, String endpoint,String organizations){ - this.userId = userId; - this.pemPath = pemPath; - this.endpoint = endpoint; - this.organizations=organizations; - } - - /** - * - * @param path in the endpoint. e.g /clients - * @return - */ - public Get get(String path){ - Get get = new Get(new HttpGet(endpoint+path)); - get.setPemPath(pemPath); - get.setUserId(userId); - get.setOrganizations(organizations); - get.setChefPath(path); - return get; - } - - public Put put(String path){ - Put put = new Put(new HttpPut(endpoint+path)); - put.setPemPath(pemPath); - put.setUserId(userId); - put.setOrganizations(organizations); - put.setChefPath(path); - return put; - } - public Post post(String path){ - Post post = new Post(new HttpPost(endpoint+path)); - post.setPemPath(pemPath); - post.setUserId(userId); - post.setOrganizations(organizations); - post.setChefPath(path); - return post; - } - - public Delete delete(String path){ - Delete del = new Delete(new HttpDelete(endpoint+path)); - del.setPemPath(pemPath); - del.setUserId(userId); - del.setOrganizations(organizations); - del.setChefPath(path); - return del; - } -} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/Utils.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/Utils.java deleted file mode 100644 index 71182c497..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/Utils.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.chef.chefclient; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.Security; -import java.security.Signature; -import java.security.SignatureException; - -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.openssl.PEMParser; -import org.bouncycastle.util.encoders.Base64; -import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; -import org.bouncycastle.openssl.PEMKeyPair; - -public class Utils { - private Utils(){} - - public static String sha1AndBase64(String inStr) { - MessageDigest md = null; - String outStr = null; - byte[] outbty = null; - try { - md = MessageDigest.getInstance("SHA-1"); - byte[] digest = md.digest(inStr.getBytes()); - outbty = Base64.encode(digest); - } catch (NoSuchAlgorithmException nsae) { - nsae.printStackTrace(); - } - return new String(outbty); - } - - public static String signWithRSA(String inStr, String pemPath) { - byte[] outStr = null; - try ( BufferedReader br = new BufferedReader(new FileReader(pemPath))) { - Security.addProvider(new BouncyCastleProvider()); - PEMParser pemParser = new PEMParser(br); - JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); - Object object = pemParser.readObject(); - KeyPair kp = converter.getKeyPair((PEMKeyPair) object);; - PrivateKey privateKey = kp.getPrivate(); - Signature instance = Signature.getInstance("RSA"); - instance.initSign(privateKey); - instance.update(inStr.getBytes()); - byte[] signature = instance.sign(); - outStr = Base64.encode(signature); - } catch (InvalidKeyException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (SignatureException e) { - e.printStackTrace(); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } - return new String(outStr); - } - - public static String[] splitAs60(String inStr) { - int count = inStr.length() / 60; - String[] out = new String[count + 1]; - - for (int i = 0; i < count; i++) { - String tmp = inStr.substring(i * 60, i * 60 + 60); - out[i] = tmp; - } - if (inStr.length() > count * 60) { - String tmp = inStr.substring(count * 60, inStr.length()); - out[count] = tmp; - } - return out; - } -} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/ChefAdapterImpl.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/ChefAdapterImpl.java deleted file mode 100644 index 824a6af95..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/ChefAdapterImpl.java +++ /dev/null @@ -1,469 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.chef.impl; - -import java.io.File; -import java.util.Map; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.json.JSONObject; -import org.onap.appc.Constants; -import org.onap.appc.adapter.chef.ChefAdapter; -import org.onap.appc.adapter.chef.chefapi.ApiMethod; -import org.onap.appc.adapter.chef.chefclient.ChefApiClient; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -/** - * This class implements the {@link ChefAdapter} interface. This interface - * defines the behaviors that our service provides. - */ -public class ChefAdapterImpl implements ChefAdapter { - // chef server Initialize variable - private String clientName = ""; - private String clientPrivatekey = ""; - private String chefserver = ""; - private String serverAddress = ""; - private String organizations = ""; - - - /** - * The constant for the status code for a successful outcome - */ - private static final String OUTCOME_SUCCESS = "success"; - - /** - * The logger to be used - */ - private final EELFLogger logger = EELFManager.getInstance().getLogger(ChefAdapterImpl.class); - - private final String CANNOT_FIND_PRIVATE_KEY_STR = "Cannot find the private key in the APPC file system, please load the private key to "; - private final String CHEF_ACTION_STR = "org.onap.appc.instance.chefAction"; - private final String ORGANIZATIONS_STR = "/organizations/"; - /** - * A reference to the adapter configuration object. - */ - private Configuration configuration; - - /** - * This default constructor is used as a work around because the activator wasnt - * getting called - */ - public ChefAdapterImpl() { - 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 ChefAdapterImpl(boolean initialize) { - configuration = ConfigurationFactory.getConfiguration(); - if (initialize) { - initialize(); - } - } - - public ChefAdapterImpl(String key) { - initialize(key); - } - - /** - * Returns the symbolic name of the adapter - * - * @return The adapter name - * @see org.onap.appc.adapter.chef.ChefAdapter#getAdapterName() - */ - @Override - public String getAdapterName() { - return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME); - } - - /** - * build node object - */ - @Override - public void nodeObejctBuilder(Map params, SvcLogicContext ctx) { - logger.info("nodeObejctBuilder"); - String name = params.get("org.onap.appc.instance.nodeobject.name"); - String normal = params.get("org.onap.appc.instance.nodeobject.normal"); - String overrides = params.get("org.onap.appc.instance.nodeobject.overrides"); - String defaults = params.get("org.onap.appc.instance.nodeobject.defaults"); - String runList = params.get("org.onap.appc.instance.nodeobject.run_list"); - String chefEnvironment = params.get("org.onap.appc.instance.nodeobject.chef_environment"); - String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults - + "},\"chef_type\":\"node\",\"run_list\":[" + runList + "],\"override\":{" + overrides - + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\"" - + chefEnvironment + "\"}"; - logger.info(nodeObject); - - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - svcLogic.setAttribute("org.onap.appc.chef.nodeObject", nodeObject); - } - - /** - * send get request to chef server - */ - public void chefInfo(Map params) { - clientName = params.get("org.onap.appc.instance.username"); - serverAddress = params.get("org.onap.appc.instance.serverAddress"); - organizations = params.get("org.onap.appc.instance.organizations"); - chefserver = "https://" + serverAddress + ORGANIZATIONS_STR + organizations; - if (params.containsKey("org.onap.appc.instance.pemPath")) { - clientPrivatekey = params.get("org.onap.appc.instance.pemPath"); - } else { - clientPrivatekey = "/opt/app/bvc/chef/" + serverAddress + "/" + organizations + "/" + clientName + ".pem"; - } - } - - public Boolean privateKeyCheck() { - File f = new File(clientPrivatekey); - return f.exists(); - } - - @Override - public void retrieveData(Map params, SvcLogicContext ctx) { - String allConfigData = params.get("org.onap.appc.instance.allConfig"); - String key = params.get("org.onap.appc.instance.key"); - String dgContext = params.get("org.onap.appc.instance.dgContext"); - JSONObject josnConfig = new JSONObject(allConfigData); - - String contextData; - try { - contextData = josnConfig.getString(key); - } catch (Exception ex) { - try { - contextData = josnConfig.getJSONObject(key).toString(); - } catch (Exception exc) { - contextData = josnConfig.getJSONArray(key).toString(); - } - } - - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - svcLogic.setAttribute(dgContext, contextData); - } - - @Override - public void combineStrings(Map params, SvcLogicContext ctx) { - - String string1 = params.get("org.onap.appc.instance.String1"); - String string2 = params.get("org.onap.appc.instance.String2"); - String dgContext = params.get("org.onap.appc.instance.dgContext"); - String contextData = string1 + string2; - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - svcLogic.setAttribute(dgContext, contextData); - } - - /** - * Send GET request to chef server - */ - @Override - public void chefGet(Map params, SvcLogicContext ctx) { - logger.info("chef get method"); - chefInfo(params); - String chefAction = params.get(CHEF_ACTION_STR); - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - int code; - String message; - if (privateKeyCheck()) { - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - ApiMethod am = cac.get(chefAction); - am.execute(); - code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - } else { - code = 500; - message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey; - } - chefServerResult(rc, Integer.toString(code), message); - } - - /** - * Send PUT request to chef server - */ - @Override - public void chefPut(Map params, SvcLogicContext ctx) { - chefInfo(params); - String chefAction = params.get(CHEF_ACTION_STR); - String chefNodeStr = params.get("org.onap.appc.instance.chefRequestBody"); - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - int code; - String message; - if (privateKeyCheck()) { - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - - ApiMethod am = cac.put(chefAction).body(chefNodeStr); - am.execute(); - code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - } else { - code = 500; - message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey; - } - logger.info(code + " " + message); - chefServerResult(rc, Integer.toString(code), message); - } - - /** - * send Post request to chef server - */ - @Override - public void chefPost(Map params, SvcLogicContext ctx) { - chefInfo(params); - logger.info("chef Post method"); - logger.info(clientName + " " + clientPrivatekey + " " + chefserver + " " + organizations); - String chefNodeStr = params.get("org.onap.appc.instance.chefRequestBody"); - String chefAction = params.get(CHEF_ACTION_STR); - - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - int code; - String message; - // should load pem from somewhere else - if (privateKeyCheck()) { - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - - // need pass path into it - // "/nodes/testnode" - ApiMethod am = cac.post(chefAction).body(chefNodeStr); - am.execute(); - code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - } else { - code = 500; - message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey; - } - logger.info(code + " " + message); - chefServerResult(rc, Integer.toString(code), message); - } - - /** - * send delete request to chef server - */ - @Override - public void chefDelete(Map params, SvcLogicContext ctx) { - logger.info("chef delete method"); - chefInfo(params); - String chefAction = params.get(CHEF_ACTION_STR); - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - int code; - String message; - if (privateKeyCheck()) { - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - ApiMethod am = cac.delete(chefAction); - am.execute(); - code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - } else { - code = 500; - message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey; - } - logger.info(code + " " + message); - chefServerResult(rc, Integer.toString(code), message); - } - - /** - * Trigger target vm run chef - */ - @Override - public void trigger(Map params, SvcLogicContext ctx) { - logger.info("Run trigger method"); - String tVmIp = params.get("org.onap.appc.instance.ip"); - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpGet httpGet = new HttpGet(tVmIp); - HttpResponse response; - response = httpClient.execute(httpGet); - int responseCode = response.getStatusLine().getStatusCode(); - HttpEntity entity = response.getEntity(); - String responseOutput = EntityUtils.toString(entity); - chefClientResult(rc, Integer.toString(responseCode), responseOutput); - doSuccess(rc); - } catch (Exception ex) { - doFailure(rc, 500, ex.toString()); - } - } - - @Override - public void checkPushJob(Map params, SvcLogicContext ctx) { - chefInfo(params); - String jobID = params.get("org.onap.appc.instance.jobid"); - int retryTimes = Integer.parseInt(params.get("org.onap.appc.instance.retryTimes")); - int retryInterval = Integer.parseInt(params.get("org.onap.appc.instance.retryInterval")); - String chefAction = "/pushy/jobs/" + jobID; - - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - String message = ""; - String status = ""; - for (int i = 0; i < retryTimes; i++) { - try { - Thread.sleep(retryInterval); // 1000 milliseconds is one second. - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - ApiMethod am = cac.get(chefAction); - am.execute(); - int code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - JSONObject obj = new JSONObject(message); - status = obj.getString("status"); - if (!"running".equals(status)) { - logger.info(i + " time " + code + " " + status); - break; - } - - } - if ("complete".equals(status)) { - svcLogic.setAttribute("org.onap.appc.chefServerResult.code", "200"); - svcLogic.setAttribute("org.onap.appc.chefServerResult.message", message); - } else { - if ("running".equals(status)) { - svcLogic.setAttribute("org.onap.appc.chefServerResult.code", "202"); - svcLogic.setAttribute("org.onap.appc.chefServerResult.message", "chef client runtime out"); - } else { - svcLogic.setAttribute("org.onap.appc.chefServerResult.code", "500"); - svcLogic.setAttribute("org.onap.appc.chefServerResult.message", message); - } - } - } - - @Override - public void pushJob(Map params, SvcLogicContext ctx) { - chefInfo(params); - String pushRequest = params.get("org.onap.appc.instance.pushRequest"); - String chefAction = "/pushy/jobs"; - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - ApiMethod am = cac.post(chefAction).body(pushRequest); - - am.execute(); - int code = am.getReturnCode(); - String message = am.getResponseBodyAsString(); - if (code == 201) { - int startIndex = message.indexOf("jobs") + 6; - int endIndex = message.length() - 2; - String jobID = message.substring(startIndex, endIndex); - svcLogic.setAttribute("org.onap.appc.jobID", jobID); - logger.info(jobID); - } - chefServerResult(rc, Integer.toString(code), message); - } - - private void doFailure(RequestContext rc, int code, String message) { - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - String msg = (message == null) ? Integer.toString(code) : message; - if (msg.contains("\n")) { - msg = msg.substring(msg.indexOf("\n")); - } - - String status; - try { - status = Integer.toString(code); - } catch (Exception e) { - logger.info("Couldn't covert " + code + " to an Integer, defaulting status to 500", e); - status = "500"; - } - svcLogic.setAttribute("org.onap.appc.chefAgent.code", status); - svcLogic.setAttribute("org.onap.appc.chefAgent.message", msg); - } - - /** - * @param rc - * The request context that manages the state and recovery of the - * request for the life of its processing. - */ - private void doSuccess(RequestContext rc) { - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - svcLogic.setAttribute("org.onap.appc.chefAgent.code", "200"); - } - - private void chefServerResult(RequestContext rc, String code, String message) { - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - svcLogic.setStatus(OUTCOME_SUCCESS); - svcLogic.setAttribute("org.onap.appc.chefServerResult.code", code); - svcLogic.setAttribute("org.onap.appc.chefServerResult.message", message); - } - - private void chefClientResult(RequestContext rc, String code, String message) { - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - svcLogic.setStatus(OUTCOME_SUCCESS); - svcLogic.setAttribute("org.onap.appc.chefClientResult.code", code); - svcLogic.setAttribute("org.onap.appc.chefClientResult.message", message); - } - - /** - * initialize the provider adapter by building the context cache - */ - private void initialize() { - configuration = ConfigurationFactory.getConfiguration(); - // need to fetch data from appc configurator or form some file in the appc vms - clientName = "testnode"; - clientPrivatekey = System.getProperty("user.dir") + "/src/test/resources/testclient.pem"; - serverAddress = "http://example.com"; - organizations = "test"; - chefserver = serverAddress + ORGANIZATIONS_STR + organizations; - logger.info("Initialize Chef Adapter"); - } - - private void initialize(String key) { - configuration = ConfigurationFactory.getConfiguration(); - // need to fetch data from appc configurator or form some file in the appc vms - clientName = "testnode"; - clientPrivatekey = key; - serverAddress = "http://example.com"; - organizations = "test"; - chefserver = serverAddress + ORGANIZATIONS_STR + organizations; - logger.info("Initialize Chef Adapter"); - } - -} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/RequestContext.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/RequestContext.java deleted file mode 100644 index 3c0e00a6a..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/RequestContext.java +++ /dev/null @@ -1,252 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.chef.impl; - -import org.onap.appc.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.ccsdk.sli.core.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. - *

- * 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. - *

- * - * @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-chef-adapter/appc-chef-adapter-bundle/src/main/resources/org/onap/appc/default.properties b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..c00220dd6 --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,96 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============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/openecomp/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 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-chef-adapter/appc-chef-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index c00220dd6..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,96 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============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/openecomp/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 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-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/chefclient/TestChefApiClient.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/chefclient/TestChefApiClient.java new file mode 100644 index 000000000..5ea152a8d --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/chefclient/TestChefApiClient.java @@ -0,0 +1,107 @@ +package org.onap.appc.adapter.chef.chefclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.InputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Properties; +import java.util.TimeZone; +import java.util.regex.Pattern; + + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.adapter.chef.chefapi.ApiMethod; +import org.onap.appc.adapter.chef.chefapi.Delete; +import org.onap.appc.adapter.chef.chefapi.Get; +import org.onap.appc.adapter.chef.chefapi.Post; +import org.onap.appc.adapter.chef.chefapi.Put; + +public class TestChefApiClient { + + private ChefApiClient client; + private Properties props; + + @Before + public void setup() throws IllegalArgumentException, IllegalAccessException { + props = new Properties(); + InputStream propStr = getClass().getResourceAsStream("/test.properties"); + if (propStr == null) { + fail("src/test/resources/test.properties missing"); + } + + try { + props.load(propStr); + propStr.close(); + } catch (Exception e) { + e.printStackTrace(); + fail("Could not initialize properties"); + } + client = new ChefApiClient( + props.getProperty("org.onap.appc.adapter.chef.chefclient.userId"), + System.getProperty("user.dir") + + props.getProperty("org.onap.appc.adapter.chef.chefclient.pemPath"), + props.getProperty("org.onap.appc.adapter.chef.chefclient.endPoint"), + props.getProperty("org.onap.appc.adapter.chef.chefclient.organizations")); + } + + @Test + public void testGet(){ + Get get = client.get(props.getProperty("org.onap.appc.adapter.chef.chefclient.path")); + ApiMethod method = get.createRequest(); + String[] response = method.test.split("\n"); + + thenStringShouldMatch("GET", response); + } + + @Test + public void testPut(){ + Put put = client.put(props.getProperty("org.onap.appc.adapter.chef.chefclient.path")); + ApiMethod method = put.createRequest(); + String[] response = method.test.split("\n"); + + thenStringShouldMatch("PUT", response); + } + + @Test + public void testPost() { + Post post = client.post(props.getProperty("org.onap.appc.adapter.chef.chefclient.path")); + ApiMethod method = post.createRequest(); + String[] response = method.test.split("\n"); + + thenStringShouldMatch("POST", response); + } + + @Test + public void testDelete(){ + Delete delete = client.delete(props.getProperty("org.onap.appc.adapter.chef.chefclient.path")); + ApiMethod method = delete.createRequest(); + String[] response = method.test.split("\n"); + + thenStringShouldMatch("DELETE", response); + } + + private String timestamp(){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + String timeStamp = sdf.format(new Date()); + timeStamp = timeStamp.replace(" ", "T"); + timeStamp = timeStamp + "Z"; + return timeStamp; + } + + private void thenStringShouldMatch(String method, String[] response){ + assertEquals("sb Method:" + method, response[0]); + assertEquals("Hashed Path:+JEk1y2gXwqZRweNjXYtx4ojxW8=", response[1]); + assertEquals("X-Ops-Content-Hash:2jmj7l5rSw0yVb/vlWAYkK/YBwk=", response[2]); + String timestamp = timestamp().substring(0, timestamp().length() - 3); + String regEx = "X-Ops-Timestamp:" + + timestamp + + "..."; + assertTrue(Pattern.matches(regEx, response[3])); + assertEquals("X-Ops-UserId:test", response[4]); + } +} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/impl/TestChefAdapterImpl.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/impl/TestChefAdapterImpl.java new file mode 100644 index 000000000..687ba8338 --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/impl/TestChefAdapterImpl.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.chef.impl; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.exceptions.APPCException; +import com.att.cdp.exceptions.ZoneException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class TestChefAdapterImpl { + private SvcLogicContext svcContext; + + private ChefAdapterImpl adapter; + + private Map params; + private String getAttribute; + + @Before + public void setup() { + adapter = new ChefAdapterImpl(Boolean.TRUE); + params = new HashMap<>(); + params.put("org.onap.appc.instance.pemPath", + "/src/test/resources/testclient.pem"); + } + + @After + public void tearDown() { + params = null; + svcContext = null; + getAttribute = null; + } + + @Test + public void testChefGetFail() throws IOException, IllegalStateException, IllegalArgumentException, + ZoneException, APPCException { + params.put("org.onap.appc.instance.chefAction", "/nodes"); + + givenParams(params, "chefGet"); + thenResponseShouldFail(); + } + + @Test + public void testChefPutFail() throws IOException, IllegalStateException, IllegalArgumentException, + ZoneException, APPCException { + params.put("org.onap.appc.instance.chefAction", "/nodes/testnode"); + params.put("org.onap.appc.instance.runList", "recipe[commandtest]"); + params.put("org.onap.appc.instance.attributes", ""); + params.put("org.onap.appc.instance.chefRequestBody", "Test Body"); + + givenParams(params, "chefPut"); + thenResponseShouldFail(); + } + + @Test + public void testTriggerFail() throws IOException, IllegalStateException, IllegalArgumentException, + ZoneException, APPCException { + params.put("org.onap.appc.instance.ip", ""); + + givenParams(params, "trigger"); + thenResponseShouldFail(); + } + + private void givenParams(Map adapterParams, String method) { + svcContext = new SvcLogicContext(); + if (method == "chefGet"){ + adapter.chefGet(adapterParams, svcContext); + getAttribute = "org.onap.appc.chefServerResult.code"; + } + if (method == "chefPut"){ + adapter.chefPut(adapterParams, svcContext); + getAttribute = "org.onap.appc.chefServerResult.code"; + } + if (method == "trigger"){ + adapter.trigger(adapterParams, svcContext); + getAttribute = "org.onap.appc.chefAgent.code"; + } + } + + private void thenResponseShouldFail(){ + String status = svcContext.getAttribute(this.getAttribute); + assertEquals("500", status); + } +} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java new file mode 100644 index 000000000..13b5fdfb3 --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java @@ -0,0 +1,182 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.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.onap.appc.test.InterceptLogger; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.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 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: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • + *
  • 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
  • + *
+ * @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: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • + *
  • 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
  • + *
+ * @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 getExecMethodNames() { + List 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-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java new file mode 100644 index 000000000..b101ecee4 --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java @@ -0,0 +1,454 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.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 events; + + /** + * Create the intercept logger + */ + public InterceptLogger() { + events = new ArrayList(1000); + } + + /** + * @return Returns all intercepted log events + */ + public List 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-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/adapter/chef/chefclient/TestChefApiClient.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/adapter/chef/chefclient/TestChefApiClient.java deleted file mode 100644 index 5ea152a8d..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/adapter/chef/chefclient/TestChefApiClient.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.onap.appc.adapter.chef.chefclient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.InputStream; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Properties; -import java.util.TimeZone; -import java.util.regex.Pattern; - - -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.adapter.chef.chefapi.ApiMethod; -import org.onap.appc.adapter.chef.chefapi.Delete; -import org.onap.appc.adapter.chef.chefapi.Get; -import org.onap.appc.adapter.chef.chefapi.Post; -import org.onap.appc.adapter.chef.chefapi.Put; - -public class TestChefApiClient { - - private ChefApiClient client; - private Properties props; - - @Before - public void setup() throws IllegalArgumentException, IllegalAccessException { - props = new Properties(); - InputStream propStr = getClass().getResourceAsStream("/test.properties"); - if (propStr == null) { - fail("src/test/resources/test.properties missing"); - } - - try { - props.load(propStr); - propStr.close(); - } catch (Exception e) { - e.printStackTrace(); - fail("Could not initialize properties"); - } - client = new ChefApiClient( - props.getProperty("org.onap.appc.adapter.chef.chefclient.userId"), - System.getProperty("user.dir") + - props.getProperty("org.onap.appc.adapter.chef.chefclient.pemPath"), - props.getProperty("org.onap.appc.adapter.chef.chefclient.endPoint"), - props.getProperty("org.onap.appc.adapter.chef.chefclient.organizations")); - } - - @Test - public void testGet(){ - Get get = client.get(props.getProperty("org.onap.appc.adapter.chef.chefclient.path")); - ApiMethod method = get.createRequest(); - String[] response = method.test.split("\n"); - - thenStringShouldMatch("GET", response); - } - - @Test - public void testPut(){ - Put put = client.put(props.getProperty("org.onap.appc.adapter.chef.chefclient.path")); - ApiMethod method = put.createRequest(); - String[] response = method.test.split("\n"); - - thenStringShouldMatch("PUT", response); - } - - @Test - public void testPost() { - Post post = client.post(props.getProperty("org.onap.appc.adapter.chef.chefclient.path")); - ApiMethod method = post.createRequest(); - String[] response = method.test.split("\n"); - - thenStringShouldMatch("POST", response); - } - - @Test - public void testDelete(){ - Delete delete = client.delete(props.getProperty("org.onap.appc.adapter.chef.chefclient.path")); - ApiMethod method = delete.createRequest(); - String[] response = method.test.split("\n"); - - thenStringShouldMatch("DELETE", response); - } - - private String timestamp(){ - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeStamp = sdf.format(new Date()); - timeStamp = timeStamp.replace(" ", "T"); - timeStamp = timeStamp + "Z"; - return timeStamp; - } - - private void thenStringShouldMatch(String method, String[] response){ - assertEquals("sb Method:" + method, response[0]); - assertEquals("Hashed Path:+JEk1y2gXwqZRweNjXYtx4ojxW8=", response[1]); - assertEquals("X-Ops-Content-Hash:2jmj7l5rSw0yVb/vlWAYkK/YBwk=", response[2]); - String timestamp = timestamp().substring(0, timestamp().length() - 3); - String regEx = "X-Ops-Timestamp:" + - timestamp + - "..."; - assertTrue(Pattern.matches(regEx, response[3])); - assertEquals("X-Ops-UserId:test", response[4]); - } -} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/adapter/chef/impl/TestChefAdapterImpl.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/adapter/chef/impl/TestChefAdapterImpl.java deleted file mode 100644 index 687ba8338..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/adapter/chef/impl/TestChefAdapterImpl.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.chef.impl; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.exceptions.APPCException; -import com.att.cdp.exceptions.ZoneException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class TestChefAdapterImpl { - private SvcLogicContext svcContext; - - private ChefAdapterImpl adapter; - - private Map params; - private String getAttribute; - - @Before - public void setup() { - adapter = new ChefAdapterImpl(Boolean.TRUE); - params = new HashMap<>(); - params.put("org.onap.appc.instance.pemPath", - "/src/test/resources/testclient.pem"); - } - - @After - public void tearDown() { - params = null; - svcContext = null; - getAttribute = null; - } - - @Test - public void testChefGetFail() throws IOException, IllegalStateException, IllegalArgumentException, - ZoneException, APPCException { - params.put("org.onap.appc.instance.chefAction", "/nodes"); - - givenParams(params, "chefGet"); - thenResponseShouldFail(); - } - - @Test - public void testChefPutFail() throws IOException, IllegalStateException, IllegalArgumentException, - ZoneException, APPCException { - params.put("org.onap.appc.instance.chefAction", "/nodes/testnode"); - params.put("org.onap.appc.instance.runList", "recipe[commandtest]"); - params.put("org.onap.appc.instance.attributes", ""); - params.put("org.onap.appc.instance.chefRequestBody", "Test Body"); - - givenParams(params, "chefPut"); - thenResponseShouldFail(); - } - - @Test - public void testTriggerFail() throws IOException, IllegalStateException, IllegalArgumentException, - ZoneException, APPCException { - params.put("org.onap.appc.instance.ip", ""); - - givenParams(params, "trigger"); - thenResponseShouldFail(); - } - - private void givenParams(Map adapterParams, String method) { - svcContext = new SvcLogicContext(); - if (method == "chefGet"){ - adapter.chefGet(adapterParams, svcContext); - getAttribute = "org.onap.appc.chefServerResult.code"; - } - if (method == "chefPut"){ - adapter.chefPut(adapterParams, svcContext); - getAttribute = "org.onap.appc.chefServerResult.code"; - } - if (method == "trigger"){ - adapter.trigger(adapterParams, svcContext); - getAttribute = "org.onap.appc.chefAgent.code"; - } - } - - private void thenResponseShouldFail(){ - String status = svcContext.getAttribute(this.getAttribute); - assertEquals("500", status); - } -} diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java deleted file mode 100644 index 13b5fdfb3..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java +++ /dev/null @@ -1,182 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.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.onap.appc.test.InterceptLogger; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.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 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: - *
    - *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • - *
  • 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
  • - *
- * @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: - *
    - *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • - *
  • 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
  • - *
- * @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 getExecMethodNames() { - List 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-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java deleted file mode 100644 index b101ecee4..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java +++ /dev/null @@ -1,454 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.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 events; - - /** - * Create the intercept logger - */ - public InterceptLogger() { - events = new ArrayList(1000); - } - - /** - * @return Returns all intercepted log events - */ - public List 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-chef-adapter/appc-chef-adapter-bundle/src/test/resources/org/onap/appc/default.properties b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..bb888132a --- /dev/null +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,111 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============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/openecomp/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 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 + +# 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 + diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties deleted file mode 100644 index bb888132a..000000000 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,111 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============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/openecomp/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 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 - -# 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 - diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/AppcDmaapAdapterActivator.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/AppcDmaapAdapterActivator.java new file mode 100644 index 000000000..812f80121 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/AppcDmaapAdapterActivator.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap; + +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. + *

+ * 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. + *

+ *

+ * 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. + *

+ *

+ * When the bundle is deactivated, the cache is torn down with all contexts being closed. + *

+ */ +public class AppcDmaapAdapterActivator implements BundleActivator { + private ServiceRegistration registration = null; + + /** + * The logger to be used + */ + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(AppcDmaapAdapterActivator.class); + + /** + * 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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @param bundleContext + * 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(final BundleContext bundleContext) throws Exception { + LOG.info("Starting Bundle " + getName()); + } + + /** + * 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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @param ctx + * 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 ctx) throws Exception { + LOG.info("Stopped Bundle " + getName()); + } + + public String getName() { + return "DMaaP Adapter"; + } + +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/http/CommonHttpClient.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/http/CommonHttpClient.java new file mode 100644 index 000000000..76b050d8e --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/http/CommonHttpClient.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap.http; + +import java.net.URI; + +import org.apache.commons.codec.binary.Base64; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.config.RequestConfig.Builder; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; + +public class CommonHttpClient { + + public static final int HTTPS_PORT = 3905; + + private String AUTH_STR; + + protected void setBasicAuth(String username, String password) { + if (username != null && password != null) { + String plain = String.format("%s:%s", username, password); + AUTH_STR = Base64.encodeBase64String(plain.getBytes()); + } else { + AUTH_STR = null; + } + } + + public HttpGet getReq(URI uri, int timeoutMs) throws Exception { + HttpGet out = (uri == null) ? new HttpGet() : new HttpGet(uri); + if (AUTH_STR != null) { + out.setHeader("Authorization", String.format("Basic %s", AUTH_STR)); + } + out.setConfig(getConfig(timeoutMs)); + return out; + } + + public HttpPost postReq(String url) throws Exception { + HttpPost out = (url == null) ? new HttpPost() : new HttpPost(url); + if (AUTH_STR != null) { + out.setHeader("Authorization", String.format("Basic %s", AUTH_STR)); + } + out.setConfig(getConfig(0)); + return out; + } + + private RequestConfig getConfig(int timeoutMs) { + Builder builder = RequestConfig.custom(); + builder.setSocketTimeout(timeoutMs + 5000); + return builder.build(); + } + + public CloseableHttpClient getClient() { + return getClient(false); + } + + public CloseableHttpClient getClient(boolean useHttps) { + return HttpClientBuilder.create().build(); + } + + public String formatHostString(String host) { + return formatHostString(host, host.contains(String.valueOf(HTTPS_PORT))); + } + + public String formatHostString(String host, boolean useHttps) { + // Trim trailing slash + String out = host.endsWith("/") ? host.substring(0, host.length() - 1) : host; + + boolean hasProto = out.startsWith("http"); + boolean hasPort = out.contains(":"); + + // Add protocol + if (!hasProto) { + out = String.format("%s%s", (useHttps) ? "https://" : "http://", out); + } + + // Add port + if (!hasPort) { + out = String.format("%s:%d", out, (useHttps) ? 3905 : 3904); + } + + return out; + + } +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/http/HttpDmaapConsumerImpl.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/http/HttpDmaapConsumerImpl.java new file mode 100644 index 000000000..df81e9718 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/http/HttpDmaapConsumerImpl.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap.http; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.json.JSONArray; +import org.onap.appc.adapter.message.Consumer; + +public class HttpDmaapConsumerImpl extends CommonHttpClient implements Consumer { + + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(HttpDmaapConsumerImpl.class); + + // Default values + private static final int DEFAULT_TIMEOUT_MS = 15000; + private static final int DEFAULT_LIMIT = 1000; + private static final String HTTPS_PORT = ":3905"; + private static final String URL_TEMPLATE = "%s/events/%s/%s/%s"; + + private List urls; + private String filter; + + private boolean useHttps = false; + + public HttpDmaapConsumerImpl(Collection hosts, String topicName, String consumerName, String consumerId) { + this(hosts, topicName, consumerName, consumerId, null); + } + + public HttpDmaapConsumerImpl(Collection hosts, String topicName, String consumerName, String consumerId, + String filter) { + this(hosts, topicName, consumerName, consumerId, filter, null, null); + } + + public HttpDmaapConsumerImpl(Collection hosts, String topicName, String consumerName, String consumerId, + String filter, String user, String password) { + urls = new ArrayList(); + for (String host : hosts) { + urls.add(String.format(URL_TEMPLATE, formatHostString(host), topicName, consumerName, consumerId)); + } + this.filter = filter; + updateCredentials(user, password); + } + + @Override + public void updateCredentials(String user, String pass) { + LOG.debug(String.format("Setting auth to %s for %s", user, this.toString())); + this.setBasicAuth(user, pass); + } + + @Override + public List fetch(int waitMs, int limit) { + LOG.debug(String.format("Fetching up to %d records with %dms wait on %s", limit, waitMs, this.toString())); + List out = new ArrayList(); + try { + List urlParams = new ArrayList(); + urlParams.add(new BasicNameValuePair("timeout", String.valueOf(waitMs))); + urlParams.add(new BasicNameValuePair("limit", String.valueOf(limit))); + if (filter != null) { + urlParams.add(new BasicNameValuePair("filter", filter)); + } + + URIBuilder builder = new URIBuilder(urls.get(0)); + builder.setParameters(urlParams); + + URI uri = builder.build(); + LOG.info(String.format("GET %s", uri)); + HttpGet request = getReq(uri, waitMs); + CloseableHttpResponse response = getClient().execute(request); + + int httpStatus = response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String body = (entity != null) ? EntityUtils.toString(entity) : null; + + LOG.debug(String.format("Request to %s completed with status %d and a body size of %s", uri, httpStatus, + (body != null ? body.length() : "null"))); + + response.close(); + if (httpStatus == 200 && body != null) { + JSONArray json = new JSONArray(body); + LOG.info(String.format("Got %d messages from DMaaP", json.length())); + for (int i = 0; i < json.length(); i++) { + out.add(json.getString(i)); + } + } else { + LOG.error(String.format("Did not get 200 from DMaaP. Got %d - %s", httpStatus, body)); + sleep(waitMs); + } + } catch (Exception e) { + if (urls.size() > 1) { + String failedUrl = urls.remove(0); + urls.add(failedUrl); + LOG.debug(String.format("Moving host %s to the end of the pool. New primary host is %s", failedUrl, + urls.get(0))); + } + LOG.error(String.format("Got exception while querying DMaaP. Message: %s", e.getMessage()), e); + sleep(waitMs); + } + + return out; + } + + @Override + public List fetch() { + return fetch(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT); + } + + @Override + public String toString() { + String hostStr = (urls == null || urls.isEmpty()) ? "N/A" : urls.get(0); + return String.format("Consumer listening to [%s]", hostStr); + } + + @Override + public void useHttps(boolean yes) { + useHttps = yes; + } + + private void sleep(int ms) { + LOG.info(String.format("Sleeping for %ds after failed request", ms / 1000)); + try { + Thread.sleep(ms); + } catch (InterruptedException e1) { + LOG.error("Interrupted while sleeping"); + } + } + + @Override + public void close() { + // Nothing to do + } + +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/http/HttpDmaapProducerImpl.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/http/HttpDmaapProducerImpl.java new file mode 100644 index 000000000..560c09be4 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/http/HttpDmaapProducerImpl.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap.http; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.onap.appc.adapter.message.Producer; + +public class HttpDmaapProducerImpl extends CommonHttpClient implements Producer { + + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(HttpDmaapProducerImpl.class); + + private static final String CONTENT_TYPE = "application/cambria"; + private static final String URL_TEMPLATE = "%s/events/%s"; + + private List hosts; + private Set topics; + + private boolean useHttps = false; + + public HttpDmaapProducerImpl(Collection urls, String topicName) { + hosts = new ArrayList(); + topics = new HashSet(); + topics.add(topicName); + + for (String host : urls) { + hosts.add(formatHostString(host)); + } + } + + public HttpDmaapProducerImpl(Collection urls, Set topicNames) { + hosts = new ArrayList(); + topics = topicNames; + + for (String host : urls) { + hosts.add(formatHostString(host)); + } + } + + @Override + public void updateCredentials(String user, String pass) { + LOG.debug(String.format("Setting auth to %s for %s", user, this.toString())); + this.setBasicAuth(user, pass); + } + + @Override + public boolean post(String partition, String data) { + int sent = 0; + try { + HttpPost request = postReq(null); + request.setHeader("Content-Type", CONTENT_TYPE); + request.setEntity(new StringEntity(bodyLine(partition, data))); + + for (String topic : topics) { + String uriStr = String.format(URL_TEMPLATE, hosts.get(0), topic); + try { + request.setURI(new URI(uriStr)); + CloseableHttpResponse response = getClient().execute(request); + if (response.getStatusLine().getStatusCode() == 200) { + sent++; + } + response.close(); + } catch (Exception sendEx) { + LOG.error(String.format("Failed to send message to %s. Reason: %s", uriStr, sendEx.getMessage()), + sendEx); + if (hosts.size() > 1) { + String failedUrl = hosts.remove(0); + hosts.add(failedUrl); + LOG.debug(String.format("Moving host %s to the end of the pool. New primary host is %s", + failedUrl, hosts.get(0))); + } + } + } + } catch (Exception buildEx) { + LOG.error( + String.format("Failed to build request with string [%s]. Message not sent to any topic. Reason: %s", + data, buildEx.getMessage()), + buildEx); + } + return sent == topics.size(); + } + + @Override + public void useHttps(boolean yes) { + useHttps = yes; + } + + /** + * Format the body for the application/cambria content type with no partitioning. See + * + * @param msg + * The message body to format + * @return A string in the application/cambria content type + */ + private String bodyLine(String partition, String msg) { + String p = (partition == null) ? "" : partition; + String m = (msg == null) ? "" : msg; + return String.format("%d.%d.%s%s", p.length(), m.length(), p, m); + } + + @Override + public void close() { + // Nothing to do + } +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/DmaapConsumerImpl.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/DmaapConsumerImpl.java new file mode 100644 index 000000000..ddf630545 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/DmaapConsumerImpl.java @@ -0,0 +1,234 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap.impl; + +import java.io.IOException; +import java.util.*; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +//import com.att.nsa.cambria.client.CambriaClientBuilders; +//import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder; +//import com.att.nsa.cambria.client.CambriaConsumer; + +import com.att.nsa.mr.client.MRClientFactory; +import com.att.nsa.mr.client.MRConsumer; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.adapter.message.Consumer; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.metricservice.MetricRegistry; +import org.onap.appc.metricservice.MetricService; +import org.onap.appc.metricservice.impl.MetricServiceImpl; +import org.onap.appc.metricservice.metric.Metric; +import org.onap.appc.metricservice.metric.MetricType; +import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric; +import org.onap.appc.metricservice.policy.PublishingPolicy; +import org.onap.appc.metricservice.publisher.LogPublisher; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +public class DmaapConsumerImpl implements Consumer { + + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(DmaapConsumerImpl.class); + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + // Default values + private static final int DEFAULT_TIMEOUT_MS = 60000; + private static final int DEFAULT_LIMIT = 1000; + private static MetricRegistry metricRegistry; + private String topic; + private DmaapRequestCounterMetric dmaapKpiMetric; + private boolean isMetricEnabled=false; + private boolean useHttps = false; + private MRConsumer client = null; + private Properties props = null; + + + public DmaapConsumerImpl(Collection urls, String topicName, String consumerGroupName, String consumerId,String user, String password) { + this(urls, topicName, consumerGroupName, consumerId,user, password,null); + + } + + public DmaapConsumerImpl(Collection urls, String topicName, String consumerGroupName, String consumerId,String user, String password,String filter) { + this.topic = topicName; + this.props = new Properties(); + String urlsStr = StringUtils.join(urls, ','); + props.setProperty("host",urlsStr); + props.setProperty("group",consumerGroupName); + props.setProperty("id",consumerId); + props.setProperty("username",user); + props.setProperty("password",password); + if(filter != null) { + props.setProperty("filter", filter); + } + } + + + private void initMetric() { + LOG.debug("Metric getting initialized"); + MetricService metricService = getMetricservice(); + metricRegistry = metricService.createRegistry("APPC"); + dmaapKpiMetric = metricRegistry.metricBuilderFactory(). + dmaapRequestCounterBuilder(). + withName("DMAAP_KPI").withType(MetricType.COUNTER). + withRecievedMessage(0) + .withPublishedMessage(0) + .build(); + if (metricRegistry.register(dmaapKpiMetric)) { + Metric[] metrics = new Metric[]{dmaapKpiMetric}; + LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics); + LogPublisher[] logPublishers = new LogPublisher[1]; + logPublishers[0] = logPublisher; + PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory(). + scheduledPolicyBuilder().withPublishers(logPublishers). + withMetrics(metrics). + build(); + LOG.debug("Policy getting initialized"); + manuallyScheduledPublishingPolicy.init(); + LOG.debug("Metric initialized"); + } + } + private MRConsumer getClient() { + return getClient(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT); + } + + /** + * @return An instance of MRConsumer created from our class variables + */ + private synchronized MRConsumer getClient(int waitMs, int limit) { + try { + props.setProperty("timeout",String.valueOf(waitMs)); + props.setProperty("limit",String.valueOf(limit)); + String topicProducerPropFileName = DmaapUtil.createConsumerPropFile(topic,props); + return MRClientFactory.createConsumer ( topicProducerPropFileName); + } catch (IOException e1) { + LOG.error("failed to createConsumer",e1); + return null; + } + } + + @Override + public synchronized void updateCredentials(String key, String secret) { + LOG.info(String.format("Setting auth to %s for %s", key, this.toString())); + String user = key; + String password = secret; + props.setProperty("user",String.valueOf(user)); + props.setProperty("password",String.valueOf(password)); + client = null; + } + + @Override + public List fetch(int waitMs, int limit) { + Properties properties=configuration.getProperties(); + if(properties!=null && properties.getProperty("metric.enabled")!=null ){ + isMetricEnabled=Boolean.valueOf(properties.getProperty("metric.enabled")); + } + if(isMetricEnabled){ + initMetric(); + } + LOG.debug(String.format("Fetching up to %d records with %dms wait on %s", limit, waitMs, this.toString())); + List out = new ArrayList(); + + // Create client once and reuse it on subsequent fetches. This is + // to support failover to other servers in the DMaaP cluster. + if (client == null) { + LOG.info("Getting DMaaP Client ..."); + client = getClient(waitMs, limit); + } + try { + for (String s : client.fetch(waitMs, limit)) { + out.add(s); + if(isMetricEnabled){ + ((DmaapRequestCounterMetric)metricRegistry.metric("DMAAP_KPI")).incrementRecievedMessage(); + } + } + LOG.debug(String.format("Got %d records from %s", out.size(), this.toString())); + } catch (Exception e) { + // Connection exception + LOG.error(String.format("Dmaap Connection Issue Detected. %s", e.getMessage())); + e.printStackTrace(); + try { + LOG.warn(String.format("Sleeping for %dms to compensate for connection failure", waitMs)); + Thread.sleep(waitMs); + } catch (InterruptedException e2) { + LOG.warn(String.format("Failed to wait for %dms after bad fetch", waitMs)); + } + } + + + return out; + } + + /** + * Close consumer Dmaap client + */ + @Override + public void close() { + LOG.debug("Closing Dmaap consumer client...."); + if (client != null) { + client.close(); + } + } + + @Override + public List fetch() { + return fetch(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT); + } + + @Override + public String toString() { + String hostStr = (props == null || props.getProperty("host") == null? "N/A" : props.getProperty("host")); + String group = (props == null || props.getProperty("group") == null? "N/A" : props.getProperty("group")); + String id = (props == null || props.getProperty("id") == null? "N/A" : props.getProperty("id")); + return String.format("Consumer %s/%s listening to %s on [%s]", group, id, topic, hostStr); + } + + @Override + public void useHttps(boolean yes) { + useHttps = yes; + } + + + private MetricService getMetricservice() { + BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext(); + // Get AAIadapter reference + ServiceReference sref = bctx.getServiceReference(MetricService.class.getName()); + if (sref != null) { + LOG.info("Metric Service from bundlecontext"); + return (MetricServiceImpl) bctx.getService(sref); + + } else { + LOG.info("Metric Service error from bundlecontext"); + LOG.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService"); + return null; + + } + } + + public Metric getMetric(String name){ + return metricRegistry.metric(name); + } +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/DmaapProducerImpl.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/DmaapProducerImpl.java new file mode 100644 index 000000000..7ed06a9e3 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/DmaapProducerImpl.java @@ -0,0 +1,223 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap.impl; + +import java.io.*; +import java.util.*; +import java.util.concurrent.TimeUnit; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +//import com.att.nsa.cambria.client.CambriaBatchingPublisher; +//import com.att.nsa.cambria.client.CambriaClientBuilders; +//import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; + +import com.att.nsa.mr.client.MRBatchingPublisher; +import com.att.nsa.mr.client.MRClientFactory; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.adapter.message.Producer; +import org.onap.appc.adapter.messaging.dmaap.impl.DmaapUtil; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.metricservice.MetricRegistry; +import org.onap.appc.metricservice.MetricService; +import org.onap.appc.metricservice.metric.Metric; +import org.onap.appc.metricservice.metric.MetricType; +import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric; +import org.onap.appc.metricservice.policy.PublishingPolicy; +import org.onap.appc.metricservice.publisher.LogPublisher; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +public class DmaapProducerImpl implements Producer { + + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(DmaapProducerImpl.class); + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + private Set topics = new HashSet(); + + private Properties props = null; + private static MetricRegistry metricRegistry; + private boolean useHttps = false; + private DmaapRequestCounterMetric dmaapKpiMetric; + private boolean isMetricEnabled=false; + + private Set clients; + + + public DmaapProducerImpl(Collection urls, String topicName, String user, String password) { + this(urls, (Set)null, user, password); + this.topics = new HashSet<>(); + if (topicName != null) { + for (String topic : topicName.split(",")) { + topics.add(topic); + } + } + } + + public DmaapProducerImpl(Collection urls, Set topicNames, String user, String password) { + topics = topicNames; + if(urls == null || user == null || password == null){ + throw new IllegalArgumentException("one of these mandaory argument is null: urls, user, password" ); + } + this.props = new Properties(); + String urlsStr = StringUtils.join(urls, ','); + props.setProperty("host",urlsStr); + props.setProperty("id", UUID.randomUUID().toString()); + props.setProperty("username",user); + props.setProperty("password",password); + } + private void initMetric() { + LOG.debug("Metric getting initialized"); + MetricService metricService = getMetricservice(); + metricRegistry=metricService.createRegistry("APPC"); + dmaapKpiMetric = metricRegistry.metricBuilderFactory(). + dmaapRequestCounterBuilder(). + withName("DMAAP_KPI").withType(MetricType.COUNTER). + withRecievedMessage(0) + .withPublishedMessage(0) + .build(); + if(metricRegistry.register(dmaapKpiMetric)) { + Metric[] metrics = new Metric[]{dmaapKpiMetric}; + LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics); + LogPublisher[] logPublishers = new LogPublisher[1]; + logPublishers[0] = logPublisher; + PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory(). + scheduledPolicyBuilder().withPublishers(logPublishers). + withMetrics(metrics). + build(); + LOG.debug("Policy getting initialized"); + manuallyScheduledPublishingPolicy.init(); + LOG.debug("Metric initialized"); + } + + } + private Set getClients() { + Set out = new HashSet(); + for (String topic : topics) { + try { + String topicProducerPropFileName = DmaapUtil.createProducerPropFile(topic,props); + final MRBatchingPublisher client = MRClientFactory.createBatchingPublisher (topicProducerPropFileName); + out.add(client); + } catch (Exception e) { + e.printStackTrace(); + } + } + + return out; + } + + @Override + public synchronized void updateCredentials(String key, String secret) { + LOG.info(String.format("Setting auth to %s for %s", key, this.toString())); + String user = key; + String password = secret; + props.setProperty("user",String.valueOf(user)); + props.setProperty("password",String.valueOf(password)); + clients = null; + } + + @Override + public boolean post(String partition, String data) { + boolean success = true; + Properties properties=configuration.getProperties(); + if(properties!=null && properties.getProperty("metric.enabled")!=null ){ + isMetricEnabled=Boolean.valueOf(properties.getProperty("metric.enabled")); + } + if(isMetricEnabled){ + initMetric(); + } + + // Create clients once and reuse them on subsequent posts. This is + // to support failover to other servers in the Dmaap cluster. + if ((clients == null) || (clients.isEmpty())) { + LOG.info("Getting CambriaBatchingPublisher Clients ..."); + clients = getClients(); + } + + for (MRBatchingPublisher client : clients) { + try { + LOG.debug(String.format("Posting %s to %s", data, client)); + client.send(partition, data); + } catch (IOException e) { + e.printStackTrace(); + success = false; + } + } + if(isMetricEnabled){ + ( (DmaapRequestCounterMetric) metricRegistry.metric("DMAAP_KPI")).incrementPublishedMessage(); + } + return success; + } + + /** + * Close producer Dmaap client + */ + @Override + public void close() { + if ((clients == null) || (clients.isEmpty())) { + return; + } + + LOG.debug("Closing Dmaap producer clients...."); + for (MRBatchingPublisher client : clients) { + try { + client.close(1, TimeUnit.SECONDS); + } catch (IOException | InterruptedException e) { + LOG.warn(String.format("Failed to cleanly close Dmaap connection for [%s]", client)); + e.printStackTrace(); + } + } + } + + @Override + public void useHttps(boolean yes) { + useHttps = yes; + } + + private MetricService getMetricservice() { +/* + return AppcDmaapAdapterActivator.getMetricService(); +*/ + + BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext(); + ServiceReference sref = bctx.getServiceReference(MetricService.class.getName()); + if (sref != null) { + LOG.info("Metric Service from bundlecontext"); + return (MetricService) bctx.getService(sref); + + } else { + LOG.info("Metric Service error from bundlecontext"); + LOG.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService"); + return null; + + } + } + + public Metric getMetric(String name){ + return metricRegistry.metric(name); + } +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/DmaapUtil.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/DmaapUtil.java new file mode 100644 index 000000000..da1b0fa38 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/DmaapUtil.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap.impl; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +public class DmaapUtil { + private final static String delimiter = "_"; + private static String createPreferredRouteFileIfNotExist(String topic) throws IOException { + String topicPreferredRouteFileName = null; + topicPreferredRouteFileName = topic+"preferredRoute.properties"; + File fo= new File(topicPreferredRouteFileName); + if(!fo.exists()) { + ClassLoader classLoader = DmaapUtil.class.getClassLoader(); + InputStream inputStream = classLoader.getResourceAsStream("preferredRoute.txt"); + Properties props = new Properties(); + props.load(inputStream); + String fileName = topic != null ? topic+delimiter+"MR1" : delimiter+"MR1"; + props.setProperty("preferredRouteKey", fileName); + topicPreferredRouteFileName = topic + "preferredRoute.properties"; + props.store(new FileOutputStream(topicPreferredRouteFileName), "preferredRoute.properties file created on the fly for topic:" + topic + " on:" + System.currentTimeMillis()); + } + return topicPreferredRouteFileName; + } + + public static String createConsumerPropFile(String topic, Properties props)throws IOException { + String defaultProfFileName = "consumer.properties"; + String topicConsumerPropFileName = createConsumerProducerPropFile(topic, defaultProfFileName,props); + return topicConsumerPropFileName; + } + + public static String createProducerPropFile(String topic, Properties props)throws IOException { + String defaultProfFileName = "producer.properties"; + String topicConsumerPropFileName = createConsumerProducerPropFile(topic, defaultProfFileName,props); + return topicConsumerPropFileName; + } + + private static String createConsumerProducerPropFile(String topic, String defaultProfFileName, Properties props) throws IOException { + ClassLoader classLoader = DmaapUtil.class.getClassLoader(); + InputStream inputStream = classLoader.getResourceAsStream(defaultProfFileName); + Properties defaultProps = new Properties(); + defaultProps.load(inputStream); + defaultProps.setProperty("topic",topic); + + String preferredRouteFileName = DmaapUtil.createPreferredRouteFileIfNotExist(topic); + if(props != null && !props.isEmpty()){ + defaultProps.putAll(props); + } + defaultProps.setProperty("topic",topic); + defaultProps.setProperty("DME2preferredRouterFilePath",preferredRouteFileName); + String id = defaultProps.getProperty("id"); + String topicConsumerPropFileName = defaultProfFileName; + topicConsumerPropFileName = id != null ? id+delimiter+topicConsumerPropFileName : delimiter+topicConsumerPropFileName; + topicConsumerPropFileName = topic != null ? topic+delimiter+topicConsumerPropFileName : delimiter+topicConsumerPropFileName; + + defaultProps.store(new FileOutputStream(topicConsumerPropFileName), defaultProfFileName+" file created on the fly for topic:"+topic+" on:"+System.currentTimeMillis()); + return topicConsumerPropFileName; + } + +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/EventSenderDmaapImpl.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/EventSenderDmaapImpl.java new file mode 100644 index 000000000..bf7649026 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/onap/appc/adapter/messaging/dmaap/impl/EventSenderDmaapImpl.java @@ -0,0 +1,178 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +import org.onap.appc.adapter.message.EventSender; +import org.onap.appc.adapter.message.MessageDestination; +import org.onap.appc.adapter.message.Producer; +import org.onap.appc.adapter.message.event.EventHeader; +import org.onap.appc.adapter.message.event.EventMessage; +import org.onap.appc.adapter.message.event.EventStatus; +import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; + +public class EventSenderDmaapImpl implements EventSender +{ + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(EventSenderDmaapImpl.class); + public static final String EVENT_TOPIC_WRITE = "dmaap.event.topic.write"; + public static final String DMAAP_USERNAME = "dmaap.appc.username"; + public static final String DMAAP_PASSWORD = "dmaap.appc.password"; + public static final String EVENT_POOL_MEMBERS = "dmaap.event.pool.members"; + + private static Configuration configuration = ConfigurationFactory.getConfiguration(); + + private Map producerMap = new ConcurrentHashMap<>(); + + public Map getProducerMap() { + return producerMap; + } + + public void setProducerMap(Map producerMap) { + this.producerMap = producerMap; + } + + public EventSenderDmaapImpl(){ + + } + + public void initialize(){ + Properties properties = configuration.getProperties(); + String writeTopic; + String username; + String password; + final List pool = new ArrayList<>(); + + for(MessageDestination destination: MessageDestination.values()){ + writeTopic = properties.getProperty(destination + "." + EVENT_TOPIC_WRITE); + username = properties.getProperty(destination + "." + DMAAP_USERNAME); + password = properties.getProperty(destination + "." + DMAAP_PASSWORD); + String hostNames = properties.getProperty(destination + "." + EVENT_POOL_MEMBERS); + + if (hostNames != null && !hostNames.isEmpty()) { + LOG.debug(String.format("hostNames = %s, taken from property: %s", hostNames, destination + "." + EVENT_POOL_MEMBERS)); + Collections.addAll(pool, hostNames.split(",")); + } + + LOG.debug(String.format("pool = %s, taken from property: %s", pool, destination + "." + EVENT_POOL_MEMBERS)); + LOG.debug(String.format("writeTopic = %s, taken from property: %s", writeTopic, destination + "." + EVENT_TOPIC_WRITE)); + LOG.debug(String.format("username = %s, taken from property: %s", username, destination + "." + DMAAP_USERNAME)); + Producer producer = new DmaapProducerImpl(pool, writeTopic,username, password); + + for (String url : pool) { + if (url.contains("3905") || url.contains("https")) { + LOG.debug("Producer should use HTTPS"); + producer.useHttps(true); + break; + } + } + producerMap.put(destination.toString(),producer); + } + + } + + @Override + public boolean sendEvent(MessageDestination destination, EventMessage msg) { + String jsonStr = msg.toJson(); + String id = msg.getEventHeader().getEventId(); + LOG.info(String.format("Posting Message [%s - %s]", id, jsonStr)); + Producer producer = producerMap.get(destination.toString()); + return producer.post(id, jsonStr); + } + + @Override + public boolean sendEvent(MessageDestination destination, EventMessage msg, String eventTopicName) { + String jsonStr = msg.toJson(); + String id = msg.getEventHeader().getEventId(); + LOG.info(String.format("Posting Message [%s - %s]", id, jsonStr)); + Producer producer = createProducer(destination, eventTopicName); + return producer.post(id, jsonStr); + } + + private Producer createProducer(MessageDestination destination, String eventTopicName) { + Properties properties = configuration.getProperties(); + final List pool = new ArrayList<>(); + String username = properties.getProperty(destination + "." + DMAAP_USERNAME); + String password = properties.getProperty(destination + "." + DMAAP_PASSWORD); + String hostNames = properties.getProperty(destination + "." + EVENT_POOL_MEMBERS); + + if (hostNames != null && !hostNames.isEmpty()) { + LOG.debug(String.format("hostNames = %s, taken from property: %s", hostNames, destination + "." + EVENT_POOL_MEMBERS)); + Collections.addAll(pool, hostNames.split(",")); + } + + LOG.debug(String.format("pool = %s, taken from property: %s", pool, destination + "." + EVENT_POOL_MEMBERS)); + LOG.debug(String.format("writeTopic = %s, taken from property: %s", eventTopicName, destination + "." + EVENT_TOPIC_WRITE)); + LOG.debug(String.format("username = %s, taken from property: %s", username, destination + "." + DMAAP_USERNAME)); + Producer producer = new DmaapProducerImpl(pool, eventTopicName,username, password); + + for (String url : pool) { + if (url.contains("3905") || url.contains("https")) { + LOG.debug("Producer should use HTTPS"); + producer.useHttps(true); + break; + } + } + return producer; + } + + @Override + public boolean sendEvent(MessageDestination destination, Map params, SvcLogicContext ctx) throws APPCException { + + if (params == null) { + String message = "Parameters map is empty (null)"; + LOG.error(message); + throw new APPCException(message); + } + String eventTime = new Date(System.currentTimeMillis()).toString(); + String apiVer = params.get("apiVer"); + String eventId = params.get("eventId"); + String reason = params.get("reason"); + String entityId=params.get("entityId"); + if(entityId!=null){ + reason=reason+"("+entityId+")"; + } + Integer code = Integer.getInteger(params.get("code"), 500); + + if (eventTime == null || apiVer == null || eventId == null || reason == null) { + String message = String.format("Missing input parameters: %s", params); + LOG.error(message); + throw new APPCException(message); + } + EventMessage eventMessage = new EventMessage( + new EventHeader(eventTime, apiVer, eventId), + new EventStatus(code, reason)); + + return sendEvent(destination,eventMessage); + } +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/AppcDmaapAdapterActivator.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/AppcDmaapAdapterActivator.java deleted file mode 100644 index 812f80121..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/AppcDmaapAdapterActivator.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap; - -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. - *

- * 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. - *

- *

- * 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. - *

- *

- * When the bundle is deactivated, the cache is torn down with all contexts being closed. - *

- */ -public class AppcDmaapAdapterActivator implements BundleActivator { - private ServiceRegistration registration = null; - - /** - * The logger to be used - */ - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(AppcDmaapAdapterActivator.class); - - /** - * 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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @param bundleContext - * 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(final BundleContext bundleContext) throws Exception { - LOG.info("Starting Bundle " + getName()); - } - - /** - * 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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @param ctx - * 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 ctx) throws Exception { - LOG.info("Stopped Bundle " + getName()); - } - - public String getName() { - return "DMaaP Adapter"; - } - -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/CommonHttpClient.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/CommonHttpClient.java deleted file mode 100644 index 76b050d8e..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/CommonHttpClient.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap.http; - -import java.net.URI; - -import org.apache.commons.codec.binary.Base64; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.config.RequestConfig.Builder; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; - -public class CommonHttpClient { - - public static final int HTTPS_PORT = 3905; - - private String AUTH_STR; - - protected void setBasicAuth(String username, String password) { - if (username != null && password != null) { - String plain = String.format("%s:%s", username, password); - AUTH_STR = Base64.encodeBase64String(plain.getBytes()); - } else { - AUTH_STR = null; - } - } - - public HttpGet getReq(URI uri, int timeoutMs) throws Exception { - HttpGet out = (uri == null) ? new HttpGet() : new HttpGet(uri); - if (AUTH_STR != null) { - out.setHeader("Authorization", String.format("Basic %s", AUTH_STR)); - } - out.setConfig(getConfig(timeoutMs)); - return out; - } - - public HttpPost postReq(String url) throws Exception { - HttpPost out = (url == null) ? new HttpPost() : new HttpPost(url); - if (AUTH_STR != null) { - out.setHeader("Authorization", String.format("Basic %s", AUTH_STR)); - } - out.setConfig(getConfig(0)); - return out; - } - - private RequestConfig getConfig(int timeoutMs) { - Builder builder = RequestConfig.custom(); - builder.setSocketTimeout(timeoutMs + 5000); - return builder.build(); - } - - public CloseableHttpClient getClient() { - return getClient(false); - } - - public CloseableHttpClient getClient(boolean useHttps) { - return HttpClientBuilder.create().build(); - } - - public String formatHostString(String host) { - return formatHostString(host, host.contains(String.valueOf(HTTPS_PORT))); - } - - public String formatHostString(String host, boolean useHttps) { - // Trim trailing slash - String out = host.endsWith("/") ? host.substring(0, host.length() - 1) : host; - - boolean hasProto = out.startsWith("http"); - boolean hasPort = out.contains(":"); - - // Add protocol - if (!hasProto) { - out = String.format("%s%s", (useHttps) ? "https://" : "http://", out); - } - - // Add port - if (!hasPort) { - out = String.format("%s:%d", out, (useHttps) ? 3905 : 3904); - } - - return out; - - } -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/HttpDmaapConsumerImpl.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/HttpDmaapConsumerImpl.java deleted file mode 100644 index df81e9718..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/HttpDmaapConsumerImpl.java +++ /dev/null @@ -1,167 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap.http; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.apache.http.HttpEntity; -import org.apache.http.NameValuePair; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; -import org.json.JSONArray; -import org.onap.appc.adapter.message.Consumer; - -public class HttpDmaapConsumerImpl extends CommonHttpClient implements Consumer { - - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(HttpDmaapConsumerImpl.class); - - // Default values - private static final int DEFAULT_TIMEOUT_MS = 15000; - private static final int DEFAULT_LIMIT = 1000; - private static final String HTTPS_PORT = ":3905"; - private static final String URL_TEMPLATE = "%s/events/%s/%s/%s"; - - private List urls; - private String filter; - - private boolean useHttps = false; - - public HttpDmaapConsumerImpl(Collection hosts, String topicName, String consumerName, String consumerId) { - this(hosts, topicName, consumerName, consumerId, null); - } - - public HttpDmaapConsumerImpl(Collection hosts, String topicName, String consumerName, String consumerId, - String filter) { - this(hosts, topicName, consumerName, consumerId, filter, null, null); - } - - public HttpDmaapConsumerImpl(Collection hosts, String topicName, String consumerName, String consumerId, - String filter, String user, String password) { - urls = new ArrayList(); - for (String host : hosts) { - urls.add(String.format(URL_TEMPLATE, formatHostString(host), topicName, consumerName, consumerId)); - } - this.filter = filter; - updateCredentials(user, password); - } - - @Override - public void updateCredentials(String user, String pass) { - LOG.debug(String.format("Setting auth to %s for %s", user, this.toString())); - this.setBasicAuth(user, pass); - } - - @Override - public List fetch(int waitMs, int limit) { - LOG.debug(String.format("Fetching up to %d records with %dms wait on %s", limit, waitMs, this.toString())); - List out = new ArrayList(); - try { - List urlParams = new ArrayList(); - urlParams.add(new BasicNameValuePair("timeout", String.valueOf(waitMs))); - urlParams.add(new BasicNameValuePair("limit", String.valueOf(limit))); - if (filter != null) { - urlParams.add(new BasicNameValuePair("filter", filter)); - } - - URIBuilder builder = new URIBuilder(urls.get(0)); - builder.setParameters(urlParams); - - URI uri = builder.build(); - LOG.info(String.format("GET %s", uri)); - HttpGet request = getReq(uri, waitMs); - CloseableHttpResponse response = getClient().execute(request); - - int httpStatus = response.getStatusLine().getStatusCode(); - HttpEntity entity = response.getEntity(); - String body = (entity != null) ? EntityUtils.toString(entity) : null; - - LOG.debug(String.format("Request to %s completed with status %d and a body size of %s", uri, httpStatus, - (body != null ? body.length() : "null"))); - - response.close(); - if (httpStatus == 200 && body != null) { - JSONArray json = new JSONArray(body); - LOG.info(String.format("Got %d messages from DMaaP", json.length())); - for (int i = 0; i < json.length(); i++) { - out.add(json.getString(i)); - } - } else { - LOG.error(String.format("Did not get 200 from DMaaP. Got %d - %s", httpStatus, body)); - sleep(waitMs); - } - } catch (Exception e) { - if (urls.size() > 1) { - String failedUrl = urls.remove(0); - urls.add(failedUrl); - LOG.debug(String.format("Moving host %s to the end of the pool. New primary host is %s", failedUrl, - urls.get(0))); - } - LOG.error(String.format("Got exception while querying DMaaP. Message: %s", e.getMessage()), e); - sleep(waitMs); - } - - return out; - } - - @Override - public List fetch() { - return fetch(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT); - } - - @Override - public String toString() { - String hostStr = (urls == null || urls.isEmpty()) ? "N/A" : urls.get(0); - return String.format("Consumer listening to [%s]", hostStr); - } - - @Override - public void useHttps(boolean yes) { - useHttps = yes; - } - - private void sleep(int ms) { - LOG.info(String.format("Sleeping for %ds after failed request", ms / 1000)); - try { - Thread.sleep(ms); - } catch (InterruptedException e1) { - LOG.error("Interrupted while sleeping"); - } - } - - @Override - public void close() { - // Nothing to do - } - -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/HttpDmaapProducerImpl.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/HttpDmaapProducerImpl.java deleted file mode 100644 index 560c09be4..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/HttpDmaapProducerImpl.java +++ /dev/null @@ -1,138 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap.http; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.onap.appc.adapter.message.Producer; - -public class HttpDmaapProducerImpl extends CommonHttpClient implements Producer { - - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(HttpDmaapProducerImpl.class); - - private static final String CONTENT_TYPE = "application/cambria"; - private static final String URL_TEMPLATE = "%s/events/%s"; - - private List hosts; - private Set topics; - - private boolean useHttps = false; - - public HttpDmaapProducerImpl(Collection urls, String topicName) { - hosts = new ArrayList(); - topics = new HashSet(); - topics.add(topicName); - - for (String host : urls) { - hosts.add(formatHostString(host)); - } - } - - public HttpDmaapProducerImpl(Collection urls, Set topicNames) { - hosts = new ArrayList(); - topics = topicNames; - - for (String host : urls) { - hosts.add(formatHostString(host)); - } - } - - @Override - public void updateCredentials(String user, String pass) { - LOG.debug(String.format("Setting auth to %s for %s", user, this.toString())); - this.setBasicAuth(user, pass); - } - - @Override - public boolean post(String partition, String data) { - int sent = 0; - try { - HttpPost request = postReq(null); - request.setHeader("Content-Type", CONTENT_TYPE); - request.setEntity(new StringEntity(bodyLine(partition, data))); - - for (String topic : topics) { - String uriStr = String.format(URL_TEMPLATE, hosts.get(0), topic); - try { - request.setURI(new URI(uriStr)); - CloseableHttpResponse response = getClient().execute(request); - if (response.getStatusLine().getStatusCode() == 200) { - sent++; - } - response.close(); - } catch (Exception sendEx) { - LOG.error(String.format("Failed to send message to %s. Reason: %s", uriStr, sendEx.getMessage()), - sendEx); - if (hosts.size() > 1) { - String failedUrl = hosts.remove(0); - hosts.add(failedUrl); - LOG.debug(String.format("Moving host %s to the end of the pool. New primary host is %s", - failedUrl, hosts.get(0))); - } - } - } - } catch (Exception buildEx) { - LOG.error( - String.format("Failed to build request with string [%s]. Message not sent to any topic. Reason: %s", - data, buildEx.getMessage()), - buildEx); - } - return sent == topics.size(); - } - - @Override - public void useHttps(boolean yes) { - useHttps = yes; - } - - /** - * Format the body for the application/cambria content type with no partitioning. See - * - * @param msg - * The message body to format - * @return A string in the application/cambria content type - */ - private String bodyLine(String partition, String msg) { - String p = (partition == null) ? "" : partition; - String m = (msg == null) ? "" : msg; - return String.format("%d.%d.%s%s", p.length(), m.length(), p, m); - } - - @Override - public void close() { - // Nothing to do - } -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/DmaapConsumerImpl.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/DmaapConsumerImpl.java deleted file mode 100644 index ddf630545..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/DmaapConsumerImpl.java +++ /dev/null @@ -1,234 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap.impl; - -import java.io.IOException; -import java.util.*; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -//import com.att.nsa.cambria.client.CambriaClientBuilders; -//import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder; -//import com.att.nsa.cambria.client.CambriaConsumer; - -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRConsumer; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.adapter.message.Consumer; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.metricservice.MetricRegistry; -import org.onap.appc.metricservice.MetricService; -import org.onap.appc.metricservice.impl.MetricServiceImpl; -import org.onap.appc.metricservice.metric.Metric; -import org.onap.appc.metricservice.metric.MetricType; -import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric; -import org.onap.appc.metricservice.policy.PublishingPolicy; -import org.onap.appc.metricservice.publisher.LogPublisher; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -public class DmaapConsumerImpl implements Consumer { - - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(DmaapConsumerImpl.class); - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - // Default values - private static final int DEFAULT_TIMEOUT_MS = 60000; - private static final int DEFAULT_LIMIT = 1000; - private static MetricRegistry metricRegistry; - private String topic; - private DmaapRequestCounterMetric dmaapKpiMetric; - private boolean isMetricEnabled=false; - private boolean useHttps = false; - private MRConsumer client = null; - private Properties props = null; - - - public DmaapConsumerImpl(Collection urls, String topicName, String consumerGroupName, String consumerId,String user, String password) { - this(urls, topicName, consumerGroupName, consumerId,user, password,null); - - } - - public DmaapConsumerImpl(Collection urls, String topicName, String consumerGroupName, String consumerId,String user, String password,String filter) { - this.topic = topicName; - this.props = new Properties(); - String urlsStr = StringUtils.join(urls, ','); - props.setProperty("host",urlsStr); - props.setProperty("group",consumerGroupName); - props.setProperty("id",consumerId); - props.setProperty("username",user); - props.setProperty("password",password); - if(filter != null) { - props.setProperty("filter", filter); - } - } - - - private void initMetric() { - LOG.debug("Metric getting initialized"); - MetricService metricService = getMetricservice(); - metricRegistry = metricService.createRegistry("APPC"); - dmaapKpiMetric = metricRegistry.metricBuilderFactory(). - dmaapRequestCounterBuilder(). - withName("DMAAP_KPI").withType(MetricType.COUNTER). - withRecievedMessage(0) - .withPublishedMessage(0) - .build(); - if (metricRegistry.register(dmaapKpiMetric)) { - Metric[] metrics = new Metric[]{dmaapKpiMetric}; - LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics); - LogPublisher[] logPublishers = new LogPublisher[1]; - logPublishers[0] = logPublisher; - PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory(). - scheduledPolicyBuilder().withPublishers(logPublishers). - withMetrics(metrics). - build(); - LOG.debug("Policy getting initialized"); - manuallyScheduledPublishingPolicy.init(); - LOG.debug("Metric initialized"); - } - } - private MRConsumer getClient() { - return getClient(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT); - } - - /** - * @return An instance of MRConsumer created from our class variables - */ - private synchronized MRConsumer getClient(int waitMs, int limit) { - try { - props.setProperty("timeout",String.valueOf(waitMs)); - props.setProperty("limit",String.valueOf(limit)); - String topicProducerPropFileName = DmaapUtil.createConsumerPropFile(topic,props); - return MRClientFactory.createConsumer ( topicProducerPropFileName); - } catch (IOException e1) { - LOG.error("failed to createConsumer",e1); - return null; - } - } - - @Override - public synchronized void updateCredentials(String key, String secret) { - LOG.info(String.format("Setting auth to %s for %s", key, this.toString())); - String user = key; - String password = secret; - props.setProperty("user",String.valueOf(user)); - props.setProperty("password",String.valueOf(password)); - client = null; - } - - @Override - public List fetch(int waitMs, int limit) { - Properties properties=configuration.getProperties(); - if(properties!=null && properties.getProperty("metric.enabled")!=null ){ - isMetricEnabled=Boolean.valueOf(properties.getProperty("metric.enabled")); - } - if(isMetricEnabled){ - initMetric(); - } - LOG.debug(String.format("Fetching up to %d records with %dms wait on %s", limit, waitMs, this.toString())); - List out = new ArrayList(); - - // Create client once and reuse it on subsequent fetches. This is - // to support failover to other servers in the DMaaP cluster. - if (client == null) { - LOG.info("Getting DMaaP Client ..."); - client = getClient(waitMs, limit); - } - try { - for (String s : client.fetch(waitMs, limit)) { - out.add(s); - if(isMetricEnabled){ - ((DmaapRequestCounterMetric)metricRegistry.metric("DMAAP_KPI")).incrementRecievedMessage(); - } - } - LOG.debug(String.format("Got %d records from %s", out.size(), this.toString())); - } catch (Exception e) { - // Connection exception - LOG.error(String.format("Dmaap Connection Issue Detected. %s", e.getMessage())); - e.printStackTrace(); - try { - LOG.warn(String.format("Sleeping for %dms to compensate for connection failure", waitMs)); - Thread.sleep(waitMs); - } catch (InterruptedException e2) { - LOG.warn(String.format("Failed to wait for %dms after bad fetch", waitMs)); - } - } - - - return out; - } - - /** - * Close consumer Dmaap client - */ - @Override - public void close() { - LOG.debug("Closing Dmaap consumer client...."); - if (client != null) { - client.close(); - } - } - - @Override - public List fetch() { - return fetch(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT); - } - - @Override - public String toString() { - String hostStr = (props == null || props.getProperty("host") == null? "N/A" : props.getProperty("host")); - String group = (props == null || props.getProperty("group") == null? "N/A" : props.getProperty("group")); - String id = (props == null || props.getProperty("id") == null? "N/A" : props.getProperty("id")); - return String.format("Consumer %s/%s listening to %s on [%s]", group, id, topic, hostStr); - } - - @Override - public void useHttps(boolean yes) { - useHttps = yes; - } - - - private MetricService getMetricservice() { - BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext(); - // Get AAIadapter reference - ServiceReference sref = bctx.getServiceReference(MetricService.class.getName()); - if (sref != null) { - LOG.info("Metric Service from bundlecontext"); - return (MetricServiceImpl) bctx.getService(sref); - - } else { - LOG.info("Metric Service error from bundlecontext"); - LOG.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService"); - return null; - - } - } - - public Metric getMetric(String name){ - return metricRegistry.metric(name); - } -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/DmaapProducerImpl.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/DmaapProducerImpl.java deleted file mode 100644 index 7ed06a9e3..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/DmaapProducerImpl.java +++ /dev/null @@ -1,223 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap.impl; - -import java.io.*; -import java.util.*; -import java.util.concurrent.TimeUnit; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -//import com.att.nsa.cambria.client.CambriaBatchingPublisher; -//import com.att.nsa.cambria.client.CambriaClientBuilders; -//import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; - -import com.att.nsa.mr.client.MRBatchingPublisher; -import com.att.nsa.mr.client.MRClientFactory; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.adapter.message.Producer; -import org.onap.appc.adapter.messaging.dmaap.impl.DmaapUtil; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.metricservice.MetricRegistry; -import org.onap.appc.metricservice.MetricService; -import org.onap.appc.metricservice.metric.Metric; -import org.onap.appc.metricservice.metric.MetricType; -import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric; -import org.onap.appc.metricservice.policy.PublishingPolicy; -import org.onap.appc.metricservice.publisher.LogPublisher; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -public class DmaapProducerImpl implements Producer { - - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(DmaapProducerImpl.class); - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - - private Set topics = new HashSet(); - - private Properties props = null; - private static MetricRegistry metricRegistry; - private boolean useHttps = false; - private DmaapRequestCounterMetric dmaapKpiMetric; - private boolean isMetricEnabled=false; - - private Set clients; - - - public DmaapProducerImpl(Collection urls, String topicName, String user, String password) { - this(urls, (Set)null, user, password); - this.topics = new HashSet<>(); - if (topicName != null) { - for (String topic : topicName.split(",")) { - topics.add(topic); - } - } - } - - public DmaapProducerImpl(Collection urls, Set topicNames, String user, String password) { - topics = topicNames; - if(urls == null || user == null || password == null){ - throw new IllegalArgumentException("one of these mandaory argument is null: urls, user, password" ); - } - this.props = new Properties(); - String urlsStr = StringUtils.join(urls, ','); - props.setProperty("host",urlsStr); - props.setProperty("id", UUID.randomUUID().toString()); - props.setProperty("username",user); - props.setProperty("password",password); - } - private void initMetric() { - LOG.debug("Metric getting initialized"); - MetricService metricService = getMetricservice(); - metricRegistry=metricService.createRegistry("APPC"); - dmaapKpiMetric = metricRegistry.metricBuilderFactory(). - dmaapRequestCounterBuilder(). - withName("DMAAP_KPI").withType(MetricType.COUNTER). - withRecievedMessage(0) - .withPublishedMessage(0) - .build(); - if(metricRegistry.register(dmaapKpiMetric)) { - Metric[] metrics = new Metric[]{dmaapKpiMetric}; - LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics); - LogPublisher[] logPublishers = new LogPublisher[1]; - logPublishers[0] = logPublisher; - PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory(). - scheduledPolicyBuilder().withPublishers(logPublishers). - withMetrics(metrics). - build(); - LOG.debug("Policy getting initialized"); - manuallyScheduledPublishingPolicy.init(); - LOG.debug("Metric initialized"); - } - - } - private Set getClients() { - Set out = new HashSet(); - for (String topic : topics) { - try { - String topicProducerPropFileName = DmaapUtil.createProducerPropFile(topic,props); - final MRBatchingPublisher client = MRClientFactory.createBatchingPublisher (topicProducerPropFileName); - out.add(client); - } catch (Exception e) { - e.printStackTrace(); - } - } - - return out; - } - - @Override - public synchronized void updateCredentials(String key, String secret) { - LOG.info(String.format("Setting auth to %s for %s", key, this.toString())); - String user = key; - String password = secret; - props.setProperty("user",String.valueOf(user)); - props.setProperty("password",String.valueOf(password)); - clients = null; - } - - @Override - public boolean post(String partition, String data) { - boolean success = true; - Properties properties=configuration.getProperties(); - if(properties!=null && properties.getProperty("metric.enabled")!=null ){ - isMetricEnabled=Boolean.valueOf(properties.getProperty("metric.enabled")); - } - if(isMetricEnabled){ - initMetric(); - } - - // Create clients once and reuse them on subsequent posts. This is - // to support failover to other servers in the Dmaap cluster. - if ((clients == null) || (clients.isEmpty())) { - LOG.info("Getting CambriaBatchingPublisher Clients ..."); - clients = getClients(); - } - - for (MRBatchingPublisher client : clients) { - try { - LOG.debug(String.format("Posting %s to %s", data, client)); - client.send(partition, data); - } catch (IOException e) { - e.printStackTrace(); - success = false; - } - } - if(isMetricEnabled){ - ( (DmaapRequestCounterMetric) metricRegistry.metric("DMAAP_KPI")).incrementPublishedMessage(); - } - return success; - } - - /** - * Close producer Dmaap client - */ - @Override - public void close() { - if ((clients == null) || (clients.isEmpty())) { - return; - } - - LOG.debug("Closing Dmaap producer clients...."); - for (MRBatchingPublisher client : clients) { - try { - client.close(1, TimeUnit.SECONDS); - } catch (IOException | InterruptedException e) { - LOG.warn(String.format("Failed to cleanly close Dmaap connection for [%s]", client)); - e.printStackTrace(); - } - } - } - - @Override - public void useHttps(boolean yes) { - useHttps = yes; - } - - private MetricService getMetricservice() { -/* - return AppcDmaapAdapterActivator.getMetricService(); -*/ - - BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext(); - ServiceReference sref = bctx.getServiceReference(MetricService.class.getName()); - if (sref != null) { - LOG.info("Metric Service from bundlecontext"); - return (MetricService) bctx.getService(sref); - - } else { - LOG.info("Metric Service error from bundlecontext"); - LOG.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService"); - return null; - - } - } - - public Metric getMetric(String name){ - return metricRegistry.metric(name); - } -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/DmaapUtil.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/DmaapUtil.java deleted file mode 100644 index da1b0fa38..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/DmaapUtil.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap.impl; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -public class DmaapUtil { - private final static String delimiter = "_"; - private static String createPreferredRouteFileIfNotExist(String topic) throws IOException { - String topicPreferredRouteFileName = null; - topicPreferredRouteFileName = topic+"preferredRoute.properties"; - File fo= new File(topicPreferredRouteFileName); - if(!fo.exists()) { - ClassLoader classLoader = DmaapUtil.class.getClassLoader(); - InputStream inputStream = classLoader.getResourceAsStream("preferredRoute.txt"); - Properties props = new Properties(); - props.load(inputStream); - String fileName = topic != null ? topic+delimiter+"MR1" : delimiter+"MR1"; - props.setProperty("preferredRouteKey", fileName); - topicPreferredRouteFileName = topic + "preferredRoute.properties"; - props.store(new FileOutputStream(topicPreferredRouteFileName), "preferredRoute.properties file created on the fly for topic:" + topic + " on:" + System.currentTimeMillis()); - } - return topicPreferredRouteFileName; - } - - public static String createConsumerPropFile(String topic, Properties props)throws IOException { - String defaultProfFileName = "consumer.properties"; - String topicConsumerPropFileName = createConsumerProducerPropFile(topic, defaultProfFileName,props); - return topicConsumerPropFileName; - } - - public static String createProducerPropFile(String topic, Properties props)throws IOException { - String defaultProfFileName = "producer.properties"; - String topicConsumerPropFileName = createConsumerProducerPropFile(topic, defaultProfFileName,props); - return topicConsumerPropFileName; - } - - private static String createConsumerProducerPropFile(String topic, String defaultProfFileName, Properties props) throws IOException { - ClassLoader classLoader = DmaapUtil.class.getClassLoader(); - InputStream inputStream = classLoader.getResourceAsStream(defaultProfFileName); - Properties defaultProps = new Properties(); - defaultProps.load(inputStream); - defaultProps.setProperty("topic",topic); - - String preferredRouteFileName = DmaapUtil.createPreferredRouteFileIfNotExist(topic); - if(props != null && !props.isEmpty()){ - defaultProps.putAll(props); - } - defaultProps.setProperty("topic",topic); - defaultProps.setProperty("DME2preferredRouterFilePath",preferredRouteFileName); - String id = defaultProps.getProperty("id"); - String topicConsumerPropFileName = defaultProfFileName; - topicConsumerPropFileName = id != null ? id+delimiter+topicConsumerPropFileName : delimiter+topicConsumerPropFileName; - topicConsumerPropFileName = topic != null ? topic+delimiter+topicConsumerPropFileName : delimiter+topicConsumerPropFileName; - - defaultProps.store(new FileOutputStream(topicConsumerPropFileName), defaultProfFileName+" file created on the fly for topic:"+topic+" on:"+System.currentTimeMillis()); - return topicConsumerPropFileName; - } - -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/EventSenderDmaapImpl.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/EventSenderDmaapImpl.java deleted file mode 100644 index bf7649026..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/impl/EventSenderDmaapImpl.java +++ /dev/null @@ -1,178 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -import org.onap.appc.adapter.message.EventSender; -import org.onap.appc.adapter.message.MessageDestination; -import org.onap.appc.adapter.message.Producer; -import org.onap.appc.adapter.message.event.EventHeader; -import org.onap.appc.adapter.message.event.EventMessage; -import org.onap.appc.adapter.message.event.EventStatus; -import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; - -public class EventSenderDmaapImpl implements EventSender -{ - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(EventSenderDmaapImpl.class); - public static final String EVENT_TOPIC_WRITE = "dmaap.event.topic.write"; - public static final String DMAAP_USERNAME = "dmaap.appc.username"; - public static final String DMAAP_PASSWORD = "dmaap.appc.password"; - public static final String EVENT_POOL_MEMBERS = "dmaap.event.pool.members"; - - private static Configuration configuration = ConfigurationFactory.getConfiguration(); - - private Map producerMap = new ConcurrentHashMap<>(); - - public Map getProducerMap() { - return producerMap; - } - - public void setProducerMap(Map producerMap) { - this.producerMap = producerMap; - } - - public EventSenderDmaapImpl(){ - - } - - public void initialize(){ - Properties properties = configuration.getProperties(); - String writeTopic; - String username; - String password; - final List pool = new ArrayList<>(); - - for(MessageDestination destination: MessageDestination.values()){ - writeTopic = properties.getProperty(destination + "." + EVENT_TOPIC_WRITE); - username = properties.getProperty(destination + "." + DMAAP_USERNAME); - password = properties.getProperty(destination + "." + DMAAP_PASSWORD); - String hostNames = properties.getProperty(destination + "." + EVENT_POOL_MEMBERS); - - if (hostNames != null && !hostNames.isEmpty()) { - LOG.debug(String.format("hostNames = %s, taken from property: %s", hostNames, destination + "." + EVENT_POOL_MEMBERS)); - Collections.addAll(pool, hostNames.split(",")); - } - - LOG.debug(String.format("pool = %s, taken from property: %s", pool, destination + "." + EVENT_POOL_MEMBERS)); - LOG.debug(String.format("writeTopic = %s, taken from property: %s", writeTopic, destination + "." + EVENT_TOPIC_WRITE)); - LOG.debug(String.format("username = %s, taken from property: %s", username, destination + "." + DMAAP_USERNAME)); - Producer producer = new DmaapProducerImpl(pool, writeTopic,username, password); - - for (String url : pool) { - if (url.contains("3905") || url.contains("https")) { - LOG.debug("Producer should use HTTPS"); - producer.useHttps(true); - break; - } - } - producerMap.put(destination.toString(),producer); - } - - } - - @Override - public boolean sendEvent(MessageDestination destination, EventMessage msg) { - String jsonStr = msg.toJson(); - String id = msg.getEventHeader().getEventId(); - LOG.info(String.format("Posting Message [%s - %s]", id, jsonStr)); - Producer producer = producerMap.get(destination.toString()); - return producer.post(id, jsonStr); - } - - @Override - public boolean sendEvent(MessageDestination destination, EventMessage msg, String eventTopicName) { - String jsonStr = msg.toJson(); - String id = msg.getEventHeader().getEventId(); - LOG.info(String.format("Posting Message [%s - %s]", id, jsonStr)); - Producer producer = createProducer(destination, eventTopicName); - return producer.post(id, jsonStr); - } - - private Producer createProducer(MessageDestination destination, String eventTopicName) { - Properties properties = configuration.getProperties(); - final List pool = new ArrayList<>(); - String username = properties.getProperty(destination + "." + DMAAP_USERNAME); - String password = properties.getProperty(destination + "." + DMAAP_PASSWORD); - String hostNames = properties.getProperty(destination + "." + EVENT_POOL_MEMBERS); - - if (hostNames != null && !hostNames.isEmpty()) { - LOG.debug(String.format("hostNames = %s, taken from property: %s", hostNames, destination + "." + EVENT_POOL_MEMBERS)); - Collections.addAll(pool, hostNames.split(",")); - } - - LOG.debug(String.format("pool = %s, taken from property: %s", pool, destination + "." + EVENT_POOL_MEMBERS)); - LOG.debug(String.format("writeTopic = %s, taken from property: %s", eventTopicName, destination + "." + EVENT_TOPIC_WRITE)); - LOG.debug(String.format("username = %s, taken from property: %s", username, destination + "." + DMAAP_USERNAME)); - Producer producer = new DmaapProducerImpl(pool, eventTopicName,username, password); - - for (String url : pool) { - if (url.contains("3905") || url.contains("https")) { - LOG.debug("Producer should use HTTPS"); - producer.useHttps(true); - break; - } - } - return producer; - } - - @Override - public boolean sendEvent(MessageDestination destination, Map params, SvcLogicContext ctx) throws APPCException { - - if (params == null) { - String message = "Parameters map is empty (null)"; - LOG.error(message); - throw new APPCException(message); - } - String eventTime = new Date(System.currentTimeMillis()).toString(); - String apiVer = params.get("apiVer"); - String eventId = params.get("eventId"); - String reason = params.get("reason"); - String entityId=params.get("entityId"); - if(entityId!=null){ - reason=reason+"("+entityId+")"; - } - Integer code = Integer.getInteger(params.get("code"), 500); - - if (eventTime == null || apiVer == null || eventId == null || reason == null) { - String message = String.format("Missing input parameters: %s", params); - LOG.error(message); - throw new APPCException(message); - } - EventMessage eventMessage = new EventMessage( - new EventHeader(eventTime, apiVer, eventId), - new EventStatus(code, reason)); - - return sendEvent(destination,eventMessage); - } -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/resources/org/onap/appc/default.properties b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..280b85c00 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,28 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# ${user.home} usually goes to /root if instantiation uses the appc-docker approach + +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 280b85c00..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,28 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# ${user.home} usually goes to /root if instantiation uses the appc-docker approach - -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/SimpleExamplePublisher.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/SimpleExamplePublisher.java new file mode 100644 index 000000000..8c07c0b4a --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/SimpleExamplePublisher.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap; + +import java.io.*; +import java.util.List; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import com.att.nsa.mr.client.MRConsumer; +import org.json.JSONObject; +import org.onap.appc.adapter.messaging.dmaap.impl.DmaapUtil; + +import com.att.nsa.mr.client.MRBatchingPublisher; +import com.att.nsa.mr.client.MRClientFactory; +import com.att.nsa.mr.client.MRPublisher.message; + + +/** + *An example of how to use the Java publisher. + */ +public class SimpleExamplePublisher +{ + + public static void main(String []args) throws InterruptedException, Exception{ + int msgCount = 1; + SimpleExamplePublisher publisher = new SimpleExamplePublisher(); + + int i=0; + + String topicProducerPropFileName = DmaapUtil.createProducerPropFile("org.onap.appc.UNIT-TEST", null); + while (i< msgCount) + { + publisher.publishMessage(topicProducerPropFileName,i); + i++; + } + + fetchMessage(); + } + + + public void publishMessage( String producerFilePath,int count ) throws IOException, InterruptedException, Exception + { + // create our publisher + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher (producerFilePath); + // publish some messages + final JSONObject msg1 = new JSONObject (); + msg1.put ( "Partition:2", "Message:" +count); + //msg1.put ( "greeting", "Hello .." ); + + pub.send ( "2", msg1.toString()); + // close the publisher to make sure everything's sent before exiting. The batching + // publisher interface allows the app to get the set of unsent messages. It could + // write them to disk, for example, to try to send them later. + final List stuck = pub.close ( 20, TimeUnit.SECONDS ); + if ( stuck.size () > 0 ) + { + System.err.println ( stuck.size() + " messages unsent" ); + } + else + { + System.out.println ( "Clean exit; all messages sent." ); + } + } + + + public static void fetchMessage() + { + int count = 0; + + try + { + String topic = "org.onap.appc.UNIT-TEST"; + Properties props = new Properties(); + props.put("id", "1"); + props.put("group", "group1"); + String topicConsumerPropFileName1 = DmaapUtil.createConsumerPropFile(topic,props); + final MRConsumer consumer1 = MRClientFactory.createConsumer ( topicConsumerPropFileName1); + + props = new Properties(); + props.put("id", "2"); + props.put("group", "group2"); + String topicConsumerPropFileName2 = DmaapUtil.createConsumerPropFile(topic,props); + final MRConsumer consumer2 = MRClientFactory.createConsumer ( topicConsumerPropFileName2); + + for ( String msg : consumer1.fetch () ) + { + count++; + System.out.println ( "consumer1 "+count + ": " + msg ); + } + for ( String msg : consumer2.fetch () ) + { + count++; + System.out.println ( "consumer1 "+count + ": " + msg ); + } + + + } + catch ( Exception x ) + { + System.out.println("inside cons exc"); + System.err.println ( x.getClass().getName () + ": " + x.getMessage () ); + } + } +} + + + + + + + + + diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestAppcDmaapAdapterActivator.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestAppcDmaapAdapterActivator.java new file mode 100644 index 000000000..5473bf7e0 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestAppcDmaapAdapterActivator.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.appc.adapter.messaging.dmaap.AppcDmaapAdapterActivator; + +public class TestAppcDmaapAdapterActivator { + + // TODO commented out to allow build to pass, need to analyze and fix +// @Test + public void coverage() { + // This does nothing since the activator does nothing + AppcDmaapAdapterActivator appc = new AppcDmaapAdapterActivator(); + try { + appc.start(null); + appc.stop(null); + + } catch (Exception e) { + fail("Got exception when starting stopping. " + e.getMessage()); + } + assertNotNull(appc.getName()); + } + +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestDmaapConsuming.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestDmaapConsuming.java new file mode 100644 index 000000000..28c2bc4e2 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestDmaapConsuming.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap; + + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.appc.adapter.message.Consumer; +import org.onap.appc.adapter.messaging.dmaap.http.HttpDmaapConsumerImpl; +import org.onap.appc.adapter.messaging.dmaap.impl.DmaapConsumerImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.junit.Ignore; + +import java.util.Arrays; +import java.util.List; + +/** + * Must have a DMaaP cluster or simulator up and running + * Update the hostname, topic, client properties in + * resources/org/onap/appc/default.properties + * + */ +public class TestDmaapConsuming { + + private static Consumer dmaapConsumer; + private static Consumer httpConsumer; + + @BeforeClass + public static void setUp() { + + Configuration configuration = ConfigurationFactory.getConfiguration(); + + List hosts = Arrays.asList(configuration.getProperty("poolMembers").split(",")); + String topic = configuration.getProperty("topic.read"); + String consumerName = configuration.getProperty("client.name"); + String consumerId = configuration.getProperty("client.name.id"); + String msgFilter = configuration.getProperty("message.filter"); + String user = configuration.getProperty("dmaap.appc.username"); + String password = configuration.getProperty("dmaap.appc.password"); + + httpConsumer = new HttpDmaapConsumerImpl(hosts, topic, consumerName, consumerId, msgFilter); + dmaapConsumer = new DmaapConsumerImpl(hosts, topic, consumerName, consumerId,user,password,msgFilter); + } + + @Test + @Ignore + public void testHttpFetchMessages() { + testFetchMessages(httpConsumer); + } + + @Test + @Ignore + public void testFetchMessages() { + testFetchMessages(dmaapConsumer); + } + + private void testFetchMessages(Consumer consumer) { + List messages = consumer.fetch(1000, 100); + Assert.assertNotNull(messages); + Assert.assertFalse(messages.isEmpty()); + } + +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestDmaapEventSender.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestDmaapEventSender.java new file mode 100644 index 000000000..bdc786337 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestDmaapEventSender.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.onap.appc.adapter.message.MessageDestination; +import org.onap.appc.adapter.message.Producer; +import org.onap.appc.adapter.message.event.EventHeader; +import org.onap.appc.adapter.message.event.EventMessage; +import org.onap.appc.adapter.message.event.EventStatus; +import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; +import org.onap.appc.adapter.messaging.dmaap.impl.EventSenderDmaapImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + + +public class TestDmaapEventSender { + + private static Properties props; + private static Map producerMap = new HashMap<>(); + private static EventMessage eventMessage; + + @BeforeClass + public static void setUp() { + + Configuration configuration = ConfigurationFactory.getConfiguration(); // test.properties file placed in home dir. + + props = new Properties(); + props.setProperty(EventSenderDmaapImpl.EVENT_POOL_MEMBERS, + configuration.getProperty(EventSenderDmaapImpl.EVENT_POOL_MEMBERS) != null ? + configuration.getProperty(EventSenderDmaapImpl.EVENT_POOL_MEMBERS) : "member1,member2,member3"); + props.setProperty(EventSenderDmaapImpl.EVENT_TOPIC_WRITE, + configuration.getProperty(EventSenderDmaapImpl.EVENT_TOPIC_WRITE) != null ? + configuration.getProperty(EventSenderDmaapImpl.EVENT_TOPIC_WRITE) : "topic1"); + + String eventClientKey = configuration.getProperty(EventSenderDmaapImpl.DMAAP_USERNAME); + if (eventClientKey != null) { + props.setProperty(EventSenderDmaapImpl.DMAAP_USERNAME,eventClientKey); + } + String eventClientSecret = configuration.getProperty(EventSenderDmaapImpl.DMAAP_PASSWORD); + if (eventClientSecret != null) { + props.setProperty(EventSenderDmaapImpl.DMAAP_PASSWORD, eventClientSecret); + } + + Producer producer = Mockito.mock(DmaapProducerImpl.class); + producerMap.put(MessageDestination.DCAE.toString(),producer); + Mockito.when(producer.post(Matchers.anyString(), Matchers.anyString())).thenReturn(true); + + eventMessage = new EventMessage( + new EventHeader("2016-03-15T10:59:33.79Z", "1.01", "17"), + new EventStatus(404, "No krokodil found")); + } + + @Test + @Ignore // requires connection to a live DMaaP server + public void testDmaapEventSenderWithProperties() { + EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); + eventSender.initialize(); + eventSender.setProducerMap(producerMap); + Assert.assertTrue(eventSender.sendEvent(MessageDestination.DCAE, eventMessage)); + } + + @Test + public void testDmaapEventSenderWithNullProperties() { + EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); +// eventSender.initialize(); + eventSender.setProducerMap(producerMap); + Assert.assertTrue(eventSender.sendEvent(MessageDestination.DCAE, eventMessage)); + } + + /* + * This test runs agains a real Dmaap (or a simulator) that should be cofigured in test.properties file. + */ + @Test + @Ignore // requires connection to a live DMaaP server + public void testDmaapEventSenderWithDmaapSim() { + EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); + eventSender.initialize(); + Assert.assertTrue(eventSender.sendEvent(MessageDestination.DCAE, eventMessage)); + } + + + @Test + @Ignore // requires connection to a live DMaaP server + public void testDmaapEventSenderDG() throws APPCException { + EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); + eventSender.initialize(); + eventSender.setProducerMap(producerMap); + Map params = new HashMap<>(); + + params.put("eventTime", eventMessage.getEventHeader().getEventTime()); + params.put("apiVer", eventMessage.getEventHeader().getApiVer()); + params.put("eventId", eventMessage.getEventHeader().getEventId()); + params.put("reason", eventMessage.getEventStatus().getReason()); + params.put("code", "200"); + + Assert.assertTrue(eventSender.sendEvent(MessageDestination.DCAE,params, new SvcLogicContext())); + } + + @Test(expected = APPCException.class) + @Ignore // requires connection to a live DMaaP server + public void testDmaapEventSenderDGNoParams() throws APPCException { + EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); + eventSender.initialize(); + eventSender.setProducerMap(producerMap); + Map params = new HashMap<>(); + + Assert.assertFalse(eventSender.sendEvent(MessageDestination.DCAE,params, new SvcLogicContext())); + } + + + @Test(expected = APPCException.class) + @Ignore // requires connection to a live DMaaP server + public void testDmaapEventSenderDGNullParam() throws APPCException { + EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); + eventSender.initialize(); + eventSender.setProducerMap(producerMap); + Map params = null; + + Assert.assertFalse(eventSender.sendEvent(MessageDestination.DCAE,params, new SvcLogicContext())); + } + + @Test(expected = APPCException.class) + @Ignore // requires connection to a live DMaaP server + public void testDmaapEventSenderDGNoParam() throws APPCException { + EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); + eventSender.initialize(); + eventSender.setProducerMap(producerMap); + Map params = new HashMap<>(); + +// params.put("apiVer", eventMessage.getEventHeader().getApiVer()); + params.put("eventId", eventMessage.getEventHeader().getEventId()); + params.put("reason", eventMessage.getEventStatus().getReason()); + params.put("code", "200"); + + eventSender.sendEvent(MessageDestination.DCAE,params, new SvcLogicContext()); + } + +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestDmaapProducing.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestDmaapProducing.java new file mode 100644 index 000000000..bdfa93726 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/TestDmaapProducing.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap; + + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.adapter.message.Producer; +import org.onap.appc.adapter.messaging.dmaap.http.HttpDmaapProducerImpl; +import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; + +import java.util.Arrays; +import java.util.List; + +/** + * Must have a DMaaP cluster or simulator up and running + * Update the hostname, topic, client properties in + * resources/org/onap/appc/default.properties + * + */ +public class TestDmaapProducing { + + private static Producer httpProducer; + private static Producer dmaapProducer; + + @BeforeClass + public static void setUp() { + + Configuration configuration = ConfigurationFactory.getConfiguration(); + + List hosts = Arrays.asList(configuration.getProperty("poolMembers").split(",")); + String topic = configuration.getProperty("topic.write"); + String user = configuration.getProperty("dmaap.appc.username"); + String password = configuration.getProperty("dmaap.appc.password"); + + dmaapProducer = new DmaapProducerImpl(hosts, topic,user,password); + httpProducer = new HttpDmaapProducerImpl(hosts, topic); + httpProducer.updateCredentials(user,password); + } + + @Test + @Ignore + public void testHttpPostMessage() { + testPostMessage(httpProducer); + } + + @Test + @Ignore + public void testPostMessages() { + testPostMessage(dmaapProducer); + } + + private void testPostMessage(Producer producer) { + Assert.assertTrue(producer.post("partition", "{\"message\": \"Hello, world!\"}")); + } + +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/impl/TestConsumerProducerImpl.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/impl/TestConsumerProducerImpl.java new file mode 100644 index 000000000..cb318dc4e --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/onap/appc/adapter/messaging/dmaap/impl/TestConsumerProducerImpl.java @@ -0,0 +1,245 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.messaging.dmaap.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.*; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.adapter.message.Consumer; +import org.onap.appc.adapter.message.Producer; +import org.onap.appc.adapter.messaging.dmaap.impl.DmaapConsumerImpl; +import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; + +public class TestConsumerProducerImpl { + + private Collection urls; + private String topicRead; + private String topicWrite; + private String group; + private String groupId; + private String user; + private String password; + + @Before + public void setup() { + System.out.println("setup entry..."); +// urls = new HashSet(); +// urls.add("dmaaphost1"); +// urls.add("dmaaphost2"); +// //remove unavailable dmaap instance for build +// //urls.add("dmaaphost3"); +// +// topicRead = "APPC-UNIT-TEST"; +// topicWrite = "APPC-UNIT-TEST"; +// group = "APPC-CLIENT"; +// groupId = "0"; + Configuration configuration = ConfigurationFactory.getConfiguration(); + List hosts = Arrays.asList(configuration.getProperty("poolMembers").split(",")); + urls = new HashSet(hosts); + topicRead = configuration.getProperty("topic.read"); + topicWrite = configuration.getProperty("topic.write"); + user = configuration.getProperty("dmaap.appc.username"); + password = configuration.getProperty("dmaap.appc.password"); + group = "APPC-CLIENT"; + groupId = "0"; + + + runoff(); + } + + /** + * Test that we can read and write and that the messages come back in order + */ + @Ignore + @Test + public void testWriteRead() { + System.out.println("testWriteRead entry..."); + Producer p = new DmaapProducerImpl(urls, topicWrite,user,password); + + String s1 = UUID.randomUUID().toString(); + String s2 = UUID.randomUUID().toString(); + if (p.post("TEST", s1) == false) { + // try again - 2nd attempt may succeed if cambria client failed over + p.post("TEST", s1); + } + if (p.post("TEST", s2) == false) { + // try again - 2nd attempt may succeed if cambria client failed over + p.post("TEST", s2); + } + + Consumer c = new DmaapConsumerImpl(urls, topicRead, group, groupId,user,password); + List out = c.fetch(); + // if fetch is empty, try again - a 2nd attempt may succeed if + // cambria client has failed over + if ((out == null) || out.isEmpty()) { + out = c.fetch(); + } + + assertNotNull(out); + assertEquals(2, out.size()); + assertEquals(s1, out.get(0)); + assertEquals(s2, out.get(1)); + + } + + /** + * Test that we can read and write and that the messages come back in order + */ + @Test + @Ignore // Https Not support on jenkins server + public void testWriteReadHttps() { + System.out.println("testWriteReadHttps entry..."); + Producer p = new DmaapProducerImpl(urls, topicWrite,user,password); + p.useHttps(true); + + String s1 = UUID.randomUUID().toString(); + String s2 = UUID.randomUUID().toString(); + if (p.post("TEST", s1) == false) { + // try again - 2nd attempt may succeed if cambria client failed over + p.post("TEST", s1); + } + if (p.post("TEST", s2) == false) { + // try again - 2nd attempt may succeed if cambria client failed over + p.post("TEST", s2); + } + + Consumer c = new DmaapConsumerImpl(urls, topicRead, group, groupId,user,password); + c.useHttps(true); + + List out = c.fetch(); + // if fetch is empty, try again - a 2nd attempt may succeed if + // cambria client has failed over + if ((out == null) || out.isEmpty()) { + out = c.fetch(); + } + + assertNotNull(out); + assertEquals(2, out.size()); + assertEquals(s1, out.get(0)); + assertEquals(s2, out.get(1)); + + } + + @Test + @Ignore // requires connection to a live DMaaP server + public void testBadUrl() { + System.out.println("testBadUrl entry..."); + urls.clear(); + urls.add("something.local"); + + // Producer p = new DmaapProducerImpl(urls, topicWrite); + Consumer c = new DmaapConsumerImpl(urls, topicRead, group, groupId,user,password); + List result = c.fetch(1000, 1000); + + assertNotNull(result); + assertTrue(result.isEmpty()); + } + + @Test + @Ignore // requires connection to a live DMaaP server + public void testAuth() { + System.out.println("testAuth entry..."); + Producer p = new DmaapProducerImpl(urls, topicWrite,user,password); + Consumer c = new DmaapConsumerImpl(urls, topicRead, group, groupId,user,password); + + p.updateCredentials("key", "secret"); + c.updateCredentials("key", "secret"); + + // TODO - Do some protected dmaap queries when the apis are updated + } + + /** + * Test DMaaP client failover to another server when a bad url is encountered + + */ + @Ignore + @Test + public void testFailover() { + System.out.println("testFailover entry..."); + urls.clear(); + urls.add("openecomp2.org"); // bad url + urls.add("dmaaphost2"); + Producer p = new DmaapProducerImpl(urls, topicWrite,user,password); + + String s1 = UUID.randomUUID().toString(); + if (p.post("TEST", s1) == false) { + // try again - cambria client should have failed over + p.post("TEST", s1); + } + + urls.clear(); + urls.add("openecomp3.org"); // bad url + urls.add("dmaaphost3"); + + Consumer c = new DmaapConsumerImpl(urls, topicRead, group, groupId,user,password); + List out = c.fetch(1000, 1000); + // if fetch is empty, try again - cambria client should have failed over + if ((out == null) || out.isEmpty()) { + out = c.fetch(); + } + + assertNotNull(out); + assertEquals(1, out.size()); + assertEquals(s1, out.get(0)); + } + + /** + * Reads through the entire topic so it is clean for testing. WARNING - ONLY USE ON TOPICS WHERE YOU ARE THE ONLY + * WRITER. Could end in an infinite loop otherwise. + */ + private void runoff() { + Consumer c = new DmaapConsumerImpl(urls, topicRead, group, groupId,user,password); + List data; + do { + data = c.fetch(1000, 10000); + } while (!data.isEmpty() && data.size()!=1); + } + + @Test + @Ignore + public void testFilter() { + System.out.println("testFilter entry..."); + List res; + String filter = "{\"class\":\"Assigned\",\"field\":\"request\"}"; + Consumer c = new DmaapConsumerImpl(urls, "DCAE-CLOSED-LOOP-EVENTS-DEV1510SIM", group, groupId,user,password,filter); + res = c.fetch(2000, 10); + assertFalse(res.isEmpty()); + + res.clear(); + filter = "{\"class\":\"Assigned\",\"field\":\"response\"}"; + c = new DmaapConsumerImpl(urls, "DCAE-CLOSED-LOOP-EVENTS-DEV1510SIM", group, groupId,user,password, filter); + res = c.fetch(2000, 10); + assertTrue(res.isEmpty()); + } +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/SimpleExamplePublisher.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/SimpleExamplePublisher.java deleted file mode 100644 index 8c07c0b4a..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/SimpleExamplePublisher.java +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap; - -import java.io.*; -import java.util.List; -import java.util.Properties; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import com.att.nsa.mr.client.MRConsumer; -import org.json.JSONObject; -import org.onap.appc.adapter.messaging.dmaap.impl.DmaapUtil; - -import com.att.nsa.mr.client.MRBatchingPublisher; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.MRPublisher.message; - - -/** - *An example of how to use the Java publisher. - */ -public class SimpleExamplePublisher -{ - - public static void main(String []args) throws InterruptedException, Exception{ - int msgCount = 1; - SimpleExamplePublisher publisher = new SimpleExamplePublisher(); - - int i=0; - - String topicProducerPropFileName = DmaapUtil.createProducerPropFile("org.onap.appc.UNIT-TEST", null); - while (i< msgCount) - { - publisher.publishMessage(topicProducerPropFileName,i); - i++; - } - - fetchMessage(); - } - - - public void publishMessage( String producerFilePath,int count ) throws IOException, InterruptedException, Exception - { - // create our publisher - final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher (producerFilePath); - // publish some messages - final JSONObject msg1 = new JSONObject (); - msg1.put ( "Partition:2", "Message:" +count); - //msg1.put ( "greeting", "Hello .." ); - - pub.send ( "2", msg1.toString()); - // close the publisher to make sure everything's sent before exiting. The batching - // publisher interface allows the app to get the set of unsent messages. It could - // write them to disk, for example, to try to send them later. - final List stuck = pub.close ( 20, TimeUnit.SECONDS ); - if ( stuck.size () > 0 ) - { - System.err.println ( stuck.size() + " messages unsent" ); - } - else - { - System.out.println ( "Clean exit; all messages sent." ); - } - } - - - public static void fetchMessage() - { - int count = 0; - - try - { - String topic = "org.onap.appc.UNIT-TEST"; - Properties props = new Properties(); - props.put("id", "1"); - props.put("group", "group1"); - String topicConsumerPropFileName1 = DmaapUtil.createConsumerPropFile(topic,props); - final MRConsumer consumer1 = MRClientFactory.createConsumer ( topicConsumerPropFileName1); - - props = new Properties(); - props.put("id", "2"); - props.put("group", "group2"); - String topicConsumerPropFileName2 = DmaapUtil.createConsumerPropFile(topic,props); - final MRConsumer consumer2 = MRClientFactory.createConsumer ( topicConsumerPropFileName2); - - for ( String msg : consumer1.fetch () ) - { - count++; - System.out.println ( "consumer1 "+count + ": " + msg ); - } - for ( String msg : consumer2.fetch () ) - { - count++; - System.out.println ( "consumer1 "+count + ": " + msg ); - } - - - } - catch ( Exception x ) - { - System.out.println("inside cons exc"); - System.err.println ( x.getClass().getName () + ": " + x.getMessage () ); - } - } -} - - - - - - - - - diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestAppcDmaapAdapterActivator.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestAppcDmaapAdapterActivator.java deleted file mode 100644 index 5473bf7e0..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestAppcDmaapAdapterActivator.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import org.junit.Test; -import org.onap.appc.adapter.messaging.dmaap.AppcDmaapAdapterActivator; - -public class TestAppcDmaapAdapterActivator { - - // TODO commented out to allow build to pass, need to analyze and fix -// @Test - public void coverage() { - // This does nothing since the activator does nothing - AppcDmaapAdapterActivator appc = new AppcDmaapAdapterActivator(); - try { - appc.start(null); - appc.stop(null); - - } catch (Exception e) { - fail("Got exception when starting stopping. " + e.getMessage()); - } - assertNotNull(appc.getName()); - } - -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestDmaapConsuming.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestDmaapConsuming.java deleted file mode 100644 index 28c2bc4e2..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestDmaapConsuming.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap; - - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.appc.adapter.message.Consumer; -import org.onap.appc.adapter.messaging.dmaap.http.HttpDmaapConsumerImpl; -import org.onap.appc.adapter.messaging.dmaap.impl.DmaapConsumerImpl; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.junit.Ignore; - -import java.util.Arrays; -import java.util.List; - -/** - * Must have a DMaaP cluster or simulator up and running - * Update the hostname, topic, client properties in - * resources/org/onap/appc/default.properties - * - */ -public class TestDmaapConsuming { - - private static Consumer dmaapConsumer; - private static Consumer httpConsumer; - - @BeforeClass - public static void setUp() { - - Configuration configuration = ConfigurationFactory.getConfiguration(); - - List hosts = Arrays.asList(configuration.getProperty("poolMembers").split(",")); - String topic = configuration.getProperty("topic.read"); - String consumerName = configuration.getProperty("client.name"); - String consumerId = configuration.getProperty("client.name.id"); - String msgFilter = configuration.getProperty("message.filter"); - String user = configuration.getProperty("dmaap.appc.username"); - String password = configuration.getProperty("dmaap.appc.password"); - - httpConsumer = new HttpDmaapConsumerImpl(hosts, topic, consumerName, consumerId, msgFilter); - dmaapConsumer = new DmaapConsumerImpl(hosts, topic, consumerName, consumerId,user,password,msgFilter); - } - - @Test - @Ignore - public void testHttpFetchMessages() { - testFetchMessages(httpConsumer); - } - - @Test - @Ignore - public void testFetchMessages() { - testFetchMessages(dmaapConsumer); - } - - private void testFetchMessages(Consumer consumer) { - List messages = consumer.fetch(1000, 100); - Assert.assertNotNull(messages); - Assert.assertFalse(messages.isEmpty()); - } - -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestDmaapEventSender.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestDmaapEventSender.java deleted file mode 100644 index bdc786337..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestDmaapEventSender.java +++ /dev/null @@ -1,172 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.onap.appc.adapter.message.MessageDestination; -import org.onap.appc.adapter.message.Producer; -import org.onap.appc.adapter.message.event.EventHeader; -import org.onap.appc.adapter.message.event.EventMessage; -import org.onap.appc.adapter.message.event.EventStatus; -import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; -import org.onap.appc.adapter.messaging.dmaap.impl.EventSenderDmaapImpl; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; - -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - - -public class TestDmaapEventSender { - - private static Properties props; - private static Map producerMap = new HashMap<>(); - private static EventMessage eventMessage; - - @BeforeClass - public static void setUp() { - - Configuration configuration = ConfigurationFactory.getConfiguration(); // test.properties file placed in home dir. - - props = new Properties(); - props.setProperty(EventSenderDmaapImpl.EVENT_POOL_MEMBERS, - configuration.getProperty(EventSenderDmaapImpl.EVENT_POOL_MEMBERS) != null ? - configuration.getProperty(EventSenderDmaapImpl.EVENT_POOL_MEMBERS) : "member1,member2,member3"); - props.setProperty(EventSenderDmaapImpl.EVENT_TOPIC_WRITE, - configuration.getProperty(EventSenderDmaapImpl.EVENT_TOPIC_WRITE) != null ? - configuration.getProperty(EventSenderDmaapImpl.EVENT_TOPIC_WRITE) : "topic1"); - - String eventClientKey = configuration.getProperty(EventSenderDmaapImpl.DMAAP_USERNAME); - if (eventClientKey != null) { - props.setProperty(EventSenderDmaapImpl.DMAAP_USERNAME,eventClientKey); - } - String eventClientSecret = configuration.getProperty(EventSenderDmaapImpl.DMAAP_PASSWORD); - if (eventClientSecret != null) { - props.setProperty(EventSenderDmaapImpl.DMAAP_PASSWORD, eventClientSecret); - } - - Producer producer = Mockito.mock(DmaapProducerImpl.class); - producerMap.put(MessageDestination.DCAE.toString(),producer); - Mockito.when(producer.post(Matchers.anyString(), Matchers.anyString())).thenReturn(true); - - eventMessage = new EventMessage( - new EventHeader("2016-03-15T10:59:33.79Z", "1.01", "17"), - new EventStatus(404, "No krokodil found")); - } - - @Test - @Ignore // requires connection to a live DMaaP server - public void testDmaapEventSenderWithProperties() { - EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); - eventSender.initialize(); - eventSender.setProducerMap(producerMap); - Assert.assertTrue(eventSender.sendEvent(MessageDestination.DCAE, eventMessage)); - } - - @Test - public void testDmaapEventSenderWithNullProperties() { - EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); -// eventSender.initialize(); - eventSender.setProducerMap(producerMap); - Assert.assertTrue(eventSender.sendEvent(MessageDestination.DCAE, eventMessage)); - } - - /* - * This test runs agains a real Dmaap (or a simulator) that should be cofigured in test.properties file. - */ - @Test - @Ignore // requires connection to a live DMaaP server - public void testDmaapEventSenderWithDmaapSim() { - EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); - eventSender.initialize(); - Assert.assertTrue(eventSender.sendEvent(MessageDestination.DCAE, eventMessage)); - } - - - @Test - @Ignore // requires connection to a live DMaaP server - public void testDmaapEventSenderDG() throws APPCException { - EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); - eventSender.initialize(); - eventSender.setProducerMap(producerMap); - Map params = new HashMap<>(); - - params.put("eventTime", eventMessage.getEventHeader().getEventTime()); - params.put("apiVer", eventMessage.getEventHeader().getApiVer()); - params.put("eventId", eventMessage.getEventHeader().getEventId()); - params.put("reason", eventMessage.getEventStatus().getReason()); - params.put("code", "200"); - - Assert.assertTrue(eventSender.sendEvent(MessageDestination.DCAE,params, new SvcLogicContext())); - } - - @Test(expected = APPCException.class) - @Ignore // requires connection to a live DMaaP server - public void testDmaapEventSenderDGNoParams() throws APPCException { - EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); - eventSender.initialize(); - eventSender.setProducerMap(producerMap); - Map params = new HashMap<>(); - - Assert.assertFalse(eventSender.sendEvent(MessageDestination.DCAE,params, new SvcLogicContext())); - } - - - @Test(expected = APPCException.class) - @Ignore // requires connection to a live DMaaP server - public void testDmaapEventSenderDGNullParam() throws APPCException { - EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); - eventSender.initialize(); - eventSender.setProducerMap(producerMap); - Map params = null; - - Assert.assertFalse(eventSender.sendEvent(MessageDestination.DCAE,params, new SvcLogicContext())); - } - - @Test(expected = APPCException.class) - @Ignore // requires connection to a live DMaaP server - public void testDmaapEventSenderDGNoParam() throws APPCException { - EventSenderDmaapImpl eventSender = new EventSenderDmaapImpl(); - eventSender.initialize(); - eventSender.setProducerMap(producerMap); - Map params = new HashMap<>(); - -// params.put("apiVer", eventMessage.getEventHeader().getApiVer()); - params.put("eventId", eventMessage.getEventHeader().getEventId()); - params.put("reason", eventMessage.getEventStatus().getReason()); - params.put("code", "200"); - - eventSender.sendEvent(MessageDestination.DCAE,params, new SvcLogicContext()); - } - -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestDmaapProducing.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestDmaapProducing.java deleted file mode 100644 index bdfa93726..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/TestDmaapProducing.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap; - - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.adapter.message.Producer; -import org.onap.appc.adapter.messaging.dmaap.http.HttpDmaapProducerImpl; -import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; - -import java.util.Arrays; -import java.util.List; - -/** - * Must have a DMaaP cluster or simulator up and running - * Update the hostname, topic, client properties in - * resources/org/onap/appc/default.properties - * - */ -public class TestDmaapProducing { - - private static Producer httpProducer; - private static Producer dmaapProducer; - - @BeforeClass - public static void setUp() { - - Configuration configuration = ConfigurationFactory.getConfiguration(); - - List hosts = Arrays.asList(configuration.getProperty("poolMembers").split(",")); - String topic = configuration.getProperty("topic.write"); - String user = configuration.getProperty("dmaap.appc.username"); - String password = configuration.getProperty("dmaap.appc.password"); - - dmaapProducer = new DmaapProducerImpl(hosts, topic,user,password); - httpProducer = new HttpDmaapProducerImpl(hosts, topic); - httpProducer.updateCredentials(user,password); - } - - @Test - @Ignore - public void testHttpPostMessage() { - testPostMessage(httpProducer); - } - - @Test - @Ignore - public void testPostMessages() { - testPostMessage(dmaapProducer); - } - - private void testPostMessage(Producer producer) { - Assert.assertTrue(producer.post("partition", "{\"message\": \"Hello, world!\"}")); - } - -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/impl/TestConsumerProducerImpl.java b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/impl/TestConsumerProducerImpl.java deleted file mode 100644 index cb318dc4e..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/java/org/openecomp/appc/adapter/messaging/dmaap/impl/TestConsumerProducerImpl.java +++ /dev/null @@ -1,245 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.messaging.dmaap.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.*; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.adapter.message.Consumer; -import org.onap.appc.adapter.message.Producer; -import org.onap.appc.adapter.messaging.dmaap.impl.DmaapConsumerImpl; -import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; - -public class TestConsumerProducerImpl { - - private Collection urls; - private String topicRead; - private String topicWrite; - private String group; - private String groupId; - private String user; - private String password; - - @Before - public void setup() { - System.out.println("setup entry..."); -// urls = new HashSet(); -// urls.add("dmaaphost1"); -// urls.add("dmaaphost2"); -// //remove unavailable dmaap instance for build -// //urls.add("dmaaphost3"); -// -// topicRead = "APPC-UNIT-TEST"; -// topicWrite = "APPC-UNIT-TEST"; -// group = "APPC-CLIENT"; -// groupId = "0"; - Configuration configuration = ConfigurationFactory.getConfiguration(); - List hosts = Arrays.asList(configuration.getProperty("poolMembers").split(",")); - urls = new HashSet(hosts); - topicRead = configuration.getProperty("topic.read"); - topicWrite = configuration.getProperty("topic.write"); - user = configuration.getProperty("dmaap.appc.username"); - password = configuration.getProperty("dmaap.appc.password"); - group = "APPC-CLIENT"; - groupId = "0"; - - - runoff(); - } - - /** - * Test that we can read and write and that the messages come back in order - */ - @Ignore - @Test - public void testWriteRead() { - System.out.println("testWriteRead entry..."); - Producer p = new DmaapProducerImpl(urls, topicWrite,user,password); - - String s1 = UUID.randomUUID().toString(); - String s2 = UUID.randomUUID().toString(); - if (p.post("TEST", s1) == false) { - // try again - 2nd attempt may succeed if cambria client failed over - p.post("TEST", s1); - } - if (p.post("TEST", s2) == false) { - // try again - 2nd attempt may succeed if cambria client failed over - p.post("TEST", s2); - } - - Consumer c = new DmaapConsumerImpl(urls, topicRead, group, groupId,user,password); - List out = c.fetch(); - // if fetch is empty, try again - a 2nd attempt may succeed if - // cambria client has failed over - if ((out == null) || out.isEmpty()) { - out = c.fetch(); - } - - assertNotNull(out); - assertEquals(2, out.size()); - assertEquals(s1, out.get(0)); - assertEquals(s2, out.get(1)); - - } - - /** - * Test that we can read and write and that the messages come back in order - */ - @Test - @Ignore // Https Not support on jenkins server - public void testWriteReadHttps() { - System.out.println("testWriteReadHttps entry..."); - Producer p = new DmaapProducerImpl(urls, topicWrite,user,password); - p.useHttps(true); - - String s1 = UUID.randomUUID().toString(); - String s2 = UUID.randomUUID().toString(); - if (p.post("TEST", s1) == false) { - // try again - 2nd attempt may succeed if cambria client failed over - p.post("TEST", s1); - } - if (p.post("TEST", s2) == false) { - // try again - 2nd attempt may succeed if cambria client failed over - p.post("TEST", s2); - } - - Consumer c = new DmaapConsumerImpl(urls, topicRead, group, groupId,user,password); - c.useHttps(true); - - List out = c.fetch(); - // if fetch is empty, try again - a 2nd attempt may succeed if - // cambria client has failed over - if ((out == null) || out.isEmpty()) { - out = c.fetch(); - } - - assertNotNull(out); - assertEquals(2, out.size()); - assertEquals(s1, out.get(0)); - assertEquals(s2, out.get(1)); - - } - - @Test - @Ignore // requires connection to a live DMaaP server - public void testBadUrl() { - System.out.println("testBadUrl entry..."); - urls.clear(); - urls.add("something.local"); - - // Producer p = new DmaapProducerImpl(urls, topicWrite); - Consumer c = new DmaapConsumerImpl(urls, topicRead, group, groupId,user,password); - List result = c.fetch(1000, 1000); - - assertNotNull(result); - assertTrue(result.isEmpty()); - } - - @Test - @Ignore // requires connection to a live DMaaP server - public void testAuth() { - System.out.println("testAuth entry..."); - Producer p = new DmaapProducerImpl(urls, topicWrite,user,password); - Consumer c = new DmaapConsumerImpl(urls, topicRead, group, groupId,user,password); - - p.updateCredentials("key", "secret"); - c.updateCredentials("key", "secret"); - - // TODO - Do some protected dmaap queries when the apis are updated - } - - /** - * Test DMaaP client failover to another server when a bad url is encountered - - */ - @Ignore - @Test - public void testFailover() { - System.out.println("testFailover entry..."); - urls.clear(); - urls.add("openecomp2.org"); // bad url - urls.add("dmaaphost2"); - Producer p = new DmaapProducerImpl(urls, topicWrite,user,password); - - String s1 = UUID.randomUUID().toString(); - if (p.post("TEST", s1) == false) { - // try again - cambria client should have failed over - p.post("TEST", s1); - } - - urls.clear(); - urls.add("openecomp3.org"); // bad url - urls.add("dmaaphost3"); - - Consumer c = new DmaapConsumerImpl(urls, topicRead, group, groupId,user,password); - List out = c.fetch(1000, 1000); - // if fetch is empty, try again - cambria client should have failed over - if ((out == null) || out.isEmpty()) { - out = c.fetch(); - } - - assertNotNull(out); - assertEquals(1, out.size()); - assertEquals(s1, out.get(0)); - } - - /** - * Reads through the entire topic so it is clean for testing. WARNING - ONLY USE ON TOPICS WHERE YOU ARE THE ONLY - * WRITER. Could end in an infinite loop otherwise. - */ - private void runoff() { - Consumer c = new DmaapConsumerImpl(urls, topicRead, group, groupId,user,password); - List data; - do { - data = c.fetch(1000, 10000); - } while (!data.isEmpty() && data.size()!=1); - } - - @Test - @Ignore - public void testFilter() { - System.out.println("testFilter entry..."); - List res; - String filter = "{\"class\":\"Assigned\",\"field\":\"request\"}"; - Consumer c = new DmaapConsumerImpl(urls, "DCAE-CLOSED-LOOP-EVENTS-DEV1510SIM", group, groupId,user,password,filter); - res = c.fetch(2000, 10); - assertFalse(res.isEmpty()); - - res.clear(); - filter = "{\"class\":\"Assigned\",\"field\":\"response\"}"; - c = new DmaapConsumerImpl(urls, "DCAE-CLOSED-LOOP-EVENTS-DEV1510SIM", group, groupId,user,password, filter); - res = c.fetch(2000, 10); - assertTrue(res.isEmpty()); - } -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/resources/org/onap/appc/default.properties b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..dd594515c --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,39 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +org.onap.appc.bootstrap.file=test.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +# Properties commented out below are provided in appc.properties +#poolMembers=:3904 +#event.pool.members=:3904 + +topic.read=APPC-CL +topic.read.timeout=5 +topic.write=APPC-CL +event.topic.write=APPC-CL +client.name=APPC-CLIENT-DMAAP-ADAPTER-TEST +client.name.id=0 + +metric.enabled=false; diff --git a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties deleted file mode 100644 index dd594515c..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,39 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -org.onap.appc.bootstrap.file=test.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -# Properties commented out below are provided in appc.properties -#poolMembers=:3904 -#event.pool.members=:3904 - -topic.read=APPC-CL -topic.read.timeout=5 -topic.write=APPC-CL -event.topic.write=APPC-CL -client.name=APPC-CLIENT-DMAAP-ADAPTER-TEST -client.name.id=0 - -metric.enabled=false; diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/CallableConsumer.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/CallableConsumer.java new file mode 100644 index 000000000..1f6bb50fc --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/CallableConsumer.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.message; + +import java.util.List; +import java.util.concurrent.Callable; + +public class CallableConsumer implements Callable> { + + private Consumer consumer; + + private int timeout = 15000; + private int limit = 1000; + + public CallableConsumer(Consumer c) { + this.consumer = c; + } + + public CallableConsumer(Consumer c, int waitMs, int fetchSize) { + this.consumer = c; + this.timeout = waitMs; + this.limit = fetchSize; + } + + @Override + public List call() { + return consumer.fetch(timeout, limit); + } + + /** + * The maximum amount of time to keep a connection alive. Currently is set to waitMs + 10s + * + * @return An integer representing the maximum amount of time to keep this thread alive + */ + public int getMaxLife() { + return 10000 + timeout; + } + +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/Consumer.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/Consumer.java new file mode 100644 index 000000000..92033064c --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/Consumer.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.message; + +import java.util.List; + +public interface Consumer { + + /** + * Gets a batch of messages from the topic. Defaults to 1000 messages with 15s wait for messages if empty. + * + * @return A list of strings representing the messages pulled from the topic. + */ + public List fetch(); + + /** + * Gets a batch of messages from the topic. + * + * @param waitMs + * The amount of time to wait in milliseconds if the topic is empty for data to be written. Should be no + * less than 15000ms to prevent too many requests + * @param limit + * The amount of messages to fetch + * @return A list of strings representing the messages pulled from the topic. + */ + public List fetch(int waitMs, int limit); + + /** + * Updates the api credentials for making authenticated requests + * + * @param apiKey + * The public key to authenticate with + * @param apiSecret + * The secret key to authenticate with + */ + public void updateCredentials(String apiKey, String apiSecret); + + /** + * Creates a dmaap client using a https connection + * + * @param yes + * True if https should be used, false otherwise + */ + public void useHttps(boolean yes); + + /** + * Closes the dmaap client https connection + */ + void close(); + +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/EventSender.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/EventSender.java new file mode 100644 index 000000000..962f14774 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/EventSender.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.message; + +import org.onap.appc.exceptions.APPCException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +import java.util.Map; + +import org.onap.appc.adapter.message.event.EventMessage; + +public interface EventSender extends SvcLogicJavaPlugin{ + boolean sendEvent(MessageDestination destination, EventMessage msg); + boolean sendEvent(MessageDestination destination, EventMessage msg,String eventTopicName); + boolean sendEvent(MessageDestination destination, Map params, SvcLogicContext ctx) throws APPCException; +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/Manager.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/Manager.java new file mode 100644 index 000000000..aea2fddce --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/Manager.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.message; + +import java.util.Set; + +public interface Manager { + + /** + * Updates the api credentials for making authenticated requests + * + * @param apiKey + * The public key to authenticate with + * @param apiSecret + * The secret key to authenticate with + */ + public void updateCredentials(String apiKey, String apiSecret); + + /** + * Return a set of strings representing topics that the user can see + * + * @return A set of strings with topic names or an empty set if no topics are visible + */ + public Set getTopics(); + +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/MessageAdapterFactory.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/MessageAdapterFactory.java new file mode 100644 index 000000000..d7507dc85 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/MessageAdapterFactory.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ +package org.onap.appc.adapter.message; + +import java.util.Collection; +import java.util.Set; + +import org.onap.appc.adapter.message.Consumer; +import org.onap.appc.adapter.message.Producer; + +public interface MessageAdapterFactory { + + // TODO: how do you configure the MessageService type? + + public Producer createProducer(Collection pools, String writeTopic, String apiKey, String apiSecret); + + public Producer createProducer(Collection pools, Set writeTopics, String apiKey, String apiSecret); + + public Consumer createConsumer(Collection pool, String readTopic, + String clientName, String clientId, String filter_json, String apiKey, String apiSecret); +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/MessageDestination.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/MessageDestination.java new file mode 100644 index 000000000..cb84b5c4c --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/MessageDestination.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.message; + +public enum MessageDestination { + DCAE +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/Producer.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/Producer.java new file mode 100644 index 000000000..52ead0253 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/Producer.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.message; + +public interface Producer { + + public boolean post(String partition, String data); + + /** + * Updates the api credentials for making authenticated requests + * + * @param apiKey + * The public key to authenticate with + * @param apiSecret + * The secret key to authenticate with + */ + public void updateCredentials(String apiKey, String apiSecret); + + /** + * Creates a dmaap client using a https connection + * + * @param yes + * True if https should be used, false otherwise + */ + public void useHttps(boolean yes); + + /** + * Closes the dmaap client https connection + */ + void close(); + +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/event/EventHeader.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/event/EventHeader.java new file mode 100644 index 000000000..2c4ab1fbf --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/event/EventHeader.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.message.event; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class EventHeader { + + @JsonProperty("eventTime") + private final String eventTime; + + @JsonProperty("apiVer") + private final String apiVer; + + @JsonProperty("eventId") + private final String eventId; + + public EventHeader(String eventTime, String apiVer, String eventId) { + this.eventTime = eventTime; + this.apiVer = apiVer; + this.eventId = eventId; + } + + public String getEventTime() { + return eventTime; + } + + public String getApiVer() { + return apiVer; + } + + public String getEventId() { + return eventId; + } + + @Override + public String toString() { + return "EventHeader{" + + "eventTime='" + eventTime + '\'' + + ", apiVer='" + apiVer + '\'' + + ", eventId='" + eventId + '\'' + + '}'; + } +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/event/EventMessage.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/event/EventMessage.java new file mode 100644 index 000000000..d64d6d0ce --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/event/EventMessage.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.message.event; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; + +import java.io.IOException; +import java.io.Serializable; + +/* + { + "EventHeader": { + "eventTime": "2016-03-15T10:59:33.79Z", + "apiVer": "1.01", + "EventId": "", + }, + "EventStatus": { + "code": "NNN", + "reason": "A reason" + } + } +*/ + + +@JsonSerialize(include = Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class EventMessage implements Serializable { + + private static final long serialVersionUID = 1L; + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + @JsonProperty("eventHeader") + private EventHeader eventHeader; + @JsonProperty("eventStatus") + private EventStatus eventStatus; + + public EventMessage(EventHeader eventHeader, EventStatus eventStatus) { + this.eventHeader = eventHeader; + this.eventStatus = eventStatus; + } + + public EventHeader getEventHeader() { + return eventHeader; + } + + public void setEventHeader(EventHeader eventHeader) { + this.eventHeader = eventHeader; + } + + public EventStatus getEventStatus() { + return eventStatus; + } + + public void setEventStatus(EventStatus eventStatus) { + this.eventStatus = eventStatus; + } + + public String toJson() { + try { + return OBJECT_MAPPER.writeValueAsString(this); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public String toString() { + return "EventMessage{" + + "eventHeader=" + eventHeader + + ", eventStatus=" + eventStatus + + '}'; + } +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/event/EventStatus.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/event/EventStatus.java new file mode 100644 index 000000000..a5ac44e0b --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/onap/appc/adapter/message/event/EventStatus.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.message.event; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class EventStatus { + + @JsonProperty("code") + private final Integer code; + + @JsonProperty("reason") + private final String reason; + + public EventStatus(Integer code, String aReason) { + this.code = code; + reason = aReason; + } + + + public Integer getCode() { + return code; + } + + public String getReason() { + return reason; + } + + @Override + public String toString() { + return "EventStatus{" + + "code=" + code + + ", reason='" + reason + '\'' + + '}'; + } +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/CallableConsumer.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/CallableConsumer.java deleted file mode 100644 index 1f6bb50fc..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/CallableConsumer.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.message; - -import java.util.List; -import java.util.concurrent.Callable; - -public class CallableConsumer implements Callable> { - - private Consumer consumer; - - private int timeout = 15000; - private int limit = 1000; - - public CallableConsumer(Consumer c) { - this.consumer = c; - } - - public CallableConsumer(Consumer c, int waitMs, int fetchSize) { - this.consumer = c; - this.timeout = waitMs; - this.limit = fetchSize; - } - - @Override - public List call() { - return consumer.fetch(timeout, limit); - } - - /** - * The maximum amount of time to keep a connection alive. Currently is set to waitMs + 10s - * - * @return An integer representing the maximum amount of time to keep this thread alive - */ - public int getMaxLife() { - return 10000 + timeout; - } - -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/Consumer.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/Consumer.java deleted file mode 100644 index 92033064c..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/Consumer.java +++ /dev/null @@ -1,73 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.message; - -import java.util.List; - -public interface Consumer { - - /** - * Gets a batch of messages from the topic. Defaults to 1000 messages with 15s wait for messages if empty. - * - * @return A list of strings representing the messages pulled from the topic. - */ - public List fetch(); - - /** - * Gets a batch of messages from the topic. - * - * @param waitMs - * The amount of time to wait in milliseconds if the topic is empty for data to be written. Should be no - * less than 15000ms to prevent too many requests - * @param limit - * The amount of messages to fetch - * @return A list of strings representing the messages pulled from the topic. - */ - public List fetch(int waitMs, int limit); - - /** - * Updates the api credentials for making authenticated requests - * - * @param apiKey - * The public key to authenticate with - * @param apiSecret - * The secret key to authenticate with - */ - public void updateCredentials(String apiKey, String apiSecret); - - /** - * Creates a dmaap client using a https connection - * - * @param yes - * True if https should be used, false otherwise - */ - public void useHttps(boolean yes); - - /** - * Closes the dmaap client https connection - */ - void close(); - -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/EventSender.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/EventSender.java deleted file mode 100644 index 962f14774..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/EventSender.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.message; - -import org.onap.appc.exceptions.APPCException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -import java.util.Map; - -import org.onap.appc.adapter.message.event.EventMessage; - -public interface EventSender extends SvcLogicJavaPlugin{ - boolean sendEvent(MessageDestination destination, EventMessage msg); - boolean sendEvent(MessageDestination destination, EventMessage msg,String eventTopicName); - boolean sendEvent(MessageDestination destination, Map params, SvcLogicContext ctx) throws APPCException; -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/Manager.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/Manager.java deleted file mode 100644 index aea2fddce..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/Manager.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.message; - -import java.util.Set; - -public interface Manager { - - /** - * Updates the api credentials for making authenticated requests - * - * @param apiKey - * The public key to authenticate with - * @param apiSecret - * The secret key to authenticate with - */ - public void updateCredentials(String apiKey, String apiSecret); - - /** - * Return a set of strings representing topics that the user can see - * - * @return A set of strings with topic names or an empty set if no topics are visible - */ - public Set getTopics(); - -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/MessageAdapterFactory.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/MessageAdapterFactory.java deleted file mode 100644 index d7507dc85..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/MessageAdapterFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ -package org.onap.appc.adapter.message; - -import java.util.Collection; -import java.util.Set; - -import org.onap.appc.adapter.message.Consumer; -import org.onap.appc.adapter.message.Producer; - -public interface MessageAdapterFactory { - - // TODO: how do you configure the MessageService type? - - public Producer createProducer(Collection pools, String writeTopic, String apiKey, String apiSecret); - - public Producer createProducer(Collection pools, Set writeTopics, String apiKey, String apiSecret); - - public Consumer createConsumer(Collection pool, String readTopic, - String clientName, String clientId, String filter_json, String apiKey, String apiSecret); -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/MessageDestination.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/MessageDestination.java deleted file mode 100644 index cb84b5c4c..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/MessageDestination.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.message; - -public enum MessageDestination { - DCAE -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/Producer.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/Producer.java deleted file mode 100644 index 52ead0253..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/Producer.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.message; - -public interface Producer { - - public boolean post(String partition, String data); - - /** - * Updates the api credentials for making authenticated requests - * - * @param apiKey - * The public key to authenticate with - * @param apiSecret - * The secret key to authenticate with - */ - public void updateCredentials(String apiKey, String apiSecret); - - /** - * Creates a dmaap client using a https connection - * - * @param yes - * True if https should be used, false otherwise - */ - public void useHttps(boolean yes); - - /** - * Closes the dmaap client https connection - */ - void close(); - -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/event/EventHeader.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/event/EventHeader.java deleted file mode 100644 index 2c4ab1fbf..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/event/EventHeader.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.message.event; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class EventHeader { - - @JsonProperty("eventTime") - private final String eventTime; - - @JsonProperty("apiVer") - private final String apiVer; - - @JsonProperty("eventId") - private final String eventId; - - public EventHeader(String eventTime, String apiVer, String eventId) { - this.eventTime = eventTime; - this.apiVer = apiVer; - this.eventId = eventId; - } - - public String getEventTime() { - return eventTime; - } - - public String getApiVer() { - return apiVer; - } - - public String getEventId() { - return eventId; - } - - @Override - public String toString() { - return "EventHeader{" + - "eventTime='" + eventTime + '\'' + - ", apiVer='" + apiVer + '\'' + - ", eventId='" + eventId + '\'' + - '}'; - } -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/event/EventMessage.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/event/EventMessage.java deleted file mode 100644 index d64d6d0ce..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/event/EventMessage.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.message.event; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; - -import java.io.IOException; -import java.io.Serializable; - -/* - { - "EventHeader": { - "eventTime": "2016-03-15T10:59:33.79Z", - "apiVer": "1.01", - "EventId": "", - }, - "EventStatus": { - "code": "NNN", - "reason": "A reason" - } - } -*/ - - -@JsonSerialize(include = Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class EventMessage implements Serializable { - - private static final long serialVersionUID = 1L; - - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - @JsonProperty("eventHeader") - private EventHeader eventHeader; - @JsonProperty("eventStatus") - private EventStatus eventStatus; - - public EventMessage(EventHeader eventHeader, EventStatus eventStatus) { - this.eventHeader = eventHeader; - this.eventStatus = eventStatus; - } - - public EventHeader getEventHeader() { - return eventHeader; - } - - public void setEventHeader(EventHeader eventHeader) { - this.eventHeader = eventHeader; - } - - public EventStatus getEventStatus() { - return eventStatus; - } - - public void setEventStatus(EventStatus eventStatus) { - this.eventStatus = eventStatus; - } - - public String toJson() { - try { - return OBJECT_MAPPER.writeValueAsString(this); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public String toString() { - return "EventMessage{" + - "eventHeader=" + eventHeader + - ", eventStatus=" + eventStatus + - '}'; - } -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/event/EventStatus.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/event/EventStatus.java deleted file mode 100644 index a5ac44e0b..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/java/org/openecomp/appc/adapter/message/event/EventStatus.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.message.event; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class EventStatus { - - @JsonProperty("code") - private final Integer code; - - @JsonProperty("reason") - private final String reason; - - public EventStatus(Integer code, String aReason) { - this.code = code; - reason = aReason; - } - - - public Integer getCode() { - return code; - } - - public String getReason() { - return reason; - } - - @Override - public String toString() { - return "EventStatus{" + - "code=" + code + - ", reason='" + reason + '\'' + - '}'; - } -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/resources/org/onap/appc/default.properties b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..a326faada --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,26 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index a326faada..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-api/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,26 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/onap/appc/adapter/factory/DmaapMessageAdapterFactoryActivator.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/onap/appc/adapter/factory/DmaapMessageAdapterFactoryActivator.java new file mode 100644 index 000000000..1597c4256 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/onap/appc/adapter/factory/DmaapMessageAdapterFactoryActivator.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ +package org.onap.appc.adapter.factory; + +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +public class DmaapMessageAdapterFactoryActivator implements BundleActivator { + private ServiceRegistration registration; + + @Override + public void start(BundleContext context) throws Exception { + registration = context.registerService( + MessageAdapterFactory.class.getName(), + new DmaapMessageAdapterFactoryImpl(), + null); + } + + @Override + public void stop(BundleContext context) throws Exception { + registration.unregister(); + } + +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/onap/appc/adapter/factory/DmaapMessageAdapterFactoryImpl.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/onap/appc/adapter/factory/DmaapMessageAdapterFactoryImpl.java new file mode 100644 index 000000000..19eb4cea8 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/onap/appc/adapter/factory/DmaapMessageAdapterFactoryImpl.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.factory; + +import java.util.Collection; +import java.util.Set; + +import org.onap.appc.adapter.message.Consumer; +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.onap.appc.adapter.message.Producer; + +import org.onap.appc.adapter.messaging.dmaap.http.HttpDmaapConsumerImpl; +import org.onap.appc.adapter.messaging.dmaap.http.HttpDmaapProducerImpl; + +import org.onap.appc.adapter.messaging.dmaap.impl.DmaapConsumerImpl; +import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; + +public class DmaapMessageAdapterFactoryImpl implements MessageAdapterFactory { + + //Set to true if the HttpDmaap... should be used instead of the regular Dmaap... + private static final boolean HTTP = true; + + public Producer createProducer(Collection pools, String writeTopic, String apiKey, String apiSecret) { + return HTTP ? new HttpDmaapProducerImpl(pools, writeTopic) : new DmaapProducerImpl(pools, writeTopic,apiKey, apiSecret); + } + + public Producer createProducer(Collection pools, Set writeTopics, String apiKey, String apiSecret) { + return HTTP ? new HttpDmaapProducerImpl(pools, writeTopics) : new DmaapProducerImpl(pools, writeTopics, apiKey, apiSecret); + } + + public Consumer createConsumer(Collection pool, String readTopic, + String clientName, String clientId, String filter_json, String apiKey, String apiSecret) { + return HTTP ? new HttpDmaapConsumerImpl(pool, readTopic, clientName, clientId, apiKey, apiSecret, filter_json) : + new DmaapConsumerImpl(pool, readTopic, clientName, clientId, apiKey, apiSecret, filter_json); + } +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/onap/appc/adapter/factory/MessageService.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/onap/appc/adapter/factory/MessageService.java new file mode 100644 index 000000000..952f903b1 --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/onap/appc/adapter/factory/MessageService.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.factory; +/** + * The message service types that are available. Only DMaaP available + **/ +public enum MessageService { + DMaaP("dmaap"); + + private String val; + + private MessageService(String val) { + this.val = val; + } + + public String getValue() { + return val; + } + + /** + * Tries to match a string to a MessageService. If no match is found, returns the default (DMaaP) + * + * @param input + * the string to try and match + * @return A MessasgeService + */ + public static MessageService parse(String input) { + if (input != null) { + for (MessageService ms : MessageService.values()) { + if (ms.getValue().equals(input.toLowerCase())) { + return ms; + } + } + } + return MessageService.DMaaP; // Default + } +} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/DmaapMessageAdapterFactoryActivator.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/DmaapMessageAdapterFactoryActivator.java deleted file mode 100644 index 1597c4256..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/DmaapMessageAdapterFactoryActivator.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ -package org.onap.appc.adapter.factory; - -import org.onap.appc.adapter.message.MessageAdapterFactory; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -public class DmaapMessageAdapterFactoryActivator implements BundleActivator { - private ServiceRegistration registration; - - @Override - public void start(BundleContext context) throws Exception { - registration = context.registerService( - MessageAdapterFactory.class.getName(), - new DmaapMessageAdapterFactoryImpl(), - null); - } - - @Override - public void stop(BundleContext context) throws Exception { - registration.unregister(); - } - -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/DmaapMessageAdapterFactoryImpl.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/DmaapMessageAdapterFactoryImpl.java deleted file mode 100644 index 19eb4cea8..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/DmaapMessageAdapterFactoryImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.factory; - -import java.util.Collection; -import java.util.Set; - -import org.onap.appc.adapter.message.Consumer; -import org.onap.appc.adapter.message.MessageAdapterFactory; -import org.onap.appc.adapter.message.Producer; - -import org.onap.appc.adapter.messaging.dmaap.http.HttpDmaapConsumerImpl; -import org.onap.appc.adapter.messaging.dmaap.http.HttpDmaapProducerImpl; - -import org.onap.appc.adapter.messaging.dmaap.impl.DmaapConsumerImpl; -import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; - -public class DmaapMessageAdapterFactoryImpl implements MessageAdapterFactory { - - //Set to true if the HttpDmaap... should be used instead of the regular Dmaap... - private static final boolean HTTP = true; - - public Producer createProducer(Collection pools, String writeTopic, String apiKey, String apiSecret) { - return HTTP ? new HttpDmaapProducerImpl(pools, writeTopic) : new DmaapProducerImpl(pools, writeTopic,apiKey, apiSecret); - } - - public Producer createProducer(Collection pools, Set writeTopics, String apiKey, String apiSecret) { - return HTTP ? new HttpDmaapProducerImpl(pools, writeTopics) : new DmaapProducerImpl(pools, writeTopics, apiKey, apiSecret); - } - - public Consumer createConsumer(Collection pool, String readTopic, - String clientName, String clientId, String filter_json, String apiKey, String apiSecret) { - return HTTP ? new HttpDmaapConsumerImpl(pool, readTopic, clientName, clientId, apiKey, apiSecret, filter_json) : - new DmaapConsumerImpl(pool, readTopic, clientName, clientId, apiKey, apiSecret, filter_json); - } -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/MessageService.java b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/MessageService.java deleted file mode 100644 index 952f903b1..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/MessageService.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.factory; -/** - * The message service types that are available. Only DMaaP available - **/ -public enum MessageService { - DMaaP("dmaap"); - - private String val; - - private MessageService(String val) { - this.val = val; - } - - public String getValue() { - return val; - } - - /** - * Tries to match a string to a MessageService. If no match is found, returns the default (DMaaP) - * - * @param input - * the string to try and match - * @return A MessasgeService - */ - public static MessageService parse(String input) { - if (input != null) { - for (MessageService ms : MessageService.values()) { - if (ms.getValue().equals(input.toLowerCase())) { - return ms; - } - } - } - return MessageService.DMaaP; // Default - } -} diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/resources/org/onap/appc/default.properties b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..a326faada --- /dev/null +++ b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,26 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. diff --git a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index a326faada..000000000 --- a/appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,26 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/AppcProviderAdapterActivator.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/AppcProviderAdapterActivator.java new file mode 100644 index 000000000..fbd650c39 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/AppcProviderAdapterActivator.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.impl.ProviderAdapterImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.i18n.Msg; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** + * This activator is used to initialize and terminate the connection pool to one or more providers. + *

+ * 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. + *

+ *

+ * 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. + *

+ *

+ * When the bundle is deactivated, the cache is torn down with all contexts being closed. + *

+ */ +public class AppcProviderAdapterActivator implements BundleActivator { + + /** + * The bundle registration + */ + private ServiceRegistration registration = null; + + /** + * The reference to the actual implementation object that implements the services + */ + private ProviderAdapter adapter; + + /** + * The logger to be used + */ + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AppcProviderAdapterActivator.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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @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, "IAAS adapter"); + try { + adapter = new ProviderAdapterImpl(configuration.getProperties()); + } catch (Exception e) { + logger.error("Error initializing APPC IAAS ProviderAdapterImpl", e); + throw e; + } + + if (registration == null) { + logger.info(Msg.REGISTERING_SERVICE, appName, adapter.getAdapterName(), + ProviderAdapter.class.getSimpleName()); + registration = context.registerService(ProviderAdapter.class, adapter, null); + } + + logger.info(Msg.COMPONENT_INITIALIZED, appName, "IAAS 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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @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, "IAAS adapter"); + logger.info(Msg.UNREGISTERING_SERVICE, appName, adapter.getAdapterName()); + registration.unregister(); + registration = null; + logger.info(Msg.COMPONENT_TERMINATED, appName, "IAAS adapter"); + } + } + + public String getName() { + return "APPC IaaS adapter"; + } + +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/ProviderAdapter.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/ProviderAdapter.java new file mode 100644 index 000000000..c14c936e0 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/ProviderAdapter.java @@ -0,0 +1,288 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas; + +import java.util.Map; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.exceptions.UnknownProviderException; +import com.att.cdp.zones.model.Image; +import com.att.cdp.zones.model.Server; +import com.att.cdp.zones.model.Stack; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +/** + * This interface defines the operations that the provider adapter exposes. + *

+ * 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. + *

+ */ +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"; + + /** + * This method is used to restart an existing virtual machine given the fully qualified URL of the machine. + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to stop the indicated server + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to start the indicated server + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to rebuild the indicated server + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to terminate the indicated server + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 terminate for some reason + */ + Server terminateServer(Map properties, SvcLogicContext context) throws APPCException; + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + */ + String getAdapterName(); + + Server evacuateServer(Map params, SvcLogicContext ctx) throws APPCException; + + Server migrateServer(Map params, SvcLogicContext ctx) throws APPCException; + + Server vmStatuschecker(Map params, SvcLogicContext ctx) throws APPCException; + + Stack terminateStack(Map params, SvcLogicContext ctx) throws APPCException; + + Stack snapshotStack(Map params, SvcLogicContext ctx) throws APPCException; + + Stack restoreStack(Map params, SvcLogicContext ctx) throws APPCException; + + /** + * This method is used to do the lookup of the indicated server + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 found for some reason + */ + Server lookupServer(Map properties, SvcLogicContext context) throws APPCException; + + /** + * 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 Image 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 + */ + Image createSnapshot(Map params, SvcLogicContext ctx) throws APPCException; + +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/IdentityURL.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/IdentityURL.java new file mode 100644 index 000000000..c98edc410 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/IdentityURL.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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 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 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderAdapterImpl.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderAdapterImpl.java new file mode 100644 index 000000000..ba6c8c678 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderAdapterImpl.java @@ -0,0 +1,359 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.appc.adapter.iaas.impl; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.provider.operation.api.IProviderOperation; +import org.onap.appc.adapter.iaas.provider.operation.api.ProviderOperationFactory; +import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; +import org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.util.StructuredPropertyHelper; +import org.onap.appc.util.StructuredPropertyHelper.Node; +import com.att.cdp.zones.model.Image; +import com.att.cdp.zones.model.Server; +import com.att.cdp.zones.model.Stack; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * 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"; + + /** + * The logger to be used + */ + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ProviderAdapterImpl.class); + /** + * A reference to the adapter configuration object. + */ + private Configuration configuration; + + /** + * reference to operation factory + */ + ProviderOperationFactory factory = ProviderOperationFactory.getInstance(); + + /** + * A cache of providers that are predefined. + */ + private Map providerCache; + + /** + * The username, password, and domain to use for dynamically created connections + */ + private static String DEFAULT_USER; + private static String DEFAULT_PASS; + private static String DEFAULT_DOMAIN; + + + /** + * 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 params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.RESTART_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + return (Server) op.doOperation(params, context); + } + + @Override + public Server stopServer(Map params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.STOP_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + return (Server) op.doOperation(params, context); + } + + @Override + public Server startServer(Map params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.START_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + return (Server) op.doOperation(params, context); + } + + @Override + public Server rebuildServer(Map params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.REBUILD_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + return (Server) op.doOperation(params, context); + } + + @Override + public Server terminateServer(Map params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.TERMINATE_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + return (Server) op.doOperation(params, context); + } + + @Override + public Server evacuateServer(Map params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.EVACUATE_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + // 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 params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.MIGRATE_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + return (Server) op.doOperation(params, context); + } + + @Override + public Server vmStatuschecker(Map params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.VMSTATUSCHECK_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + return (Server) op.doOperation(params, context); + } + + @Override + public Stack terminateStack(Map params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.TERMINATE_STACK); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + return (Stack) op.doOperation(params, context); + } + + @Override + public Stack snapshotStack(Map params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.SNAPSHOT_STACK); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + return (Stack) op.doOperation(params, context); + } + + @Override + public Stack restoreStack(Map params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.RESTORE_STACK); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + return (Stack) op.doOperation(params, context); + } + + @Override + public Server lookupServer(Map params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.LOOKUP_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + return (Server) op.doOperation(params, context); + } + + @Override + public Image createSnapshot(Map params, SvcLogicContext context) throws APPCException { + + IProviderOperation op = factory.getOperationObject(Operation.SNAPSHOT_SERVICE); + op.setProviderCache(this.providerCache); + op.setDefaultPass(DEFAULT_PASS); + op.setDefaultUser(DEFAULT_USER); + op.setDefaultDomain(DEFAULT_DOMAIN); + return (Image) op.doOperation(params, context); + } + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + * @see org.onap.appc.adapter.iaas.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.

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.

+         * 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 

+ */ + providerCache = new HashMap<>(); + Properties properties = configuration.getProperties(); + List providers = StructuredPropertyHelper.getStructuredProperties(properties, Property.PROVIDER); + + for (Node provider : providers) { + ProviderCache cache = new ProviderCache(); + List 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 = 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(); + DEFAULT_USER = node2.getValue(); + break; + case Property.PROVIDER_TENANT_PASSWORD: + password = node2.getValue(); + DEFAULT_PASS = node2.getValue(); + break; + case Property.PROVIDER_TENANT_DOMAIN: + domain = node2.getValue(); + DEFAULT_DOMAIN = node2.getValue(); + 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(); + } + } + +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderCache.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderCache.java new file mode 100644 index 000000000..5453a9ec1 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderCache.java @@ -0,0 +1,165 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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. + *

+ * 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. + *

+ */ +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 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 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 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 UserId + * @param password + * @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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/RequestContext.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/RequestContext.java new file mode 100644 index 000000000..ef237f96d --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/RequestContext.java @@ -0,0 +1,249 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.appc.adapter.iaas.impl; + +import org.onap.appc.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.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. + *

+ * 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. + *

+ * + * @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-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/RequestFailedException.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/RequestFailedException.java new file mode 100644 index 000000000..13df3900c --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/RequestFailedException.java @@ -0,0 +1,255 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.impl; + +import org.glassfish.grizzly.http.util.HttpStatus; +import com.att.cdp.zones.model.Server; +import com.att.cdp.zones.model.Stack; + +/** + * 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 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalog.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalog.java new file mode 100644 index 000000000..c078eb7b3 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalog.java @@ -0,0 +1,310 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.impl; + +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; +import com.att.cdp.exceptions.ZoneException; +import com.att.cdp.zones.spi.RequestState; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.cdp.zones.spi.AbstractService.State; +import com.woorea.openstack.keystone.model.Access; +import com.woorea.openstack.keystone.model.Access.Service; +import com.woorea.openstack.keystone.model.Tenant; + +/** + * This class is used to capture and cache the service catalog for a specific OpenStack provider. + *

+ * 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. + *

+ *

+ * 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. + *

+ *

+ * 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. + *

+ *

+ * 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. + *

+ */ +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 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 tenantIdentifier 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 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 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. + *

+ * This method is used to track requests made to the various service implementations and to provide additional + * information for diagnostic purposes. The RequestState class stores the state in thread-local storage + * and is available to all code on that thread. + *

+ *

+ * 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". + *

+ * + * @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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogFactory.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogFactory.java new file mode 100644 index 000000000..4c759b2c6 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogFactory.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.impl; + +import java.util.Properties; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ServiceCatalogFactory { + + private static EELFLogger logger= EELFManager.getInstance().getLogger(org.onap.appc.adapter.iaas.impl.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 ceredential 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(); + if(version == null){ + logger.error("Invalid Identity URL check configuration"); + return null; + } + String prefix = version.split("\\.")[0]; + if (prefix != null) { + switch (prefix) { + case "v2": + return new ServiceCatalogV2(url, projectIdentifier, principal, credential, properties); + case "v3": + return new ServiceCatalogV3(url, projectIdentifier, principal, credential, domain, properties); + } + } + return null; + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV2.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV2.java new file mode 100644 index 000000000..1e7112cd3 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV2.java @@ -0,0 +1,380 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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.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. + *

+ * 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. + *

+ *

+ * 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. + *

+ *

+ * 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. + *

+ *

+ * 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. + *

+ */ +public class ServiceCatalogV2 extends ServiceCatalog { + + /** + * 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> serviceEndpoints; + + /** + * A map of service types that are published + */ + private Map 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) { + e.printStackTrace(); + return; + } + Keystone keystone = new Keystone(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(); + 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 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 getRegions() { + Lock readLock = rwLock.readLock(); + readLock.lock(); + try { + return regions; + } finally { + readLock.unlock(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public List getServiceTypes() { + Lock readLock = rwLock.readLock(); + readLock.lock(); + try { + ArrayList 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(ServiceCatalog.COMPUTE_SERVICE)) { + String endpointUrl = endpoint.getPublicURL(); + Matcher matcher = urlPattern.matcher(endpointUrl); + if (matcher.matches()) { + if (url.getHost().equals(matcher.group(1))) { + if (url.getPort() != null) { + if (!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 (String serviceType : serviceEndpoints.keySet()) { + List endpoints = serviceEndpoints.get(serviceType); + Service service = serviceTypes.get(serviceType); + + 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 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 endpoints = service.getEndpoints(); + for (Service.Endpoint endpoint : endpoints) { + List 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(); + if (accessKey != null && accessKey.getToken() != null) { + 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(); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV3.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV3.java new file mode 100644 index 000000000..b1c47e5d5 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV3.java @@ -0,0 +1,402 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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. + *

+ * 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. + *

+ *

+ * 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. + *

+ *

+ * 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. + *

+ *

+ * 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. + *

+ */ +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> serviceEndpoints; + + /** + * A map of service types that are published + */ + private Map 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) { + e.printStackTrace(); + return; + } + Keystone keystone = new Keystone(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 = null; + if (projectIdentifier.length() == 32 && projectIdentifier.matches("[0-9a-fA-F]+")) { //$NON-NLS-1$ + // authenticate = authenticate.withTenantId(projectIdentifier); + scope = Scope.project(projectIdentifier); + } else { + // authenticate = authenticate.withTenantName(projectIdentifier); + scope = Scope.project(domain, projectIdentifier); + } + + 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(); + 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 ex) { + throw new ContextConnectionException(ex.getMessage()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public List 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() { + Lock readLock = rwLock.readLock(); + readLock.lock(); + try { + return project.getName(); + } finally { + readLock.unlock(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Set getRegions() { + Lock readLock = rwLock.readLock(); + readLock.lock(); + try { + return regions; + } finally { + readLock.unlock(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public List getServiceTypes() { + Lock readLock = rwLock.readLock(); + readLock.lock(); + try { + ArrayList 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(ServiceCatalog.COMPUTE_SERVICE)) { + String endpointUrl = endpoint.getUrl(); + Matcher matcher = urlPattern.matcher(endpointUrl); + if (matcher.matches()) { + if (url.getHost().equals(matcher.group(1))) { + if (url.getPort() != null) { + if (!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]\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) { + builder.append("\t" + region + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + builder.append(String.format("%d services:\n", serviceEndpoints.size())); //$NON-NLS-1$ + for (String serviceType : serviceEndpoints.keySet()) { + List endpoints = serviceEndpoints.get(serviceType); + Service service = serviceTypes.get(serviceType); + + builder.append(String.format("\t%s - %d endpoints\n", service.getType(), //$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.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 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 endpoints = service.getEndpoints(); + for (Service.Endpoint endpoint : endpoints) { + List 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(Token accessToken) { + Date now = Time.getCurrentUTCDate(); + if (accessToken != null) { + 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(); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/TenantCache.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/TenantCache.java new file mode 100644 index 000000000..659202d1c --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/TenantCache.java @@ -0,0 +1,382 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.impl; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.onap.appc.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.i18n.Msg; +import org.onap.appc.pool.Allocator; +import org.onap.appc.pool.Destructor; +import org.onap.appc.pool.Pool; +import org.onap.appc.pool.PoolSpecificationException; +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 com.woorea.openstack.connector.JaxRs20Connector; +// import com.sun.jersey.api.client.ClientHandlerException; +import com.woorea.openstack.keystone.model.Access.Service.Endpoint; + +/** + * This class maintains a cache of tenants within a specific provider. + *

+ * 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. + *

+ */ +public class TenantCache implements Allocator, Destructor { + + 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.JerseyConnector"; + 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> 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; + configuration = ConfigurationFactory.getConfiguration(); + } + + /** + * @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. + *

+ * 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. + *

+ *

+ * 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. + *

+ *

+ * 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. + *

+ */ + 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 = ServiceCatalogFactory.getServiceCatalog(url, tenant, userid, password, domain, 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(); + + for (String region : catalog.getRegions()) { + try { + Pool pool = new Pool<>(min, max); + pool.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, url); + pool.setProperty(ContextFactory.PROPERTY_TENANT, tenantName); + 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); + e.printStackTrace(); + } + } + initialized = true; + break; + } catch (ContextConnectionException e) { + attempt++; + 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)); + + try { + Thread.sleep(delay * 1000L); + } catch (InterruptedException ie) { + // ignore + } + } + } catch (ZoneException e) { + logger.error(e.getMessage()); + break; + } + } + + if (!initialized) { + logger.error(Msg.CONNECTION_FAILED, provider.getProviderName(), url); + } + } + + /** + * 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> getPools() { + return pools; + } + + /** + * @see org.onap.appc.pool.Allocator#allocate(org.onap.appc.pool.Pool) + */ + @SuppressWarnings("unchecked") + @Override + public Context allocate(Pool pool) { + logger.debug("Allocationg context for pool"); + Class providerClass; + try { + providerClass = (Class) Class.forName("com.att.cdp.openstack.OpenStackProvider"); + // String providerType = provider.getProviderType(); + + // Context context = ContextFactory.getContext(providerType, pool.getProperties()); + 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); + e.printStackTrace(); + } + return null; + } + + /** + * @see org.onap.appc.pool.Destructor#destroy(java.lang.Object, org.onap.appc.pool.Pool) + */ + @Override + public void destroy(Context context, Pool pool) { + try { + context.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * @return the service catalog for this provider + */ + public ServiceCatalog getServiceCatalog() { + return catalog; + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/VMURL.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/VMURL.java new file mode 100644 index 000000000..777327cad --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/VMURL.java @@ -0,0 +1,175 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/api/IProviderOperation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/api/IProviderOperation.java new file mode 100644 index 000000000..3417762d1 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/api/IProviderOperation.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.api; + +import org.onap.appc.adapter.iaas.impl.ProviderCache; +import org.onap.appc.exceptions.APPCException; +import com.att.cdp.zones.model.ModelObject; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import java.util.Map; + +/** + * @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 params, SvcLogicContext context) throws APPCException; + + /** + * sets a cache of providers that are predefined. + * + * @param providerCache + */ + void setProviderCache(Map 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 defaultPass + */ + void setDefaultPass(String defaultPass); +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/api/ProviderOperationFactory.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/api/ProviderOperationFactory.java new file mode 100644 index 000000000..1eed4ef90 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/api/ProviderOperationFactory.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.api; + +import org.onap.appc.adapter.iaas.provider.operation.impl.*; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; +import org.onap.appc.exceptions.APPCException; +import java.util.HashMap; +import java.util.Map; + +/** + * 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 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 APPCException { + + 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; + default: + throw new APPCException("Unsupported provider operation."); + } + operations.put(op, opObject); + } + return opObject; + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/constants/Constants.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/constants/Constants.java new file mode 100644 index 000000000..503cb1ae8 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/constants/Constants.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.common.constants; + +/** + * @since September 26, 2016 + */ +public class Constants { + + 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 = ' '; +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/constants/Property.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/constants/Property.java new file mode 100644 index 000000000..90532b92d --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/constants/Property.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.common.constants; + +/** + * @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"; +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/enums/Operation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/enums/Operation.java new file mode 100644 index 000000000..2f81fab9c --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/enums/Operation.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.common.enums; + +/** + * @since September 26, 2016 + */ +public enum Operation { + EVACUATE_SERVICE { + public String toString() { + return "evacuateServer"; + } + }, + MIGRATE_SERVICE { + public String toString() { + return "migrateServer"; + } + }, + REBUILD_SERVICE { + public String toString() { + return "rebuildServer"; + } + }, + RESTART_SERVICE { + public String toString() { + return "restartServer"; + } + }, + VMSTATUSCHECK_SERVICE { + public String toString() { + return "vmStatuschecker"; + } + }, + SNAPSHOT_SERVICE { + public String toString() { + return "createSnapshot"; + } + }, + TERMINATE_STACK { + public String toString() { + return "terminateStack"; + } + }, + SNAPSHOT_STACK { + public String toString() { + return "snapshotStack"; + } + }, + START_SERVICE { + public String toString() { + return "startServer"; + } + }, + STOP_SERVICE { + public String toString() { + return "stopServer"; + } + }, + TERMINATE_SERVICE { + public String toString() { + return "terminateServer"; + } + }, + LOOKUP_SERVICE { + public String toString() { + return "lookupServer"; + } + }, + RESTORE_STACK { + public String toString() { + return "restoreStack"; + } + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/enums/Outcome.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/enums/Outcome.java new file mode 100644 index 000000000..972409174 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/common/enums/Outcome.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.common.enums; + +/** + * @since September 26, 2016 + */ +public enum Outcome { + FAILURE { + public String toString() { + return "failure"; + } + }, + SUCCESS { + public String toString() { + return "success"; + } + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java new file mode 100644 index 000000000..5165b0ce0 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java @@ -0,0 +1,233 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.IdentityURL; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.impl.VMURL; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import org.slf4j.MDC; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import java.util.TimeZone; +import static org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants.DATE_FORMAT; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +public class CreateSnapshot extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(CreateSnapshot.class); + private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + private String generateSnapshotName(String server) { + setTimeForMetricsLogger(); + + SimpleDateFormat df = new SimpleDateFormat(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 snapshot = null; + while (rc.attempt()) { + try { + snapshot = service.getImageByName(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 params, SvcLogicContext ctx) throws APPCException { + Image snapshot = 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + VMURL vm = VMURL.parseURL(vm_url); + if (validateVM(rc, appName, vm_url, vm)) + return null; + + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + + Context context = null; + try { + context = getContext(rc, vm_url, identStr); + if (context != null) { + Server server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString()); + + if (hasImageAccess(rc, context)) { + snapshot = createSnapshot(rc, server); + doSuccess(rc); + } 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(); + } + } catch (ResourceNotFoundException e) { + msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); + logger.error(msg); + metricsLogger.error(msg, e); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg); + } catch (Exception e1) { + msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), + Operation.SNAPSHOT_SERVICE.toString(), vm_url, + context == null ? "Unknown" : context.getTenantName()); + logger.error(msg, e1); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + } catch (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + } + return snapshot; + } + + @Override + protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) + throws APPCException { + + setMDC(Operation.SNAPSHOT_SERVICE.toString(), "App-C IaaS Adapter:Snapshot", ADAPTER_NAME); + logOperation(Msg.SNAPSHOTING_SERVER, params, context); + setTimeForMetricsLogger(); + + metricsLogger.info("Executing Provider Operation: Create Snapshot"); + + return createSnapshot(params, context); + } + + private void setTimeForMetricsLogger() { + long startTime = System.currentTimeMillis(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + df.setTimeZone(tz); + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + String durationStr = String.valueOf(duration); + String endTimeStrUTC = df.format(new Date()); + MDC.put("EndTimestamp", endTimeStrUTC); + MDC.put("ElapsedTime", durationStr); + MDC.put("TargetEntity", "cdp"); + MDC.put("TargetServiceName", "create snapshot"); + MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.CreateSnapshot"); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java new file mode 100644 index 000000000..7ddcd37e6 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java @@ -0,0 +1,355 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.impl; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.IdentityURL; +import org.onap.appc.adapter.iaas.impl.ProviderAdapterImpl; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.impl.VMURL; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +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.Status; +import com.att.cdp.zones.model.Hypervisor.State; +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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.slf4j.MDC; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +public class EvacuateServer extends ProviderServerOperation { + + 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 target_host) + 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() ..."); + } + + SetTimeForMetricsLogger(); + + String msg; + try { + while (rc.attempt()) { + try { + logger.debug("Calling CDP moveServer - server id = " + server.getId()); + service.moveServer(server.getId(), target_host); + // Wait for completion, expecting the server to go to a non pending state + waitForStateChange(rc, 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(), service.getURL(), + ctx.getTenant().getName(), ctx.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(); + } + } + + } catch (ZoneException e) { + msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(), + e.getMessage()); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Evacute 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(); + } + + + /** + * @see org.onap.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map, + * org.openecomp.sdnc.sli.SvcLogicContext) + */ + private Server evacuateServer(Map params, SvcLogicContext ctx) throws APPCException { + 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + VMURL vm = VMURL.parseURL(vm_url); + if (validateVM(rc, appName, vm_url, vm)) + return null; + + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + + // retrieve the optional parameters + String rebuild_vm = params.get(ProviderAdapter.PROPERTY_REBUILD_VM); + String targethost_id = params.get(ProviderAdapter.PROPERTY_TARGETHOST_ID); + + Context context = null; + try { + context = getContext(rc, vm_url, identStr); + if (context != null) { + + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString()); + + // check target host status + if (isComputeNodeDown(context, targethost_id)) { + msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(), + "Target host " + targethost_id + " status is not UP/ENABLED"); + logger.error(msg); + metricsLogger.error(msg); + throw new RequestFailedException("Evacuate Server", msg, HttpStatus.BAD_REQUEST_400, server); + } + + // save hypervisor name before evacuate + String hypervisor = server.getHypervisor().getHostName(); + + evacuateServer(rc, server, targethost_id); + + server.refreshAll(); + String hypervisor_after_evacuate = server.getHypervisor().getHostName(); + logger.debug("Hostname before evacuate: " + hypervisor + ", After evacuate: " + + hypervisor_after_evacuate); + + // check hypervisor host name after evacuate. If it is unchanged, the evacuate + // failed. + if ((hypervisor != null) && (hypervisor.equals(hypervisor_after_evacuate))) { + 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); + + } + + // check VM status after evacuate + if (server.getStatus() == Server.Status.ERROR) { + 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); + } + + context.close(); + doSuccess(rc); + 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 ((rebuild_vm == null) || !(rebuild_vm.equalsIgnoreCase("false"))) { + List 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. + String rebuildErrorCode = + ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE); + if (rebuildErrorCode != null) { + try { + int error_code = Integer.parseInt(rebuildErrorCode); + if (error_code != HttpStatus.OK_200.getStatusCode()) { + logger.debug("Rebuild after evacuate failed - error code=" + error_code + + ", message=" + ctx.getAttribute( + org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE)); + msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED, + server.getName(), hypervisor, hypervisor_after_evacuate, + ctx.getAttribute(org.onap.appc.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(error_code), msg); + } + } catch (NumberFormatException e) { + // ignore + } + } + } + } + + } + } catch (ResourceNotFoundException e) { + msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); + logger.error(msg); + metricsLogger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg); + } catch (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + } catch (Exception e1) { + msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), + Operation.EVACUATE_SERVICE.toString(), vm_url, + context == null ? "Unknown" : context.getTenantName()); + logger.error(msg, e1); + metricsLogger.error(msg, e1); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + } catch (RequestFailedException e) { + msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage()); + logger.error(msg); + metricsLogger.error(msg); + doFailure(rc, e.getStatus(), e.getMessage()); + } + + return 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 node_down = false; + + // Check host status. A node is considered down only if a matching target host is + // found and it's state/status is not UP/ENABLED. + if ((host != null) && !(host.isEmpty())) { + List hypervisors = service.getHypervisors(); + logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray())); + for (Hypervisor h : hypervisors) { + if (h.getHostName().startsWith(host)) { + // host matches one of the hypervisors + State hstate = h.getState(); + Status hstatus = h.getStatus(); + logger.debug("Host matching hypervisor: " + h.getHostName() + ", State/Status: " + hstate.toString() + + "/" + hstatus.toString()); + if (hstate != State.UP || hstatus != Status.ENABLED) { + node_down = true; + } + } + } + } + return node_down; + } + + @Override + protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) + throws APPCException { + setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", ADAPTER_NAME); + logOperation(Msg.EVACUATING_SERVER, params, context); + + SetTimeForMetricsLogger(); + + metricsLogger.info("Executing Provider Operation: Evacuate"); + return evacuateServer(params, context); + } + + private void SetTimeForMetricsLogger() { + long startTime = System.currentTimeMillis(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + df.setTimeZone(tz); + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + String durationStr = String.valueOf(duration); + String endTimeStrUTC = df.format(new Date()); + MDC.put("EndTimestamp", endTimeStrUTC); + MDC.put("ElapsedTime", durationStr); + MDC.put("TargetEntity", "cdp"); + MDC.put("TargetServiceName", "evacuate server"); + MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer"); + } + + public void setProvideAdapterRef(ProviderAdapterImpl pai) { + paImpl = pai; + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/LookupServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/LookupServer.java new file mode 100644 index 000000000..924322d1f --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/LookupServer.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.impl; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.impl.VMURL; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.glassfish.grizzly.http.util.HttpStatus; +import java.io.IOException; +import java.util.Map; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +public class LookupServer extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class); + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + + public Server lookupServer(Map params, SvcLogicContext ctx) throws APPCException { + Server server = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); // should we test the return and fail if false? + + String vm_url = null; + try { + // process vm_url + validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, + ProviderAdapter.PROPERTY_PROVIDER_NAME); + + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + VMURL vm = VMURL.parseURL(vm_url); + if (validateVM(rc, appName, vm_url, vm)) { + return null; + } + + // use try with resource to ensure context is closed (returned to pool) + try (Context context = resolveContext(rc, params, appName, vm_url)) { + // resloveContext & getContext call doFailure and log errors before returning null + if (context != null) { + rc.reset(); + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString()); + ctx.setAttribute("serverFound", "success"); + String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "LookupServer", vm_url); + ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + doSuccess(rc); + } + } catch (ZoneException e) { + // server not found + String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); + logger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg); + ctx.setAttribute("serverFound", "failure"); + } catch (IOException e) { + // exception closing context + String msg = EELFResourceManager.format(Msg.CLOSE_CONTEXT_FAILED, e, vm_url); + logger.error(msg); + } catch (Exception e1) { + String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, + e1.getClass().getSimpleName(), Operation.LOOKUP_SERVICE.toString(), vm_url, "Unknown"); + logger.error(msg, e1); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + + } catch (RequestFailedException e) { + // parameters not valid, unable to connect to provider + String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); + logger.error(msg); + doFailure(rc, HttpStatus.NOT_FOUND_404, msg); + ctx.setAttribute("serverFound", "failure"); + } + return server; + } + + @Override + protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) + throws APPCException { + setMDC(Operation.LOOKUP_SERVICE.toString(), "App-C IaaS Adapter:LookupServer", ADAPTER_NAME); + logOperation(Msg.LOOKING_SERVER_UP, params, context); + return lookupServer(params, context); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/MigrateServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/MigrateServer.java new file mode 100644 index 000000000..b28918c09 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/MigrateServer.java @@ -0,0 +1,240 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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.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 org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.IdentityURL; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.impl.VMURL; +import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.slf4j.MDC; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.Map; +import java.util.TimeZone; +import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.MIGRATE_SERVICE; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +public class MigrateServer extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class); + private static 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 migratableStatuses = + Arrays.asList(Server.Status.READY, Server.Status.RUNNING, Server.Status.SUSPENDED); + + + private String getConnectionExceptionMessage(RequestContext rc, Context ctx, ContextConnectionException 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 || (!skipHypervisorCheck.equalsIgnoreCase("true"))) { + // Check of the Hypervisor for the VM Server is UP and reachable + checkHypervisor(server); + } + + boolean inConfirmPhase = false; + 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; + } + + // Verify resize + service.processResize(server); + // 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); + logger.error(msg, e); + metricsLogger.error(msg, e); + 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()); + generateEvent(rc, false, msg); + logger.error(msg, e); + metricsLogger.error(msg, e); + throw new RequestFailedException("Migrate Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server); + } + } + + /** + * @see org.onap.appc.adapter.iaas.ProviderAdapter#migrateServer(java.util.Map, + * org.openecomp.sdnc.sli.SvcLogicContext) + */ + private Server migrateServer(Map params, SvcLogicContext ctx) throws APPCException { + 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + VMURL vm = VMURL.parseURL(vm_url); + if (validateVM(rc, appName, vm_url, vm)) + return null; + + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + + Context context = null; + try { + context = getContext(rc, vm_url, identStr); + if (context != null) { + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString()); + migrateServer(rc, server, ctx); + server.refreshStatus(); + context.close(); + doSuccess(rc); + } + } catch (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + } catch (ResourceNotFoundException e) { + msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); + 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(), + MIGRATE_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); + logger.error(msg, e1); + metricsLogger.error(msg); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + } catch (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + } + + return server; + } + + @Override + protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) + throws APPCException { + setMDC(Operation.MIGRATE_SERVICE.toString(), "App-C IaaS Adapter:Migrate", ADAPTER_NAME); + logOperation(Msg.MIGRATING_SERVER, params, context); + + setTimeForMetricsLogger(); + + metricsLogger.info("Executing Provider Operation: Migrate"); + + return migrateServer(params, context); + } + + private void setTimeForMetricsLogger() { + long startTime = System.currentTimeMillis(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + df.setTimeZone(tz); + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + String durationStr = String.valueOf(duration); + String endTimeStrUTC = df.format(new Date()); + MDC.put("EndTimestamp", endTimeStrUTC); + MDC.put("ElapsedTime", durationStr); + MDC.put("TargetEntity", "cdp"); + MDC.put("TargetServiceName", "migrate server"); + MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.MigrateServer"); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RebuildServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RebuildServer.java new file mode 100644 index 000000000..a2b27f29a --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RebuildServer.java @@ -0,0 +1,434 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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.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 org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.IdentityURL; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.impl.VMURL; +import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.slf4j.MDC; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; +import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.STOP_SERVICE; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +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(); + + /** + * 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(10L * 1000L); + } catch (InterruptedException e) { + logger.trace("Sleep threw interrupted exception, should never occur"); + metricsLogger.trace("Sleep threw interrupted exception, should never occur"); + } + } 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. + *

+ * 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. + *

+ * + * @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 exception for non image/snap boot source + if (ServerBootSource.VOLUME.equals(builtFrom)) { + 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 || (!skipHypervisorCheck.equalsIgnoreCase("true"))) { + // Check of the Hypervisor for the VM Server is UP and reachable + checkHypervisor(server); + } + + /* + * Get the image to use. This is determined by the presence or absence of snapshot images. If any snapshots + * exist, then the latest snapshot is used, otherwise the image used to construct the VM is used. + */ + List snapshots = server.getSnapshots(); + String imageToUse; + if (snapshots != null && !snapshots.isEmpty()) { + imageToUse = snapshots.get(0).getId(); + } else { + imageToUse = server.getImage(); + ImageService imageService = server.getContext().getImageService(); + 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 org.onap.appc.adapter.iaas.ProviderAdapter#rebuildServer(java.util.Map, + * org.openecomp.sdnc.sli.SvcLogicContext) + */ + @SuppressWarnings("nls") + public Server rebuildServer(Map params, SvcLogicContext ctx) throws APPCException { + 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + VMURL vm = VMURL.parseURL(vm_url); + if (validateVM(rc, appName, vm_url, 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; + try { + context = getContext(rc, vm_url, identStr); + if (context != null) { + rc.reset(); + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), 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 (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + ctx.setAttribute("REBUILD_STATUS", "ERROR"); + } catch (ResourceNotFoundException e) { + msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); + 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(), + STOP_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); + ctx.setAttribute("REBUILD_STATUS", "ERROR"); + logger.error(msg, e1); + metricsLogger.error(msg); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); + } + } catch (RequestFailedException e) { + doFailure(rc, e.getStatus(), e.getMessage()); + ctx.setAttribute("REBUILD_STATUS", "ERROR"); + } + + return server; + } + + @Override + protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) + throws APPCException { + setMDC(Operation.REBUILD_SERVICE.toString(), "App-C IaaS Adapter:Rebuild", ADAPTER_NAME); + logOperation(Msg.REBUILDING_SERVER, params, context); + + setTimeForMetricsLogger(); + + metricsLogger.info("Executing Provider Operation: Rebuild"); + + return rebuildServer(params, context); + } + + private void setTimeForMetricsLogger() { + long startTime = System.currentTimeMillis(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + df.setTimeZone(tz); + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + String durationStr = String.valueOf(duration); + String endTimeStrUTC = df.format(new Date()); + MDC.put("EndTimestamp", endTimeStrUTC); + MDC.put("ElapsedTime", durationStr); + MDC.put("TargetEntity", "cdp"); + MDC.put("TargetServiceName", "rebuild server"); + MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.RebuildServer"); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RestartServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RestartServer.java new file mode 100644 index 000000000..cc30ca833 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RestartServer.java @@ -0,0 +1,275 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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 org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.IdentityURL; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.impl.VMURL; +import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.appc.exceptions.UnknownProviderException; +import org.onap.appc.i18n.Msg; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.slf4j.MDC; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import java.util.TimeZone; +import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.RESTART_SERVICE; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +public class RestartServer extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestartServer.class); + private static 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(), "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 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. + *

+ * The fully qualified URL contains enough information to locate the appropriate server. The URL is of the form + * + *

+     *  [scheme]://[host[:port]] / [path] / [tenant_id] / servers / [vm_id]
+     * 
+ * + * 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. + *

+ * + * @throws UnknownProviderException If the provider cannot be found + * @throws IllegalArgumentException if the expected argument(s) are not defined or are invalid + * @see org.onap.appc.adapter.iaas.ProviderAdapter#restartServer(java.util.Map, + * org.openecomp.sdnc.sli.SvcLogicContext) + */ + @SuppressWarnings("nls") + private Server restartServer(Map params, SvcLogicContext ctx) + throws UnknownProviderException, 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + + VMURL vm = VMURL.parseURL(vm_url); + if (validateVM(rc, appName, vm_url, vm)) + return null; + + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + + Context context = null; + try { + context = getContext(rc, vm_url, identStr); + if (context != null) { + rc.reset(); + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), 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", vm_url); + ctx.setAttribute(org.onap.appc.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, vm_url); + 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(), RESTART_SERVICE.toString(), vm_url, + context == null ? "Unknown" : context.getTenantName()); + 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 params, SvcLogicContext context) + throws UnknownProviderException { + setMDC(RESTART_SERVICE.toString(), "App-C IaaS Adapter:Restart", 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) { + long startTime = System.currentTimeMillis(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + df.setTimeZone(tz); + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + String durationStr = String.valueOf(duration); + String endTimeStrUTC = df.format(new Date()); + MDC.put("EndTimestamp", endTimeStrUTC); + MDC.put("ElapsedTime", durationStr); + MDC.put("TargetEntity", "cdp"); + MDC.put("TargetServiceName", targetServiceName); + MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.RestartServer"); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RestoreStack.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RestoreStack.java new file mode 100644 index 000000000..7eeb23783 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/RestoreStack.java @@ -0,0 +1,151 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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 org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderStackOperation; +import org.onap.appc.adapter.openstack.heat.SnapshotResource; +import org.onap.appc.adapter.openstack.heat.StackResource; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import java.util.Map; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +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 params, SvcLogicContext ctx) + throws IllegalArgumentException, APPCException { + 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 vm_url = null; + Context context = null; + + 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); + vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + String snapshotId = params.get(ProviderAdapter.PROPERTY_INPUT_SNAPSHOT_ID); + + context = resolveContext(rc, params, appName, vm_url); + + if (context != null) { + stack = lookupStack(rc, context, stackId); + logger.debug(Msg.STACK_FOUND, vm_url, context.getTenantName(), 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, vm_url); + 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", vm_url, null == context ? "n/a" : context.getTenantName()); + logger.error(msg, e1); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, e1); + } + return stack; + } + + @Override + protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) + throws APPCException { + setMDC(Operation.RESTORE_STACK.toString(), "App-C IaaS Adapter:Restore-Stack", ADAPTER_NAME); + logOperation(Msg.RESTORING_STACK, params, context); + return restoreStack(params, context); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java new file mode 100644 index 000000000..bf7ebc755 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java @@ -0,0 +1,193 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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 org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderStackOperation; +import org.onap.appc.adapter.openstack.heat.SnapshotResource; +import org.onap.appc.adapter.openstack.heat.StackResource; +import org.onap.appc.adapter.openstack.heat.model.CreateSnapshotParams; +import org.onap.appc.adapter.openstack.heat.model.Snapshot; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.slf4j.MDC; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import java.util.TimeZone; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +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 params, SvcLogicContext ctx) + throws IllegalArgumentException, APPCException { + Stack stack = null; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + ctx.setAttribute("SNAPSHOT_STATUS", "STACK_NOT_FOUND"); + + setTimeForMetricsLogger(); + + String vm_url = null; + Context context = null; + 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); + vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + context = resolveContext(rc, params, appName, vm_url); + + if (context != null) { + stack = lookupStack(rc, context, stackId); + logger.debug(Msg.STACK_FOUND, vm_url, context.getTenantName(), 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, vm_url); + 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", vm_url, null == context ? "n/a" : context.getTenantName()); + logger.error(msg, e1); + metricsLogger.error(msg); + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, e1); + } + return stack; + } + + @Override + protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) + throws APPCException { + setMDC(Operation.SNAPSHOT_STACK.toString(), "App-C IaaS Adapter:Snapshot-Stack", ADAPTER_NAME); + logOperation(Msg.SNAPSHOTING_STACK, params, context); + + setTimeForMetricsLogger(); + + metricsLogger.info("Executing Provider Operation: Snapshot Stack"); + + return snapshotStack(params, context); + } + + private void setTimeForMetricsLogger() { + long startTime = System.currentTimeMillis(); + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + df.setTimeZone(tz); + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + String durationStr = String.valueOf(duration); + String endTimeStrUTC = df.format(new Date()); + MDC.put("EndTimestamp", endTimeStrUTC); + MDC.put("ElapsedTime", durationStr); + MDC.put("TargetEntity", "cdp"); + MDC.put("TargetServiceName", "snapshot stack"); + MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.SnapshotStack"); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/StartServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/StartServer.java new file mode 100644 index 000000000..1dbeacbf3 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/StartServer.java @@ -0,0 +1,184 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.impl; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.IdentityURL; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.impl.VMURL; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.glassfish.grizzly.http.util.HttpStatus; +import java.util.Map; +import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.START_SERVICE; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +public class StartServer extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(StartServer.class); + + /** + * @see org.onap.appc.adapter.iaas.ProviderAdapter#startServer(java.util.Map, + * org.openecomp.sdnc.sli.SvcLogicContext) + */ + @SuppressWarnings("nls") + public Server startServer(Map params, SvcLogicContext ctx) throws APPCException { + 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + + VMURL vm = VMURL.parseURL(vm_url); + if (validateVM(rc, appName, vm_url, 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("START_STATUS", "ERROR"); + try { + context = getContext(rc, vm_url, identStr); + if (context != null) { + rc.reset(); + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString()); + 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, vm_url); + 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(), START_SERVICE.toString(), vm_url, + context == null ? "Unknown" : context.getTenantName()); + 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 params, SvcLogicContext context) + throws APPCException { + setMDC(Operation.START_SERVICE.toString(), "App-C IaaS Adapter:Start", ADAPTER_NAME); + logOperation(Msg.STARTING_SERVER, params, context); + return startServer(params, context); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/StopServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/StopServer.java new file mode 100644 index 000000000..df836b77c --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/StopServer.java @@ -0,0 +1,202 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.impl; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.IdentityURL; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.impl.VMURL; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.glassfish.grizzly.http.util.HttpStatus; +import java.util.Map; +import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.STOP_SERVICE; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +public class StopServer extends ProviderServerOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(StopServer.class); + private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + + /** + * @see org.onap.appc.adapter.iaas.ProviderAdapter#stopServer(java.util.Map, + * org.openecomp.sdnc.sli.SvcLogicContext) + */ + @SuppressWarnings("nls") + public Server stopServer(Map params, SvcLogicContext ctx) throws APPCException { + 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + ctx.setAttribute("STOP_STATUS", "SUCCESS"); + + VMURL vm = VMURL.parseURL(vm_url); + if (validateVM(rc, appName, vm_url, 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"); + try { + context = getContext(rc, vm_url, identStr); + if (context != null) { + rc.reset(); + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString()); + + 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", vm_url); + ctx.setAttribute(org.onap.appc.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, vm_url); + 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(), + STOP_SERVICE.toString(), vm_url, 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 params, SvcLogicContext context) + throws APPCException { + setMDC(STOP_SERVICE.toString(), "App-C IaaS Adapter:Stop", ADAPTER_NAME); + logOperation(Msg.STOPPING_SERVER, params, context); + return stopServer(params, context); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/TerminateServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/TerminateServer.java new file mode 100644 index 000000000..73385ee35 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/TerminateServer.java @@ -0,0 +1,245 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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 org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.IdentityURL; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.impl.VMURL; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.appc.exceptions.UnknownProviderException; +import org.onap.appc.i18n.Msg; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import java.util.Map; +import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.RESTART_SERVICE; +import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.TERMINATE_SERVICE; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +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. + *

+ * The fully qualified URL contains enough information to locate the appropriate server. The URL is of the form + * + *

+     *  [scheme]://[host[:port]] / [path] / [tenant_id] / servers / [vm_id]
+     * 
+ * + * 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. + *

+ * + * @throws UnknownProviderException If the provider cannot be found + * @throws IllegalArgumentException if the expected argument(s) are not defined or are invalid + * @see org.onap.appc.adapter.iaas.ProviderAdapter#terminateServer(java.util.Map, + * org.openecomp.sdnc.sli.SvcLogicContext) + */ + @SuppressWarnings("nls") + public Server terminateServer(Map params, SvcLogicContext ctx) + throws UnknownProviderException, 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + ctx.setAttribute("TERMINATE_STATUS", "SUCCESS"); + + VMURL vm = VMURL.parseURL(vm_url); + if (validateVM(rc, appName, vm_url, vm)) + return null; + + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + + Context context = null; + try { + context = getContext(rc, vm_url, identStr); + if (context != null) { + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), 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, vm_url); + 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(), RESTART_SERVICE.toString(), vm_url, + 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.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 params, SvcLogicContext context) + throws UnknownProviderException { + setMDC(TERMINATE_SERVICE.toString(), "App-C IaaS Adapter:Terminate", ADAPTER_NAME); + logOperation(Msg.TERMINATING_SERVER, params, context); + return terminateServer(params, context); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/TerminateStack.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/TerminateStack.java new file mode 100644 index 000000000..1e3ce1e68 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/TerminateStack.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.impl; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderStackOperation; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.glassfish.grizzly.http.util.HttpStatus; +import java.util.Map; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +public class TerminateStack extends ProviderStackOperation { + + 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 params, SvcLogicContext ctx) + throws IllegalArgumentException, APPCException { + 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + + Context context = resolveContext(rc, params, appName, vm_url); + + try { + if (context != null) { + rc.reset(); + stack = lookupStack(rc, context, stackId); + logger.debug(Msg.STACK_FOUND, vm_url, 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", vm_url); + ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); + } + } catch (ResourceNotFoundException e) { + String msg = EELFResourceManager.format(Msg.STACK_NOT_FOUND, e, vm_url); + 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(), vm_url, 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 params, SvcLogicContext context) + throws APPCException { + setMDC(Operation.TERMINATE_STACK.toString(), "App-C IaaS Adapter:Terminate-Stack", ADAPTER_NAME); + logOperation(Msg.TERMINATING_STACK, params, context); + return terminateStack(params, context); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/VmStatuschecker.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/VmStatuschecker.java new file mode 100644 index 000000000..9185e35fc --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/VmStatuschecker.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.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 org.glassfish.grizzly.http.util.HttpStatus; +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.IdentityURL; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.iaas.impl.VMURL; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.UnknownProviderException; +import org.onap.appc.i18n.Msg; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import java.util.Map; +import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.RESTART_SERVICE; +import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; + +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 params, SvcLogicContext ctx) + throws UnknownProviderException, 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); + + VMURL vm = VMURL.parseURL(vm_url); + if (validateVM(rc, appName, vm_url, vm)) + return null; + + IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); + String identStr = (ident == null) ? null : ident.toString(); + + Context context = null; + try { + context = getContext(rc, vm_url, identStr); + if (context != null) { + server = lookupServer(rc, context, vm.getServerId()); + logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), 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, vm_url); + 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(), RESTART_SERVICE.toString(), vm_url, + context == null ? "Unknown" : context.getTenantName()); + 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 params, SvcLogicContext context) + throws UnknownProviderException { + setMDC(Operation.VMSTATUSCHECK_SERVICE.toString(), "App-C IaaS Adapter:VmStatusCheck", ADAPTER_NAME); + logOperation(Msg.CHECKING_SERVER, params, context); + return vmStatuschecker(params, context); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/base/ProviderOperation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/base/ProviderOperation.java new file mode 100644 index 000000000..2b50dbe8a --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/base/ProviderOperation.java @@ -0,0 +1,453 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.impl.base; + +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.*; +import org.onap.appc.adapter.iaas.provider.operation.api.IProviderOperation; +import org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants; +import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.pool.Pool; +import org.onap.appc.pool.PoolExtensionException; +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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.slf4j.MDC; +import java.net.URI; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import static org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants.MDC_ADAPTER; +import static org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants.MDC_SERVICE; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; + +public abstract class ProviderOperation implements IProviderOperation { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ProviderOperation.class); + protected static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + public void setProviderCache(Map providerCache) { + this.providerCache = providerCache; + } + + /** + * A cache of providers that are predefined. + */ + private Map providerCache; + + + public void setDefaultUser(String defaultUser) { + DEFAULT_USER = defaultUser; + } + + public void setDefaultPass(String defaultPass) { + DEFAULT_PASS = defaultPass; + } + + @Override + public void setDefaultDomain(String defaultDomain) { + DEFAULT_DOMAIN = defaultDomain; + } + + /** + * The username and password to use for dynamically created connections + */ + private static String DEFAULT_USER; + private static String DEFAULT_PASS; + private static String DEFAULT_DOMAIN; + + + /** + * set MDC props + * + * @param service + * @param serviceName + * @param adapterName + */ + protected void setMDC(String service, String serviceName, String adapterName) { + MDC.put(MDC_ADAPTER, adapterName); + MDC.put(MDC_SERVICE, service); + MDC.put(MDC_SERVICE_NAME, serviceName); + } + + /** + * initial log of the operation + * + * @param msg + * @param params + * @param context + */ + protected void logOperation(Msg msg, Map params, SvcLogicContext context) { + + String appName = configuration.getProperty(org.onap.appc.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 parameters) { + for (String key : parameters.keySet()) { + logger.debug(Msg.PROPERTY_VALUE, key, parameters.get(key)); + } + } + + /** + * 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 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 parameters, String... propertyNames) + throws RequestFailedException { + boolean success = true; + StringBuilder msg = + new StringBuilder(EELFResourceManager.format(Msg.MISSING_REQUIRED_PROPERTIES, MDC.get(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. + * @param code + * @param message + */ + protected void doFailure(RequestContext rc, HttpStatus code, String message) { + try { + doFailure(rc, code, message, null); + } catch (APPCException ignored) { + /* never happens */} + } + + protected void doFailure(RequestContext rc, HttpStatus code, String message, Throwable cause) throws APPCException { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + String msg = (message == null) ? code.getReasonPhrase() : message; + if (msg.contains("\n")) { + msg = msg.substring(0, msg.indexOf("\n")); + } + String status; + try { + status = Integer.toString(code.getStatusCode()); + } catch (Exception e) { + status = "500"; + } + svcLogic.setStatus(Outcome.FAILURE.toString()); + svcLogic.setAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE, status); + svcLogic.setAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + + if (null != cause) + throw new APPCException(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(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE, + Integer.toString(HttpStatus.OK_200.getStatusCode())); + } + + protected boolean validateVM(RequestContext rc, String appName, String vm_url, VMURL vm) + throws RequestFailedException { + String msg; + if (vm == null) { + msg = EELFResourceManager.format(Msg.INVALID_SELF_LINK_URL, appName, vm_url); + 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) { + 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()); + // cache.setProviderType("OpenStack"); + + TenantCache tenant = cache.addTenant(vm.getTenantId(), null, DEFAULT_USER, DEFAULT_PASS, DEFAULT_DOMAIN); + + // 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(org.onap.appc.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, DEFAULT_USER, DEFAULT_PASS, DEFAULT_DOMAIN); + + 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 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. + */ + if (context.isStale()) { + context.relogin(); + } + 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; + } + + protected Context resolveContext(RequestContext rc, Map params, String appName, String vm_url) + throws RequestFailedException { + + VMURL vm = VMURL.parseURL(vm_url); + if (vm == null) { + String msg = EELFResourceManager.format(Msg.INVALID_SELF_LINK_URL, appName, vm_url); + 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, vm_url, identStr); + + } + + + + protected abstract ModelObject executeProviderOperation(Map params, SvcLogicContext context) + throws APPCException; + + @Override + public ModelObject doOperation(Map params, SvcLogicContext context) throws APPCException { + + return executeProviderOperation(params, context); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/base/ProviderServerOperation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/base/ProviderServerOperation.java new file mode 100644 index 000000000..9ef82aea2 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/base/ProviderServerOperation.java @@ -0,0 +1,560 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.impl.base; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.impl.*; +import org.onap.appc.i18n.Msg; +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 org.glassfish.grizzly.http.util.HttpStatus; +import java.util.ArrayList; +import java.util.List; + +/** + * @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 + * @throws ZoneException + * @throws RequestFailedException + */ + @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. + *

+ * 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. + *

+ * + * @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 + * @throws NotLoggedInException + */ + @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 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 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, + // HttpStatus.BAD_GATEWAY_502, server); + } + } + + 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. + *

+ * 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. + *

+ * + * @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 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 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, + // HttpStatus.BAD_GATEWAY_502, server); + } + } + + 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 + * @throws ZoneException + * @throws RequestFailedException + */ + @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 + * @throws ZoneException + * @throws RequestFailedException + */ + @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 + * @throws ZoneException + * @throws RequestFailedException + */ + @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 ports = server.getPorts(); + + NetworkService netSvc = context.getNetworkService(); + + String msg; + for (Port port : ports) { + + switch (port.getPortState().toString().toUpperCase()) { + /** + * The port is connected, configured, and usable for communication + */ + case "ONLINE": + Network network = netSvc.getNetworkById(port.getNetwork()); + // Subnet subnet = netSvc.getSubnetById(port.getSubnetId()); + if (!network.getStatus().equals(Network.Status.ACTIVE.toString())) { + msg = EELFResourceManager.format(Msg.SERVER_NETWORK_ERROR, server.getName(), port.getId()); + logger.error(msg); + doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg); + throw new RequestFailedException("VM Server Network is DOWN", msg.toString(), + HttpStatus.PRECONDITION_FAILED_412, server); + } + break; + + /** + * The port is disconnected or powered-off and cannot be used for communication + */ + case "OFFLINE": + msg = EELFResourceManager.format(Msg.SERVER_NETWORK_ERROR, server.getName(), port.getId()); + logger.error(msg); + doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg); + throw new RequestFailedException("VM Server Port status is OFFLINE", msg.toString(), + HttpStatus.PRECONDITION_FAILED_412, server); + + /** + * The port's status is changing because of some event or operation. The final state is yet to be + * determined. + */ + case "PENDING": + msg = EELFResourceManager.format(Msg.SERVER_NETWORK_ERROR, server.getName(), port.getId()); + logger.error(msg); + doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg); + throw new RequestFailedException("VM Server Port status is PENDING", msg.toString(), + HttpStatus.PRECONDITION_FAILED_412, server); + + /** + * The port is in an unknown state and cannot be used. + */ + case "UNKNOWN": + msg = EELFResourceManager.format(Msg.SERVER_NETWORK_ERROR, server.getName(), port.getId()); + logger.error(msg); + doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg); + throw new RequestFailedException("VM Server Port status is UNKNOWN", msg.toString(), + HttpStatus.PRECONDITION_FAILED_412, server); + } + + } + logger.info("Passed the VM Server the Hypervisor status checks.."); + + } + + /** + * 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 = null; + if (server.getHypervisor() != null && server.getHypervisor().getStatus() != null + && server.getHypervisor().getState() != null) { + String status = null; + String state = null; + + 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.toString()); + + // doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg); + throw new RequestFailedException("Hypervisor status DOWN or NOT ENABLED", msg.toString(), + HttpStatus.PRECONDITION_FAILED_412, server); + + } + } else { + msg = EELFResourceManager.format(Msg.HYPERVISOR_STATUS_UKNOWN, server.getName()); + logger.error(msg.toString()); + + throw new RequestFailedException("Unable to determine Hypervisor status", msg.toString(), + HttpStatus.PRECONDITION_FAILED_412, server); + } + + logger.info("Passed the Hypervisor status checks.."); + + } + + /** + * Checks if a Host machine is reachable + * + * @param ipAddress IP Address of the Host Machine. + * @param server The server object representing the Virtual Machine server + * @return boolean + * + */ + /* + * private boolean isHostReachable(String ipAddress) throws IOException { + * + * InetAddress address = InetAddress.getByName(ipAddress); + * + * return address.isReachable(15000); + * + * + * } + */ + +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/base/ProviderStackOperation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/base/ProviderStackOperation.java new file mode 100644 index 000000000..cbf620230 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/base/ProviderStackOperation.java @@ -0,0 +1,194 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.provider.operation.impl.base; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.adapter.iaas.impl.RequestFailedException; +import org.onap.appc.adapter.openstack.heat.StackResource; +import org.onap.appc.i18n.Msg; +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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.woorea.openstack.base.client.OpenStackBaseException; +import org.glassfish.grizzly.http.util.HttpStatus; +import java.util.List; + +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.toUpperCase().equals(expectedStatus)) { + return true; + } else { + try { + Thread.sleep(pollInterval * 1000); + } catch (InterruptedException ignored) { + } + } + 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 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"); + } + } + } + + ctx.setAttribute("TERMINATE_STATUS", "ERROR"); + throw new TimeoutException("Timeout waiting for stack status change"); + + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/SnapshotResource.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/SnapshotResource.java new file mode 100644 index 000000000..549c7b93b --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/SnapshotResource.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat; + +import org.onap.appc.adapter.openstack.heat.model.CreateSnapshotParams; +import org.onap.appc.adapter.openstack.heat.model.Snapshot; +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; + + +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 { + 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 { + 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 { + public ShowSnapshot(String stackName, String stackID, String snapshotID) { + super(client, HttpMethod.GET, "/stacks/" + stackName + "/" + stackID + "/snapshots/" + snapshotID, null, + Snapshot.class); + } + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/StackResource.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/StackResource.java new file mode 100644 index 000000000..5add047f7 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/StackResource.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat; + +import org.onap.appc.adapter.openstack.heat.model.CreateSnapshotParams; +import org.onap.appc.adapter.openstack.heat.model.Snapshot; +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 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 { + public ShowStack(String stackName, String stackID) { + super(client, HttpMethod.GET, "/stacks/" + stackName + "/" + stackID, null, Stack.class); + } + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/CreateSnapshotParams.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/CreateSnapshotParams.java new file mode 100644 index 000000000..642b85367 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/CreateSnapshotParams.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +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) +@Generated("org.jsonschema2pojo") +@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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Data.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Data.java new file mode 100644 index 000000000..df662013a --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Data.java @@ -0,0 +1,229 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import javax.validation.Valid; +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) +@Generated("org.jsonschema2pojo") +@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") + @Valid + private Environment environment; + @JsonProperty("template") + @Valid + private Template template; + @JsonProperty("action") + private String action; + @JsonProperty("project_id") + private String projectId; + @JsonProperty("id") + private String id; + @JsonProperty("resources") + @Valid + 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Environment.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Environment.java new file mode 100644 index 000000000..b5a9ddcad --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Environment.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import javax.validation.Valid; +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) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({"parameters", "resource_registry"}) +public class Environment { + + @JsonProperty("parameters") + @Valid + private Parameters parameters; + @JsonProperty("resource_registry") + @Valid + 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Metadata.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Metadata.java new file mode 100644 index 000000000..08e44b725 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Metadata.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({ + +}) +public class Metadata { + + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Parameters.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Parameters.java new file mode 100644 index 000000000..8adc97a4f --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Parameters.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({ + +}) +public class Parameters { + + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Properties.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Properties.java new file mode 100644 index 000000000..0a7605268 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Properties.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +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) +@Generated("org.jsonschema2pojo") +@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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/ResourceData.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/ResourceData.java new file mode 100644 index 000000000..fea775c71 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/ResourceData.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +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) +@Generated("org.jsonschema2pojo") +@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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/ResourceRegistry.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/ResourceRegistry.java new file mode 100644 index 000000000..d15c1c339 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/ResourceRegistry.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import javax.validation.Valid; +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) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({"resources"}) +public class ResourceRegistry { + + @JsonProperty("resources") + @Valid + 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Resources.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Resources.java new file mode 100644 index 000000000..ffa9f0d1a --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Resources.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({ + +}) +public class Resources { + + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Resources_.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Resources_.java new file mode 100644 index 000000000..e6889b0a7 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Resources_.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import javax.validation.Valid; +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) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({"volume"}) +public class Resources_ { + + @JsonProperty("volume") + @Valid + 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Resources__.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Resources__.java new file mode 100644 index 000000000..c34310556 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Resources__.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import javax.validation.Valid; +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) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({"volume"}) +public class Resources__ { + + @JsonProperty("volume") + @Valid + 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Snapshot.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Snapshot.java new file mode 100644 index 000000000..57c7d5439 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Snapshot.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import javax.validation.Valid; +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) +@Generated("org.jsonschema2pojo") +@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") + @Valid + 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/SnapshotDetails.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/SnapshotDetails.java new file mode 100644 index 000000000..f121ddd70 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/SnapshotDetails.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import javax.validation.Valid; +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) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({"snapshot"}) +public class SnapshotDetails { + + @JsonProperty("snapshot") + @Valid + 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/SnapshotRestoreResponse.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/SnapshotRestoreResponse.java new file mode 100644 index 000000000..482a29f3b --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/SnapshotRestoreResponse.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +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) +@Generated("org.jsonschema2pojo") +@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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Template.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Template.java new file mode 100644 index 000000000..310d711f5 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Template.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import javax.validation.Valid; +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) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({"heat_template_version", "resources"}) +public class Template { + + @JsonProperty("heat_template_version") + private String heatTemplateVersion; + @JsonProperty("resources") + @Valid + 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Volume.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Volume.java new file mode 100644 index 000000000..5943ba71b --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Volume.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import javax.validation.Valid; +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) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({"type", "properties"}) +public class Volume { + + @JsonProperty("type") + private String type; + @JsonProperty("properties") + @Valid + 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Volume_.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Volume_.java new file mode 100644 index 000000000..a8df4a7dc --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/openstack/heat/model/Volume_.java @@ -0,0 +1,187 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.openstack.heat.model; + +import javax.annotation.Generated; +import javax.validation.Valid; +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) +@Generated("org.jsonschema2pojo") +@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") + @Valid + private ResourceData resourceData; + @JsonProperty("resource_id") + private String resourceId; + @JsonProperty("action") + private String action; + @JsonProperty("type") + private String type; + @JsonProperty("metadata") + @Valid + 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/utils/Constants.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/utils/Constants.java new file mode 100644 index 000000000..6b9602a62 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/utils/Constants.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.utils; + + +public class Constants { + + /** + * The name of the adapter + */ + public static final String ADAPTER_NAME = "Appc IaaS Adapter"; +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/AppcProviderAdapterActivator.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/AppcProviderAdapterActivator.java deleted file mode 100644 index fbd650c39..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/AppcProviderAdapterActivator.java +++ /dev/null @@ -1,147 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.impl.ProviderAdapterImpl; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.i18n.Msg; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -/** - * This activator is used to initialize and terminate the connection pool to one or more providers. - *

- * 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. - *

- *

- * 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. - *

- *

- * When the bundle is deactivated, the cache is torn down with all contexts being closed. - *

- */ -public class AppcProviderAdapterActivator implements BundleActivator { - - /** - * The bundle registration - */ - private ServiceRegistration registration = null; - - /** - * The reference to the actual implementation object that implements the services - */ - private ProviderAdapter adapter; - - /** - * The logger to be used - */ - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AppcProviderAdapterActivator.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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @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, "IAAS adapter"); - try { - adapter = new ProviderAdapterImpl(configuration.getProperties()); - } catch (Exception e) { - logger.error("Error initializing APPC IAAS ProviderAdapterImpl", e); - throw e; - } - - if (registration == null) { - logger.info(Msg.REGISTERING_SERVICE, appName, adapter.getAdapterName(), - ProviderAdapter.class.getSimpleName()); - registration = context.registerService(ProviderAdapter.class, adapter, null); - } - - logger.info(Msg.COMPONENT_INITIALIZED, appName, "IAAS 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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @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, "IAAS adapter"); - logger.info(Msg.UNREGISTERING_SERVICE, appName, adapter.getAdapterName()); - registration.unregister(); - registration = null; - logger.info(Msg.COMPONENT_TERMINATED, appName, "IAAS adapter"); - } - } - - public String getName() { - return "APPC IaaS adapter"; - } - -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/ProviderAdapter.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/ProviderAdapter.java deleted file mode 100644 index c14c936e0..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/ProviderAdapter.java +++ /dev/null @@ -1,288 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas; - -import java.util.Map; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.exceptions.UnknownProviderException; -import com.att.cdp.zones.model.Image; -import com.att.cdp.zones.model.Server; -import com.att.cdp.zones.model.Stack; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -/** - * This interface defines the operations that the provider adapter exposes. - *

- * 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. - *

- */ -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"; - - /** - * This method is used to restart an existing virtual machine given the fully qualified URL of the machine. - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 properties, SvcLogicContext context) throws APPCException; - - /** - * This method is used to stop the indicated server - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 properties, SvcLogicContext context) throws APPCException; - - /** - * This method is used to start the indicated server - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 properties, SvcLogicContext context) throws APPCException; - - /** - * This method is used to rebuild the indicated server - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 properties, SvcLogicContext context) throws APPCException; - - /** - * This method is used to terminate the indicated server - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 terminate for some reason - */ - Server terminateServer(Map properties, SvcLogicContext context) throws APPCException; - - /** - * Returns the symbolic name of the adapter - * - * @return The adapter name - */ - String getAdapterName(); - - Server evacuateServer(Map params, SvcLogicContext ctx) throws APPCException; - - Server migrateServer(Map params, SvcLogicContext ctx) throws APPCException; - - Server vmStatuschecker(Map params, SvcLogicContext ctx) throws APPCException; - - Stack terminateStack(Map params, SvcLogicContext ctx) throws APPCException; - - Stack snapshotStack(Map params, SvcLogicContext ctx) throws APPCException; - - Stack restoreStack(Map params, SvcLogicContext ctx) throws APPCException; - - /** - * This method is used to do the lookup of the indicated server - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 found for some reason - */ - Server lookupServer(Map properties, SvcLogicContext context) throws APPCException; - - /** - * 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 Image 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 - */ - Image createSnapshot(Map params, SvcLogicContext ctx) throws APPCException; - -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/IdentityURL.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/IdentityURL.java deleted file mode 100644 index c98edc410..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/IdentityURL.java +++ /dev/null @@ -1,146 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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 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 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ProviderAdapterImpl.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ProviderAdapterImpl.java deleted file mode 100644 index ba6c8c678..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ProviderAdapterImpl.java +++ /dev/null @@ -1,359 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.appc.adapter.iaas.impl; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.provider.operation.api.IProviderOperation; -import org.onap.appc.adapter.iaas.provider.operation.api.ProviderOperationFactory; -import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; -import org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.util.StructuredPropertyHelper; -import org.onap.appc.util.StructuredPropertyHelper.Node; -import com.att.cdp.zones.model.Image; -import com.att.cdp.zones.model.Server; -import com.att.cdp.zones.model.Stack; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -/** - * 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"; - - /** - * The logger to be used - */ - private static final EELFLogger logger = EELFManager.getInstance().getLogger(ProviderAdapterImpl.class); - /** - * A reference to the adapter configuration object. - */ - private Configuration configuration; - - /** - * reference to operation factory - */ - ProviderOperationFactory factory = ProviderOperationFactory.getInstance(); - - /** - * A cache of providers that are predefined. - */ - private Map providerCache; - - /** - * The username, password, and domain to use for dynamically created connections - */ - private static String DEFAULT_USER; - private static String DEFAULT_PASS; - private static String DEFAULT_DOMAIN; - - - /** - * 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 params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.RESTART_SERVICE); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - return (Server) op.doOperation(params, context); - } - - @Override - public Server stopServer(Map params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.STOP_SERVICE); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - return (Server) op.doOperation(params, context); - } - - @Override - public Server startServer(Map params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.START_SERVICE); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - return (Server) op.doOperation(params, context); - } - - @Override - public Server rebuildServer(Map params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.REBUILD_SERVICE); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - return (Server) op.doOperation(params, context); - } - - @Override - public Server terminateServer(Map params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.TERMINATE_SERVICE); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - return (Server) op.doOperation(params, context); - } - - @Override - public Server evacuateServer(Map params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.EVACUATE_SERVICE); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - // 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 params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.MIGRATE_SERVICE); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - return (Server) op.doOperation(params, context); - } - - @Override - public Server vmStatuschecker(Map params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.VMSTATUSCHECK_SERVICE); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - return (Server) op.doOperation(params, context); - } - - @Override - public Stack terminateStack(Map params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.TERMINATE_STACK); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - return (Stack) op.doOperation(params, context); - } - - @Override - public Stack snapshotStack(Map params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.SNAPSHOT_STACK); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - return (Stack) op.doOperation(params, context); - } - - @Override - public Stack restoreStack(Map params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.RESTORE_STACK); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - return (Stack) op.doOperation(params, context); - } - - @Override - public Server lookupServer(Map params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.LOOKUP_SERVICE); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - return (Server) op.doOperation(params, context); - } - - @Override - public Image createSnapshot(Map params, SvcLogicContext context) throws APPCException { - - IProviderOperation op = factory.getOperationObject(Operation.SNAPSHOT_SERVICE); - op.setProviderCache(this.providerCache); - op.setDefaultPass(DEFAULT_PASS); - op.setDefaultUser(DEFAULT_USER); - op.setDefaultDomain(DEFAULT_DOMAIN); - return (Image) op.doOperation(params, context); - } - - /** - * Returns the symbolic name of the adapter - * - * @return The adapter name - * @see org.onap.appc.adapter.iaas.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.

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.

-         * 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 

- */ - providerCache = new HashMap<>(); - Properties properties = configuration.getProperties(); - List providers = StructuredPropertyHelper.getStructuredProperties(properties, Property.PROVIDER); - - for (Node provider : providers) { - ProviderCache cache = new ProviderCache(); - List 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 = 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(); - DEFAULT_USER = node2.getValue(); - break; - case Property.PROVIDER_TENANT_PASSWORD: - password = node2.getValue(); - DEFAULT_PASS = node2.getValue(); - break; - case Property.PROVIDER_TENANT_DOMAIN: - domain = node2.getValue(); - DEFAULT_DOMAIN = node2.getValue(); - 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(); - } - } - -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ProviderCache.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ProviderCache.java deleted file mode 100644 index 5453a9ec1..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ProviderCache.java +++ /dev/null @@ -1,165 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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. - *

- * 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. - *

- */ -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 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 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 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 UserId - * @param password - * @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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/RequestContext.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/RequestContext.java deleted file mode 100644 index ef237f96d..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/RequestContext.java +++ /dev/null @@ -1,249 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.appc.adapter.iaas.impl; - -import org.onap.appc.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.ccsdk.sli.core.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. - *

- * 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. - *

- * - * @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-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/RequestFailedException.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/RequestFailedException.java deleted file mode 100644 index 13df3900c..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/RequestFailedException.java +++ /dev/null @@ -1,255 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.impl; - -import org.glassfish.grizzly.http.util.HttpStatus; -import com.att.cdp.zones.model.Server; -import com.att.cdp.zones.model.Stack; - -/** - * 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 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalog.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalog.java deleted file mode 100644 index c078eb7b3..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalog.java +++ /dev/null @@ -1,310 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.impl; - -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; -import com.att.cdp.exceptions.ZoneException; -import com.att.cdp.zones.spi.RequestState; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.cdp.zones.spi.AbstractService.State; -import com.woorea.openstack.keystone.model.Access; -import com.woorea.openstack.keystone.model.Access.Service; -import com.woorea.openstack.keystone.model.Tenant; - -/** - * This class is used to capture and cache the service catalog for a specific OpenStack provider. - *

- * 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. - *

- *

- * 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. - *

- *

- * 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. - *

- *

- * 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. - *

- */ -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 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 tenantIdentifier 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 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 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. - *

- * This method is used to track requests made to the various service implementations and to provide additional - * information for diagnostic purposes. The RequestState class stores the state in thread-local storage - * and is available to all code on that thread. - *

- *

- * 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". - *

- * - * @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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogFactory.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogFactory.java deleted file mode 100644 index 4c759b2c6..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogFactory.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.impl; - -import java.util.Properties; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ServiceCatalogFactory { - - private static EELFLogger logger= EELFManager.getInstance().getLogger(org.onap.appc.adapter.iaas.impl.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 ceredential 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(); - if(version == null){ - logger.error("Invalid Identity URL check configuration"); - return null; - } - String prefix = version.split("\\.")[0]; - if (prefix != null) { - switch (prefix) { - case "v2": - return new ServiceCatalogV2(url, projectIdentifier, principal, credential, properties); - case "v3": - return new ServiceCatalogV3(url, projectIdentifier, principal, credential, domain, properties); - } - } - return null; - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogV2.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogV2.java deleted file mode 100644 index 1e7112cd3..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogV2.java +++ /dev/null @@ -1,380 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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.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. - *

- * 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. - *

- *

- * 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. - *

- *

- * 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. - *

- *

- * 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. - *

- */ -public class ServiceCatalogV2 extends ServiceCatalog { - - /** - * 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> serviceEndpoints; - - /** - * A map of service types that are published - */ - private Map 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) { - e.printStackTrace(); - return; - } - Keystone keystone = new Keystone(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(); - 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 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 getRegions() { - Lock readLock = rwLock.readLock(); - readLock.lock(); - try { - return regions; - } finally { - readLock.unlock(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public List getServiceTypes() { - Lock readLock = rwLock.readLock(); - readLock.lock(); - try { - ArrayList 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(ServiceCatalog.COMPUTE_SERVICE)) { - String endpointUrl = endpoint.getPublicURL(); - Matcher matcher = urlPattern.matcher(endpointUrl); - if (matcher.matches()) { - if (url.getHost().equals(matcher.group(1))) { - if (url.getPort() != null) { - if (!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 (String serviceType : serviceEndpoints.keySet()) { - List endpoints = serviceEndpoints.get(serviceType); - Service service = serviceTypes.get(serviceType); - - 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 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 endpoints = service.getEndpoints(); - for (Service.Endpoint endpoint : endpoints) { - List 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(); - if (accessKey != null && accessKey.getToken() != null) { - 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(); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogV3.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogV3.java deleted file mode 100644 index b1c47e5d5..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ServiceCatalogV3.java +++ /dev/null @@ -1,402 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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. - *

- * 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. - *

- *

- * 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. - *

- *

- * 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. - *

- *

- * 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. - *

- */ -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> serviceEndpoints; - - /** - * A map of service types that are published - */ - private Map 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) { - e.printStackTrace(); - return; - } - Keystone keystone = new Keystone(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 = null; - if (projectIdentifier.length() == 32 && projectIdentifier.matches("[0-9a-fA-F]+")) { //$NON-NLS-1$ - // authenticate = authenticate.withTenantId(projectIdentifier); - scope = Scope.project(projectIdentifier); - } else { - // authenticate = authenticate.withTenantName(projectIdentifier); - scope = Scope.project(domain, projectIdentifier); - } - - 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(); - 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 ex) { - throw new ContextConnectionException(ex.getMessage()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public List 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() { - Lock readLock = rwLock.readLock(); - readLock.lock(); - try { - return project.getName(); - } finally { - readLock.unlock(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Set getRegions() { - Lock readLock = rwLock.readLock(); - readLock.lock(); - try { - return regions; - } finally { - readLock.unlock(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public List getServiceTypes() { - Lock readLock = rwLock.readLock(); - readLock.lock(); - try { - ArrayList 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(ServiceCatalog.COMPUTE_SERVICE)) { - String endpointUrl = endpoint.getUrl(); - Matcher matcher = urlPattern.matcher(endpointUrl); - if (matcher.matches()) { - if (url.getHost().equals(matcher.group(1))) { - if (url.getPort() != null) { - if (!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]\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) { - builder.append("\t" + region + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - builder.append(String.format("%d services:\n", serviceEndpoints.size())); //$NON-NLS-1$ - for (String serviceType : serviceEndpoints.keySet()) { - List endpoints = serviceEndpoints.get(serviceType); - Service service = serviceTypes.get(serviceType); - - builder.append(String.format("\t%s - %d endpoints\n", service.getType(), //$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.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 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 endpoints = service.getEndpoints(); - for (Service.Endpoint endpoint : endpoints) { - List 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(Token accessToken) { - Date now = Time.getCurrentUTCDate(); - if (accessToken != null) { - 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(); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/TenantCache.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/TenantCache.java deleted file mode 100644 index 659202d1c..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/TenantCache.java +++ /dev/null @@ -1,382 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.impl; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.onap.appc.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.i18n.Msg; -import org.onap.appc.pool.Allocator; -import org.onap.appc.pool.Destructor; -import org.onap.appc.pool.Pool; -import org.onap.appc.pool.PoolSpecificationException; -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 com.woorea.openstack.connector.JaxRs20Connector; -// import com.sun.jersey.api.client.ClientHandlerException; -import com.woorea.openstack.keystone.model.Access.Service.Endpoint; - -/** - * This class maintains a cache of tenants within a specific provider. - *

- * 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. - *

- */ -public class TenantCache implements Allocator, Destructor { - - 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.JerseyConnector"; - 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> 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; - configuration = ConfigurationFactory.getConfiguration(); - } - - /** - * @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. - *

- * 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. - *

- *

- * 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. - *

- *

- * 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. - *

- */ - 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 = ServiceCatalogFactory.getServiceCatalog(url, tenant, userid, password, domain, 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(); - - for (String region : catalog.getRegions()) { - try { - Pool pool = new Pool<>(min, max); - pool.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, url); - pool.setProperty(ContextFactory.PROPERTY_TENANT, tenantName); - 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); - e.printStackTrace(); - } - } - initialized = true; - break; - } catch (ContextConnectionException e) { - attempt++; - 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)); - - try { - Thread.sleep(delay * 1000L); - } catch (InterruptedException ie) { - // ignore - } - } - } catch (ZoneException e) { - logger.error(e.getMessage()); - break; - } - } - - if (!initialized) { - logger.error(Msg.CONNECTION_FAILED, provider.getProviderName(), url); - } - } - - /** - * 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> getPools() { - return pools; - } - - /** - * @see org.onap.appc.pool.Allocator#allocate(org.onap.appc.pool.Pool) - */ - @SuppressWarnings("unchecked") - @Override - public Context allocate(Pool pool) { - logger.debug("Allocationg context for pool"); - Class providerClass; - try { - providerClass = (Class) Class.forName("com.att.cdp.openstack.OpenStackProvider"); - // String providerType = provider.getProviderType(); - - // Context context = ContextFactory.getContext(providerType, pool.getProperties()); - 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); - e.printStackTrace(); - } - return null; - } - - /** - * @see org.onap.appc.pool.Destructor#destroy(java.lang.Object, org.onap.appc.pool.Pool) - */ - @Override - public void destroy(Context context, Pool pool) { - try { - context.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * @return the service catalog for this provider - */ - public ServiceCatalog getServiceCatalog() { - return catalog; - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/VMURL.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/VMURL.java deleted file mode 100644 index 777327cad..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/VMURL.java +++ /dev/null @@ -1,175 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/api/IProviderOperation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/api/IProviderOperation.java deleted file mode 100644 index 3417762d1..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/api/IProviderOperation.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.api; - -import org.onap.appc.adapter.iaas.impl.ProviderCache; -import org.onap.appc.exceptions.APPCException; -import com.att.cdp.zones.model.ModelObject; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import java.util.Map; - -/** - * @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 params, SvcLogicContext context) throws APPCException; - - /** - * sets a cache of providers that are predefined. - * - * @param providerCache - */ - void setProviderCache(Map 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 defaultPass - */ - void setDefaultPass(String defaultPass); -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/api/ProviderOperationFactory.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/api/ProviderOperationFactory.java deleted file mode 100644 index 1eed4ef90..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/api/ProviderOperationFactory.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.api; - -import org.onap.appc.adapter.iaas.provider.operation.impl.*; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; -import org.onap.appc.exceptions.APPCException; -import java.util.HashMap; -import java.util.Map; - -/** - * 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 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 APPCException { - - 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; - default: - throw new APPCException("Unsupported provider operation."); - } - operations.put(op, opObject); - } - return opObject; - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/constants/Constants.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/constants/Constants.java deleted file mode 100644 index 503cb1ae8..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/constants/Constants.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.common.constants; - -/** - * @since September 26, 2016 - */ -public class Constants { - - 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 = ' '; -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/constants/Property.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/constants/Property.java deleted file mode 100644 index 90532b92d..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/constants/Property.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.common.constants; - -/** - * @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"; -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/enums/Operation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/enums/Operation.java deleted file mode 100644 index 2f81fab9c..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/enums/Operation.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.common.enums; - -/** - * @since September 26, 2016 - */ -public enum Operation { - EVACUATE_SERVICE { - public String toString() { - return "evacuateServer"; - } - }, - MIGRATE_SERVICE { - public String toString() { - return "migrateServer"; - } - }, - REBUILD_SERVICE { - public String toString() { - return "rebuildServer"; - } - }, - RESTART_SERVICE { - public String toString() { - return "restartServer"; - } - }, - VMSTATUSCHECK_SERVICE { - public String toString() { - return "vmStatuschecker"; - } - }, - SNAPSHOT_SERVICE { - public String toString() { - return "createSnapshot"; - } - }, - TERMINATE_STACK { - public String toString() { - return "terminateStack"; - } - }, - SNAPSHOT_STACK { - public String toString() { - return "snapshotStack"; - } - }, - START_SERVICE { - public String toString() { - return "startServer"; - } - }, - STOP_SERVICE { - public String toString() { - return "stopServer"; - } - }, - TERMINATE_SERVICE { - public String toString() { - return "terminateServer"; - } - }, - LOOKUP_SERVICE { - public String toString() { - return "lookupServer"; - } - }, - RESTORE_STACK { - public String toString() { - return "restoreStack"; - } - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/enums/Outcome.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/enums/Outcome.java deleted file mode 100644 index 972409174..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/common/enums/Outcome.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.common.enums; - -/** - * @since September 26, 2016 - */ -public enum Outcome { - FAILURE { - public String toString() { - return "failure"; - } - }, - SUCCESS { - public String toString() { - return "success"; - } - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java deleted file mode 100644 index 5165b0ce0..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/CreateSnapshot.java +++ /dev/null @@ -1,233 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.glassfish.grizzly.http.util.HttpStatus; -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.IdentityURL; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.impl.VMURL; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import org.slf4j.MDC; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import static org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants.DATE_FORMAT; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -public class CreateSnapshot extends ProviderServerOperation { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(CreateSnapshot.class); - private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - - private String generateSnapshotName(String server) { - setTimeForMetricsLogger(); - - SimpleDateFormat df = new SimpleDateFormat(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 snapshot = null; - while (rc.attempt()) { - try { - snapshot = service.getImageByName(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 params, SvcLogicContext ctx) throws APPCException { - Image snapshot = 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - VMURL vm = VMURL.parseURL(vm_url); - if (validateVM(rc, appName, vm_url, vm)) - return null; - - IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); - String identStr = (ident == null) ? null : ident.toString(); - - Context context = null; - try { - context = getContext(rc, vm_url, identStr); - if (context != null) { - Server server = lookupServer(rc, context, vm.getServerId()); - logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString()); - - if (hasImageAccess(rc, context)) { - snapshot = createSnapshot(rc, server); - doSuccess(rc); - } 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(); - } - } catch (ResourceNotFoundException e) { - msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); - logger.error(msg); - metricsLogger.error(msg, e); - doFailure(rc, HttpStatus.NOT_FOUND_404, msg); - } catch (Exception e1) { - msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), - Operation.SNAPSHOT_SERVICE.toString(), vm_url, - context == null ? "Unknown" : context.getTenantName()); - logger.error(msg, e1); - doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); - } - } catch (RequestFailedException e) { - doFailure(rc, e.getStatus(), e.getMessage()); - } - return snapshot; - } - - @Override - protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) - throws APPCException { - - setMDC(Operation.SNAPSHOT_SERVICE.toString(), "App-C IaaS Adapter:Snapshot", ADAPTER_NAME); - logOperation(Msg.SNAPSHOTING_SERVER, params, context); - setTimeForMetricsLogger(); - - metricsLogger.info("Executing Provider Operation: Create Snapshot"); - - return createSnapshot(params, context); - } - - private void setTimeForMetricsLogger() { - long startTime = System.currentTimeMillis(); - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - df.setTimeZone(tz); - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; - String durationStr = String.valueOf(duration); - String endTimeStrUTC = df.format(new Date()); - MDC.put("EndTimestamp", endTimeStrUTC); - MDC.put("ElapsedTime", durationStr); - MDC.put("TargetEntity", "cdp"); - MDC.put("TargetServiceName", "create snapshot"); - MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.CreateSnapshot"); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java deleted file mode 100644 index 7ddcd37e6..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/EvacuateServer.java +++ /dev/null @@ -1,355 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.impl; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.IdentityURL; -import org.onap.appc.adapter.iaas.impl.ProviderAdapterImpl; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.impl.VMURL; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -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.Status; -import com.att.cdp.zones.model.Hypervisor.State; -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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.glassfish.grizzly.http.util.HttpStatus; -import org.slf4j.MDC; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -public class EvacuateServer extends ProviderServerOperation { - - 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 target_host) - 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() ..."); - } - - SetTimeForMetricsLogger(); - - String msg; - try { - while (rc.attempt()) { - try { - logger.debug("Calling CDP moveServer - server id = " + server.getId()); - service.moveServer(server.getId(), target_host); - // Wait for completion, expecting the server to go to a non pending state - waitForStateChange(rc, 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(), service.getURL(), - ctx.getTenant().getName(), ctx.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(); - } - } - - } catch (ZoneException e) { - msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(), - e.getMessage()); - logger.error(msg); - metricsLogger.error(msg); - throw new RequestFailedException("Evacute 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(); - } - - - /** - * @see org.onap.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map, - * org.openecomp.sdnc.sli.SvcLogicContext) - */ - private Server evacuateServer(Map params, SvcLogicContext ctx) throws APPCException { - 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - VMURL vm = VMURL.parseURL(vm_url); - if (validateVM(rc, appName, vm_url, vm)) - return null; - - IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); - String identStr = (ident == null) ? null : ident.toString(); - - // retrieve the optional parameters - String rebuild_vm = params.get(ProviderAdapter.PROPERTY_REBUILD_VM); - String targethost_id = params.get(ProviderAdapter.PROPERTY_TARGETHOST_ID); - - Context context = null; - try { - context = getContext(rc, vm_url, identStr); - if (context != null) { - - server = lookupServer(rc, context, vm.getServerId()); - logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString()); - - // check target host status - if (isComputeNodeDown(context, targethost_id)) { - msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(), - "Target host " + targethost_id + " status is not UP/ENABLED"); - logger.error(msg); - metricsLogger.error(msg); - throw new RequestFailedException("Evacuate Server", msg, HttpStatus.BAD_REQUEST_400, server); - } - - // save hypervisor name before evacuate - String hypervisor = server.getHypervisor().getHostName(); - - evacuateServer(rc, server, targethost_id); - - server.refreshAll(); - String hypervisor_after_evacuate = server.getHypervisor().getHostName(); - logger.debug("Hostname before evacuate: " + hypervisor + ", After evacuate: " - + hypervisor_after_evacuate); - - // check hypervisor host name after evacuate. If it is unchanged, the evacuate - // failed. - if ((hypervisor != null) && (hypervisor.equals(hypervisor_after_evacuate))) { - 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); - - } - - // check VM status after evacuate - if (server.getStatus() == Server.Status.ERROR) { - 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); - } - - context.close(); - doSuccess(rc); - 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 ((rebuild_vm == null) || !(rebuild_vm.equalsIgnoreCase("false"))) { - List 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. - String rebuildErrorCode = - ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE); - if (rebuildErrorCode != null) { - try { - int error_code = Integer.parseInt(rebuildErrorCode); - if (error_code != HttpStatus.OK_200.getStatusCode()) { - logger.debug("Rebuild after evacuate failed - error code=" + error_code - + ", message=" + ctx.getAttribute( - org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE)); - msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED, - server.getName(), hypervisor, hypervisor_after_evacuate, - ctx.getAttribute(org.onap.appc.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(error_code), msg); - } - } catch (NumberFormatException e) { - // ignore - } - } - } - } - - } - } catch (ResourceNotFoundException e) { - msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); - logger.error(msg); - metricsLogger.error(msg); - doFailure(rc, HttpStatus.NOT_FOUND_404, msg); - } catch (RequestFailedException e) { - doFailure(rc, e.getStatus(), e.getMessage()); - } catch (Exception e1) { - msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(), - Operation.EVACUATE_SERVICE.toString(), vm_url, - context == null ? "Unknown" : context.getTenantName()); - logger.error(msg, e1); - metricsLogger.error(msg, e1); - doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); - } - } catch (RequestFailedException e) { - msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage()); - logger.error(msg); - metricsLogger.error(msg); - doFailure(rc, e.getStatus(), e.getMessage()); - } - - return 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 node_down = false; - - // Check host status. A node is considered down only if a matching target host is - // found and it's state/status is not UP/ENABLED. - if ((host != null) && !(host.isEmpty())) { - List hypervisors = service.getHypervisors(); - logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray())); - for (Hypervisor h : hypervisors) { - if (h.getHostName().startsWith(host)) { - // host matches one of the hypervisors - State hstate = h.getState(); - Status hstatus = h.getStatus(); - logger.debug("Host matching hypervisor: " + h.getHostName() + ", State/Status: " + hstate.toString() - + "/" + hstatus.toString()); - if (hstate != State.UP || hstatus != Status.ENABLED) { - node_down = true; - } - } - } - } - return node_down; - } - - @Override - protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) - throws APPCException { - setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", ADAPTER_NAME); - logOperation(Msg.EVACUATING_SERVER, params, context); - - SetTimeForMetricsLogger(); - - metricsLogger.info("Executing Provider Operation: Evacuate"); - return evacuateServer(params, context); - } - - private void SetTimeForMetricsLogger() { - long startTime = System.currentTimeMillis(); - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - df.setTimeZone(tz); - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; - String durationStr = String.valueOf(duration); - String endTimeStrUTC = df.format(new Date()); - MDC.put("EndTimestamp", endTimeStrUTC); - MDC.put("ElapsedTime", durationStr); - MDC.put("TargetEntity", "cdp"); - MDC.put("TargetServiceName", "evacuate server"); - MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer"); - } - - public void setProvideAdapterRef(ProviderAdapterImpl pai) { - paImpl = pai; - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/LookupServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/LookupServer.java deleted file mode 100644 index 924322d1f..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/LookupServer.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.impl; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.impl.VMURL; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.glassfish.grizzly.http.util.HttpStatus; -import java.io.IOException; -import java.util.Map; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -public class LookupServer extends ProviderServerOperation { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class); - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - - - public Server lookupServer(Map params, SvcLogicContext ctx) throws APPCException { - Server server = null; - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); // should we test the return and fail if false? - - String vm_url = null; - try { - // process vm_url - validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL, - ProviderAdapter.PROPERTY_PROVIDER_NAME); - - String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); - vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - VMURL vm = VMURL.parseURL(vm_url); - if (validateVM(rc, appName, vm_url, vm)) { - return null; - } - - // use try with resource to ensure context is closed (returned to pool) - try (Context context = resolveContext(rc, params, appName, vm_url)) { - // resloveContext & getContext call doFailure and log errors before returning null - if (context != null) { - rc.reset(); - server = lookupServer(rc, context, vm.getServerId()); - logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString()); - ctx.setAttribute("serverFound", "success"); - String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "LookupServer", vm_url); - ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); - doSuccess(rc); - } - } catch (ZoneException e) { - // server not found - String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); - logger.error(msg); - doFailure(rc, HttpStatus.NOT_FOUND_404, msg); - ctx.setAttribute("serverFound", "failure"); - } catch (IOException e) { - // exception closing context - String msg = EELFResourceManager.format(Msg.CLOSE_CONTEXT_FAILED, e, vm_url); - logger.error(msg); - } catch (Exception e1) { - String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, - e1.getClass().getSimpleName(), Operation.LOOKUP_SERVICE.toString(), vm_url, "Unknown"); - logger.error(msg, e1); - doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); - } - - } catch (RequestFailedException e) { - // parameters not valid, unable to connect to provider - String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); - logger.error(msg); - doFailure(rc, HttpStatus.NOT_FOUND_404, msg); - ctx.setAttribute("serverFound", "failure"); - } - return server; - } - - @Override - protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) - throws APPCException { - setMDC(Operation.LOOKUP_SERVICE.toString(), "App-C IaaS Adapter:LookupServer", ADAPTER_NAME); - logOperation(Msg.LOOKING_SERVER_UP, params, context); - return lookupServer(params, context); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/MigrateServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/MigrateServer.java deleted file mode 100644 index b28918c09..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/MigrateServer.java +++ /dev/null @@ -1,240 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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.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 org.glassfish.grizzly.http.util.HttpStatus; -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.IdentityURL; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.impl.VMURL; -import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.slf4j.MDC; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.MIGRATE_SERVICE; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -public class MigrateServer extends ProviderServerOperation { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class); - private static 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 migratableStatuses = - Arrays.asList(Server.Status.READY, Server.Status.RUNNING, Server.Status.SUSPENDED); - - - private String getConnectionExceptionMessage(RequestContext rc, Context ctx, ContextConnectionException 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 || (!skipHypervisorCheck.equalsIgnoreCase("true"))) { - // Check of the Hypervisor for the VM Server is UP and reachable - checkHypervisor(server); - } - - boolean inConfirmPhase = false; - 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; - } - - // Verify resize - service.processResize(server); - // 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); - logger.error(msg, e); - metricsLogger.error(msg, e); - 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()); - generateEvent(rc, false, msg); - logger.error(msg, e); - metricsLogger.error(msg, e); - throw new RequestFailedException("Migrate Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server); - } - } - - /** - * @see org.onap.appc.adapter.iaas.ProviderAdapter#migrateServer(java.util.Map, - * org.openecomp.sdnc.sli.SvcLogicContext) - */ - private Server migrateServer(Map params, SvcLogicContext ctx) throws APPCException { - 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - - String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); - VMURL vm = VMURL.parseURL(vm_url); - if (validateVM(rc, appName, vm_url, vm)) - return null; - - IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); - String identStr = (ident == null) ? null : ident.toString(); - - Context context = null; - try { - context = getContext(rc, vm_url, identStr); - if (context != null) { - server = lookupServer(rc, context, vm.getServerId()); - logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString()); - migrateServer(rc, server, ctx); - server.refreshStatus(); - context.close(); - doSuccess(rc); - } - } catch (RequestFailedException e) { - doFailure(rc, e.getStatus(), e.getMessage()); - } catch (ResourceNotFoundException e) { - msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); - 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(), - MIGRATE_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); - logger.error(msg, e1); - metricsLogger.error(msg); - doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); - } - } catch (RequestFailedException e) { - doFailure(rc, e.getStatus(), e.getMessage()); - } - - return server; - } - - @Override - protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) - throws APPCException { - setMDC(Operation.MIGRATE_SERVICE.toString(), "App-C IaaS Adapter:Migrate", ADAPTER_NAME); - logOperation(Msg.MIGRATING_SERVER, params, context); - - setTimeForMetricsLogger(); - - metricsLogger.info("Executing Provider Operation: Migrate"); - - return migrateServer(params, context); - } - - private void setTimeForMetricsLogger() { - long startTime = System.currentTimeMillis(); - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - df.setTimeZone(tz); - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; - String durationStr = String.valueOf(duration); - String endTimeStrUTC = df.format(new Date()); - MDC.put("EndTimestamp", endTimeStrUTC); - MDC.put("ElapsedTime", durationStr); - MDC.put("TargetEntity", "cdp"); - MDC.put("TargetServiceName", "migrate server"); - MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.MigrateServer"); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RebuildServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RebuildServer.java deleted file mode 100644 index a2b27f29a..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RebuildServer.java +++ /dev/null @@ -1,434 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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.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 org.glassfish.grizzly.http.util.HttpStatus; -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.IdentityURL; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.impl.VMURL; -import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.slf4j.MDC; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; -import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.STOP_SERVICE; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -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(); - - /** - * 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(10L * 1000L); - } catch (InterruptedException e) { - logger.trace("Sleep threw interrupted exception, should never occur"); - metricsLogger.trace("Sleep threw interrupted exception, should never occur"); - } - } 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. - *

- * 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. - *

- * - * @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 exception for non image/snap boot source - if (ServerBootSource.VOLUME.equals(builtFrom)) { - 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 || (!skipHypervisorCheck.equalsIgnoreCase("true"))) { - // Check of the Hypervisor for the VM Server is UP and reachable - checkHypervisor(server); - } - - /* - * Get the image to use. This is determined by the presence or absence of snapshot images. If any snapshots - * exist, then the latest snapshot is used, otherwise the image used to construct the VM is used. - */ - List snapshots = server.getSnapshots(); - String imageToUse; - if (snapshots != null && !snapshots.isEmpty()) { - imageToUse = snapshots.get(0).getId(); - } else { - imageToUse = server.getImage(); - ImageService imageService = server.getContext().getImageService(); - 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 org.onap.appc.adapter.iaas.ProviderAdapter#rebuildServer(java.util.Map, - * org.openecomp.sdnc.sli.SvcLogicContext) - */ - @SuppressWarnings("nls") - public Server rebuildServer(Map params, SvcLogicContext ctx) throws APPCException { - 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - VMURL vm = VMURL.parseURL(vm_url); - if (validateVM(rc, appName, vm_url, 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; - try { - context = getContext(rc, vm_url, identStr); - if (context != null) { - rc.reset(); - server = lookupServer(rc, context, vm.getServerId()); - logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), 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 (RequestFailedException e) { - doFailure(rc, e.getStatus(), e.getMessage()); - ctx.setAttribute("REBUILD_STATUS", "ERROR"); - } catch (ResourceNotFoundException e) { - msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url); - 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(), - STOP_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName()); - ctx.setAttribute("REBUILD_STATUS", "ERROR"); - logger.error(msg, e1); - metricsLogger.error(msg); - doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg); - } - } catch (RequestFailedException e) { - doFailure(rc, e.getStatus(), e.getMessage()); - ctx.setAttribute("REBUILD_STATUS", "ERROR"); - } - - return server; - } - - @Override - protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) - throws APPCException { - setMDC(Operation.REBUILD_SERVICE.toString(), "App-C IaaS Adapter:Rebuild", ADAPTER_NAME); - logOperation(Msg.REBUILDING_SERVER, params, context); - - setTimeForMetricsLogger(); - - metricsLogger.info("Executing Provider Operation: Rebuild"); - - return rebuildServer(params, context); - } - - private void setTimeForMetricsLogger() { - long startTime = System.currentTimeMillis(); - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - df.setTimeZone(tz); - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; - String durationStr = String.valueOf(duration); - String endTimeStrUTC = df.format(new Date()); - MDC.put("EndTimestamp", endTimeStrUTC); - MDC.put("ElapsedTime", durationStr); - MDC.put("TargetEntity", "cdp"); - MDC.put("TargetServiceName", "rebuild server"); - MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.RebuildServer"); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestartServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestartServer.java deleted file mode 100644 index cc30ca833..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestartServer.java +++ /dev/null @@ -1,275 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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 org.glassfish.grizzly.http.util.HttpStatus; -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.IdentityURL; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.impl.VMURL; -import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; -import org.onap.appc.exceptions.UnknownProviderException; -import org.onap.appc.i18n.Msg; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.slf4j.MDC; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.RESTART_SERVICE; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -public class RestartServer extends ProviderServerOperation { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestartServer.class); - private static 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(), "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 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. - *

- * The fully qualified URL contains enough information to locate the appropriate server. The URL is of the form - * - *

-     *  [scheme]://[host[:port]] / [path] / [tenant_id] / servers / [vm_id]
-     * 
- * - * 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. - *

- * - * @throws UnknownProviderException If the provider cannot be found - * @throws IllegalArgumentException if the expected argument(s) are not defined or are invalid - * @see org.onap.appc.adapter.iaas.ProviderAdapter#restartServer(java.util.Map, - * org.openecomp.sdnc.sli.SvcLogicContext) - */ - @SuppressWarnings("nls") - private Server restartServer(Map params, SvcLogicContext ctx) - throws UnknownProviderException, 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - - VMURL vm = VMURL.parseURL(vm_url); - if (validateVM(rc, appName, vm_url, vm)) - return null; - - IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); - String identStr = (ident == null) ? null : ident.toString(); - - Context context = null; - try { - context = getContext(rc, vm_url, identStr); - if (context != null) { - rc.reset(); - server = lookupServer(rc, context, vm.getServerId()); - logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), 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", vm_url); - ctx.setAttribute(org.onap.appc.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, vm_url); - 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(), RESTART_SERVICE.toString(), vm_url, - context == null ? "Unknown" : context.getTenantName()); - 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 params, SvcLogicContext context) - throws UnknownProviderException { - setMDC(RESTART_SERVICE.toString(), "App-C IaaS Adapter:Restart", 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) { - long startTime = System.currentTimeMillis(); - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - df.setTimeZone(tz); - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; - String durationStr = String.valueOf(duration); - String endTimeStrUTC = df.format(new Date()); - MDC.put("EndTimestamp", endTimeStrUTC); - MDC.put("ElapsedTime", durationStr); - MDC.put("TargetEntity", "cdp"); - MDC.put("TargetServiceName", targetServiceName); - MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.RestartServer"); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestoreStack.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestoreStack.java deleted file mode 100644 index 7eeb23783..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/RestoreStack.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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 org.glassfish.grizzly.http.util.HttpStatus; -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderStackOperation; -import org.onap.appc.adapter.openstack.heat.SnapshotResource; -import org.onap.appc.adapter.openstack.heat.StackResource; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import java.util.Map; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -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 params, SvcLogicContext ctx) - throws IllegalArgumentException, APPCException { - 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 vm_url = null; - Context context = null; - - 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); - vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - String snapshotId = params.get(ProviderAdapter.PROPERTY_INPUT_SNAPSHOT_ID); - - context = resolveContext(rc, params, appName, vm_url); - - if (context != null) { - stack = lookupStack(rc, context, stackId); - logger.debug(Msg.STACK_FOUND, vm_url, context.getTenantName(), 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, vm_url); - 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", vm_url, null == context ? "n/a" : context.getTenantName()); - logger.error(msg, e1); - doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, e1); - } - return stack; - } - - @Override - protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) - throws APPCException { - setMDC(Operation.RESTORE_STACK.toString(), "App-C IaaS Adapter:Restore-Stack", ADAPTER_NAME); - logOperation(Msg.RESTORING_STACK, params, context); - return restoreStack(params, context); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java deleted file mode 100644 index bf7ebc755..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/SnapshotStack.java +++ /dev/null @@ -1,193 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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 org.glassfish.grizzly.http.util.HttpStatus; -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderStackOperation; -import org.onap.appc.adapter.openstack.heat.SnapshotResource; -import org.onap.appc.adapter.openstack.heat.StackResource; -import org.onap.appc.adapter.openstack.heat.model.CreateSnapshotParams; -import org.onap.appc.adapter.openstack.heat.model.Snapshot; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.slf4j.MDC; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -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 params, SvcLogicContext ctx) - throws IllegalArgumentException, APPCException { - Stack stack = null; - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - ctx.setAttribute("SNAPSHOT_STATUS", "STACK_NOT_FOUND"); - - setTimeForMetricsLogger(); - - String vm_url = null; - Context context = null; - 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); - vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - context = resolveContext(rc, params, appName, vm_url); - - if (context != null) { - stack = lookupStack(rc, context, stackId); - logger.debug(Msg.STACK_FOUND, vm_url, context.getTenantName(), 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, vm_url); - 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", vm_url, null == context ? "n/a" : context.getTenantName()); - logger.error(msg, e1); - metricsLogger.error(msg); - doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, e1); - } - return stack; - } - - @Override - protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) - throws APPCException { - setMDC(Operation.SNAPSHOT_STACK.toString(), "App-C IaaS Adapter:Snapshot-Stack", ADAPTER_NAME); - logOperation(Msg.SNAPSHOTING_STACK, params, context); - - setTimeForMetricsLogger(); - - metricsLogger.info("Executing Provider Operation: Snapshot Stack"); - - return snapshotStack(params, context); - } - - private void setTimeForMetricsLogger() { - long startTime = System.currentTimeMillis(); - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - df.setTimeZone(tz); - long endTime = System.currentTimeMillis(); - long duration = endTime - startTime; - String durationStr = String.valueOf(duration); - String endTimeStrUTC = df.format(new Date()); - MDC.put("EndTimestamp", endTimeStrUTC); - MDC.put("ElapsedTime", durationStr); - MDC.put("TargetEntity", "cdp"); - MDC.put("TargetServiceName", "snapshot stack"); - MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.SnapshotStack"); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StartServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StartServer.java deleted file mode 100644 index 1dbeacbf3..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StartServer.java +++ /dev/null @@ -1,184 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.impl; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.IdentityURL; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.impl.VMURL; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.glassfish.grizzly.http.util.HttpStatus; -import java.util.Map; -import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.START_SERVICE; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -public class StartServer extends ProviderServerOperation { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(StartServer.class); - - /** - * @see org.onap.appc.adapter.iaas.ProviderAdapter#startServer(java.util.Map, - * org.openecomp.sdnc.sli.SvcLogicContext) - */ - @SuppressWarnings("nls") - public Server startServer(Map params, SvcLogicContext ctx) throws APPCException { - 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - - VMURL vm = VMURL.parseURL(vm_url); - if (validateVM(rc, appName, vm_url, 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("START_STATUS", "ERROR"); - try { - context = getContext(rc, vm_url, identStr); - if (context != null) { - rc.reset(); - server = lookupServer(rc, context, vm.getServerId()); - logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString()); - 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, vm_url); - 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(), START_SERVICE.toString(), vm_url, - context == null ? "Unknown" : context.getTenantName()); - 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 params, SvcLogicContext context) - throws APPCException { - setMDC(Operation.START_SERVICE.toString(), "App-C IaaS Adapter:Start", ADAPTER_NAME); - logOperation(Msg.STARTING_SERVER, params, context); - return startServer(params, context); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StopServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StopServer.java deleted file mode 100644 index df836b77c..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/StopServer.java +++ /dev/null @@ -1,202 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.impl; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.IdentityURL; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.impl.VMURL; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.glassfish.grizzly.http.util.HttpStatus; -import java.util.Map; -import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.STOP_SERVICE; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -public class StopServer extends ProviderServerOperation { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(StopServer.class); - private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - - /** - * @see org.onap.appc.adapter.iaas.ProviderAdapter#stopServer(java.util.Map, - * org.openecomp.sdnc.sli.SvcLogicContext) - */ - @SuppressWarnings("nls") - public Server stopServer(Map params, SvcLogicContext ctx) throws APPCException { - 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - ctx.setAttribute("STOP_STATUS", "SUCCESS"); - - VMURL vm = VMURL.parseURL(vm_url); - if (validateVM(rc, appName, vm_url, 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"); - try { - context = getContext(rc, vm_url, identStr); - if (context != null) { - rc.reset(); - server = lookupServer(rc, context, vm.getServerId()); - logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString()); - - 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", vm_url); - ctx.setAttribute(org.onap.appc.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, vm_url); - 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(), - STOP_SERVICE.toString(), vm_url, 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 params, SvcLogicContext context) - throws APPCException { - setMDC(STOP_SERVICE.toString(), "App-C IaaS Adapter:Stop", ADAPTER_NAME); - logOperation(Msg.STOPPING_SERVER, params, context); - return stopServer(params, context); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateServer.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateServer.java deleted file mode 100644 index 73385ee35..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateServer.java +++ /dev/null @@ -1,245 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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 org.glassfish.grizzly.http.util.HttpStatus; -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.IdentityURL; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.impl.VMURL; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; -import org.onap.appc.exceptions.UnknownProviderException; -import org.onap.appc.i18n.Msg; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import java.util.Map; -import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.RESTART_SERVICE; -import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.TERMINATE_SERVICE; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -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. - *

- * The fully qualified URL contains enough information to locate the appropriate server. The URL is of the form - * - *

-     *  [scheme]://[host[:port]] / [path] / [tenant_id] / servers / [vm_id]
-     * 
- * - * 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. - *

- * - * @throws UnknownProviderException If the provider cannot be found - * @throws IllegalArgumentException if the expected argument(s) are not defined or are invalid - * @see org.onap.appc.adapter.iaas.ProviderAdapter#terminateServer(java.util.Map, - * org.openecomp.sdnc.sli.SvcLogicContext) - */ - @SuppressWarnings("nls") - public Server terminateServer(Map params, SvcLogicContext ctx) - throws UnknownProviderException, 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - ctx.setAttribute("TERMINATE_STATUS", "SUCCESS"); - - VMURL vm = VMURL.parseURL(vm_url); - if (validateVM(rc, appName, vm_url, vm)) - return null; - - IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); - String identStr = (ident == null) ? null : ident.toString(); - - Context context = null; - try { - context = getContext(rc, vm_url, identStr); - if (context != null) { - server = lookupServer(rc, context, vm.getServerId()); - logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), 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, vm_url); - 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(), RESTART_SERVICE.toString(), vm_url, - 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.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 params, SvcLogicContext context) - throws UnknownProviderException { - setMDC(TERMINATE_SERVICE.toString(), "App-C IaaS Adapter:Terminate", ADAPTER_NAME); - logOperation(Msg.TERMINATING_SERVER, params, context); - return terminateServer(params, context); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateStack.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateStack.java deleted file mode 100644 index 1e3ce1e68..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/TerminateStack.java +++ /dev/null @@ -1,128 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.impl; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderStackOperation; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.glassfish.grizzly.http.util.HttpStatus; -import java.util.Map; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -public class TerminateStack extends ProviderStackOperation { - - 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 params, SvcLogicContext ctx) - throws IllegalArgumentException, APPCException { - 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - - Context context = resolveContext(rc, params, appName, vm_url); - - try { - if (context != null) { - rc.reset(); - stack = lookupStack(rc, context, stackId); - logger.debug(Msg.STACK_FOUND, vm_url, 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", vm_url); - ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg); - } - } catch (ResourceNotFoundException e) { - String msg = EELFResourceManager.format(Msg.STACK_NOT_FOUND, e, vm_url); - 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(), vm_url, 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 params, SvcLogicContext context) - throws APPCException { - setMDC(Operation.TERMINATE_STACK.toString(), "App-C IaaS Adapter:Terminate-Stack", ADAPTER_NAME); - logOperation(Msg.TERMINATING_STACK, params, context); - return terminateStack(params, context); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/VmStatuschecker.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/VmStatuschecker.java deleted file mode 100644 index 9185e35fc..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/VmStatuschecker.java +++ /dev/null @@ -1,159 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.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 org.glassfish.grizzly.http.util.HttpStatus; -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.IdentityURL; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.iaas.impl.VMURL; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.UnknownProviderException; -import org.onap.appc.i18n.Msg; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import java.util.Map; -import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.RESTART_SERVICE; -import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME; - -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 params, SvcLogicContext ctx) - throws UnknownProviderException, 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 vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL); - - VMURL vm = VMURL.parseURL(vm_url); - if (validateVM(rc, appName, vm_url, vm)) - return null; - - IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL)); - String identStr = (ident == null) ? null : ident.toString(); - - Context context = null; - try { - context = getContext(rc, vm_url, identStr); - if (context != null) { - server = lookupServer(rc, context, vm.getServerId()); - logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), 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, vm_url); - 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(), RESTART_SERVICE.toString(), vm_url, - context == null ? "Unknown" : context.getTenantName()); - 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 params, SvcLogicContext context) - throws UnknownProviderException { - setMDC(Operation.VMSTATUSCHECK_SERVICE.toString(), "App-C IaaS Adapter:VmStatusCheck", ADAPTER_NAME); - logOperation(Msg.CHECKING_SERVER, params, context); - return vmStatuschecker(params, context); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderOperation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderOperation.java deleted file mode 100644 index 2b50dbe8a..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderOperation.java +++ /dev/null @@ -1,453 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.impl.base; - -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.*; -import org.onap.appc.adapter.iaas.provider.operation.api.IProviderOperation; -import org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants; -import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.pool.Pool; -import org.onap.appc.pool.PoolExtensionException; -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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.glassfish.grizzly.http.util.HttpStatus; -import org.slf4j.MDC; -import java.net.URI; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; -import static org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants.MDC_ADAPTER; -import static org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants.MDC_SERVICE; -import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; - -public abstract class ProviderOperation implements IProviderOperation { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(ProviderOperation.class); - protected static final Configuration configuration = ConfigurationFactory.getConfiguration(); - - public void setProviderCache(Map providerCache) { - this.providerCache = providerCache; - } - - /** - * A cache of providers that are predefined. - */ - private Map providerCache; - - - public void setDefaultUser(String defaultUser) { - DEFAULT_USER = defaultUser; - } - - public void setDefaultPass(String defaultPass) { - DEFAULT_PASS = defaultPass; - } - - @Override - public void setDefaultDomain(String defaultDomain) { - DEFAULT_DOMAIN = defaultDomain; - } - - /** - * The username and password to use for dynamically created connections - */ - private static String DEFAULT_USER; - private static String DEFAULT_PASS; - private static String DEFAULT_DOMAIN; - - - /** - * set MDC props - * - * @param service - * @param serviceName - * @param adapterName - */ - protected void setMDC(String service, String serviceName, String adapterName) { - MDC.put(MDC_ADAPTER, adapterName); - MDC.put(MDC_SERVICE, service); - MDC.put(MDC_SERVICE_NAME, serviceName); - } - - /** - * initial log of the operation - * - * @param msg - * @param params - * @param context - */ - protected void logOperation(Msg msg, Map params, SvcLogicContext context) { - - String appName = configuration.getProperty(org.onap.appc.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 parameters) { - for (String key : parameters.keySet()) { - logger.debug(Msg.PROPERTY_VALUE, key, parameters.get(key)); - } - } - - /** - * 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 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 parameters, String... propertyNames) - throws RequestFailedException { - boolean success = true; - StringBuilder msg = - new StringBuilder(EELFResourceManager.format(Msg.MISSING_REQUIRED_PROPERTIES, MDC.get(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. - * @param code - * @param message - */ - protected void doFailure(RequestContext rc, HttpStatus code, String message) { - try { - doFailure(rc, code, message, null); - } catch (APPCException ignored) { - /* never happens */} - } - - protected void doFailure(RequestContext rc, HttpStatus code, String message, Throwable cause) throws APPCException { - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - String msg = (message == null) ? code.getReasonPhrase() : message; - if (msg.contains("\n")) { - msg = msg.substring(0, msg.indexOf("\n")); - } - String status; - try { - status = Integer.toString(code.getStatusCode()); - } catch (Exception e) { - status = "500"; - } - svcLogic.setStatus(Outcome.FAILURE.toString()); - svcLogic.setAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE, status); - svcLogic.setAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE, msg); - - if (null != cause) - throw new APPCException(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(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE, - Integer.toString(HttpStatus.OK_200.getStatusCode())); - } - - protected boolean validateVM(RequestContext rc, String appName, String vm_url, VMURL vm) - throws RequestFailedException { - String msg; - if (vm == null) { - msg = EELFResourceManager.format(Msg.INVALID_SELF_LINK_URL, appName, vm_url); - 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) { - 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()); - // cache.setProviderType("OpenStack"); - - TenantCache tenant = cache.addTenant(vm.getTenantId(), null, DEFAULT_USER, DEFAULT_PASS, DEFAULT_DOMAIN); - - // 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(org.onap.appc.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, DEFAULT_USER, DEFAULT_PASS, DEFAULT_DOMAIN); - - 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 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. - */ - if (context.isStale()) { - context.relogin(); - } - 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; - } - - protected Context resolveContext(RequestContext rc, Map params, String appName, String vm_url) - throws RequestFailedException { - - VMURL vm = VMURL.parseURL(vm_url); - if (vm == null) { - String msg = EELFResourceManager.format(Msg.INVALID_SELF_LINK_URL, appName, vm_url); - 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, vm_url, identStr); - - } - - - - protected abstract ModelObject executeProviderOperation(Map params, SvcLogicContext context) - throws APPCException; - - @Override - public ModelObject doOperation(Map params, SvcLogicContext context) throws APPCException { - - return executeProviderOperation(params, context); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderServerOperation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderServerOperation.java deleted file mode 100644 index 9ef82aea2..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderServerOperation.java +++ /dev/null @@ -1,560 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.impl.base; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.impl.*; -import org.onap.appc.i18n.Msg; -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 org.glassfish.grizzly.http.util.HttpStatus; -import java.util.ArrayList; -import java.util.List; - -/** - * @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 - * @throws ZoneException - * @throws RequestFailedException - */ - @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. - *

- * 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. - *

- * - * @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 - * @throws NotLoggedInException - */ - @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 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 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, - // HttpStatus.BAD_GATEWAY_502, server); - } - } - - 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. - *

- * 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. - *

- * - * @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 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 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, - // HttpStatus.BAD_GATEWAY_502, server); - } - } - - 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 - * @throws ZoneException - * @throws RequestFailedException - */ - @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 - * @throws ZoneException - * @throws RequestFailedException - */ - @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 - * @throws ZoneException - * @throws RequestFailedException - */ - @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 ports = server.getPorts(); - - NetworkService netSvc = context.getNetworkService(); - - String msg; - for (Port port : ports) { - - switch (port.getPortState().toString().toUpperCase()) { - /** - * The port is connected, configured, and usable for communication - */ - case "ONLINE": - Network network = netSvc.getNetworkById(port.getNetwork()); - // Subnet subnet = netSvc.getSubnetById(port.getSubnetId()); - if (!network.getStatus().equals(Network.Status.ACTIVE.toString())) { - msg = EELFResourceManager.format(Msg.SERVER_NETWORK_ERROR, server.getName(), port.getId()); - logger.error(msg); - doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg); - throw new RequestFailedException("VM Server Network is DOWN", msg.toString(), - HttpStatus.PRECONDITION_FAILED_412, server); - } - break; - - /** - * The port is disconnected or powered-off and cannot be used for communication - */ - case "OFFLINE": - msg = EELFResourceManager.format(Msg.SERVER_NETWORK_ERROR, server.getName(), port.getId()); - logger.error(msg); - doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg); - throw new RequestFailedException("VM Server Port status is OFFLINE", msg.toString(), - HttpStatus.PRECONDITION_FAILED_412, server); - - /** - * The port's status is changing because of some event or operation. The final state is yet to be - * determined. - */ - case "PENDING": - msg = EELFResourceManager.format(Msg.SERVER_NETWORK_ERROR, server.getName(), port.getId()); - logger.error(msg); - doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg); - throw new RequestFailedException("VM Server Port status is PENDING", msg.toString(), - HttpStatus.PRECONDITION_FAILED_412, server); - - /** - * The port is in an unknown state and cannot be used. - */ - case "UNKNOWN": - msg = EELFResourceManager.format(Msg.SERVER_NETWORK_ERROR, server.getName(), port.getId()); - logger.error(msg); - doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg); - throw new RequestFailedException("VM Server Port status is UNKNOWN", msg.toString(), - HttpStatus.PRECONDITION_FAILED_412, server); - } - - } - logger.info("Passed the VM Server the Hypervisor status checks.."); - - } - - /** - * 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 = null; - if (server.getHypervisor() != null && server.getHypervisor().getStatus() != null - && server.getHypervisor().getState() != null) { - String status = null; - String state = null; - - 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.toString()); - - // doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg); - throw new RequestFailedException("Hypervisor status DOWN or NOT ENABLED", msg.toString(), - HttpStatus.PRECONDITION_FAILED_412, server); - - } - } else { - msg = EELFResourceManager.format(Msg.HYPERVISOR_STATUS_UKNOWN, server.getName()); - logger.error(msg.toString()); - - throw new RequestFailedException("Unable to determine Hypervisor status", msg.toString(), - HttpStatus.PRECONDITION_FAILED_412, server); - } - - logger.info("Passed the Hypervisor status checks.."); - - } - - /** - * Checks if a Host machine is reachable - * - * @param ipAddress IP Address of the Host Machine. - * @param server The server object representing the Virtual Machine server - * @return boolean - * - */ - /* - * private boolean isHostReachable(String ipAddress) throws IOException { - * - * InetAddress address = InetAddress.getByName(ipAddress); - * - * return address.isReachable(15000); - * - * - * } - */ - -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderStackOperation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderStackOperation.java deleted file mode 100644 index cbf620230..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderStackOperation.java +++ /dev/null @@ -1,194 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.provider.operation.impl.base; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.adapter.iaas.impl.RequestFailedException; -import org.onap.appc.adapter.openstack.heat.StackResource; -import org.onap.appc.i18n.Msg; -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 org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import com.woorea.openstack.base.client.OpenStackBaseException; -import org.glassfish.grizzly.http.util.HttpStatus; -import java.util.List; - -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.toUpperCase().equals(expectedStatus)) { - return true; - } else { - try { - Thread.sleep(pollInterval * 1000); - } catch (InterruptedException ignored) { - } - } - 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 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"); - } - } - } - - ctx.setAttribute("TERMINATE_STATUS", "ERROR"); - throw new TimeoutException("Timeout waiting for stack status change"); - - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/SnapshotResource.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/SnapshotResource.java deleted file mode 100644 index 549c7b93b..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/SnapshotResource.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat; - -import org.onap.appc.adapter.openstack.heat.model.CreateSnapshotParams; -import org.onap.appc.adapter.openstack.heat.model.Snapshot; -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; - - -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 { - 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 { - 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 { - public ShowSnapshot(String stackName, String stackID, String snapshotID) { - super(client, HttpMethod.GET, "/stacks/" + stackName + "/" + stackID + "/snapshots/" + snapshotID, null, - Snapshot.class); - } - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/StackResource.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/StackResource.java deleted file mode 100644 index 5add047f7..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/StackResource.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat; - -import org.onap.appc.adapter.openstack.heat.model.CreateSnapshotParams; -import org.onap.appc.adapter.openstack.heat.model.Snapshot; -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 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 { - public ShowStack(String stackName, String stackID) { - super(client, HttpMethod.GET, "/stacks/" + stackName + "/" + stackID, null, Stack.class); - } - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/CreateSnapshotParams.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/CreateSnapshotParams.java deleted file mode 100644 index 642b85367..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/CreateSnapshotParams.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -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) -@Generated("org.jsonschema2pojo") -@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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Data.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Data.java deleted file mode 100644 index df662013a..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Data.java +++ /dev/null @@ -1,229 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import javax.validation.Valid; -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) -@Generated("org.jsonschema2pojo") -@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") - @Valid - private Environment environment; - @JsonProperty("template") - @Valid - private Template template; - @JsonProperty("action") - private String action; - @JsonProperty("project_id") - private String projectId; - @JsonProperty("id") - private String id; - @JsonProperty("resources") - @Valid - 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Environment.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Environment.java deleted file mode 100644 index b5a9ddcad..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Environment.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import javax.validation.Valid; -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) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({"parameters", "resource_registry"}) -public class Environment { - - @JsonProperty("parameters") - @Valid - private Parameters parameters; - @JsonProperty("resource_registry") - @Valid - 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Metadata.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Metadata.java deleted file mode 100644 index 08e44b725..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Metadata.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang.builder.ToStringBuilder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - -}) -public class Metadata { - - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Parameters.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Parameters.java deleted file mode 100644 index 8adc97a4f..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Parameters.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang.builder.ToStringBuilder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - -}) -public class Parameters { - - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Properties.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Properties.java deleted file mode 100644 index 0a7605268..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Properties.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -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) -@Generated("org.jsonschema2pojo") -@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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/ResourceData.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/ResourceData.java deleted file mode 100644 index fea775c71..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/ResourceData.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -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) -@Generated("org.jsonschema2pojo") -@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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/ResourceRegistry.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/ResourceRegistry.java deleted file mode 100644 index d15c1c339..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/ResourceRegistry.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import javax.validation.Valid; -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) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({"resources"}) -public class ResourceRegistry { - - @JsonProperty("resources") - @Valid - 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Resources.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Resources.java deleted file mode 100644 index ffa9f0d1a..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Resources.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang.builder.ToStringBuilder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - -}) -public class Resources { - - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Resources_.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Resources_.java deleted file mode 100644 index e6889b0a7..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Resources_.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import javax.validation.Valid; -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) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({"volume"}) -public class Resources_ { - - @JsonProperty("volume") - @Valid - 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Resources__.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Resources__.java deleted file mode 100644 index c34310556..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Resources__.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import javax.validation.Valid; -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) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({"volume"}) -public class Resources__ { - - @JsonProperty("volume") - @Valid - 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Snapshot.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Snapshot.java deleted file mode 100644 index 57c7d5439..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Snapshot.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import javax.validation.Valid; -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) -@Generated("org.jsonschema2pojo") -@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") - @Valid - 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/SnapshotDetails.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/SnapshotDetails.java deleted file mode 100644 index f121ddd70..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/SnapshotDetails.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import javax.validation.Valid; -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) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({"snapshot"}) -public class SnapshotDetails { - - @JsonProperty("snapshot") - @Valid - 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/SnapshotRestoreResponse.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/SnapshotRestoreResponse.java deleted file mode 100644 index 482a29f3b..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/SnapshotRestoreResponse.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -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) -@Generated("org.jsonschema2pojo") -@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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Template.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Template.java deleted file mode 100644 index 310d711f5..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Template.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import javax.validation.Valid; -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) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({"heat_template_version", "resources"}) -public class Template { - - @JsonProperty("heat_template_version") - private String heatTemplateVersion; - @JsonProperty("resources") - @Valid - 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Volume.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Volume.java deleted file mode 100644 index 5943ba71b..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Volume.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import javax.validation.Valid; -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) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({"type", "properties"}) -public class Volume { - - @JsonProperty("type") - private String type; - @JsonProperty("properties") - @Valid - 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Volume_.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Volume_.java deleted file mode 100644 index a8df4a7dc..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/openstack/heat/model/Volume_.java +++ /dev/null @@ -1,187 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.openstack.heat.model; - -import javax.annotation.Generated; -import javax.validation.Valid; -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) -@Generated("org.jsonschema2pojo") -@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") - @Valid - private ResourceData resourceData; - @JsonProperty("resource_id") - private String resourceId; - @JsonProperty("action") - private String action; - @JsonProperty("type") - private String type; - @JsonProperty("metadata") - @Valid - 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/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/utils/Constants.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/utils/Constants.java deleted file mode 100644 index 6b9602a62..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/utils/Constants.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.utils; - - -public class Constants { - - /** - * The name of the adapter - */ - public static final String ADAPTER_NAME = "Appc IaaS Adapter"; -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/resources/org/onap/appc/default.properties b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..1ecb98c01 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,112 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============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/openecomp/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 diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 1ecb98c01..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,112 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============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/openecomp/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 diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestIdentityUrl.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestIdentityUrl.java new file mode 100644 index 000000000..dac22eadb --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestIdentityUrl.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.appc.adapter.iaas.impl; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import java.util.Properties; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.appc.adapter.iaas.impl.IdentityURL; +import org.onap.appc.configuration.ConfigurationFactory; + +public class TestIdentityUrl { + + private static String URL; + + @BeforeClass + public static void before() { + Properties props = ConfigurationFactory.getConfiguration().getProperties(); + URL = props.getProperty(""); + } + + /** + * Test that we can parse and interpret valid URLs + */ + @Test + public void testValidURL1() { + URL = "http://192.168.1.1:5000/v2.0/"; + IdentityURL idurl = IdentityURL.parseURL(URL); + assertNotNull(idurl); + assertTrue(idurl.getScheme().equals("http")); + assertTrue(idurl.getHost().equals("192.168.1.1")); + assertTrue(idurl.getPort().equals("5000")); + assertNull(idurl.getPath()); + assertTrue(idurl.getVersion().equals("v2.0")); + assertTrue(idurl.toString().equals("http://192.168.1.1:5000/v2.0")); + } + + @Test + public void testValidURL2() { + URL = "https://192.168.1.1:5000/v3/"; + IdentityURL idurl = IdentityURL.parseURL(URL); + assertNotNull(idurl); + assertTrue(idurl.getScheme().equals("https")); + assertTrue(idurl.getHost().equals("192.168.1.1")); + assertTrue(idurl.getPort().equals("5000")); + assertNull(idurl.getPath()); + assertTrue(idurl.getVersion().equals("v3")); + assertTrue(idurl.toString().equals("https://192.168.1.1:5000/v3")); + } + + @Test + public void testValidURL3() { + URL = "http://192.168.1.1/v2.0/"; + IdentityURL idurl = IdentityURL.parseURL(URL); + assertNotNull(idurl); + assertTrue(idurl.getScheme().equals("http")); + assertTrue(idurl.getHost().equals("192.168.1.1")); + assertNull(idurl.getPort()); + assertNull(idurl.getPath()); + assertTrue(idurl.getVersion().equals("v2.0")); + System.out.println(idurl.toString()); + assertTrue(idurl.toString().equals("http://192.168.1.1/v2.0")); + } + + @Test + public void testValidURL4() { + URL = "http://msb.onap.org:80/api/multicloud/v0/cloudowner_region/identity/v3"; + IdentityURL idurl = IdentityURL.parseURL(URL); + assertNotNull(idurl); + assertTrue(idurl.getScheme().equals("http")); + assertTrue(idurl.getHost().equals("msb.onap.org")); + assertTrue(idurl.getPort().equals("80")); + assertTrue(idurl.getPath().equals("/api/multicloud/v0/cloudowner_region/identity")); + assertTrue(idurl.getVersion().equals("v3")); + assertTrue(idurl.toString().equals("http://msb.onap.org:80/api/multicloud/v0/cloudowner_region/identity/v3")); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderAdapterImpl.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderAdapterImpl.java new file mode 100644 index 000000000..386c1115b --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderAdapterImpl.java @@ -0,0 +1,901 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +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.junit.experimental.categories.Category; +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.ProviderAdapter; +import org.onap.appc.adapter.iaas.impl.ProviderAdapterImpl; +import org.onap.appc.adapter.iaas.impl.ProviderCache; +import org.onap.appc.adapter.iaas.impl.ServiceCatalog; +import org.onap.appc.adapter.iaas.impl.TenantCache; +import org.onap.appc.adapter.iaas.impl.VMURL; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.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.Image; +import com.att.cdp.zones.model.Server; +import com.att.cdp.zones.model.Server.Status; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.woorea.openstack.keystone.model.Access.Service.Endpoint; + +/** + * Test the ProviderAdapter implementation. + */ +@Category(org.onap.appc.adapter.iaas.impl.TestProviderAdapterImpl.class) +public class TestProviderAdapterImpl { + + @SuppressWarnings("nls") + private static final String PROVIDER_NAME = "ILAB"; + + @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 ProviderAdapterImpl adapter; + + /** + * Use reflection to locate fields and methods so that they can be manipulated during the test + * to change the internal state accordingly. + * + * @throws NoSuchFieldException if the field(s) dont exist + * @throws SecurityException if reflective access is not allowed + * @throws NoSuchMethodException If the method(s) dont exist + */ + @SuppressWarnings("nls") + @BeforeClass + public static void once() throws NoSuchFieldException, SecurityException, NoSuchMethodException { + providerAdapterImplClass = ProviderAdapterImpl.class; + configurationFactoryClass = ConfigurationFactory.class; + + providerCacheField = providerAdapterImplClass.getDeclaredField("providerCache"); + providerCacheField.setAccessible(true); + + configField = configurationFactoryClass.getDeclaredField("config"); + configField.setAccessible(true); + + Properties props = ConfigurationFactory.getConfiguration().getProperties(); + IDENTITY_URL = props.getProperty("provider1.identity"); + PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc"); + CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc"); + TENANT_NAME = props.getProperty("provider1.tenant1.name", "appc"); + TENANT_ID = props.getProperty("provider1.tenant1.id", "abcde12345fghijk6789lmnopq123rst"); + REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne"); + SERVER_URL = props.getProperty("test.url"); + } + + /** + * Setup the test environment. + * + * @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. + * @throws NullPointerException if the specified object is null and the field is an instance + * field. + * @throws ExceptionInInitializerError if the initialization provoked by this method fails. + */ + @Before + public void setup() throws IllegalArgumentException, IllegalAccessException { + configField.set(null, null); + Properties properties = new Properties(); + adapter = new ProviderAdapterImpl(properties); + } + + /** + * This method inspects the provider adapter implementation to make sure that the cache of + * providers and tenants, as well as the service catalog, and all pools of contexts have been + * set up correctly. + * + * @throws IllegalAccessException if this Field object is enforcing Java language access control + * and the underlying field is inaccessible. + * @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). + */ + @SuppressWarnings({"unchecked"}) + @Ignore + @Test + public void validateCacheIsCreatedCorrectly() throws IllegalArgumentException, IllegalAccessException { + Map providerCaches = (Map) providerCacheField.get(adapter); + + assertNotNull(providerCaches); + assertEquals(1, providerCaches.size()); + assertTrue(providerCaches.containsKey(PROVIDER_NAME)); + + ProviderCache providerCache = providerCaches.get(PROVIDER_NAME); + assertEquals(PROVIDER_NAME, providerCache.getProviderName()); + assertEquals(PROVIDER_TYPE, providerCache.getProviderType()); + + Map tenantCaches = providerCache.getTenants(); + assertNotNull(tenantCaches); + assertEquals(1, tenantCaches.size()); + assertTrue(tenantCaches.containsKey(TENANT_NAME)); + + TenantCache tenantCache = tenantCaches.get(TENANT_NAME); + + assertEquals(TENANT_ID, tenantCache.getTenantId()); + assertEquals(TENANT_NAME, tenantCache.getTenantName()); + assertEquals(USER_ID, tenantCache.getUserid()); + + ServiceCatalog catalog = tenantCache.getServiceCatalog(); + assertNotNull(catalog); + + System.out.println(catalog.toString()); + List serviceTypes = catalog.getServiceTypes(); + assertNotNull(serviceTypes); + assertEquals(12, serviceTypes.size()); + + assertEquals(TENANT_NAME, catalog.getProjectName()); + assertEquals(TENANT_ID, catalog.getProjectId()); + + Set regionNames = catalog.getRegions(); + assertNotNull(regionNames); + assertEquals(1, regionNames.size()); + assertTrue(regionNames.contains(REGION_NAME)); + + List endpoints = catalog.getEndpoints(ServiceCatalog.IDENTITY_SERVICE); + assertNotNull(endpoints); + assertEquals(1, endpoints.size()); + Endpoint endpoint = (Endpoint) endpoints.get(0); + assertNotNull(endpoint); + assertEquals(REGION_NAME, endpoint.getRegion()); + assertEquals(IDENTITY_URL, endpoint.getPublicURL()); + + endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE); + assertNotNull(endpoints); + assertEquals(1, endpoints.size()); + endpoint = (Endpoint) endpoints.get(0); + assertNotNull(endpoint); + assertEquals(REGION_NAME, endpoint.getRegion()); + + endpoints = catalog.getEndpoints(ServiceCatalog.VOLUME_SERVICE); + assertNotNull(endpoints); + assertEquals(1, endpoints.size()); + endpoint = (Endpoint) endpoints.get(0); + assertNotNull(endpoint); + assertEquals(REGION_NAME, endpoint.getRegion()); + + endpoints = catalog.getEndpoints(ServiceCatalog.IMAGE_SERVICE); + assertNotNull(endpoints); + assertEquals(1, endpoints.size()); + endpoint = (Endpoint) endpoints.get(0); + assertNotNull(endpoint); + assertEquals(REGION_NAME, endpoint.getRegion()); + + endpoints = catalog.getEndpoints(ServiceCatalog.NETWORK_SERVICE); + assertNotNull(endpoints); + assertEquals(1, endpoints.size()); + endpoint = (Endpoint) endpoints.get(0); + assertNotNull(endpoint); + assertEquals(REGION_NAME, endpoint.getRegion()); + + assertTrue(catalog.isServicePublished(ServiceCatalog.IDENTITY_SERVICE)); + assertTrue(catalog.isServicePublished(ServiceCatalog.COMPUTE_SERVICE)); + assertTrue(catalog.isServicePublished(ServiceCatalog.VOLUME_SERVICE)); + assertTrue(catalog.isServicePublished(ServiceCatalog.IMAGE_SERVICE)); + assertTrue(catalog.isServicePublished(ServiceCatalog.NETWORK_SERVICE)); + } + + /** + * This test case is used to actually validate that a server has been restarted from an already + * running state + * + * @throws ZoneException If the login cannot be performed because the principal and/or + * credentials are invalid. + * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if + * the expected argument(s) are not defined or are invalid + * @throws IllegalStateException If the identity service is not available or cannot be created + * @throws IOException if an I/O error occurs + * @throws APPCException + */ + // @Ignore + @Test + public void testRestartRunningServer() + throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException { + Properties properties = new Properties(); + properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); + properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); + properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); + properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); + properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true"); + + try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { + context.login(PRINCIPAL, CREDENTIAL); + VMURL vm = VMURL.parseURL(SERVER_URL); + + ComputeService computeService = context.getComputeService(); + Server server = computeService.getServer(vm.getServerId()); + if (!server.getStatus().equals(Status.RUNNING)) { + server.start(); + assertTrue(waitForStateChange(server, Status.RUNNING)); + } + + Map params = new HashMap<>(); + params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); + params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); + SvcLogicContext svcContext = new SvcLogicContext(); + + server = adapter.restartServer(params, svcContext); + + assertEquals(Server.Status.RUNNING, server.getStatus()); + } + } + + + /****************************************/ + /** + * Tests that the vmStatuschecker method works and returns the correct status of the VM + * requested + * + * @throws ZoneException If the login cannot be performed because the principal and/or + * credentials are invalid. + * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if + * the expected argument(s) are not defined or are invalid + * @throws IllegalStateException If the identity service is not available or cannot be created + * @throws IOException if an I/O error occurs + * @throws UnknownProviderException If the provider cannot be found + */ + // @Ignore + @Test + public void testVmStatuschecker() throws IllegalStateException, IllegalArgumentException, ZoneException, + UnknownProviderException, IOException { + Properties properties = new Properties(); + properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); + properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); + properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); + properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); + properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true"); + + try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { + context.login(PRINCIPAL, CREDENTIAL); + VMURL vm = VMURL.parseURL(SERVER_URL); + + ComputeService computeService = context.getComputeService(); + Server server = computeService.getServer(vm.getServerId()); + if (!server.getStatus().equals(Status.RUNNING)) { + server.start(); + assertTrue(waitForStateChange(server, Status.RUNNING)); + } + // or instead of the if-block, can ensureRunning(server) be used? + ensureRunning(server); + assertEquals(Server.Status.RUNNING, server.getStatus()); + } + } + + /****************************************/ + + + /** + * Tests that we can restart a server that is already stopped + * + * @throws ZoneException If the login cannot be performed because the principal and/or + * credentials are invalid. + * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if + * the expected argument(s) are not defined or are invalid. + * @throws IllegalStateException If the identity service is not available or cannot be created + * @throws IOException if an I/O error occurs + * @throws APPCException + */ + // @Ignore + @Test + public void testRestartStoppedServer() + throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException { + Properties properties = new Properties(); + properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); + properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); + properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); + properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); + + try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { + context.login(PRINCIPAL, CREDENTIAL); + VMURL vm = VMURL.parseURL(SERVER_URL); + + ComputeService computeService = context.getComputeService(); + Server server = computeService.getServer(vm.getServerId()); + if (!server.getStatus().equals(Status.READY)) { + server.stop(); + assertTrue(waitForStateChange(server, Status.READY)); + } + + Map params = new HashMap<>(); + params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); + params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); + SvcLogicContext svcContext = new SvcLogicContext(); + + server = adapter.restartServer(params, svcContext); + + assertEquals(Server.Status.RUNNING, server.getStatus()); + + } + } + + /** + * Tests that we can rebuild a running server (not created from a bootable volume) + * + * @throws ZoneException If the login cannot be performed because the principal and/or + * credentials are invalid. + * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if + * the expected argument(s) are not defined or are invalid. + * @throws IllegalStateException If the identity service is not available or cannot be created + * @throws UnknownProviderException If the provider cannot be found + * @throws IOException if an I/O error occurs + * @throws APPCException If the server cannot be rebuilt for some reason + */ + // @Ignore + @Test + public void testRebuildRunningServer() + throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException { + Properties properties = new Properties(); + properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); + properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); + properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); + properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); + + try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { + context.login(PRINCIPAL, CREDENTIAL); + VMURL vm = VMURL.parseURL(SERVER_URL); + + ComputeService computeService = context.getComputeService(); + Server server = computeService.getServer(vm.getServerId()); + ensureRunning(server); + + Map params = new HashMap<>(); + params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); + params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); + SvcLogicContext svcContext = new SvcLogicContext(); + + server = adapter.rebuildServer(params, svcContext); + assertTrue(waitForStateChange(server, Status.RUNNING)); + + } + } + + /** + * Tests that we can rebuild a paused server (not created from a bootable volume) + * + * @throws ZoneException If the login cannot be performed because the principal and/or + * credentials are invalid. + * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if + * the expected argument(s) are not defined or are invalid. + * @throws IllegalStateException If the identity service is not available or cannot be created + * @throws UnknownProviderException If the provider cannot be found + * @throws IOException if an I/O error occurs + * @throws APPCException If the server cannot be rebuilt for some reason + */ + // @Ignore + @Test + public void testRebuildPausedServer() + throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException { + Properties properties = new Properties(); + properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); + properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); + properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); + properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); + + try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { + context.login(PRINCIPAL, CREDENTIAL); + VMURL vm = VMURL.parseURL(SERVER_URL); + + ComputeService computeService = context.getComputeService(); + Server server = computeService.getServer(vm.getServerId()); + ensurePaused(server); + + Map params = new HashMap<>(); + params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); + params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); + SvcLogicContext svcContext = new SvcLogicContext(); + + server = adapter.rebuildServer(params, svcContext); + assertTrue(waitForStateChange(server, Status.RUNNING)); + } + } + + /** + * Tests that we can rebuild a paused server (not created from a bootable volume) + * + * @throws ZoneException If the login cannot be performed because the principal and/or + * credentials are invalid. + * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if + * the expected argument(s) are not defined or are invalid. + * @throws IllegalStateException If the identity service is not available or cannot be created + * @throws UnknownProviderException If the provider cannot be found + * @throws IOException if an I/O error occurs + * @throws APPCException If the server cannot be rebuilt for some reason + */ + // @Ignore + @Test + public void testRebuildSuspendedServer() + throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException { + Properties properties = new Properties(); + properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); + properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); + properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); + properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); + + try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { + context.login(PRINCIPAL, CREDENTIAL); + VMURL vm = VMURL.parseURL(SERVER_URL); + + ComputeService computeService = context.getComputeService(); + Server server = computeService.getServer(vm.getServerId()); + ensureSuspended(server); + + Map params = new HashMap<>(); + params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); + params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); + SvcLogicContext svcContext = new SvcLogicContext(); + + server = adapter.rebuildServer(params, svcContext); + assertTrue(waitForStateChange(server, Status.RUNNING)); + } + } + + /** + * Tests that we can rebuild a paused server (not created from a bootable volume) + * + * @throws ZoneException If the login cannot be performed because the principal and/or + * credentials are invalid. + * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if + * the expected argument(s) are not defined or are invalid. + * @throws IllegalStateException If the identity service is not available or cannot be created + * @throws UnknownProviderException If the provider cannot be found + * @throws IOException if an I/O error occurs + * @throws APPCException If the server cannot be rebuilt for some reason + */ + // @Ignore + @Test + public void testRebuildStoppedServer() + throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException { + Properties properties = new Properties(); + properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); + properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); + properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); + properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); + + try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { + context.login(PRINCIPAL, CREDENTIAL); + VMURL vm = VMURL.parseURL(SERVER_URL); + + ComputeService computeService = context.getComputeService(); + Server server = computeService.getServer(vm.getServerId()); + ensureStopped(server); + + Map params = new HashMap<>(); + params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); + params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); + SvcLogicContext svcContext = new SvcLogicContext(); + + server = adapter.rebuildServer(params, svcContext); + assertTrue(waitForStateChange(server, Status.RUNNING)); + } + } + + /** + * Test subsequent action on second vm in different Tenant resulting in {"itemNotFound": + * {"message": "Instance could not be found", "code": 404}} + * + * @throws ZoneException If the login cannot be performed because the principal and/or + * credentials are invalid. + * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if + * the expected argument(s) are not defined or are invalid + * @throws IllegalStateException If the identity service is not available or cannot be created + * @throws IOException if an I/O error occurs + * @throws APPCException + */ + + @Test + public void testTenantVerification() + throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException { + + Properties properties = new Properties(); + properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, "http://example.com:5000"); + properties.setProperty(ContextFactory.PROPERTY_TENANT, "APP-C"); + properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); + + String vmUrl = + "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"; + + // try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { + // context.login("AppC", "AppC"); + + // call lookupServer on vm in defined tenant "APP-C_TLV" + VMURL vm = VMURL.parseURL(vmUrl); + + Map params = new HashMap<>(); + params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl); + params.put(ProviderAdapter.PROPERTY_IDENTITY_URL, "http://example.com:5000/v2.0"); + params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, "http://example.com:5000/v2.0"); + SvcLogicContext svcContext = new SvcLogicContext(); + + long start, end = 0; + + System.out.println("\n--------------------Begin lookupServer on tenant 1--------------------"); + start = System.currentTimeMillis(); + Server server = adapter.lookupServer(params, svcContext); + end = System.currentTimeMillis(); + + System.out.println(String.format("lookupServer on tenant 1 took %ds", (end - start) / 1000)); + System.out.println("----------------------------------------------------------------------\n"); + assertNotNull(server); + + // repeat to show that context is reused for second request + System.out.println("\n-----------------Begin repeat lookupServer on tenant 1----------------"); + start = System.currentTimeMillis(); + server = adapter.lookupServer(params, svcContext); + end = System.currentTimeMillis(); + + System.out.println(String.format("Repeat lookupServer on tenant 1 took %ds", (end - start) / 1000)); + System.out.println("----------------------------------------------------------------------\n"); + assertNotNull(server); + + // call lookupServer on vm in second tenant "Play" + // This is where we would fail due to using the previous + // tenants context + vmUrl = "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"; + vm = VMURL.parseURL(vmUrl); + params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl); + + System.out.println("\n--------------------Begin lookupServer on tenant 2--------------------"); + start = System.currentTimeMillis(); + server = adapter.lookupServer(params, svcContext); + end = System.currentTimeMillis(); + System.out.println(String.format("\nlookupServer on tenant 2 took %ds", (end - start) / 1000)); + System.out.println("----------------------------------------------------------------------\n"); + assertNotNull(server); + + // call lookupServer on vm in non-existing tenant + vmUrl = "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"; + vm = VMURL.parseURL(vmUrl); + params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl); + + System.out.println("\n--------------Begin lookupServer on non-existant tenant--------------"); + start = System.currentTimeMillis(); + server = adapter.lookupServer(params, svcContext); + end = System.currentTimeMillis(); + System.out.println(String.format("\nlookupServer on tenant 3 took %ds", (end - start) / 1000)); + System.out.println("----------------------------------------------------------------------\n"); + assertNull(server); + + // } + } + + /****************************************/ + + + @Test + public void testSnapshotServer() throws Exception { + Properties properties = new Properties(); + properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, "http://example.com:5000"); + // properties.setProperty(ContextFactory.PROPERTY_REGION, ""); + properties.setProperty(ContextFactory.PROPERTY_TENANT, "Play"); + properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); + + String vmUrl = + "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"; + + try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { + context.login("AppC", "AppC"); + VMURL vm = VMURL.parseURL(vmUrl); + + Map params = new HashMap<>(); + params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl); + params.put(ProviderAdapter.PROPERTY_IDENTITY_URL, "http://example.com:5000/v2.0"); + params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, "http://example.com:5000/v2.0"); + SvcLogicContext svcContext = new SvcLogicContext(); + + long start, end = 0; + + start = System.currentTimeMillis(); + Image image = adapter.createSnapshot(params, svcContext); + end = System.currentTimeMillis(); + + System.out.println(String.format("Image ID: %s", image.getId())); + System.out.println(String.format("Snapshot took %ds", (end - start) / 1000)); + + start = System.currentTimeMillis(); + adapter.rebuildServer(params, svcContext); + end = System.currentTimeMillis(); + System.out.println(String.format("Rebuild took %ds", (end - start) / 1000)); + } + + } + + /** + * Ensures that the server is in stopped (shutdown) state prior to test + * + * @param server The server to ensure is stopped + * @throws ZoneException If the server can't be operated upon for some reason + */ + @SuppressWarnings("nls") + private static void ensureStopped(Server server) throws ZoneException { + switch (server.getStatus()) { + case READY: + break; + + case PENDING: + waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED, + Server.Status.SUSPENDED, Server.Status.ERROR); + ensureSuspended(server); + break; + + case PAUSED: + server.unpause(); + waitForStateChange(server, Server.Status.RUNNING); + server.stop(); + waitForStateChange(server, Server.Status.READY); + break; + + case SUSPENDED: + server.resume(); + waitForStateChange(server, Server.Status.RUNNING); + server.stop(); + waitForStateChange(server, Server.Status.READY); + break; + + case RUNNING: + server.stop(); + waitForStateChange(server, Server.Status.READY); + break; + + case DELETED: + case ERROR: + default: + fail("Server state is not valid for test - " + server.getStatus().name()); + } + } + + /** + * Ensures that the server is in suspended state prior to test + * + * @param server The server to ensure is suspended + * @throws ZoneException If the server can't be operated upon for some reason + */ + @SuppressWarnings("nls") + private static void ensureSuspended(Server server) throws ZoneException { + switch (server.getStatus()) { + case SUSPENDED: + break; + + case PENDING: + waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED, + Server.Status.SUSPENDED, Server.Status.ERROR); + ensureSuspended(server); + break; + + case PAUSED: + server.unpause(); + waitForStateChange(server, Server.Status.RUNNING); + server.suspend(); + waitForStateChange(server, Server.Status.SUSPENDED); + break; + + case READY: + server.start(); + waitForStateChange(server, Server.Status.RUNNING); + server.suspend(); + waitForStateChange(server, Server.Status.SUSPENDED); + break; + + case RUNNING: + server.suspend(); + waitForStateChange(server, Server.Status.SUSPENDED); + break; + + case DELETED: + case ERROR: + default: + fail("Server state is not valid for test - " + server.getStatus().name()); + } + } + + /** + * This method makes sure that the indicated server is running before performing a test + * + * @param server The server to ensure is running + * @throws ZoneException If the server can't be operated upon + */ + @SuppressWarnings("nls") + private static void ensureRunning(Server server) throws ZoneException { + switch (server.getStatus()) { + case RUNNING: + break; + + case PENDING: + waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED, + Server.Status.SUSPENDED, Server.Status.ERROR); + ensureRunning(server); + break; + + case PAUSED: + server.unpause(); + waitForStateChange(server, Server.Status.RUNNING); + break; + + case SUSPENDED: + server.resume(); + waitForStateChange(server, Server.Status.RUNNING); + break; + + case READY: + server.start(); + waitForStateChange(server, Server.Status.RUNNING); + break; + + case DELETED: + case ERROR: + default: + fail("Server state is not valid for test - " + server.getStatus().name()); + } + } + + /** + * This method will make sure that the server we are testing is paused + * + * @param server The server to make sure is paused for the test + * @throws ZoneException If anything fails + */ + @SuppressWarnings("nls") + private static void ensurePaused(Server server) throws ZoneException { + switch (server.getStatus()) { + case PAUSED: + break; + + case PENDING: + waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED, + Server.Status.SUSPENDED, Server.Status.ERROR); + ensurePaused(server); + break; + + case READY: + server.start(); + waitForStateChange(server, Server.Status.RUNNING); + server.pause(); + waitForStateChange(server, Server.Status.PAUSED); + break; + + case RUNNING: + server.pause(); + waitForStateChange(server, Server.Status.PAUSED); + break; + + case SUSPENDED: + server.resume(); + waitForStateChange(server, Server.Status.RUNNING); + server.pause(); + waitForStateChange(server, Server.Status.PAUSED); + break; + + case ERROR: + case DELETED: + default: + fail("Server state is not valid for test - " + server.getStatus().name()); + } + } + + /** + * Enter a pool-wait loop checking the server state to see if it has entered one of the desired + * states or not. + *

+ * 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 alloted timeout + * period, then the method returns a failed response (false). No exceptions are thrown from this + * method. + *

+ * + * @param server The server to wait on + * @param desiredStates A variable list of desired states, any one of which is allowed. + * @return True if the server entered one of the desired states, and false if not and the wait + * loop timed out. + */ + private static boolean waitForStateChange(Server server, Server.Status... desiredStates) { + int timeout = ConfigurationFactory.getConfiguration() + .getIntegerProperty(Constants.PROPERTY_SERVER_STATE_CHANGE_TIMEOUT); + long limit = System.currentTimeMillis() + (timeout * 1000); + Server vm = server; + + try { + while (limit > System.currentTimeMillis()) { + vm.refresh(); + for (Server.Status desiredState : desiredStates) { + if (server.getStatus().equals(desiredState)) { + return true; + } + } + + try { + Thread.sleep(10000L); + } catch (InterruptedException e) { + // ignore + } + } + } catch (ZoneException e) { + e.printStackTrace(); + } + + return false; + } + + /* + * @Test public void testTerminateStack() throws IllegalStateException, + * IllegalArgumentException, ZoneException, UnknownProviderException, IOException { Properties + * properties = new Properties(); properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, + * IDENTITY_URL); properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); + * properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); + * properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); + * properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true"); try (Context context = + * ContextFactory.getContext(PROVIDER_TYPE, properties)) { context.login(PRINCIPAL, CREDENTIAL); + * VMURL vm = VMURL.parseURL(SERVER_URL); ComputeService computeService = + * context.getComputeService(); Server server = computeService.getServer(vm.getServerId()); if + * (!server.getStatus().equals(Status.RUNNING)) { server.start(); + * assertTrue(waitForStateChange(server, Status.RUNNING)); } Map params = new + * HashMap<>(); params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); + * params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); SvcLogicContext svcContext + * = new SvcLogicContext(); Stack stack = adapter.terminateStack(params, svcContext); + * assertNotNull(stack); } } + */ + +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderOperation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderOperation.java new file mode 100644 index 000000000..c080cf953 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderOperation.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.impl; + +import java.lang.reflect.Field; +import java.util.Map; +import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderOperation; +import org.onap.appc.exceptions.APPCException; +import com.att.cdp.zones.model.ModelObject; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.MDC; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import static org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants.MDC_SERVICE; + +/** + * This class is used to test methods and functions of the adapter implementation that do not + * require and do not set up connections to any providers. + * + * @since Jan 20, 2016 + * @version $Id$ + */ + +public class TestProviderOperation extends ProviderOperation { + + private static Class providerAdapterImplClass; + private static Class configurationFactoryClass; + private static Field providerCacheField; + private static Field configField; + + /** + * Use reflection to locate fields and methods so that they can be manipulated during the test + * to change the internal state accordingly. + * + * @throws NoSuchFieldException if the field(s) dont exist + * @throws SecurityException if reflective access is not allowed + * @throws NoSuchMethodException If the method(s) dont exist + */ + @SuppressWarnings("nls") + @BeforeClass + public static void once() throws NoSuchFieldException, SecurityException, NoSuchMethodException { + providerAdapterImplClass = ProviderAdapterImpl.class; + configurationFactoryClass = ConfigurationFactory.class; + + providerCacheField = providerAdapterImplClass.getDeclaredField("providerCache"); + providerCacheField.setAccessible(true); + + configField = configurationFactoryClass.getDeclaredField("config"); + configField.setAccessible(true); + } + + /** + * This test expects a failure because the value to be validated is a null URL + * + * @throws RequestFailedException Expected + */ + @SuppressWarnings("nls") + @Test(expected = RequestFailedException.class) + public void testValidateParameterPatternExpectFailNullValue() throws RequestFailedException { + MDC.put(MDC_SERVICE, "junit"); + SvcLogicContext svcContext = new SvcLogicContext(); + RequestContext rc = new RequestContext(svcContext); + String link = null; + + validateVMURL(VMURL.parseURL(link)); + } + + /** + * This test expects a failure because the value to be validated is an empty URL + * + * @throws RequestFailedException Expected + */ + @SuppressWarnings("nls") + @Test(expected = RequestFailedException.class) + public void testValidateParameterPatternExpectFailEmptyValue() throws RequestFailedException { + MDC.put(MDC_SERVICE, "junit"); + SvcLogicContext svcContext = new SvcLogicContext(); + RequestContext rc = new RequestContext(svcContext); + String link = ""; + + validateVMURL(VMURL.parseURL(link)); + } + + /** + * This test expects a failure because the value to be validated is a blank URL + * + * @throws RequestFailedException Expected + */ + @SuppressWarnings("nls") + @Test(expected = RequestFailedException.class) + public void testValidateParameterPatternExpectFailBlankValue() throws RequestFailedException { + MDC.put(MDC_SERVICE, "junit"); + SvcLogicContext svcContext = new SvcLogicContext(); + RequestContext rc = new RequestContext(svcContext); + String link = " "; + + validateVMURL(VMURL.parseURL(link)); + } + + /** + * This test expects a failure because the value to be validated is a bad URL + * + * @throws RequestFailedException Expected + */ + @SuppressWarnings("nls") + @Test(expected = RequestFailedException.class) + public void testValidateParameterPatternExpectFailBadURL() throws RequestFailedException { + MDC.put(MDC_SERVICE, "junit"); + SvcLogicContext svcContext = new SvcLogicContext(); + RequestContext rc = new RequestContext(svcContext); + String link = "http://some.host:1234/01d82c08594a4b23a0f9260c94be0c4d/"; + + validateVMURL(VMURL.parseURL(link)); + } + + /** + * This test expects to pass + * + * @throws RequestFailedException Un-Expected + */ + @SuppressWarnings("nls") + @Test + public void testValidateParameterPatternValidURL() throws RequestFailedException { + MDC.put(MDC_SERVICE, "junit"); + SvcLogicContext svcContext = new SvcLogicContext(); + RequestContext rc = new RequestContext(svcContext); + String link = + "http://some.host:1234/v2/01d82c08594a4b23a0f9260c94be0c4d/servers/f888f89f-096b-421e-ba36-34f714071551"; + + validateVMURL(VMURL.parseURL(link)); + } + + @Override + protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) + throws APPCException { + return null; + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestRequestContext.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestRequestContext.java new file mode 100644 index 000000000..7ea30635c --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestRequestContext.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.appc.adapter.iaas.impl; + +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.Constants; +import org.onap.appc.adapter.iaas.impl.RequestContext; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; + +/** + * Test the RequestContext object + *

+ * The request context is used to track retries, recovery attempts, and time to live of the + * processing of a request. + *

+ */ + +public class TestRequestContext { + + private RequestContext rc; + private Configuration config = ConfigurationFactory.getConfiguration(); + + /** + * Set up the test environment by forcing the retry delay and limit to small values for the test + * and setting up the request context object. + */ + @Before + public void setup() { + config.setProperty(Constants.PROPERTY_RETRY_DELAY, "1"); + config.setProperty(Constants.PROPERTY_RETRY_LIMIT, "3"); + rc = new RequestContext(null); + rc.setTimeToLiveSeconds(2); + } + + /** + * Ensure that we set up the property correctly + */ + @Test + public void testRetryDelayProperty() { + assertEquals(1, rc.getRetryDelay()); + } + + /** + * Ensure that we set up the property correctly + */ + @Test + public void testRetryLimitProperty() { + assertEquals(3, rc.getRetryLimit()); + } + + /** + * This test ensures that the retry attempt counter is zero on a new context + */ + @Test + public void testRetryCountNoRetries() { + assertEquals(0, rc.getAttempts()); + } + + /** + * Test that the delay is accurate + */ + @Test + public void testDelay() { + long future = System.currentTimeMillis() + (rc.getRetryDelay() * 1000L); + + rc.delay(); + + assertTrue(System.currentTimeMillis() >= future); + } + + /** + * The RequestContext tracks the number of retry attempts against the limit. This test verifies + * that tracking logic works correctly. + */ + @Test + public void testCanRetry() { + assertEquals(0, rc.getAttempts()); + assertTrue(rc.attempt()); + assertEquals(1, rc.getAttempts()); + assertTrue(rc.attempt()); + assertEquals(2, rc.getAttempts()); + assertTrue(rc.attempt()); + assertEquals(3, rc.getAttempts()); + assertFalse(rc.attempt()); + assertEquals(3, rc.getAttempts()); + assertFalse(rc.attempt()); + assertEquals(3, rc.getAttempts()); + assertFalse(rc.attempt()); + assertEquals(3, rc.getAttempts()); + } + + /** + * The same RequestContext is used throughout the processing, and retries need to be reset once + * successfully connected so that any earlier (successful) recoveries are not considered when + * performing any new future recoveries. This test ensures that a reset clears the retry counter + * and that we can attempt retries again up to the limit. + */ + @Test + public void testResetAndCanRetry() { + assertTrue(rc.attempt()); + assertTrue(rc.attempt()); + assertTrue(rc.attempt()); + rc.reset(); + + assertTrue(rc.attempt()); + assertTrue(rc.attempt()); + assertTrue(rc.attempt()); + assertFalse(rc.attempt()); + assertFalse(rc.attempt()); + assertFalse(rc.attempt()); + } + + /** + * This test is used to test tracking of time to live for the request context. Because time is + * inexact, the assertions can only be ranges of values, such as at least some value or greater. + * The total duration tracking in the request context is only updated on each call to + * {@link RequestContext#isAlive()}. Also, durations are NOT affected by calls to reset. + */ + @Test + public void testTimeToLive() { + assertTrue(rc.getTotalDuration() == 0L); + assertTrue(rc.isAlive()); + rc.reset(); + rc.delay(); + assertTrue(rc.isAlive()); + assertTrue(rc.getTotalDuration() >= 1000L); + rc.reset(); + rc.delay(); + rc.isAlive(); + assertTrue(rc.getTotalDuration() >= 2000L); + rc.reset(); + rc.delay(); + assertFalse(rc.isAlive()); + assertTrue(rc.getTotalDuration() >= 3000L); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalog.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalog.java new file mode 100644 index 000000000..c1a41f209 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalog.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.adapter.iaas.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.configuration.ConfigurationFactory; +import com.att.cdp.exceptions.ZoneException; +import com.woorea.openstack.keystone.model.Access.Service; + +/** + * This class tests the service catalog against a known provider. + */ +public class TestServiceCatalog { + + // Number + private static int EXPECTED_REGIONS = 2; + private static int EXPECTED_ENDPOINTS = 1; + + private static String PRINCIPAL; + private static String CREDENTIAL; + private static String TENANT_NAME; + private static String TENANT_ID; + private static String IDENTITY_URL; + private static String REGION_NAME; + + private ServiceCatalog catalog; + + private Properties properties; + + @BeforeClass + public static void before() { + Properties props = ConfigurationFactory.getConfiguration().getProperties(); + IDENTITY_URL = props.getProperty("provider1.identity"); + PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc"); + CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc"); + TENANT_NAME = props.getProperty("provider1.tenant1.name", "appc"); + TENANT_ID = props.getProperty("provider1.tenant1.id", + props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst")); + REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne"); + + EXPECTED_REGIONS = Integer.valueOf(props.getProperty("test.expected-regions", "2")); + EXPECTED_ENDPOINTS = Integer.valueOf(props.getProperty("test.expected-endpoints", "0")); + } + + /** + * Setup the test environment by loading a new service catalog for each test + * + * @throws ZoneException + */ + @Before + public void setup() throws ZoneException { + properties = new Properties(); + catalog = Mockito.mock(ServiceCatalog.class, Mockito.CALLS_REAL_METHODS); + catalog.rwLock = new ReentrantReadWriteLock(); + + Set testdata = new HashSet<>(); + testdata.add("RegionOne"); + catalog.regions = testdata; + } + + /** + * Test that we find all of the expected region(s) + */ + @Test + public void testKnownRegions() { + assertEquals(EXPECTED_REGIONS, catalog.getRegions().size()); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogFactory.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogFactory.java new file mode 100644 index 000000000..e974d27ba --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogFactory.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.impl; + +import java.util.Properties; +import org.junit.Assert; +import org.junit.Test; + +public class TestServiceCatalogFactory { + + @Test + public void testGetServiceCatalogV2() { + String tenantIdentifier = null; + String principal = null; + String credential = null; + String domain = null; + Properties properties = null; + + String url = "http://192.168.1.1:5000/v2.0/"; + ServiceCatalog catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential, + domain, properties); + Assert.assertNotNull(catalog); + Assert.assertEquals(catalog.getClass(), ServiceCatalogV2.class); + + url = "http://192.168.1.1:5000/v2/"; + catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential, domain, + properties); + Assert.assertNotNull(catalog); + Assert.assertEquals(catalog.getClass(), ServiceCatalogV2.class); + + url = "http://192.168.1.1:5000/v2.1/"; + catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential, domain, + properties); + Assert.assertNotNull(catalog); + Assert.assertEquals(catalog.getClass(), ServiceCatalogV2.class); + + } + + @Test + public void testGetServiceCatalogV3() { + String url = "http://192.168.1.1:5000/v3.0/"; + String tenantIdentifier = null; + String principal = null; + String credential = null; + String domain = null; + Properties properties = null; + ServiceCatalog catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential, + domain, properties); + + Assert.assertNotNull(catalog); + Assert.assertEquals(catalog.getClass(), ServiceCatalogV3.class); + } + + @Test + public void testGetServiceCatalogOther() { + String url = "http://192.168.1.1:5000/v4.0/"; + String tenantIdentifier = null; + String principal = null; + String credential = null; + String domain = null; + Properties properties = null; + ServiceCatalog catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential, + domain, properties); + + Assert.assertNull(catalog); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV2.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV2.java new file mode 100644 index 000000000..58b56e06f --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV2.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.iaas.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import com.att.cdp.exceptions.ZoneException; +import com.woorea.openstack.keystone.model.Access.Service; +import java.util.List; +import java.util.Properties; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.configuration.ConfigurationFactory; + +/** + * This class tests the service catalog against a known provider. + */ +@Ignore +public class TestServiceCatalogV2 { + + // Number + private static int EXPECTED_REGIONS = 1; + private static int EXPECTED_ENDPOINTS = 1; + + private static String PRINCIPAL; + private static String CREDENTIAL; + private static String TENANT_NAME; + private static String TENANT_ID; + private static String IDENTITY_URL; + private static String REGION_NAME; + + private ServiceCatalogV2 catalog; + + private Properties properties; + + @BeforeClass + public static void before() { + Properties props = ConfigurationFactory.getConfiguration().getProperties(); + IDENTITY_URL = props.getProperty("provider1.identity", "appc"); + PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc"); + CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc"); + TENANT_NAME = props.getProperty("provider1.tenant1.name", "appc"); + TENANT_ID = props.getProperty("provider1.tenant1.id", + props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst")); + REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne"); + + EXPECTED_REGIONS = Integer.valueOf(props.getProperty("test.expected-regions", "0")); + EXPECTED_ENDPOINTS = Integer.valueOf(props.getProperty("test.expected-endpoints", "0")); + } + + /** + * Setup the test environment by loading a new service catalog for each test + * + * @throws ZoneException + */ + @Before + public void setup() throws ZoneException { + properties = new Properties(); + catalog = new ServiceCatalogV2(IDENTITY_URL, TENANT_NAME, PRINCIPAL, CREDENTIAL, properties); + catalog.init(); + } + + /** + * Test that the tenant name and ID are returned correctly + */ + @Test + public void testKnownTenant() { + assertEquals(TENANT_NAME, catalog.getProjectName()); + assertEquals(TENANT_ID, catalog.getProjectId()); + } + + /** + * Test that we find all of the expected region(s) + */ + @Test + public void testKnownRegions() { + assertEquals(EXPECTED_REGIONS, catalog.getRegions().size()); + // assertEquals(REGION_NAME, catalog.getRegions().toArray()[0]); + } + + /** + * Test that we can check for published services correctly + */ + @Test + public void testServiceTypesPublished() { + assertTrue(catalog.isServicePublished("compute")); + assertFalse(catalog.isServicePublished("bogus")); + } + + /** + * Check that we can get the list of published services + */ + @Test + public void testPublishedServicesList() { + // List services = catalog.getServiceTypes(); + + // assertTrue(services.contains(ServiceCatalog.COMPUTE_SERVICE)); + // assertTrue(services.contains(ServiceCatalog.IDENTITY_SERVICE)); + // assertTrue(services.contains(ServiceCatalog.IMAGE_SERVICE)); + // assertTrue(services.contains(ServiceCatalog.NETWORK_SERVICE)); + // assertTrue(services.contains(ServiceCatalog.VOLUME_SERVICE)); + } + + /** + * Test that we can get the endpoint(s) for a service + */ + @Test + public void testEndpointList() { + List endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE); + + assertNotNull(endpoints); + assertFalse(endpoints.isEmpty()); + assertEquals(EXPECTED_ENDPOINTS, endpoints.size()); + + Service.Endpoint endpoint = endpoints.get(0); + // assertEquals(REGION_NAME, endpoint.getRegion()); + } + + @Test + public void testToString() { + String testString = catalog.toString(); + assertNotNull(testString); + } + + @Ignore + @Test + public void liveConnectionTest() { + // this test should only be used by developers when testing against a live Openstack + // instance, otherwise it should be ignored + properties = new Properties(); + String identity = "http://192.168.0.1:5000/v2.0"; + String tenantName = "Tenant"; + String user = "user"; + String pass = "pass"; + + ServiceCatalogV2 catalog = new ServiceCatalogV2(identity, tenantName, user, pass, properties); + + try { + catalog.init(); + } catch (ZoneException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + String out = catalog.toString(); + System.out.println(out); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV3.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV3.java new file mode 100644 index 000000000..26a4d7dbf --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV3.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.adapter.iaas.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import com.att.cdp.exceptions.ZoneException; +import com.woorea.openstack.keystone.v3.model.Token.Service.Endpoint; +import java.util.List; +import java.util.Properties; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.configuration.ConfigurationFactory; + +/** + * This class tests the service catalog against a known provider. + */ +@Ignore +public class TestServiceCatalogV3 { + + // Number + private static int EXPECTED_REGIONS = 1; + private static int EXPECTED_ENDPOINTS = 1; + + private static String PRINCIPAL; + private static String CREDENTIAL; + private static String DOMAIN; + private static String TENANT_NAME; + private static String TENANT_ID; + private static String IDENTITY_URL; + private static String REGION_NAME; + + private ServiceCatalogV3 catalog; + + private Properties properties; + + @BeforeClass + public static void before() { + Properties props = ConfigurationFactory.getConfiguration().getProperties(); + IDENTITY_URL = props.getProperty("provider1.identity"); + PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc"); + CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc"); + DOMAIN = props.getProperty("provider1.tenant1.domain", "Default"); + TENANT_NAME = props.getProperty("provider1.tenant1.name", "appc"); + TENANT_ID = props.getProperty("provider1.tenant1.id", + props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst")); + REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne"); + + EXPECTED_REGIONS = Integer.valueOf(props.getProperty("test.expected-regions", "0")); + EXPECTED_ENDPOINTS = Integer.valueOf(props.getProperty("test.expected-endpoints", "0")); + } + + /** + * Setup the test environment by loading a new service catalog for each test + * + * @throws ZoneException + */ + @Before + public void setup() throws ZoneException { + properties = new Properties(); + catalog = new ServiceCatalogV3(IDENTITY_URL, TENANT_NAME, PRINCIPAL, CREDENTIAL, DOMAIN, properties); + } + + /** + * Test that the tenant name and ID are returned correctly + */ + @Test + public void testKnownTenant() { + assertEquals(TENANT_NAME, catalog.getProjectName()); + assertEquals(TENANT_ID, catalog.getProjectId()); + } + + /** + * Test that we find all of the expected region(s) + */ + @Test + public void testKnownRegions() { + assertEquals(EXPECTED_REGIONS, catalog.getRegions().size()); + // assertEquals(REGION_NAME, catalog.getRegions().toArray()[0]); + } + + /** + * Test that we can check for published services correctly + */ + @Test + public void testServiceTypesPublished() { + assertTrue(catalog.isServicePublished("compute")); + assertFalse(catalog.isServicePublished("bogus")); + } + + /** + * Check that we can get the list of published services + */ + @Test + public void testPublishedServicesList() { + List services = catalog.getServiceTypes(); + + assertTrue(services.contains(ServiceCatalog.COMPUTE_SERVICE)); + assertTrue(services.contains(ServiceCatalog.IDENTITY_SERVICE)); + assertTrue(services.contains(ServiceCatalog.IMAGE_SERVICE)); + assertTrue(services.contains(ServiceCatalog.NETWORK_SERVICE)); + assertTrue(services.contains(ServiceCatalog.VOLUME_SERVICE)); + } + + /** + * Test that we can get the endpoint(s) for a service + */ + @Test + public void testEndpointList() { + List endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE); + + assertNotNull(endpoints); + assertFalse(endpoints.isEmpty()); + assertEquals(EXPECTED_ENDPOINTS, endpoints.size()); + + Endpoint endpoint = endpoints.get(0); + // assertEquals(REGION_NAME, endpoint.getRegion()); + } + + @Test + public void testToString() { + String testString = catalog.toString(); + assertNotNull(testString); + } + + @Ignore + @Test + public void liveConnectionTest() { + // this test should only be used by developers when testing against a live Openstack + // instance, otherwise it should be ignored + properties = new Properties(); + String identity = ""; + String tenantName = ""; + String user = ""; + String pass = ""; + + catalog = new ServiceCatalogV3(IDENTITY_URL, TENANT_NAME, PRINCIPAL, CREDENTIAL, DOMAIN, properties); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestVMURL.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestVMURL.java new file mode 100644 index 000000000..d433afb64 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestVMURL.java @@ -0,0 +1,130 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.adapter.iaas.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import java.util.Properties; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.appc.adapter.iaas.impl.VMURL; +import org.onap.appc.configuration.ConfigurationFactory; + +public class TestVMURL { + + private static String IP; + private static String PORT; + private static String TENANTID; + private static String VMID; + private static String URL; + + @BeforeClass + public static void before() { + Properties props = ConfigurationFactory.getConfiguration().getProperties(); + IP = props.getProperty("test.ip"); + PORT = props.getProperty("test.port"); + TENANTID = props.getProperty("test.tenantid"); + VMID = props.getProperty("test.vmid"); + } + + /** + * Test that we can parse and interpret valid URLs + */ + @Test + public void testValidURL1() { + URL = String.format("http://%s:%s/v2/%s/servers/%s", IP, PORT, TENANTID, VMID); + VMURL url = VMURL.parseURL(URL); + + assertEquals("http", url.getScheme()); + assertEquals(IP, url.getHost()); + assertEquals(PORT, url.getPort()); + assertEquals(TENANTID, url.getTenantId()); + assertEquals(VMID, url.getServerId()); + assertEquals(url.toString(), URL); + } + + @Test + public void testValidURL2() { + URL = String.format("http://%s/v2/%s/servers/%s", IP, TENANTID, VMID); + VMURL url = VMURL.parseURL(URL); + assertEquals("http", url.getScheme()); + assertEquals(IP, url.getHost()); + assertNull(url.getPort()); + assertNull(url.getPath()); + assertEquals(TENANTID, url.getTenantId()); + assertEquals(VMID, url.getServerId()); + assertEquals(url.toString(), URL); + } + + @Test + public void testValidURL3() { + URL = "http://msb.onap.org:80/api/multicloud/v0/cloudowner_region/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"; + VMURL url = VMURL.parseURL(URL); + assertNotNull(url); + assertEquals("http", url.getScheme()); + assertEquals("msb.onap.org", url.getHost()); + assertEquals("80", url.getPort()); + assertEquals("/api/multicloud/v0/cloudowner_region", url.getPath()); + assertEquals(TENANTID, url.getTenantId()); + assertEquals(VMID, url.getServerId()); + assertEquals(url.toString(), URL); + } + + /** + * Test that we ignore and return null for invalid URLs + */ + @Test + public void testInvalidURLs() { + VMURL url = VMURL.parseURL(null); + assertNull(url); + + url = VMURL.parseURL(String.format("%s:%s/v2/%s/servers/%s", IP, PORT, TENANTID, VMID)); + assertNull(url); + + url = VMURL.parseURL(String.format("http:/%s:%s/v2/%s/servers/%s", IP, PORT, TENANTID, VMID)); + assertNull(url); + + url = VMURL.parseURL(String.format("http:///%s:%s/v2/%s/servers/%s", IP, PORT, TENANTID, VMID)); + assertNull(url); + + url = VMURL.parseURL(String.format("http://v2/%s/servers/%s", TENANTID, VMID)); + assertNull(url); + + url = VMURL.parseURL(String.format("%s:%s/%s/servers/%s", IP, PORT, TENANTID, VMID)); + assertNull(url); + + url = VMURL.parseURL(String.format("%s:%s/v2/servers/%s", IP, PORT, VMID)); + assertNull(url); + + url = VMURL.parseURL(String.format("%s:%s/v2/%s/%s", IP, PORT, TENANTID, VMID)); + assertNull(url); + + url = VMURL.parseURL(String.format("%s:%s/v2/%s/servers", IP, PORT, TENANTID)); + assertNull(url); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java new file mode 100644 index 000000000..7a03a8d84 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.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.onap.appc.test.InterceptLogger; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.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 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: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the + * declared field
  • + *
  • 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
  • + *
+ * @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: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the + * declared field
  • + *
  • 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
  • + *
+ * @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 getExecMethodNames() { + List 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-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java new file mode 100644 index 000000000..6c81a6c6e --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java @@ -0,0 +1,449 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.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 events; + + /** + * Create the intercept logger + */ + public InterceptLogger() { + events = new ArrayList(1000); + } + + /** + * @return Returns all intercepted log events + */ + public List 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-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestIdentityUrl.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestIdentityUrl.java deleted file mode 100644 index dac22eadb..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestIdentityUrl.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.appc.adapter.iaas.impl; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import java.util.Properties; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.appc.adapter.iaas.impl.IdentityURL; -import org.onap.appc.configuration.ConfigurationFactory; - -public class TestIdentityUrl { - - private static String URL; - - @BeforeClass - public static void before() { - Properties props = ConfigurationFactory.getConfiguration().getProperties(); - URL = props.getProperty(""); - } - - /** - * Test that we can parse and interpret valid URLs - */ - @Test - public void testValidURL1() { - URL = "http://192.168.1.1:5000/v2.0/"; - IdentityURL idurl = IdentityURL.parseURL(URL); - assertNotNull(idurl); - assertTrue(idurl.getScheme().equals("http")); - assertTrue(idurl.getHost().equals("192.168.1.1")); - assertTrue(idurl.getPort().equals("5000")); - assertNull(idurl.getPath()); - assertTrue(idurl.getVersion().equals("v2.0")); - assertTrue(idurl.toString().equals("http://192.168.1.1:5000/v2.0")); - } - - @Test - public void testValidURL2() { - URL = "https://192.168.1.1:5000/v3/"; - IdentityURL idurl = IdentityURL.parseURL(URL); - assertNotNull(idurl); - assertTrue(idurl.getScheme().equals("https")); - assertTrue(idurl.getHost().equals("192.168.1.1")); - assertTrue(idurl.getPort().equals("5000")); - assertNull(idurl.getPath()); - assertTrue(idurl.getVersion().equals("v3")); - assertTrue(idurl.toString().equals("https://192.168.1.1:5000/v3")); - } - - @Test - public void testValidURL3() { - URL = "http://192.168.1.1/v2.0/"; - IdentityURL idurl = IdentityURL.parseURL(URL); - assertNotNull(idurl); - assertTrue(idurl.getScheme().equals("http")); - assertTrue(idurl.getHost().equals("192.168.1.1")); - assertNull(idurl.getPort()); - assertNull(idurl.getPath()); - assertTrue(idurl.getVersion().equals("v2.0")); - System.out.println(idurl.toString()); - assertTrue(idurl.toString().equals("http://192.168.1.1/v2.0")); - } - - @Test - public void testValidURL4() { - URL = "http://msb.onap.org:80/api/multicloud/v0/cloudowner_region/identity/v3"; - IdentityURL idurl = IdentityURL.parseURL(URL); - assertNotNull(idurl); - assertTrue(idurl.getScheme().equals("http")); - assertTrue(idurl.getHost().equals("msb.onap.org")); - assertTrue(idurl.getPort().equals("80")); - assertTrue(idurl.getPath().equals("/api/multicloud/v0/cloudowner_region/identity")); - assertTrue(idurl.getVersion().equals("v3")); - assertTrue(idurl.toString().equals("http://msb.onap.org:80/api/multicloud/v0/cloudowner_region/identity/v3")); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestProviderAdapterImpl.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestProviderAdapterImpl.java deleted file mode 100644 index 386c1115b..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestProviderAdapterImpl.java +++ /dev/null @@ -1,901 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -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.junit.experimental.categories.Category; -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.ProviderAdapter; -import org.onap.appc.adapter.iaas.impl.ProviderAdapterImpl; -import org.onap.appc.adapter.iaas.impl.ProviderCache; -import org.onap.appc.adapter.iaas.impl.ServiceCatalog; -import org.onap.appc.adapter.iaas.impl.TenantCache; -import org.onap.appc.adapter.iaas.impl.VMURL; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.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.Image; -import com.att.cdp.zones.model.Server; -import com.att.cdp.zones.model.Server.Status; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import com.woorea.openstack.keystone.model.Access.Service.Endpoint; - -/** - * Test the ProviderAdapter implementation. - */ -@Category(org.onap.appc.adapter.iaas.impl.TestProviderAdapterImpl.class) -public class TestProviderAdapterImpl { - - @SuppressWarnings("nls") - private static final String PROVIDER_NAME = "ILAB"; - - @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 ProviderAdapterImpl adapter; - - /** - * Use reflection to locate fields and methods so that they can be manipulated during the test - * to change the internal state accordingly. - * - * @throws NoSuchFieldException if the field(s) dont exist - * @throws SecurityException if reflective access is not allowed - * @throws NoSuchMethodException If the method(s) dont exist - */ - @SuppressWarnings("nls") - @BeforeClass - public static void once() throws NoSuchFieldException, SecurityException, NoSuchMethodException { - providerAdapterImplClass = ProviderAdapterImpl.class; - configurationFactoryClass = ConfigurationFactory.class; - - providerCacheField = providerAdapterImplClass.getDeclaredField("providerCache"); - providerCacheField.setAccessible(true); - - configField = configurationFactoryClass.getDeclaredField("config"); - configField.setAccessible(true); - - Properties props = ConfigurationFactory.getConfiguration().getProperties(); - IDENTITY_URL = props.getProperty("provider1.identity"); - PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc"); - CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc"); - TENANT_NAME = props.getProperty("provider1.tenant1.name", "appc"); - TENANT_ID = props.getProperty("provider1.tenant1.id", "abcde12345fghijk6789lmnopq123rst"); - REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne"); - SERVER_URL = props.getProperty("test.url"); - } - - /** - * Setup the test environment. - * - * @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. - * @throws NullPointerException if the specified object is null and the field is an instance - * field. - * @throws ExceptionInInitializerError if the initialization provoked by this method fails. - */ - @Before - public void setup() throws IllegalArgumentException, IllegalAccessException { - configField.set(null, null); - Properties properties = new Properties(); - adapter = new ProviderAdapterImpl(properties); - } - - /** - * This method inspects the provider adapter implementation to make sure that the cache of - * providers and tenants, as well as the service catalog, and all pools of contexts have been - * set up correctly. - * - * @throws IllegalAccessException if this Field object is enforcing Java language access control - * and the underlying field is inaccessible. - * @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). - */ - @SuppressWarnings({"unchecked"}) - @Ignore - @Test - public void validateCacheIsCreatedCorrectly() throws IllegalArgumentException, IllegalAccessException { - Map providerCaches = (Map) providerCacheField.get(adapter); - - assertNotNull(providerCaches); - assertEquals(1, providerCaches.size()); - assertTrue(providerCaches.containsKey(PROVIDER_NAME)); - - ProviderCache providerCache = providerCaches.get(PROVIDER_NAME); - assertEquals(PROVIDER_NAME, providerCache.getProviderName()); - assertEquals(PROVIDER_TYPE, providerCache.getProviderType()); - - Map tenantCaches = providerCache.getTenants(); - assertNotNull(tenantCaches); - assertEquals(1, tenantCaches.size()); - assertTrue(tenantCaches.containsKey(TENANT_NAME)); - - TenantCache tenantCache = tenantCaches.get(TENANT_NAME); - - assertEquals(TENANT_ID, tenantCache.getTenantId()); - assertEquals(TENANT_NAME, tenantCache.getTenantName()); - assertEquals(USER_ID, tenantCache.getUserid()); - - ServiceCatalog catalog = tenantCache.getServiceCatalog(); - assertNotNull(catalog); - - System.out.println(catalog.toString()); - List serviceTypes = catalog.getServiceTypes(); - assertNotNull(serviceTypes); - assertEquals(12, serviceTypes.size()); - - assertEquals(TENANT_NAME, catalog.getProjectName()); - assertEquals(TENANT_ID, catalog.getProjectId()); - - Set regionNames = catalog.getRegions(); - assertNotNull(regionNames); - assertEquals(1, regionNames.size()); - assertTrue(regionNames.contains(REGION_NAME)); - - List endpoints = catalog.getEndpoints(ServiceCatalog.IDENTITY_SERVICE); - assertNotNull(endpoints); - assertEquals(1, endpoints.size()); - Endpoint endpoint = (Endpoint) endpoints.get(0); - assertNotNull(endpoint); - assertEquals(REGION_NAME, endpoint.getRegion()); - assertEquals(IDENTITY_URL, endpoint.getPublicURL()); - - endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE); - assertNotNull(endpoints); - assertEquals(1, endpoints.size()); - endpoint = (Endpoint) endpoints.get(0); - assertNotNull(endpoint); - assertEquals(REGION_NAME, endpoint.getRegion()); - - endpoints = catalog.getEndpoints(ServiceCatalog.VOLUME_SERVICE); - assertNotNull(endpoints); - assertEquals(1, endpoints.size()); - endpoint = (Endpoint) endpoints.get(0); - assertNotNull(endpoint); - assertEquals(REGION_NAME, endpoint.getRegion()); - - endpoints = catalog.getEndpoints(ServiceCatalog.IMAGE_SERVICE); - assertNotNull(endpoints); - assertEquals(1, endpoints.size()); - endpoint = (Endpoint) endpoints.get(0); - assertNotNull(endpoint); - assertEquals(REGION_NAME, endpoint.getRegion()); - - endpoints = catalog.getEndpoints(ServiceCatalog.NETWORK_SERVICE); - assertNotNull(endpoints); - assertEquals(1, endpoints.size()); - endpoint = (Endpoint) endpoints.get(0); - assertNotNull(endpoint); - assertEquals(REGION_NAME, endpoint.getRegion()); - - assertTrue(catalog.isServicePublished(ServiceCatalog.IDENTITY_SERVICE)); - assertTrue(catalog.isServicePublished(ServiceCatalog.COMPUTE_SERVICE)); - assertTrue(catalog.isServicePublished(ServiceCatalog.VOLUME_SERVICE)); - assertTrue(catalog.isServicePublished(ServiceCatalog.IMAGE_SERVICE)); - assertTrue(catalog.isServicePublished(ServiceCatalog.NETWORK_SERVICE)); - } - - /** - * This test case is used to actually validate that a server has been restarted from an already - * running state - * - * @throws ZoneException If the login cannot be performed because the principal and/or - * credentials are invalid. - * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if - * the expected argument(s) are not defined or are invalid - * @throws IllegalStateException If the identity service is not available or cannot be created - * @throws IOException if an I/O error occurs - * @throws APPCException - */ - // @Ignore - @Test - public void testRestartRunningServer() - throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException { - Properties properties = new Properties(); - properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); - properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); - properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); - properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); - properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true"); - - try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { - context.login(PRINCIPAL, CREDENTIAL); - VMURL vm = VMURL.parseURL(SERVER_URL); - - ComputeService computeService = context.getComputeService(); - Server server = computeService.getServer(vm.getServerId()); - if (!server.getStatus().equals(Status.RUNNING)) { - server.start(); - assertTrue(waitForStateChange(server, Status.RUNNING)); - } - - Map params = new HashMap<>(); - params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); - params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); - SvcLogicContext svcContext = new SvcLogicContext(); - - server = adapter.restartServer(params, svcContext); - - assertEquals(Server.Status.RUNNING, server.getStatus()); - } - } - - - /****************************************/ - /** - * Tests that the vmStatuschecker method works and returns the correct status of the VM - * requested - * - * @throws ZoneException If the login cannot be performed because the principal and/or - * credentials are invalid. - * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if - * the expected argument(s) are not defined or are invalid - * @throws IllegalStateException If the identity service is not available or cannot be created - * @throws IOException if an I/O error occurs - * @throws UnknownProviderException If the provider cannot be found - */ - // @Ignore - @Test - public void testVmStatuschecker() throws IllegalStateException, IllegalArgumentException, ZoneException, - UnknownProviderException, IOException { - Properties properties = new Properties(); - properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); - properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); - properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); - properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); - properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true"); - - try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { - context.login(PRINCIPAL, CREDENTIAL); - VMURL vm = VMURL.parseURL(SERVER_URL); - - ComputeService computeService = context.getComputeService(); - Server server = computeService.getServer(vm.getServerId()); - if (!server.getStatus().equals(Status.RUNNING)) { - server.start(); - assertTrue(waitForStateChange(server, Status.RUNNING)); - } - // or instead of the if-block, can ensureRunning(server) be used? - ensureRunning(server); - assertEquals(Server.Status.RUNNING, server.getStatus()); - } - } - - /****************************************/ - - - /** - * Tests that we can restart a server that is already stopped - * - * @throws ZoneException If the login cannot be performed because the principal and/or - * credentials are invalid. - * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if - * the expected argument(s) are not defined or are invalid. - * @throws IllegalStateException If the identity service is not available or cannot be created - * @throws IOException if an I/O error occurs - * @throws APPCException - */ - // @Ignore - @Test - public void testRestartStoppedServer() - throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException { - Properties properties = new Properties(); - properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); - properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); - properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); - properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); - - try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { - context.login(PRINCIPAL, CREDENTIAL); - VMURL vm = VMURL.parseURL(SERVER_URL); - - ComputeService computeService = context.getComputeService(); - Server server = computeService.getServer(vm.getServerId()); - if (!server.getStatus().equals(Status.READY)) { - server.stop(); - assertTrue(waitForStateChange(server, Status.READY)); - } - - Map params = new HashMap<>(); - params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); - params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); - SvcLogicContext svcContext = new SvcLogicContext(); - - server = adapter.restartServer(params, svcContext); - - assertEquals(Server.Status.RUNNING, server.getStatus()); - - } - } - - /** - * Tests that we can rebuild a running server (not created from a bootable volume) - * - * @throws ZoneException If the login cannot be performed because the principal and/or - * credentials are invalid. - * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if - * the expected argument(s) are not defined or are invalid. - * @throws IllegalStateException If the identity service is not available or cannot be created - * @throws UnknownProviderException If the provider cannot be found - * @throws IOException if an I/O error occurs - * @throws APPCException If the server cannot be rebuilt for some reason - */ - // @Ignore - @Test - public void testRebuildRunningServer() - throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException { - Properties properties = new Properties(); - properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); - properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); - properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); - properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); - - try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { - context.login(PRINCIPAL, CREDENTIAL); - VMURL vm = VMURL.parseURL(SERVER_URL); - - ComputeService computeService = context.getComputeService(); - Server server = computeService.getServer(vm.getServerId()); - ensureRunning(server); - - Map params = new HashMap<>(); - params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); - params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); - SvcLogicContext svcContext = new SvcLogicContext(); - - server = adapter.rebuildServer(params, svcContext); - assertTrue(waitForStateChange(server, Status.RUNNING)); - - } - } - - /** - * Tests that we can rebuild a paused server (not created from a bootable volume) - * - * @throws ZoneException If the login cannot be performed because the principal and/or - * credentials are invalid. - * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if - * the expected argument(s) are not defined or are invalid. - * @throws IllegalStateException If the identity service is not available or cannot be created - * @throws UnknownProviderException If the provider cannot be found - * @throws IOException if an I/O error occurs - * @throws APPCException If the server cannot be rebuilt for some reason - */ - // @Ignore - @Test - public void testRebuildPausedServer() - throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException { - Properties properties = new Properties(); - properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); - properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); - properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); - properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); - - try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { - context.login(PRINCIPAL, CREDENTIAL); - VMURL vm = VMURL.parseURL(SERVER_URL); - - ComputeService computeService = context.getComputeService(); - Server server = computeService.getServer(vm.getServerId()); - ensurePaused(server); - - Map params = new HashMap<>(); - params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); - params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); - SvcLogicContext svcContext = new SvcLogicContext(); - - server = adapter.rebuildServer(params, svcContext); - assertTrue(waitForStateChange(server, Status.RUNNING)); - } - } - - /** - * Tests that we can rebuild a paused server (not created from a bootable volume) - * - * @throws ZoneException If the login cannot be performed because the principal and/or - * credentials are invalid. - * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if - * the expected argument(s) are not defined or are invalid. - * @throws IllegalStateException If the identity service is not available or cannot be created - * @throws UnknownProviderException If the provider cannot be found - * @throws IOException if an I/O error occurs - * @throws APPCException If the server cannot be rebuilt for some reason - */ - // @Ignore - @Test - public void testRebuildSuspendedServer() - throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException { - Properties properties = new Properties(); - properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); - properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); - properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); - properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); - - try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { - context.login(PRINCIPAL, CREDENTIAL); - VMURL vm = VMURL.parseURL(SERVER_URL); - - ComputeService computeService = context.getComputeService(); - Server server = computeService.getServer(vm.getServerId()); - ensureSuspended(server); - - Map params = new HashMap<>(); - params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); - params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); - SvcLogicContext svcContext = new SvcLogicContext(); - - server = adapter.rebuildServer(params, svcContext); - assertTrue(waitForStateChange(server, Status.RUNNING)); - } - } - - /** - * Tests that we can rebuild a paused server (not created from a bootable volume) - * - * @throws ZoneException If the login cannot be performed because the principal and/or - * credentials are invalid. - * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if - * the expected argument(s) are not defined or are invalid. - * @throws IllegalStateException If the identity service is not available or cannot be created - * @throws UnknownProviderException If the provider cannot be found - * @throws IOException if an I/O error occurs - * @throws APPCException If the server cannot be rebuilt for some reason - */ - // @Ignore - @Test - public void testRebuildStoppedServer() - throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException { - Properties properties = new Properties(); - properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL); - properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); - properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); - properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); - - try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { - context.login(PRINCIPAL, CREDENTIAL); - VMURL vm = VMURL.parseURL(SERVER_URL); - - ComputeService computeService = context.getComputeService(); - Server server = computeService.getServer(vm.getServerId()); - ensureStopped(server); - - Map params = new HashMap<>(); - params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); - params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); - SvcLogicContext svcContext = new SvcLogicContext(); - - server = adapter.rebuildServer(params, svcContext); - assertTrue(waitForStateChange(server, Status.RUNNING)); - } - } - - /** - * Test subsequent action on second vm in different Tenant resulting in {"itemNotFound": - * {"message": "Instance could not be found", "code": 404}} - * - * @throws ZoneException If the login cannot be performed because the principal and/or - * credentials are invalid. - * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if - * the expected argument(s) are not defined or are invalid - * @throws IllegalStateException If the identity service is not available or cannot be created - * @throws IOException if an I/O error occurs - * @throws APPCException - */ - - @Test - public void testTenantVerification() - throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException { - - Properties properties = new Properties(); - properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, "http://example.com:5000"); - properties.setProperty(ContextFactory.PROPERTY_TENANT, "APP-C"); - properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); - - String vmUrl = - "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"; - - // try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { - // context.login("AppC", "AppC"); - - // call lookupServer on vm in defined tenant "APP-C_TLV" - VMURL vm = VMURL.parseURL(vmUrl); - - Map params = new HashMap<>(); - params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl); - params.put(ProviderAdapter.PROPERTY_IDENTITY_URL, "http://example.com:5000/v2.0"); - params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, "http://example.com:5000/v2.0"); - SvcLogicContext svcContext = new SvcLogicContext(); - - long start, end = 0; - - System.out.println("\n--------------------Begin lookupServer on tenant 1--------------------"); - start = System.currentTimeMillis(); - Server server = adapter.lookupServer(params, svcContext); - end = System.currentTimeMillis(); - - System.out.println(String.format("lookupServer on tenant 1 took %ds", (end - start) / 1000)); - System.out.println("----------------------------------------------------------------------\n"); - assertNotNull(server); - - // repeat to show that context is reused for second request - System.out.println("\n-----------------Begin repeat lookupServer on tenant 1----------------"); - start = System.currentTimeMillis(); - server = adapter.lookupServer(params, svcContext); - end = System.currentTimeMillis(); - - System.out.println(String.format("Repeat lookupServer on tenant 1 took %ds", (end - start) / 1000)); - System.out.println("----------------------------------------------------------------------\n"); - assertNotNull(server); - - // call lookupServer on vm in second tenant "Play" - // This is where we would fail due to using the previous - // tenants context - vmUrl = "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"; - vm = VMURL.parseURL(vmUrl); - params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl); - - System.out.println("\n--------------------Begin lookupServer on tenant 2--------------------"); - start = System.currentTimeMillis(); - server = adapter.lookupServer(params, svcContext); - end = System.currentTimeMillis(); - System.out.println(String.format("\nlookupServer on tenant 2 took %ds", (end - start) / 1000)); - System.out.println("----------------------------------------------------------------------\n"); - assertNotNull(server); - - // call lookupServer on vm in non-existing tenant - vmUrl = "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"; - vm = VMURL.parseURL(vmUrl); - params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl); - - System.out.println("\n--------------Begin lookupServer on non-existant tenant--------------"); - start = System.currentTimeMillis(); - server = adapter.lookupServer(params, svcContext); - end = System.currentTimeMillis(); - System.out.println(String.format("\nlookupServer on tenant 3 took %ds", (end - start) / 1000)); - System.out.println("----------------------------------------------------------------------\n"); - assertNull(server); - - // } - } - - /****************************************/ - - - @Test - public void testSnapshotServer() throws Exception { - Properties properties = new Properties(); - properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, "http://example.com:5000"); - // properties.setProperty(ContextFactory.PROPERTY_REGION, ""); - properties.setProperty(ContextFactory.PROPERTY_TENANT, "Play"); - properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); - - String vmUrl = - "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"; - - try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) { - context.login("AppC", "AppC"); - VMURL vm = VMURL.parseURL(vmUrl); - - Map params = new HashMap<>(); - params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl); - params.put(ProviderAdapter.PROPERTY_IDENTITY_URL, "http://example.com:5000/v2.0"); - params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, "http://example.com:5000/v2.0"); - SvcLogicContext svcContext = new SvcLogicContext(); - - long start, end = 0; - - start = System.currentTimeMillis(); - Image image = adapter.createSnapshot(params, svcContext); - end = System.currentTimeMillis(); - - System.out.println(String.format("Image ID: %s", image.getId())); - System.out.println(String.format("Snapshot took %ds", (end - start) / 1000)); - - start = System.currentTimeMillis(); - adapter.rebuildServer(params, svcContext); - end = System.currentTimeMillis(); - System.out.println(String.format("Rebuild took %ds", (end - start) / 1000)); - } - - } - - /** - * Ensures that the server is in stopped (shutdown) state prior to test - * - * @param server The server to ensure is stopped - * @throws ZoneException If the server can't be operated upon for some reason - */ - @SuppressWarnings("nls") - private static void ensureStopped(Server server) throws ZoneException { - switch (server.getStatus()) { - case READY: - break; - - case PENDING: - waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED, - Server.Status.SUSPENDED, Server.Status.ERROR); - ensureSuspended(server); - break; - - case PAUSED: - server.unpause(); - waitForStateChange(server, Server.Status.RUNNING); - server.stop(); - waitForStateChange(server, Server.Status.READY); - break; - - case SUSPENDED: - server.resume(); - waitForStateChange(server, Server.Status.RUNNING); - server.stop(); - waitForStateChange(server, Server.Status.READY); - break; - - case RUNNING: - server.stop(); - waitForStateChange(server, Server.Status.READY); - break; - - case DELETED: - case ERROR: - default: - fail("Server state is not valid for test - " + server.getStatus().name()); - } - } - - /** - * Ensures that the server is in suspended state prior to test - * - * @param server The server to ensure is suspended - * @throws ZoneException If the server can't be operated upon for some reason - */ - @SuppressWarnings("nls") - private static void ensureSuspended(Server server) throws ZoneException { - switch (server.getStatus()) { - case SUSPENDED: - break; - - case PENDING: - waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED, - Server.Status.SUSPENDED, Server.Status.ERROR); - ensureSuspended(server); - break; - - case PAUSED: - server.unpause(); - waitForStateChange(server, Server.Status.RUNNING); - server.suspend(); - waitForStateChange(server, Server.Status.SUSPENDED); - break; - - case READY: - server.start(); - waitForStateChange(server, Server.Status.RUNNING); - server.suspend(); - waitForStateChange(server, Server.Status.SUSPENDED); - break; - - case RUNNING: - server.suspend(); - waitForStateChange(server, Server.Status.SUSPENDED); - break; - - case DELETED: - case ERROR: - default: - fail("Server state is not valid for test - " + server.getStatus().name()); - } - } - - /** - * This method makes sure that the indicated server is running before performing a test - * - * @param server The server to ensure is running - * @throws ZoneException If the server can't be operated upon - */ - @SuppressWarnings("nls") - private static void ensureRunning(Server server) throws ZoneException { - switch (server.getStatus()) { - case RUNNING: - break; - - case PENDING: - waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED, - Server.Status.SUSPENDED, Server.Status.ERROR); - ensureRunning(server); - break; - - case PAUSED: - server.unpause(); - waitForStateChange(server, Server.Status.RUNNING); - break; - - case SUSPENDED: - server.resume(); - waitForStateChange(server, Server.Status.RUNNING); - break; - - case READY: - server.start(); - waitForStateChange(server, Server.Status.RUNNING); - break; - - case DELETED: - case ERROR: - default: - fail("Server state is not valid for test - " + server.getStatus().name()); - } - } - - /** - * This method will make sure that the server we are testing is paused - * - * @param server The server to make sure is paused for the test - * @throws ZoneException If anything fails - */ - @SuppressWarnings("nls") - private static void ensurePaused(Server server) throws ZoneException { - switch (server.getStatus()) { - case PAUSED: - break; - - case PENDING: - waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED, - Server.Status.SUSPENDED, Server.Status.ERROR); - ensurePaused(server); - break; - - case READY: - server.start(); - waitForStateChange(server, Server.Status.RUNNING); - server.pause(); - waitForStateChange(server, Server.Status.PAUSED); - break; - - case RUNNING: - server.pause(); - waitForStateChange(server, Server.Status.PAUSED); - break; - - case SUSPENDED: - server.resume(); - waitForStateChange(server, Server.Status.RUNNING); - server.pause(); - waitForStateChange(server, Server.Status.PAUSED); - break; - - case ERROR: - case DELETED: - default: - fail("Server state is not valid for test - " + server.getStatus().name()); - } - } - - /** - * Enter a pool-wait loop checking the server state to see if it has entered one of the desired - * states or not. - *

- * 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 alloted timeout - * period, then the method returns a failed response (false). No exceptions are thrown from this - * method. - *

- * - * @param server The server to wait on - * @param desiredStates A variable list of desired states, any one of which is allowed. - * @return True if the server entered one of the desired states, and false if not and the wait - * loop timed out. - */ - private static boolean waitForStateChange(Server server, Server.Status... desiredStates) { - int timeout = ConfigurationFactory.getConfiguration() - .getIntegerProperty(Constants.PROPERTY_SERVER_STATE_CHANGE_TIMEOUT); - long limit = System.currentTimeMillis() + (timeout * 1000); - Server vm = server; - - try { - while (limit > System.currentTimeMillis()) { - vm.refresh(); - for (Server.Status desiredState : desiredStates) { - if (server.getStatus().equals(desiredState)) { - return true; - } - } - - try { - Thread.sleep(10000L); - } catch (InterruptedException e) { - // ignore - } - } - } catch (ZoneException e) { - e.printStackTrace(); - } - - return false; - } - - /* - * @Test public void testTerminateStack() throws IllegalStateException, - * IllegalArgumentException, ZoneException, UnknownProviderException, IOException { Properties - * properties = new Properties(); properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, - * IDENTITY_URL); properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME); - * properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME); - * properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*"); - * properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true"); try (Context context = - * ContextFactory.getContext(PROVIDER_TYPE, properties)) { context.login(PRINCIPAL, CREDENTIAL); - * VMURL vm = VMURL.parseURL(SERVER_URL); ComputeService computeService = - * context.getComputeService(); Server server = computeService.getServer(vm.getServerId()); if - * (!server.getStatus().equals(Status.RUNNING)) { server.start(); - * assertTrue(waitForStateChange(server, Status.RUNNING)); } Map params = new - * HashMap<>(); params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); - * params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); SvcLogicContext svcContext - * = new SvcLogicContext(); Stack stack = adapter.terminateStack(params, svcContext); - * assertNotNull(stack); } } - */ - -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestProviderOperation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestProviderOperation.java deleted file mode 100644 index c080cf953..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestProviderOperation.java +++ /dev/null @@ -1,162 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.impl; - -import java.lang.reflect.Field; -import java.util.Map; -import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderOperation; -import org.onap.appc.exceptions.APPCException; -import com.att.cdp.zones.model.ModelObject; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.slf4j.MDC; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import static org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants.MDC_SERVICE; - -/** - * This class is used to test methods and functions of the adapter implementation that do not - * require and do not set up connections to any providers. - * - * @since Jan 20, 2016 - * @version $Id$ - */ - -public class TestProviderOperation extends ProviderOperation { - - private static Class providerAdapterImplClass; - private static Class configurationFactoryClass; - private static Field providerCacheField; - private static Field configField; - - /** - * Use reflection to locate fields and methods so that they can be manipulated during the test - * to change the internal state accordingly. - * - * @throws NoSuchFieldException if the field(s) dont exist - * @throws SecurityException if reflective access is not allowed - * @throws NoSuchMethodException If the method(s) dont exist - */ - @SuppressWarnings("nls") - @BeforeClass - public static void once() throws NoSuchFieldException, SecurityException, NoSuchMethodException { - providerAdapterImplClass = ProviderAdapterImpl.class; - configurationFactoryClass = ConfigurationFactory.class; - - providerCacheField = providerAdapterImplClass.getDeclaredField("providerCache"); - providerCacheField.setAccessible(true); - - configField = configurationFactoryClass.getDeclaredField("config"); - configField.setAccessible(true); - } - - /** - * This test expects a failure because the value to be validated is a null URL - * - * @throws RequestFailedException Expected - */ - @SuppressWarnings("nls") - @Test(expected = RequestFailedException.class) - public void testValidateParameterPatternExpectFailNullValue() throws RequestFailedException { - MDC.put(MDC_SERVICE, "junit"); - SvcLogicContext svcContext = new SvcLogicContext(); - RequestContext rc = new RequestContext(svcContext); - String link = null; - - validateVMURL(VMURL.parseURL(link)); - } - - /** - * This test expects a failure because the value to be validated is an empty URL - * - * @throws RequestFailedException Expected - */ - @SuppressWarnings("nls") - @Test(expected = RequestFailedException.class) - public void testValidateParameterPatternExpectFailEmptyValue() throws RequestFailedException { - MDC.put(MDC_SERVICE, "junit"); - SvcLogicContext svcContext = new SvcLogicContext(); - RequestContext rc = new RequestContext(svcContext); - String link = ""; - - validateVMURL(VMURL.parseURL(link)); - } - - /** - * This test expects a failure because the value to be validated is a blank URL - * - * @throws RequestFailedException Expected - */ - @SuppressWarnings("nls") - @Test(expected = RequestFailedException.class) - public void testValidateParameterPatternExpectFailBlankValue() throws RequestFailedException { - MDC.put(MDC_SERVICE, "junit"); - SvcLogicContext svcContext = new SvcLogicContext(); - RequestContext rc = new RequestContext(svcContext); - String link = " "; - - validateVMURL(VMURL.parseURL(link)); - } - - /** - * This test expects a failure because the value to be validated is a bad URL - * - * @throws RequestFailedException Expected - */ - @SuppressWarnings("nls") - @Test(expected = RequestFailedException.class) - public void testValidateParameterPatternExpectFailBadURL() throws RequestFailedException { - MDC.put(MDC_SERVICE, "junit"); - SvcLogicContext svcContext = new SvcLogicContext(); - RequestContext rc = new RequestContext(svcContext); - String link = "http://some.host:1234/01d82c08594a4b23a0f9260c94be0c4d/"; - - validateVMURL(VMURL.parseURL(link)); - } - - /** - * This test expects to pass - * - * @throws RequestFailedException Un-Expected - */ - @SuppressWarnings("nls") - @Test - public void testValidateParameterPatternValidURL() throws RequestFailedException { - MDC.put(MDC_SERVICE, "junit"); - SvcLogicContext svcContext = new SvcLogicContext(); - RequestContext rc = new RequestContext(svcContext); - String link = - "http://some.host:1234/v2/01d82c08594a4b23a0f9260c94be0c4d/servers/f888f89f-096b-421e-ba36-34f714071551"; - - validateVMURL(VMURL.parseURL(link)); - } - - @Override - protected ModelObject executeProviderOperation(Map params, SvcLogicContext context) - throws APPCException { - return null; - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestRequestContext.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestRequestContext.java deleted file mode 100644 index 7ea30635c..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestRequestContext.java +++ /dev/null @@ -1,162 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.appc.adapter.iaas.impl; - -import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.Constants; -import org.onap.appc.adapter.iaas.impl.RequestContext; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; - -/** - * Test the RequestContext object - *

- * The request context is used to track retries, recovery attempts, and time to live of the - * processing of a request. - *

- */ - -public class TestRequestContext { - - private RequestContext rc; - private Configuration config = ConfigurationFactory.getConfiguration(); - - /** - * Set up the test environment by forcing the retry delay and limit to small values for the test - * and setting up the request context object. - */ - @Before - public void setup() { - config.setProperty(Constants.PROPERTY_RETRY_DELAY, "1"); - config.setProperty(Constants.PROPERTY_RETRY_LIMIT, "3"); - rc = new RequestContext(null); - rc.setTimeToLiveSeconds(2); - } - - /** - * Ensure that we set up the property correctly - */ - @Test - public void testRetryDelayProperty() { - assertEquals(1, rc.getRetryDelay()); - } - - /** - * Ensure that we set up the property correctly - */ - @Test - public void testRetryLimitProperty() { - assertEquals(3, rc.getRetryLimit()); - } - - /** - * This test ensures that the retry attempt counter is zero on a new context - */ - @Test - public void testRetryCountNoRetries() { - assertEquals(0, rc.getAttempts()); - } - - /** - * Test that the delay is accurate - */ - @Test - public void testDelay() { - long future = System.currentTimeMillis() + (rc.getRetryDelay() * 1000L); - - rc.delay(); - - assertTrue(System.currentTimeMillis() >= future); - } - - /** - * The RequestContext tracks the number of retry attempts against the limit. This test verifies - * that tracking logic works correctly. - */ - @Test - public void testCanRetry() { - assertEquals(0, rc.getAttempts()); - assertTrue(rc.attempt()); - assertEquals(1, rc.getAttempts()); - assertTrue(rc.attempt()); - assertEquals(2, rc.getAttempts()); - assertTrue(rc.attempt()); - assertEquals(3, rc.getAttempts()); - assertFalse(rc.attempt()); - assertEquals(3, rc.getAttempts()); - assertFalse(rc.attempt()); - assertEquals(3, rc.getAttempts()); - assertFalse(rc.attempt()); - assertEquals(3, rc.getAttempts()); - } - - /** - * The same RequestContext is used throughout the processing, and retries need to be reset once - * successfully connected so that any earlier (successful) recoveries are not considered when - * performing any new future recoveries. This test ensures that a reset clears the retry counter - * and that we can attempt retries again up to the limit. - */ - @Test - public void testResetAndCanRetry() { - assertTrue(rc.attempt()); - assertTrue(rc.attempt()); - assertTrue(rc.attempt()); - rc.reset(); - - assertTrue(rc.attempt()); - assertTrue(rc.attempt()); - assertTrue(rc.attempt()); - assertFalse(rc.attempt()); - assertFalse(rc.attempt()); - assertFalse(rc.attempt()); - } - - /** - * This test is used to test tracking of time to live for the request context. Because time is - * inexact, the assertions can only be ranges of values, such as at least some value or greater. - * The total duration tracking in the request context is only updated on each call to - * {@link RequestContext#isAlive()}. Also, durations are NOT affected by calls to reset. - */ - @Test - public void testTimeToLive() { - assertTrue(rc.getTotalDuration() == 0L); - assertTrue(rc.isAlive()); - rc.reset(); - rc.delay(); - assertTrue(rc.isAlive()); - assertTrue(rc.getTotalDuration() >= 1000L); - rc.reset(); - rc.delay(); - rc.isAlive(); - assertTrue(rc.getTotalDuration() >= 2000L); - rc.reset(); - rc.delay(); - assertFalse(rc.isAlive()); - assertTrue(rc.getTotalDuration() >= 3000L); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalog.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalog.java deleted file mode 100644 index c1a41f209..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalog.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.adapter.iaas.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.appc.configuration.ConfigurationFactory; -import com.att.cdp.exceptions.ZoneException; -import com.woorea.openstack.keystone.model.Access.Service; - -/** - * This class tests the service catalog against a known provider. - */ -public class TestServiceCatalog { - - // Number - private static int EXPECTED_REGIONS = 2; - private static int EXPECTED_ENDPOINTS = 1; - - private static String PRINCIPAL; - private static String CREDENTIAL; - private static String TENANT_NAME; - private static String TENANT_ID; - private static String IDENTITY_URL; - private static String REGION_NAME; - - private ServiceCatalog catalog; - - private Properties properties; - - @BeforeClass - public static void before() { - Properties props = ConfigurationFactory.getConfiguration().getProperties(); - IDENTITY_URL = props.getProperty("provider1.identity"); - PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc"); - CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc"); - TENANT_NAME = props.getProperty("provider1.tenant1.name", "appc"); - TENANT_ID = props.getProperty("provider1.tenant1.id", - props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst")); - REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne"); - - EXPECTED_REGIONS = Integer.valueOf(props.getProperty("test.expected-regions", "2")); - EXPECTED_ENDPOINTS = Integer.valueOf(props.getProperty("test.expected-endpoints", "0")); - } - - /** - * Setup the test environment by loading a new service catalog for each test - * - * @throws ZoneException - */ - @Before - public void setup() throws ZoneException { - properties = new Properties(); - catalog = Mockito.mock(ServiceCatalog.class, Mockito.CALLS_REAL_METHODS); - catalog.rwLock = new ReentrantReadWriteLock(); - - Set testdata = new HashSet<>(); - testdata.add("RegionOne"); - catalog.regions = testdata; - } - - /** - * Test that we find all of the expected region(s) - */ - @Test - public void testKnownRegions() { - assertEquals(EXPECTED_REGIONS, catalog.getRegions().size()); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalogFactory.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalogFactory.java deleted file mode 100644 index e974d27ba..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalogFactory.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.impl; - -import java.util.Properties; -import org.junit.Assert; -import org.junit.Test; - -public class TestServiceCatalogFactory { - - @Test - public void testGetServiceCatalogV2() { - String tenantIdentifier = null; - String principal = null; - String credential = null; - String domain = null; - Properties properties = null; - - String url = "http://192.168.1.1:5000/v2.0/"; - ServiceCatalog catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential, - domain, properties); - Assert.assertNotNull(catalog); - Assert.assertEquals(catalog.getClass(), ServiceCatalogV2.class); - - url = "http://192.168.1.1:5000/v2/"; - catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential, domain, - properties); - Assert.assertNotNull(catalog); - Assert.assertEquals(catalog.getClass(), ServiceCatalogV2.class); - - url = "http://192.168.1.1:5000/v2.1/"; - catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential, domain, - properties); - Assert.assertNotNull(catalog); - Assert.assertEquals(catalog.getClass(), ServiceCatalogV2.class); - - } - - @Test - public void testGetServiceCatalogV3() { - String url = "http://192.168.1.1:5000/v3.0/"; - String tenantIdentifier = null; - String principal = null; - String credential = null; - String domain = null; - Properties properties = null; - ServiceCatalog catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential, - domain, properties); - - Assert.assertNotNull(catalog); - Assert.assertEquals(catalog.getClass(), ServiceCatalogV3.class); - } - - @Test - public void testGetServiceCatalogOther() { - String url = "http://192.168.1.1:5000/v4.0/"; - String tenantIdentifier = null; - String principal = null; - String credential = null; - String domain = null; - Properties properties = null; - ServiceCatalog catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential, - domain, properties); - - Assert.assertNull(catalog); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalogV2.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalogV2.java deleted file mode 100644 index 58b56e06f..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalogV2.java +++ /dev/null @@ -1,174 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.iaas.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import com.att.cdp.exceptions.ZoneException; -import com.woorea.openstack.keystone.model.Access.Service; -import java.util.List; -import java.util.Properties; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.configuration.ConfigurationFactory; - -/** - * This class tests the service catalog against a known provider. - */ -@Ignore -public class TestServiceCatalogV2 { - - // Number - private static int EXPECTED_REGIONS = 1; - private static int EXPECTED_ENDPOINTS = 1; - - private static String PRINCIPAL; - private static String CREDENTIAL; - private static String TENANT_NAME; - private static String TENANT_ID; - private static String IDENTITY_URL; - private static String REGION_NAME; - - private ServiceCatalogV2 catalog; - - private Properties properties; - - @BeforeClass - public static void before() { - Properties props = ConfigurationFactory.getConfiguration().getProperties(); - IDENTITY_URL = props.getProperty("provider1.identity", "appc"); - PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc"); - CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc"); - TENANT_NAME = props.getProperty("provider1.tenant1.name", "appc"); - TENANT_ID = props.getProperty("provider1.tenant1.id", - props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst")); - REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne"); - - EXPECTED_REGIONS = Integer.valueOf(props.getProperty("test.expected-regions", "0")); - EXPECTED_ENDPOINTS = Integer.valueOf(props.getProperty("test.expected-endpoints", "0")); - } - - /** - * Setup the test environment by loading a new service catalog for each test - * - * @throws ZoneException - */ - @Before - public void setup() throws ZoneException { - properties = new Properties(); - catalog = new ServiceCatalogV2(IDENTITY_URL, TENANT_NAME, PRINCIPAL, CREDENTIAL, properties); - catalog.init(); - } - - /** - * Test that the tenant name and ID are returned correctly - */ - @Test - public void testKnownTenant() { - assertEquals(TENANT_NAME, catalog.getProjectName()); - assertEquals(TENANT_ID, catalog.getProjectId()); - } - - /** - * Test that we find all of the expected region(s) - */ - @Test - public void testKnownRegions() { - assertEquals(EXPECTED_REGIONS, catalog.getRegions().size()); - // assertEquals(REGION_NAME, catalog.getRegions().toArray()[0]); - } - - /** - * Test that we can check for published services correctly - */ - @Test - public void testServiceTypesPublished() { - assertTrue(catalog.isServicePublished("compute")); - assertFalse(catalog.isServicePublished("bogus")); - } - - /** - * Check that we can get the list of published services - */ - @Test - public void testPublishedServicesList() { - // List services = catalog.getServiceTypes(); - - // assertTrue(services.contains(ServiceCatalog.COMPUTE_SERVICE)); - // assertTrue(services.contains(ServiceCatalog.IDENTITY_SERVICE)); - // assertTrue(services.contains(ServiceCatalog.IMAGE_SERVICE)); - // assertTrue(services.contains(ServiceCatalog.NETWORK_SERVICE)); - // assertTrue(services.contains(ServiceCatalog.VOLUME_SERVICE)); - } - - /** - * Test that we can get the endpoint(s) for a service - */ - @Test - public void testEndpointList() { - List endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE); - - assertNotNull(endpoints); - assertFalse(endpoints.isEmpty()); - assertEquals(EXPECTED_ENDPOINTS, endpoints.size()); - - Service.Endpoint endpoint = endpoints.get(0); - // assertEquals(REGION_NAME, endpoint.getRegion()); - } - - @Test - public void testToString() { - String testString = catalog.toString(); - assertNotNull(testString); - } - - @Ignore - @Test - public void liveConnectionTest() { - // this test should only be used by developers when testing against a live Openstack - // instance, otherwise it should be ignored - properties = new Properties(); - String identity = "http://192.168.0.1:5000/v2.0"; - String tenantName = "Tenant"; - String user = "user"; - String pass = "pass"; - - ServiceCatalogV2 catalog = new ServiceCatalogV2(identity, tenantName, user, pass, properties); - - try { - catalog.init(); - } catch (ZoneException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - String out = catalog.toString(); - System.out.println(out); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalogV3.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalogV3.java deleted file mode 100644 index 26a4d7dbf..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestServiceCatalogV3.java +++ /dev/null @@ -1,167 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.adapter.iaas.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import com.att.cdp.exceptions.ZoneException; -import com.woorea.openstack.keystone.v3.model.Token.Service.Endpoint; -import java.util.List; -import java.util.Properties; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.configuration.ConfigurationFactory; - -/** - * This class tests the service catalog against a known provider. - */ -@Ignore -public class TestServiceCatalogV3 { - - // Number - private static int EXPECTED_REGIONS = 1; - private static int EXPECTED_ENDPOINTS = 1; - - private static String PRINCIPAL; - private static String CREDENTIAL; - private static String DOMAIN; - private static String TENANT_NAME; - private static String TENANT_ID; - private static String IDENTITY_URL; - private static String REGION_NAME; - - private ServiceCatalogV3 catalog; - - private Properties properties; - - @BeforeClass - public static void before() { - Properties props = ConfigurationFactory.getConfiguration().getProperties(); - IDENTITY_URL = props.getProperty("provider1.identity"); - PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc"); - CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc"); - DOMAIN = props.getProperty("provider1.tenant1.domain", "Default"); - TENANT_NAME = props.getProperty("provider1.tenant1.name", "appc"); - TENANT_ID = props.getProperty("provider1.tenant1.id", - props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst")); - REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne"); - - EXPECTED_REGIONS = Integer.valueOf(props.getProperty("test.expected-regions", "0")); - EXPECTED_ENDPOINTS = Integer.valueOf(props.getProperty("test.expected-endpoints", "0")); - } - - /** - * Setup the test environment by loading a new service catalog for each test - * - * @throws ZoneException - */ - @Before - public void setup() throws ZoneException { - properties = new Properties(); - catalog = new ServiceCatalogV3(IDENTITY_URL, TENANT_NAME, PRINCIPAL, CREDENTIAL, DOMAIN, properties); - } - - /** - * Test that the tenant name and ID are returned correctly - */ - @Test - public void testKnownTenant() { - assertEquals(TENANT_NAME, catalog.getProjectName()); - assertEquals(TENANT_ID, catalog.getProjectId()); - } - - /** - * Test that we find all of the expected region(s) - */ - @Test - public void testKnownRegions() { - assertEquals(EXPECTED_REGIONS, catalog.getRegions().size()); - // assertEquals(REGION_NAME, catalog.getRegions().toArray()[0]); - } - - /** - * Test that we can check for published services correctly - */ - @Test - public void testServiceTypesPublished() { - assertTrue(catalog.isServicePublished("compute")); - assertFalse(catalog.isServicePublished("bogus")); - } - - /** - * Check that we can get the list of published services - */ - @Test - public void testPublishedServicesList() { - List services = catalog.getServiceTypes(); - - assertTrue(services.contains(ServiceCatalog.COMPUTE_SERVICE)); - assertTrue(services.contains(ServiceCatalog.IDENTITY_SERVICE)); - assertTrue(services.contains(ServiceCatalog.IMAGE_SERVICE)); - assertTrue(services.contains(ServiceCatalog.NETWORK_SERVICE)); - assertTrue(services.contains(ServiceCatalog.VOLUME_SERVICE)); - } - - /** - * Test that we can get the endpoint(s) for a service - */ - @Test - public void testEndpointList() { - List endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE); - - assertNotNull(endpoints); - assertFalse(endpoints.isEmpty()); - assertEquals(EXPECTED_ENDPOINTS, endpoints.size()); - - Endpoint endpoint = endpoints.get(0); - // assertEquals(REGION_NAME, endpoint.getRegion()); - } - - @Test - public void testToString() { - String testString = catalog.toString(); - assertNotNull(testString); - } - - @Ignore - @Test - public void liveConnectionTest() { - // this test should only be used by developers when testing against a live Openstack - // instance, otherwise it should be ignored - properties = new Properties(); - String identity = ""; - String tenantName = ""; - String user = ""; - String pass = ""; - - catalog = new ServiceCatalogV3(IDENTITY_URL, TENANT_NAME, PRINCIPAL, CREDENTIAL, DOMAIN, properties); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestVMURL.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestVMURL.java deleted file mode 100644 index d433afb64..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/adapter/iaas/impl/TestVMURL.java +++ /dev/null @@ -1,130 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.adapter.iaas.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import java.util.Properties; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.appc.adapter.iaas.impl.VMURL; -import org.onap.appc.configuration.ConfigurationFactory; - -public class TestVMURL { - - private static String IP; - private static String PORT; - private static String TENANTID; - private static String VMID; - private static String URL; - - @BeforeClass - public static void before() { - Properties props = ConfigurationFactory.getConfiguration().getProperties(); - IP = props.getProperty("test.ip"); - PORT = props.getProperty("test.port"); - TENANTID = props.getProperty("test.tenantid"); - VMID = props.getProperty("test.vmid"); - } - - /** - * Test that we can parse and interpret valid URLs - */ - @Test - public void testValidURL1() { - URL = String.format("http://%s:%s/v2/%s/servers/%s", IP, PORT, TENANTID, VMID); - VMURL url = VMURL.parseURL(URL); - - assertEquals("http", url.getScheme()); - assertEquals(IP, url.getHost()); - assertEquals(PORT, url.getPort()); - assertEquals(TENANTID, url.getTenantId()); - assertEquals(VMID, url.getServerId()); - assertEquals(url.toString(), URL); - } - - @Test - public void testValidURL2() { - URL = String.format("http://%s/v2/%s/servers/%s", IP, TENANTID, VMID); - VMURL url = VMURL.parseURL(URL); - assertEquals("http", url.getScheme()); - assertEquals(IP, url.getHost()); - assertNull(url.getPort()); - assertNull(url.getPath()); - assertEquals(TENANTID, url.getTenantId()); - assertEquals(VMID, url.getServerId()); - assertEquals(url.toString(), URL); - } - - @Test - public void testValidURL3() { - URL = "http://msb.onap.org:80/api/multicloud/v0/cloudowner_region/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"; - VMURL url = VMURL.parseURL(URL); - assertNotNull(url); - assertEquals("http", url.getScheme()); - assertEquals("msb.onap.org", url.getHost()); - assertEquals("80", url.getPort()); - assertEquals("/api/multicloud/v0/cloudowner_region", url.getPath()); - assertEquals(TENANTID, url.getTenantId()); - assertEquals(VMID, url.getServerId()); - assertEquals(url.toString(), URL); - } - - /** - * Test that we ignore and return null for invalid URLs - */ - @Test - public void testInvalidURLs() { - VMURL url = VMURL.parseURL(null); - assertNull(url); - - url = VMURL.parseURL(String.format("%s:%s/v2/%s/servers/%s", IP, PORT, TENANTID, VMID)); - assertNull(url); - - url = VMURL.parseURL(String.format("http:/%s:%s/v2/%s/servers/%s", IP, PORT, TENANTID, VMID)); - assertNull(url); - - url = VMURL.parseURL(String.format("http:///%s:%s/v2/%s/servers/%s", IP, PORT, TENANTID, VMID)); - assertNull(url); - - url = VMURL.parseURL(String.format("http://v2/%s/servers/%s", TENANTID, VMID)); - assertNull(url); - - url = VMURL.parseURL(String.format("%s:%s/%s/servers/%s", IP, PORT, TENANTID, VMID)); - assertNull(url); - - url = VMURL.parseURL(String.format("%s:%s/v2/servers/%s", IP, PORT, VMID)); - assertNull(url); - - url = VMURL.parseURL(String.format("%s:%s/v2/%s/%s", IP, PORT, TENANTID, VMID)); - assertNull(url); - - url = VMURL.parseURL(String.format("%s:%s/v2/%s/servers", IP, PORT, TENANTID)); - assertNull(url); - } -} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java deleted file mode 100644 index 7a03a8d84..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java +++ /dev/null @@ -1,181 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.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.onap.appc.test.InterceptLogger; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.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 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: - *
    - *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the - * declared field
  • - *
  • 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
  • - *
- * @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: - *
    - *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the - * declared field
  • - *
  • 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
  • - *
- * @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 getExecMethodNames() { - List 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-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java deleted file mode 100644 index 6c81a6c6e..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java +++ /dev/null @@ -1,449 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.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 events; - - /** - * Create the intercept logger - */ - public InterceptLogger() { - events = new ArrayList(1000); - } - - /** - * @return Returns all intercepted log events - */ - public List 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-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/onap/appc/default.properties b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..d63c49143 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,112 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============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/openecomp/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 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 + +# 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 + diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties deleted file mode 100644 index d63c49143..000000000 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,112 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============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/openecomp/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 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 - -# 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 - diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/AppcNetconfAdapterActivator.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/AppcNetconfAdapterActivator.java new file mode 100644 index 000000000..bae220d13 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/AppcNetconfAdapterActivator.java @@ -0,0 +1,139 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + +import org.onap.appc.adapter.netconf.internal.NetconfDataAccessServiceImpl; +import org.onap.ccsdk.sli.core.dblib.DbLibService; +import org.onap.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.ServiceReference; +import org.osgi.framework.ServiceRegistration; + +public class AppcNetconfAdapterActivator implements BundleActivator { + + /** + * The bundle registration + */ + private ServiceRegistration registration = null; + private ServiceRegistration reporterRegistration = null; + private ServiceRegistration factoryRegistration = null; + private ServiceRegistration dbRegistration = null; + + /** + * The reference to the actual implementation object that implements the services + */ + private NetconfClientFactory clientFactory; + private NetconfDataAccessService DAService; + + /** + * The logger to be used + */ + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AppcNetconfAdapterActivator.class); + + /** + * 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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @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 { + if (registration == null) { + clientFactory = new NetconfClientFactory(); + factoryRegistration = context.registerService(NetconfClientFactory.class, clientFactory, null); + + DAService = new NetconfDataAccessServiceImpl(); + //set dblib service + DbLibService dblibSvc = null; + ServiceReference sref = context.getServiceReference(DbLibService.class.getName()); + try{ + dblibSvc = (DbLibService)context.getService(sref); + }catch(Exception e){ + logger.error(e.getMessage()); + } + DAService.setDbLibService(dblibSvc); + /////////////////////////////////// + factoryRegistration = context.registerService(NetconfDataAccessService.class, DAService, null); + } + + logger.info(Msg.COMPONENT_INITIALIZED, "NETCONF 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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @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 { + if (registration != null) { + registration.unregister(); + registration = null; + } + if (reporterRegistration != null) { + reporterRegistration.unregister(); + reporterRegistration = null; + } + + if (null != factoryRegistration) { + factoryRegistration.unregister(); + factoryRegistration = null; + } + + if (dbRegistration != null) { + dbRegistration.unregister(); + dbRegistration = null; + } + } + + public String getName() { + return "APPC NETCONF adapter"; + } + +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/ConnectionDetails.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/ConnectionDetails.java new file mode 100644 index 000000000..7536f9655 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/ConnectionDetails.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + + +public class ConnectionDetails { + + private String host; + private int port; + private String username; + private String password; + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/MockOperationalStateValidatorImpl.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/MockOperationalStateValidatorImpl.java new file mode 100644 index 000000000..079ae76a4 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/MockOperationalStateValidatorImpl.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + +import org.onap.appc.exceptions.APPCException; + + +public class MockOperationalStateValidatorImpl implements OperationalStateValidator { + @Override + public VnfType getVnfType() { + return VnfType.MOCK; + } + + @Override + public String getConfigurationFileName() { + String configFileName = OperationalStateValidatorFactory.configuration.getProperty(this.getClass().getCanonicalName() + CONFIG_FILE_PROPERTY_SUFFIX); + return configFileName; + } + + @Override + public void validateResponse(String response) throws APPCException { + if(response != null && response.toUpperCase().contains("INVALID")){ + throw new APPCException("INVALID"); + } + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClient.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClient.java new file mode 100644 index 000000000..eaed60fc0 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClient.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + +import org.onap.appc.exceptions.APPCException; + + + +public interface NetconfClient { + + /** + * Open connection to netconf device. + * + * @param connectionDetails object providing details required for netconf connection + */ + void connect(NetconfConnectionDetails connectionDetails) throws APPCException; + + /** + * Send Netconf message to device and receive response. + * + * @param message input netconf xml message + * @return output netconf xml message + */ + String exchangeMessage(String message) throws APPCException; + + /** + * send configuration to Netconf server + * + * @param configuration - xml configuration payload + */ + void configure(String configuration) throws APPCException; + + /** + * returns running configuration of Netconf server + */ + String getConfiguration() throws APPCException; + + /** + * Disconnect from netconf device. + */ + void disconnect() throws APPCException; +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClientFactory.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClientFactory.java new file mode 100644 index 000000000..45c8fb0ed --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClientFactory.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + +import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; +import org.onap.appc.adapter.netconf.odlconnector.NetconfClientRestconfImpl; + + +public class NetconfClientFactory { + + public NetconfClient GetNetconfClient(NetconfClientType type){ + + if(type==NetconfClientType.RESTCONF) { + return new NetconfClientRestconfImpl(); + }else if(type == NetconfClientType.SSH){ + return new NetconfClientJsch(); + } + + return null; + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClientRestconf.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClientRestconf.java new file mode 100644 index 000000000..a23a16797 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClientRestconf.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + +import org.onap.appc.exceptions.APPCException; + + + +public interface NetconfClientRestconf { + + /* + mount device to controller + @param deviceMountPointName - the name of the mounting point in controller + @param payload - json data describing device info + */ + void connect(String deviceMountPointName, String payload) throws APPCException; + + /* + check connection to device + @param deviceMountPointName - the name of the mounting point in controller + */ + boolean checkConnection(String deviceMountPointName) throws APPCException; + + /* + send configuration to Netconf server + @param configuration - xml configuration payload + @param deviceMountPointName - the name of the mounting point in controller + @param moduleName - name of the yang model + @param nodeName - name of the node created in server + */ + void configure(String configuration, String deviceMountPointName, String moduleName, String nodeName) throws APPCException; + + /* + returns configuration of Netconf server + @param deviceMountPointName - the name of the mounting point in controller + @param moduleName - name of the yang model + @param nodeName - name of the node created in server + */ + String getConfiguration(String deviceName, String moduleName, String nodeName) throws APPCException; + + /* + unmount device + @param deviceMountPointName - the name of the mounting point in controller + */ + void disconnect(String deviceMountPointName) throws APPCException; +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClientType.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClientType.java new file mode 100644 index 000000000..bf7512456 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfClientType.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + + +public enum NetconfClientType { + RESTCONF, + SSH +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfConnectionDetails.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfConnectionDetails.java new file mode 100644 index 000000000..e7c0cc44d --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfConnectionDetails.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + +import java.util.List; +import java.util.Properties; + +/** + * Provides details required for connecting to netconf device. + */ +public class NetconfConnectionDetails { + + private String host; + private int port; + private String username; + private String password; + + public static int DEFAULT_PORT = 830; + private List capabilities; + private Properties additionalProperties; + + public NetconfConnectionDetails() { + super(); + setPort(DEFAULT_PORT); + } + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public List getCapabilities() { + return capabilities; + } + + public void setCapabilities(List capabilities) { + this.capabilities = capabilities; + } + + public Properties getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(Properties additionalProperties) { + this.additionalProperties = additionalProperties; + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfDataAccessService.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfDataAccessService.java new file mode 100644 index 000000000..f831541da --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/NetconfDataAccessService.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + +import org.onap.appc.adapter.netconf.exception.DataAccessException; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + + +@SuppressWarnings("JavaDoc") +public interface NetconfDataAccessService { + + /** + * + * @param schema + */ + void setSchema(String schema); + + /** + * + * @param dbLibService + */ + void setDbLibService(DbLibService dbLibService); + + /** + * + * @param xmlID + * @return + * @throws DataAccessException + */ + String retrieveConfigFileName(String xmlID) throws DataAccessException; + + /** + * + * @param vnfType + * @param connectionDetails + * @return + * @throws DataAccessException + */ + boolean retrieveConnectionDetails(String vnfType, ConnectionDetails connectionDetails) throws DataAccessException; + + /** + * + * @param vnfType + * @param connectionDetails + * @return + * @throws DataAccessException + */ + boolean retrieveNetconfConnectionDetails(String vnfType, NetconfConnectionDetails connectionDetails) throws + DataAccessException; + + /** + * + * @param instanceId + * @param requestId + * @param creationDate + * @param logText + * @return + * @throws DataAccessException + */ + boolean logDeviceInteraction(String instanceId, String requestId, String creationDate, String logText) throws + DataAccessException; + +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/OperationalStateValidator.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/OperationalStateValidator.java new file mode 100644 index 000000000..ffa3862e8 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/OperationalStateValidator.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + +import org.onap.appc.exceptions.APPCException; + + +public interface OperationalStateValidator { + public VnfType getVnfType(); + public String getConfigurationFileName(); + public void validateResponse(String response) throws APPCException; + final public static String CONFIG_FILE_PROPERTY_SUFFIX = "-CONFIG_FILE"; +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/OperationalStateValidatorFactory.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/OperationalStateValidatorFactory.java new file mode 100644 index 000000000..37e96917d --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/OperationalStateValidatorFactory.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + +import org.apache.commons.lang3.NotImplementedException; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; + +public class OperationalStateValidatorFactory { + protected static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + public static OperationalStateValidator getOperationalStateValidator(String vnfType) { + VnfType vnfTypeEnum = null; + try { + vnfTypeEnum = VnfType.getVnfType(vnfType); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Illegal value in vnfType. vnfType="+vnfType,e); + } + return getOperationalStateValidator(vnfTypeEnum); + } + + public static OperationalStateValidator getOperationalStateValidator(VnfType vnfType) { + switch (vnfType) { + case VNF: + case VNF_MOCK: + return new VNFOperationalStateValidatorImpl(); + case MOCK: + return new MockOperationalStateValidatorImpl(); + default: + throw new NotImplementedException("missing implementaion for the given vnfType:" + vnfType.name()); + } + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/VNFOperationalStateValidatorImpl.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/VNFOperationalStateValidatorImpl.java new file mode 100644 index 000000000..4bb5ab238 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/VNFOperationalStateValidatorImpl.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.exceptions.APPCException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.*; + +public class VNFOperationalStateValidatorImpl implements OperationalStateValidator { + private static final String OPERATIONAL_STATE_ELEMENT_NAME = "operationalState"; + @Override + public VnfType getVnfType() { + return VnfType.VNF; + } + + @Override + public String getConfigurationFileName() { + String configFileName = OperationalStateValidatorFactory.configuration.getProperty(this.getClass().getCanonicalName() + CONFIG_FILE_PROPERTY_SUFFIX); + configFileName = configFileName == null? "VnfGetOperationalStates" : configFileName; + return configFileName; + } + + @Override + public void validateResponse(String response) throws APPCException { + if(StringUtils.isEmpty(response)) { + throw new APPCException("empty response"); + } + + boolean isValid = false; + String errorMsg = "unexpected response"; + try { + List operationalStateList = getOperationalStateList(response); + if(operationalStateList != null && !operationalStateList.isEmpty()) { + for (Map.Entry stateEntry : operationalStateList) { + if(!((String)stateEntry.getValue()).equalsIgnoreCase("ENABLED")){ + errorMsg = "at least one "+OPERATIONAL_STATE_ELEMENT_NAME+" is not in valid satae. "+operationalStateList.toString(); + isValid = false; + break; + }else{ + isValid =true; + } + } + }else { + errorMsg = "response without any "+OPERATIONAL_STATE_ELEMENT_NAME+" element"; + } + } catch (Exception e ) { + isValid = false; + errorMsg = e.toString(); + } + if(!isValid) throw new APPCException(errorMsg); + } + + private static List getOperationalStateList(String xmlText) throws IOException, ParserConfigurationException, SAXException { + List entryList = null; + if(StringUtils.isNotEmpty(xmlText)) { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + + Document document = builder.parse(new ByteArrayInputStream(xmlText.getBytes("UTF-8"))); + if(document != null) { + Element rootElement = document.getDocumentElement(); + NodeList nodeList = rootElement.getElementsByTagName(OPERATIONAL_STATE_ELEMENT_NAME); + if (nodeList != null && nodeList.getLength() > 0) { + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + String text = node.getTextContent(); + String id = getElementID(node); + entryList = (entryList == null) ? new ArrayList() : entryList; + Map.Entry entry = new AbstractMap.SimpleEntry(id, text); + entryList.add(entry); + } + } + } + } + return entryList; + } + + private static String getElementID(Node node) { + String id = null; + Node parentNode = node.getParentNode(); + if (parentNode != null) { + if (node.getNodeType() == Node.ELEMENT_NODE) { + NodeList nodeList = ((Element) parentNode).getElementsByTagName("id"); + if (nodeList != null && nodeList.getLength() > 0) { + Node idNode = nodeList.item(0); + id = idNode != null ? idNode.getTextContent() : null; + } + }else { + id = parentNode.getNodeValue()+"|"+parentNode.getTextContent(); + } + } + + id = StringUtils.isEmpty(id) ? null : StringUtils.normalizeSpace(id); + id = StringUtils.isBlank(id) ? null : id; + id = id != null ? id : "unknown-id"; + return id; + } + +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/VnfType.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/VnfType.java new file mode 100644 index 000000000..19edc2fd3 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/VnfType.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf; + +public enum VnfType { + VNF("VNF"), + MOCK("MOCK"), + VNF_MOCK("MOCK"), + ; + + String familyType; + String upperCaseName; + VnfType(String familyType) { + this.familyType = familyType; + this.upperCaseName = name().toUpperCase(); + } + + public VnfType getFamilyType() { + return VnfType.valueOf(familyType); + } + + public String getUpperCaseName() { + return upperCaseName; + } + + public static VnfType getVnfType(String inSensitiveCaseName){ + String localUpperCaseName = inSensitiveCaseName.toUpperCase(); + for(VnfType vnfType : VnfType.values()){ + if(vnfType.getUpperCaseName().equals(localUpperCaseName)){ + return vnfType; + } + } + throw new IllegalArgumentException( + "No enum with upperCaseName for this input value:" + inSensitiveCaseName ); + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/exception/DataAccessException.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/exception/DataAccessException.java new file mode 100644 index 000000000..0c4964da0 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/exception/DataAccessException.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.exception; + + +public class DataAccessException extends RuntimeException { + + private static final long serialVersionUID = -155423437162622414L; + + public DataAccessException(){ + } + + public DataAccessException(String message){ + super(message); + } + + public DataAccessException(Throwable cause){ + super(cause); + } + + public DataAccessException(String message , Throwable cause){ + super(message , cause); + } + +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/exception/NetconfDAOException.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/exception/NetconfDAOException.java new file mode 100644 index 000000000..5ff1a331e --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/exception/NetconfDAOException.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.exception; + +public class NetconfDAOException extends RuntimeException { + + private static final long serialVersionUID = -155423437162622414L; + + public NetconfDAOException(){ + } + + public NetconfDAOException(String message){ + super(message); + } + + public NetconfDAOException(Throwable cause){ + super(cause); + } + + public NetconfDAOException(String message , Throwable cause){ + super(message , cause); + } + + +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfAdapter.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfAdapter.java new file mode 100644 index 000000000..2d8c6f417 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfAdapter.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.internal; + +import org.onap.appc.configuration.ConfigurationFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.concurrent.*; + +/** + * Provides basic methods for exchanging netconf messages. + */ +public class NetconfAdapter { + + private static final Logger LOG = LoggerFactory.getLogger(NetconfAdapter.class); + private static final long MAX_WAITING_TIME = 1800000; + private static ExecutorService executor = Executors.newFixedThreadPool(5); + + // device input stream + private InputStream in; + // device output stream + private OutputStream out; + private long maxWaitingTime = ConfigurationFactory.getConfiguration().getLongProperty("org.onap.appc.netconf.recv.timeout", MAX_WAITING_TIME); + + /** + * Constructor. + * + * @param in InputStream this instance will read netconf messages from + * @param out OutputStream this instance will write netconf messages to + * @throws IOException + */ + public NetconfAdapter(InputStream in, OutputStream out) throws IOException { + this.in = in; + this.out = out; + } + + /** + * Receives netconf message from InputStream and return it's text (without netconf frame characters). + * + * @return text of message received from netconf device + * @throws IOException + */ + public String receiveMessage() throws IOException { + + final NetconfMessage message = new NetconfMessage(); + final byte[] buf = new byte[1024]; + + //int readByte = 1; + // Read data with timeout + Callable readTask = new Callable() { + @Override + public Boolean call() throws Exception { + int c; + while ((c = in.read(buf)) > 0) { + if (c > 0) { + message.append(buf, 0, c); + if (message.isCompleted()) { + break; + } + } + } + + if (c < 0) { + return false; + } + return true; + } + }; + + Future future = executor.submit(readTask); + Boolean status; + try { + status = future.get(maxWaitingTime, TimeUnit.MILLISECONDS); + } catch (Exception e) { + throw new IOException(e); + } + + if (status == false) { + throw new IOException("Failed to read netconf message"); + } + + + String text = message.getText(); + if (text != null) { + text = text.trim(); + } + if (LOG.isDebugEnabled()) { + LOG.debug("Received message from netconf device:\n" + text); + } + return text; + } + + /** + * Sends netconf message with provided text (adds netconf frame characters and sends the message). + * + * @param text text of message to be sent to netconf device + * @throws IOException + */ + public void sendMessage(final String text) throws IOException { + if (LOG.isDebugEnabled()) { + LOG.debug("Sending message to netconf device:\n" + text); + } + out.write(new NetconfMessage(text).getFrame()); + out.flush(); + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfAdapter2.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfAdapter2.java new file mode 100644 index 000000000..928d77470 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfAdapter2.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.internal; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; + +/** + * Provides basic methods for exchanging netconf messages. + */ +public class NetconfAdapter2 { + + private static final Logger LOG = LoggerFactory.getLogger(NetconfAdapter2.class); + + // device input pipe + private final PipedOutputStream pipedOutIn = new PipedOutputStream(); + private PipedInputStream in; + // device output pipe + private final PipedInputStream pipedInOut = new PipedInputStream(); + private PipedOutputStream out; + + /** + * Constructor. + * + * @throws IOException + */ + public NetconfAdapter2() throws IOException { + in = new PipedInputStream(pipedOutIn); + out = new PipedOutputStream(pipedInOut); + } + + /** + * @return InputStream this instance will read netconf messages from. + */ + public InputStream getIn() { + return in; + } + + /** + * @return OutputStream this instance will write netconf messages to. + */ + public OutputStream getOut() { + return out; + } + + /** + * Receives netconf message from InputStream and return it's text (without netconf frame characters). + * + * @return text of message received from netconf device + * @throws IOException + */ + public String receiveMessage() throws IOException { + NetconfMessage message = new NetconfMessage(); + byte[] buf = new byte[1024]; + int c; + while((c = pipedInOut.read(buf)) > 0) { + message.append(buf, 0, c); + if (message.isCompleted()) { + break; + } + } + String text = message.getText(); + if(LOG.isDebugEnabled()) { + LOG.debug("Received message from netconf device:\n" + text); + } + return text; + } + + /** + * Sends netconf message with provided text (adds netconf frame characters and sends the message). + * + * @param text text of message to be sent to netconf device + * @throws IOException + */ + public void sendMessage(final String text) throws IOException { + if(LOG.isDebugEnabled()) { + LOG.debug("Sending message to netconf device:\n" + text); + } + pipedOutIn.write(new NetconfMessage(text).getFrame()); + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfConstMessages.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfConstMessages.java new file mode 100644 index 000000000..c7ad9bc50 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfConstMessages.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.internal; + +public class NetconfConstMessages { + + public static final String CAPABILITIES_START = + "\n" + + "\n" + + " \n"; + + public static final String CAPABILITIES_BASE = + " urn:ietf:params:netconf:base:1.0\n"; + + public static final String CAPABILITIES_END = + " \n" + + ""; + + public static final String GET_RUNNING_CONFIG = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""; + + public static final String CLOSE_SESSION = + "\n" + + "\n" + + " \n" + + ""; +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfDataAccessServiceImpl.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfDataAccessServiceImpl.java new file mode 100644 index 000000000..f3cca8597 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfDataAccessServiceImpl.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.internal; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.appc.adapter.netconf.ConnectionDetails; +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.NetconfDataAccessService; +import org.onap.appc.adapter.netconf.exception.DataAccessException; +import org.onap.appc.adapter.netconf.util.Constants; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + +import javax.sql.rowset.CachedRowSet; +import java.sql.SQLException; +import java.util.ArrayList; + +public class NetconfDataAccessServiceImpl implements NetconfDataAccessService { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(NetconfDataAccessServiceImpl.class); + + public void setSchema(String schema) { + this.schema = schema; + } + + private String schema; + + public void setDbLibService(DbLibService service) {dbLibService = service;} + + private DbLibService dbLibService; + + @Override + public String retrieveConfigFileName(String xmlID) throws DataAccessException { + String fileContent = ""; + + String queryString = "select " + Constants.FILE_CONTENT_TABLE_FIELD_NAME + " " + + "from " + Constants.CONFIGFILES_TABLE_NAME + " " + + "where " + Constants.FILE_NAME_TABLE_FIELD_NAME + " = ?"; + + ArrayList argList = new ArrayList<>(); + argList.add(xmlID); + + try { + final CachedRowSet data = dbLibService.getData(queryString, argList, schema); + if (data.first()) { + fileContent = data.getString(Constants.FILE_CONTENT_TABLE_FIELD_NAME); + } + } catch (Exception e) { + logger.error("Error Accessing Database " + e); + throw new DataAccessException(e); + } + + return fileContent; + } + + @Override + public boolean retrieveConnectionDetails(String vnfType, ConnectionDetails connectionDetails) throws + DataAccessException { + boolean recordFound = false; + + String queryString = "select " + Constants.USER_NAME_TABLE_FIELD_NAME + "," + + Constants.PASSWORD_TABLE_FIELD_NAME + "," + Constants.PORT_NUMBER_TABLE_FIELD_NAME + " " + + "from " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME + " " + + "where " + Constants.VNF_TYPE_TABLE_FIELD_NAME + " = ?"; + + ArrayList argList = new ArrayList<>(); + argList.add(vnfType); + + try { + final CachedRowSet data = dbLibService.getData(queryString, argList, schema); + if (data.first()) { + connectionDetails.setUsername(data.getString(Constants.USER_NAME_TABLE_FIELD_NAME)); + connectionDetails.setPassword(data.getString(Constants.PASSWORD_TABLE_FIELD_NAME)); + connectionDetails.setPort(data.getInt(Constants.PORT_NUMBER_TABLE_FIELD_NAME)); + recordFound = true; + } + } catch (SQLException e) { + logger.error("Error Accessing Database " + e); + throw new DataAccessException(e); + } + + return recordFound; + } + + @Override + public boolean retrieveNetconfConnectionDetails(String vnfType, NetconfConnectionDetails connectionDetails) + throws DataAccessException { + ConnectionDetails connDetails = new ConnectionDetails(); + if(this.retrieveConnectionDetails(vnfType, connDetails)) + { + connectionDetails.setHost(connDetails.getHost()); + connectionDetails.setPort(connDetails.getPort()); + connectionDetails.setUsername(connDetails.getUsername()); + connectionDetails.setPassword(connDetails.getPassword()); + } + return true; + } + + @Override + public boolean logDeviceInteraction(String instanceId, String requestId, String creationDate, String logText) + throws DataAccessException { + String queryString = "INSERT INTO "+ Constants.DEVICE_INTERFACE_LOG_TABLE_NAME+"("+ + Constants.SERVICE_INSTANCE_ID_FIELD_NAME+","+ + Constants.REQUEST_ID_FIELD_NAME+","+ + Constants.CREATION_DATE_FIELD_NAME+","+ + Constants.LOG_FIELD_NAME+") "; + queryString += "values(?,?,?,?)"; + + ArrayList argList = new ArrayList<>(); + argList.add(instanceId); + argList.add(requestId); + argList.add(creationDate); + argList.add(logText); + + try { + dbLibService.writeData(queryString, argList, schema); + } catch (SQLException e) { + logger.error("Logging Device interaction failed - "+ queryString); + throw new DataAccessException(e); + } + + return true; + } + +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfMessage.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfMessage.java new file mode 100644 index 000000000..700a51b9f --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/internal/NetconfMessage.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.internal; + +import java.io.ByteArrayOutputStream; + +class NetconfMessage { + + private static final String EOM = "]]>]]>"; + + private String text; + private MessageBuffer buffer = new MessageBuffer(); + private int eomNotch; + + NetconfMessage() { + } + + NetconfMessage(String text) { + if(text == null) { + throw new NullPointerException("Netconf message payload is null"); + } + append(text.getBytes(), 0, text.length()); + if(this.text == null) { + this.text = text; + } + } + + void append(byte[] bytes, int start, int end) { + boolean eomFound = false; + for(int i = start; i < end; i++) { + if(bytes[i] == EOM.charAt(eomNotch)) { + // advance notch + eomNotch++; + } else { + // reset notch + eomNotch = 0; + } + if(eomNotch == EOM.length()) { + // end of message found + eomFound = true; + end = i + 1; + break; + } + } + buffer.write(bytes, start, end); + if(eomFound) { + text = new String(buffer.getBytes(), 0, buffer.size() - EOM.length()); + buffer.reset(); + } + } + + String getText() { + return text; + } + + boolean isCompleted() { + return (text != null); + } + + byte[] getFrame() { + StringBuilder sb = new StringBuilder(); + if(text != null) { + sb.append(text).append("\n"); + } + sb.append(EOM); + return sb.toString().getBytes(); + } + + private class MessageBuffer extends ByteArrayOutputStream { + + byte[] getBytes() { + return buf; + } + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/jsch/JSchLogger.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/jsch/JSchLogger.java new file mode 100644 index 000000000..37bb3b2f2 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/jsch/JSchLogger.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.jsch; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * JSch logger implementation delegating to logback. + */ +public class JSchLogger implements com.jcraft.jsch.Logger { + + private static final Logger LOG = LoggerFactory.getLogger(JSchLogger.class); + + @Override + public boolean isEnabled(int level) { + return true; + } + + @Override + public void log(int level, String message) { + switch(level) { + case com.jcraft.jsch.Logger.DEBUG: + LOG.debug(message); + break; + + case com.jcraft.jsch.Logger.INFO: + LOG.info(message); + break; + + case com.jcraft.jsch.Logger.WARN: + LOG.warn(message); + break; + + case com.jcraft.jsch.Logger.ERROR: + case com.jcraft.jsch.Logger.FATAL: + LOG.error(message); + break; + } + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/jsch/NetconfClientJsch.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/jsch/NetconfClientJsch.java new file mode 100644 index 000000000..7b9d7a4ae --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/jsch/NetconfClientJsch.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.jsch; + +import com.jcraft.jsch.Channel; +import com.jcraft.jsch.ChannelSubsystem; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.Session; + +import java.io.IOException; +import java.util.List; +import java.util.Properties; + +import org.onap.appc.adapter.netconf.NetconfClient; +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.internal.NetconfAdapter; +import org.onap.appc.adapter.netconf.internal.NetconfConstMessages; +import org.onap.appc.encryption.EncryptionTool; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.i18n.Msg; +import com.att.eelf.i18n.EELFResourceManager; + +/** + * Implementation of NetconfClient interface based on JCraft jsch library. + */ +public class NetconfClientJsch implements NetconfClient { + + private static final int SESSION_CONNECT_TIMEOUT = 30000; + private static final int CHANNEL_CONNECT_TIMEOUT = 10000; + + private Session session; + private Channel channel; + private NetconfAdapter netconfAdapter; + + + @Override + public void connect(NetconfConnectionDetails connectionDetails) throws APPCException { + String host = connectionDetails.getHost(); + int port = connectionDetails.getPort(); + String username = connectionDetails.getUsername(); + String password = connectionDetails.getPassword(); + try { + JSch.setLogger(new JSchLogger()); + JSch jsch = new JSch(); + session = jsch.getSession(EncryptionTool.getInstance().decrypt(username), host, port); + session.setPassword(EncryptionTool.getInstance().decrypt(password)); + session.setConfig("StrictHostKeyChecking", "no"); + + Properties additionalProps = connectionDetails.getAdditionalProperties(); + if((additionalProps != null) && !additionalProps.isEmpty()) { + session.setConfig(additionalProps); + } + + session.connect(SESSION_CONNECT_TIMEOUT); + session.setTimeout(10000); + try { +// session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!! + channel = session.openChannel("subsystem"); + ((ChannelSubsystem)channel).setSubsystem("netconf"); + netconfAdapter = new NetconfAdapter(channel.getInputStream(), channel.getOutputStream()); + channel.connect(CHANNEL_CONNECT_TIMEOUT); + hello(connectionDetails.getCapabilities()); + } catch(Exception e) { + disconnect(); + throw e; + } + } catch(Exception e) { + String message = EELFResourceManager.format(Msg.CANNOT_ESTABLISH_CONNECTION, host, String.valueOf(port), username); + throw new APPCException(message, e); + } + } + + @Override + public String exchangeMessage(String message) throws APPCException { + try { + netconfAdapter.sendMessage(message); + return netconfAdapter.receiveMessage(); + } catch(IOException e) { + throw new APPCException(e); + } + } + + @Override + public void configure(String configuration) throws APPCException { + try { + isOk(exchangeMessage(configuration)); + } catch(IOException e) { + throw new APPCException(e); + } + } + + @Override + public String getConfiguration() throws APPCException { + return exchangeMessage(NetconfConstMessages.GET_RUNNING_CONFIG); + } + + @Override + public void disconnect() { + try { + if((channel != null) && !channel.isClosed()) { + netconfAdapter.sendMessage(NetconfConstMessages.CLOSE_SESSION); + isOk(netconfAdapter.receiveMessage()); + } + } catch(IOException e) { + throw new RuntimeException("Error closing netconf device", e); + } finally { + netconfAdapter = null; + if(channel != null) { + channel.disconnect(); + channel = null; + } + if(session != null) { + session.disconnect(); + session = null; + } + } + } + + private void hello(List capabilities) throws IOException { + String helloIn = netconfAdapter.receiveMessage(); + if(helloIn == null) { + throw new IOException("Expected hello message, but nothing received error from netconf device"); + } + if(helloIn.contains("")) { + throw new IOException("Expected hello message, but received error from netconf device:\n" + helloIn); + } + StringBuilder sb = new StringBuilder(); + sb.append(NetconfConstMessages.CAPABILITIES_START); + sb.append(NetconfConstMessages.CAPABILITIES_BASE); + if(capabilities != null) { + for(String capability: capabilities) { + sb.append(" ").append(capability).append("\n"); + } + } + sb.append(NetconfConstMessages.CAPABILITIES_END); + String helloOut = sb.toString(); + netconfAdapter.sendMessage(helloOut); + } + + private void isOk(String response) throws IOException { + if(response == null) { + throw new IOException("No response from netconf device"); + } + if(!response.contains("")) { + throw new IOException("Error response from netconf device: \n" + response); + } + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/odlconnector/NetconfClientRestconfImpl.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/odlconnector/NetconfClientRestconfImpl.java new file mode 100644 index 000000000..bc89551a8 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/odlconnector/NetconfClientRestconfImpl.java @@ -0,0 +1,236 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.odlconnector; + +import org.apache.http.HttpStatus; +import org.onap.appc.adapter.netconf.NetconfClient; +import org.onap.appc.adapter.netconf.NetconfClientRestconf; +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.util.Constants; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.util.httpClient; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.Properties; + +public class NetconfClientRestconfImpl implements NetconfClient, NetconfClientRestconf { + + private EELFLogger logger = EELFManager.getInstance().getLogger(NetconfClientRestconfImpl.class); + + private NetconfConnectionDetails connectionDetails; + + //constructor + public NetconfClientRestconfImpl(){ + } + + //restconf client impl + + @SuppressWarnings("deprecation") + @Override + public void configure(String configuration, String deviceMountPointName, String moduleName, String nodeName) throws APPCException { + + logger.info("Configuring device "+deviceMountPointName+" with configuration "+configuration); + + int httpCode = httpClient.putMethod(Constants.PROTOCOL,Constants.CONTROLLER_IP,Constants.CONTROLLER_PORT,getModuleConfigurePath(deviceMountPointName, moduleName, nodeName),configuration,"application/json"); + + if (httpCode != HttpStatus.SC_OK) { + logger.error("Configuration request failed. throwing Exception !"); + throw new APPCException("Error configuring node :"+nodeName + ", of Module :" + moduleName + ", in device :" + deviceMountPointName); + } + } + + @Override + public void connect(String deviceMountPointName, String payload) throws APPCException{ + + logger.info("Connecting device "+deviceMountPointName); + + int httpCode = httpClient.postMethod(Constants.PROTOCOL,Constants.CONTROLLER_IP,Constants.CONTROLLER_PORT,getConnectPath(),payload,"application/json"); + + if(httpCode != HttpStatus.SC_NO_CONTENT){ + logger.error("Connect request failed with code "+httpCode+". throwing Exception !"); + throw new APPCException("Error connecting device :" + deviceMountPointName); + } + } + + @Override + public boolean checkConnection(String deviceMountPointName) throws APPCException { + logger.info("Checking device "+deviceMountPointName+" connectivity"); + + String result = httpClient.getMethod(Constants.PROTOCOL,Constants.CONTROLLER_IP,Constants.CONTROLLER_PORT,getCheckConnectivityPath(deviceMountPointName),"application/json"); + + return result != null; + } + + @Override + public void disconnect(String deviceMountPointName) throws APPCException { + logger.info("Disconnecting "+deviceMountPointName); + + int httpCode = httpClient.deleteMethod(Constants.PROTOCOL,Constants.CONTROLLER_IP,Constants.CONTROLLER_PORT,getDisconnectPath(deviceMountPointName),"application/json"); + + if(httpCode != HttpStatus.SC_OK){ + logger.error("Disconnection of device "+deviceMountPointName+" failed!"); + throw new APPCException("Disconnection of device "+deviceMountPointName+" failed!"); + } + } + + @Override + public String getConfiguration(String deviceMountPointName, String moduleName, String nodeName) throws APPCException{ + logger.info("Getting configuration of device "+deviceMountPointName); + + String result = httpClient.getMethod(Constants.PROTOCOL,Constants.CONTROLLER_IP,Constants.CONTROLLER_PORT,getModuleConfigurePath(deviceMountPointName, moduleName, nodeName),"application/json"); + + if (result == null) { + logger.error("Configuration request failed. throwing Exception !"); + throw new APPCException("Error getting configuration of node :"+nodeName + ", of Module :" + moduleName + ", in device :" + deviceMountPointName); + } + + return result; + } + + //netconf client impl + + @Override + public void connect(NetconfConnectionDetails connectionDetails) throws APPCException { + if(connectionDetails == null){ + throw new APPCException("Invalid connection details - null value"); + } + this.connectionDetails = connectionDetails; + this.connect(connectionDetails.getHost(),getPayload()); + } + + @Override + public String exchangeMessage(String message) throws APPCException { + // TODO implement + return null; + } + + @Override + public void configure(String configuration) throws APPCException { + if(connectionDetails == null){ + throw new APPCException("Invalid connection details - null value"); + } + + Properties props = connectionDetails.getAdditionalProperties(); + if(props == null || !props.containsKey("module.name") || !props.containsKey("node.name")){ + throw new APPCException("Invalid properties!"); + } + + String moduleName = props.getProperty("module.name"); + String nodeName = props.getProperty("node.name"); + String deviceMountPointName = connectionDetails.getHost(); + + int httpCode = httpClient.putMethod(Constants.PROTOCOL,Constants.CONTROLLER_IP,Constants.CONTROLLER_PORT,getModuleConfigurePath(deviceMountPointName, moduleName, nodeName),configuration,"application/xml"); + + if (httpCode != HttpStatus.SC_OK) { + logger.error("Configuration request failed. throwing Exception !"); + throw new APPCException("Error configuring node :"+nodeName + ", of Module :" + moduleName + ", in device :" + deviceMountPointName); + } + } + + @Override + public String getConfiguration() throws APPCException { + if(connectionDetails == null){ + throw new APPCException("Invalid connection details - null value"); + } + + Properties props = connectionDetails.getAdditionalProperties(); + if(props == null || !props.containsKey("module.name") || !props.containsKey("node.name")){ + throw new APPCException("Invalid properties!"); + } + + return this.getConfiguration(connectionDetails.getHost(),props.getProperty("module.name"),props.getProperty("node.name")); + } + + @Override + public void disconnect() throws APPCException { + if(connectionDetails == null){ + throw new APPCException("Invalid connection details - null value"); + } + this.disconnect(connectionDetails.getHost()); + } + + //private methods + private String getModuleConfigurePath(String deviceMountPointName, String moduleName, String nodeName){ + + + String deviceSpecificPath = deviceMountPointName + "/yang-ext:mount/" + moduleName + ":" + nodeName; + + return Constants.CONFIGURE_PATH + deviceSpecificPath; + } + + private String getConnectPath(){ + + return Constants.CONNECT_PATH; + } + + private String getCheckConnectivityPath(String deviceMountPointName) { + return Constants.CHECK_CONNECTION_PATH + deviceMountPointName; + } + + private String getDisconnectPath(String deviceMountPointName) { + return Constants.DISCONNECT_PATH + deviceMountPointName; + } + + private String getPayload() { + return "{\n" + + " \"config:module\":\n" + + " {\n" + + " \"type\":\"odl-sal-netconf-connector-cfg:sal-netconf-connector\",\n" + + " \"netconf-northbound-ssh\\odl-sal-netconf-connector-cfg:name\":"+connectionDetails.getHost()+",\n" + + " \"odl-sal-netconf-connector-cfg:address\":"+connectionDetails.getHost()+",\n" + + " \"odl-sal-netconf-connector-cfg:port\":"+connectionDetails.getPort()+",\n" + + " \"odl-sal-netconf-connector-cfg:username\":"+connectionDetails.getUsername()+",\n" + + " \"odl-sal-netconf-connector-cfg:password\":"+connectionDetails.getPassword()+",\n" + + " \"tcp-only\":\"false\",\n" + + " \"odl-sal-netconf-connector-cfg:event-executor\":\n" + + " {\n" + + " \"type\":\"netty:netty-event-executor\",\n" + + " \"name\":\"global-event-executor\"\n" + + " },\n" + + " \"odl-sal-netconf-connector-cfg:binding-registry\":\n" + + " {\n" + + " \"type\":\"opendaylight-md-sal-binding:binding-broker-osgi-registry\",\n" + + " \"name\":\"binding-osgi-broker\"\n" + + " },\n" + + " \"odl-sal-netconf-connector-cfg:dom-registry\":\n" + + " {\n" + + " \"type\":\"opendaylight-md-sal-dom:dom-broker-osgi-registry\",\n" + + " \"name\":\"dom-broker\"\n" + + " },\n" + + " \"odl-sal-netconf-connector-cfg:client-dispatcher\":\n" + + " {\n" + + " \"type\":\"odl-netconf-cfg:netconf-client-dispatcher\",\n" + + " \"name\":\"global-netconf-dispatcher\"\n" + + " },\n" + + " \"odl-sal-netconf-connector-cfg:processing-executor\":\n" + + " {\n" + + " \"type\":\"threadpool:threadpool\",\n" + + " \"name\":\"global-netconf-processing-executor\"\n" + + " }\n" + + " }\n" + + "}"; + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/util/Constants.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/util/Constants.java new file mode 100644 index 000000000..e8b8e9378 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/onap/appc/adapter/netconf/util/Constants.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.util; + +public class Constants { + + public static final String CONFIGURE_PATH = "/restconf/config/opendaylight-inventory:nodes/node/"; + public static final String CONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules"; + public static final String CHECK_CONNECTION_PATH = "/restconf/operational/opendaylight-inventory:nodes/node/"; + public static final String DISCONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules/module/odl-sal-netconf-connector-cfg:sal-netconf-connector/"; + + public static final String CONTROLLER_IP = "127.0.0.1"; + public static final int CONTROLLER_PORT = 8181; + public static final String PROTOCOL = "http"; + + // tables and fields + public static final String NETCONF_SCHEMA = "sdnctl"; + public static final String DEVICE_AUTHENTICATION_TABLE_NAME = "DEVICE_AUTHENTICATION"; + public static final String CONFIGFILES_TABLE_NAME = "CONFIGFILES"; + public static final String DEVICE_INTERFACE_LOG_TABLE_NAME = "DEVICE_INTERFACE_LOG"; + public static final String FILE_CONTENT_TABLE_FIELD_NAME = "FILE_CONTENT"; + public static final String FILE_NAME_TABLE_FIELD_NAME = "FILE_NAME"; + public static final String USER_NAME_TABLE_FIELD_NAME = "USER_NAME"; + public static final String PASSWORD_TABLE_FIELD_NAME = "PASSWORD"; + public static final String VM_HOST_TABLE_FIELD_NAME = "VM_HOST"; + public static final String VM_NAME_TABLE_FIELD_NAME = "VM_NAME"; + public static final String PORT_NUMBER_TABLE_FIELD_NAME = "PORT_NUMBER"; + public static final String VNF_TYPE_TABLE_FIELD_NAME = "VNF_TYPE"; + public static final String SERVICE_INSTANCE_ID_FIELD_NAME = "SERVICE_INSTANCE_ID"; + public static final String REQUEST_ID_FIELD_NAME = "REQUEST_ID"; + public static final String CREATION_DATE_FIELD_NAME = "CREATION_DATE"; + public static final String LOG_FIELD_NAME = "LOG"; + + // input fields names + public static final String VNF_TYPE_FIELD_NAME = "org.onap.appc.vftype"; + public static final String TARGET_VNF_TYPE = "target-vnf-type"; + public static final String FILE_CONTENT_FIELD_NAME = "file-content"; + public static final String CONNECTION_DETAILS_FIELD_NAME = "connection-details"; + public static final String CONFIGURATION_FILE_FIELD_NAME = "configuration-file-name"; + public static final String VNF_HOST_IP_ADDRESS_FIELD_NAME = "vnf-host-ip-address"; + public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; + public static final String RESOURCEKEY = "resourceKey"; + public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; + public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/AppcNetconfAdapterActivator.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/AppcNetconfAdapterActivator.java deleted file mode 100644 index bae220d13..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/AppcNetconfAdapterActivator.java +++ /dev/null @@ -1,139 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - -import org.onap.appc.adapter.netconf.internal.NetconfDataAccessServiceImpl; -import org.onap.ccsdk.sli.core.dblib.DbLibService; -import org.onap.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.ServiceReference; -import org.osgi.framework.ServiceRegistration; - -public class AppcNetconfAdapterActivator implements BundleActivator { - - /** - * The bundle registration - */ - private ServiceRegistration registration = null; - private ServiceRegistration reporterRegistration = null; - private ServiceRegistration factoryRegistration = null; - private ServiceRegistration dbRegistration = null; - - /** - * The reference to the actual implementation object that implements the services - */ - private NetconfClientFactory clientFactory; - private NetconfDataAccessService DAService; - - /** - * The logger to be used - */ - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AppcNetconfAdapterActivator.class); - - /** - * 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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @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 { - if (registration == null) { - clientFactory = new NetconfClientFactory(); - factoryRegistration = context.registerService(NetconfClientFactory.class, clientFactory, null); - - DAService = new NetconfDataAccessServiceImpl(); - //set dblib service - DbLibService dblibSvc = null; - ServiceReference sref = context.getServiceReference(DbLibService.class.getName()); - try{ - dblibSvc = (DbLibService)context.getService(sref); - }catch(Exception e){ - logger.error(e.getMessage()); - } - DAService.setDbLibService(dblibSvc); - /////////////////////////////////// - factoryRegistration = context.registerService(NetconfDataAccessService.class, DAService, null); - } - - logger.info(Msg.COMPONENT_INITIALIZED, "NETCONF 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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @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 { - if (registration != null) { - registration.unregister(); - registration = null; - } - if (reporterRegistration != null) { - reporterRegistration.unregister(); - reporterRegistration = null; - } - - if (null != factoryRegistration) { - factoryRegistration.unregister(); - factoryRegistration = null; - } - - if (dbRegistration != null) { - dbRegistration.unregister(); - dbRegistration = null; - } - } - - public String getName() { - return "APPC NETCONF adapter"; - } - -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/ConnectionDetails.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/ConnectionDetails.java deleted file mode 100644 index 7536f9655..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/ConnectionDetails.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - - -public class ConnectionDetails { - - private String host; - private int port; - private String username; - private String password; - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/MockOperationalStateValidatorImpl.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/MockOperationalStateValidatorImpl.java deleted file mode 100644 index 079ae76a4..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/MockOperationalStateValidatorImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - -import org.onap.appc.exceptions.APPCException; - - -public class MockOperationalStateValidatorImpl implements OperationalStateValidator { - @Override - public VnfType getVnfType() { - return VnfType.MOCK; - } - - @Override - public String getConfigurationFileName() { - String configFileName = OperationalStateValidatorFactory.configuration.getProperty(this.getClass().getCanonicalName() + CONFIG_FILE_PROPERTY_SUFFIX); - return configFileName; - } - - @Override - public void validateResponse(String response) throws APPCException { - if(response != null && response.toUpperCase().contains("INVALID")){ - throw new APPCException("INVALID"); - } - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClient.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClient.java deleted file mode 100644 index eaed60fc0..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClient.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - -import org.onap.appc.exceptions.APPCException; - - - -public interface NetconfClient { - - /** - * Open connection to netconf device. - * - * @param connectionDetails object providing details required for netconf connection - */ - void connect(NetconfConnectionDetails connectionDetails) throws APPCException; - - /** - * Send Netconf message to device and receive response. - * - * @param message input netconf xml message - * @return output netconf xml message - */ - String exchangeMessage(String message) throws APPCException; - - /** - * send configuration to Netconf server - * - * @param configuration - xml configuration payload - */ - void configure(String configuration) throws APPCException; - - /** - * returns running configuration of Netconf server - */ - String getConfiguration() throws APPCException; - - /** - * Disconnect from netconf device. - */ - void disconnect() throws APPCException; -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClientFactory.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClientFactory.java deleted file mode 100644 index 45c8fb0ed..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClientFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - -import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; -import org.onap.appc.adapter.netconf.odlconnector.NetconfClientRestconfImpl; - - -public class NetconfClientFactory { - - public NetconfClient GetNetconfClient(NetconfClientType type){ - - if(type==NetconfClientType.RESTCONF) { - return new NetconfClientRestconfImpl(); - }else if(type == NetconfClientType.SSH){ - return new NetconfClientJsch(); - } - - return null; - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClientRestconf.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClientRestconf.java deleted file mode 100644 index a23a16797..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClientRestconf.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - -import org.onap.appc.exceptions.APPCException; - - - -public interface NetconfClientRestconf { - - /* - mount device to controller - @param deviceMountPointName - the name of the mounting point in controller - @param payload - json data describing device info - */ - void connect(String deviceMountPointName, String payload) throws APPCException; - - /* - check connection to device - @param deviceMountPointName - the name of the mounting point in controller - */ - boolean checkConnection(String deviceMountPointName) throws APPCException; - - /* - send configuration to Netconf server - @param configuration - xml configuration payload - @param deviceMountPointName - the name of the mounting point in controller - @param moduleName - name of the yang model - @param nodeName - name of the node created in server - */ - void configure(String configuration, String deviceMountPointName, String moduleName, String nodeName) throws APPCException; - - /* - returns configuration of Netconf server - @param deviceMountPointName - the name of the mounting point in controller - @param moduleName - name of the yang model - @param nodeName - name of the node created in server - */ - String getConfiguration(String deviceName, String moduleName, String nodeName) throws APPCException; - - /* - unmount device - @param deviceMountPointName - the name of the mounting point in controller - */ - void disconnect(String deviceMountPointName) throws APPCException; -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClientType.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClientType.java deleted file mode 100644 index bf7512456..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfClientType.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - - -public enum NetconfClientType { - RESTCONF, - SSH -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfConnectionDetails.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfConnectionDetails.java deleted file mode 100644 index e7c0cc44d..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfConnectionDetails.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - -import java.util.List; -import java.util.Properties; - -/** - * Provides details required for connecting to netconf device. - */ -public class NetconfConnectionDetails { - - private String host; - private int port; - private String username; - private String password; - - public static int DEFAULT_PORT = 830; - private List capabilities; - private Properties additionalProperties; - - public NetconfConnectionDetails() { - super(); - setPort(DEFAULT_PORT); - } - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public List getCapabilities() { - return capabilities; - } - - public void setCapabilities(List capabilities) { - this.capabilities = capabilities; - } - - public Properties getAdditionalProperties() { - return additionalProperties; - } - - public void setAdditionalProperties(Properties additionalProperties) { - this.additionalProperties = additionalProperties; - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfDataAccessService.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfDataAccessService.java deleted file mode 100644 index f831541da..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/NetconfDataAccessService.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - -import org.onap.appc.adapter.netconf.exception.DataAccessException; -import org.onap.ccsdk.sli.core.dblib.DbLibService; - - -@SuppressWarnings("JavaDoc") -public interface NetconfDataAccessService { - - /** - * - * @param schema - */ - void setSchema(String schema); - - /** - * - * @param dbLibService - */ - void setDbLibService(DbLibService dbLibService); - - /** - * - * @param xmlID - * @return - * @throws DataAccessException - */ - String retrieveConfigFileName(String xmlID) throws DataAccessException; - - /** - * - * @param vnfType - * @param connectionDetails - * @return - * @throws DataAccessException - */ - boolean retrieveConnectionDetails(String vnfType, ConnectionDetails connectionDetails) throws DataAccessException; - - /** - * - * @param vnfType - * @param connectionDetails - * @return - * @throws DataAccessException - */ - boolean retrieveNetconfConnectionDetails(String vnfType, NetconfConnectionDetails connectionDetails) throws - DataAccessException; - - /** - * - * @param instanceId - * @param requestId - * @param creationDate - * @param logText - * @return - * @throws DataAccessException - */ - boolean logDeviceInteraction(String instanceId, String requestId, String creationDate, String logText) throws - DataAccessException; - -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/OperationalStateValidator.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/OperationalStateValidator.java deleted file mode 100644 index ffa3862e8..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/OperationalStateValidator.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - -import org.onap.appc.exceptions.APPCException; - - -public interface OperationalStateValidator { - public VnfType getVnfType(); - public String getConfigurationFileName(); - public void validateResponse(String response) throws APPCException; - final public static String CONFIG_FILE_PROPERTY_SUFFIX = "-CONFIG_FILE"; -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/OperationalStateValidatorFactory.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/OperationalStateValidatorFactory.java deleted file mode 100644 index 37e96917d..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/OperationalStateValidatorFactory.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - -import org.apache.commons.lang3.NotImplementedException; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; - -public class OperationalStateValidatorFactory { - protected static final Configuration configuration = ConfigurationFactory.getConfiguration(); - - public static OperationalStateValidator getOperationalStateValidator(String vnfType) { - VnfType vnfTypeEnum = null; - try { - vnfTypeEnum = VnfType.getVnfType(vnfType); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Illegal value in vnfType. vnfType="+vnfType,e); - } - return getOperationalStateValidator(vnfTypeEnum); - } - - public static OperationalStateValidator getOperationalStateValidator(VnfType vnfType) { - switch (vnfType) { - case VNF: - case VNF_MOCK: - return new VNFOperationalStateValidatorImpl(); - case MOCK: - return new MockOperationalStateValidatorImpl(); - default: - throw new NotImplementedException("missing implementaion for the given vnfType:" + vnfType.name()); - } - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/VNFOperationalStateValidatorImpl.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/VNFOperationalStateValidatorImpl.java deleted file mode 100644 index 4bb5ab238..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/VNFOperationalStateValidatorImpl.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.exceptions.APPCException; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.*; - -public class VNFOperationalStateValidatorImpl implements OperationalStateValidator { - private static final String OPERATIONAL_STATE_ELEMENT_NAME = "operationalState"; - @Override - public VnfType getVnfType() { - return VnfType.VNF; - } - - @Override - public String getConfigurationFileName() { - String configFileName = OperationalStateValidatorFactory.configuration.getProperty(this.getClass().getCanonicalName() + CONFIG_FILE_PROPERTY_SUFFIX); - configFileName = configFileName == null? "VnfGetOperationalStates" : configFileName; - return configFileName; - } - - @Override - public void validateResponse(String response) throws APPCException { - if(StringUtils.isEmpty(response)) { - throw new APPCException("empty response"); - } - - boolean isValid = false; - String errorMsg = "unexpected response"; - try { - List operationalStateList = getOperationalStateList(response); - if(operationalStateList != null && !operationalStateList.isEmpty()) { - for (Map.Entry stateEntry : operationalStateList) { - if(!((String)stateEntry.getValue()).equalsIgnoreCase("ENABLED")){ - errorMsg = "at least one "+OPERATIONAL_STATE_ELEMENT_NAME+" is not in valid satae. "+operationalStateList.toString(); - isValid = false; - break; - }else{ - isValid =true; - } - } - }else { - errorMsg = "response without any "+OPERATIONAL_STATE_ELEMENT_NAME+" element"; - } - } catch (Exception e ) { - isValid = false; - errorMsg = e.toString(); - } - if(!isValid) throw new APPCException(errorMsg); - } - - private static List getOperationalStateList(String xmlText) throws IOException, ParserConfigurationException, SAXException { - List entryList = null; - if(StringUtils.isNotEmpty(xmlText)) { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - - Document document = builder.parse(new ByteArrayInputStream(xmlText.getBytes("UTF-8"))); - if(document != null) { - Element rootElement = document.getDocumentElement(); - NodeList nodeList = rootElement.getElementsByTagName(OPERATIONAL_STATE_ELEMENT_NAME); - if (nodeList != null && nodeList.getLength() > 0) { - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - String text = node.getTextContent(); - String id = getElementID(node); - entryList = (entryList == null) ? new ArrayList() : entryList; - Map.Entry entry = new AbstractMap.SimpleEntry(id, text); - entryList.add(entry); - } - } - } - } - return entryList; - } - - private static String getElementID(Node node) { - String id = null; - Node parentNode = node.getParentNode(); - if (parentNode != null) { - if (node.getNodeType() == Node.ELEMENT_NODE) { - NodeList nodeList = ((Element) parentNode).getElementsByTagName("id"); - if (nodeList != null && nodeList.getLength() > 0) { - Node idNode = nodeList.item(0); - id = idNode != null ? idNode.getTextContent() : null; - } - }else { - id = parentNode.getNodeValue()+"|"+parentNode.getTextContent(); - } - } - - id = StringUtils.isEmpty(id) ? null : StringUtils.normalizeSpace(id); - id = StringUtils.isBlank(id) ? null : id; - id = id != null ? id : "unknown-id"; - return id; - } - -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/VnfType.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/VnfType.java deleted file mode 100644 index 19edc2fd3..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/VnfType.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf; - -public enum VnfType { - VNF("VNF"), - MOCK("MOCK"), - VNF_MOCK("MOCK"), - ; - - String familyType; - String upperCaseName; - VnfType(String familyType) { - this.familyType = familyType; - this.upperCaseName = name().toUpperCase(); - } - - public VnfType getFamilyType() { - return VnfType.valueOf(familyType); - } - - public String getUpperCaseName() { - return upperCaseName; - } - - public static VnfType getVnfType(String inSensitiveCaseName){ - String localUpperCaseName = inSensitiveCaseName.toUpperCase(); - for(VnfType vnfType : VnfType.values()){ - if(vnfType.getUpperCaseName().equals(localUpperCaseName)){ - return vnfType; - } - } - throw new IllegalArgumentException( - "No enum with upperCaseName for this input value:" + inSensitiveCaseName ); - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/exception/DataAccessException.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/exception/DataAccessException.java deleted file mode 100644 index 0c4964da0..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/exception/DataAccessException.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.exception; - - -public class DataAccessException extends RuntimeException { - - private static final long serialVersionUID = -155423437162622414L; - - public DataAccessException(){ - } - - public DataAccessException(String message){ - super(message); - } - - public DataAccessException(Throwable cause){ - super(cause); - } - - public DataAccessException(String message , Throwable cause){ - super(message , cause); - } - -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/exception/NetconfDAOException.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/exception/NetconfDAOException.java deleted file mode 100644 index 5ff1a331e..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/exception/NetconfDAOException.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.exception; - -public class NetconfDAOException extends RuntimeException { - - private static final long serialVersionUID = -155423437162622414L; - - public NetconfDAOException(){ - } - - public NetconfDAOException(String message){ - super(message); - } - - public NetconfDAOException(Throwable cause){ - super(cause); - } - - public NetconfDAOException(String message , Throwable cause){ - super(message , cause); - } - - -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfAdapter.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfAdapter.java deleted file mode 100644 index 2d8c6f417..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfAdapter.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.internal; - -import org.onap.appc.configuration.ConfigurationFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.concurrent.*; - -/** - * Provides basic methods for exchanging netconf messages. - */ -public class NetconfAdapter { - - private static final Logger LOG = LoggerFactory.getLogger(NetconfAdapter.class); - private static final long MAX_WAITING_TIME = 1800000; - private static ExecutorService executor = Executors.newFixedThreadPool(5); - - // device input stream - private InputStream in; - // device output stream - private OutputStream out; - private long maxWaitingTime = ConfigurationFactory.getConfiguration().getLongProperty("org.onap.appc.netconf.recv.timeout", MAX_WAITING_TIME); - - /** - * Constructor. - * - * @param in InputStream this instance will read netconf messages from - * @param out OutputStream this instance will write netconf messages to - * @throws IOException - */ - public NetconfAdapter(InputStream in, OutputStream out) throws IOException { - this.in = in; - this.out = out; - } - - /** - * Receives netconf message from InputStream and return it's text (without netconf frame characters). - * - * @return text of message received from netconf device - * @throws IOException - */ - public String receiveMessage() throws IOException { - - final NetconfMessage message = new NetconfMessage(); - final byte[] buf = new byte[1024]; - - //int readByte = 1; - // Read data with timeout - Callable readTask = new Callable() { - @Override - public Boolean call() throws Exception { - int c; - while ((c = in.read(buf)) > 0) { - if (c > 0) { - message.append(buf, 0, c); - if (message.isCompleted()) { - break; - } - } - } - - if (c < 0) { - return false; - } - return true; - } - }; - - Future future = executor.submit(readTask); - Boolean status; - try { - status = future.get(maxWaitingTime, TimeUnit.MILLISECONDS); - } catch (Exception e) { - throw new IOException(e); - } - - if (status == false) { - throw new IOException("Failed to read netconf message"); - } - - - String text = message.getText(); - if (text != null) { - text = text.trim(); - } - if (LOG.isDebugEnabled()) { - LOG.debug("Received message from netconf device:\n" + text); - } - return text; - } - - /** - * Sends netconf message with provided text (adds netconf frame characters and sends the message). - * - * @param text text of message to be sent to netconf device - * @throws IOException - */ - public void sendMessage(final String text) throws IOException { - if (LOG.isDebugEnabled()) { - LOG.debug("Sending message to netconf device:\n" + text); - } - out.write(new NetconfMessage(text).getFrame()); - out.flush(); - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfAdapter2.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfAdapter2.java deleted file mode 100644 index 928d77470..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfAdapter2.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.internal; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.*; - -/** - * Provides basic methods for exchanging netconf messages. - */ -public class NetconfAdapter2 { - - private static final Logger LOG = LoggerFactory.getLogger(NetconfAdapter2.class); - - // device input pipe - private final PipedOutputStream pipedOutIn = new PipedOutputStream(); - private PipedInputStream in; - // device output pipe - private final PipedInputStream pipedInOut = new PipedInputStream(); - private PipedOutputStream out; - - /** - * Constructor. - * - * @throws IOException - */ - public NetconfAdapter2() throws IOException { - in = new PipedInputStream(pipedOutIn); - out = new PipedOutputStream(pipedInOut); - } - - /** - * @return InputStream this instance will read netconf messages from. - */ - public InputStream getIn() { - return in; - } - - /** - * @return OutputStream this instance will write netconf messages to. - */ - public OutputStream getOut() { - return out; - } - - /** - * Receives netconf message from InputStream and return it's text (without netconf frame characters). - * - * @return text of message received from netconf device - * @throws IOException - */ - public String receiveMessage() throws IOException { - NetconfMessage message = new NetconfMessage(); - byte[] buf = new byte[1024]; - int c; - while((c = pipedInOut.read(buf)) > 0) { - message.append(buf, 0, c); - if (message.isCompleted()) { - break; - } - } - String text = message.getText(); - if(LOG.isDebugEnabled()) { - LOG.debug("Received message from netconf device:\n" + text); - } - return text; - } - - /** - * Sends netconf message with provided text (adds netconf frame characters and sends the message). - * - * @param text text of message to be sent to netconf device - * @throws IOException - */ - public void sendMessage(final String text) throws IOException { - if(LOG.isDebugEnabled()) { - LOG.debug("Sending message to netconf device:\n" + text); - } - pipedOutIn.write(new NetconfMessage(text).getFrame()); - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfConstMessages.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfConstMessages.java deleted file mode 100644 index c7ad9bc50..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfConstMessages.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.internal; - -public class NetconfConstMessages { - - public static final String CAPABILITIES_START = - "\n" + - "\n" + - " \n"; - - public static final String CAPABILITIES_BASE = - " urn:ietf:params:netconf:base:1.0\n"; - - public static final String CAPABILITIES_END = - " \n" + - ""; - - public static final String GET_RUNNING_CONFIG = - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - - public static final String CLOSE_SESSION = - "\n" + - "\n" + - " \n" + - ""; -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfDataAccessServiceImpl.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfDataAccessServiceImpl.java deleted file mode 100644 index f3cca8597..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfDataAccessServiceImpl.java +++ /dev/null @@ -1,147 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.internal; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.appc.adapter.netconf.ConnectionDetails; -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.NetconfDataAccessService; -import org.onap.appc.adapter.netconf.exception.DataAccessException; -import org.onap.appc.adapter.netconf.util.Constants; -import org.onap.ccsdk.sli.core.dblib.DbLibService; - -import javax.sql.rowset.CachedRowSet; -import java.sql.SQLException; -import java.util.ArrayList; - -public class NetconfDataAccessServiceImpl implements NetconfDataAccessService { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(NetconfDataAccessServiceImpl.class); - - public void setSchema(String schema) { - this.schema = schema; - } - - private String schema; - - public void setDbLibService(DbLibService service) {dbLibService = service;} - - private DbLibService dbLibService; - - @Override - public String retrieveConfigFileName(String xmlID) throws DataAccessException { - String fileContent = ""; - - String queryString = "select " + Constants.FILE_CONTENT_TABLE_FIELD_NAME + " " + - "from " + Constants.CONFIGFILES_TABLE_NAME + " " + - "where " + Constants.FILE_NAME_TABLE_FIELD_NAME + " = ?"; - - ArrayList argList = new ArrayList<>(); - argList.add(xmlID); - - try { - final CachedRowSet data = dbLibService.getData(queryString, argList, schema); - if (data.first()) { - fileContent = data.getString(Constants.FILE_CONTENT_TABLE_FIELD_NAME); - } - } catch (Exception e) { - logger.error("Error Accessing Database " + e); - throw new DataAccessException(e); - } - - return fileContent; - } - - @Override - public boolean retrieveConnectionDetails(String vnfType, ConnectionDetails connectionDetails) throws - DataAccessException { - boolean recordFound = false; - - String queryString = "select " + Constants.USER_NAME_TABLE_FIELD_NAME + "," + - Constants.PASSWORD_TABLE_FIELD_NAME + "," + Constants.PORT_NUMBER_TABLE_FIELD_NAME + " " + - "from " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME + " " + - "where " + Constants.VNF_TYPE_TABLE_FIELD_NAME + " = ?"; - - ArrayList argList = new ArrayList<>(); - argList.add(vnfType); - - try { - final CachedRowSet data = dbLibService.getData(queryString, argList, schema); - if (data.first()) { - connectionDetails.setUsername(data.getString(Constants.USER_NAME_TABLE_FIELD_NAME)); - connectionDetails.setPassword(data.getString(Constants.PASSWORD_TABLE_FIELD_NAME)); - connectionDetails.setPort(data.getInt(Constants.PORT_NUMBER_TABLE_FIELD_NAME)); - recordFound = true; - } - } catch (SQLException e) { - logger.error("Error Accessing Database " + e); - throw new DataAccessException(e); - } - - return recordFound; - } - - @Override - public boolean retrieveNetconfConnectionDetails(String vnfType, NetconfConnectionDetails connectionDetails) - throws DataAccessException { - ConnectionDetails connDetails = new ConnectionDetails(); - if(this.retrieveConnectionDetails(vnfType, connDetails)) - { - connectionDetails.setHost(connDetails.getHost()); - connectionDetails.setPort(connDetails.getPort()); - connectionDetails.setUsername(connDetails.getUsername()); - connectionDetails.setPassword(connDetails.getPassword()); - } - return true; - } - - @Override - public boolean logDeviceInteraction(String instanceId, String requestId, String creationDate, String logText) - throws DataAccessException { - String queryString = "INSERT INTO "+ Constants.DEVICE_INTERFACE_LOG_TABLE_NAME+"("+ - Constants.SERVICE_INSTANCE_ID_FIELD_NAME+","+ - Constants.REQUEST_ID_FIELD_NAME+","+ - Constants.CREATION_DATE_FIELD_NAME+","+ - Constants.LOG_FIELD_NAME+") "; - queryString += "values(?,?,?,?)"; - - ArrayList argList = new ArrayList<>(); - argList.add(instanceId); - argList.add(requestId); - argList.add(creationDate); - argList.add(logText); - - try { - dbLibService.writeData(queryString, argList, schema); - } catch (SQLException e) { - logger.error("Logging Device interaction failed - "+ queryString); - throw new DataAccessException(e); - } - - return true; - } - -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfMessage.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfMessage.java deleted file mode 100644 index 700a51b9f..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/internal/NetconfMessage.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.internal; - -import java.io.ByteArrayOutputStream; - -class NetconfMessage { - - private static final String EOM = "]]>]]>"; - - private String text; - private MessageBuffer buffer = new MessageBuffer(); - private int eomNotch; - - NetconfMessage() { - } - - NetconfMessage(String text) { - if(text == null) { - throw new NullPointerException("Netconf message payload is null"); - } - append(text.getBytes(), 0, text.length()); - if(this.text == null) { - this.text = text; - } - } - - void append(byte[] bytes, int start, int end) { - boolean eomFound = false; - for(int i = start; i < end; i++) { - if(bytes[i] == EOM.charAt(eomNotch)) { - // advance notch - eomNotch++; - } else { - // reset notch - eomNotch = 0; - } - if(eomNotch == EOM.length()) { - // end of message found - eomFound = true; - end = i + 1; - break; - } - } - buffer.write(bytes, start, end); - if(eomFound) { - text = new String(buffer.getBytes(), 0, buffer.size() - EOM.length()); - buffer.reset(); - } - } - - String getText() { - return text; - } - - boolean isCompleted() { - return (text != null); - } - - byte[] getFrame() { - StringBuilder sb = new StringBuilder(); - if(text != null) { - sb.append(text).append("\n"); - } - sb.append(EOM); - return sb.toString().getBytes(); - } - - private class MessageBuffer extends ByteArrayOutputStream { - - byte[] getBytes() { - return buf; - } - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/jsch/JSchLogger.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/jsch/JSchLogger.java deleted file mode 100644 index 37bb3b2f2..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/jsch/JSchLogger.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.jsch; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * JSch logger implementation delegating to logback. - */ -public class JSchLogger implements com.jcraft.jsch.Logger { - - private static final Logger LOG = LoggerFactory.getLogger(JSchLogger.class); - - @Override - public boolean isEnabled(int level) { - return true; - } - - @Override - public void log(int level, String message) { - switch(level) { - case com.jcraft.jsch.Logger.DEBUG: - LOG.debug(message); - break; - - case com.jcraft.jsch.Logger.INFO: - LOG.info(message); - break; - - case com.jcraft.jsch.Logger.WARN: - LOG.warn(message); - break; - - case com.jcraft.jsch.Logger.ERROR: - case com.jcraft.jsch.Logger.FATAL: - LOG.error(message); - break; - } - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/jsch/NetconfClientJsch.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/jsch/NetconfClientJsch.java deleted file mode 100644 index 7b9d7a4ae..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/jsch/NetconfClientJsch.java +++ /dev/null @@ -1,170 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.jsch; - -import com.jcraft.jsch.Channel; -import com.jcraft.jsch.ChannelSubsystem; -import com.jcraft.jsch.JSch; -import com.jcraft.jsch.Session; - -import java.io.IOException; -import java.util.List; -import java.util.Properties; - -import org.onap.appc.adapter.netconf.NetconfClient; -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.internal.NetconfAdapter; -import org.onap.appc.adapter.netconf.internal.NetconfConstMessages; -import org.onap.appc.encryption.EncryptionTool; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.i18n.Msg; -import com.att.eelf.i18n.EELFResourceManager; - -/** - * Implementation of NetconfClient interface based on JCraft jsch library. - */ -public class NetconfClientJsch implements NetconfClient { - - private static final int SESSION_CONNECT_TIMEOUT = 30000; - private static final int CHANNEL_CONNECT_TIMEOUT = 10000; - - private Session session; - private Channel channel; - private NetconfAdapter netconfAdapter; - - - @Override - public void connect(NetconfConnectionDetails connectionDetails) throws APPCException { - String host = connectionDetails.getHost(); - int port = connectionDetails.getPort(); - String username = connectionDetails.getUsername(); - String password = connectionDetails.getPassword(); - try { - JSch.setLogger(new JSchLogger()); - JSch jsch = new JSch(); - session = jsch.getSession(EncryptionTool.getInstance().decrypt(username), host, port); - session.setPassword(EncryptionTool.getInstance().decrypt(password)); - session.setConfig("StrictHostKeyChecking", "no"); - - Properties additionalProps = connectionDetails.getAdditionalProperties(); - if((additionalProps != null) && !additionalProps.isEmpty()) { - session.setConfig(additionalProps); - } - - session.connect(SESSION_CONNECT_TIMEOUT); - session.setTimeout(10000); - try { -// session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!! - channel = session.openChannel("subsystem"); - ((ChannelSubsystem)channel).setSubsystem("netconf"); - netconfAdapter = new NetconfAdapter(channel.getInputStream(), channel.getOutputStream()); - channel.connect(CHANNEL_CONNECT_TIMEOUT); - hello(connectionDetails.getCapabilities()); - } catch(Exception e) { - disconnect(); - throw e; - } - } catch(Exception e) { - String message = EELFResourceManager.format(Msg.CANNOT_ESTABLISH_CONNECTION, host, String.valueOf(port), username); - throw new APPCException(message, e); - } - } - - @Override - public String exchangeMessage(String message) throws APPCException { - try { - netconfAdapter.sendMessage(message); - return netconfAdapter.receiveMessage(); - } catch(IOException e) { - throw new APPCException(e); - } - } - - @Override - public void configure(String configuration) throws APPCException { - try { - isOk(exchangeMessage(configuration)); - } catch(IOException e) { - throw new APPCException(e); - } - } - - @Override - public String getConfiguration() throws APPCException { - return exchangeMessage(NetconfConstMessages.GET_RUNNING_CONFIG); - } - - @Override - public void disconnect() { - try { - if((channel != null) && !channel.isClosed()) { - netconfAdapter.sendMessage(NetconfConstMessages.CLOSE_SESSION); - isOk(netconfAdapter.receiveMessage()); - } - } catch(IOException e) { - throw new RuntimeException("Error closing netconf device", e); - } finally { - netconfAdapter = null; - if(channel != null) { - channel.disconnect(); - channel = null; - } - if(session != null) { - session.disconnect(); - session = null; - } - } - } - - private void hello(List capabilities) throws IOException { - String helloIn = netconfAdapter.receiveMessage(); - if(helloIn == null) { - throw new IOException("Expected hello message, but nothing received error from netconf device"); - } - if(helloIn.contains("")) { - throw new IOException("Expected hello message, but received error from netconf device:\n" + helloIn); - } - StringBuilder sb = new StringBuilder(); - sb.append(NetconfConstMessages.CAPABILITIES_START); - sb.append(NetconfConstMessages.CAPABILITIES_BASE); - if(capabilities != null) { - for(String capability: capabilities) { - sb.append(" ").append(capability).append("\n"); - } - } - sb.append(NetconfConstMessages.CAPABILITIES_END); - String helloOut = sb.toString(); - netconfAdapter.sendMessage(helloOut); - } - - private void isOk(String response) throws IOException { - if(response == null) { - throw new IOException("No response from netconf device"); - } - if(!response.contains("")) { - throw new IOException("Error response from netconf device: \n" + response); - } - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/odlconnector/NetconfClientRestconfImpl.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/odlconnector/NetconfClientRestconfImpl.java deleted file mode 100644 index bc89551a8..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/odlconnector/NetconfClientRestconfImpl.java +++ /dev/null @@ -1,236 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.odlconnector; - -import org.apache.http.HttpStatus; -import org.onap.appc.adapter.netconf.NetconfClient; -import org.onap.appc.adapter.netconf.NetconfClientRestconf; -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.util.Constants; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.util.httpClient; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.Properties; - -public class NetconfClientRestconfImpl implements NetconfClient, NetconfClientRestconf { - - private EELFLogger logger = EELFManager.getInstance().getLogger(NetconfClientRestconfImpl.class); - - private NetconfConnectionDetails connectionDetails; - - //constructor - public NetconfClientRestconfImpl(){ - } - - //restconf client impl - - @SuppressWarnings("deprecation") - @Override - public void configure(String configuration, String deviceMountPointName, String moduleName, String nodeName) throws APPCException { - - logger.info("Configuring device "+deviceMountPointName+" with configuration "+configuration); - - int httpCode = httpClient.putMethod(Constants.PROTOCOL,Constants.CONTROLLER_IP,Constants.CONTROLLER_PORT,getModuleConfigurePath(deviceMountPointName, moduleName, nodeName),configuration,"application/json"); - - if (httpCode != HttpStatus.SC_OK) { - logger.error("Configuration request failed. throwing Exception !"); - throw new APPCException("Error configuring node :"+nodeName + ", of Module :" + moduleName + ", in device :" + deviceMountPointName); - } - } - - @Override - public void connect(String deviceMountPointName, String payload) throws APPCException{ - - logger.info("Connecting device "+deviceMountPointName); - - int httpCode = httpClient.postMethod(Constants.PROTOCOL,Constants.CONTROLLER_IP,Constants.CONTROLLER_PORT,getConnectPath(),payload,"application/json"); - - if(httpCode != HttpStatus.SC_NO_CONTENT){ - logger.error("Connect request failed with code "+httpCode+". throwing Exception !"); - throw new APPCException("Error connecting device :" + deviceMountPointName); - } - } - - @Override - public boolean checkConnection(String deviceMountPointName) throws APPCException { - logger.info("Checking device "+deviceMountPointName+" connectivity"); - - String result = httpClient.getMethod(Constants.PROTOCOL,Constants.CONTROLLER_IP,Constants.CONTROLLER_PORT,getCheckConnectivityPath(deviceMountPointName),"application/json"); - - return result != null; - } - - @Override - public void disconnect(String deviceMountPointName) throws APPCException { - logger.info("Disconnecting "+deviceMountPointName); - - int httpCode = httpClient.deleteMethod(Constants.PROTOCOL,Constants.CONTROLLER_IP,Constants.CONTROLLER_PORT,getDisconnectPath(deviceMountPointName),"application/json"); - - if(httpCode != HttpStatus.SC_OK){ - logger.error("Disconnection of device "+deviceMountPointName+" failed!"); - throw new APPCException("Disconnection of device "+deviceMountPointName+" failed!"); - } - } - - @Override - public String getConfiguration(String deviceMountPointName, String moduleName, String nodeName) throws APPCException{ - logger.info("Getting configuration of device "+deviceMountPointName); - - String result = httpClient.getMethod(Constants.PROTOCOL,Constants.CONTROLLER_IP,Constants.CONTROLLER_PORT,getModuleConfigurePath(deviceMountPointName, moduleName, nodeName),"application/json"); - - if (result == null) { - logger.error("Configuration request failed. throwing Exception !"); - throw new APPCException("Error getting configuration of node :"+nodeName + ", of Module :" + moduleName + ", in device :" + deviceMountPointName); - } - - return result; - } - - //netconf client impl - - @Override - public void connect(NetconfConnectionDetails connectionDetails) throws APPCException { - if(connectionDetails == null){ - throw new APPCException("Invalid connection details - null value"); - } - this.connectionDetails = connectionDetails; - this.connect(connectionDetails.getHost(),getPayload()); - } - - @Override - public String exchangeMessage(String message) throws APPCException { - // TODO implement - return null; - } - - @Override - public void configure(String configuration) throws APPCException { - if(connectionDetails == null){ - throw new APPCException("Invalid connection details - null value"); - } - - Properties props = connectionDetails.getAdditionalProperties(); - if(props == null || !props.containsKey("module.name") || !props.containsKey("node.name")){ - throw new APPCException("Invalid properties!"); - } - - String moduleName = props.getProperty("module.name"); - String nodeName = props.getProperty("node.name"); - String deviceMountPointName = connectionDetails.getHost(); - - int httpCode = httpClient.putMethod(Constants.PROTOCOL,Constants.CONTROLLER_IP,Constants.CONTROLLER_PORT,getModuleConfigurePath(deviceMountPointName, moduleName, nodeName),configuration,"application/xml"); - - if (httpCode != HttpStatus.SC_OK) { - logger.error("Configuration request failed. throwing Exception !"); - throw new APPCException("Error configuring node :"+nodeName + ", of Module :" + moduleName + ", in device :" + deviceMountPointName); - } - } - - @Override - public String getConfiguration() throws APPCException { - if(connectionDetails == null){ - throw new APPCException("Invalid connection details - null value"); - } - - Properties props = connectionDetails.getAdditionalProperties(); - if(props == null || !props.containsKey("module.name") || !props.containsKey("node.name")){ - throw new APPCException("Invalid properties!"); - } - - return this.getConfiguration(connectionDetails.getHost(),props.getProperty("module.name"),props.getProperty("node.name")); - } - - @Override - public void disconnect() throws APPCException { - if(connectionDetails == null){ - throw new APPCException("Invalid connection details - null value"); - } - this.disconnect(connectionDetails.getHost()); - } - - //private methods - private String getModuleConfigurePath(String deviceMountPointName, String moduleName, String nodeName){ - - - String deviceSpecificPath = deviceMountPointName + "/yang-ext:mount/" + moduleName + ":" + nodeName; - - return Constants.CONFIGURE_PATH + deviceSpecificPath; - } - - private String getConnectPath(){ - - return Constants.CONNECT_PATH; - } - - private String getCheckConnectivityPath(String deviceMountPointName) { - return Constants.CHECK_CONNECTION_PATH + deviceMountPointName; - } - - private String getDisconnectPath(String deviceMountPointName) { - return Constants.DISCONNECT_PATH + deviceMountPointName; - } - - private String getPayload() { - return "{\n" + - " \"config:module\":\n" + - " {\n" + - " \"type\":\"odl-sal-netconf-connector-cfg:sal-netconf-connector\",\n" + - " \"netconf-northbound-ssh\\odl-sal-netconf-connector-cfg:name\":"+connectionDetails.getHost()+",\n" + - " \"odl-sal-netconf-connector-cfg:address\":"+connectionDetails.getHost()+",\n" + - " \"odl-sal-netconf-connector-cfg:port\":"+connectionDetails.getPort()+",\n" + - " \"odl-sal-netconf-connector-cfg:username\":"+connectionDetails.getUsername()+",\n" + - " \"odl-sal-netconf-connector-cfg:password\":"+connectionDetails.getPassword()+",\n" + - " \"tcp-only\":\"false\",\n" + - " \"odl-sal-netconf-connector-cfg:event-executor\":\n" + - " {\n" + - " \"type\":\"netty:netty-event-executor\",\n" + - " \"name\":\"global-event-executor\"\n" + - " },\n" + - " \"odl-sal-netconf-connector-cfg:binding-registry\":\n" + - " {\n" + - " \"type\":\"opendaylight-md-sal-binding:binding-broker-osgi-registry\",\n" + - " \"name\":\"binding-osgi-broker\"\n" + - " },\n" + - " \"odl-sal-netconf-connector-cfg:dom-registry\":\n" + - " {\n" + - " \"type\":\"opendaylight-md-sal-dom:dom-broker-osgi-registry\",\n" + - " \"name\":\"dom-broker\"\n" + - " },\n" + - " \"odl-sal-netconf-connector-cfg:client-dispatcher\":\n" + - " {\n" + - " \"type\":\"odl-netconf-cfg:netconf-client-dispatcher\",\n" + - " \"name\":\"global-netconf-dispatcher\"\n" + - " },\n" + - " \"odl-sal-netconf-connector-cfg:processing-executor\":\n" + - " {\n" + - " \"type\":\"threadpool:threadpool\",\n" + - " \"name\":\"global-netconf-processing-executor\"\n" + - " }\n" + - " }\n" + - "}"; - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/util/Constants.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/util/Constants.java deleted file mode 100644 index e8b8e9378..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/java/org/openecomp/appc/adapter/netconf/util/Constants.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.util; - -public class Constants { - - public static final String CONFIGURE_PATH = "/restconf/config/opendaylight-inventory:nodes/node/"; - public static final String CONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules"; - public static final String CHECK_CONNECTION_PATH = "/restconf/operational/opendaylight-inventory:nodes/node/"; - public static final String DISCONNECT_PATH = "/restconf/config/opendaylight-inventory:nodes/node/controller-config/yang-ext:mount/config:modules/module/odl-sal-netconf-connector-cfg:sal-netconf-connector/"; - - public static final String CONTROLLER_IP = "127.0.0.1"; - public static final int CONTROLLER_PORT = 8181; - public static final String PROTOCOL = "http"; - - // tables and fields - public static final String NETCONF_SCHEMA = "sdnctl"; - public static final String DEVICE_AUTHENTICATION_TABLE_NAME = "DEVICE_AUTHENTICATION"; - public static final String CONFIGFILES_TABLE_NAME = "CONFIGFILES"; - public static final String DEVICE_INTERFACE_LOG_TABLE_NAME = "DEVICE_INTERFACE_LOG"; - public static final String FILE_CONTENT_TABLE_FIELD_NAME = "FILE_CONTENT"; - public static final String FILE_NAME_TABLE_FIELD_NAME = "FILE_NAME"; - public static final String USER_NAME_TABLE_FIELD_NAME = "USER_NAME"; - public static final String PASSWORD_TABLE_FIELD_NAME = "PASSWORD"; - public static final String VM_HOST_TABLE_FIELD_NAME = "VM_HOST"; - public static final String VM_NAME_TABLE_FIELD_NAME = "VM_NAME"; - public static final String PORT_NUMBER_TABLE_FIELD_NAME = "PORT_NUMBER"; - public static final String VNF_TYPE_TABLE_FIELD_NAME = "VNF_TYPE"; - public static final String SERVICE_INSTANCE_ID_FIELD_NAME = "SERVICE_INSTANCE_ID"; - public static final String REQUEST_ID_FIELD_NAME = "REQUEST_ID"; - public static final String CREATION_DATE_FIELD_NAME = "CREATION_DATE"; - public static final String LOG_FIELD_NAME = "LOG"; - - // input fields names - public static final String VNF_TYPE_FIELD_NAME = "org.onap.appc.vftype"; - public static final String TARGET_VNF_TYPE = "target-vnf-type"; - public static final String FILE_CONTENT_FIELD_NAME = "file-content"; - public static final String CONNECTION_DETAILS_FIELD_NAME = "connection-details"; - public static final String CONFIGURATION_FILE_FIELD_NAME = "configuration-file-name"; - public static final String VNF_HOST_IP_ADDRESS_FIELD_NAME = "vnf-host-ip-address"; - public static final String DG_ERROR_FIELD_NAME = "org.onap.appc.dg.error"; - public static final String RESOURCEKEY = "resourceKey"; - public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; - public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; - -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/resources/org/onap/appc/default.properties b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..5e4516a3b --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,44 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +org.onap.appc.netconf.db.jdbc.driver=netconfctl +org.onap.appc.netconf.db.url.netconfctl=jdbc:mysql://127.0.0.1:3306/test +org.onap.appc.netconf.db.user.netconfctl=test +org.onap.appc.netconf.db.pass.netconfctl=123456 +org.onap.appc.netconf.recv.timeout=1800000 + +### ### +### Properties commented out below provided in appc.properties ### +### ### +#event.pool.members=:3904 +event.topic.write=APPC-TEST1 +event.client.key=VIlbtVl6YLhNUrtU +event.client.secret=64AG2hF4pYeG2pq7CT6XwUOT +#restconf.user= +#restconf.pass= + +org.onap.appc.adapter.netconf.VNFOperationalStateValidatorImpl-CONFIG_FILE=VnfGetOperationalStates diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 5e4516a3b..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,44 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -org.onap.appc.netconf.db.jdbc.driver=netconfctl -org.onap.appc.netconf.db.url.netconfctl=jdbc:mysql://127.0.0.1:3306/test -org.onap.appc.netconf.db.user.netconfctl=test -org.onap.appc.netconf.db.pass.netconfctl=123456 -org.onap.appc.netconf.recv.timeout=1800000 - -### ### -### Properties commented out below provided in appc.properties ### -### ### -#event.pool.members=:3904 -event.topic.write=APPC-TEST1 -event.client.key=VIlbtVl6YLhNUrtU -event.client.secret=64AG2hF4pYeG2pq7CT6XwUOT -#restconf.user= -#restconf.pass= - -org.onap.appc.adapter.netconf.VNFOperationalStateValidatorImpl-CONFIG_FILE=VnfGetOperationalStates diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/internal/TestNetconfAdapter.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/internal/TestNetconfAdapter.java new file mode 100644 index 000000000..cb20cbdb5 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/internal/TestNetconfAdapter.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.internal; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.adapter.netconf.internal.NetconfAdapter; + +import java.io.IOException; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; + +public class TestNetconfAdapter { + + private static final String EOM = "]]>]]>"; + + @Test + public void testReceiveMessage() throws IOException { + PipedOutputStream pos = new PipedOutputStream(); + PipedInputStream is = new PipedInputStream(pos); + + PipedInputStream pis = new PipedInputStream(); + PipedOutputStream os = new PipedOutputStream(pis); + + NetconfAdapter netconfAdapter = new NetconfAdapter(is, os); + + String request = "Hello, netconf!"; + pos.write(request.getBytes()); + pos.write(EOM.getBytes()); + String response = netconfAdapter.receiveMessage(); + Assert.assertNotNull(response); + Assert.assertEquals(request, response.trim()); + } + + @Test + public void testSendMessage() throws IOException { + PipedOutputStream pos = new PipedOutputStream(); + PipedInputStream is = new PipedInputStream(pos); + + PipedInputStream pis = new PipedInputStream(); + PipedOutputStream os = new PipedOutputStream(pis); + + NetconfAdapter netconfAdapter = new NetconfAdapter(is, os); + + String request = "Hello, netconf!"; + netconfAdapter.sendMessage(request); + byte[] bytes = new byte[request.length()+EOM.length()+2]; + int count = pis.read(bytes); + String response = new String(bytes, 0, count); + Assert.assertNotNull(response); + Assert.assertTrue(response.endsWith(EOM)); + response = response.substring(0, response.length() - EOM.length()).trim(); + Assert.assertEquals(request, response); + } + + @Test + public void testSendReceive() throws IOException { + PipedOutputStream os = new PipedOutputStream(); + PipedInputStream is = new PipedInputStream(os); + + NetconfAdapter netconfAdapter = new NetconfAdapter(is, os); + + String request = "Hello, netconf!"; + netconfAdapter.sendMessage(request); + String response = netconfAdapter.receiveMessage(); + Assert.assertNotNull(response); + Assert.assertEquals(request, response.trim()); + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestGetRunningConfig.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestGetRunningConfig.java new file mode 100644 index 000000000..b559bc749 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestGetRunningConfig.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.jsch; + +import java.util.Collections; +import java.util.List; + +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; +import org.onap.appc.exceptions.APPCException; + +public class TestGetRunningConfig { + + private static final String HOST = "192.168.1.2"; + private static final String USER = "test"; + private static final String PSWD = "test123"; + private static final int PORT = 830; + private static final List CAPABILITIES = Collections.singletonList("urn:org:onap:appc:capability:1.1.0"); + + public static void main(String[] args) throws APPCException { + try { + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost(HOST); + connectionDetails.setPort(PORT); + connectionDetails.setUsername(USER); + connectionDetails.setPassword(PSWD); + connectionDetails.setCapabilities(CAPABILITIES); + NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); + netconfClientJsch.connect(connectionDetails); + try { + System.out.println("=> Running get configuration..."); + String configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + } finally { + netconfClientJsch.disconnect(); + } + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestModifyConfig.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestModifyConfig.java new file mode 100644 index 000000000..809625333 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestModifyConfig.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.jsch; + +import java.util.Collections; +import java.util.List; + +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; +import org.onap.appc.exceptions.APPCException; + +public class TestModifyConfig { + + private static final String HOST = "192.168.1.2"; + private static final String USER = "test"; + private static final String PSWD = "test123"; + private static final int PORT = 830; + private static final List CAPABILITIES = Collections.singletonList("urn:org:onap:appc:capability:1.1.0"); + private static final String CONFIG = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " merge\n" + + " \n" + + " \n" + + " 1\n" + + " \n" + + " 1\n" + + " \n" + + " 1\n" + + " \n" + + " example.com\n" + + " 60\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""; + + public static void main(String[] args) throws APPCException { + try { + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost(HOST); + connectionDetails.setPort(PORT); + connectionDetails.setUsername(USER); + connectionDetails.setPassword(PSWD); + connectionDetails.setCapabilities(CAPABILITIES); + NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); + netconfClientJsch.connect(connectionDetails); + try { + System.out.println("=> Running get configuration..."); + String configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + + System.out.println("=> Reconfiguring device..."); + String outMessage = netconfClientJsch.exchangeMessage(CONFIG); + System.out.println("=> Reconfiguration response:\n" + outMessage); + + System.out.println("=> Running get configuration..."); + configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + } finally { + netconfClientJsch.disconnect(); + } + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestModifyConfigMock.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestModifyConfigMock.java new file mode 100644 index 000000000..915721d51 --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestModifyConfigMock.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.jsch; + +import java.util.Collections; +import java.util.List; + +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; +import org.onap.appc.exceptions.APPCException; + +public class TestModifyConfigMock { + + private static final String HOST = "192.168.1.2"; + private static final String USER = "test"; + private static final String PSWD = "test123"; + private static final int PORT = 830; + private static final List CAPABILITIES = Collections.singletonList("urn:org:onap:appc:capability:1.1.0"); + private static final String CONFIG = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " merge\n" + + " \n" + + " \n" + + " 1\n" + + " \n" + + " 1\n" + + " \n" + + " 1\n" + + " \n" + + " example.com\n" + + " 60\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""; + + public static void main(String[] args) throws APPCException { + try { + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost(HOST); + connectionDetails.setPort(PORT); + connectionDetails.setUsername(USER); + connectionDetails.setPassword(PSWD); + connectionDetails.setCapabilities(CAPABILITIES); + NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); + netconfClientJsch.connect(connectionDetails); + try { + System.out.println("=> Running get configuration..."); + String configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + + System.out.println("=> Reconfiguring device..."); + String outMessage = netconfClientJsch.exchangeMessage(CONFIG); + System.out.println("=> Reconfiguration response:\n" + outMessage); + + System.out.println("=> Running get configuration..."); + configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + } finally { + netconfClientJsch.disconnect(); + } + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestModifyConfigRouterMock.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestModifyConfigRouterMock.java new file mode 100644 index 000000000..83e62bc9f --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestModifyConfigRouterMock.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.jsch; + +import java.util.Collections; +import java.util.List; + +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; +import org.onap.appc.exceptions.APPCException; + +public class TestModifyConfigRouterMock { + + private static final String HOST = "10.147.27.50"; // yuma netconf simulator + private static final int PORT = 830; + private static final String USER = "admin"; + private static final String PSWD = "admin"; + private static final List CAPABILITIES = Collections.emptyList(); + private static final String CONFIG = + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " 1\n" + + " \n" + + " 100.100.100.0/24\n" + + " 10\n" + + " \n" + + " \n" + + " \n" + + " 1000\n" + + " 10.10.1.1\n" + + " \n" + + " 2000\n" + + " 10.10.1.2\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + + public static void main(String[] args) throws APPCException { + try { + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost(HOST); + connectionDetails.setPort(PORT); + connectionDetails.setUsername(USER); + connectionDetails.setPassword(PSWD); + connectionDetails.setCapabilities(CAPABILITIES); + NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); + netconfClientJsch.connect(connectionDetails); + try { + System.out.println("=> Running get configuration..."); + String configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + + System.out.println("=> Reconfiguring device..."); + String outMessage = netconfClientJsch.exchangeMessage(CONFIG); + System.out.println("=> Reconfiguration response:\n" + outMessage); + } finally { + netconfClientJsch.disconnect(); + } + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestOperationalStates.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestOperationalStates.java new file mode 100644 index 000000000..263dd5a8f --- /dev/null +++ b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/onap/appc/adapter/netconf/jsch/TestOperationalStates.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.netconf.jsch; + +import java.util.Collections; +import java.util.List; + +import org.onap.appc.adapter.netconf.NetconfConnectionDetails; +import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; +import org.onap.appc.exceptions.APPCException; + +public class TestOperationalStates { + + private static final String HOST = "192.168.1.2"; + private static final String USER = "test"; + private static final String PSWD = "test123"; + private static final int PORT = 830; + private static final List CAPABILITIES = Collections.singletonList("urn:org:onap:appc:capability:1.1.0"); + private static final String GET_OPERATIONAL_STATES = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""; + + public static void main(String[] args) throws APPCException { + try { + NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); + connectionDetails.setHost(HOST); + connectionDetails.setPort(PORT); + connectionDetails.setUsername(USER); + connectionDetails.setPassword(PSWD); + connectionDetails.setCapabilities(CAPABILITIES); + NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); + netconfClientJsch.connect(connectionDetails); + try { + System.out.println("=> Running get configuration..."); + String configuration = netconfClientJsch.getConfiguration(); + System.out.println("=> Configuration:\n" + configuration); + + System.out.println("=> Running get operational states..."); + String outMessage = netconfClientJsch.exchangeMessage(GET_OPERATIONAL_STATES); + System.out.println("=> Operational states:\n" + outMessage); + } finally { + netconfClientJsch.disconnect(); + } + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/internal/TestNetconfAdapter.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/internal/TestNetconfAdapter.java deleted file mode 100644 index cb20cbdb5..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/internal/TestNetconfAdapter.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.internal; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.adapter.netconf.internal.NetconfAdapter; - -import java.io.IOException; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; - -public class TestNetconfAdapter { - - private static final String EOM = "]]>]]>"; - - @Test - public void testReceiveMessage() throws IOException { - PipedOutputStream pos = new PipedOutputStream(); - PipedInputStream is = new PipedInputStream(pos); - - PipedInputStream pis = new PipedInputStream(); - PipedOutputStream os = new PipedOutputStream(pis); - - NetconfAdapter netconfAdapter = new NetconfAdapter(is, os); - - String request = "Hello, netconf!"; - pos.write(request.getBytes()); - pos.write(EOM.getBytes()); - String response = netconfAdapter.receiveMessage(); - Assert.assertNotNull(response); - Assert.assertEquals(request, response.trim()); - } - - @Test - public void testSendMessage() throws IOException { - PipedOutputStream pos = new PipedOutputStream(); - PipedInputStream is = new PipedInputStream(pos); - - PipedInputStream pis = new PipedInputStream(); - PipedOutputStream os = new PipedOutputStream(pis); - - NetconfAdapter netconfAdapter = new NetconfAdapter(is, os); - - String request = "Hello, netconf!"; - netconfAdapter.sendMessage(request); - byte[] bytes = new byte[request.length()+EOM.length()+2]; - int count = pis.read(bytes); - String response = new String(bytes, 0, count); - Assert.assertNotNull(response); - Assert.assertTrue(response.endsWith(EOM)); - response = response.substring(0, response.length() - EOM.length()).trim(); - Assert.assertEquals(request, response); - } - - @Test - public void testSendReceive() throws IOException { - PipedOutputStream os = new PipedOutputStream(); - PipedInputStream is = new PipedInputStream(os); - - NetconfAdapter netconfAdapter = new NetconfAdapter(is, os); - - String request = "Hello, netconf!"; - netconfAdapter.sendMessage(request); - String response = netconfAdapter.receiveMessage(); - Assert.assertNotNull(response); - Assert.assertEquals(request, response.trim()); - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestGetRunningConfig.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestGetRunningConfig.java deleted file mode 100644 index b559bc749..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestGetRunningConfig.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.jsch; - -import java.util.Collections; -import java.util.List; - -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; -import org.onap.appc.exceptions.APPCException; - -public class TestGetRunningConfig { - - private static final String HOST = "192.168.1.2"; - private static final String USER = "test"; - private static final String PSWD = "test123"; - private static final int PORT = 830; - private static final List CAPABILITIES = Collections.singletonList("urn:org:onap:appc:capability:1.1.0"); - - public static void main(String[] args) throws APPCException { - try { - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - connectionDetails.setHost(HOST); - connectionDetails.setPort(PORT); - connectionDetails.setUsername(USER); - connectionDetails.setPassword(PSWD); - connectionDetails.setCapabilities(CAPABILITIES); - NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); - netconfClientJsch.connect(connectionDetails); - try { - System.out.println("=> Running get configuration..."); - String configuration = netconfClientJsch.getConfiguration(); - System.out.println("=> Configuration:\n" + configuration); - } finally { - netconfClientJsch.disconnect(); - } - } catch(Exception e) { - e.printStackTrace(); - } - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestModifyConfig.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestModifyConfig.java deleted file mode 100644 index 809625333..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestModifyConfig.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.jsch; - -import java.util.Collections; -import java.util.List; - -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; -import org.onap.appc.exceptions.APPCException; - -public class TestModifyConfig { - - private static final String HOST = "192.168.1.2"; - private static final String USER = "test"; - private static final String PSWD = "test123"; - private static final int PORT = 830; - private static final List CAPABILITIES = Collections.singletonList("urn:org:onap:appc:capability:1.1.0"); - private static final String CONFIG = - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " merge\n" + - " \n" + - " \n" + - " 1\n" + - " \n" + - " 1\n" + - " \n" + - " 1\n" + - " \n" + - " example.com\n" + - " 60\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - - public static void main(String[] args) throws APPCException { - try { - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - connectionDetails.setHost(HOST); - connectionDetails.setPort(PORT); - connectionDetails.setUsername(USER); - connectionDetails.setPassword(PSWD); - connectionDetails.setCapabilities(CAPABILITIES); - NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); - netconfClientJsch.connect(connectionDetails); - try { - System.out.println("=> Running get configuration..."); - String configuration = netconfClientJsch.getConfiguration(); - System.out.println("=> Configuration:\n" + configuration); - - System.out.println("=> Reconfiguring device..."); - String outMessage = netconfClientJsch.exchangeMessage(CONFIG); - System.out.println("=> Reconfiguration response:\n" + outMessage); - - System.out.println("=> Running get configuration..."); - configuration = netconfClientJsch.getConfiguration(); - System.out.println("=> Configuration:\n" + configuration); - } finally { - netconfClientJsch.disconnect(); - } - } catch(Exception e) { - e.printStackTrace(); - } - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestModifyConfigMock.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestModifyConfigMock.java deleted file mode 100644 index 915721d51..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestModifyConfigMock.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.jsch; - -import java.util.Collections; -import java.util.List; - -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; -import org.onap.appc.exceptions.APPCException; - -public class TestModifyConfigMock { - - private static final String HOST = "192.168.1.2"; - private static final String USER = "test"; - private static final String PSWD = "test123"; - private static final int PORT = 830; - private static final List CAPABILITIES = Collections.singletonList("urn:org:onap:appc:capability:1.1.0"); - private static final String CONFIG = - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " merge\n" + - " \n" + - " \n" + - " 1\n" + - " \n" + - " 1\n" + - " \n" + - " 1\n" + - " \n" + - " example.com\n" + - " 60\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - - public static void main(String[] args) throws APPCException { - try { - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - connectionDetails.setHost(HOST); - connectionDetails.setPort(PORT); - connectionDetails.setUsername(USER); - connectionDetails.setPassword(PSWD); - connectionDetails.setCapabilities(CAPABILITIES); - NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); - netconfClientJsch.connect(connectionDetails); - try { - System.out.println("=> Running get configuration..."); - String configuration = netconfClientJsch.getConfiguration(); - System.out.println("=> Configuration:\n" + configuration); - - System.out.println("=> Reconfiguring device..."); - String outMessage = netconfClientJsch.exchangeMessage(CONFIG); - System.out.println("=> Reconfiguration response:\n" + outMessage); - - System.out.println("=> Running get configuration..."); - configuration = netconfClientJsch.getConfiguration(); - System.out.println("=> Configuration:\n" + configuration); - } finally { - netconfClientJsch.disconnect(); - } - } catch(Exception e) { - e.printStackTrace(); - } - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestModifyConfigRouterMock.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestModifyConfigRouterMock.java deleted file mode 100644 index 83e62bc9f..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestModifyConfigRouterMock.java +++ /dev/null @@ -1,94 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.jsch; - -import java.util.Collections; -import java.util.List; - -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; -import org.onap.appc.exceptions.APPCException; - -public class TestModifyConfigRouterMock { - - private static final String HOST = "10.147.27.50"; // yuma netconf simulator - private static final int PORT = 830; - private static final String USER = "admin"; - private static final String PSWD = "admin"; - private static final List CAPABILITIES = Collections.emptyList(); - private static final String CONFIG = - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " 1\n" + - " \n" + - " 100.100.100.0/24\n" + - " 10\n" + - " \n" + - " \n" + - " \n" + - " 1000\n" + - " 10.10.1.1\n" + - " \n" + - " 2000\n" + - " 10.10.1.2\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n"; - - public static void main(String[] args) throws APPCException { - try { - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - connectionDetails.setHost(HOST); - connectionDetails.setPort(PORT); - connectionDetails.setUsername(USER); - connectionDetails.setPassword(PSWD); - connectionDetails.setCapabilities(CAPABILITIES); - NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); - netconfClientJsch.connect(connectionDetails); - try { - System.out.println("=> Running get configuration..."); - String configuration = netconfClientJsch.getConfiguration(); - System.out.println("=> Configuration:\n" + configuration); - - System.out.println("=> Reconfiguring device..."); - String outMessage = netconfClientJsch.exchangeMessage(CONFIG); - System.out.println("=> Reconfiguration response:\n" + outMessage); - } finally { - netconfClientJsch.disconnect(); - } - } catch(Exception e) { - e.printStackTrace(); - } - } -} diff --git a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestOperationalStates.java b/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestOperationalStates.java deleted file mode 100644 index 263dd5a8f..000000000 --- a/appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/src/test/java/org/openecomp/appc/adapter/netconf/jsch/TestOperationalStates.java +++ /dev/null @@ -1,90 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.netconf.jsch; - -import java.util.Collections; -import java.util.List; - -import org.onap.appc.adapter.netconf.NetconfConnectionDetails; -import org.onap.appc.adapter.netconf.jsch.NetconfClientJsch; -import org.onap.appc.exceptions.APPCException; - -public class TestOperationalStates { - - private static final String HOST = "192.168.1.2"; - private static final String USER = "test"; - private static final String PSWD = "test123"; - private static final int PORT = 830; - private static final List CAPABILITIES = Collections.singletonList("urn:org:onap:appc:capability:1.1.0"); - private static final String GET_OPERATIONAL_STATES = - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - - public static void main(String[] args) throws APPCException { - try { - NetconfConnectionDetails connectionDetails = new NetconfConnectionDetails(); - connectionDetails.setHost(HOST); - connectionDetails.setPort(PORT); - connectionDetails.setUsername(USER); - connectionDetails.setPassword(PSWD); - connectionDetails.setCapabilities(CAPABILITIES); - NetconfClientJsch netconfClientJsch = new NetconfClientJsch(); - netconfClientJsch.connect(connectionDetails); - try { - System.out.println("=> Running get configuration..."); - String configuration = netconfClientJsch.getConfiguration(); - System.out.println("=> Configuration:\n" + configuration); - - System.out.println("=> Running get operational states..."); - String outMessage = netconfClientJsch.exchangeMessage(GET_OPERATIONAL_STATES); - System.out.println("=> Operational states:\n" + outMessage); - } finally { - netconfClientJsch.disconnect(); - } - } catch(Exception e) { - e.printStackTrace(); - } - } -} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RequestFactory.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RequestFactory.java new file mode 100644 index 000000000..685ae13a9 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RequestFactory.java @@ -0,0 +1,60 @@ +/* + * ============LICENSE_START============================================================================================================= + * Copyright (c) 2017 Intel Corp. All rights reserved. + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 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.appc.adapter.rest; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.utils.URIBuilder; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; + +public class RequestFactory { + private final EELFLogger logger = EELFManager.getInstance().getLogger(RequestFactory.class); + + final static Map> map = new HashMap<>(); + + static { + map.put("GET", HttpGet::new); + map.put("POST", HttpPost::new); + map.put("PUT", HttpPut::new); + map.put("DELETE", HttpDelete::new); + } + + public HttpRequestBase getHttpRequest(String method, String tUrl) { + Supplier httpRequestSupplier = map.get(method.toUpperCase()); + URI uri = null; + if (httpRequestSupplier != null ) { + try { + uri = new URIBuilder(tUrl).build(); + } catch (URISyntaxException ex) { + logger.error("URI Syntax Incorrect: " + tUrl, ex); + } + HttpRequestBase httpRequest = httpRequestSupplier.get(); + httpRequest.setURI(uri); + return httpRequest; + + } + throw new IllegalArgumentException("No method named: " + method.toUpperCase()); + } +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestActivator.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestActivator.java new file mode 100644 index 000000000..3e224b923 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestActivator.java @@ -0,0 +1,145 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.rest; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.rest.impl.RestAdapterImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.i18n.Msg; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +/** + * This activator is used to initialize and terminate the connection pool to one or more providers. + *

+ * 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. + *

+ *

+ * 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. + *

+ *

+ * When the bundle is deactivated, the cache is torn down with all contexts being closed. + *

+ */ +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 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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @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(); + if (registration == null) { + 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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @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/onap/appc/adapter/rest/RestAdapter.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestAdapter.java new file mode 100644 index 000000000..8542f105a --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestAdapter.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.rest; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import com.att.cdp.zones.model.Server; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +/** + * This interface defines the operations that the provider adapter exposes. + *

+ * 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. + *

+ */ +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.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"; + + /** + * This method is used to restart an existing virtual machine given the fully qualified URL of the machine. + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to stop the indicated server + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to start the indicated server + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to rebuild the indicated server + *

+ * This method is invoked from a directed graph as an Executor 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: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. 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.
+ *
org.onap.appc.instance.url
+ *
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)
+ *
+ *

+ * + * @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 Server 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 properties, SvcLogicContext context) throws APPCException; + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + */ + String getAdapterName(); + + // Server evacuateServer(Map params, SvcLogicContext ctx) throws APPCException; + + //Server migrateServer(Map params, SvcLogicContext ctx) throws APPCException; + + void commonGet(Map params, SvcLogicContext ctx) ; + + void commonPost(Map params, SvcLogicContext ctx) ; + + void commonPut(Map params, SvcLogicContext ctx) ; + + void commonDelete(Map params, SvcLogicContext ctx) ; + +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestContext.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestContext.java new file mode 100644 index 000000000..a3e6b1db4 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestContext.java @@ -0,0 +1,254 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.adapter.rest.impl; + +import org.onap.appc.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.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. + *

+ * 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. + *

+ * + * @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/onap/appc/adapter/rest/impl/RequestFailedException.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestFailedException.java new file mode 100644 index 000000000..3d3f35985 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestFailedException.java @@ -0,0 +1,247 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.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/onap/appc/adapter/rest/impl/RestAdapterImpl.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RestAdapterImpl.java new file mode 100644 index 000000000..bbb37f4cf --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RestAdapterImpl.java @@ -0,0 +1,244 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.rest.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.json.JSONObject; +import org.onap.appc.Constants; +import org.onap.appc.adapter.rest.RestAdapter; +import org.onap.appc.adapter.rest.RequestFactory; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.Iterator; +import java.util.Map; +import java.util.function.Supplier; + +/** + * This class implements the {@link RestAdapter} interface. This interface + * defines the behaviors that our service provides. + */ +public class RestAdapterImpl implements RestAdapter { + + /** + * The constant for the status code for a failed outcome + */ + @SuppressWarnings("nls") + private static final String OUTCOME_FAILURE = "failure"; + + /** + * The constant for the status code for a successful outcome + */ + @SuppressWarnings("nls") + private static final String OUTCOME_SUCCESS = "success"; + + /** + * The logger to be used + */ + private final EELFLogger logger = EELFManager.getInstance().getLogger(RestAdapterImpl.class); + + /** + * A reference to the adapter configuration object. + */ + private Configuration configuration; + + /** + * This default constructor is used as a work around because the activator + * wasnt getting called + */ + public RestAdapterImpl() { + initialize(); + + } + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + * @see org.onap.appc.adapter.rest.RestAdapter#getAdapterName() + */ + @Override + public String getAdapterName() { + return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME); + } + + public void commonGet(Map params, SvcLogicContext ctx) { + logger.info("Run get method"); + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + HttpGet httpGet = (HttpGet) createHttpRequest("GET", params, rc); + executeHttpRequest(httpGet, rc); + } + + public void commonDelete(Map params, SvcLogicContext ctx) { + logger.info("Run Delete method"); + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + HttpDelete httpDelete = (HttpDelete) createHttpRequest("DELETE", params, rc); + executeHttpRequest(httpDelete, rc); + } + + public void commonPost(Map params, SvcLogicContext ctx) { + logger.info("Run post method"); + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + HttpPost httpPost = (HttpPost) createHttpRequest("POST", params, rc); + executeHttpRequest(httpPost, rc); + } + + public void commonPut(Map params, SvcLogicContext ctx) { + logger.info("Run put method"); + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + HttpPut httpPut = (HttpPut) createHttpRequest("PUT", params, rc); + executeHttpRequest(httpPut, rc); + } + + @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())); + } + + public void executeHttpRequest(HttpRequestBase httpRequest, RequestContext rc){ + try { + HttpClient httpClient = HttpClients.createDefault(); + HttpResponse response = httpClient.execute(httpRequest); + 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()); + } + } + + public HttpRequestBase createHttpRequest(String method, Map params, RequestContext rc){ + HttpRequestBase httpRequest = null; + try { + String tUrl = params.get("org.onap.appc.instance.URI"); + String haveHeader = params.get("org.onap.appc.instance.haveHeader"); + String headers = params.get("org.onap.appc.instance.headers"); + + Supplier requestFactory = RequestFactory::new; + httpRequest = requestFactory.get().getHttpRequest(method, 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); + httpRequest.addHeader(String1, String2); + } + } + if (params.containsKey("org.onap.appc.instance.requestBody")) { + String body = params.get("org.onap.appc.instance.requestBody"); + StringEntity bodyParams = new StringEntity (body,"UTF-8"); + if (method.equals("PUT")){ + HttpPut httpPut = (HttpPut) httpRequest; + httpPut.setEntity(bodyParams); + } + if (method.equals("POST")){ + HttpPost httpPost = (HttpPost) httpRequest; + httpPost.setEntity(bodyParams); + } + } + } catch (Exception ex) { + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); + } + return httpRequest; + } + + + /** + * 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/java/org/openecomp/appc/adapter/rest/RequestFactory.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RequestFactory.java deleted file mode 100644 index 685ae13a9..000000000 --- a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RequestFactory.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * ============LICENSE_START============================================================================================================= - * Copyright (c) 2017 Intel Corp. All rights reserved. - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 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.appc.adapter.rest; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.utils.URIBuilder; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Supplier; - -public class RequestFactory { - private final EELFLogger logger = EELFManager.getInstance().getLogger(RequestFactory.class); - - final static Map> map = new HashMap<>(); - - static { - map.put("GET", HttpGet::new); - map.put("POST", HttpPost::new); - map.put("PUT", HttpPut::new); - map.put("DELETE", HttpDelete::new); - } - - public HttpRequestBase getHttpRequest(String method, String tUrl) { - Supplier httpRequestSupplier = map.get(method.toUpperCase()); - URI uri = null; - if (httpRequestSupplier != null ) { - try { - uri = new URIBuilder(tUrl).build(); - } catch (URISyntaxException ex) { - logger.error("URI Syntax Incorrect: " + tUrl, ex); - } - HttpRequestBase httpRequest = httpRequestSupplier.get(); - httpRequest.setURI(uri); - return httpRequest; - - } - throw new IllegalArgumentException("No method named: " + method.toUpperCase()); - } -} 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 deleted file mode 100644 index 3e224b923..000000000 --- a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RestActivator.java +++ /dev/null @@ -1,145 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.rest; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.rest.impl.RestAdapterImpl; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.i18n.Msg; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -/** - * This activator is used to initialize and terminate the connection pool to one or more providers. - *

- * 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. - *

- *

- * 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. - *

- *

- * When the bundle is deactivated, the cache is torn down with all contexts being closed. - *

- */ -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 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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @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(); - if (registration == null) { - 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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @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 deleted file mode 100644 index 8542f105a..000000000 --- a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/RestAdapter.java +++ /dev/null @@ -1,208 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.rest; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import com.att.cdp.zones.model.Server; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - -/** - * This interface defines the operations that the provider adapter exposes. - *

- * 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. - *

- */ -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.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"; - - /** - * This method is used to restart an existing virtual machine given the fully qualified URL of the machine. - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 properties, SvcLogicContext context) throws APPCException; - - /** - * This method is used to stop the indicated server - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 properties, SvcLogicContext context) throws APPCException; - - /** - * This method is used to start the indicated server - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 properties, SvcLogicContext context) throws APPCException; - - /** - * This method is used to rebuild the indicated server - *

- * This method is invoked from a directed graph as an Executor 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: - *

- *
org.onap.appc.provider.type
- *
The appropriate provider type, such as OpenStackProvider. 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.
- *
org.onap.appc.instance.url
- *
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)
- *
- *

- * - * @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 Server 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 properties, SvcLogicContext context) throws APPCException; - - /** - * Returns the symbolic name of the adapter - * - * @return The adapter name - */ - String getAdapterName(); - - // Server evacuateServer(Map params, SvcLogicContext ctx) throws APPCException; - - //Server migrateServer(Map params, SvcLogicContext ctx) throws APPCException; - - void commonGet(Map params, SvcLogicContext ctx) ; - - void commonPost(Map params, SvcLogicContext ctx) ; - - void commonPut(Map params, SvcLogicContext ctx) ; - - void commonDelete(Map 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 deleted file mode 100644 index a3e6b1db4..000000000 --- a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RequestContext.java +++ /dev/null @@ -1,254 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.adapter.rest.impl; - -import org.onap.appc.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.ccsdk.sli.core.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. - *

- * 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. - *

- * - * @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 deleted file mode 100644 index 3d3f35985..000000000 --- a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RequestFailedException.java +++ /dev/null @@ -1,247 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.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 deleted file mode 100644 index bbb37f4cf..000000000 --- a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/openecomp/appc/adapter/rest/impl/RestAdapterImpl.java +++ /dev/null @@ -1,244 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.rest.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.glassfish.grizzly.http.util.HttpStatus; -import org.json.JSONObject; -import org.onap.appc.Constants; -import org.onap.appc.adapter.rest.RestAdapter; -import org.onap.appc.adapter.rest.RequestFactory; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import java.util.Iterator; -import java.util.Map; -import java.util.function.Supplier; - -/** - * This class implements the {@link RestAdapter} interface. This interface - * defines the behaviors that our service provides. - */ -public class RestAdapterImpl implements RestAdapter { - - /** - * The constant for the status code for a failed outcome - */ - @SuppressWarnings("nls") - private static final String OUTCOME_FAILURE = "failure"; - - /** - * The constant for the status code for a successful outcome - */ - @SuppressWarnings("nls") - private static final String OUTCOME_SUCCESS = "success"; - - /** - * The logger to be used - */ - private final EELFLogger logger = EELFManager.getInstance().getLogger(RestAdapterImpl.class); - - /** - * A reference to the adapter configuration object. - */ - private Configuration configuration; - - /** - * This default constructor is used as a work around because the activator - * wasnt getting called - */ - public RestAdapterImpl() { - initialize(); - - } - - /** - * Returns the symbolic name of the adapter - * - * @return The adapter name - * @see org.onap.appc.adapter.rest.RestAdapter#getAdapterName() - */ - @Override - public String getAdapterName() { - return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME); - } - - public void commonGet(Map params, SvcLogicContext ctx) { - logger.info("Run get method"); - - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - - HttpGet httpGet = (HttpGet) createHttpRequest("GET", params, rc); - executeHttpRequest(httpGet, rc); - } - - public void commonDelete(Map params, SvcLogicContext ctx) { - logger.info("Run Delete method"); - - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - - HttpDelete httpDelete = (HttpDelete) createHttpRequest("DELETE", params, rc); - executeHttpRequest(httpDelete, rc); - } - - public void commonPost(Map params, SvcLogicContext ctx) { - logger.info("Run post method"); - - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - - HttpPost httpPost = (HttpPost) createHttpRequest("POST", params, rc); - executeHttpRequest(httpPost, rc); - } - - public void commonPut(Map params, SvcLogicContext ctx) { - logger.info("Run put method"); - - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - - HttpPut httpPut = (HttpPut) createHttpRequest("PUT", params, rc); - executeHttpRequest(httpPut, rc); - } - - @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())); - } - - public void executeHttpRequest(HttpRequestBase httpRequest, RequestContext rc){ - try { - HttpClient httpClient = HttpClients.createDefault(); - HttpResponse response = httpClient.execute(httpRequest); - 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()); - } - } - - public HttpRequestBase createHttpRequest(String method, Map params, RequestContext rc){ - HttpRequestBase httpRequest = null; - try { - String tUrl = params.get("org.onap.appc.instance.URI"); - String haveHeader = params.get("org.onap.appc.instance.haveHeader"); - String headers = params.get("org.onap.appc.instance.headers"); - - Supplier requestFactory = RequestFactory::new; - httpRequest = requestFactory.get().getHttpRequest(method, 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); - httpRequest.addHeader(String1, String2); - } - } - if (params.containsKey("org.onap.appc.instance.requestBody")) { - String body = params.get("org.onap.appc.instance.requestBody"); - StringEntity bodyParams = new StringEntity (body,"UTF-8"); - if (method.equals("PUT")){ - HttpPut httpPut = (HttpPut) httpRequest; - httpPut.setEntity(bodyParams); - } - if (method.equals("POST")){ - HttpPost httpPost = (HttpPost) httpRequest; - httpPost.setEntity(bodyParams); - } - } - } catch (Exception ex) { - doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); - } - return httpRequest; - } - - - /** - * 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/onap/appc/default.properties b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..c00220dd6 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,96 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============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/openecomp/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 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/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 deleted file mode 100644 index c00220dd6..000000000 --- a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,96 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============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/openecomp/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 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/onap/appc/adapter/rest/impl/TestRestAdapterImpl.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/onap/appc/adapter/rest/impl/TestRestAdapterImpl.java new file mode 100644 index 000000000..65ff0d8f4 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/onap/appc/adapter/rest/impl/TestRestAdapterImpl.java @@ -0,0 +1,140 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Copyright (C) 2017 Intel Corp. + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.rest.impl; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.util.EntityUtils; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import org.onap.appc.exceptions.APPCException; +import com.att.cdp.exceptions.ZoneException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + + +/** + * Test the ProviderAdapter implementation. + */ +public class TestRestAdapterImpl { + 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 testCreateHttpRequestGet() throws IOException, IllegalStateException, IllegalArgumentException, + ZoneException, APPCException { + + Map params = new HashMap<>(); + params.put("org.onap.appc.instance.URI", "http://example.com:8080/about/health"); + params.put("org.onap.appc.instance.haveHeader","false"); + + HttpGet httpGet = ((HttpGet) givenParams(params, "GET")); + + assertEquals("GET", httpGet.getMethod()); + assertEquals("http://example.com:8080/about/health", httpGet.getURI().toURL().toString()); + } + + @Test + public void testCreateHttpRequestPost() throws IOException, IllegalStateException, IllegalArgumentException, + ZoneException, APPCException { + + Map params = new HashMap<>(); + params.put("org.onap.appc.instance.URI", "http://example.com:8081/posttest"); + params.put("org.onap.appc.instance.haveHeader","false"); + params.put("org.onap.appc.instance.requestBody", "{\"name\":\"MyNode\", \"width\":200, \"height\":100}"); + + HttpPost httpPost = ((HttpPost) givenParams(params, "POST")); + + assertEquals("POST", httpPost.getMethod()); + assertEquals("http://example.com:8081/posttest", httpPost.getURI().toURL().toString()); + assertEquals("{\"name\":\"MyNode\", \"width\":200, \"height\":100}", EntityUtils.toString(httpPost.getEntity())); + } + + @Test + public void testCreateHttpRequestPut() throws IOException, IllegalStateException, IllegalArgumentException, + ZoneException, APPCException { + + Map params = new HashMap<>(); + params.put("org.onap.appc.instance.URI", "http://example.com:8081/puttest"); + params.put("org.onap.appc.instance.haveHeader","false"); + params.put("org.onap.appc.instance.requestBody", "{\"name\":\"MyNode2\", \"width\":300, \"height\":300}"); + + HttpPut httpPut = ((HttpPut) givenParams(params, "PUT")); + //Header headers[] = httpPut.getAllHeaders(); + + assertEquals("PUT", httpPut.getMethod()); + assertEquals("http://example.com:8081/puttest", httpPut.getURI().toURL().toString()); + assertEquals("{\"name\":\"MyNode2\", \"width\":300, \"height\":300}", EntityUtils.toString(httpPut.getEntity())); + } + + @Test + public void testCreateHttpRequestDelete() throws IOException, IllegalStateException, IllegalArgumentException, + ZoneException, APPCException { + + Map params = new HashMap<>(); + params.put("org.onap.appc.instance.URI", "http://example.com:8081/deletetest"); + params.put("org.onap.appc.instance.haveHeader","false"); + + HttpDelete httpDelete = ((HttpDelete) givenParams(params, "DELETE")); + + assertEquals("DELETE", httpDelete.getMethod()); + assertEquals("http://example.com:8081/deletetest", httpDelete.getURI().toURL().toString()); + } + + private HttpRequestBase givenParams(Map params, String method){ + SvcLogicContext ctx = new SvcLogicContext(); + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + adapter = new RestAdapterImpl(); + return adapter.createHttpRequest(method, params, rc); + } + + +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java new file mode 100644 index 000000000..7e0154e68 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.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.onap.appc.test.InterceptLogger; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.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 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: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • + *
  • 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
  • + *
+ * @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: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • + *
  • 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
  • + *
+ * @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 getExecMethodNames() { + List 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/onap/appc/test/InterceptLogger.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java new file mode 100644 index 000000000..c67f0cc8b --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java @@ -0,0 +1,455 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.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 events; + + /** + * Create the intercept logger + */ + public InterceptLogger() { + events = new ArrayList(1000); + } + + /** + * @return Returns all intercepted log events + */ + public List 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/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 deleted file mode 100644 index 65ff0d8f4..000000000 --- a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/adapter/rest/impl/TestRestAdapterImpl.java +++ /dev/null @@ -1,140 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * Copyright (C) 2017 Intel Corp. - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.rest.impl; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.util.EntityUtils; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import org.onap.appc.exceptions.APPCException; -import com.att.cdp.exceptions.ZoneException; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - - -/** - * Test the ProviderAdapter implementation. - */ -public class TestRestAdapterImpl { - 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 testCreateHttpRequestGet() throws IOException, IllegalStateException, IllegalArgumentException, - ZoneException, APPCException { - - Map params = new HashMap<>(); - params.put("org.onap.appc.instance.URI", "http://example.com:8080/about/health"); - params.put("org.onap.appc.instance.haveHeader","false"); - - HttpGet httpGet = ((HttpGet) givenParams(params, "GET")); - - assertEquals("GET", httpGet.getMethod()); - assertEquals("http://example.com:8080/about/health", httpGet.getURI().toURL().toString()); - } - - @Test - public void testCreateHttpRequestPost() throws IOException, IllegalStateException, IllegalArgumentException, - ZoneException, APPCException { - - Map params = new HashMap<>(); - params.put("org.onap.appc.instance.URI", "http://example.com:8081/posttest"); - params.put("org.onap.appc.instance.haveHeader","false"); - params.put("org.onap.appc.instance.requestBody", "{\"name\":\"MyNode\", \"width\":200, \"height\":100}"); - - HttpPost httpPost = ((HttpPost) givenParams(params, "POST")); - - assertEquals("POST", httpPost.getMethod()); - assertEquals("http://example.com:8081/posttest", httpPost.getURI().toURL().toString()); - assertEquals("{\"name\":\"MyNode\", \"width\":200, \"height\":100}", EntityUtils.toString(httpPost.getEntity())); - } - - @Test - public void testCreateHttpRequestPut() throws IOException, IllegalStateException, IllegalArgumentException, - ZoneException, APPCException { - - Map params = new HashMap<>(); - params.put("org.onap.appc.instance.URI", "http://example.com:8081/puttest"); - params.put("org.onap.appc.instance.haveHeader","false"); - params.put("org.onap.appc.instance.requestBody", "{\"name\":\"MyNode2\", \"width\":300, \"height\":300}"); - - HttpPut httpPut = ((HttpPut) givenParams(params, "PUT")); - //Header headers[] = httpPut.getAllHeaders(); - - assertEquals("PUT", httpPut.getMethod()); - assertEquals("http://example.com:8081/puttest", httpPut.getURI().toURL().toString()); - assertEquals("{\"name\":\"MyNode2\", \"width\":300, \"height\":300}", EntityUtils.toString(httpPut.getEntity())); - } - - @Test - public void testCreateHttpRequestDelete() throws IOException, IllegalStateException, IllegalArgumentException, - ZoneException, APPCException { - - Map params = new HashMap<>(); - params.put("org.onap.appc.instance.URI", "http://example.com:8081/deletetest"); - params.put("org.onap.appc.instance.haveHeader","false"); - - HttpDelete httpDelete = ((HttpDelete) givenParams(params, "DELETE")); - - assertEquals("DELETE", httpDelete.getMethod()); - assertEquals("http://example.com:8081/deletetest", httpDelete.getURI().toURL().toString()); - } - - private HttpRequestBase givenParams(Map params, String method){ - SvcLogicContext ctx = new SvcLogicContext(); - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - - adapter = new RestAdapterImpl(); - return adapter.createHttpRequest(method, params, rc); - } - - -} 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 deleted file mode 100644 index 7e0154e68..000000000 --- a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.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.onap.appc.test.InterceptLogger; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.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 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: - *
    - *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • - *
  • 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
  • - *
- * @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: - *
    - *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • - *
  • 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
  • - *
- * @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 getExecMethodNames() { - List 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 deleted file mode 100644 index c67f0cc8b..000000000 --- a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java +++ /dev/null @@ -1,455 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.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 events; - - /** - * Create the intercept logger - */ - public InterceptLogger() { - events = new ArrayList(1000); - } - - /** - * @return Returns all intercepted log events - */ - public List 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/onap/appc/default.properties b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..84cd0beb6 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,116 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============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/openecomp/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 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 + 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 deleted file mode 100644 index 84cd0beb6..000000000 --- a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,116 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============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/openecomp/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 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 - diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/RestHealthcheckActivator.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/RestHealthcheckActivator.java new file mode 100644 index 000000000..acd9d013b --- /dev/null +++ b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/RestHealthcheckActivator.java @@ -0,0 +1,116 @@ + +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ +package org.onap.appc.adapter.restHealthcheck; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.restHealthcheck.impl.RestHealthcheckAdapterImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.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; + +public class RestHealthcheckActivator implements BundleActivator { + + /** + * The bundle registration + */ + private ServiceRegistration registration = null; + + /** + * The reference to the actual implementation object that implements the services + */ + private RestHealthcheckAdapter adapter; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestHealthcheckActivator.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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @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()); + + adapter = new RestHealthcheckAdapterImpl(); + if (registration == null) { + registration = context.registerService(RestHealthcheckAdapter.class, adapter, null); + } + + } + + /** + * 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. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @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) { + + registration.unregister(); + registration = null; + + } + } + + public String getName() { + return "APPC Rest Healthcheck adapter"; + } + +} diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/RestHealthcheckAdapter.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/RestHealthcheckAdapter.java new file mode 100644 index 000000000..6413ec415 --- /dev/null +++ b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/RestHealthcheckAdapter.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ +package org.onap.appc.adapter.restHealthcheck; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import com.att.cdp.zones.model.Server; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public interface RestHealthcheckAdapter extends SvcLogicJavaPlugin { + + + static final String PROPERTY_PROVIDER_TYPE = "org.onap.appc.provider.type"; + + + static final String PROPERTY_PROVIDER_NAME = "org.onap.appc.provider.name"; + + static final String PROPERTY_INSTANCE_URL = "org.onap.appc.instance.url"; + + + static final String PROPERTY_IDENTITY_URL = "org.onap.appc.identity.url"; + + String getAdapterName(); + + void checkHealth(Map params, SvcLogicContext ctx) ; + +} diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/impl/RequestContext.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/impl/RequestContext.java new file mode 100644 index 000000000..7114f5524 --- /dev/null +++ b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/impl/RequestContext.java @@ -0,0 +1,249 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.adapter.restHealthcheck.impl; + +import org.onap.appc.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +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 + */ + + + /** + * 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 = 10; + 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 = 10; + 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. + *

+ * 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. + *

+ * + * @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-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/impl/RequestFailedException.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/impl/RequestFailedException.java new file mode 100644 index 000000000..07ed295ef --- /dev/null +++ b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/impl/RequestFailedException.java @@ -0,0 +1,244 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.adapter.restHealthcheck.impl; + +import org.glassfish.grizzly.http.util.HttpStatus; + +import com.att.cdp.zones.model.Server; + + +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-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/impl/RestHealthcheckAdapterImpl.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/impl/RestHealthcheckAdapterImpl.java new file mode 100644 index 000000000..37820a63d --- /dev/null +++ b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/onap/appc/adapter/restHealthcheck/impl/RestHealthcheckAdapterImpl.java @@ -0,0 +1,311 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.restHealthcheck.impl; + +import java.util.Map; +import java.util.Properties; +import org.apache.http.impl.client.CloseableHttpClient; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.restHealthcheck.RestHealthcheckAdapter; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.pool.PoolExtensionException; +import org.onap.appc.util.StructuredPropertyHelper; + + +import com.att.cdp.zones.ImageService; +import com.att.cdp.zones.Provider; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import org.glassfish.grizzly.http.util.HttpStatus; + +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 java.net.InetAddress; + +public class RestHealthcheckAdapterImpl implements RestHealthcheckAdapter { + + /** + * 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"; + + + @SuppressWarnings("nls") + public static final String PING_SERVICE = "pingServer"; + + /** + * The logger to be used + */ + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestHealthcheckAdapterImpl.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 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 providerCache; + + /** + * This default constructor is used as a work around because the activator + * wasnt getting called + */ + public RestHealthcheckAdapterImpl() { + initialize(); + + } + + + public RestHealthcheckAdapterImpl(boolean initialize) { + + if (initialize) { + initialize(); + + } + } + + + public RestHealthcheckAdapterImpl(Properties props) { + initialize(); + + } + + + @Override + public String getAdapterName() { + return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME); + } + + public void checkHealth(Map params, SvcLogicContext ctx) { + logger.info("VNF rest health check"); + String uri=params.get("VNF.URI"); + String endPoint=params.get("VNF.endpoint"); + String tUrl=uri+"/"+endPoint; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + try(CloseableHttpClient httpClient = HttpClients.createDefault()) { + HttpGet httpGet = new HttpGet(tUrl); + HttpResponse response = null; + response = httpClient.execute(httpGet); + int responseCode=response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String responseOutput=EntityUtils.toString(entity); + if(responseCode==200) + { + doSuccess(rc,responseCode,responseOutput); + } + else + { + doHealthCheckFailure(rc,responseCode,responseOutput); + } + } catch (Exception ex) { + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); + } + } + + + + + @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("healthcheck.result.code", "200"); + svcLogic.setAttribute("healthcheck.result.message", status+" "+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 doHealthCheckFailure(RequestContext rc, int code, String message) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + String msg = Integer.toString(code)+" "+message; + svcLogic.setAttribute("healthcheck.result.code", "200"); + svcLogic.setAttribute("healthcheck.result.message", msg); + + } + + + @SuppressWarnings("static-method") + private void doSuccess(RequestContext rc, int code, String message) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + String msg = Integer.toString(code)+" "+message; + svcLogic.setAttribute("healthcheck.result.code", "400"); + svcLogic.setAttribute("healthcheck.result.message", msg); + + } + + + /** + * initialize the provider adapter by building the context cache + */ + private void initialize() { + + + logger.info("init rest health check adapter!!!!!"); + } + +} diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/RestHealthcheckActivator.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/RestHealthcheckActivator.java deleted file mode 100644 index acd9d013b..000000000 --- a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/RestHealthcheckActivator.java +++ /dev/null @@ -1,116 +0,0 @@ - -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ -package org.onap.appc.adapter.restHealthcheck; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.restHealthcheck.impl.RestHealthcheckAdapterImpl; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.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; - -public class RestHealthcheckActivator implements BundleActivator { - - /** - * The bundle registration - */ - private ServiceRegistration registration = null; - - /** - * The reference to the actual implementation object that implements the services - */ - private RestHealthcheckAdapter adapter; - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestHealthcheckActivator.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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @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()); - - adapter = new RestHealthcheckAdapterImpl(); - if (registration == null) { - registration = context.registerService(RestHealthcheckAdapter.class, adapter, null); - } - - } - - /** - * 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. - *

- * This method must complete and return to its caller in a timely manner. - *

- * - * @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) { - - registration.unregister(); - registration = null; - - } - } - - public String getName() { - return "APPC Rest Healthcheck adapter"; - } - -} diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/RestHealthcheckAdapter.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/RestHealthcheckAdapter.java deleted file mode 100644 index 6413ec415..000000000 --- a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/RestHealthcheckAdapter.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ -package org.onap.appc.adapter.restHealthcheck; - -import java.util.Map; - -import org.onap.appc.exceptions.APPCException; -import com.att.cdp.zones.model.Server; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; - - -public interface RestHealthcheckAdapter extends SvcLogicJavaPlugin { - - - static final String PROPERTY_PROVIDER_TYPE = "org.onap.appc.provider.type"; - - - static final String PROPERTY_PROVIDER_NAME = "org.onap.appc.provider.name"; - - static final String PROPERTY_INSTANCE_URL = "org.onap.appc.instance.url"; - - - static final String PROPERTY_IDENTITY_URL = "org.onap.appc.identity.url"; - - String getAdapterName(); - - void checkHealth(Map params, SvcLogicContext ctx) ; - -} diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/impl/RequestContext.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/impl/RequestContext.java deleted file mode 100644 index 7114f5524..000000000 --- a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/impl/RequestContext.java +++ /dev/null @@ -1,249 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.adapter.restHealthcheck.impl; - -import org.onap.appc.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -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 - */ - - - /** - * 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 = 10; - 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 = 10; - 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. - *

- * 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. - *

- * - * @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-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/impl/RequestFailedException.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/impl/RequestFailedException.java deleted file mode 100644 index 07ed295ef..000000000 --- a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/impl/RequestFailedException.java +++ /dev/null @@ -1,244 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.appc.adapter.restHealthcheck.impl; - -import org.glassfish.grizzly.http.util.HttpStatus; - -import com.att.cdp.zones.model.Server; - - -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-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/impl/RestHealthcheckAdapterImpl.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/impl/RestHealthcheckAdapterImpl.java deleted file mode 100644 index 37820a63d..000000000 --- a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/java/org/openecomp/appc/adapter/restHealthcheck/impl/RestHealthcheckAdapterImpl.java +++ /dev/null @@ -1,311 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.restHealthcheck.impl; - -import java.util.Map; -import java.util.Properties; -import org.apache.http.impl.client.CloseableHttpClient; - -import org.onap.appc.Constants; -import org.onap.appc.adapter.restHealthcheck.RestHealthcheckAdapter; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.pool.PoolExtensionException; -import org.onap.appc.util.StructuredPropertyHelper; - - -import com.att.cdp.zones.ImageService; -import com.att.cdp.zones.Provider; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -import org.glassfish.grizzly.http.util.HttpStatus; - -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 java.net.InetAddress; - -public class RestHealthcheckAdapterImpl implements RestHealthcheckAdapter { - - /** - * 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"; - - - @SuppressWarnings("nls") - public static final String PING_SERVICE = "pingServer"; - - /** - * The logger to be used - */ - private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestHealthcheckAdapterImpl.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 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 providerCache; - - /** - * This default constructor is used as a work around because the activator - * wasnt getting called - */ - public RestHealthcheckAdapterImpl() { - initialize(); - - } - - - public RestHealthcheckAdapterImpl(boolean initialize) { - - if (initialize) { - initialize(); - - } - } - - - public RestHealthcheckAdapterImpl(Properties props) { - initialize(); - - } - - - @Override - public String getAdapterName() { - return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME); - } - - public void checkHealth(Map params, SvcLogicContext ctx) { - logger.info("VNF rest health check"); - String uri=params.get("VNF.URI"); - String endPoint=params.get("VNF.endpoint"); - String tUrl=uri+"/"+endPoint; - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - - try(CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpGet httpGet = new HttpGet(tUrl); - HttpResponse response = null; - response = httpClient.execute(httpGet); - int responseCode=response.getStatusLine().getStatusCode(); - HttpEntity entity = response.getEntity(); - String responseOutput=EntityUtils.toString(entity); - if(responseCode==200) - { - doSuccess(rc,responseCode,responseOutput); - } - else - { - doHealthCheckFailure(rc,responseCode,responseOutput); - } - } catch (Exception ex) { - doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); - } - } - - - - - @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("healthcheck.result.code", "200"); - svcLogic.setAttribute("healthcheck.result.message", status+" "+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 doHealthCheckFailure(RequestContext rc, int code, String message) { - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - String msg = Integer.toString(code)+" "+message; - svcLogic.setAttribute("healthcheck.result.code", "200"); - svcLogic.setAttribute("healthcheck.result.message", msg); - - } - - - @SuppressWarnings("static-method") - private void doSuccess(RequestContext rc, int code, String message) { - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - String msg = Integer.toString(code)+" "+message; - svcLogic.setAttribute("healthcheck.result.code", "400"); - svcLogic.setAttribute("healthcheck.result.message", msg); - - } - - - /** - * initialize the provider adapter by building the context cache - */ - private void initialize() { - - - logger.info("init rest health check adapter!!!!!"); - } - -} diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/resources/org/onap/appc/default.properties b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..248aabbd8 --- /dev/null +++ b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,79 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============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/openecomp/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 +# diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 248aabbd8..000000000 --- a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,79 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============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/openecomp/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 -# diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/onap/appc/adapter/restHealthcheck/impl/TestRestHealthcheckAdapterImpl.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/onap/appc/adapter/restHealthcheck/impl/TestRestHealthcheckAdapterImpl.java new file mode 100644 index 000000000..e100a8a01 --- /dev/null +++ b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/onap/appc/adapter/restHealthcheck/impl/TestRestHealthcheckAdapterImpl.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ +package org.onap.appc.adapter.restHealthcheck.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.onap.appc.Constants; +import org.onap.appc.adapter.restHealthcheck.*; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.exceptions.APPCException; +import org.onap.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.onap.ccsdk.sli.core.sli.SvcLogicContext; + + + +public class TestRestHealthcheckAdapterImpl { + + @SuppressWarnings("nls") + private static final String PROVIDER_NAME = "ILAB"; + + @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 RestHealthcheckAdapterImpl adapter; + + + @SuppressWarnings("nls") + @BeforeClass + public static void once() throws NoSuchFieldException, SecurityException, NoSuchMethodException { + + } + + @Before + public void setup() throws IllegalArgumentException, IllegalAccessException { + + adapter = new RestHealthcheckAdapterImpl(); + } + + @Test + public void testCheckHealth() throws IOException, IllegalStateException, IllegalArgumentException, + ZoneException, APPCException { + + Map params = new HashMap<>(); + params.put("VNF.URI", "http://restHalthCheck.test"); + params.put("VNF.endpoint", "health"); + SvcLogicContext svcContext = new SvcLogicContext(); + adapter.checkHealth(params, svcContext); + String statusCode=svcContext.getAttribute("healthcheck.result.code"); + assertEquals("200",statusCode); + } + + + +} diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java new file mode 100644 index 000000000..7e0154e68 --- /dev/null +++ b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/onap/appc/test/ExecutorHarness.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.onap.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.onap.appc.test.InterceptLogger; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.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 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: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • + *
  • 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
  • + *
+ * @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: + *
    + *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • + *
  • 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
  • + *
+ * @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 getExecMethodNames() { + List 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-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java new file mode 100644 index 000000000..c67f0cc8b --- /dev/null +++ b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/onap/appc/test/InterceptLogger.java @@ -0,0 +1,455 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.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 events; + + /** + * Create the intercept logger + */ + public InterceptLogger() { + events = new ArrayList(1000); + } + + /** + * @return Returns all intercepted log events + */ + public List 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-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/adapter/restHealthcheck/impl/TestRestHealthcheckAdapterImpl.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/adapter/restHealthcheck/impl/TestRestHealthcheckAdapterImpl.java deleted file mode 100644 index e100a8a01..000000000 --- a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/adapter/restHealthcheck/impl/TestRestHealthcheckAdapterImpl.java +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ -package org.onap.appc.adapter.restHealthcheck.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.onap.appc.Constants; -import org.onap.appc.adapter.restHealthcheck.*; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.exceptions.APPCException; -import org.onap.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.onap.ccsdk.sli.core.sli.SvcLogicContext; - - - -public class TestRestHealthcheckAdapterImpl { - - @SuppressWarnings("nls") - private static final String PROVIDER_NAME = "ILAB"; - - @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 RestHealthcheckAdapterImpl adapter; - - - @SuppressWarnings("nls") - @BeforeClass - public static void once() throws NoSuchFieldException, SecurityException, NoSuchMethodException { - - } - - @Before - public void setup() throws IllegalArgumentException, IllegalAccessException { - - adapter = new RestHealthcheckAdapterImpl(); - } - - @Test - public void testCheckHealth() throws IOException, IllegalStateException, IllegalArgumentException, - ZoneException, APPCException { - - Map params = new HashMap<>(); - params.put("VNF.URI", "http://restHalthCheck.test"); - params.put("VNF.endpoint", "health"); - SvcLogicContext svcContext = new SvcLogicContext(); - adapter.checkHealth(params, svcContext); - String statusCode=svcContext.getAttribute("healthcheck.result.code"); - assertEquals("200",statusCode); - } - - - -} diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java deleted file mode 100644 index 7e0154e68..000000000 --- a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/test/ExecutorHarness.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - -package org.onap.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.onap.appc.test.InterceptLogger; - -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.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 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: - *
    - *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • - *
  • 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
  • - *
- * @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: - *
    - *
  • invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
  • - *
  • 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
  • - *
- * @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 getExecMethodNames() { - List 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-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java deleted file mode 100644 index c67f0cc8b..000000000 --- a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/test/InterceptLogger.java +++ /dev/null @@ -1,455 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - - - -package org.onap.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 events; - - /** - * Create the intercept logger - */ - public InterceptLogger() { - events = new ArrayList(1000); - } - - /** - * @return Returns all intercepted log events - */ - public List 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-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/resources/org/onap/appc/default.properties b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..881ceab82 --- /dev/null +++ b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,98 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============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/openecomp/appc/data/properties,${user.home},. + +appc.application.name=APPC + +# +# Define the message resource bundle name to be loaded +org.onap.appc.resources=/opt/openecomp/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=/opt/openecomp/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 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. +# + + + +provider1.identity=http://localhost:4000/v2.0 +provider1.tenant1.name=Provider1 +provider1.tenant1.userid=test +provider1.tenant1.password=test + +# After a change to the provider make sure to recheck these values with an api call to proivider1.identity/tokens +test.expected-regions=1 +test.expected-endpoints=1 diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 881ceab82..000000000 --- a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,98 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============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/openecomp/appc/data/properties,${user.home},. - -appc.application.name=APPC - -# -# Define the message resource bundle name to be loaded -org.onap.appc.resources=/opt/openecomp/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=/opt/openecomp/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 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. -# - - - -provider1.identity=http://localhost:4000/v2.0 -provider1.tenant1.name=Provider1 -provider1.tenant1.userid=test -provider1.tenant1.password=test - -# After a change to the provider make sure to recheck these values with an api call to proivider1.identity/tokens -test.expected-regions=1 -test.expected-endpoints=1 diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/Constants.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/Constants.java new file mode 100644 index 000000000..d3ed28a75 --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/Constants.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh; + +public class Constants { + + private Constants(){} + + // tables and fields + public static final String NETCONF_SCHEMA = "sdnctl"; + public static final String SDNCTL_SCHEMA = "sdnctl"; + public static final String DEVICE_AUTHENTICATION_TABLE_NAME = "DEVICE_AUTHENTICATION"; + public static final String CONFIGFILES_TABLE_NAME = "CONFIGFILES"; + public static final String DEVICE_INTERFACE_LOG_TABLE_NAME = "DEVICE_INTERFACE_LOG"; + public static final String FILE_CONTENT_TABLE_FIELD_NAME = "FILE_CONTENT"; + public static final String FILE_NAME_TABLE_FIELD_NAME = "FILE_NAME"; + public static final String USER_NAME_TABLE_FIELD_NAME = "USER_NAME"; + public static final String PASSWORD_TABLE_FIELD_NAME = "PASSWORD"; + public static final String PORT_NUMBER_TABLE_FIELD_NAME = "PORT_NUMBER"; + public static final String VNF_TYPE_TABLE_FIELD_NAME = "VNF_TYPE"; + public static final String SERVICE_INSTANCE_ID_FIELD_NAME = "SERVICE_INSTANCE_ID"; + public static final String REQUEST_ID_FIELD_NAME = "REQUEST_ID"; + public static final String CREATION_DATE_FIELD_NAME = "CREATION_DATE"; + public static final String LOG_FIELD_NAME = "LOG"; + public static final String ASDC_ARTIFACTS_TABLE_NAME = "ASDC_ARTIFACTS"; + + // input fields names + public static final String PAYLOAD = "payload"; + + public static final String CONNECTION_RETRY_DELAY = "org.onap.appc.ssh.connection.retry.delay"; + public static final String CONNECTION_RETRY_COUNT = "org.onap.appc.ssh.connection.retry.count"; + public static final int DEFAULT_CONNECTION_RETRY_DELAY = 60; + public static final int DEFAULT_CONNECTION_RETRY_COUNT = 5; + + public static final int DEFAULT_SSH_COMMAND_RETRY_COUNT = 3; + + public static final int DEFAULT_CHECKACTIVE_RETRY_COUNT = 3; + public static final int DEFAULT_CHECKACTIVE_RETRY_DELAY = 30; + + public static final int DEFAULT_STOP_RETRY_COUNT = 3; + public static final int DEFAULT_STOP_RETRY_DELAY = 30; //seconds + + public static final String PARAM_IN_CONNECTION_DETAILS = "connection-details"; + public static final String PARAM_IN_NODE_NAME = "node-name"; + public static final String PARAM_IN_NODE_STATUS = "node-status"; + public static final String PARAM_IN_VM_URL = "vm-url"; + public static final String SKIP_EXECUTION_INSTALLER_BIN_FILE = "Skip-execution-installer-bin-file"; + public static final String SKIP_DEPLOY = "Skip-deploy"; + public static final String UPGRADE_VERSION = "upgrade-version"; + + //command to get number of UP hosts + public static final String STATE_COMMAND = "/opt/jnetx/skyfall-scp/asp-state.sh | grep -o UP | wc -l"; + //command to get each VNFC status + public static final String VNFC_STATE_COMMAND = "/opt/jnetx/skyfall-scp/asp-state.sh"; + //command to restart node + public static final String RESTART_NODE_COMMAND = "/opt/jnetx/skyfall-scp/asp-stop.sh --restart -f --nodes"; + //command to start node + public static final String START_NODE_COMMAND = "/opt/jnetx/skyfall-scp/asp-start.sh -f --nodes"; + //command to stop node + public static final String STOP_NODE_COMMAND = "/opt/jnetx/skyfall-scp/asp-stop.sh -f --nodes"; + public static final int STATE_COMMAND_RESULT = 18; + //commands to check FE hosts + public static final String FE_STATE_TRUE_TEST_COMMAND = "ssh -t -q fe1 /opt/omni/bin/swmml -e display-platform-status | grep -o TRUE | wc -l"; + public static final int FE_STATE_TRUE_TEST_RESULT = 22; + public static final String FE_STATE_FALSE_TEST_COMMAND = "ssh -t -q fe1 /opt/omni/bin/swmml -e display-platform-status | grep -o FALSE | wc -l"; + public static final int FE_STATE_FALSE_TEST_RESULT = 2; + public static final String FE_OPERATIONAL_TEST_COMMAND = "ssh -t -q fe1 /opt/omni/bin/swmml -e display-platform-status | grep -o 'NOT FULLY OPERATIONAL' | wc -l"; + public static final int FE_OPERATIONAL_TEST_RESULT = 2; + + //smp commands + public static final String SMP_CHECK_ACTIVE_STATE_COMMAND = "cat skyfall-scp/runtime/SCP_SMP_*/smp/log/system.log| grep SSS | tail -1"; + public static final String SMP_STATE_ACTIVE="SMP is active"; + public static final String SMP_STATE_INACTIVE="SMP is not active"; + + //rsync command + public static final String RSYNC_COMMAND = "yes n | /opt/jnetx/skyfall-scp/asp-rsync.sh --check | grep -o 'is active' | wc -l"; + public static final int RSYNC_COMMAND_RESULT = 9; + + public static final String PARAM_IN_TIMEOUT = "timeout"; + public static final String PARAM_IN_FILE_URL = "source-file-url"; + public static final String DOWNLOAD_COMMAND = "wget -N %s"; + + // pre-define VM names + public static final String[] VM_NAMES = {"fe1", "fe2", "be1", "be2", "be3", "be4", "be5", "smp1", "smp2"}; + + public static final String DEFAULT_DISK_SPACE = "10240000"; + public static final String DF_COMMAND_TEMPLATE = "ssh %s df | grep vda1 | grep -v grep | tr -s ' '|cut -d ' ' -f4"; + + public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; + public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; + + + // constants for DG + public static final String CONNECTION_DETAILS_FIELD_NAME = PARAM_IN_CONNECTION_DETAILS; + public static final String VNF_HOST_IP_ADDRESS_FIELD_NAME = "vnf-host-ip-address"; + public static final String VNF_HOST_IP2_ADDRESS_FIELD_NAME = "vnf-host-ip2-address"; + public static final String DG_ERROR_FIELD_NAME = "org.openecom.appc.dg.error"; +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshAdapter.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshAdapter.java new file mode 100644 index 000000000..768a7d317 --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshAdapter.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh; + +/** + * Factory class for creating SshConnection instances. + */ +public interface SshAdapter { + + /** + * Creates instance of SshConnection. + * + * @param host remote host to open SSH connection to + * @param port remote SSH port + * @param username SSH connection user name + * @param password SSH connection password + * @return instance of SshConnection + */ + SshConnection getConnection(String host, int port, String username, String password); +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshConnection.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshConnection.java new file mode 100644 index 000000000..68d98575b --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshConnection.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh; + +import java.io.OutputStream; + +/** + * Provides utility method(s) to call commands on remote host via SSH. + */ +public interface SshConnection { + + /** + * Connect to SSH server. + */ + void connect(); + + /** + * Connect to SSH Server using a retry mechanism + */ + void connectWithRetry(); + + /** + * Disconnect from SSH server. + */ + void disconnect(); + + /** + * Exec remote command over SSH. Return command execution status. + * Command output is written to out or err stream. + * + * @param cmd command to execute + * @param out content of sysout will go to this stream + * @param err content of syserr will go to this stream + * @return command execution status + */ + int execCommand(String cmd, OutputStream out, OutputStream err); + + /** + * Exec remote command over SSH with pseudo-tty. Return command execution status. + * Command output is written to out stream only as pseudo-tty writes to one stream only. + * + * @param cmd command to execute + * @param out content of sysout will go to this stream + * @return command execution status + */ + int execCommandWithPty(String cmd, OutputStream out); + + /** + * Set the command execution timeout + * @param timeout time in milliseconds + */ + void setExecTimeout(long timeout); +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshConnectionDetails.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshConnectionDetails.java new file mode 100644 index 000000000..de1b301bc --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshConnectionDetails.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh; + +/** + * Provides details required for connecting to device. + */ +public class SshConnectionDetails { + + private static int DEFAULT_PORT = 22; + + private String host; + private int port = DEFAULT_PORT; + private String username; + private String password; + + public SshConnectionDetails() { + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshDataAccessException.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshDataAccessException.java new file mode 100644 index 000000000..cb18375d4 --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshDataAccessException.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh; + + + +public class SshDataAccessException extends RuntimeException { + + private static final long serialVersionUID = -155423437162622414L; + + public SshDataAccessException(){ + } + + public SshDataAccessException(String message){ + super(message); + } + + public SshDataAccessException(Throwable cause){ + super(cause); + } + + public SshDataAccessException(String message , Throwable cause){ + super(message , cause); + } + +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshDataAccessService.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshDataAccessService.java new file mode 100644 index 000000000..d932faa78 --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshDataAccessService.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh; + +import org.onap.ccsdk.sli.core.dblib.DbLibService; + + +@SuppressWarnings("JavaDoc") +public interface SshDataAccessService { + + /** + * + * @param schema + */ + void setSchema(String schema); + + /** + *@param dbLibService + */ + void setDbLibService(DbLibService dbLibService); + + /** + * + * @param xmlID + * @return + * @throws SshDataAccessException + */ + String retrieveConfigFileName(String xmlID) throws SshDataAccessException; + + /** + * + * @param vnfType + * @param connectionDetails + * @return + * @throws SshException + */ + boolean retrieveConnectionDetails(String vnfType, SshConnectionDetails connectionDetails) throws SshDataAccessException; + +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshException.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshException.java new file mode 100644 index 000000000..6c906c7f7 --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/onap/appc/adapter/ssh/SshException.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh; + +public class SshException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** + * Constructor with message. + * + * @param message exception message + */ + public SshException(String message) { + super(message); + } + + /** + * Constructor with message and cause exception. + * + * @param message exception message + * @param cause exception cause + */ + public SshException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/Constants.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/Constants.java deleted file mode 100644 index d3ed28a75..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/Constants.java +++ /dev/null @@ -1,120 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh; - -public class Constants { - - private Constants(){} - - // tables and fields - public static final String NETCONF_SCHEMA = "sdnctl"; - public static final String SDNCTL_SCHEMA = "sdnctl"; - public static final String DEVICE_AUTHENTICATION_TABLE_NAME = "DEVICE_AUTHENTICATION"; - public static final String CONFIGFILES_TABLE_NAME = "CONFIGFILES"; - public static final String DEVICE_INTERFACE_LOG_TABLE_NAME = "DEVICE_INTERFACE_LOG"; - public static final String FILE_CONTENT_TABLE_FIELD_NAME = "FILE_CONTENT"; - public static final String FILE_NAME_TABLE_FIELD_NAME = "FILE_NAME"; - public static final String USER_NAME_TABLE_FIELD_NAME = "USER_NAME"; - public static final String PASSWORD_TABLE_FIELD_NAME = "PASSWORD"; - public static final String PORT_NUMBER_TABLE_FIELD_NAME = "PORT_NUMBER"; - public static final String VNF_TYPE_TABLE_FIELD_NAME = "VNF_TYPE"; - public static final String SERVICE_INSTANCE_ID_FIELD_NAME = "SERVICE_INSTANCE_ID"; - public static final String REQUEST_ID_FIELD_NAME = "REQUEST_ID"; - public static final String CREATION_DATE_FIELD_NAME = "CREATION_DATE"; - public static final String LOG_FIELD_NAME = "LOG"; - public static final String ASDC_ARTIFACTS_TABLE_NAME = "ASDC_ARTIFACTS"; - - // input fields names - public static final String PAYLOAD = "payload"; - - public static final String CONNECTION_RETRY_DELAY = "org.onap.appc.ssh.connection.retry.delay"; - public static final String CONNECTION_RETRY_COUNT = "org.onap.appc.ssh.connection.retry.count"; - public static final int DEFAULT_CONNECTION_RETRY_DELAY = 60; - public static final int DEFAULT_CONNECTION_RETRY_COUNT = 5; - - public static final int DEFAULT_SSH_COMMAND_RETRY_COUNT = 3; - - public static final int DEFAULT_CHECKACTIVE_RETRY_COUNT = 3; - public static final int DEFAULT_CHECKACTIVE_RETRY_DELAY = 30; - - public static final int DEFAULT_STOP_RETRY_COUNT = 3; - public static final int DEFAULT_STOP_RETRY_DELAY = 30; //seconds - - public static final String PARAM_IN_CONNECTION_DETAILS = "connection-details"; - public static final String PARAM_IN_NODE_NAME = "node-name"; - public static final String PARAM_IN_NODE_STATUS = "node-status"; - public static final String PARAM_IN_VM_URL = "vm-url"; - public static final String SKIP_EXECUTION_INSTALLER_BIN_FILE = "Skip-execution-installer-bin-file"; - public static final String SKIP_DEPLOY = "Skip-deploy"; - public static final String UPGRADE_VERSION = "upgrade-version"; - - //command to get number of UP hosts - public static final String STATE_COMMAND = "/opt/jnetx/skyfall-scp/asp-state.sh | grep -o UP | wc -l"; - //command to get each VNFC status - public static final String VNFC_STATE_COMMAND = "/opt/jnetx/skyfall-scp/asp-state.sh"; - //command to restart node - public static final String RESTART_NODE_COMMAND = "/opt/jnetx/skyfall-scp/asp-stop.sh --restart -f --nodes"; - //command to start node - public static final String START_NODE_COMMAND = "/opt/jnetx/skyfall-scp/asp-start.sh -f --nodes"; - //command to stop node - public static final String STOP_NODE_COMMAND = "/opt/jnetx/skyfall-scp/asp-stop.sh -f --nodes"; - public static final int STATE_COMMAND_RESULT = 18; - //commands to check FE hosts - public static final String FE_STATE_TRUE_TEST_COMMAND = "ssh -t -q fe1 /opt/omni/bin/swmml -e display-platform-status | grep -o TRUE | wc -l"; - public static final int FE_STATE_TRUE_TEST_RESULT = 22; - public static final String FE_STATE_FALSE_TEST_COMMAND = "ssh -t -q fe1 /opt/omni/bin/swmml -e display-platform-status | grep -o FALSE | wc -l"; - public static final int FE_STATE_FALSE_TEST_RESULT = 2; - public static final String FE_OPERATIONAL_TEST_COMMAND = "ssh -t -q fe1 /opt/omni/bin/swmml -e display-platform-status | grep -o 'NOT FULLY OPERATIONAL' | wc -l"; - public static final int FE_OPERATIONAL_TEST_RESULT = 2; - - //smp commands - public static final String SMP_CHECK_ACTIVE_STATE_COMMAND = "cat skyfall-scp/runtime/SCP_SMP_*/smp/log/system.log| grep SSS | tail -1"; - public static final String SMP_STATE_ACTIVE="SMP is active"; - public static final String SMP_STATE_INACTIVE="SMP is not active"; - - //rsync command - public static final String RSYNC_COMMAND = "yes n | /opt/jnetx/skyfall-scp/asp-rsync.sh --check | grep -o 'is active' | wc -l"; - public static final int RSYNC_COMMAND_RESULT = 9; - - public static final String PARAM_IN_TIMEOUT = "timeout"; - public static final String PARAM_IN_FILE_URL = "source-file-url"; - public static final String DOWNLOAD_COMMAND = "wget -N %s"; - - // pre-define VM names - public static final String[] VM_NAMES = {"fe1", "fe2", "be1", "be2", "be3", "be4", "be5", "smp1", "smp2"}; - - public static final String DEFAULT_DISK_SPACE = "10240000"; - public static final String DF_COMMAND_TEMPLATE = "ssh %s df | grep vda1 | grep -v grep | tr -s ' '|cut -d ' ' -f4"; - - public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message"; - public static final String ATTRIBUTE_ERROR_MESSAGE = "error-message"; - - - // constants for DG - public static final String CONNECTION_DETAILS_FIELD_NAME = PARAM_IN_CONNECTION_DETAILS; - public static final String VNF_HOST_IP_ADDRESS_FIELD_NAME = "vnf-host-ip-address"; - public static final String VNF_HOST_IP2_ADDRESS_FIELD_NAME = "vnf-host-ip2-address"; - public static final String DG_ERROR_FIELD_NAME = "org.openecom.appc.dg.error"; -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshAdapter.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshAdapter.java deleted file mode 100644 index 768a7d317..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshAdapter.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh; - -/** - * Factory class for creating SshConnection instances. - */ -public interface SshAdapter { - - /** - * Creates instance of SshConnection. - * - * @param host remote host to open SSH connection to - * @param port remote SSH port - * @param username SSH connection user name - * @param password SSH connection password - * @return instance of SshConnection - */ - SshConnection getConnection(String host, int port, String username, String password); -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshConnection.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshConnection.java deleted file mode 100644 index 68d98575b..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshConnection.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh; - -import java.io.OutputStream; - -/** - * Provides utility method(s) to call commands on remote host via SSH. - */ -public interface SshConnection { - - /** - * Connect to SSH server. - */ - void connect(); - - /** - * Connect to SSH Server using a retry mechanism - */ - void connectWithRetry(); - - /** - * Disconnect from SSH server. - */ - void disconnect(); - - /** - * Exec remote command over SSH. Return command execution status. - * Command output is written to out or err stream. - * - * @param cmd command to execute - * @param out content of sysout will go to this stream - * @param err content of syserr will go to this stream - * @return command execution status - */ - int execCommand(String cmd, OutputStream out, OutputStream err); - - /** - * Exec remote command over SSH with pseudo-tty. Return command execution status. - * Command output is written to out stream only as pseudo-tty writes to one stream only. - * - * @param cmd command to execute - * @param out content of sysout will go to this stream - * @return command execution status - */ - int execCommandWithPty(String cmd, OutputStream out); - - /** - * Set the command execution timeout - * @param timeout time in milliseconds - */ - void setExecTimeout(long timeout); -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshConnectionDetails.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshConnectionDetails.java deleted file mode 100644 index de1b301bc..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshConnectionDetails.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh; - -/** - * Provides details required for connecting to device. - */ -public class SshConnectionDetails { - - private static int DEFAULT_PORT = 22; - - private String host; - private int port = DEFAULT_PORT; - private String username; - private String password; - - public SshConnectionDetails() { - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshDataAccessException.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshDataAccessException.java deleted file mode 100644 index cb18375d4..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshDataAccessException.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh; - - - -public class SshDataAccessException extends RuntimeException { - - private static final long serialVersionUID = -155423437162622414L; - - public SshDataAccessException(){ - } - - public SshDataAccessException(String message){ - super(message); - } - - public SshDataAccessException(Throwable cause){ - super(cause); - } - - public SshDataAccessException(String message , Throwable cause){ - super(message , cause); - } - -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshDataAccessService.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshDataAccessService.java deleted file mode 100644 index d932faa78..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshDataAccessService.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh; - -import org.onap.ccsdk.sli.core.dblib.DbLibService; - - -@SuppressWarnings("JavaDoc") -public interface SshDataAccessService { - - /** - * - * @param schema - */ - void setSchema(String schema); - - /** - *@param dbLibService - */ - void setDbLibService(DbLibService dbLibService); - - /** - * - * @param xmlID - * @return - * @throws SshDataAccessException - */ - String retrieveConfigFileName(String xmlID) throws SshDataAccessException; - - /** - * - * @param vnfType - * @param connectionDetails - * @return - * @throws SshException - */ - boolean retrieveConnectionDetails(String vnfType, SshConnectionDetails connectionDetails) throws SshDataAccessException; - -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshException.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshException.java deleted file mode 100644 index 6c906c7f7..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-api/src/main/java/org/openecomp/appc/adapter/ssh/SshException.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh; - -public class SshException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Constructor with message. - * - * @param message exception message - */ - public SshException(String message) { - super(message); - } - - /** - * Constructor with message and cause exception. - * - * @param message exception message - * @param cause exception cause - */ - public SshException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/onap/appc/adapter/ssh/sshd/SshAdapterSshd.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/onap/appc/adapter/ssh/sshd/SshAdapterSshd.java new file mode 100644 index 000000000..a5bbe34e2 --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/onap/appc/adapter/ssh/sshd/SshAdapterSshd.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh.sshd; + +import org.onap.appc.adapter.ssh.SshAdapter; +import org.onap.appc.adapter.ssh.SshConnection; + +public class SshAdapterSshd implements SshAdapter { + + @Override + public SshConnection getConnection(String host, int port, String username, String password) { + return new SshConnectionSshd(host, port, username, password); + } +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/onap/appc/adapter/ssh/sshd/SshConnectionSshd.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/onap/appc/adapter/ssh/sshd/SshConnectionSshd.java new file mode 100644 index 000000000..c35c58798 --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/onap/appc/adapter/ssh/sshd/SshConnectionSshd.java @@ -0,0 +1,236 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh.sshd; + +import org.onap.appc.adapter.ssh.Constants; +import org.onap.appc.adapter.ssh.SshConnection; +import org.onap.appc.adapter.ssh.SshException; +import org.onap.appc.encryption.EncryptionTool; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.apache.sshd.ClientChannel; +import org.apache.sshd.ClientSession; +import org.apache.sshd.SshClient; +import org.apache.sshd.client.channel.ChannelExec; +import org.apache.sshd.client.future.AuthFuture; +import org.apache.sshd.client.future.OpenFuture; +import org.apache.sshd.common.KeyPairProvider; +import org.apache.sshd.common.keyprovider.FileKeyPairProvider; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.io.OutputStream; +import java.security.KeyPair; + +/** + * Implementation of SshConnection interface based on Apache MINA SSHD library. + */ +class SshConnectionSshd implements SshConnection { + + private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); + + private static final long AUTH_TIMEOUT = 60000; + private static final long EXEC_TIMEOUT = 120000; + + private String host; + private int port; + private String username; + private String password; + private long timeout = EXEC_TIMEOUT; + private String keyFile; + private SshClient sshClient; + private ClientSession clientSession; + private static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + public SshConnectionSshd(String host, int port, String username, String password, String keyFile) { + this.host = host; + this.port = port; + this.username = username; + this.password = password; + this.keyFile = keyFile; + } + + public SshConnectionSshd(String host, int port, String username, String password) { + this(host, port, username, password, null); + } + + public SshConnectionSshd(String host, int port, String keyFile) { + this(host, port, null, null, keyFile); + } + + @Override + public void connect() { + sshClient = SshClient.setUpDefaultClient(); + sshClient.start(); + try { + clientSession = + sshClient.connect(EncryptionTool.getInstance().decrypt(username), host, port).await().getSession(); + if (password != null) { + clientSession.addPasswordIdentity(EncryptionTool.getInstance().decrypt(password)); + } + if (keyFile != null) { + KeyPairProvider keyPairProvider = new FileKeyPairProvider(new String[] { + keyFile + }); + KeyPair keyPair = keyPairProvider.loadKeys().iterator().next(); + clientSession.addPublicKeyIdentity(keyPair); + } + AuthFuture authFuture = clientSession.auth(); + authFuture.await(AUTH_TIMEOUT); + if (!authFuture.isSuccess()) { + throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port + + "]. Authentication failed."); + } + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port + "].", + e); + } + if (logger.isDebugEnabled()) { + logger.debug("SSH: connected to [" + toString() + "]"); + } + } + + @Override + public void connectWithRetry() { + int retryCount = 0; + int retryDelay = 0; + int retriesLeft = 0; + retryCount = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_COUNT, + Constants.DEFAULT_CONNECTION_RETRY_COUNT); + retryDelay = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_DELAY, + Constants.DEFAULT_CONNECTION_RETRY_DELAY); + retriesLeft = retryCount + 1; + do { + try { + this.connect(); + break; + } catch (RuntimeException e) { + if (retriesLeft > 1) { + logger.debug("SSH Connection failed. Waiting for change in server's state."); + waitForConnection(retryDelay); + retriesLeft--; + logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1) + + "] out of [" + retryCount + "]"); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + } while (retriesLeft > 0); + } + + @Override + public void disconnect() { + try { + if (logger.isDebugEnabled()) { + logger.debug("SSH: disconnecting from [" + toString() + "]"); + } + clientSession.close(false); + } finally { + if (sshClient != null) { + sshClient.stop(); + } + } + } + + @Override + public void setExecTimeout(long timeout) { + this.timeout = timeout; + } + + @Override + public int execCommand(String cmd, OutputStream out, OutputStream err) { + return execCommand(cmd, out, err, false); + } + + @Override + public int execCommandWithPty(String cmd, OutputStream out) { + return execCommand(cmd, out, out, true); + } + + private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) { + try { + if (logger.isDebugEnabled()) { + logger.debug("SSH: executing command"); + } + ChannelExec client = clientSession.createExecChannel(cmd); + client.setUsePty(usePty); // use pseudo-tty? + client.setOut(out); + client.setErr(err); + OpenFuture openFuture = client.open(); + int exitStatus = 0; + try { + client.waitFor(ClientChannel.CLOSED, timeout); + openFuture.verify(); + Integer exitStatusI = client.getExitStatus(); + if (exitStatusI == null) { + throw new SshException("Error executing command [" + cmd + "] over SSH [" + username + "@" + host + + ":" + port + "]. Operation timed out."); + } + exitStatus = exitStatusI; + } finally { + client.close(false); + } + return exitStatus; + } catch (RuntimeException e) { + throw e; + } catch (Exception t) { + throw new SshException( + "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", t); + } + } + + private void waitForConnection(int retryDelay) { + long time = retryDelay * 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(); + } + } + } + } + + @Override + public String toString() { + String address = host; + if (username != null) { + address = username + '@' + address; + } + return address; + } +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/onap/appc/adapter/ssh/sshd/SshdDataAccessService.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/onap/appc/adapter/ssh/sshd/SshdDataAccessService.java new file mode 100644 index 000000000..07a814083 --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/onap/appc/adapter/ssh/sshd/SshdDataAccessService.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh.sshd; + +import javax.sql.rowset.CachedRowSet; + +import org.onap.appc.adapter.ssh.Constants; +import org.onap.appc.adapter.ssh.SshConnectionDetails; +import org.onap.appc.adapter.ssh.SshDataAccessException; +import org.onap.appc.adapter.ssh.SshDataAccessService; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + +import java.sql.SQLException; +import java.util.ArrayList; + +public class SshdDataAccessService implements SshDataAccessService { + + private String schema = Constants.NETCONF_SCHEMA; + private DbLibService dbLibService; + + @Override + public void setSchema(String schema) { + this.schema = schema; + } + + @Override + public void setDbLibService(DbLibService dbLibService) { + this.dbLibService = dbLibService; + } + + @Override + public boolean retrieveConnectionDetails(String vnfType, SshConnectionDetails connectionDetails) throws SshDataAccessException { + + boolean recordFound = false; + + String queryString = "select " + Constants.USER_NAME_TABLE_FIELD_NAME + "," + Constants.PASSWORD_TABLE_FIELD_NAME + "," + Constants.PORT_NUMBER_TABLE_FIELD_NAME + " " + + "from " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME + " " + + "where " + Constants.VNF_TYPE_TABLE_FIELD_NAME + " = ?"; + + ArrayList argList = new ArrayList<>(); + argList.add(vnfType); + + try { + + final CachedRowSet data = dbLibService.getData(queryString, argList, schema); + if (data.first()) { + recordFound = true; + connectionDetails.setUsername(data.getString(Constants.USER_NAME_TABLE_FIELD_NAME)); + connectionDetails.setPassword(data.getString(Constants.PASSWORD_TABLE_FIELD_NAME)); + connectionDetails.setPort(data.getInt(Constants.PORT_NUMBER_TABLE_FIELD_NAME)); + } + + } catch (SQLException e) { + throw new SshDataAccessException(e); + } + + return recordFound; + } + + @Override + public String retrieveConfigFileName(String xmlID) throws SshDataAccessException { + String fileContent; + + String queryString = "select " + Constants.FILE_CONTENT_TABLE_FIELD_NAME + " " + + "from " + Constants.CONFIGFILES_TABLE_NAME + " " + + "where " + Constants.FILE_NAME_TABLE_FIELD_NAME + " = ?"; + + ArrayList argList = new ArrayList<>(); + argList.add(xmlID); + + try { + + final CachedRowSet data = dbLibService.getData(queryString, argList, schema); + fileContent = data.getString(Constants.FILE_CONTENT_TABLE_FIELD_NAME); + + } catch (SQLException e) { + throw new SshDataAccessException(e); + } + + return fileContent; + } + + +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/openecomp/appc/adapter/ssh/sshd/SshAdapterSshd.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/openecomp/appc/adapter/ssh/sshd/SshAdapterSshd.java deleted file mode 100644 index a5bbe34e2..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/openecomp/appc/adapter/ssh/sshd/SshAdapterSshd.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh.sshd; - -import org.onap.appc.adapter.ssh.SshAdapter; -import org.onap.appc.adapter.ssh.SshConnection; - -public class SshAdapterSshd implements SshAdapter { - - @Override - public SshConnection getConnection(String host, int port, String username, String password) { - return new SshConnectionSshd(host, port, username, password); - } -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/openecomp/appc/adapter/ssh/sshd/SshConnectionSshd.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/openecomp/appc/adapter/ssh/sshd/SshConnectionSshd.java deleted file mode 100644 index c35c58798..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/openecomp/appc/adapter/ssh/sshd/SshConnectionSshd.java +++ /dev/null @@ -1,236 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh.sshd; - -import org.onap.appc.adapter.ssh.Constants; -import org.onap.appc.adapter.ssh.SshConnection; -import org.onap.appc.adapter.ssh.SshException; -import org.onap.appc.encryption.EncryptionTool; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.apache.sshd.ClientChannel; -import org.apache.sshd.ClientSession; -import org.apache.sshd.SshClient; -import org.apache.sshd.client.channel.ChannelExec; -import org.apache.sshd.client.future.AuthFuture; -import org.apache.sshd.client.future.OpenFuture; -import org.apache.sshd.common.KeyPairProvider; -import org.apache.sshd.common.keyprovider.FileKeyPairProvider; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.io.OutputStream; -import java.security.KeyPair; - -/** - * Implementation of SshConnection interface based on Apache MINA SSHD library. - */ -class SshConnectionSshd implements SshConnection { - - private static final EELFLogger logger = EELFManager.getInstance().getApplicationLogger(); - - private static final long AUTH_TIMEOUT = 60000; - private static final long EXEC_TIMEOUT = 120000; - - private String host; - private int port; - private String username; - private String password; - private long timeout = EXEC_TIMEOUT; - private String keyFile; - private SshClient sshClient; - private ClientSession clientSession; - private static final Configuration configuration = ConfigurationFactory.getConfiguration(); - - public SshConnectionSshd(String host, int port, String username, String password, String keyFile) { - this.host = host; - this.port = port; - this.username = username; - this.password = password; - this.keyFile = keyFile; - } - - public SshConnectionSshd(String host, int port, String username, String password) { - this(host, port, username, password, null); - } - - public SshConnectionSshd(String host, int port, String keyFile) { - this(host, port, null, null, keyFile); - } - - @Override - public void connect() { - sshClient = SshClient.setUpDefaultClient(); - sshClient.start(); - try { - clientSession = - sshClient.connect(EncryptionTool.getInstance().decrypt(username), host, port).await().getSession(); - if (password != null) { - clientSession.addPasswordIdentity(EncryptionTool.getInstance().decrypt(password)); - } - if (keyFile != null) { - KeyPairProvider keyPairProvider = new FileKeyPairProvider(new String[] { - keyFile - }); - KeyPair keyPair = keyPairProvider.loadKeys().iterator().next(); - clientSession.addPublicKeyIdentity(keyPair); - } - AuthFuture authFuture = clientSession.auth(); - authFuture.await(AUTH_TIMEOUT); - if (!authFuture.isSuccess()) { - throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port - + "]. Authentication failed."); - } - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new SshException("Error establishing ssh connection to [" + username + "@" + host + ":" + port + "].", - e); - } - if (logger.isDebugEnabled()) { - logger.debug("SSH: connected to [" + toString() + "]"); - } - } - - @Override - public void connectWithRetry() { - int retryCount = 0; - int retryDelay = 0; - int retriesLeft = 0; - retryCount = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_COUNT, - Constants.DEFAULT_CONNECTION_RETRY_COUNT); - retryDelay = configuration.getIntegerProperty(Constants.CONNECTION_RETRY_DELAY, - Constants.DEFAULT_CONNECTION_RETRY_DELAY); - retriesLeft = retryCount + 1; - do { - try { - this.connect(); - break; - } catch (RuntimeException e) { - if (retriesLeft > 1) { - logger.debug("SSH Connection failed. Waiting for change in server's state."); - waitForConnection(retryDelay); - retriesLeft--; - logger.debug("Retrying SSH connection. Attempt [" + Integer.toString(retryCount - retriesLeft + 1) - + "] out of [" + retryCount + "]"); - } else { - throw e; - } - } catch (Exception e) { - throw e; - } - } while (retriesLeft > 0); - } - - @Override - public void disconnect() { - try { - if (logger.isDebugEnabled()) { - logger.debug("SSH: disconnecting from [" + toString() + "]"); - } - clientSession.close(false); - } finally { - if (sshClient != null) { - sshClient.stop(); - } - } - } - - @Override - public void setExecTimeout(long timeout) { - this.timeout = timeout; - } - - @Override - public int execCommand(String cmd, OutputStream out, OutputStream err) { - return execCommand(cmd, out, err, false); - } - - @Override - public int execCommandWithPty(String cmd, OutputStream out) { - return execCommand(cmd, out, out, true); - } - - private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) { - try { - if (logger.isDebugEnabled()) { - logger.debug("SSH: executing command"); - } - ChannelExec client = clientSession.createExecChannel(cmd); - client.setUsePty(usePty); // use pseudo-tty? - client.setOut(out); - client.setErr(err); - OpenFuture openFuture = client.open(); - int exitStatus = 0; - try { - client.waitFor(ClientChannel.CLOSED, timeout); - openFuture.verify(); - Integer exitStatusI = client.getExitStatus(); - if (exitStatusI == null) { - throw new SshException("Error executing command [" + cmd + "] over SSH [" + username + "@" + host - + ":" + port + "]. Operation timed out."); - } - exitStatus = exitStatusI; - } finally { - client.close(false); - } - return exitStatus; - } catch (RuntimeException e) { - throw e; - } catch (Exception t) { - throw new SshException( - "Error executing command [" + cmd + "] over SSH [" + username + "@" + host + ":" + port + "]", t); - } - } - - private void waitForConnection(int retryDelay) { - long time = retryDelay * 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(); - } - } - } - } - - @Override - public String toString() { - String address = host; - if (username != null) { - address = username + '@' + address; - } - return address; - } -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/openecomp/appc/adapter/ssh/sshd/SshdDataAccessService.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/openecomp/appc/adapter/ssh/sshd/SshdDataAccessService.java deleted file mode 100644 index 07a814083..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/main/java/org/openecomp/appc/adapter/ssh/sshd/SshdDataAccessService.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh.sshd; - -import javax.sql.rowset.CachedRowSet; - -import org.onap.appc.adapter.ssh.Constants; -import org.onap.appc.adapter.ssh.SshConnectionDetails; -import org.onap.appc.adapter.ssh.SshDataAccessException; -import org.onap.appc.adapter.ssh.SshDataAccessService; -import org.onap.ccsdk.sli.core.dblib.DbLibService; - -import java.sql.SQLException; -import java.util.ArrayList; - -public class SshdDataAccessService implements SshDataAccessService { - - private String schema = Constants.NETCONF_SCHEMA; - private DbLibService dbLibService; - - @Override - public void setSchema(String schema) { - this.schema = schema; - } - - @Override - public void setDbLibService(DbLibService dbLibService) { - this.dbLibService = dbLibService; - } - - @Override - public boolean retrieveConnectionDetails(String vnfType, SshConnectionDetails connectionDetails) throws SshDataAccessException { - - boolean recordFound = false; - - String queryString = "select " + Constants.USER_NAME_TABLE_FIELD_NAME + "," + Constants.PASSWORD_TABLE_FIELD_NAME + "," + Constants.PORT_NUMBER_TABLE_FIELD_NAME + " " + - "from " + Constants.DEVICE_AUTHENTICATION_TABLE_NAME + " " + - "where " + Constants.VNF_TYPE_TABLE_FIELD_NAME + " = ?"; - - ArrayList argList = new ArrayList<>(); - argList.add(vnfType); - - try { - - final CachedRowSet data = dbLibService.getData(queryString, argList, schema); - if (data.first()) { - recordFound = true; - connectionDetails.setUsername(data.getString(Constants.USER_NAME_TABLE_FIELD_NAME)); - connectionDetails.setPassword(data.getString(Constants.PASSWORD_TABLE_FIELD_NAME)); - connectionDetails.setPort(data.getInt(Constants.PORT_NUMBER_TABLE_FIELD_NAME)); - } - - } catch (SQLException e) { - throw new SshDataAccessException(e); - } - - return recordFound; - } - - @Override - public String retrieveConfigFileName(String xmlID) throws SshDataAccessException { - String fileContent; - - String queryString = "select " + Constants.FILE_CONTENT_TABLE_FIELD_NAME + " " + - "from " + Constants.CONFIGFILES_TABLE_NAME + " " + - "where " + Constants.FILE_NAME_TABLE_FIELD_NAME + " = ?"; - - ArrayList argList = new ArrayList<>(); - argList.add(xmlID); - - try { - - final CachedRowSet data = dbLibService.getData(queryString, argList, schema); - fileContent = data.getString(Constants.FILE_CONTENT_TABLE_FIELD_NAME); - - } catch (SQLException e) { - throw new SshDataAccessException(e); - } - - return fileContent; - } - - -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/onap/appc/adapter/ssh/sshd/SshAdapterSample.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/onap/appc/adapter/ssh/sshd/SshAdapterSample.java new file mode 100644 index 000000000..f79a81856 --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/onap/appc/adapter/ssh/sshd/SshAdapterSample.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh.sshd; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; + +import org.onap.appc.adapter.ssh.SshAdapter; +import org.onap.appc.adapter.ssh.SshConnection; +import org.onap.appc.adapter.ssh.sshd.SshAdapterSshd; + +public class SshAdapterSample { + + public static void main(String[] args) { + String host = "hostname"; + int port = 22; + String username = "user"; + String password = "secret"; + String command = "ls"; + + SshAdapter sshAdapter = new SshAdapterSshd(); + SshConnection sshConnection = sshAdapter.getConnection(host, port, username, password); + sshConnection.connect(); + try { + OutputStream stdout = new ByteArrayOutputStream(); + OutputStream stderr = new ByteArrayOutputStream(); + int status = sshConnection.execCommand(command, stdout, stderr); + if(status == 0) { + System.out.println("Command executed successfully. Output:\n" + stdout.toString()); + } else { + System.err.println("Command returned status " + status + ". Error:\n" + stderr.toString()); + } + } finally { + sshConnection.disconnect(); + } + } +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/onap/appc/adapter/ssh/sshd/SshAdapterTest.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/onap/appc/adapter/ssh/sshd/SshAdapterTest.java new file mode 100644 index 000000000..12b2258d0 --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/onap/appc/adapter/ssh/sshd/SshAdapterTest.java @@ -0,0 +1,250 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh.sshd; + +import org.apache.sshd.SshServer; +import org.apache.sshd.common.NamedFactory; +import org.apache.sshd.common.util.OsUtils; +import org.apache.sshd.server.Command; +import org.apache.sshd.server.CommandFactory; +import org.apache.sshd.server.PasswordAuthenticator; +import org.apache.sshd.server.PublickeyAuthenticator; +import org.apache.sshd.server.command.ScpCommandFactory; +import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; +import org.apache.sshd.server.session.ServerSession; +import org.apache.sshd.server.sftp.SftpSubsystem; +import org.apache.sshd.server.shell.ProcessShellFactory; +import org.hamcrest.CoreMatchers; +import org.junit.*; +import org.junit.rules.ExpectedException; +import org.onap.appc.adapter.ssh.SshAdapter; +import org.onap.appc.adapter.ssh.SshConnection; +import org.onap.appc.adapter.ssh.SshException; +import org.onap.appc.adapter.ssh.sshd.SshAdapterSshd; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.BindException; +import java.security.PublicKey; +import java.util.Collections; +import java.util.EnumSet; + +public class SshAdapterTest { + + private static final boolean START_SERVER = true; + private static final String SSH_HOST = "localhost"; + private static final int SSH_PORT = 2222; + private static final String SSH_USERNAME = "test"; + private static final String SSH_PASSWORD = "test"; + private static final String F_TEST_CMD = "ping -%c 4 %s"; + + private int sshPort = SSH_PORT; + private SshServer sshd; + private SshAdapter sshAdapter = new SshAdapterSshd(); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testExecute() { + String cmd = String.format(F_TEST_CMD, OsUtils.isUNIX() ? 'c' : 'n', "localhost"); + SshConnection sshConnection = connect(SSH_USERNAME, SSH_PASSWORD); + try { + System.out.println("SSH client connected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); + ByteArrayOutputStream stdout = new ByteArrayOutputStream(); + ByteArrayOutputStream stderr = new ByteArrayOutputStream(); + int status = execCmd(sshConnection, cmd, stdout, stderr, false); + Assert.assertEquals(stdout.toString() + ". " + stderr.toString(), 0, status); + } finally { + disconnect(sshConnection); + } + } + + @Test + public void testExecuteWithPty() { + String cmd = String.format(F_TEST_CMD, OsUtils.isUNIX() ? 'c' : 'n', "localhost"); + SshConnection sshConnection = connect(SSH_USERNAME, SSH_PASSWORD); + try { + System.out.println("SSH client connected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); + ByteArrayOutputStream stdout = new ByteArrayOutputStream(); + int status = execCmd(sshConnection, cmd, stdout, null, true); + Assert.assertEquals(stdout.toString() + ". " + stdout.toString(), 0, status); + } finally { + disconnect(sshConnection); + } + } + + @Test + public void testExecuteInvalidCommand() { + String cmd = String.format(F_TEST_CMD, OsUtils.isUNIX() ? 'c' : 'n', "nosuchhost"); + SshConnection sshConnection = connect(SSH_USERNAME, SSH_PASSWORD); + try { + ByteArrayOutputStream stdout = new ByteArrayOutputStream(); + ByteArrayOutputStream stderr = new ByteArrayOutputStream(); + int status = execCmd(sshConnection, cmd, stdout, stderr, false); + Assert.assertNotEquals(stdout.toString() + ". " + stderr.toString(), 0, status); + } finally { + disconnect(sshConnection); + } + } + + @Test + public void testWrongUsername() { + thrown.expect(SshException.class); + thrown.expectMessage(CoreMatchers.containsString("Authentication failed")); + disconnect(connect("WrongUsername", SSH_PASSWORD)); + } + + @Test + public void testWrongPassword() { + thrown.expect(SshException.class); + thrown.expectMessage(CoreMatchers.containsString("Authentication failed")); + disconnect(connect(SSH_USERNAME, "WrongPassword")); + } + + @Before + public void beforeTest() throws IOException { + if (START_SERVER) { + startServer(); + } + } + + @After + public void afterTest() throws InterruptedException { + stopServer(); + } + + private SshConnection connect(String username, String password) { + SshConnection sshConnection = sshAdapter.getConnection(SSH_HOST, sshPort, username, password); + sshConnection.connect(); + System.out.println("SSH client connected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); + return sshConnection; + } + + private void disconnect(SshConnection sshConnection) { + sshConnection.disconnect(); + System.out.println("SSH client disconnected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); + } + + private int execCmd(SshConnection sshConnection, String cmd, OutputStream stdout, OutputStream stderr, boolean usePty) { + System.out.println("=> Running command [" + cmd + "] over SSH"); + int status; + if (usePty) { + status = sshConnection.execCommandWithPty(cmd, stdout); + } else { + status = sshConnection.execCommand(cmd, stdout, stderr); + } + System.out.println("=> Command [" + cmd + "] status is [" + status + "], stdout is [" + String.valueOf(stdout) + "], stderr is [" + String.valueOf(stderr) + "]"); + return status; + } + + private void startServer() throws IOException { + sshd = SshServer.setUpDefaultServer(); + sshd.setSubsystemFactories(Collections.>singletonList(new SftpSubsystem.Factory())); + sshd.setCommandFactory(new ScpCommandFactory(new CommandFactory() { + + public Command createCommand(String command) { + EnumSet ttyOptions; + if (OsUtils.isUNIX()) { + ttyOptions = EnumSet.of(ProcessShellFactory.TtyOptions.ONlCr); + } else { + ttyOptions = EnumSet.of(ProcessShellFactory.TtyOptions.Echo, ProcessShellFactory.TtyOptions.ICrNl, ProcessShellFactory.TtyOptions.ONlCr); + } + return new ProcessShellFactory(command.split(" "), ttyOptions).create(); + } + })); + if (OsUtils.isUNIX()) { + sshd.setShellFactory(new ProcessShellFactory(new String[]{"/bin/sh", "-i", "-l"}, + EnumSet.of(ProcessShellFactory.TtyOptions.ONlCr))); + } else { + sshd.setShellFactory(new ProcessShellFactory(new String[]{"cmd.exe "}, + EnumSet.of(ProcessShellFactory.TtyOptions.Echo, ProcessShellFactory.TtyOptions.ICrNl, ProcessShellFactory.TtyOptions.ONlCr))); + } +// if(SecurityUtils.isBouncyCastleRegistered()) { +// sshd.setKeyPairProvider(new PEMGeneratorHostKeyProvider(System.getProperty("java.io.tmpdir") + "/key.pem")); +// } else { + sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(System.getProperty("java.io.tmpdir") + "/key.ser")); +// } + sshd.setPasswordAuthenticator(new PasswordAuthenticator() { + + @Override + public boolean authenticate(String username, String password, ServerSession session) { + return (SSH_USERNAME.equals(username) && SSH_PASSWORD.equals(password)); + } + }); + sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() { + + public boolean authenticate(String username, PublicKey key, ServerSession session) { + return true; + } + }); + sshd.getProperties().put(SshServer.WELCOME_BANNER, "Welcome to SSHD\n"); + startServer0(); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // ignore + } + } + + private void startServer0() throws IOException { + boolean serverStarted = false; + IOException exception = null; + while (!serverStarted && (sshPort < Integer.MAX_VALUE)) { + try { + System.out.println("Starting SSH server on port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); + sshd.setPort(sshPort); + sshd.start(); + serverStarted = true; + } catch (BindException e) { + System.err.println("Cannot start SSH server on port [" + sshPort + "]. " + e.getMessage()); + if (exception == null) { + // store first thrown exception - will be thrown if cannot start the server + exception = e; + } + sshPort++; + } + } + if (!serverStarted) { + throw exception; + } + System.out.println("SSH server started on port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); + } + + private void stopServer() { + try { + if (sshd != null) { + sshd.stop(true); + System.out.println("SSH server stopped on port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); + } + } catch (InterruptedException e) { + System.err.println("=> Error stopping SSH server."); + e.printStackTrace(); + } finally { + sshd = null; + } + } +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/openecomp/appc/adapter/ssh/sshd/SshAdapterSample.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/openecomp/appc/adapter/ssh/sshd/SshAdapterSample.java deleted file mode 100644 index f79a81856..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/openecomp/appc/adapter/ssh/sshd/SshAdapterSample.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh.sshd; - -import java.io.ByteArrayOutputStream; -import java.io.OutputStream; - -import org.onap.appc.adapter.ssh.SshAdapter; -import org.onap.appc.adapter.ssh.SshConnection; -import org.onap.appc.adapter.ssh.sshd.SshAdapterSshd; - -public class SshAdapterSample { - - public static void main(String[] args) { - String host = "hostname"; - int port = 22; - String username = "user"; - String password = "secret"; - String command = "ls"; - - SshAdapter sshAdapter = new SshAdapterSshd(); - SshConnection sshConnection = sshAdapter.getConnection(host, port, username, password); - sshConnection.connect(); - try { - OutputStream stdout = new ByteArrayOutputStream(); - OutputStream stderr = new ByteArrayOutputStream(); - int status = sshConnection.execCommand(command, stdout, stderr); - if(status == 0) { - System.out.println("Command executed successfully. Output:\n" + stdout.toString()); - } else { - System.err.println("Command returned status " + status + ". Error:\n" + stderr.toString()); - } - } finally { - sshConnection.disconnect(); - } - } -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/openecomp/appc/adapter/ssh/sshd/SshAdapterTest.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/openecomp/appc/adapter/ssh/sshd/SshAdapterTest.java deleted file mode 100644 index 12b2258d0..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-sshd/src/test/java/org/openecomp/appc/adapter/ssh/sshd/SshAdapterTest.java +++ /dev/null @@ -1,250 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh.sshd; - -import org.apache.sshd.SshServer; -import org.apache.sshd.common.NamedFactory; -import org.apache.sshd.common.util.OsUtils; -import org.apache.sshd.server.Command; -import org.apache.sshd.server.CommandFactory; -import org.apache.sshd.server.PasswordAuthenticator; -import org.apache.sshd.server.PublickeyAuthenticator; -import org.apache.sshd.server.command.ScpCommandFactory; -import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; -import org.apache.sshd.server.session.ServerSession; -import org.apache.sshd.server.sftp.SftpSubsystem; -import org.apache.sshd.server.shell.ProcessShellFactory; -import org.hamcrest.CoreMatchers; -import org.junit.*; -import org.junit.rules.ExpectedException; -import org.onap.appc.adapter.ssh.SshAdapter; -import org.onap.appc.adapter.ssh.SshConnection; -import org.onap.appc.adapter.ssh.SshException; -import org.onap.appc.adapter.ssh.sshd.SshAdapterSshd; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.BindException; -import java.security.PublicKey; -import java.util.Collections; -import java.util.EnumSet; - -public class SshAdapterTest { - - private static final boolean START_SERVER = true; - private static final String SSH_HOST = "localhost"; - private static final int SSH_PORT = 2222; - private static final String SSH_USERNAME = "test"; - private static final String SSH_PASSWORD = "test"; - private static final String F_TEST_CMD = "ping -%c 4 %s"; - - private int sshPort = SSH_PORT; - private SshServer sshd; - private SshAdapter sshAdapter = new SshAdapterSshd(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testExecute() { - String cmd = String.format(F_TEST_CMD, OsUtils.isUNIX() ? 'c' : 'n', "localhost"); - SshConnection sshConnection = connect(SSH_USERNAME, SSH_PASSWORD); - try { - System.out.println("SSH client connected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); - ByteArrayOutputStream stdout = new ByteArrayOutputStream(); - ByteArrayOutputStream stderr = new ByteArrayOutputStream(); - int status = execCmd(sshConnection, cmd, stdout, stderr, false); - Assert.assertEquals(stdout.toString() + ". " + stderr.toString(), 0, status); - } finally { - disconnect(sshConnection); - } - } - - @Test - public void testExecuteWithPty() { - String cmd = String.format(F_TEST_CMD, OsUtils.isUNIX() ? 'c' : 'n', "localhost"); - SshConnection sshConnection = connect(SSH_USERNAME, SSH_PASSWORD); - try { - System.out.println("SSH client connected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); - ByteArrayOutputStream stdout = new ByteArrayOutputStream(); - int status = execCmd(sshConnection, cmd, stdout, null, true); - Assert.assertEquals(stdout.toString() + ". " + stdout.toString(), 0, status); - } finally { - disconnect(sshConnection); - } - } - - @Test - public void testExecuteInvalidCommand() { - String cmd = String.format(F_TEST_CMD, OsUtils.isUNIX() ? 'c' : 'n', "nosuchhost"); - SshConnection sshConnection = connect(SSH_USERNAME, SSH_PASSWORD); - try { - ByteArrayOutputStream stdout = new ByteArrayOutputStream(); - ByteArrayOutputStream stderr = new ByteArrayOutputStream(); - int status = execCmd(sshConnection, cmd, stdout, stderr, false); - Assert.assertNotEquals(stdout.toString() + ". " + stderr.toString(), 0, status); - } finally { - disconnect(sshConnection); - } - } - - @Test - public void testWrongUsername() { - thrown.expect(SshException.class); - thrown.expectMessage(CoreMatchers.containsString("Authentication failed")); - disconnect(connect("WrongUsername", SSH_PASSWORD)); - } - - @Test - public void testWrongPassword() { - thrown.expect(SshException.class); - thrown.expectMessage(CoreMatchers.containsString("Authentication failed")); - disconnect(connect(SSH_USERNAME, "WrongPassword")); - } - - @Before - public void beforeTest() throws IOException { - if (START_SERVER) { - startServer(); - } - } - - @After - public void afterTest() throws InterruptedException { - stopServer(); - } - - private SshConnection connect(String username, String password) { - SshConnection sshConnection = sshAdapter.getConnection(SSH_HOST, sshPort, username, password); - sshConnection.connect(); - System.out.println("SSH client connected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); - return sshConnection; - } - - private void disconnect(SshConnection sshConnection) { - sshConnection.disconnect(); - System.out.println("SSH client disconnected. Server port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); - } - - private int execCmd(SshConnection sshConnection, String cmd, OutputStream stdout, OutputStream stderr, boolean usePty) { - System.out.println("=> Running command [" + cmd + "] over SSH"); - int status; - if (usePty) { - status = sshConnection.execCommandWithPty(cmd, stdout); - } else { - status = sshConnection.execCommand(cmd, stdout, stderr); - } - System.out.println("=> Command [" + cmd + "] status is [" + status + "], stdout is [" + String.valueOf(stdout) + "], stderr is [" + String.valueOf(stderr) + "]"); - return status; - } - - private void startServer() throws IOException { - sshd = SshServer.setUpDefaultServer(); - sshd.setSubsystemFactories(Collections.>singletonList(new SftpSubsystem.Factory())); - sshd.setCommandFactory(new ScpCommandFactory(new CommandFactory() { - - public Command createCommand(String command) { - EnumSet ttyOptions; - if (OsUtils.isUNIX()) { - ttyOptions = EnumSet.of(ProcessShellFactory.TtyOptions.ONlCr); - } else { - ttyOptions = EnumSet.of(ProcessShellFactory.TtyOptions.Echo, ProcessShellFactory.TtyOptions.ICrNl, ProcessShellFactory.TtyOptions.ONlCr); - } - return new ProcessShellFactory(command.split(" "), ttyOptions).create(); - } - })); - if (OsUtils.isUNIX()) { - sshd.setShellFactory(new ProcessShellFactory(new String[]{"/bin/sh", "-i", "-l"}, - EnumSet.of(ProcessShellFactory.TtyOptions.ONlCr))); - } else { - sshd.setShellFactory(new ProcessShellFactory(new String[]{"cmd.exe "}, - EnumSet.of(ProcessShellFactory.TtyOptions.Echo, ProcessShellFactory.TtyOptions.ICrNl, ProcessShellFactory.TtyOptions.ONlCr))); - } -// if(SecurityUtils.isBouncyCastleRegistered()) { -// sshd.setKeyPairProvider(new PEMGeneratorHostKeyProvider(System.getProperty("java.io.tmpdir") + "/key.pem")); -// } else { - sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(System.getProperty("java.io.tmpdir") + "/key.ser")); -// } - sshd.setPasswordAuthenticator(new PasswordAuthenticator() { - - @Override - public boolean authenticate(String username, String password, ServerSession session) { - return (SSH_USERNAME.equals(username) && SSH_PASSWORD.equals(password)); - } - }); - sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() { - - public boolean authenticate(String username, PublicKey key, ServerSession session) { - return true; - } - }); - sshd.getProperties().put(SshServer.WELCOME_BANNER, "Welcome to SSHD\n"); - startServer0(); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // ignore - } - } - - private void startServer0() throws IOException { - boolean serverStarted = false; - IOException exception = null; - while (!serverStarted && (sshPort < Integer.MAX_VALUE)) { - try { - System.out.println("Starting SSH server on port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); - sshd.setPort(sshPort); - sshd.start(); - serverStarted = true; - } catch (BindException e) { - System.err.println("Cannot start SSH server on port [" + sshPort + "]. " + e.getMessage()); - if (exception == null) { - // store first thrown exception - will be thrown if cannot start the server - exception = e; - } - sshPort++; - } - } - if (!serverStarted) { - throw exception; - } - System.out.println("SSH server started on port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); - } - - private void stopServer() { - try { - if (sshd != null) { - sshd.stop(true); - System.out.println("SSH server stopped on port [" + sshPort + "]. [" + getClass().getName() + "#" + System.identityHashCode(this) + "]"); - } - } catch (InterruptedException e) { - System.err.println("=> Error stopping SSH server."); - e.printStackTrace(); - } finally { - sshd = null; - } - } -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/onap/appc/adapter/ssh/SshAdapterMock.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/onap/appc/adapter/ssh/SshAdapterMock.java new file mode 100644 index 000000000..4b5cc4ef2 --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/onap/appc/adapter/ssh/SshAdapterMock.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh; + +import java.util.ArrayList; +import java.util.List; + +public class SshAdapterMock implements SshAdapter { + + private List connectionMocks = new ArrayList<>(); + + private int returnStatus; + private String returnStdout; + private String returnStderr; + + @Override + public SshConnection getConnection(String host, int port, String username, String password) { + SshConnectionMock sshConnectionMock = new SshConnectionMock(host, port, username, password); + sshConnectionMock.setReturnStatus(returnStatus); + sshConnectionMock.setReturnStdout(returnStdout); + sshConnectionMock.setReturnStderr(returnStderr); + connectionMocks.add(sshConnectionMock); + return sshConnectionMock; + } + + public List getConnectionMocks() { + return connectionMocks; + } + + public int getReturnStatus() { + return returnStatus; + } + + public void setReturnStatus(int returnStatus) { + this.returnStatus = returnStatus; + } + + public String getReturnStdout() { + return returnStdout; + } + + public void setReturnStdout(String returnStdout) { + this.returnStdout = returnStdout; + } + + public String getReturnStderr() { + return returnStderr; + } + + public void setReturnStderr(String returnStderr) { + this.returnStderr = returnStderr; + } +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/onap/appc/adapter/ssh/SshConnectionMock.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/onap/appc/adapter/ssh/SshConnectionMock.java new file mode 100644 index 000000000..f8fa1621e --- /dev/null +++ b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/onap/appc/adapter/ssh/SshConnectionMock.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.ssh; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; + +import org.onap.appc.adapter.ssh.SshConnection; + +public class SshConnectionMock implements SshConnection { + + private static final int DEF_SUCCESS_STATUS = 0; + + private String host; + private int port; + private String username; + private String password; + private long timeout; + + private int returnStatus = DEF_SUCCESS_STATUS; + private String returnStdout; + private String returnStderr; + + private int connectCallCount = 0; + private int disconnectCallCount = 0; + private List executedCommands = new ArrayList<>(); + + public SshConnectionMock(String host, int port, String username, String password) { + this.host = host; + this.port = port; + this.username = username; + this.password = password; + } + + @Override + public void connect() { + connectCallCount++; + } + + @Override + public void connectWithRetry() { + connectCallCount++; + } + + @Override + public void disconnect() { + disconnectCallCount++; + } + + @Override + public int execCommand(String cmd, OutputStream out, OutputStream err) { + return execCommand(cmd, out, err, false); + } + + @Override + public int execCommandWithPty(String cmd, OutputStream out) { + return execCommand(cmd, out, out, true); + } + + private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) { + executedCommands.add(cmd); + try { + if((out != null) && (returnStdout != null)) { + out.write(returnStdout.getBytes()); + } + } catch(IOException e) { + throw new RuntimeException("Error writing to stdout output stream", e); + } + try { + if((err != null) && (returnStderr != null)) { + err.write(returnStderr.getBytes()); + } + } catch(IOException e) { + throw new RuntimeException("Error writing to stderr output stream", e); + } + return returnStatus; + } + + @Override + public void setExecTimeout(long timeout) { + this.timeout = timeout; + } + + public long getExecTimeout() { + return timeout; + } + + public String getHost() { + return host; + } + + public int getPort() { + return port; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + public int getConnectCallCount() { + return connectCallCount; + } + + public int getDisconnectCallCount() { + return disconnectCallCount; + } + + public List getExecutedCommands() { + return executedCommands; + } + + public int getReturnStatus() { + return returnStatus; + } + + public void setReturnStatus(int returnStatus) { + this.returnStatus = returnStatus; + } + + public String getReturnStdout() { + return returnStdout; + } + + public void setReturnStdout(String returnStdout) { + this.returnStdout = returnStdout; + } + + public String getReturnStderr() { + return returnStderr; + } + + public void setReturnStderr(String returnStderr) { + this.returnStderr = returnStderr; + } +} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/openecomp/appc/adapter/ssh/SshAdapterMock.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/openecomp/appc/adapter/ssh/SshAdapterMock.java deleted file mode 100644 index 4b5cc4ef2..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/openecomp/appc/adapter/ssh/SshAdapterMock.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh; - -import java.util.ArrayList; -import java.util.List; - -public class SshAdapterMock implements SshAdapter { - - private List connectionMocks = new ArrayList<>(); - - private int returnStatus; - private String returnStdout; - private String returnStderr; - - @Override - public SshConnection getConnection(String host, int port, String username, String password) { - SshConnectionMock sshConnectionMock = new SshConnectionMock(host, port, username, password); - sshConnectionMock.setReturnStatus(returnStatus); - sshConnectionMock.setReturnStdout(returnStdout); - sshConnectionMock.setReturnStderr(returnStderr); - connectionMocks.add(sshConnectionMock); - return sshConnectionMock; - } - - public List getConnectionMocks() { - return connectionMocks; - } - - public int getReturnStatus() { - return returnStatus; - } - - public void setReturnStatus(int returnStatus) { - this.returnStatus = returnStatus; - } - - public String getReturnStdout() { - return returnStdout; - } - - public void setReturnStdout(String returnStdout) { - this.returnStdout = returnStdout; - } - - public String getReturnStderr() { - return returnStderr; - } - - public void setReturnStderr(String returnStderr) { - this.returnStderr = returnStderr; - } -} diff --git a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/openecomp/appc/adapter/ssh/SshConnectionMock.java b/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/openecomp/appc/adapter/ssh/SshConnectionMock.java deleted file mode 100644 index f8fa1621e..000000000 --- a/appc-adapters/appc-ssh-adapter/appc-ssh-adapter-tests/src/main/java/org/openecomp/appc/adapter/ssh/SshConnectionMock.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.adapter.ssh; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import org.onap.appc.adapter.ssh.SshConnection; - -public class SshConnectionMock implements SshConnection { - - private static final int DEF_SUCCESS_STATUS = 0; - - private String host; - private int port; - private String username; - private String password; - private long timeout; - - private int returnStatus = DEF_SUCCESS_STATUS; - private String returnStdout; - private String returnStderr; - - private int connectCallCount = 0; - private int disconnectCallCount = 0; - private List executedCommands = new ArrayList<>(); - - public SshConnectionMock(String host, int port, String username, String password) { - this.host = host; - this.port = port; - this.username = username; - this.password = password; - } - - @Override - public void connect() { - connectCallCount++; - } - - @Override - public void connectWithRetry() { - connectCallCount++; - } - - @Override - public void disconnect() { - disconnectCallCount++; - } - - @Override - public int execCommand(String cmd, OutputStream out, OutputStream err) { - return execCommand(cmd, out, err, false); - } - - @Override - public int execCommandWithPty(String cmd, OutputStream out) { - return execCommand(cmd, out, out, true); - } - - private int execCommand(String cmd, OutputStream out, OutputStream err, boolean usePty) { - executedCommands.add(cmd); - try { - if((out != null) && (returnStdout != null)) { - out.write(returnStdout.getBytes()); - } - } catch(IOException e) { - throw new RuntimeException("Error writing to stdout output stream", e); - } - try { - if((err != null) && (returnStderr != null)) { - err.write(returnStderr.getBytes()); - } - } catch(IOException e) { - throw new RuntimeException("Error writing to stderr output stream", e); - } - return returnStatus; - } - - @Override - public void setExecTimeout(long timeout) { - this.timeout = timeout; - } - - public long getExecTimeout() { - return timeout; - } - - public String getHost() { - return host; - } - - public int getPort() { - return port; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public int getConnectCallCount() { - return connectCallCount; - } - - public int getDisconnectCallCount() { - return disconnectCallCount; - } - - public List getExecutedCommands() { - return executedCommands; - } - - public int getReturnStatus() { - return returnStatus; - } - - public void setReturnStatus(int returnStatus) { - this.returnStatus = returnStatus; - } - - public String getReturnStdout() { - return returnStdout; - } - - public void setReturnStdout(String returnStdout) { - this.returnStdout = returnStdout; - } - - public String getReturnStderr() { - return returnStderr; - } - - public void setReturnStderr(String returnStderr) { - this.returnStderr = returnStderr; - } -} -- cgit 1.2.3-korg