From 5a6a6de6f1a26a1897e4917a0df613e25a24eb70 Mon Sep 17 00:00:00 2001 From: "Benjamin, Max (mb388a)" Date: Mon, 30 Jul 2018 15:56:09 -0400 Subject: Containerization feature of SO Change-Id: I95381232eeefcd247a66a5cec370a8ce1c288e18 Issue-ID: SO-670 Signed-off-by: Benjamin, Max (mb388a) --- .../org/onap/so/asdc/ASDCControllerSingleton.java | 67 + .../main/java/org/onap/so/asdc/Application.java | 44 + .../java/org/onap/so/asdc/CatalogDBConfig.java | 79 + .../java/org/onap/so/asdc/JerseyConfiguration.java | 52 + .../java/org/onap/so/asdc/RequestDBConfig.java | 78 + .../org/onap/so/asdc/WebSecurityConfigImpl.java | 51 + .../org/onap/so/asdc/client/ASDCConfiguration.java | 263 ++++ .../org/onap/so/asdc/client/ASDCController.java | 776 ++++++++++ .../onap/so/asdc/client/ASDCControllerStatus.java | 27 + .../so/asdc/client/ASDCNotificationCallBack.java | 58 + .../onap/so/asdc/client/ASDCStatusCallBack.java | 75 + .../so/asdc/client/DistributionStatusMessage.java | 77 + .../client/FinalDistributionStatusMessage.java | 86 ++ .../org/onap/so/asdc/client/ResourceInstance.java | 79 + .../client/exceptions/ASDCControllerException.java | 51 + .../client/exceptions/ASDCDownloadException.java | 51 + .../client/exceptions/ASDCParametersException.java | 51 + .../exceptions/ArtifactInstallerException.java | 51 + .../client/test/emulators/ArtifactInfoImpl.java | 171 +++ .../test/emulators/DistributionClientEmulator.java | 188 +++ .../asdc/client/test/emulators/JsonStatusData.java | 124 ++ .../test/emulators/JsonVfModuleMetaData.java | 96 ++ .../test/emulators/NotificationDataImpl.java | 175 +++ .../client/test/emulators/ResourceInfoImpl.java | 158 ++ .../asdc/client/test/rest/ASDCRestInterface.java | 120 ++ .../onap/so/asdc/installer/ASDCElementInfo.java | 211 +++ .../onap/so/asdc/installer/BigDecimalVersion.java | 62 + .../so/asdc/installer/IArtifactOrchestrator.java | 37 + .../org/onap/so/asdc/installer/IVfModuleData.java | 51 + .../so/asdc/installer/IVfResourceInstaller.java | 32 + .../so/asdc/installer/ToscaResourceStructure.java | 506 +++++++ .../onap/so/asdc/installer/VfModuleArtifact.java | 90 ++ .../onap/so/asdc/installer/VfModuleMetaData.java | 96 ++ .../onap/so/asdc/installer/VfModuleStructure.java | 114 ++ .../so/asdc/installer/VfResourceStructure.java | 220 +++ .../installer/heat/ToscaResourceInstaller.java | 1589 ++++++++++++++++++++ .../tenantIsolation/AaiClientPropertiesImpl.java | 70 + .../asdc/tenantIsolation/DistributionStatus.java | 29 + .../asdc/tenantIsolation/SpringContextHelper.java | 41 + .../asdc/tenantIsolation/WatchdogDistribution.java | 194 +++ .../onap/so/asdc/util/ASDCNotificationLogging.java | 779 ++++++++++ .../org/onap/so/asdc/util/NotificationLogging.java | 169 +++ .../src/main/java/org/onap/so/asdc/util/ToLog.java | 29 + .../java/org/onap/so/asdc/util/YamlEditor.java | 176 +++ .../mso/asdc/ASDCControllerSingleton.java | 82 - .../mso/asdc/client/ASDCConfiguration.java | 508 ------- .../openecomp/mso/asdc/client/ASDCController.java | 915 ----------- .../mso/asdc/client/ASDCControllerStatus.java | 27 - .../mso/asdc/client/ASDCGlobalController.java | 217 --- .../mso/asdc/client/DistributionStatusMessage.java | 77 - .../client/FinalDistributionStatusMessage.java | 86 -- .../client/exceptions/ASDCControllerException.java | 51 - .../client/exceptions/ASDCDownloadException.java | 51 - .../client/exceptions/ASDCParametersException.java | 51 - .../exceptions/ArtifactInstallerException.java | 51 - .../test/emulators/DistributionClientEmulator.java | 204 --- .../client/test/emulators/JsonArtifactInfo.java | 122 -- .../emulators/JsonArtifactInfoDeserializer.java | 48 - .../test/emulators/JsonNotificationData.java | 149 -- .../client/test/emulators/JsonResourceInfo.java | 105 -- .../emulators/JsonResourceInfoDeserializer.java | 43 - .../asdc/client/test/emulators/JsonStatusData.java | 124 -- .../test/emulators/JsonVfModuleMetaData.java | 96 -- .../asdc/client/test/rest/ASDCRestInterface.java | 117 -- .../mso/asdc/healthcheck/HealthCheckHandler.java | 95 -- .../mso/asdc/installer/ASDCElementInfo.java | 211 --- .../mso/asdc/installer/BigDecimalVersion.java | 62 - .../mso/asdc/installer/IArtifactOrchestrator.java | 37 - .../mso/asdc/installer/IVfModuleData.java | 54 - .../mso/asdc/installer/IVfResourceInstaller.java | 32 - .../mso/asdc/installer/ToscaResourceStructure.java | 537 ------- .../mso/asdc/installer/VfModuleArtifact.java | 70 - .../mso/asdc/installer/VfModuleMetaData.java | 96 -- .../mso/asdc/installer/VfModuleStructure.java | 113 -- .../mso/asdc/installer/VfResourceStructure.java | 246 --- .../installer/heat/ToscaResourceInstaller.java | 1272 ---------------- .../asdc/installer/heat/VfResourceInstaller.java | 790 ---------- .../tenantIsolation/AaiClientPropertiesImpl.java | 62 - .../asdc/tenantIsolation/AsdcPropertiesUtils.java | 59 - .../asdc/tenantIsolation/DistributionStatus.java | 29 - .../asdc/tenantIsolation/WatchdogDistribution.java | 239 --- .../mso/asdc/util/ASDCNotificationLogging.java | 525 ------- .../mso/asdc/util/NotificationLogging.java | 169 --- .../java/org/openecomp/mso/asdc/util/ToLog.java | 29 - .../org/openecomp/mso/asdc/util/YamlEditor.java | 176 --- 85 files changed, 7543 insertions(+), 8027 deletions(-) create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/ASDCControllerSingleton.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/Application.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/CatalogDBConfig.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/JerseyConfiguration.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/RequestDBConfig.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCControllerStatus.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCNotificationCallBack.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCStatusCallBack.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/DistributionStatusMessage.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/FinalDistributionStatusMessage.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/ResourceInstance.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCControllerException.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCDownloadException.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCParametersException.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerException.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImpl.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulator.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonStatusData.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/installer/BigDecimalVersion.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/installer/IArtifactOrchestrator.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfModuleData.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfResourceInstaller.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleArtifact.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleMetaData.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleStructure.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImpl.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/DistributionStatus.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/SpringContextHelper.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/util/NotificationLogging.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/util/ToLog.java create mode 100644 asdc-controller/src/main/java/org/onap/so/asdc/util/YamlEditor.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/ASDCControllerSingleton.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCConfiguration.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCController.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCControllerStatus.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCGlobalController.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/DistributionStatusMessage.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/FinalDistributionStatusMessage.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ASDCControllerException.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ASDCDownloadException.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ASDCParametersException.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ArtifactInstallerException.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/DistributionClientEmulator.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonArtifactInfo.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonArtifactInfoDeserializer.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonNotificationData.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonResourceInfo.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonResourceInfoDeserializer.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonStatusData.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonVfModuleMetaData.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/rest/ASDCRestInterface.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/healthcheck/HealthCheckHandler.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/ASDCElementInfo.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/BigDecimalVersion.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/IArtifactOrchestrator.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/IVfModuleData.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/IVfResourceInstaller.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/ToscaResourceStructure.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleArtifact.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleMetaData.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleStructure.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfResourceStructure.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/heat/ToscaResourceInstaller.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/heat/VfResourceInstaller.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/AaiClientPropertiesImpl.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/AsdcPropertiesUtils.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/DistributionStatus.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/WatchdogDistribution.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/util/ASDCNotificationLogging.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/util/NotificationLogging.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/util/ToLog.java delete mode 100644 asdc-controller/src/main/java/org/openecomp/mso/asdc/util/YamlEditor.java (limited to 'asdc-controller/src/main/java/org') diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/ASDCControllerSingleton.java b/asdc-controller/src/main/java/org/onap/so/asdc/ASDCControllerSingleton.java new file mode 100644 index 0000000000..0ed878446f --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/ASDCControllerSingleton.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc; + +import javax.annotation.PreDestroy; + +import org.onap.so.asdc.client.ASDCController; +import org.onap.so.asdc.client.exceptions.ASDCControllerException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.security.SecureRandom; + +@Component +@Profile("!test") +public class ASDCControllerSingleton { + + + @Autowired + private ASDCController asdcController; + + + + @Scheduled (fixedRate = 50000) + public void periodicControllerTask() { + + try { + int randomNumber = new SecureRandom().nextInt(Integer.MAX_VALUE); + asdcController.setControllerName("mso-controller"+randomNumber); + asdcController.initASDC(); + } catch (ASDCControllerException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @PreDestroy + private void terminate () { + try { + asdcController.closeASDC (); + } catch (ASDCControllerException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/Application.java b/asdc-controller/src/main/java/org/onap/so/asdc/Application.java new file mode 100644 index 0000000000..a365d0740d --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/Application.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = { "org.onap.so" }) +public class Application { + + private static final String LOGS_DIR = "logs_dir"; + + private static void setLogsDir() { + if (System.getProperty(LOGS_DIR) == null) { + System.getProperties().setProperty(LOGS_DIR, "./logs/asdc/"); + } + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + System.getProperties().setProperty("mso.db", "MARIADB"); + System.getProperties().setProperty("mso.config.path", "."); + System.getProperties().setProperty("server.name", "Springboot"); + setLogsDir(); + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/CatalogDBConfig.java b/asdc-controller/src/main/java/org/onap/so/asdc/CatalogDBConfig.java new file mode 100644 index 0000000000..48f0990bf3 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/CatalogDBConfig.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc; + + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.Profile; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories( + entityManagerFactoryRef = "entityManagerFactory", + basePackages = {"org.onap.so.db.catalog.data.repository"} + ) +@Profile({"!test"}) +public class CatalogDBConfig { + + @Primary + @Bean(name = "dataSource") + @ConfigurationProperties(prefix = "spring.datasource") + public DataSource dataSource() { + return DataSourceBuilder.create().build(); + } + + @Primary + @Bean(name = "entityManagerFactory") + public LocalContainerEntityManagerFactoryBean + entityManagerFactory( + EntityManagerFactoryBuilder builder, + @Qualifier("dataSource") DataSource dataSource + ) { + return builder + .dataSource(dataSource) + .packages("org.onap.so.db.catalog.beans") + .persistenceUnit("catalogDB") + .build(); + } + + @Primary + @Bean(name = "transactionManager") + public PlatformTransactionManager transactionManager( + @Qualifier("entityManagerFactory") EntityManagerFactory + entityManagerFactory + ) { + return new JpaTransactionManager(entityManagerFactory); + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/JerseyConfiguration.java b/asdc-controller/src/main/java/org/onap/so/asdc/JerseyConfiguration.java new file mode 100644 index 0000000000..3a26b7b60c --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/JerseyConfiguration.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc; + +import javax.annotation.PostConstruct; +import javax.ws.rs.ApplicationPath; +import org.glassfish.jersey.server.ResourceConfig; +import org.onap.so.asdc.client.test.rest.ASDCRestInterface; +import org.springframework.context.annotation.Configuration; +import io.swagger.jaxrs.config.BeanConfig; +import io.swagger.jaxrs.listing.ApiListingResource; +import io.swagger.jaxrs.listing.SwaggerSerializers; + +@Configuration +@ApplicationPath("/test") +public class JerseyConfiguration extends ResourceConfig { + + + @PostConstruct + public void setUp() { + register(ASDCRestInterface.class); + register(ApiListingResource.class); + register(SwaggerSerializers.class); + + BeanConfig beanConfig = new BeanConfig(); + beanConfig.setVersion("1.0.2"); + beanConfig.setSchemes(new String[] { "http" }); + beanConfig.setHost("localhost:8080"); + beanConfig.setBasePath("/mso"); + beanConfig.setResourcePackage("org.onap.so.apihandlerinfra"); + beanConfig.setPrettyPrint(true); + beanConfig.setScan(true); + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/RequestDBConfig.java b/asdc-controller/src/main/java/org/onap/so/asdc/RequestDBConfig.java new file mode 100644 index 0000000000..da2fb2e8be --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/RequestDBConfig.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc; + + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories( + entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager", + basePackages = { "org.onap.so.db.request.data.repository" } + ) +@Profile({"!test"}) +public class RequestDBConfig { + + @Bean(name = "requestDataSource") + @ConfigurationProperties(prefix = "request.datasource") + public DataSource dataSource() { + return DataSourceBuilder.create().build(); + } + + + @Bean(name = "requestEntityManagerFactory") + public LocalContainerEntityManagerFactoryBean + entityManagerFactory( + EntityManagerFactoryBuilder builder, + @Qualifier("requestDataSource") DataSource dataSource + ) { + return builder + .dataSource(dataSource) + .packages("org.onap.so.db.request.beans") + .persistenceUnit("requestDB") + .build(); + } + + + @Bean(name = "requestTransactionManager") + public PlatformTransactionManager transactionManager( + @Qualifier("requestEntityManagerFactory") EntityManagerFactory + entityManagerFactory + ) { + return new JpaTransactionManager(entityManagerFactory); + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java new file mode 100644 index 0000000000..bbd7cc06e3 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc; + +import org.onap.so.security.MSOSpringFirewall; +import org.onap.so.security.WebSecurityConfig; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.web.firewall.StrictHttpFirewall; +import org.springframework.util.StringUtils; + +@EnableWebSecurity +public class WebSecurityConfigImpl extends WebSecurityConfig { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable() + .authorizeRequests() + .antMatchers("/manage/health","/manage/info").permitAll() + .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),",").toString()) + .and() + .httpBasic(); + } + + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java new file mode 100644 index 0000000000..85e3e9e747 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java @@ -0,0 +1,263 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + + +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.onap.sdc.api.consumer.IConfiguration; +import org.onap.so.logger.MsoLogger; +import org.onap.so.utils.CryptoUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public class ASDCConfiguration implements IConfiguration { + + // SHell command to obtain the same encryption, 128 bits key, key must be HEX + // echo -n "This is a test string" | openssl aes-128-ecb -e -K 546573746F736973546573746F736973 -nosalt | xxd + + + + private String asdcControllerName; + + public static final String MSO_PROP_ASDC = "MSO_PROP_ASDC"; + public static final String PARAMETER_PATTERN = "asdc-connections"; + public static final String MSG_BUS_ADDRESS_ATTRIBUTE_NAME = "messageBusAddress"; + public static final String WATCHDOG_TIMEOUT_NAME = "watchDogTimeout"; + + public static final String CONSUMER_GROUP_ATTRIBUTE_NAME = "consumerGroup"; + public static final String CONSUMER_ID_ATTRIBUTE_NAME = "consumerId"; + public static final String ENVIRONMENT_NAME_ATTRIBUTE_NAME = "environmentName"; + public static final String PASSWORD_ATTRIBUTE_NAME = "password"; + public static final String POLLING_INTERVAL_ATTRIBUTE_NAME = "pollingInterval"; + public static final String RELEVANT_ARTIFACT_TYPES_ATTRIBUTE_NAME = "relevantArtifactTypes"; + public static final String USER_ATTRIBUTE_NAME = "user"; + public static final String ASDC_ADDRESS_ATTRIBUTE_NAME = "asdcAddress"; + public static final String POLLING_TIMEOUT_ATTRIBUTE_NAME = "pollingTimeout"; + public static final String ACTIVATE_SERVER_TLS_AUTH = "activateServerTLSAuth"; + public static final String KEY_STORE_PASSWORD = "keyStorePassword"; + public static final String KEY_STORE_PATH = "keyStorePath"; + + public static final String HEAT="HEAT"; + public static final String HEAT_ARTIFACT="HEAT_ARTIFACT"; + public static final String HEAT_ENV="HEAT_ENV"; + public static final String HEAT_NESTED="HEAT_NESTED"; + public static final String HEAT_NET="HEAT_NET"; + public static final String HEAT_VOL="HEAT_VOL"; + public static final String OTHER="OTHER"; + public static final String TOSCA_CSAR="TOSCA_CSAR"; + public static final String VF_MODULES_METADATA="VF_MODULES_METADATA"; + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.ASDC,ASDCConfiguration.class); + + + + private static final String[] SUPPORTED_ARTIFACT_TYPES = {HEAT, + HEAT_ARTIFACT, + HEAT_ENV, + HEAT_NESTED, + HEAT_NET, + HEAT_VOL, + OTHER, + TOSCA_CSAR, + VF_MODULES_METADATA}; + + public static final List SUPPORTED_ARTIFACT_TYPES_LIST = Collections.unmodifiableList(Arrays.asList(SUPPORTED_ARTIFACT_TYPES)); + + @Autowired + private Environment env; + + @Value("${mso.asdc.config.key}") + private String configKey; + + @Value("${mso.asdc-connections.asdc-controller1.messageBusAddress}") + private String[] messageBusAddress; + + + public void setAsdcControllerName(String asdcControllerName) { + this.asdcControllerName = asdcControllerName; + } + + + @Override + public java.lang.Boolean isUseHttpsWithDmaap() { + return false; + } + + @Override + public boolean isConsumeProduceStatusTopic(){ + return true; + } + + @Override + public List getMsgBusAddress(){ + if (messageBusAddress.length > 0) { + return Arrays.asList(messageBusAddress); + } else { + return Collections.emptyList(); + } + + + } + + public String getAsdcControllerName () { + return asdcControllerName; + } + + + @Override + public String getConsumerGroup() { + return getPropertyOrNull("mso.asdc-connections.asdc-controller1.consumerGroup"); + } + + public int getWatchDogTimeout () { + return getIntegerPropertyOrZero("mso.asdc-connections.asdc-controller1.watchDogTimeout"); + + } + + @Override + public String getConsumerID () { + return getPropertyOrNull("mso.asdc-connections.asdc-controller1.consumerId"); + } + + public int getIntegerPropertyOrZero (String propertyName) { + String property = env.getProperty(propertyName); + if (property == null || "NULL".equals(property) || property.isEmpty()) { + return 0; + } else { + try { + return Integer.parseInt(property); + } catch (NumberFormatException e) { + return 0; + } + } + } + + public String getPropertyOrNull (String propertyName) { + String config = env.getProperty(propertyName); + if (config==null || "NULL".equals(config) || config.isEmpty()) { + return null; + } else { + return config; + } + } + + public String getEncryptedPropertyOrNull (String propertyName) { + String decryptedKey; + String config = env.getProperty(propertyName); + + if (config==null || "NULL".equals(config) || config.isEmpty()) { + return null; + } + + try { + decryptedKey = CryptoUtils.decrypt(config, this.configKey); + } catch (GeneralSecurityException e) { + msoLogger.debug("Exception while decrypting property: " + propertyName, e); + return null; + } + + if (decryptedKey.isEmpty ()) { + return null; + } else { + return decryptedKey; + } + } + + public boolean getBooleanPropertyWithDefault (String propertyName, boolean defaultValue) { + String config = env.getProperty(propertyName); + if (config == null || "NULL".equals(config) || config.isEmpty()) { + return defaultValue; + } else { + try { + return Boolean.valueOf(config); + } catch (Exception e) { + return defaultValue; + } + } + } + + @Override + public String getEnvironmentName () { + return getPropertyOrNull("mso.asdc-connections.asdc-controller1.environmentName"); + } + + @Override + public String getPassword () { + return getEncryptedPropertyOrNull("mso.asdc-connections.asdc-controller1.password"); + } + + @Override + public int getPollingInterval () { + return getIntegerPropertyOrZero("mso.asdc-connections.asdc-controller1.pollingInterval"); + } + + @Override + public List getRelevantArtifactTypes () { + // DO not return the Static List SUPPORTED_ARTIFACT_TYPES_LIST because the ASDC Client will try to modify it !!! + return Arrays.asList(SUPPORTED_ARTIFACT_TYPES); + } + + @Override + public String getUser () { + return getPropertyOrNull("mso.asdc-connections.asdc-controller1.user"); + } + + @Override + public String getAsdcAddress () { + return getPropertyOrNull("mso.asdc-connections.asdc-controller1.asdcAddress"); + } + + @Override + public int getPollingTimeout () { + return getIntegerPropertyOrZero("mso.asdc-connections.asdc-controller1.pollingTimeout"); + } + + @Override + public boolean activateServerTLSAuth() { + return getBooleanPropertyWithDefault("mso.asdc-connections.asdc-controller1.activateServerTLSAuth", true); + } + + @Override + public String getKeyStorePassword() { + return getPropertyOrNull("mso.asdc-connections.asdc-controller1.keyStorePassword"); + } + + @Override + public String getKeyStorePath() { + return getPropertyOrNull("mso.asdc-connections.asdc-controller1.keyStorePath"); + } + + /** + * The flag allows the client to receive metadata for all resources of the service regardless of the artifacts associated to them. + * Setting the flag to false will preserve legacy behavior. + */ + @Override + public boolean isFilterInEmptyResources() { + return getBooleanPropertyWithDefault("mso.asdc-connections.asdc-controller1.isFilterInEmptyResources", true); + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java new file mode 100644 index 0000000000..7423a7a197 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java @@ -0,0 +1,776 @@ +/*- +d * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.List; + +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.consumer.IDistributionStatusMessage; +import org.onap.sdc.api.consumer.IFinalDistrStatusMessage; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.impl.DistributionClientFactory; +import org.onap.sdc.utils.DistributionActionResultEnum; +import org.onap.sdc.utils.DistributionStatusEnum; +import org.onap.so.asdc.client.exceptions.ASDCControllerException; +import org.onap.so.asdc.client.exceptions.ASDCDownloadException; +import org.onap.so.asdc.client.exceptions.ASDCParametersException; +import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; +import org.onap.so.asdc.installer.IVfResourceInstaller; +import org.onap.so.asdc.installer.ToscaResourceStructure; +import org.onap.so.asdc.installer.VfResourceStructure; +import org.onap.so.asdc.installer.heat.ToscaResourceInstaller; +import org.onap.so.asdc.tenantIsolation.DistributionStatus; +import org.onap.so.asdc.tenantIsolation.WatchdogDistribution; +import org.onap.so.asdc.util.ASDCNotificationLogging; +import org.onap.so.db.request.beans.WatchdogDistributionStatus; +import org.onap.so.db.request.data.repository.WatchdogDistributionStatusRepository; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoAlarmLogger; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class ASDCController { + + protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC,ASDCController.class); + + protected static MsoAlarmLogger alarmLogger = new MsoAlarmLogger (); + + protected boolean isAsdcClientAutoManaged = false; + + protected String controllerName; + + private ASDCControllerStatus controllerStatus = ASDCControllerStatus.STOPPED; + + protected int nbOfNotificationsOngoing = 0; + + @Autowired + private ToscaResourceInstaller toscaInstaller; + + @Autowired + private WatchdogDistributionStatusRepository wdsRepo; + + @Autowired + private ASDCConfiguration asdcConfig; + + @Autowired + private ASDCStatusCallBack asdcStatusCallBack; + + @Autowired + private ASDCNotificationCallBack asdcNotificationCallBack; + + private IDistributionClient distributionClient; + + private static final String UUID_PARAM = "(UUID:"; + + @Autowired + private WatchdogDistribution wd; + + + public int getNbOfNotificationsOngoing () { + return nbOfNotificationsOngoing; + } + + public IDistributionClient getDistributionClient() { + return distributionClient; + } + + + + public void setDistributionClient(IDistributionClient distributionClient) { + this.distributionClient = distributionClient; + } + + + + protected void changeControllerStatus (ASDCControllerStatus newControllerStatus) { + switch (newControllerStatus) { + + case BUSY: + ++this.nbOfNotificationsOngoing; + this.controllerStatus = newControllerStatus; + break; + + case IDLE: + if (this.nbOfNotificationsOngoing > 1) { + --this.nbOfNotificationsOngoing; + } else { + this.nbOfNotificationsOngoing = 0; + this.controllerStatus = newControllerStatus; + } + + break; + default: + this.controllerStatus = newControllerStatus; + break; + + } + } + + public ASDCControllerStatus getControllerStatus () { + return this.controllerStatus; + } + + public ASDCController () { + isAsdcClientAutoManaged = true; + } + + public ASDCController (String controllerConfigName) { + isAsdcClientAutoManaged = true; + this.controllerName = controllerConfigName; + } + + public ASDCController (String controllerConfigName, IDistributionClient asdcClient, IVfResourceInstaller resourceinstaller) { + distributionClient = asdcClient; + } + + public ASDCController (String controllerConfigName,IDistributionClient asdcClient) { + distributionClient = asdcClient; + this.controllerName = controllerConfigName; + } + public String getControllerName() { + return controllerName; + } + + public void setControllerName(String controllerName) { + this.controllerName = controllerName; + } + + /** + * This method initializes the ASDC Controller and the ASDC Client. + * + * @throws ASDCControllerException It throws an exception if the ASDC Client cannot be instantiated or if an init + * attempt is done when already initialized + * @throws ASDCParametersException If there is an issue with the parameters provided + * @throws IOException In case of issues when trying to load the key file + */ + public void initASDC () throws ASDCControllerException { + String event = "Initialize the ASDC Controller"; + MsoLogger.setServiceName ("InitASDC"); + LOGGER.debug (event); + if (this.getControllerStatus () != ASDCControllerStatus.STOPPED) { + String endEvent = "The controller is already initialized, call the closeASDC method first"; + throw new ASDCControllerException (endEvent); + } + + if (asdcConfig != null) { + asdcConfig.setAsdcControllerName(controllerName); + } + + if (this.distributionClient == null) { + distributionClient = DistributionClientFactory.createDistributionClient (); + } + + long initStartTime = System.currentTimeMillis (); + IDistributionClientResult result = this.distributionClient.init (asdcConfig, + asdcNotificationCallBack, asdcStatusCallBack); + if (!result.getDistributionActionResult ().equals (DistributionActionResultEnum.SUCCESS)) { + String endEvent = "ASDC distribution client init failed with reason:" + + result.getDistributionMessageResult (); + LOGGER.recordMetricEvent (initStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.UnknownError, "Initialization of the ASDC Controller failed with reason:" + result.getDistributionMessageResult (), "ASDC", "init", null); + LOGGER.debug (endEvent); + this.changeControllerStatus (ASDCControllerStatus.STOPPED); + throw new ASDCControllerException ("Initialization of the ASDC Controller failed with reason: " + + result.getDistributionMessageResult ()); + } + LOGGER.recordMetricEvent (initStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully initialize ASDC Controller", "ASDC", "init", null); + + long clientstartStartTime = System.currentTimeMillis (); + result = this.distributionClient.start (); + if (!result.getDistributionActionResult ().equals (DistributionActionResultEnum.SUCCESS)) { + String endEvent = "ASDC distribution client start failed with reason:" + + result.getDistributionMessageResult (); + LOGGER.recordMetricEvent (clientstartStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.UnknownError, endEvent, "ASDC", "start", null); + LOGGER.debug (endEvent); + this.changeControllerStatus (ASDCControllerStatus.STOPPED); + throw new ASDCControllerException ("Startup of the ASDC Controller failed with reason: " + + result.getDistributionMessageResult ()); + } + LOGGER.recordMetricEvent (clientstartStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully start ASDC distribution client", "ASDC", "start", null); + + + this.changeControllerStatus (ASDCControllerStatus.IDLE); + LOGGER.info (MessageEnum.ASDC_INIT_ASDC_CLIENT_SUC, "ASDC", "changeControllerStatus",""); + } + + /** + * This method closes the ASDC Controller and the ASDC Client. + * + * @throws ASDCControllerException It throws an exception if the ASDC Client cannot be closed because + * it's currently BUSY in processing notifications. + */ + public void closeASDC () throws ASDCControllerException { + + MsoLogger.setServiceName ("CloseController"); + if (this.getControllerStatus () == ASDCControllerStatus.BUSY) { + throw new ASDCControllerException ("Cannot close the ASDC controller as it's currently in BUSY state"); + } + if (this.distributionClient != null) { + this.distributionClient.stop (); + // If auto managed we can set it to Null, ASDCController controls it. + // In the other case the client of this class has specified it, so we can't reset it + if (isAsdcClientAutoManaged) { + // Next init will initialize it with a new ASDC Client + this.distributionClient = null; + } + + } + this.changeControllerStatus (ASDCControllerStatus.STOPPED); + } + + private boolean checkResourceAlreadyDeployed (VfResourceStructure resource) throws ArtifactInstallerException { + + + if (toscaInstaller.isResourceAlreadyDeployed (resource)) { + LOGGER.info (MessageEnum.ASDC_ARTIFACT_ALREADY_EXIST, + resource.getResourceInstance().getResourceInstanceName(), + resource.getResourceInstance().getResourceUUID(), + resource.getResourceInstance().getResourceName(), "", ""); + + this.sendDeployNotificationsForResource(resource,DistributionStatusEnum.ALREADY_DOWNLOADED,null); + this.sendDeployNotificationsForResource(resource,DistributionStatusEnum.ALREADY_DEPLOYED,null); + + return true; + } else { + return false; + } + } + + + + private IDistributionClientDownloadResult downloadTheArtifact (IArtifactInfo artifact, + String distributionId) throws ASDCDownloadException { + + LOGGER.debug ("Trying to download the artifact : " + artifact.getArtifactURL () + + UUID_PARAM + + artifact.getArtifactUUID () + + ")"); + IDistributionClientDownloadResult downloadResult; + + + try { + downloadResult = distributionClient.download (artifact); + if (null == downloadResult) { + LOGGER.info (MessageEnum.ASDC_ARTIFACT_NULL, artifact.getArtifactUUID (), "", ""); + return downloadResult; + } + } catch (RuntimeException e) { + LOGGER.debug ("Not able to download the artifact due to an exception: " + artifact.getArtifactURL ()); + this.sendASDCNotification (NotificationType.DOWNLOAD, + artifact.getArtifactURL (), + asdcConfig.getConsumerID (), + distributionId, + DistributionStatusEnum.DOWNLOAD_ERROR, + e.getMessage (), + System.currentTimeMillis ()); + + throw new ASDCDownloadException ("Exception caught when downloading the artifact", e); + } + + if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult ())) { + + LOGGER.info (MessageEnum.ASDC_ARTIFACT_DOWNLOAD_SUC, + artifact.getArtifactURL (), + artifact.getArtifactUUID (), + String.valueOf (downloadResult.getArtifactPayload ().length), "", ""); + + } else { + + LOGGER.error (MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL, + artifact.getArtifactName (), + artifact.getArtifactURL (), + artifact.getArtifactUUID (), + downloadResult.getDistributionMessageResult (), "", "", MsoLogger.ErrorCode.DataError, "ASDC artifact download fail"); + + this.sendASDCNotification (NotificationType.DOWNLOAD, + artifact.getArtifactURL (), + asdcConfig.getConsumerID (), + distributionId, + DistributionStatusEnum.DOWNLOAD_ERROR, + downloadResult.getDistributionMessageResult (), + System.currentTimeMillis ()); + + throw new ASDCDownloadException ("Artifact " + artifact.getArtifactName () + + " could not be downloaded from ASDC URL " + + artifact.getArtifactURL () + + UUID_PARAM + + artifact.getArtifactUUID () + + ")" + + System.lineSeparator () + + "Error message is " + + downloadResult.getDistributionMessageResult () + + System.lineSeparator ()); + + } + + this.sendASDCNotification (NotificationType.DOWNLOAD, + artifact.getArtifactURL (), + asdcConfig.getConsumerID (), + distributionId, + DistributionStatusEnum.DOWNLOAD_OK, + null, + System.currentTimeMillis ()); + return downloadResult; + + } + + private void writeArtifactToFile (IArtifactInfo artifact, + IDistributionClientDownloadResult resultArtifact) { + + LOGGER.debug ("Trying to write artifact to file : " + artifact.getArtifactURL () + + UUID_PARAM + + artifact.getArtifactUUID () + + ")"); + + byte[] payloadBytes = resultArtifact.getArtifactPayload(); + + try (FileOutputStream outFile = new FileOutputStream(System.getProperty("mso.config.path") + "/ASDC" + "/" + artifact.getArtifactName())) { + LOGGER.info(MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF, "***WRITE FILE ARTIFACT NAME", "ASDC", artifact.getArtifactName()); + outFile.write(payloadBytes, 0, payloadBytes.length); + outFile.close(); + } catch (Exception e) { + LOGGER.debug("Exception :",e); + LOGGER.error(MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL, + artifact.getArtifactName (), + artifact.getArtifactURL (), + artifact.getArtifactUUID (), + resultArtifact.getDistributionMessageResult (), "", "", MsoLogger.ErrorCode.DataError, "ASDC write to file failed"); + } + + } + + + private void sendDeployNotificationsForResource(VfResourceStructure vfResourceStructure,DistributionStatusEnum distribStatus, String errorReason) { + + for (IArtifactInfo artifactInfo : vfResourceStructure.getResourceInstance().getArtifacts()) { + + if ((DistributionStatusEnum.DEPLOY_OK.equals(distribStatus) && !artifactInfo.getArtifactType().equalsIgnoreCase("OTHER") && !vfResourceStructure.isAlreadyDeployed()) + // This could be NULL if the artifact is a VF module artifact, this won't be present in the MAP + && vfResourceStructure.getArtifactsMapByUUID().get(artifactInfo.getArtifactUUID()) != null + && vfResourceStructure.getArtifactsMapByUUID().get(artifactInfo.getArtifactUUID()).getDeployedInDb() == 0) { + this.sendASDCNotification (NotificationType.DEPLOY, + artifactInfo.getArtifactURL (), + asdcConfig.getConsumerID (), + vfResourceStructure.getNotification().getDistributionID(), + DistributionStatusEnum.DEPLOY_ERROR, + "The artifact has not been used by the modules defined in the resource", + System.currentTimeMillis ()); + } else { + this.sendASDCNotification (NotificationType.DEPLOY, + artifactInfo.getArtifactURL (), + asdcConfig.getConsumerID (), + vfResourceStructure.getNotification().getDistributionID(), + distribStatus, + errorReason, + System.currentTimeMillis ()); + } + } + } + + private void sendCsarDeployNotification(INotificationData iNotif, VfResourceStructure resourceStructure, ToscaResourceStructure toscaResourceStructure, boolean deploySuccessful, String errorReason) { + + IArtifactInfo csarArtifact = toscaResourceStructure.getToscaArtifact(); + + if(deploySuccessful){ + + this.sendASDCNotification (NotificationType.DEPLOY, + csarArtifact.getArtifactURL (), + asdcConfig.getConsumerID (), + resourceStructure.getNotification().getDistributionID(), + DistributionStatusEnum.DEPLOY_OK, + errorReason, + System.currentTimeMillis ()); + + } else { + + this.sendASDCNotification (NotificationType.DEPLOY, + csarArtifact.getArtifactURL (), + asdcConfig.getConsumerID (), + resourceStructure.getNotification().getDistributionID(), + DistributionStatusEnum.DEPLOY_ERROR, + errorReason, + System.currentTimeMillis ()); + + } + } + + private void deployResourceStructure (VfResourceStructure resourceStructure, ToscaResourceStructure toscaResourceStructure) throws ArtifactInstallerException { + + LOGGER.info (MessageEnum.ASDC_START_DEPLOY_ARTIFACT, resourceStructure.getResourceInstance().getResourceInstanceName(), resourceStructure.getResourceInstance().getResourceUUID(), "ASDC"); + try { + String resourceType = resourceStructure.getResourceInstance().getResourceType(); + String category = resourceStructure.getResourceInstance().getCategory(); + if("VF".equals(resourceType) && !"Allotted Resource".equalsIgnoreCase(category)){ + resourceStructure.createVfModuleStructures(); + } + toscaInstaller.installTheResource(toscaResourceStructure, resourceStructure); + + } catch (ArtifactInstallerException e) { + LOGGER.info (MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL, + resourceStructure.getResourceInstance().getResourceName(), + resourceStructure.getResourceInstance().getResourceUUID(), + String.valueOf (resourceStructure.getVfModuleStructure().size()), "ASDC", "deployResourceStructure"); + sendDeployNotificationsForResource(resourceStructure,DistributionStatusEnum.DEPLOY_ERROR,e.getMessage()); + throw e; + } + + if (resourceStructure.isDeployedSuccessfully() || toscaResourceStructure.isDeployedSuccessfully()) { + LOGGER.info (MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC, + resourceStructure.getResourceInstance().getResourceName(), + resourceStructure.getResourceInstance().getResourceUUID(), + String.valueOf (resourceStructure.getVfModuleStructure().size()), "ASDC", "deployResourceStructure"); + sendDeployNotificationsForResource(resourceStructure,DistributionStatusEnum.DEPLOY_OK ,null); + } + + } + + + private enum NotificationType { + DOWNLOAD, DEPLOY + } + + private void sendASDCNotification (NotificationType notificationType, + String artifactURL, + String consumerID, + String distributionID, + DistributionStatusEnum status, + String errorReason, + long timestamp) { + + String event = "Sending " + notificationType.name () + + "(" + + status.name () + + ")" + + " notification to ASDC for artifact:" + + artifactURL; + + if (errorReason != null) { + event=event+"("+errorReason+")"; + } + LOGGER.info (MessageEnum.ASDC_SEND_NOTIF_ASDC, notificationType.name (), status.name (), artifactURL, "ASDC", "sendASDCNotification"); + LOGGER.debug (event); + + long subStarttime = System.currentTimeMillis (); + String action = ""; + try { + IDistributionStatusMessage message = new DistributionStatusMessage (artifactURL, + consumerID, + distributionID, + status, + timestamp); + + switch (notificationType) { + case DOWNLOAD: + if (errorReason != null) { + this.distributionClient.sendDownloadStatus (message, errorReason); + } else { + this.distributionClient.sendDownloadStatus (message); + } + action = "sendDownloadStatus"; + break; + case DEPLOY: + if (errorReason != null) { + this.distributionClient.sendDeploymentStatus (message, errorReason); + } else { + this.distributionClient.sendDeploymentStatus (message); + } + action = "sendDeploymentdStatus"; + break; + default: + break; + } + } catch (RuntimeException e) { + LOGGER.warn (MessageEnum.ASDC_SEND_NOTIF_ASDC_EXEC, "ASDC", "sendASDCNotification", MsoLogger.ErrorCode.SchemaError, "RuntimeException - sendASDCNotification", e); + } + LOGGER.recordMetricEvent (subStarttime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully sent notification to ASDC", "ASDC", action, null); + } + + private void sendFinalDistributionStatus ( + String distributionID, + DistributionStatusEnum status, + String errorReason) { + + + LOGGER.debug ("Enter sendFinalDistributionStatus with DistributionID " + distributionID + " and Status of " + status.name() + " and ErrorReason " + errorReason); + + long subStarttime = System.currentTimeMillis (); + try { + + + IFinalDistrStatusMessage finalDistribution = new FinalDistributionStatusMessage(distributionID,status,subStarttime, asdcConfig.getConsumerID()); + + if(errorReason == null){ + this.distributionClient.sendFinalDistrStatus(finalDistribution); + }else{ + this.distributionClient.sendFinalDistrStatus(finalDistribution, errorReason); + } + + + } catch (RuntimeException e) { + LOGGER.debug ("Exception caught in sendFinalDistributionStatus " + e.getMessage()); + LOGGER.warn (MessageEnum.ASDC_SEND_NOTIF_ASDC_EXEC, "ASDC", "sendASDCNotification", MsoLogger.ErrorCode.SchemaError, "RuntimeException - sendASDCNotification", e); + } + LOGGER.recordMetricEvent (subStarttime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully sent Final notification to ASDC", "ASDC", null, null); + } + + public void treatNotification (INotificationData iNotif) { + + int noOfArtifacts = 0; + + + for (IResourceInstance resource : iNotif.getResources ()) { + noOfArtifacts += resource.getArtifacts ().size (); + } + LOGGER.info (MessageEnum.ASDC_RECEIVE_CALLBACK_NOTIF, + String.valueOf (noOfArtifacts), + iNotif.getServiceUUID (), "ASDC"); + + try { + LOGGER.debug(ASDCNotificationLogging.dumpASDCNotification(iNotif)); + LOGGER.info(MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF, iNotif.getServiceUUID(), "ASDC", "treatNotification"); + this.changeControllerStatus(ASDCControllerStatus.BUSY); + toscaInstaller.processWatchdog(iNotif.getDistributionID(),iNotif.getServiceUUID()); + + // Process only the Resource artifacts in MSO + this.processResourceNotification(iNotif); + + //******************************************************************************************************** + //Start Watchdog loop and wait for all components to complete before reporting final status back. + // **If timer expires first then we will report a Distribution Error back to ASDC + //******************************************************************************************************** + long initialStartTime = System.currentTimeMillis(); + boolean componentsComplete = false; + String distributionStatus = null; + String watchdogError = null; + String overallStatus = null; + int watchDogTimeout = asdcConfig.getWatchDogTimeout() * 1000; + boolean isDeploySuccess = false; + + while(!componentsComplete && (System.currentTimeMillis() - initialStartTime) < watchDogTimeout) + { + + try{ + distributionStatus = wd.getOverallDistributionStatus(iNotif.getDistributionID()); + Thread.sleep(watchDogTimeout / 10); + }catch(Exception e){ + LOGGER.debug ("Exception in Watchdog Loop " + e.getMessage()); + Thread.sleep(watchDogTimeout / 10); + } + + if(distributionStatus != null && !distributionStatus.equalsIgnoreCase(DistributionStatus.INCOMPLETE.name())){ + + if(distributionStatus.equalsIgnoreCase(DistributionStatus.SUCCESS.name())){ + isDeploySuccess = true; + overallStatus = DistributionStatusEnum.DISTRIBUTION_COMPLETE_OK.name(); + }else{ + overallStatus = DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name(); + } + componentsComplete = true; + } + } + + if(!componentsComplete){ + LOGGER.debug("Timeout of " + watchDogTimeout + " seconds was reached before all components reported status"); + watchdogError = "Timeout occurred while waiting for all components to report status"; + overallStatus = DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name(); + } + + if(distributionStatus == null){ + overallStatus = DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name(); + LOGGER.debug("DistributionStatus is null for DistributionId: " + iNotif.getDistributionID()); + } + + try { + wd.executePatchAAI(iNotif.getDistributionID(), iNotif.getServiceInvariantUUID(), overallStatus); + LOGGER.debug ("A&AI Updated succefully with Distribution Status!"); + } + catch(Exception e) { + LOGGER.debug ("Exception in Watchdog executePatchAAI(): " + e.getMessage()); + watchdogError = "Error calling A&AI " + e.getMessage(); + if(e.getCause() != null) { + LOGGER.debug ("Exception caused by: " + e.getCause().getMessage()); + } + } + + + if(isDeploySuccess && watchdogError == null){ + sendFinalDistributionStatus(iNotif.getDistributionID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_OK, null); + WatchdogDistributionStatus wds = new WatchdogDistributionStatus(iNotif.getDistributionID()); + wds.setDistributionIdStatus(DistributionStatusEnum.DISTRIBUTION_COMPLETE_OK.toString()); + wdsRepo.save(wds); + } else { + sendFinalDistributionStatus(iNotif.getDistributionID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR, watchdogError); + WatchdogDistributionStatus wds = new WatchdogDistributionStatus(iNotif.getDistributionID()); + wds.setDistributionIdStatus(DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.toString()); + wdsRepo.save(wds); + } + + + + } catch (Exception e) { + LOGGER.error (MessageEnum.ASDC_GENERAL_EXCEPTION_ARG, + "Unexpected exception caught during the notification processing", "ASDC", "treatNotification", MsoLogger.ErrorCode.SchemaError, "RuntimeException in treatNotification", + e); + + try { + wd.executePatchAAI(iNotif.getDistributionID(), iNotif.getServiceInvariantUUID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name()); + LOGGER.debug ("A&AI Updated succefully with Distribution Status of " + DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name()); + } + catch(Exception aaiException) { + LOGGER.debug ("Exception in executePatchAAI(): " + aaiException.getMessage()); + if(aaiException.getCause() != null) { + LOGGER.debug ("Exception caused by: " + aaiException.getCause().getMessage()); + } + } + + sendFinalDistributionStatus(iNotif.getDistributionID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR, e.getMessage()); + + WatchdogDistributionStatus wds = new WatchdogDistributionStatus(iNotif.getDistributionID()); + wds.setDistributionIdStatus(DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.toString()); + wdsRepo.save(wds); + + } finally { + this.changeControllerStatus (ASDCControllerStatus.IDLE); + } + } + + private void processResourceNotification (INotificationData iNotif) { + // For each artifact, create a structure describing the VFModule in a ordered flat level + VfResourceStructure resourceStructure = null; + ToscaResourceStructure toscaResourceStructure = new ToscaResourceStructure(); + boolean deploySuccessful = true; + String errorMessage = null; + + try { + + this.processCsarServiceArtifacts(iNotif, toscaResourceStructure); + + for (IResourceInstance resource : iNotif.getResources()){ + + resourceStructure = new VfResourceStructure(iNotif,resource); + + String resourceType = resourceStructure.getResourceInstance().getResourceType(); + String category = resourceStructure.getResourceInstance().getCategory(); + + LOGGER.debug("Processing Resource Type: " + resourceType + " and Model UUID: " + resourceStructure.getResourceInstance().getResourceUUID()); + + if("VF".equals(resourceType) && !"Allotted Resource".equalsIgnoreCase(category)){ + + for (IArtifactInfo artifact : resource.getArtifacts()) { + IDistributionClientDownloadResult resultArtifact = this.downloadTheArtifact(artifact, + iNotif.getDistributionID()); + if (resultArtifact != null) { + if (ASDCConfiguration.VF_MODULES_METADATA.equals(artifact.getArtifactType())) { + LOGGER.debug("VF_MODULE_ARTIFACT: "+new String(resultArtifact.getArtifactPayload(),"UTF-8")); + LOGGER.debug(ASDCNotificationLogging.dumpVfModuleMetaDataList(resourceStructure.decodeVfModuleArtifact(resultArtifact.getArtifactPayload()))); + } + resourceStructure.addArtifactToStructure(distributionClient,artifact, resultArtifact); + } + } + } + } + try{ + + //Deploy All resources and artifacts + LOGGER.debug("Preparing to deploy Service: " + iNotif.getServiceUUID()); + if(resourceStructure == null){ + resourceStructure = new VfResourceStructure(iNotif,new ResourceInstance()); + } + this.deployResourceStructure(resourceStructure, toscaResourceStructure); + + + } catch(ArtifactInstallerException e){ + deploySuccessful = false; + errorMessage = e.getMessage(); + } + + this.sendCsarDeployNotification(iNotif, resourceStructure, toscaResourceStructure, deploySuccessful, errorMessage); + + } catch (ASDCDownloadException | UnsupportedEncodingException e) { + LOGGER.error(MessageEnum.ASDC_GENERAL_EXCEPTION_ARG, + "Exception caught during Installation of artifact", "ASDC", "processResourceNotification", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in processResourceNotification", e); + } + } + private void processCsarServiceArtifacts (INotificationData iNotif, ToscaResourceStructure toscaResourceStructure) { + + List serviceArtifacts = iNotif.getServiceArtifacts(); + + for(IArtifactInfo artifact : serviceArtifacts){ + + if(artifact.getArtifactType().equals(ASDCConfiguration.TOSCA_CSAR)){ + + try{ + + toscaResourceStructure.setToscaArtifact(artifact); + + IDistributionClientDownloadResult resultArtifact = this.downloadTheArtifact(artifact,iNotif.getDistributionID()); + + writeArtifactToFile(artifact, resultArtifact); + + toscaResourceStructure.updateResourceStructure(artifact); + + toscaResourceStructure.setServiceVersion(iNotif.getServiceVersion()); + + LOGGER.debug(ASDCNotificationLogging.dumpCSARNotification(iNotif, toscaResourceStructure)); + + + } catch(Exception e){ + LOGGER.error(MessageEnum.ASDC_GENERAL_EXCEPTION_ARG, + "Exception caught during processCsarServiceArtifacts", "ASDC", "processCsarServiceArtifacts", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in processCsarServiceArtifacts", e); + } + } + + } + } + + private static final String UNKNOWN="Unknown"; + + /** + * @return the address of the ASDC we are connected to. + */ + public String getAddress () { + if (asdcConfig != null) { + return asdcConfig.getAsdcAddress (); + } + return UNKNOWN; + } + + /** + * @return the environment name of the ASDC we are connected to. + */ + public String getEnvironment () { + if (asdcConfig != null) { + return asdcConfig.getEnvironmentName (); + } + return UNKNOWN; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCControllerStatus.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCControllerStatus.java new file mode 100644 index 0000000000..e358fee4a1 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCControllerStatus.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + + + +public enum ASDCControllerStatus { + STOPPED, IDLE, BUSY +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCNotificationCallBack.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCNotificationCallBack.java new file mode 100644 index 0000000000..ab5b7aa39e --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCNotificationCallBack.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + +import org.onap.sdc.api.consumer.INotificationCallback; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.so.logger.MsoLogger; +import org.onap.so.utils.UUIDChecker; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * Inner class for Notification callback + * + * + */ +@Component +public final class ASDCNotificationCallBack implements INotificationCallback { + + @Autowired + private ASDCController asdcController; + + protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC,ASDCNotificationCallBack.class); + + /** + * This method can be called multiple times at the same moment. + * The controller must be thread safe ! + */ + @Override + public void activateCallback (INotificationData iNotif) { + long startTime = System.currentTimeMillis (); + UUIDChecker.generateUUID (LOGGER); + MsoLogger.setServiceName ("NotificationHandler"); + MsoLogger.setLogContext (iNotif.getDistributionID (), iNotif.getServiceUUID ()); + String event = "Receive a callback notification in ASDC, nb of resources: " + iNotif.getResources ().size (); + LOGGER.debug(event); + asdcController.treatNotification (iNotif); + LOGGER.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Completed the treatment of the notification"); + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCStatusCallBack.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCStatusCallBack.java new file mode 100644 index 0000000000..cbacd88870 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCStatusCallBack.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + +import org.onap.sdc.api.consumer.IStatusCallback; +import org.onap.sdc.api.notification.IStatusData; +import org.onap.sdc.utils.DistributionStatusEnum; +import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; +import org.onap.so.asdc.installer.heat.ToscaResourceInstaller; +import org.onap.so.db.request.beans.WatchdogDistributionStatus; +import org.onap.so.db.request.data.repository.WatchdogDistributionStatusRepository; +import org.onap.so.logger.MsoLogger; +import org.onap.so.utils.UUIDChecker; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public final class ASDCStatusCallBack implements IStatusCallback { + + @Autowired + private ToscaResourceInstaller toscaInstaller; + + protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC,ASDCStatusCallBack.class); + + @Autowired + private WatchdogDistributionStatusRepository watchdogDistributionStatusRepository; + + @Override + public void activateCallback (IStatusData iStatus) { + long startTime = System.currentTimeMillis (); + UUIDChecker.generateUUID (LOGGER); + MsoLogger.setServiceName ("ASDCStatusCallBack"); + MsoLogger.setLogContext (iStatus.getDistributionID (), iStatus.getComponentName()); + String event = "Receive a callback componentStatus in ASDC, for componentName: " + iStatus.getComponentName() + " and status of " + iStatus.getStatus() + " distributionID of " + iStatus.getDistributionID(); + + try{ + + if(iStatus.getStatus() != null){ + if(iStatus.getStatus().equals(DistributionStatusEnum.COMPONENT_DONE_OK) || iStatus.getStatus().equals(DistributionStatusEnum.COMPONENT_DONE_ERROR)) { + WatchdogDistributionStatus watchdogDistributionStatus = watchdogDistributionStatusRepository.findOne(iStatus.getDistributionID ()); + if(watchdogDistributionStatus==null){ + watchdogDistributionStatus = new WatchdogDistributionStatus(); + watchdogDistributionStatus.setDistributionId(iStatus.getDistributionID ()); + watchdogDistributionStatusRepository.save(watchdogDistributionStatus); + } + LOGGER.debug(event); + toscaInstaller.installTheComponentStatus(iStatus); + + } + } + }catch(ArtifactInstallerException e){ + LOGGER.error("Error in ASDCStatusCallback " + e.getMessage(),e); + LOGGER.debug("Error in ASDCStatusCallback " + e.getMessage()); + } + LOGGER.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Completed the treatment of the notification"); + } +} \ No newline at end of file diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/DistributionStatusMessage.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/DistributionStatusMessage.java new file mode 100644 index 0000000000..db2d2c3bd3 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/DistributionStatusMessage.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + + +import org.onap.sdc.api.consumer.IDistributionStatusMessage; +import org.onap.sdc.utils.DistributionStatusEnum; + +public class DistributionStatusMessage implements IDistributionStatusMessage { + + private String artifactURL; + + private String consumerID; + + private String distributionID; + + private DistributionStatusEnum distributionStatus; + + private long timestamp; + + public DistributionStatusMessage (final String artifactUrl, final String consumerId,final String distributionId, final DistributionStatusEnum distributionStatusEnum, final long timestampL) { + artifactURL = artifactUrl; + consumerID = consumerId; + distributionID = distributionId; + distributionStatus = distributionStatusEnum; + timestamp = timestampL; + } + + @Override + public String getArtifactURL() { + + return artifactURL; + } + + @Override + public String getConsumerID() { + + return consumerID; + } + + @Override + public String getDistributionID() { + + return distributionID; + } + + @Override + public DistributionStatusEnum getStatus() { + + return distributionStatus; + } + + @Override + public long getTimestamp() { + + return timestamp; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/FinalDistributionStatusMessage.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/FinalDistributionStatusMessage.java new file mode 100644 index 0000000000..376b678c0e --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/FinalDistributionStatusMessage.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + +import org.onap.sdc.api.consumer.IFinalDistrStatusMessage; +import org.onap.sdc.utils.DistributionStatusEnum; + +public class FinalDistributionStatusMessage implements IFinalDistrStatusMessage{ + + private String componentName; + + private String consumerID; + + private String distributionID; + + private DistributionStatusEnum status; + + private long timestamp; + + public FinalDistributionStatusMessage (String distributionId, final DistributionStatusEnum distributionStatusEnum, final long timestampL, String consumerId) { + //componentName = componentname; + consumerID = consumerId; + distributionID = distributionId; + status = distributionStatusEnum; + timestamp = timestampL; + } + + public DistributionStatusEnum getStatus() { + return status; + } + + public void setStatus(DistributionStatusEnum status) { + this.status = status; + } + + public String getDistributionID() { + return distributionID; + } + + public void setDistributionID(String distributionID) { + this.distributionID = distributionID; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public String getComponentName() { + return componentName; + } + + public void setComponentName(String componentName) { + this.componentName = componentName; + } + + public String getConsumerID() { + return consumerID; + } + + public void setConsumerID(String consumerID) { + this.consumerID = consumerID; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ResourceInstance.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ResourceInstance.java new file mode 100644 index 0000000000..cfdff85bc3 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ResourceInstance.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client; + +import java.util.ArrayList; + +import org.onap.sdc.api.notification.IResourceInstance; + +final class ResourceInstance implements IResourceInstance { + + @Override + public String getResourceInstanceName(){ + return new String(); + } + + @Override + public String getResourceName(){ + return new String(); + } + + @Override + public String getResourceVersion(){ + return new String(); + } + + @Override + public String getResourceType(){ + return new String(); + } + + @Override + public String getResourceUUID(){ + return new String(); + } + + @Override + public java.util.List getArtifacts(){ + return new ArrayList(); + } + + @Override + public String getResourceInvariantUUID(){ + return new String(); + } + + @Override + public String getResourceCustomizationUUID(){ + return new String(); + } + + @Override + public String getCategory(){ + return new String(); + } + + @Override + public String getSubcategory(){ + return new String(); + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCControllerException.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCControllerException.java new file mode 100644 index 0000000000..98257f761c --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCControllerException.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.exceptions; + + +/** + * Exception of the ASDC controller. + */ +public class ASDCControllerException extends Exception { + + /** + * serialization id. + */ + private static final long serialVersionUID = -4236006447255525130L; + + /** + * @param message The message to dump + * @param cause The Throwable cause object + */ + public ASDCControllerException (final String message) { + super (message); + + } + + /** + * @param message The message to dump + * @param cause The Throwable cause object + */ + public ASDCControllerException (final String message, final Throwable cause) { + super (message, cause); + + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCDownloadException.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCDownloadException.java new file mode 100644 index 0000000000..f4e0bf0327 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCDownloadException.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.exceptions; + + +/** + * Exception during download from ASDC. + */ +public class ASDCDownloadException extends Exception { + + /** + * serialization id. + */ + private static final long serialVersionUID = -5276848693231134901L; + + /** + * @param message The message to dump + * @param cause The Throwable cause object + */ + public ASDCDownloadException (final String message) { + super (message); + + } + + /** + * @param message The message to dump + * @param cause The Throwable cause object + */ + public ASDCDownloadException (final String message, final Throwable cause) { + super (message, cause); + + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCParametersException.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCParametersException.java new file mode 100644 index 0000000000..aecb9223c9 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCParametersException.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.exceptions; + + +/** + * Exception of the ASDC controller. + */ +public class ASDCParametersException extends Exception { + + /** + * serialization id. + */ + private static final long serialVersionUID = 8425657297510362736L; + + /** + * @param message The message to dump + * @param cause The Throwable cause object + */ + public ASDCParametersException (final String message) { + super (message); + + } + + /** + * @param message The message to dump + * @param cause The Throwable cause object + */ + public ASDCParametersException (final String message, final Throwable cause) { + super (message, cause); + + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerException.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerException.java new file mode 100644 index 0000000000..78ccb5da0a --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerException.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.exceptions; + + +/** + * Exception during artifact installation. + */ +public class ArtifactInstallerException extends Exception { + + /** + * serialization id. + */ + private static final long serialVersionUID = 4095937499475915021L; + + /** + * @param message The message to dump + * @param cause The Throwable cause object + */ + public ArtifactInstallerException (final String message) { + super (message); + + } + + /** + * @param message The message to dump + * @param cause The Throwable cause object + */ + public ArtifactInstallerException (final String message, final Throwable cause) { + super (message, cause); + + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImpl.java new file mode 100644 index 0000000000..7dab49f82a --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImpl.java @@ -0,0 +1,171 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.emulators; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.sdc.api.notification.IArtifactInfo; + +public class ArtifactInfoImpl implements IArtifactInfo { + + private String artifactName; + private String artifactType; + private String artifactURL; + private String artifactChecksum; + private String artifactDescription; + private Integer artifactTimeout; + private String artifactVersion; + private String artifactUUID; + private String generatedFromUUID; + private ArtifactInfoImpl generatedArtifact; + private List relatedArtifactsInfo; + private List relatedArtifactsImpl; + ArtifactInfoImpl(){} + + private ArtifactInfoImpl(IArtifactInfo iArtifactInfo){ + artifactName = iArtifactInfo.getArtifactName(); + artifactType = iArtifactInfo.getArtifactType(); + artifactURL = iArtifactInfo.getArtifactURL(); + artifactChecksum = iArtifactInfo.getArtifactChecksum(); + artifactDescription = iArtifactInfo.getArtifactDescription(); + artifactTimeout = iArtifactInfo.getArtifactTimeout(); + artifactVersion = iArtifactInfo.getArtifactVersion(); + artifactUUID = iArtifactInfo.getArtifactUUID(); + generatedArtifact = (ArtifactInfoImpl) iArtifactInfo.getGeneratedArtifact(); + relatedArtifactsInfo = iArtifactInfo.getRelatedArtifacts(); + } + + public static List convertToArtifactInfoImpl(List list){ + List ret = new ArrayList(); + if( list != null ){ + for(IArtifactInfo artifactInfo : list ){ + ret.add(new ArtifactInfoImpl(artifactInfo)); + } + } + return ret; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public Integer getArtifactTimeout() { + return artifactTimeout; + } + + public void setArtifactTimeout(Integer artifactTimeout) { + this.artifactTimeout = artifactTimeout; + } + + @Override + public String toString() { + return "BaseArtifactInfoImpl [artifactName=" + artifactName + + ", artifactType=" + artifactType + ", artifactURL=" + + artifactURL + ", artifactChecksum=" + artifactChecksum + + ", artifactDescription=" + artifactDescription + + ", artifactVersion=" + artifactVersion + + ", artifactUUID=" + artifactUUID + + ", artifactTimeout=" + artifactTimeout + "]"; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getGeneratedFromUUID() { + return generatedFromUUID; + } + + public void setGeneratedFromUUID(String generatedFromUUID) { + this.generatedFromUUID = generatedFromUUID; + } + + @Override + public ArtifactInfoImpl getGeneratedArtifact() { + return generatedArtifact; + } + + public void setGeneratedArtifact(ArtifactInfoImpl generatedArtifact) { + this.generatedArtifact = generatedArtifact; + } + + @Override + public List getRelatedArtifacts(){ + List temp = new ArrayList(); + if( relatedArtifactsInfo != null ){ + temp.addAll(relatedArtifactsImpl); + } + return temp; + } + + public void setRelatedArtifacts(List relatedArtifacts) { + this.relatedArtifactsImpl = relatedArtifacts; + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulator.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulator.java new file mode 100644 index 0000000000..4f76d3fa17 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulator.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.emulators; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.LinkedList; +import java.util.List; + +import org.onap.so.asdc.installer.IVfModuleData; +import org.onap.so.logger.MsoLogger; +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.consumer.IComponentDoneStatusMessage; +import org.onap.sdc.api.consumer.IConfiguration; +import org.onap.sdc.api.consumer.IDistributionStatusMessage; +import org.onap.sdc.api.consumer.IFinalDistrStatusMessage; +import org.onap.sdc.api.consumer.INotificationCallback; +import org.onap.sdc.api.consumer.IStatusCallback; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.IVfModuleMetadata; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.impl.DistributionClientDownloadResultImpl; +import org.onap.sdc.impl.DistributionClientResultImpl; +import org.onap.sdc.utils.DistributionActionResultEnum; + +public class DistributionClientEmulator implements IDistributionClient { + + private String resourcePath; + + private List listVFModuleMetaData; + + private List distributionMessageReceived = new LinkedList<>(); + + + private static final MsoLogger logger = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC,DistributionClientEmulator.class ); + + public DistributionClientEmulator() { + } + + public DistributionClientEmulator(String notifFolderInResource) { + resourcePath = notifFolderInResource; + } + + public List getDistributionMessageReceived() { + return distributionMessageReceived; + } + + @Override + public List decodeVfModuleArtifact(byte[] arg0) { + return null; + } + + public String getResourcePath() { + return resourcePath; + } + + public void setResourcePath(String resourcePath) { + this.resourcePath = resourcePath; + } + + public List getListVFModuleMetaData() { + return listVFModuleMetaData; + } + + @Override + public IDistributionClientDownloadResult download (IArtifactInfo arg0) { + + String filename = arg0.getArtifactURL(); + + byte[] inputStream=null; + try { + inputStream = getData(filename); + } catch (IOException e) { + e.printStackTrace(); + logger.debug("InputStream is NULL for:"+ resourcePath + filename); + } + + return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name(),arg0.getArtifactName(),inputStream); + } + + private byte[] getData(String filename) throws IOException { + return Files.readAllBytes(Paths.get(resourcePath + filename)); + } + + @Override + public IConfiguration getConfiguration() { + return null; + } + + @Override + public IDistributionClientResult init(IConfiguration arg0, INotificationCallback arg1) { + return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + } + + @Override + public IDistributionClientResult init(IConfiguration arg0, INotificationCallback arg1, IStatusCallback arg2) { + return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + } + + @Override + public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage arg0) { + this.distributionMessageReceived.add(arg0); + return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + } + + @Override + public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage arg0, String arg1) { + this.distributionMessageReceived.add(arg0); + return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + } + + @Override + public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage arg0) { + this.distributionMessageReceived.add(arg0); + return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + } + + @Override + public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage arg0, String arg1) { + this.distributionMessageReceived.add(arg0); + return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + } + + @Override + public IDistributionClientResult start() { + return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + } + + @Override + public IDistributionClientResult stop() { + return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + + } + + @Override + public IDistributionClientResult updateConfiguration(IConfiguration arg0) { + return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); + } + + @Override + public IDistributionClientResult sendComponentDoneStatus( + IComponentDoneStatusMessage arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public IDistributionClientResult sendFinalDistrStatus( + IFinalDistrStatusMessage arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public IDistributionClientResult sendComponentDoneStatus( + IComponentDoneStatusMessage arg0, String arg1) { + // TODO Auto-generated method stub + return null; + } + + @Override + public IDistributionClientResult sendFinalDistrStatus( + IFinalDistrStatusMessage arg0, String arg1) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonStatusData.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonStatusData.java new file mode 100644 index 0000000000..58193dbee6 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonStatusData.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.emulators; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +import org.onap.sdc.api.notification.IStatusData; +import org.onap.sdc.utils.DistributionStatusEnum; + +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.databind.ObjectMapper; + + +public class JsonStatusData implements IStatusData { + + @JsonIgnore + private static ObjectMapper mapper = new ObjectMapper(); + + @JsonIgnore + private Map attributesMap = new HashMap<>(); + + public JsonStatusData() { + + } + + @Override + public String getErrorReason(){ + return "MSO FAILURE"; + } + + @Override + public String getDistributionID(){ + //return (String)this.attributesMap.get("distributionID"); + return "35120a87-1f82-4276-9735-f6de5a244d65"; + } + + @Override + public String getConsumerID(){ + //return (String)this.attributesMap.get("consumerID"); + return "mso.123456"; + } + + @Override + public String getComponentName(){ + //return (String)this.attributesMap.get("componentName"); + return "SDN-C"; + } + + @Override + public Long getTimestamp(){ + //return (String)this.attributesMap.get("timestamp"); + return null; + } + + @Override + public String getArtifactURL(){ + //return (String)this.attributesMap.get("artifactURL"); + return "/sdc/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml"; + } + + @Override + public DistributionStatusEnum getStatus(){ + //return (DistributionStatusEnum)this.attributesMap.get(DistributionStatusEnum.DEPLOY_OK); + return DistributionStatusEnum.COMPONENT_DONE_OK; + } + + /** + * Method instantiate a INotificationData implementation from a JSON file. + * + * @param notifFilePath The file path in String + * @return A JsonNotificationData instance + * @throws IOException in case of the file is not readable or not accessible + */ + public static JsonStatusData instantiateNotifFromJsonFile(String notifFilePath) throws IOException { + + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(notifFilePath + "status-structure.json"); + + //String fileLocation = System.getProperty("mso.config.path") + "notif-structure.json"; + + //String source = fileLocation; + //InputStream is = IOUtils.toInputStream(source, "UTF-8"); + + //String myString = IOUtils.toString(is, "UTF-8"); + + + //System.out.println(myString); + + if (is == null) { + //throw new FileExistsException("Resource Path does not exist: "+notifFilePath); + } + return mapper.readValue(is, JsonStatusData.class); + } + + @SuppressWarnings("unused") + @JsonAnySetter + public final void setAttribute(String attrName, Object attrValue) { + if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) { + this.attributesMap.put(attrName,attrValue); + } + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java new file mode 100644 index 0000000000..9202559868 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.emulators; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.onap.so.asdc.installer.IVfModuleData; + +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class JsonVfModuleMetaData implements IVfModuleData { + + @JsonProperty("artifacts") + private List artifacts; + @JsonProperty("properties") + //private List> properties = new ArrayList<>(); + private Map properties = new HashMap<>(); + + public Map getProperties() { + return properties; + } + + @JsonIgnore + private Map attributesMap = new HashMap<>(); + + @Override + public List getArtifacts() { + return artifacts; + } + + @Override + public String getVfModuleModelDescription() { + return (String)attributesMap.get("vfModuleModelDescription"); + } + + @Override + public String getVfModuleModelInvariantUUID() { + return (String)attributesMap.get("vfModuleModelInvariantUUID"); + } + + @Override + public String getVfModuleModelCustomizationUUID() { + return (String)attributesMap.get("vfModuleModelCustomizationUUID"); + } + + @Override + public String getVfModuleModelName() { + return (String)attributesMap.get("vfModuleModelName"); + } + + @Override + public String getVfModuleModelUUID() { + return (String)attributesMap.get("vfModuleModelUUID"); + } + + @Override + public String getVfModuleModelVersion() { + return (String)attributesMap.get("vfModuleModelVersion"); + } + + @Override + public boolean isBase() { + return (boolean)attributesMap.get("isBase"); + } + + @SuppressWarnings("unused") + @JsonAnySetter + public final void setAttribute(String attrName, Object attrValue) { + if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) { + this.attributesMap.put(attrName,attrValue); + } + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java new file mode 100644 index 0000000000..294221352c --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java @@ -0,0 +1,175 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.emulators; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.notification.IResourceInstance; +import org.springframework.stereotype.Component; + +@Component +public class NotificationDataImpl implements INotificationData { + + private String distributionID; + private String serviceName; + private String serviceVersion; + private String serviceUUID; + private String serviceDescription; + private String serviceInvariantUUID; + private List resources; + private List serviceArtifacts; + private String workloadContext; + + @Override + public String getDistributionID() { + return distributionID; + } + + @Override + public String getServiceName() { + return serviceName; + } + + @Override + public String getServiceVersion() { + return serviceVersion; + } + + @Override + public String getServiceUUID() { + return serviceUUID; + } + + public void setDistributionID(String distributionID) { + this.distributionID = distributionID; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public void setServiceVersion(String serviceVersion) { + this.serviceVersion = serviceVersion; + } + + public void setServiceUUID(String serviceUUID) { + this.serviceUUID = serviceUUID; + } + + + + public String getServiceDescription() { + return serviceDescription; + } + + public void setServiceDescription(String serviceDescription) { + this.serviceDescription = serviceDescription; + } + + @Override + public String getWorkloadContext() { + return workloadContext; + } + + @Override + public void setWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } + + @Override + public String toString() { + return "NotificationDataImpl [distributionID=" + distributionID + ", serviceName=" + serviceName + + ", serviceVersion=" + serviceVersion + ", serviceUUID=" + serviceUUID + ", serviceDescription=" + + serviceDescription + ", serviceInvariantUUID=" + serviceInvariantUUID + ", resources=" + resources + + ", serviceArtifacts=" + serviceArtifacts + ", workloadContext=" + workloadContext + "]"; + } + + @Override + public List getResources() { + List ret = new ArrayList(); + if( resources != null ){ + ret.addAll(resources); + } + return ret; + } + + public List getResourcesImpl(){ + return resources; + } + + List getServiceArtifactsImpl(){ + return serviceArtifacts; + } + + @Override + public List getServiceArtifacts() { + List temp = new ArrayList(); + if( serviceArtifacts != null ){ + temp.addAll(serviceArtifacts); + } + return temp; + } + + public void setServiceArtifacts(List relevantServiceArtifacts) { + serviceArtifacts = relevantServiceArtifacts; + + } + + @Override + public String getServiceInvariantUUID() { + return serviceInvariantUUID; + } + + + public void setServiceInvariantUUID(String serviceInvariantUUID) { + this.serviceInvariantUUID = serviceInvariantUUID; + } + @Override + public IArtifactInfo getArtifactMetadataByUUID(String artifactUUID){ + IArtifactInfo ret = findArtifactInfoByUUID(artifactUUID, serviceArtifacts); + if( ret == null && resources != null ){ + for( ResourceInfoImpl currResourceInstance : resources ){ + ret = findArtifactInfoByUUID(artifactUUID, currResourceInstance.getArtifactsImpl()); + if( ret != null ){ + break; + } + } + } + return ret; + + } + + private IArtifactInfo findArtifactInfoByUUID(String artifactUUID, List listToCheck) { + IArtifactInfo ret = null; + if( listToCheck != null ){ + for(IArtifactInfo curr: listToCheck ){ + if(curr.getArtifactUUID().equals(artifactUUID) ){ + ret = curr; + break; + } + } + } + return ret; + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java new file mode 100644 index 0000000000..eb4764dec1 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.emulators; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.IResourceInstance; + +public class ResourceInfoImpl implements IResourceInstance{ + ResourceInfoImpl (){} + private String resourceInstanceName; + private String resourceCustomizationUUID; + private String resourceName; + private String resourceVersion; + private String resourceType; + private String resourceUUID; + private String resourceInvariantUUID; + private String category; + private String subcategory; + private List artifacts; + + private ResourceInfoImpl(IResourceInstance resourceInstance){ + resourceInstanceName = resourceInstance.getResourceInstanceName(); + resourceCustomizationUUID = resourceInstance.getResourceCustomizationUUID(); + resourceName = resourceInstance.getResourceName(); + resourceVersion = resourceInstance.getResourceVersion(); + resourceType = resourceInstance.getResourceType(); + resourceUUID = resourceInstance.getResourceUUID(); + resourceInvariantUUID = resourceInstance.getResourceInvariantUUID(); + category = resourceInstance.getCategory(); + subcategory = resourceInstance.getSubcategory(); + artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(resourceInstance.getArtifacts()); + } + + public static List convertToJsonContainer(List resources){ + List buildResources = new ArrayList(); + if( resources != null ){ + for( IResourceInstance resourceInstance : resources ){ + buildResources.add(new ResourceInfoImpl(resourceInstance)); + } + } + return buildResources; + } + + @Override + public String getResourceInstanceName() { + return resourceInstanceName; + } + + public void setResourceInstanceName(String resourceInstanceName) { + this.resourceInstanceName = resourceInstanceName; + } + + @Override + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + @Override + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + @Override + public String getResourceType() { + return resourceType; + } + + public void setResoucreType(String resourceType) { + this.resourceType = resourceType; + } + + @Override + public String getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(String resourceUUID) { + this.resourceUUID = resourceUUID; + } + + @Override + public List getArtifacts() { + List temp = new ArrayList(); + if( artifacts != null ){ + temp.addAll(artifacts); + } + return temp; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + public List getArtifactsImpl(){ + return artifacts; + } + + @Override + public String getResourceInvariantUUID() { + return resourceInvariantUUID; + } + + public void setResourceInvariantUUID(String resourceInvariantUUID) { + this.resourceInvariantUUID = resourceInvariantUUID; + } + public String getResourceCustomizationUUID() { + return resourceCustomizationUUID; + } + + public void setResourceCustomizationUUID(String resourceCustomizationUUID) { + this.resourceCustomizationUUID = resourceCustomizationUUID; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubcategory() { + return subcategory; + } + + public void setSubcategory(String subcategory) { + this.subcategory = subcategory; + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java new file mode 100644 index 0000000000..e86fac72a6 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.client.test.rest; + + +import java.io.IOException; + +import javax.transaction.Transactional; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.onap.so.asdc.client.ASDCController; +import org.onap.so.asdc.client.exceptions.ASDCControllerException; +import org.onap.so.asdc.client.exceptions.ASDCParametersException; +import org.onap.so.asdc.client.test.emulators.DistributionClientEmulator; +import org.onap.so.asdc.client.test.emulators.NotificationDataImpl; +import org.onap.so.asdc.client.test.emulators.JsonStatusData; +import org.onap.so.asdc.installer.heat.ToscaResourceInstaller; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +/** + * This is a TEST only rest interface. It is not used in production, it is used to aid in testing the ASDC service on jboss without the need to be connected + * to the ASDC service broker. It starts the test at the treatNotification step and simulates both the notification step as well as the artifact download step. + * + * i.e. http://localhost:8080/asdc/treatNotification/v1 + * + * i.e. http://localhost:8080/asdc/statusData/v1 + * + * @author jm5423 + * + */ + +@Path("/") +@Component +@Profile("test") +public class ASDCRestInterface { + + private static DistributionClientEmulator distributionClientEmulator; + + private static JsonStatusData statusData; + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC,ASDCRestInterface.class ); + + @Autowired + private ASDCController asdcController; + + @Autowired + private ToscaResourceInstaller toscaInstaller; + + @POST + @Path("/treatNotification/v1") + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response invokeASDCService(NotificationDataImpl request, @HeaderParam("resource-location") String resourceLocation) + throws ASDCControllerException, ASDCParametersException, IOException { + distributionClientEmulator = new DistributionClientEmulator(resourceLocation); + + asdcController.setControllerName("asdc-controller1"); + asdcController.setDistributionClient(distributionClientEmulator); + asdcController.initASDC(); + asdcController.treatNotification(request); + asdcController.closeASDC(); + return Response.status(200).build(); + } + + @POST + @Path("/statusData/v1") + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response invokeASDCStatusData(String request) { + + try{ + distributionClientEmulator = new DistributionClientEmulator("resource-examples/"); + statusData = JsonStatusData.instantiateNotifFromJsonFile("resource-examples/"); + + ASDCController asdcController = new ASDCController("asdc-controller1", distributionClientEmulator); + //LOGGER.info(MessageEnum.ASDC_INIT_ASDC_CLIENT_EXC, notifDataWithoutModuleInfo.getServiceUUID(), "ASDC", "initASDC()"); + asdcController.initASDC(); + //LOGGER.info(MessageEnum.ASDC_INIT_ASDC_CLIENT_EXC, notifDataWithoutModuleInfo.getServiceUUID(), "ASDC", "treatNotification()"); + toscaInstaller.installTheComponentStatus(statusData); + //asdcController.treatNotification(notifDataWithoutModuleInfo); + //LOGGER.info(MessageEnum.ASDC_INIT_ASDC_CLIENT_EXC, notifDataWithoutModuleInfo.getServiceUUID(), "ASDC", "closeASDC()"); + asdcController.closeASDC(); + }catch(Exception e){ + System.out.println("Error caught " + e.getMessage()); + LOGGER.error(MessageEnum.ASDC_GENERAL_EXCEPTION, + "Exception caught during ASDCRestInterface", "ASDC", "invokeASDCService", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in invokeASDCService", e); + } + System.out.println("ASDC Updates are complete"); + LOGGER.info(MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC, statusData.getDistributionID(), "ASDC", "ASDC Updates Are Complete"); + + return null; + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java new file mode 100644 index 0000000000..1e227aefa1 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java @@ -0,0 +1,211 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.installer; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.so.asdc.client.ASDCConfiguration; + +/** + * A class representing a generic element whose information can be used for example to log artifacts, resource... data. + */ +public class ASDCElementInfo { + + /** + * A default, empty instance used in case a source element was not correctly provided. + */ + public static final ASDCElementInfo EMPTY_INSTANCE = new ASDCElementInfo(); + + /** + * Used to define the other possible ASDC Element types (usually in addition to existing artifact types, etc.).
+ *
+ * Possible types allowed:
+ *
    + *
  • {@link ASDCElementTypeEnum#VNF_RESOURCE}
  • + *
      + */ + public static enum ASDCElementTypeEnum { + /** + * The type VNF_RESOURCE. Represents a VNF_RESOURCE element. + */ + VNF_RESOURCE + }; + + /** + * The map of element information fields useful for logging. The complete contents of this list will be concatenated. + */ + private final Map elementInfoMap = new HashMap<>(); + + /** + * The type of this element. + */ + private final String type; + + private ASDCElementInfo () { + // Private parameterless constructor. Not visible, only used for EMPTY_INSTANCE. + this.type = ""; + } + + /** + * Artifact-type based constructor. Requires a valid artifact type. + * @param artifactType The artifact type + */ + private ASDCElementInfo (String artifactType) { + // We need the exact type name here... + this.type = artifactType; + } + + /** + * 'Other element type'-based constructor. Requires a valid element type. + * @param elementType An ASDCElementTypeEnum entry. This will usually contain enumerated types not in the existing + */ + private ASDCElementInfo (ASDCElementTypeEnum elementType) { + // We need the exact type name here... + this.type = elementType.name(); + } + + /** + * Add an information entry (name, UUID, etc.) from an artifact/resource/..., once a at time. + * + * @param key The key (name) of the information entry (Artifact UUID, Resource Name, etc.) + * @param value The value bound to the information entry. + */ + public final void addElementInfo(String key, String value) { + if ((key != null) && (value != null)) { + this.getElementInfoMap().put(key, value); + } + } + + /** + * Returns an aggregated, formatted list of the expected details about an ASDC element. + * (non-Javadoc) + * @return An aggregated list of element information entries, comma-separated. + * @see java.lang.Object#toString() + */ + @Override + public final String toString() { + StringBuilder sb = new StringBuilder(); + List aggregatedElements = new ArrayList<>(); + for (Entry entry : this.getElementInfoMap().entrySet()) { + aggregatedElements.add(entry.getKey() + ": " + entry.getValue()); + } + sb.append(aggregatedElements.size() > 0 ? aggregatedElements.get(0) : ""); + if (aggregatedElements.size() > 1) { + for (int i = 1; i < aggregatedElements.size(); ++i) { + sb.append (", "); + sb.append(aggregatedElements.get(i)); + } + } + return sb.toString(); + } + + /** + * The type that was defined at creation time. This is typically VNF_RESOURCE, VF_MODULE_METADATA, HEAT_ENV, etc. + * @return The type of this element information type. This will usually be either an ArtifactTypeEnum entry name or an ASDCElementTypeEnum entry name. + * @see ASDCElementInfo.ASDCElementTypeEnum + */ + public String getType() { + return type; + } + + /** + * Provides the map of all element information entries for this type. + * @return A map of all element information entries which will be used by the toString() method. + * @see ASDCElementInfo#toString() + */ + protected Map getElementInfoMap() { + return elementInfoMap; + } + + /** + * Create an ASDCElementInfo object from a VNF Resource.
      + *
      + * Used information:
      + *
        + *
      • Resource Instance Name
      • + *
      • Resource Instance UUID
      • + *
      + * + * @param vfResourceStructure The VfResourceStructure to use as source of information (see {@link VfResourceStructure}). + * @return an ASDCElementInfo using the information held in the VNF Resource. + */ + public static final ASDCElementInfo createElementFromVfResourceStructure (VfResourceStructure vfResourceStructure) { + if (vfResourceStructure == null) { + return EMPTY_INSTANCE; + } + ASDCElementInfo elementInfo = new ASDCElementInfo(ASDCElementTypeEnum.VNF_RESOURCE); + IResourceInstance resourceInstance = vfResourceStructure.getResourceInstance(); + elementInfo.addElementInfo("Resource Instance Name", resourceInstance.getResourceInstanceName()); + elementInfo.addElementInfo("Resource Instance Invariant UUID", resourceInstance.getResourceInvariantUUID()); + return elementInfo; + } + + /** + * Create an ASDCElementInfo object from a VF Module.
      + *
      + * Used information:
      + *
        + *
      • Module Model Name
      • + *
      • Module Model UUID
      • + *
      + * + * @param vfModuleStructure The VfModuleStructure to use as source of information (see {@link VfModuleStructure}). + * @return an ASDCElementInfo using the information held in the VF Module. + */ + public static final ASDCElementInfo createElementFromVfModuleStructure (VfModuleStructure vfModuleStructure) { + if (vfModuleStructure == null) { + return EMPTY_INSTANCE; + } + ASDCElementInfo elementInfo = new ASDCElementInfo(ASDCConfiguration.VF_MODULES_METADATA); + IVfModuleData moduleMetadata = vfModuleStructure.getVfModuleMetadata(); + elementInfo.addElementInfo("Module Model Name", moduleMetadata.getVfModuleModelName()); + elementInfo.addElementInfo("Module Model Invariant UUID", moduleMetadata.getVfModuleModelInvariantUUID()); + return elementInfo; + } + + /** + * Create an ASDCElementInfo object from an IArtfiactInfo instance.
      + *
      + * Used information:
      + *
        + *
      • IArtifactInfo Name
      • + *
      • IArtifactInfo UUID
      • + *
      + * + * @param artifactInfo The VfModuleStructure to use as source of information (see {@link IArtifactInfo}). + * @return an ASDCElementInfo using the information held in the IArtifactInfo instance. + */ + public static final ASDCElementInfo createElementFromVfArtifactInfo (IArtifactInfo artifactInfo) { + if (artifactInfo == null) { + return EMPTY_INSTANCE; + } + ASDCElementInfo elementInfo = new ASDCElementInfo(artifactInfo.getArtifactType()); + elementInfo.addElementInfo(elementInfo.getType() + " Name", artifactInfo.getArtifactName()); + elementInfo.addElementInfo(elementInfo.getType() + " UUID", artifactInfo.getArtifactUUID()); + return elementInfo; + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/BigDecimalVersion.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/BigDecimalVersion.java new file mode 100644 index 0000000000..1dd92eac7a --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/BigDecimalVersion.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.installer; + + +import java.math.BigDecimal; + +public class BigDecimalVersion { + + /** + * This method truncates and convert the version String provided in the notification. + * + * @param version The version to check + * @return A BigDecimal value checked and truncated + */ + public static BigDecimal castAndCheckNotificationVersion(String version) { + // Truncate the version if bad type + String[] splitVersion = version.split("\\."); + StringBuilder newVersion = new StringBuilder(); + if (splitVersion.length > 1) { + newVersion.append(splitVersion[0]); + newVersion.append("."); + newVersion.append(splitVersion[1]); + } else { + return new BigDecimal(splitVersion[0]); + } + + for (int i=2;i; + public abstract java.util.List getArtifacts(); + + public abstract java.util.Map getProperties(); +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfResourceInstaller.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfResourceInstaller.java new file mode 100644 index 0000000000..445b10b588 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfResourceInstaller.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.installer; + + + +import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; + +public interface IVfResourceInstaller { + + boolean isResourceAlreadyDeployed (VfResourceStructure vfResourceStructure) throws ArtifactInstallerException; + + public void installTheResource (VfResourceStructure vfResourceStructure) throws ArtifactInstallerException; +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java new file mode 100644 index 0000000000..565ddf42b5 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java @@ -0,0 +1,506 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.installer; + +import java.io.File; +import java.util.List; + +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.so.asdc.client.exceptions.ASDCDownloadException; +import org.onap.so.db.catalog.beans.AllottedResource; +import org.onap.so.db.catalog.beans.AllottedResourceCustomization; +import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization; +import org.onap.so.db.catalog.beans.CollectionResource; +import org.onap.so.db.catalog.beans.CollectionResourceCustomization; +import org.onap.so.db.catalog.beans.ConfigurationResource; +import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization; +import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization; +import org.onap.so.db.catalog.beans.NetworkInstanceGroup; +import org.onap.so.db.catalog.beans.NetworkResource; +import org.onap.so.db.catalog.beans.NetworkResourceCustomization; +import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.ServiceProxyResource; +import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization; +import org.onap.so.db.catalog.beans.TempNetworkHeatTemplateLookup; +import org.onap.so.db.catalog.beans.ToscaCsar; +import org.onap.so.db.catalog.beans.VfModule; +import org.onap.so.db.catalog.beans.VfModuleCustomization; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; + +public class ToscaResourceStructure { + + Metadata serviceMetadata; + private Service catalogService; + ISdcCsarHelper sdcCsarHelper; + List allottedList; + List networkTypes; + List vfTypes; + String heatTemplateUUID; + String volHeatTemplateUUID; + String volHeatEnvTemplateUUID; + String envHeatTemplateUUID; + String heatFilesUUID; + String workloadPerformance; + boolean isVnfAlreadyInstalled = false; + String serviceVersion; + private boolean isDeployedSuccessfully=false; + + + private NetworkResourceCustomization catalogNetworkResourceCustomization; + + private NetworkResource catalogNetworkResource; + + private List catalogNetworkInstanceGroup; + + private CollectionNetworkResourceCustomization catalogCollectionNetworkResourceCustomization; + + private CollectionResource catalogCollectionResource; + + private CollectionResourceCustomization catalogCollectionResourceCustomization; + + private NetworkCollectionResourceCustomization catalogNetworkCollectionResourceCustomization; + + private ServiceProxyResource catalogServiceProxyResource; + + private ServiceProxyResourceCustomization catalogServiceProxyResourceCustomization; + + private ConfigurationResource catalogConfigurationResource; + + private ConfigurationResourceCustomization catalogConfigurationResourceCustomization; + + private AllottedResourceCustomization catalogResourceCustomization; + + private VfModule vfModule; + + private VfModuleCustomization vfModuleCustomization; + + //private VnfResource vnfResource; + + private VnfResourceCustomization vnfResourceCustomization; + + private AllottedResource allottedResource; + + private AllottedResourceCustomization allottedResourceCustomization; + + private TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup; + + private IArtifactInfo toscaArtifact; + + private ToscaCsar toscaCsar; + + protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC, ToscaResourceStructure.class); + + + public ToscaResourceStructure(){ + } + + public void updateResourceStructure(IArtifactInfo artifact) throws ASDCDownloadException { + + + try { + + SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();//Autoclosable + + LOGGER.debug("MSO config path is: " + System.getProperty("mso.config.path")); + + File spoolFile = new File(System.getProperty("mso.config.path") + "/ASDC/" + artifact.getArtifactName()); + + LOGGER.debug("ASDC File path is: " + spoolFile.getAbsolutePath()); + LOGGER.info(MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF, "***PATH", "ASDC", spoolFile.getAbsolutePath()); + + + sdcCsarHelper = factory.getSdcCsarHelper(spoolFile.getAbsolutePath()); + + }catch(Exception e){ + System.out.println("System out " + e.getMessage()); + LOGGER.error(MessageEnum.ASDC_GENERAL_EXCEPTION_ARG, + "Exception caught during parser *****LOOK********* " + artifact.getArtifactName(), "ASDC", "processResourceNotification", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in processResourceNotification", e); + + throw new ASDCDownloadException ("Exception caught when passing the csar file to the parser ", e); + } + + serviceMetadata = sdcCsarHelper.getServiceMetadata(); + + } + + public String getHeatTemplateUUID() { + return heatTemplateUUID; + } + + public void setHeatTemplateUUID(String heatTemplateUUID) { + this.heatTemplateUUID = heatTemplateUUID; + } + + public List getAllottedList() { + return allottedList; + } + + public void setAllottedList(List allottedList) { + this.allottedList = allottedList; + } + + public ISdcCsarHelper getSdcCsarHelper() { + return sdcCsarHelper; + } + + public void setSdcCsarHelper(ISdcCsarHelper sdcCsarHelper) { + this.sdcCsarHelper = sdcCsarHelper; + } + + public Metadata getServiceMetadata() { + return serviceMetadata; + } + + public Service getCatalogService() { + return catalogService; + } + + public void setServiceMetadata(Metadata serviceMetadata) { + this.serviceMetadata = serviceMetadata; + } + + public void setCatalogService(Service catalogService) { + this.catalogService = catalogService; + } + + public List getNetworkTypes() { + return networkTypes; + } + + public void setNetworkTypes(List networkTypes) { + this.networkTypes = networkTypes; + } + + public List getVfTypes() { + return vfTypes; + } + + public void setVfTypes(List vfTypes) { + this.vfTypes = vfTypes; + } + + public AllottedResourceCustomization getCatalogResourceCustomization() { + return catalogResourceCustomization; + } + + public void setCatalogResourceCustomization( + AllottedResourceCustomization catalogResourceCustomization) { + this.catalogResourceCustomization = catalogResourceCustomization; + } + + // Network Only + public NetworkResourceCustomization getCatalogNetworkResourceCustomization() { + return catalogNetworkResourceCustomization; + } + // Network Only + public void setCatalogNetworkResourceCustomization(NetworkResourceCustomization catalogNetworkResourceCustomization) { + this.catalogNetworkResourceCustomization = catalogNetworkResourceCustomization; + } + + public NetworkResource getCatalogNetworkResource() { + return catalogNetworkResource; + } + + public void setCatalogNetworkResource(NetworkResource catalogNetworkResource) { + this.catalogNetworkResource = catalogNetworkResource; + } + + public VfModule getCatalogVfModule() { + return vfModule; + } + + public void setCatalogVfModule(VfModule vfModule) { + this.vfModule = vfModule; + } +/* + public VnfResource getCatalogVnfResource() { + return vnfResource; + } + + public void setCatalogVnfResource(VnfResource vnfResource) { + this.vnfResource = vnfResource; + } + + */ + + public VnfResourceCustomization getCatalogVnfResourceCustomization() { + return vnfResourceCustomization; + } + + public void setCatalogVnfResourceCustomization( + VnfResourceCustomization vnfResourceCustomization) { + this.vnfResourceCustomization = vnfResourceCustomization; + } + + public VfModuleCustomization getCatalogVfModuleCustomization() { + return vfModuleCustomization; + } + + public void setCatalogVfModuleCustomization(VfModuleCustomization vfModuleCustomization) { + this.vfModuleCustomization = vfModuleCustomization; + } + + public AllottedResource getAllottedResource() { + return allottedResource; + } + + public void setAllottedResource(AllottedResource allottedResource) { + this.allottedResource = allottedResource; + } + + public AllottedResourceCustomization getCatalogAllottedResourceCustomization() { + return allottedResourceCustomization; + } + + public void setCatalogAllottedResourceCustomization( + AllottedResourceCustomization allottedResourceCustomization) { + this.allottedResourceCustomization = allottedResourceCustomization; + } + + public TempNetworkHeatTemplateLookup getCatalogTempNetworkHeatTemplateLookup() { + return tempNetworkHeatTemplateLookup; + } + + public void setCatalogTempNetworkHeatTemplateLookup( + TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup) { + this.tempNetworkHeatTemplateLookup = tempNetworkHeatTemplateLookup; + } + + public String getHeatFilesUUID() { + return heatFilesUUID; + } + + public void setHeatFilesUUID(String heatFilesUUID) { + this.heatFilesUUID = heatFilesUUID; + } + + public IArtifactInfo getToscaArtifact() { + return toscaArtifact; + } + + public void setToscaArtifact(IArtifactInfo toscaArtifact) { + this.toscaArtifact = toscaArtifact; + } + + public ToscaCsar getCatalogToscaCsar() { + return toscaCsar; + } + + public void setCatalogToscaCsar(ToscaCsar toscaCsar) { + this.toscaCsar = toscaCsar; + } + + public boolean isVnfAlreadyInstalled() { + return isVnfAlreadyInstalled; + } + + public void setVnfAlreadyInstalled(boolean isVnfAlreadyInstalled) { + this.isVnfAlreadyInstalled = isVnfAlreadyInstalled; + } + + public String getVolHeatTemplateUUID() { + return volHeatTemplateUUID; + } + + public void setVolHeatTemplateUUID(String volHeatTemplateUUID) { + this.volHeatTemplateUUID = volHeatTemplateUUID; + } + + public String getEnvHeatTemplateUUID() { + return envHeatTemplateUUID; + } + + public void setEnvHeatTemplateUUID(String envHeatTemplateUUID) { + this.envHeatTemplateUUID = envHeatTemplateUUID; + } + + public String getVolHeatEnvTemplateUUID() { + return volHeatEnvTemplateUUID; + } + + public void setVolHeatEnvTemplateUUID(String volHeatEnvTemplateUUID) { + this.volHeatEnvTemplateUUID = volHeatEnvTemplateUUID; + } + + public String getServiceVersion() { + return serviceVersion; + } + + public void setServiceVersion(String serviceVersion) { + this.serviceVersion = serviceVersion; + } + + public String getWorkloadPerformance() { + return workloadPerformance; + } + + public void setWorkloadPerformance(String workloadPerformance) { + this.workloadPerformance = workloadPerformance; + } + + public VfModule getVfModule() { + return vfModule; + } + + public void setVfModule(VfModule vfModule) { + this.vfModule = vfModule; + } + + public VfModuleCustomization getVfModuleCustomization() { + return vfModuleCustomization; + } + + public void setVfModuleCustomization(VfModuleCustomization vfModuleCustomization) { + this.vfModuleCustomization = vfModuleCustomization; + } + + + public VnfResourceCustomization getVnfResourceCustomization() { + return vnfResourceCustomization; + } + + public void setVnfResourceCustomization( + VnfResourceCustomization vnfResourceCustomization) { + this.vnfResourceCustomization = vnfResourceCustomization; + } + + public AllottedResourceCustomization getAllottedResourceCustomization() { + return allottedResourceCustomization; + } + + public void setAllottedResourceCustomization( + AllottedResourceCustomization allottedResourceCustomization) { + this.allottedResourceCustomization = allottedResourceCustomization; + } + + public TempNetworkHeatTemplateLookup getTempNetworkHeatTemplateLookup() { + return tempNetworkHeatTemplateLookup; + } + + public void setTempNetworkHeatTemplateLookup( + TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup) { + this.tempNetworkHeatTemplateLookup = tempNetworkHeatTemplateLookup; + } + + public List getCatalogNetworkInstanceGroup() { + return catalogNetworkInstanceGroup; + } + + public void setCatalogNetworkInstanceGroup(List catalogNetworkInstanceGroup) { + this.catalogNetworkInstanceGroup = catalogNetworkInstanceGroup; + } + + public CollectionNetworkResourceCustomization getCatalogCollectionNetworkResourceCustomization() { + return catalogCollectionNetworkResourceCustomization; + } + + public void setCatalogCollectionNetworkResourceCustomization( + CollectionNetworkResourceCustomization catalogCollectionNetworkResourceCustomization) { + this.catalogCollectionNetworkResourceCustomization = catalogCollectionNetworkResourceCustomization; + } + + public CollectionResource getCatalogCollectionResource() { + return catalogCollectionResource; + } + + public void setCatalogCollectionResource(CollectionResource catalogCollectionResource) { + this.catalogCollectionResource = catalogCollectionResource; + } + + public CollectionResourceCustomization getCatalogCollectionResourceCustomization() { + return catalogCollectionResourceCustomization; + } + + public void setCatalogCollectionResourceCustomization( + CollectionResourceCustomization catalogCollectionResourceCustomization) { + this.catalogCollectionResourceCustomization = catalogCollectionResourceCustomization; + } + + public NetworkCollectionResourceCustomization getCatalogNetworkCollectionResourceCustomization() { + return catalogNetworkCollectionResourceCustomization; + } + + public void setCatalogNetworkCollectionResourceCustomization( + NetworkCollectionResourceCustomization catalogNetworkCollectionResourceCustomization) { + this.catalogNetworkCollectionResourceCustomization = catalogNetworkCollectionResourceCustomization; + } + + public ServiceProxyResource getCatalogServiceProxyResource() { + return catalogServiceProxyResource; + } + + public void setCatalogServiceProxyResource(ServiceProxyResource catalogServiceProxyResource) { + this.catalogServiceProxyResource = catalogServiceProxyResource; + } + + public ServiceProxyResourceCustomization getCatalogServiceProxyResourceCustomization() { + return catalogServiceProxyResourceCustomization; + } + + public void setCatalogServiceProxyResourceCustomization( + ServiceProxyResourceCustomization catalogServiceProxyResourceCustomization) { + this.catalogServiceProxyResourceCustomization = catalogServiceProxyResourceCustomization; + } + + public ConfigurationResource getCatalogConfigurationResource() { + return catalogConfigurationResource; + } + + public void setCatalogConfigurationResource(ConfigurationResource catalogConfigurationResource) { + this.catalogConfigurationResource = catalogConfigurationResource; + } + + public ConfigurationResourceCustomization getCatalogConfigurationResourceCustomization() { + return catalogConfigurationResourceCustomization; + } + + public void setCatalogConfigurationResourceCustomization( + ConfigurationResourceCustomization catalogConfigurationResourceCustomization) { + this.catalogConfigurationResourceCustomization = catalogConfigurationResourceCustomization; + } + + public ToscaCsar getToscaCsar() { + return toscaCsar; + } + + public void setToscaCsar(ToscaCsar toscaCsar) { + this.toscaCsar = toscaCsar; + } + + public static MsoLogger getLogger() { + return LOGGER; + } + + public boolean isDeployedSuccessfully() { + return isDeployedSuccessfully; + } + + public void setSuccessfulDeployment() { + isDeployedSuccessfully = true; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleArtifact.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleArtifact.java new file mode 100644 index 0000000000..adc8071454 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleArtifact.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.installer; + + +import java.io.UnsupportedEncodingException; + +import org.onap.so.db.catalog.beans.HeatEnvironment; +import org.onap.so.db.catalog.beans.HeatFiles; +import org.onap.so.db.catalog.beans.HeatTemplate; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; + +/** + * The structure that contains the artifactInfo and its associated DownloadedResult. + * + */ +public final class VfModuleArtifact { + private final IArtifactInfo artifactInfo; + private int deployedInDb=0; + private final String result; + private HeatFiles heatFiles; + private HeatTemplate heatTemplate; + private HeatEnvironment heatEnvironment; + + public VfModuleArtifact(IArtifactInfo artifactinfo,IDistributionClientDownloadResult clientResult) throws UnsupportedEncodingException { + artifactInfo=artifactinfo; + result = new String(clientResult.getArtifactPayload(), "UTF-8"); + + } + + public HeatFiles getHeatFiles() { + return heatFiles; + } + + public void setHeatFiles(HeatFiles heatFiles) { + this.heatFiles = heatFiles; + } + + public HeatTemplate getHeatTemplate() { + return heatTemplate; + } + + public void setHeatTemplate(HeatTemplate heatTemplate) { + this.heatTemplate = heatTemplate; + } + + public IArtifactInfo getArtifactInfo() { + return artifactInfo; + } + + public String getResult() { + return result; + } + + public int getDeployedInDb() { + return deployedInDb; + } + + public void incrementDeployedInDB() { + ++deployedInDb; + } + + public HeatEnvironment getHeatEnvironment() { + return heatEnvironment; + } + + public void setHeatEnvironment(HeatEnvironment heatEnvironment) { + this.heatEnvironment=heatEnvironment; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleMetaData.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleMetaData.java new file mode 100644 index 0000000000..11000bec98 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleMetaData.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.installer; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class VfModuleMetaData implements IVfModuleData { + + @JsonProperty("artifacts") + private List artifacts; + + @JsonProperty("properties") + //private List> properties = new ArrayList<>(); + private Map properties = new HashMap<>(); + + @JsonIgnore + private Map attributesMap = new HashMap<>(); + + @Override + public List getArtifacts() { + return artifacts; + } + + public Map getProperties() { + return properties; + } + + @Override + public String getVfModuleModelDescription() { + return (String)attributesMap.get("vfModuleModelDescription"); + } + + @Override + public String getVfModuleModelInvariantUUID() { + return (String)attributesMap.get("vfModuleModelInvariantUUID"); + } + + public String getVfModuleModelCustomizationUUID() { + return (String)attributesMap.get("vfModuleModelCustomizationUUID"); + } + + @Override + public String getVfModuleModelName() { + return (String)attributesMap.get("vfModuleModelName"); + } + + @Override + public String getVfModuleModelUUID() { + return (String)attributesMap.get("vfModuleModelUUID"); + } + + @Override + public String getVfModuleModelVersion() { + return (String)attributesMap.get("vfModuleModelVersion"); + } + + @Override + public boolean isBase() { + return (boolean)attributesMap.get("isBase"); + } + + + + @SuppressWarnings("unused") + @JsonAnySetter + public final void setAttribute(String attrName, Object attrValue) { + if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) { + this.attributesMap.put(attrName,attrValue); + } + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleStructure.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleStructure.java new file mode 100644 index 0000000000..9f0525db3d --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleStructure.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.installer; + + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.onap.sdc.api.notification.IVfModuleMetadata; +import org.onap.so.asdc.client.ASDCConfiguration; +import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; +import org.onap.so.db.catalog.beans.VfModule; + +public final class VfModuleStructure { + + private final IVfModuleData vfModuleMetadata; + + private final VfResourceStructure parentVfResource; + + private VfModule catalogVfModule; + /** + * The list of artifact existing in this resource hashed by artifactType. + */ + private final Map> artifactsMap; + + public VfModuleStructure(VfResourceStructure vfParentResource,IVfModuleData vfmoduleMetadata) throws ArtifactInstallerException { + + vfModuleMetadata = vfmoduleMetadata; + parentVfResource = vfParentResource; + + artifactsMap = new HashMap<>(); + + for (String artifactUUID:this.vfModuleMetadata.getArtifacts()) { + if (vfParentResource.getArtifactsMapByUUID().containsKey(artifactUUID)) { + this.addToStructure(vfParentResource.getArtifactsMapByUUID().get(artifactUUID)); + } else { + throw new ArtifactInstallerException("Artifact (UUID:"+artifactUUID+ ") referenced in the VFModule UUID list has not been downloaded, cancelling the Resource deployment"); + } + } + } + + private void addToStructure(VfModuleArtifact vfModuleArtifact) { + + if (artifactsMap.containsKey(vfModuleArtifact.getArtifactInfo().getArtifactType())) { + artifactsMap.get(vfModuleArtifact.getArtifactInfo().getArtifactType()).add(vfModuleArtifact); + + } else { + List nestedList = new LinkedList<>(); + nestedList.add(vfModuleArtifact); + + artifactsMap.put(vfModuleArtifact.getArtifactInfo().getArtifactType(), nestedList); + } + } + + public List getOrderedArtifactList() { + + List artifactsList = new LinkedList<>(); + + artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT)); + artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_ENV)); + artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_VOL)); + + artifactsList.addAll((artifactsMap.get(ASDCConfiguration.HEAT_NESTED))); + + artifactsList.addAll((artifactsMap.get(ASDCConfiguration.HEAT_ARTIFACT))); + + artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_VOL)); + + return null; + } + + public IVfModuleData getVfModuleMetadata() { + return vfModuleMetadata; + } + + public VfResourceStructure getParentVfResource() { + return parentVfResource; + } + + public Map> getArtifactsMap() { + return artifactsMap; + } + + + public VfModule getCatalogVfModule() { + return catalogVfModule; + } + + public void setCatalogVfModule(VfModule catalogVfModule) { + this.catalogVfModule = catalogVfModule; + } + + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java new file mode 100644 index 0000000000..a045c2bb3a --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java @@ -0,0 +1,220 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.installer; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import org.onap.so.asdc.client.ASDCConfiguration; +import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; +import org.onap.so.db.catalog.beans.AllottedResourceCustomization; +import org.onap.so.db.catalog.beans.NetworkResourceCustomization; +import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.VnfResource; +import org.onap.so.logger.MsoLogger; +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.so.logger.MessageEnum; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +/** + * This structure exists to avoid having issues if the order of the vfResource/vfmodule artifact is not good (tree structure). + * + */ + + +public class VfResourceStructure { + + protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC, VfResourceStructure.class); + + private boolean isDeployedSuccessfully=false; + /** + * The Raw notification data. + */ + private final INotificationData notification; + /** + * The Raw notification data. + */ + private boolean isAlreadyDeployed=false; + + /** + * The resource we will try to deploy. + */ + private final IResourceInstance resourceInstance; + + /** + * The list of VfModules defined for this resource. + */ + private final List vfModulesStructureList; + + /** + * The list of VfModulesMetadata defined for this resource. + */ + private List vfModulesMetadataList; + + private VnfResource catalogVnfResource; + + private NetworkResourceCustomization catalogNetworkResourceCustomization; + + private AllottedResourceCustomization catalogResourceCustomization; + + private Service catalogService; + + /** + * The list of artifacts existing in this resource hashed by UUID. + */ + private final Map artifactsMapByUUID; + + + public VfResourceStructure(INotificationData notificationdata, IResourceInstance resourceinstance) { + notification=notificationdata; + resourceInstance=resourceinstance; + vfModulesStructureList = new LinkedList<>(); + artifactsMapByUUID = new HashMap<>(); + } + + public void addArtifactToStructure(IDistributionClient distributionClient,IArtifactInfo artifactinfo,IDistributionClientDownloadResult clientResult) throws UnsupportedEncodingException { + VfModuleArtifact vfModuleArtifact = new VfModuleArtifact(artifactinfo,clientResult); + + switch(artifactinfo.getArtifactType()) { + case ASDCConfiguration.HEAT: + case ASDCConfiguration.HEAT_ENV: + case ASDCConfiguration.HEAT_VOL: + case ASDCConfiguration.HEAT_NESTED: // For 1607 only 1 level tree is supported + case ASDCConfiguration.HEAT_ARTIFACT: + case ASDCConfiguration.HEAT_NET: + case ASDCConfiguration.OTHER: + artifactsMapByUUID.put(artifactinfo.getArtifactUUID(), vfModuleArtifact); + break; + case ASDCConfiguration.VF_MODULES_METADATA: + vfModulesMetadataList = this.decodeVfModuleArtifact(clientResult.getArtifactPayload()); + break; + default: + break; + } + } + + public void createVfModuleStructures() throws ArtifactInstallerException { + + //for vender tosca VNF there is no VFModule in VF + if (vfModulesMetadataList == null) { + LOGGER.info(MessageEnum.ASDC_GENERAL_INFO,"There is no VF mudules in the VF.", "ASDC", "createVfModuleStructures"); + return; + } + for (IVfModuleData vfModuleMeta:vfModulesMetadataList) { + vfModulesStructureList.add(new VfModuleStructure(this,vfModuleMeta)); + } + } + + public INotificationData getNotification() { + return notification; + } + + public IResourceInstance getResourceInstance() { + return resourceInstance; + } + + public List getVfModuleStructure() { + return vfModulesStructureList; + } + + public boolean isDeployedSuccessfully() { + return isDeployedSuccessfully; + } + + public void setSuccessfulDeployment() { + isDeployedSuccessfully = true; + } + + public boolean isAlreadyDeployed() { + return isAlreadyDeployed; + } + + public void setAlreadyDeployed(boolean isAlreadyDeployed) { + this.isAlreadyDeployed = isAlreadyDeployed; + } + + public Map getArtifactsMapByUUID() { + return artifactsMapByUUID; + } + + public List getVfModulesStructureList() { + return vfModulesStructureList; + } + + public VnfResource getCatalogVnfResource() { + return catalogVnfResource; + } + + public void setCatalogVnfResource(VnfResource catalogVnfResource) { + this.catalogVnfResource = catalogVnfResource; + } + + // Network Only + public NetworkResourceCustomization getCatalogNetworkResourceCustomization() { + return catalogNetworkResourceCustomization; + } + // Network Only + public void setCatalogNetworkResourceCustomization(NetworkResourceCustomization catalogNetworkResourceCustomization) { + this.catalogNetworkResourceCustomization = catalogNetworkResourceCustomization; + } + + public AllottedResourceCustomization getCatalogResourceCustomization() { + return catalogResourceCustomization; + } + + public void setCatalogResourceCustomization( + AllottedResourceCustomization catalogResourceCustomization) { + this.catalogResourceCustomization = catalogResourceCustomization; + } + + public Service getCatalogService() { + return catalogService; + } + + public void setCatalogService(Service catalogService) { + this.catalogService = catalogService; + } + + public List decodeVfModuleArtifact(byte[] arg0) { + try { + List listVFModuleMetaData = new ObjectMapper().readValue(arg0, new TypeReference>(){}); + return listVFModuleMetaData; + + } catch (JsonParseException e) { + LOGGER.debug("JsonParseException : ",e); + } catch (JsonMappingException e) { + LOGGER.debug("JsonMappingException : ",e); + } catch (IOException e) { + LOGGER.debug("IOException : ",e); + } + return null; + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java new file mode 100644 index 0000000000..ea952f6daf --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java @@ -0,0 +1,1589 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.installer.heat; + + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import org.hibernate.exception.ConstraintViolationException; +import org.hibernate.exception.LockAcquisitionException; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.IStatusData; +import org.onap.sdc.tosca.parser.impl.SdcPropertyNames; +import org.onap.sdc.tosca.parser.impl.SdcTypes; +import org.onap.sdc.toscaparser.api.CapabilityAssignment; +import org.onap.sdc.toscaparser.api.CapabilityAssignments; +import org.onap.sdc.toscaparser.api.Group; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.RequirementAssignment; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.sdc.utils.DistributionStatusEnum; +import org.onap.so.asdc.client.ASDCConfiguration; +import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; +import org.onap.so.asdc.installer.ASDCElementInfo; +import org.onap.so.asdc.installer.BigDecimalVersion; +import org.onap.so.asdc.installer.IVfModuleData; +import org.onap.so.asdc.installer.ToscaResourceStructure; +import org.onap.so.asdc.installer.VfModuleArtifact; +import org.onap.so.asdc.installer.VfModuleStructure; +import org.onap.so.asdc.installer.VfResourceStructure; +import org.onap.so.asdc.util.YamlEditor; +import org.onap.so.db.catalog.beans.AllottedResource; +import org.onap.so.db.catalog.beans.AllottedResourceCustomization; +import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization; +import org.onap.so.db.catalog.beans.CollectionResource; +import org.onap.so.db.catalog.beans.CollectionResourceCustomization; +import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization; +import org.onap.so.db.catalog.beans.ConfigurationResource; +import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization; +import org.onap.so.db.catalog.beans.ExternalServiceToInternalService; +import org.onap.so.db.catalog.beans.HeatEnvironment; +import org.onap.so.db.catalog.beans.HeatFiles; +import org.onap.so.db.catalog.beans.HeatTemplate; +import org.onap.so.db.catalog.beans.HeatTemplateParam; +import org.onap.so.db.catalog.beans.InstanceGroupType; +import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization; +import org.onap.so.db.catalog.beans.NetworkInstanceGroup; +import org.onap.so.db.catalog.beans.NetworkResource; +import org.onap.so.db.catalog.beans.NetworkResourceCustomization; +import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.ServiceProxyResource; +import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization; +import org.onap.so.db.catalog.beans.SubType; +import org.onap.so.db.catalog.beans.TempNetworkHeatTemplateLookup; +import org.onap.so.db.catalog.beans.ToscaCsar; +import org.onap.so.db.catalog.beans.VFCInstanceGroup; +import org.onap.so.db.catalog.beans.VfModule; +import org.onap.so.db.catalog.beans.VfModuleCustomization; +import org.onap.so.db.catalog.beans.VnfResource; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization; +import org.onap.so.db.catalog.data.repository.AllottedResourceCustomizationRepository; +import org.onap.so.db.catalog.data.repository.AllottedResourceRepository; +import org.onap.so.db.catalog.data.repository.CollectionResourceCustomizationRepository; +import org.onap.so.db.catalog.data.repository.CollectionResourceRepository; +import org.onap.so.db.catalog.data.repository.ConfigurationResourceCustomizationRepository; +import org.onap.so.db.catalog.data.repository.ExternalServiceToInternalServiceRepository; +import org.onap.so.db.catalog.data.repository.HeatTemplateRepository; +import org.onap.so.db.catalog.data.repository.InstanceGroupRepository; +import org.onap.so.db.catalog.data.repository.NetworkResourceCustomizationRepository; +import org.onap.so.db.catalog.data.repository.NetworkResourceRepository; +import org.onap.so.db.catalog.data.repository.ServiceProxyResourceCustomizationRepository; +import org.onap.so.db.catalog.data.repository.ServiceRepository; +import org.onap.so.db.catalog.data.repository.TempNetworkHeatTemplateRepository; +import org.onap.so.db.catalog.data.repository.VFModuleCustomizationRepository; +import org.onap.so.db.catalog.data.repository.VFModuleRepository; +import org.onap.so.db.catalog.data.repository.VnfCustomizationRepository; +import org.onap.so.db.catalog.data.repository.VnfResourceRepository; +import org.onap.so.db.catalog.data.repository.VnfcInstanceGroupCustomizationRepository; +import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus; +import org.onap.so.db.request.beans.WatchdogDistributionStatus; +import org.onap.so.db.request.beans.WatchdogServiceModVerIdLookup; +import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatusRepository; +import org.onap.so.db.request.data.repository.WatchdogDistributionStatusRepository; +import org.onap.so.db.request.data.repository.WatchdogServiceModVerIdLookupRepository; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +@Component +public class ToscaResourceInstaller { + + protected static final String ALLOTTED_RESOURCE = "Allotted Resource"; + + protected static final String MULTI_STAGE_DESIGN = "multi_stage_design"; + + protected static final String SCALABLE = "scalable"; + + protected static final String BASIC = "BASIC"; + + protected static final String PROVIDER = "PROVIDER"; + + protected static final String HEAT = "HEAT"; + + protected static final String MANUAL_RECORD = "MANUAL_RECORD"; + + protected static final String MSO = "SO"; + + + @Autowired + protected ServiceRepository serviceRepo; + + @Autowired + protected InstanceGroupRepository instanceGroupRepo; + + @Autowired + protected ServiceProxyResourceCustomizationRepository serviceProxyCustomizationRepo; + + @Autowired + protected CollectionResourceRepository collectionRepo; + + @Autowired + protected CollectionResourceCustomizationRepository collectionCustomizationRepo; + + @Autowired + protected ConfigurationResourceCustomizationRepository configCustomizationRepo; + + @Autowired + protected VnfResourceRepository vnfRepo; + + @Autowired + protected VnfCustomizationRepository vnfCustomizationRepo; + + @Autowired + protected VFModuleRepository vfModuleRepo; + + @Autowired + protected VFModuleCustomizationRepository vfModuleCustomizationRepo; + + @Autowired + protected VnfcInstanceGroupCustomizationRepository vnfcInstanceGroupCustomizationRepo; + + @Autowired + protected AllottedResourceRepository allottedRepo; + + @Autowired + protected AllottedResourceCustomizationRepository allottedCustomizationRepo; + + @Autowired + protected NetworkResourceRepository networkRepo; + + @Autowired + protected HeatTemplateRepository heatRepo; + + @Autowired + protected NetworkResourceCustomizationRepository networkCustomizationRepo; + + @Autowired + protected WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository; + @Autowired + protected WatchdogDistributionStatusRepository watchdogDistributionStatusRepository; + @Autowired + protected WatchdogServiceModVerIdLookupRepository watchdogModVerIdLookupRepository; + + @Autowired + protected TempNetworkHeatTemplateRepository tempNetworkLookupRepo; + + @Autowired + protected ExternalServiceToInternalServiceRepository externalServiceToInternalServiceRepository; + + protected static final MsoLogger logger = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC,ToscaResourceInstaller.class); + + public boolean isResourceAlreadyDeployed(VfResourceStructure vfResourceStruct) throws ArtifactInstallerException { + boolean status = false; + VfResourceStructure vfResourceStructure = vfResourceStruct; + try { + status = vfResourceStructure.isDeployedSuccessfully(); + } catch (RuntimeException e) { + status = false; + } + try { + Service existingService = serviceRepo.findOneByModelUUID(vfResourceStructure.getNotification().getServiceUUID()); + if(existingService != null) + status = true; + if (status) { + logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(), + vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(), + vfResourceStructure.getNotification().getServiceName(), + BigDecimalVersion.castAndCheckNotificationVersionToString( + vfResourceStructure.getNotification().getServiceVersion()), + vfResourceStructure.getNotification().getServiceUUID(), + vfResourceStructure.getResourceInstance().getResourceName(), "", ""); + WatchdogComponentDistributionStatus wdStatus = new WatchdogComponentDistributionStatus(vfResourceStruct.getNotification().getDistributionID(), MSO); + wdStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name()); + watchdogCDStatusRepository.saveAndFlush(wdStatus); + } else { + logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(), + vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(), + vfResourceStructure.getNotification().getServiceName(), + BigDecimalVersion.castAndCheckNotificationVersionToString( + vfResourceStructure.getNotification().getServiceVersion()), + vfResourceStructure.getNotification().getServiceUUID(), + vfResourceStructure.getResourceInstance().getResourceName(), "", ""); + } + return status; + } catch (Exception e) { + logger.error(MessageEnum.ASDC_ARTIFACT_CHECK_EXC, "", "", MsoLogger.ErrorCode.SchemaError, + "Exception - isResourceAlreadyDeployed"); + throw new ArtifactInstallerException("Exception caught during checking existence of the VNF Resource.", e); + } + } + + public void installTheComponentStatus(IStatusData iStatus) throws ArtifactInstallerException { + logger.debug("Entering installTheComponentStatus for distributionId " + iStatus.getDistributionID() + + " and ComponentName " + iStatus.getComponentName()); + + try { + WatchdogComponentDistributionStatus cdStatus = new WatchdogComponentDistributionStatus(iStatus.getDistributionID(), + iStatus.getComponentName()); + cdStatus.setComponentDistributionStatus(iStatus.getStatus().toString()); + watchdogCDStatusRepository.save(cdStatus); + + } catch (Exception e) { + logger.debug("Exception caught in installTheComponentStatus " + e.getMessage()); + throw new ArtifactInstallerException("Exception caught in installTheComponentStatus " + e.getMessage()); + } + } + + @Transactional(rollbackFor = { ArtifactInstallerException.class }) + public void installTheResource(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStruct) + throws ArtifactInstallerException { + VfResourceStructure vfResourceStructure = vfResourceStruct; + extractHeatInformation(toscaResourceStruct, vfResourceStructure); + + // PCLO: in case of deployment failure, use a string that will represent + // the type of artifact that failed... + List artifactListForLogging = new ArrayList<>(); + try { + createToscaCsar(toscaResourceStruct); + createService(toscaResourceStruct, vfResourceStruct); + Service service = toscaResourceStruct.getCatalogService(); + List vfNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceVfList(); + + + for (NodeTemplate nodeTemplate : vfNodeTemplatesList) { + + Metadata metadata = nodeTemplate.getMetaData(); + String serviceType = toscaResourceStruct.getCatalogService().getServiceType(); + String vfCustomizationCategory = toscaResourceStruct.getSdcCsarHelper() + .getMetadataPropertyValue(metadata, SdcPropertyNames.PROPERTY_NAME_CATEGORY); + processVfModules(toscaResourceStruct, vfResourceStructure, service, nodeTemplate, metadata, + vfCustomizationCategory); + } + + List allottedResourceList = toscaResourceStruct.getSdcCsarHelper().getAllottedResources(); + processAllottedResources(toscaResourceStruct, service, allottedResourceList); + processNetworks(toscaResourceStruct, service); + // process Network Collections + processNetworkCollections(toscaResourceStruct, service); + // Process Service Proxy & Configuration + processServiceProxyAndConfiguration(toscaResourceStruct, service); + + serviceRepo.save(service); + + WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(vfResourceStruct.getNotification().getDistributionID(), MSO); + status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name()); + watchdogCDStatusRepository.save(status); + + toscaResourceStruct.setSuccessfulDeployment(); + + } catch (Exception e) { + logger.debug("Exception :", e); + WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(vfResourceStruct.getNotification().getDistributionID(), MSO); + status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name()); + watchdogCDStatusRepository.save(status); + Throwable dbExceptionToCapture = e; + while (!(dbExceptionToCapture instanceof ConstraintViolationException + || dbExceptionToCapture instanceof LockAcquisitionException) + && (dbExceptionToCapture.getCause() != null)) { + dbExceptionToCapture = dbExceptionToCapture.getCause(); + } + + if (dbExceptionToCapture instanceof ConstraintViolationException + || dbExceptionToCapture instanceof LockAcquisitionException) { + logger.warn(MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED, + vfResourceStructure.getResourceInstance().getResourceName(), + vfResourceStructure.getNotification().getServiceVersion(), "", MsoLogger.ErrorCode.DataError, "Exception - ASCDC Artifact already deployed", e); + } else { + String elementToLog = (!artifactListForLogging.isEmpty() + ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString() + : "No element listed"); + logger.error(MessageEnum.ASDC_ARTIFACT_INSTALL_EXC, elementToLog, "", "", MsoLogger.ErrorCode.DataError, + "Exception caught during installation of " + + vfResourceStructure.getResourceInstance().getResourceName() + + ". Transaction rollback", + e); + throw new ArtifactInstallerException("Exception caught during installation of " + + vfResourceStructure.getResourceInstance().getResourceName() + ". Transaction rollback.", e); + } + } + } + + protected void processNetworks(ToscaResourceStructure toscaResourceStruct, Service service) + throws ArtifactInstallerException { + List nodeTemplatesVLList = toscaResourceStruct.getSdcCsarHelper().getServiceVlList(); + + if (nodeTemplatesVLList != null) { + for (NodeTemplate vlNode : nodeTemplatesVLList) { + String networkResourceModelName = vlNode.getMetaData() + .getValue(SdcPropertyNames.PROPERTY_NAME_NAME); + + TempNetworkHeatTemplateLookup tempNetworkLookUp = tempNetworkLookupRepo.findFirstBynetworkResourceModelName(networkResourceModelName); + + if (tempNetworkLookUp != null ) { + HeatTemplate heatTemplate = heatRepo.findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid()); + if (heatTemplate != null ) { + NetworkResourceCustomization networkCustomization = createNetwork(vlNode, toscaResourceStruct, heatTemplate,tempNetworkLookUp.getAicVersionMax(), + tempNetworkLookUp.getAicVersionMin(),service); + service.getNetworkCustomizations() + .add(networkCustomization); + } + else{ + throw new ArtifactInstallerException( + "No HeatTemplate found for artifactUUID: " + + tempNetworkLookUp.getHeatTemplateArtifactUuid()); + } + } else { + throw new ArtifactInstallerException( + "No NetworkResourceName found in TempNetworkHeatTemplateLookup for " + + networkResourceModelName); + } + + } + } + } + + protected void processAllottedResources(ToscaResourceStructure toscaResourceStruct, Service service, + List allottedResourceList) { + if (allottedResourceList != null) { + for (NodeTemplate allottedNode : allottedResourceList) { + service.getAllottedCustomizations() + .add(createAllottedResource(allottedNode, toscaResourceStruct, service)); + } + } + } + + protected void processServiceProxyAndConfiguration(ToscaResourceStructure toscaResourceStruct, Service service) { + + List serviceProxyResourceList = toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.SERVICE_PROXY); + + List configurationNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION); + + if (serviceProxyResourceList != null) { + for (NodeTemplate spNode : serviceProxyResourceList) { + createServiceProxy(spNode, service, toscaResourceStruct); + serviceProxyCustomizationRepo.saveAndFlush(toscaResourceStruct.getCatalogServiceProxyResourceCustomization()); + + for (NodeTemplate configNode : configurationNodeTemplatesList) { + + List requirementsList = toscaResourceStruct.getSdcCsarHelper().getRequirementsOf(configNode).getAll(); + for (RequirementAssignment requirement : requirementsList) { + if (requirement.getNodeTemplateName().equals(spNode.getName())) { + createConfiguration(configNode, toscaResourceStruct, toscaResourceStruct.getCatalogServiceProxyResourceCustomization()); + configCustomizationRepo.saveAndFlush(toscaResourceStruct.getCatalogConfigurationResourceCustomization()); + break; + } + } + } + + } + } + } + + protected void processNetworkCollections(ToscaResourceStructure toscaResourceStruct, Service service) { + + List networkCollectionList = toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CR); + + if (networkCollectionList != null) { + for (NodeTemplate crNode : networkCollectionList) { + + createNetworkCollection(crNode, toscaResourceStruct, service); + collectionRepo.saveAndFlush(toscaResourceStruct.getCatalogCollectionResource()); + + List networkInstanceGroupList = toscaResourceStruct.getCatalogNetworkInstanceGroup(); + for(NetworkInstanceGroup networkInstanceGroup : networkInstanceGroupList){ + instanceGroupRepo.saveAndFlush(networkInstanceGroup); + } + + } + } + service.getCollectionResourceCustomizations().add(toscaResourceStruct.getCatalogCollectionResourceCustomization()); + } + + protected void processVfModules(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStructure, + Service service, NodeTemplate nodeTemplate, Metadata metadata, String vfCustomizationCategory) throws Exception { + if (!vfCustomizationCategory.equalsIgnoreCase(ALLOTTED_RESOURCE)) + { + + String vfCustomizationUUID = toscaResourceStruct.getSdcCsarHelper() + .getMetadataPropertyValue(metadata, SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); + logger.debug("vfCustomizationUUID=" + vfCustomizationUUID); + + VnfResourceCustomization vnfResource = createVnfResource(nodeTemplate, toscaResourceStruct, service); + + for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) { + logger.debug("vfModuleStructure:" + vfModuleStructure.toString()); + List vfGroups = toscaResourceStruct + .getSdcCsarHelper().getVfModulesByVf(vfCustomizationUUID); + IVfModuleData vfMetadata = vfModuleStructure.getVfModuleMetadata(); + Optional matchingObject = vfGroups.stream(). + filter(group -> group.getMetadata().getValue("vfModuleModelCustomizationUUID").equals(vfMetadata.getVfModuleModelCustomizationUUID())). + findFirst(); + if(matchingObject.isPresent()){ + VfModuleCustomization vfModuleCustomization = createVFModuleResource(matchingObject.get(), nodeTemplate, toscaResourceStruct, vfResourceStructure,vfMetadata, vnfResource); + vfModuleCustomization.getVfModule().setVnfResources(vnfResource.getVnfResources()); + }else + throw (new Exception("Cannot find matching VFModule Customization")); + + } + service.getVnfCustomizations().add(vnfResource); + } + } + + protected void processFlexware(ToscaResourceStructure toscaResourceStruct, Service service, NodeTemplate nodeTemplate, + String serviceType) { + if (serviceType != null && serviceType.equalsIgnoreCase("Flexware")) { + + createVnfResource(nodeTemplate, toscaResourceStruct, service); + String modelName = toscaResourceStruct.getVnfResourceCustomization().getVnfResources().getModelName(); + + String modelVersion = BigDecimalVersion.castAndCheckNotificationVersionToString( + toscaResourceStruct.getCatalogVnfResourceCustomization().getVnfResources().getModelVersion()); + // check for duplicate record already in the database + VnfResource vnfResource = vnfRepo.findByModelNameAndModelVersion(modelName, modelVersion); + + if (vnfResource != null) { + toscaResourceStruct.setVnfAlreadyInstalled(true); + } + + vnfCustomizationRepo.saveAndFlush(toscaResourceStruct.getCatalogVnfResourceCustomization()); + } + } + + public void processWatchdog(String distributionId, String servideUUID) { + WatchdogServiceModVerIdLookup modVerIdLookup = new WatchdogServiceModVerIdLookup(distributionId,servideUUID); + watchdogModVerIdLookupRepository.saveAndFlush(modVerIdLookup); + + WatchdogDistributionStatus distributionStatus = new WatchdogDistributionStatus(distributionId); + watchdogDistributionStatusRepository.saveAndFlush(distributionStatus); + } + + protected void extractHeatInformation(ToscaResourceStructure toscaResourceStruct, + VfResourceStructure vfResourceStructure) { + for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { + + switch (vfModuleArtifact.getArtifactInfo().getArtifactType()) { + case ASDCConfiguration.HEAT: + case ASDCConfiguration.HEAT_NESTED: + createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, + vfModuleArtifact); + break; + case ASDCConfiguration.HEAT_VOL: + createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, + vfModuleArtifact); + VfModuleArtifact envModuleArtifact = getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact); + createHeatEnvFromArtifact(vfResourceStructure, envModuleArtifact); + break; + case ASDCConfiguration.HEAT_ENV: + createHeatEnvFromArtifact(vfResourceStructure, vfModuleArtifact); + break; + case ASDCConfiguration.HEAT_ARTIFACT: + createHeatFileFromArtifact(vfResourceStructure, vfModuleArtifact, + toscaResourceStruct); + break; + case ASDCConfiguration.HEAT_NET: + case ASDCConfiguration.OTHER: + logger.warn(MessageEnum.ASDC_ARTIFACT_TYPE_NOT_SUPPORT, + vfModuleArtifact.getArtifactInfo().getArtifactType() + "(Artifact Name:" + + vfModuleArtifact.getArtifactInfo().getArtifactName() + ")", + "", "", MsoLogger.ErrorCode.DataError, "Artifact type not supported"); + break; + default: + break; + + } + } + } + + protected VfModuleArtifact getHeatEnvArtifactFromGeneratedArtifact(VfResourceStructure vfResourceStructure, + VfModuleArtifact vfModuleArtifact) { + String artifactName = vfModuleArtifact.getArtifactInfo().getArtifactName(); + artifactName = artifactName.substring(0, artifactName.indexOf('.')); + for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { + if (moduleArtifact.getArtifactInfo().getArtifactName().contains(artifactName) + && moduleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) { + return moduleArtifact; + } + } + return null; + } + + public String verifyTheFilePrefixInArtifacts(String filebody, VfResourceStructure vfResourceStructure, + List listTypes) { + String newFileBody = filebody; + for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { + + if (listTypes.contains(moduleArtifact.getArtifactInfo().getArtifactType())) { + + newFileBody = verifyTheFilePrefixInString(newFileBody, + moduleArtifact.getArtifactInfo().getArtifactName()); + } + } + return newFileBody; + } + + public String verifyTheFilePrefixInString(final String body, final String filenameToVerify) { + + String needlePrefix = "file:///"; + String prefixedFilenameToVerify = needlePrefix + filenameToVerify; + + if ((body == null) || (body.length() == 0) || (filenameToVerify == null) || (filenameToVerify.length() == 0)) { + return body; + } + + StringBuilder sb = new StringBuilder(body.length()); + + int currentIndex = 0; + int startIndex = 0; + + while (currentIndex != -1) { + startIndex = currentIndex; + currentIndex = body.indexOf(prefixedFilenameToVerify, startIndex); + + if (currentIndex == -1) { + break; + } + // We append from the startIndex up to currentIndex (start of File + // Name) + sb.append(body.substring(startIndex, currentIndex)); + sb.append(filenameToVerify); + + currentIndex += prefixedFilenameToVerify.length(); + } + + sb.append(body.substring(startIndex)); + + return sb.toString(); + } + + protected void createHeatTemplateFromArtifact(VfResourceStructure vfResourceStructure, + ToscaResourceStructure toscaResourceStruct, VfModuleArtifact vfModuleArtifact) { + HeatTemplate heatTemplate = new HeatTemplate(); + List typeList = new ArrayList<>(); + typeList.add(ASDCConfiguration.HEAT_NESTED); + typeList.add(ASDCConfiguration.HEAT_ARTIFACT); + + heatTemplate.setTemplateBody( + verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList)); + heatTemplate.setTemplateName(vfModuleArtifact.getArtifactInfo().getArtifactName()); + + if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) { + heatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout()); + } else { + heatTemplate.setTimeoutMinutes(240); + } + + heatTemplate.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); + heatTemplate.setVersion(BigDecimalVersion + .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); + heatTemplate.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + + if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { + heatTemplate.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); + } else { + heatTemplate.setArtifactChecksum(MANUAL_RECORD); + } + + Set heatParam = extractHeatTemplateParameters( + vfModuleArtifact.getResult(), vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + heatTemplate.setParameters(heatParam); + vfModuleArtifact.setHeatTemplate(heatTemplate); + } + + protected void createHeatEnvFromArtifact(VfResourceStructure vfResourceStructure, + VfModuleArtifact vfModuleArtifact) { + HeatEnvironment heatEnvironment = new HeatEnvironment(); + heatEnvironment.setName(vfModuleArtifact.getArtifactInfo().getArtifactName()); + List typeList = new ArrayList<>(); + typeList.add(ASDCConfiguration.HEAT); + typeList.add(ASDCConfiguration.HEAT_VOL); + heatEnvironment.setEnvironment( + verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList)); + heatEnvironment.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); + heatEnvironment.setVersion(BigDecimalVersion + .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); + heatEnvironment.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + + if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { + heatEnvironment.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); + } else { + heatEnvironment.setArtifactChecksum(MANUAL_RECORD); + } + vfModuleArtifact.setHeatEnvironment(heatEnvironment); + } + + protected void createHeatFileFromArtifact(VfResourceStructure vfResourceStructure, + VfModuleArtifact vfModuleArtifact, ToscaResourceStructure toscaResourceStruct) { + + HeatFiles heatFile = new HeatFiles(); + heatFile.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + heatFile.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); + heatFile.setFileBody(vfModuleArtifact.getResult()); + heatFile.setFileName(vfModuleArtifact.getArtifactInfo().getArtifactName()); + heatFile.setVersion(BigDecimalVersion + .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); + toscaResourceStruct.setHeatFilesUUID(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { + heatFile.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); + } else { + heatFile.setArtifactChecksum(MANUAL_RECORD); + } + vfModuleArtifact.setHeatFiles(heatFile); + } + + protected Service createService(ToscaResourceStructure toscaResourceStructure, + VfResourceStructure vfResourceStructure) { + + toscaResourceStructure.getServiceMetadata(); + + Metadata serviceMetadata = toscaResourceStructure.getServiceMetadata(); + + Service service = new Service(); + + if (serviceMetadata != null) { + + if (toscaResourceStructure.getServiceVersion() != null) { + service.setModelVersion(toscaResourceStructure.getServiceVersion()); + } + + service.setServiceType(serviceMetadata.getValue("serviceType")); + service.setServiceRole(serviceMetadata.getValue("serviceRole")); + + service.setDescription(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + service.setModelName(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + service.setModelUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + service.setEnvironmentContext(serviceMetadata.getValue("environmentContext")); + + if (vfResourceStructure != null) + service.setWorkloadContext(vfResourceStructure.getNotification().getWorkloadContext()); + + service.setModelInvariantUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + service.setCsar(toscaResourceStructure.getCatalogToscaCsar()); + } + + + toscaResourceStructure.setCatalogService(service); + return service; + } + + protected ServiceProxyResourceCustomization createServiceProxy(NodeTemplate nodeTemplate, Service service, ToscaResourceStructure toscaResourceStructure) { + + Metadata spMetadata = nodeTemplate.getMetaData(); + + ServiceProxyResource spResource = new ServiceProxyResource(); + + spResource.setModelName(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + spResource.setModelInvariantUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + spResource.setModelUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + spResource.setModelVersion(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + spResource.setDescription(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + + ServiceProxyResourceCustomization spCustomizationResource = new ServiceProxyResourceCustomization(); + + Set serviceProxyCustomizationSet = new HashSet<>(); + + spCustomizationResource.setModelCustomizationUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + spCustomizationResource.setModelInstanceName(nodeTemplate.getName()); + spCustomizationResource.setToscaNodeType(nodeTemplate.getType()); + spCustomizationResource.setSourceService(service); + spCustomizationResource.setServiceProxyResource(spResource); + spCustomizationResource.setToscaNodeType(nodeTemplate.getType()); + spCustomizationResource.setServiceProxyResource(spResource); + serviceProxyCustomizationSet.add(spCustomizationResource); + + + spResource.setServiceProxyCustomization(serviceProxyCustomizationSet); + + toscaResourceStructure.setCatalogServiceProxyResource(spResource); + + toscaResourceStructure.setCatalogServiceProxyResourceCustomization(spCustomizationResource); + + return spCustomizationResource; + } + + protected ConfigurationResourceCustomization createConfiguration(NodeTemplate nodeTemplate, ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization) { + + Metadata metadata = nodeTemplate.getMetaData(); + + ConfigurationResource configResource = new ConfigurationResource(); + + configResource.setModelName(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + configResource.setModelInvariantUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + configResource.setModelUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + configResource.setModelVersion(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + configResource.setDescription(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + configResource.setToscaNodeType(nodeTemplate.getType()); + + ConfigurationResourceCustomization configCustomizationResource = new ConfigurationResourceCustomization(); + + Set configResourceCustomizationSet = new HashSet<>(); + + configCustomizationResource.setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + configCustomizationResource.setModelInstanceName(nodeTemplate.getName()); + + configCustomizationResource.setNfFunction(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)); + configCustomizationResource.setNfRole(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)); + configCustomizationResource.setNfType(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)); + configCustomizationResource.setServiceProxyResourceCustomization(spResourceCustomization); + configCustomizationResource.setConfigResourceCustomization(configCustomizationResource); + configCustomizationResource.setConfigurationResource(configResource); + configResourceCustomizationSet.add(configCustomizationResource); + + configResource.setConfigurationResourceCustomization(configResourceCustomizationSet); + + toscaResourceStructure.setCatalogConfigurationResource(configResource); + + toscaResourceStructure.setCatalogConfigurationResourceCustomization(configCustomizationResource); + + return configCustomizationResource; + } + + + protected void createToscaCsar(ToscaResourceStructure toscaResourceStructure) { + ToscaCsar toscaCsar = new ToscaCsar(); + if (toscaResourceStructure.getToscaArtifact().getArtifactChecksum() != null) { + toscaCsar.setArtifactChecksum(toscaResourceStructure.getToscaArtifact().getArtifactChecksum()); + } else { + toscaCsar.setArtifactChecksum(MANUAL_RECORD); + } + toscaCsar.setArtifactUUID(toscaResourceStructure.getToscaArtifact().getArtifactUUID()); + toscaCsar.setName(toscaResourceStructure.getToscaArtifact().getArtifactName()); + toscaCsar.setVersion(toscaResourceStructure.getToscaArtifact().getArtifactVersion()); + toscaCsar.setDescription(toscaResourceStructure.getToscaArtifact().getArtifactDescription()); + toscaCsar.setUrl(toscaResourceStructure.getToscaArtifact().getArtifactURL()); + + toscaResourceStructure.setCatalogToscaCsar(toscaCsar); + } + + protected NetworkResourceCustomization createNetwork(NodeTemplate networkNodeTemplate, + ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin,Service service) { + + NetworkResourceCustomization networkResourceCustomization=networkCustomizationRepo.findOneByModelCustomizationUUID(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + if(networkResourceCustomization==null){ + networkResourceCustomization = createNetworkResourceCustomization(networkNodeTemplate, + toscaResourceStructure); + + NetworkResource networkResource = findExistingNetworkResource(service, + networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + if(networkResource == null) + networkResource = createNetworkResource(networkNodeTemplate, toscaResourceStructure, heatTemplate, + aicMax, aicMin); + + networkResource.addNetworkResourceCustomization(networkResourceCustomization); + networkResourceCustomization.setNetworkResource(networkResource); + } + return networkResourceCustomization; + } + + protected NetworkResource findExistingNetworkResource(Service service, String modelUUID) { + NetworkResource networkResource = null; + for(NetworkResourceCustomization networkCustom : service.getNetworkCustomizations()){ + if (networkCustom.getNetworkResource() != null + && networkCustom.getNetworkResource().getModelUUID().equals(modelUUID)) { + networkResource = networkCustom.getNetworkResource(); + } + } + if(networkResource==null) + networkResource = networkRepo.findResourceByModelUUID(modelUUID); + + return networkResource; + } + + protected NetworkResourceCustomization createNetworkResourceCustomization(NodeTemplate networkNodeTemplate, + ToscaResourceStructure toscaResourceStructure) { + NetworkResourceCustomization networkResourceCustomization = new NetworkResourceCustomization(); + networkResourceCustomization.setModelInstanceName( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + networkResourceCustomization.setModelCustomizationUUID( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); + + networkResourceCustomization.setNetworkTechnology( + testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY))); + networkResourceCustomization.setNetworkType(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE))); + networkResourceCustomization.setNetworkRole(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE))); + networkResourceCustomization.setNetworkScope(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE))); + return networkResourceCustomization; + } + + protected NetworkResource createNetworkResource(NodeTemplate networkNodeTemplate, + ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin) { + NetworkResource networkResource = new NetworkResource(); + String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue( + networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK); + + if ("true".equalsIgnoreCase(providerNetwork)) { + networkResource.setNeutronNetworkType(PROVIDER); + } else { + networkResource.setNeutronNetworkType(BASIC); + } + + networkResource.setModelName( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + + networkResource.setModelInvariantUUID( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); + networkResource.setModelUUID( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); + networkResource.setModelVersion( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + + networkResource.setAicVersionMax(aicMax); + networkResource.setAicVersionMin(aicMin); + networkResource.setToscaNodeType(networkNodeTemplate.getType()); + networkResource.setDescription( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + networkResource.setOrchestrationMode(HEAT); + networkResource.setHeatTemplate(heatTemplate); + return networkResource; + } + + protected CollectionNetworkResourceCustomization createNetworkCollection(NodeTemplate networkNodeTemplate, + ToscaResourceStructure toscaResourceStructure, Service service) { + + CollectionNetworkResourceCustomization collectionNetworkResourceCustomization = new CollectionNetworkResourceCustomization(); + + // **** Build Object to populate Collection_Resource table + CollectionResource collectionResource = new CollectionResource(); + + collectionResource + .setModelName(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + collectionResource.setModelInvariantUUID( + networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + collectionResource + .setModelUUID(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + collectionResource + .setModelVersion(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + collectionResource + .setDescription(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + collectionResource.setToscaNodeType(networkNodeTemplate.getType()); + + toscaResourceStructure.setCatalogCollectionResource(collectionResource); + + // **** Build object to populate Collection_Resource_Customization table + NetworkCollectionResourceCustomization ncfc = new NetworkCollectionResourceCustomization(); + + ncfc.setFunction(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + "cr_function")); + ncfc.setRole(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + "cr_role")); + ncfc.setType(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + "cr_type")); + + ncfc.setModelInstanceName(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + ncfc.setModelCustomizationUUID( + networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + + Set networkResourceCustomizationSet = new HashSet<>(); + networkResourceCustomizationSet.add(collectionNetworkResourceCustomization); + + ncfc.setNetworkResourceCustomization(networkResourceCustomizationSet); + + ncfc.setCollectionResource(collectionResource); + toscaResourceStructure.setCatalogCollectionResourceCustomization(ncfc); + + //*** Build object to populate the Instance_Group table + List groupList = toscaResourceStructure.getSdcCsarHelper() + .getGroupsOfOriginOfNodeTemplateByToscaGroupType(networkNodeTemplate, + "org.openecomp.groups.NetworkCollection"); + + List networkInstanceGroupList = new ArrayList<>(); + + List collectionResourceInstanceGroupCustomizationList = new ArrayList(); + + for (Group group : groupList) { + + NetworkInstanceGroup networkInstanceGroup = new NetworkInstanceGroup(); + Metadata instanceMetadata = group.getMetadata(); + networkInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + networkInstanceGroup + .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + networkInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + networkInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + networkInstanceGroup.setToscaNodeType(group.getType()); + networkInstanceGroup.setRole(SubType.SUB_INTERFACE.toString()); // Set + // Role + networkInstanceGroup.setType(InstanceGroupType.L3_NETWORK); // Set + // type + networkInstanceGroup.setCollectionResource(collectionResource); + + // ****Build object to populate + // Collection_Resource_Instance_Group_Customization table + CollectionResourceInstanceGroupCustomization crInstanceGroupCustomization = new CollectionResourceInstanceGroupCustomization(); + crInstanceGroupCustomization.setInstanceGroup(networkInstanceGroup); + crInstanceGroupCustomization.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + crInstanceGroupCustomization.setModelCustomizationUUID( + networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + + String quantityName = instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME); + String fixedQuantity = quantityName.replace("NetworkCollection", "Fixed"); + if (toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + fixedQuantity + "_quantity") != null) { + + crInstanceGroupCustomization.setSubInterfaceNetworkQuantity(Integer.parseInt( + toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + fixedQuantity + "_quantity"))); + } + + crInstanceGroupCustomization.setDescription( + toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME) + + "_network_collection_description")); + crInstanceGroupCustomization.setFunction( + toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME) + + "_network_collection_function")); + crInstanceGroupCustomization.setCollectionResourceCust(ncfc); + collectionResourceInstanceGroupCustomizationList.add(crInstanceGroupCustomization); + + networkInstanceGroup + .setCollectionInstanceGroupCustomizations(collectionResourceInstanceGroupCustomizationList); + + networkInstanceGroupList.add(networkInstanceGroup); + + //} + + toscaResourceStructure.setCatalogNetworkInstanceGroup(networkInstanceGroupList); + + List vlNodeList = toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplateBySdcType(networkNodeTemplate, SdcTypes.VL); + + List collectionNetworkResourceCustomizationList = new ArrayList<>(); + + //*****Build object to populate the NetworkResource table + NetworkResource networkResource = new NetworkResource(); + + for(NodeTemplate vlNodeTemplate : vlNodeList){ + + String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue( + vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK); + + if ("true".equalsIgnoreCase(providerNetwork)) { + networkResource.setNeutronNetworkType(PROVIDER); + } else { + networkResource.setNeutronNetworkType(BASIC); + } + + networkResource.setModelName(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + + networkResource.setModelInvariantUUID( + vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + networkResource.setModelUUID(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + networkResource + .setModelVersion(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + + networkResource.setAicVersionMax( + vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)); + + TempNetworkHeatTemplateLookup tempNetworkLookUp = tempNetworkLookupRepo.findFirstBynetworkResourceModelName( + vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + + if (tempNetworkLookUp != null ) { + + HeatTemplate heatTemplate = heatRepo + .findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid()); + networkResource.setHeatTemplate(heatTemplate); + + networkResource.setAicVersionMin(tempNetworkLookUp.getAicVersionMin()); + + } + + networkResource.setToscaNodeType(vlNodeTemplate.getType()); + networkResource + .setDescription(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + networkResource.setOrchestrationMode(HEAT); + + // Build object to populate the + // Collection_Network_Resource_Customization table + for (NodeTemplate memberNode : group.getMemberNodes()) { + collectionNetworkResourceCustomization.setModelInstanceName(memberNode.getName()); + } + + collectionNetworkResourceCustomization.setModelCustomizationUUID( + vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + + collectionNetworkResourceCustomization.setNetworkTechnology( + toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNodeTemplate, + SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY)); + collectionNetworkResourceCustomization.setNetworkType(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE)); + collectionNetworkResourceCustomization.setNetworkRole(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE)); + collectionNetworkResourceCustomization.setNetworkScope(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE)); + collectionNetworkResourceCustomization.setInstanceGroup(networkInstanceGroup); + collectionNetworkResourceCustomization.setNetworkResource(networkResource); + collectionNetworkResourceCustomization.setNetworkResourceCustomization(ncfc); + + collectionNetworkResourceCustomizationList.add(collectionNetworkResourceCustomization); + } + + } + + return collectionNetworkResourceCustomization; + } + + protected VnfcInstanceGroupCustomization createVNFCInstanceGroup(NodeTemplate vnfcNodeTemplate, Group group, + VnfResourceCustomization vnfResourceCustomization) { + + Metadata instanceMetadata = group.getMetadata(); + // Populate InstanceGroup + VFCInstanceGroup vfcInstanceGroup = new VFCInstanceGroup(); + + vfcInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + vfcInstanceGroup.setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + vfcInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + vfcInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + vfcInstanceGroup.setToscaNodeType(group.getType()); + vfcInstanceGroup.setRole("SUB-INTERFACE"); // Set Role + vfcInstanceGroup.setType(InstanceGroupType.VNFC); // Set type + + //Populate VNFCInstanceGroupCustomization + VnfcInstanceGroupCustomization vfcInstanceGroupCustom = new VnfcInstanceGroupCustomization(); + + vfcInstanceGroupCustom.setModelCustomizationUUID(vnfResourceCustomization.getModelCustomizationUUID()); + vfcInstanceGroupCustom.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + vfcInstanceGroupCustom.setDescription(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + vfcInstanceGroupCustom.setFunction("FUNCTION"); + vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup); + vfcInstanceGroupCustom.setVnfResourceCust(vnfResourceCustomization); + + return vfcInstanceGroupCustom; + + } + + protected VFCInstanceGroup findExistingVnfcInstanceGroup(VnfResourceCustomization vnfResourceCustomization, + String modelUUID) { + VFCInstanceGroup vfcInstanceGroup = null; + List vnfInstanceGroupCustomizations = vnfResourceCustomization + .getVnfcInstanceGroupCustomizations(); + if(vnfInstanceGroupCustomizations != null){ + for (VnfcInstanceGroupCustomization vnfcInstanceGroupCustom : vnfResourceCustomization + .getVnfcInstanceGroupCustomizations()) { + if (vnfcInstanceGroupCustom.getInstanceGroup() != null + && vnfcInstanceGroupCustom.getInstanceGroup().getModelUUID().equals(modelUUID)) { + vfcInstanceGroup = (VFCInstanceGroup)vnfcInstanceGroupCustom.getInstanceGroup(); + } + } + } + if (vfcInstanceGroup == null) + vfcInstanceGroup = (VFCInstanceGroup) instanceGroupRepo.findByModelUUID(modelUUID); + + return vfcInstanceGroup; + } + + protected VfModuleCustomization createVFModuleResource(Group group, NodeTemplate nodeTemplate, + ToscaResourceStructure toscaResourceStructure, VfResourceStructure vfResourceStructure, + IVfModuleData vfModuleData, VnfResourceCustomization vnfResource) { + VfModuleCustomization vfModuleCustomization = findExistingVfModuleCustomization(vnfResource, + vfModuleData.getVfModuleModelCustomizationUUID()); + if(vfModuleCustomization == null){ + VfModule vfModule = findExistingVfModule(vnfResource, + nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)); + Metadata vfMetadata = group.getMetadata(); + if(vfModule==null) + vfModule=createVfModule(group, toscaResourceStructure, vfModuleData, vfMetadata); + + vfModuleCustomization = createVfModuleCustomzation(group, toscaResourceStructure, vfModule, vfModuleData); + setHeatInformationForVfModule(toscaResourceStructure, vfResourceStructure, vfModule, vfModuleCustomization, + vfMetadata); + vfModuleCustomization.setVfModule(vfModule); + vfModule.getVfModuleCustomization().add(vfModuleCustomization); + vnfResource.getVfModuleCustomizations().add(vfModuleCustomization); + } else { + vfResourceStructure.setAlreadyDeployed(true); + } + + return vfModuleCustomization; + } + + protected VfModuleCustomization findExistingVfModuleCustomization(VnfResourceCustomization vnfResource, + String vfModuleModelCustomizationUUID) { + VfModuleCustomization vfModuleCustomization = null; + for(VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()){ + if(vfModuleCustom.getModelCustomizationUUID().equalsIgnoreCase(vfModuleModelCustomizationUUID)){ + vfModuleCustomization = vfModuleCustom; + } + } + if(vfModuleCustomization==null) + vfModuleCustomization = vfModuleCustomizationRepo + .findByModelCustomizationUUID(vfModuleModelCustomizationUUID); + + return vfModuleCustomization; + } + + protected VfModule findExistingVfModule(VnfResourceCustomization vnfResource, String modelUUID) { + VfModule vfModule = null; + for(VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()){ + if(vfModuleCustom.getVfModule() != null && vfModuleCustom.getVfModule().getModelUUID().equals(modelUUID)){ + vfModule = vfModuleCustom.getVfModule(); + } + } + if(vfModule==null) + vfModule = vfModuleRepo.findByModelUUID(modelUUID); + + return vfModule; + } + + protected VfModuleCustomization createVfModuleCustomzation(Group group, + ToscaResourceStructure toscaResourceStructure, VfModule vfModule, IVfModuleData vfModuleData) { + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + + vfModuleCustomization.setModelCustomizationUUID(vfModuleData.getVfModuleModelCustomizationUUID()); + + vfModuleCustomization.setVfModule(vfModule); + + String initialCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, + SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT); + if (initialCount != null && initialCount.length() > 0) { + vfModuleCustomization.setInitialCount(Integer.valueOf(initialCount)); + } + + vfModuleCustomization.setInitialCount(Integer.valueOf(toscaResourceStructure.getSdcCsarHelper() + .getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT))); + + String availabilityZoneCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, + SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT); + if (availabilityZoneCount != null && availabilityZoneCount.length() > 0) { + vfModuleCustomization.setAvailabilityZoneCount(Integer.valueOf(availabilityZoneCount)); + } + + vfModuleCustomization.setLabel(toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, + SdcPropertyNames.PROPERTY_NAME_VFMODULELABEL)); + + String maxInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, + SdcPropertyNames.PROPERTY_NAME_MAXVFMODULEINSTANCES); + if (maxInstances != null && maxInstances.length() > 0) { + vfModuleCustomization.setMaxInstances(Integer.valueOf(maxInstances)); + } + + String minInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, + SdcPropertyNames.PROPERTY_NAME_MINVFMODULEINSTANCES); + if (minInstances != null && minInstances.length() > 0) { + vfModuleCustomization.setMinInstances(Integer.valueOf(minInstances)); + } + return vfModuleCustomization; + } + + protected VfModule createVfModule(Group group, ToscaResourceStructure toscaResourceStructure, + IVfModuleData vfModuleData, Metadata vfMetadata) { + VfModule vfModule = new VfModule(); + String vfModuleModelUUID = vfModuleData.getVfModuleModelUUID(); + + if(vfModuleModelUUID == null) { + vfModuleModelUUID = testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, + SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)); + } else if (vfModuleModelUUID.indexOf('.') > -1) { + vfModuleModelUUID = vfModuleModelUUID.substring(0, vfModuleModelUUID.indexOf('.')); + } + + vfModule.setModelInvariantUUID(testNull(toscaResourceStructure.getSdcCsarHelper() + .getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID))); + vfModule.setModelName(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, + SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME))); + vfModule.setModelUUID(vfModuleModelUUID); + vfModule.setModelVersion(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, + SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION))); + vfModule.setDescription(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, + SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + + String vfModuleType = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, + SdcPropertyNames.PROPERTY_NAME_VFMODULETYPE); + if (vfModuleType != null && "Base".equalsIgnoreCase(vfModuleType)) { + vfModule.setIsBase(true); + } else { + vfModule.setIsBase(false); + } + return vfModule; + } + + protected void setHeatInformationForVfModule(ToscaResourceStructure toscaResourceStructure, + VfResourceStructure vfResourceStructure, VfModule vfModule, VfModuleCustomization vfModuleCustomization, + Metadata vfMetadata) { + Optional matchingObject = vfResourceStructure.getVfModuleStructure().stream() + .filter(vfModuleStruct -> vfModuleStruct.getVfModuleMetadata().getVfModuleModelUUID() + .equalsIgnoreCase(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, + SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID))) + .findFirst(); + + if (matchingObject.isPresent()) { + List heatFilesList = new ArrayList<>(); + List volumeHeatChildTemplates = new ArrayList(); + List heatChildTemplates = new ArrayList(); + HeatTemplate parentHeatTemplate = new HeatTemplate(); + String parentArtifactType = null; + Set artifacts = new HashSet<>(matchingObject.get().getVfModuleMetadata().getArtifacts()); + for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { + + List childNestedHeatTemplates = new ArrayList(); + + if (artifacts.contains(vfModuleArtifact.getArtifactInfo().getArtifactUUID())) { + checkVfModuleArtifactType(vfModule, vfModuleCustomization, heatFilesList, vfModuleArtifact, + childNestedHeatTemplates, parentHeatTemplate, vfResourceStructure); + } + + if(vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)){ + parentArtifactType = identifyParentOfNestedTemplate(matchingObject.get(), vfModuleArtifact); + + if(!childNestedHeatTemplates.isEmpty()){ + + if (parentArtifactType != null && parentArtifactType.equalsIgnoreCase(ASDCConfiguration.HEAT_VOL)) { + volumeHeatChildTemplates.add(childNestedHeatTemplates.get(0)); + } else { + heatChildTemplates.add(childNestedHeatTemplates.get(0)); + } + } + } + + } + if(!heatFilesList.isEmpty()){ + vfModule.setHeatFiles(heatFilesList); + } + + + // Set all Child Templates related to HEAT_VOLUME + if(!volumeHeatChildTemplates.isEmpty()){ + vfModule.getVolumeHeatTemplate().setChildTemplates(volumeHeatChildTemplates); + } + + // Set all Child Templates related to HEAT + if(!heatChildTemplates.isEmpty()){ + vfModule.getVolumeHeatTemplate().setChildTemplates(heatChildTemplates); + } + } + } + + protected void checkVfModuleArtifactType(VfModule vfModule, VfModuleCustomization vfModuleCustomization, + List heatFilesList, VfModuleArtifact vfModuleArtifact, List nestedHeatTemplates, + HeatTemplate parentHeatTemplate, VfResourceStructure vfResourceStructure) { + if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT)) { + vfModuleArtifact.incrementDeployedInDB(); + vfModule.setModuleHeatTemplate(vfModuleArtifact.getHeatTemplate()); + } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_VOL)) { + vfModule.setVolumeHeatTemplate(vfModuleArtifact.getHeatTemplate()); + VfModuleArtifact volVfModuleArtifact = this.getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact); + vfModuleCustomization.setVolumeHeatEnv(volVfModuleArtifact.getHeatEnvironment()); + vfModuleArtifact.incrementDeployedInDB(); + } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) { + if(vfModuleArtifact.getHeatEnvironment().getName().contains("volume")) { + vfModuleCustomization.setVolumeHeatEnv(vfModuleArtifact.getHeatEnvironment()); + } else { + vfModuleCustomization.setHeatEnvironment(vfModuleArtifact.getHeatEnvironment()); + } + vfModuleArtifact.incrementDeployedInDB(); + } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ARTIFACT)) { + heatFilesList.add(vfModuleArtifact.getHeatFiles()); + vfModuleArtifact.incrementDeployedInDB(); + } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) { + nestedHeatTemplates.add(vfModuleArtifact.getHeatTemplate()); + vfModuleArtifact.incrementDeployedInDB(); + } + } + + protected VnfResourceCustomization createVnfResource(NodeTemplate vfNodeTemplate, + ToscaResourceStructure toscaResourceStructure, Service service) { + VnfResourceCustomization vnfResourceCustomization = vnfCustomizationRepo.findOneByModelCustomizationUUID( + vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + if(vnfResourceCustomization == null){ + VnfResource vnfResource = findExistingVnfResource(service, + vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + + if(vnfResource==null) + vnfResource=createVnfResource(vfNodeTemplate); + + vnfResourceCustomization = createVnfResourceCustomization(vfNodeTemplate, toscaResourceStructure, + vnfResource); + vnfResourceCustomization.setVnfResources(vnfResource); + vnfResource.getVnfResourceCustomizations().add(vnfResourceCustomization); + + // Fetch VNFC Instance Group Info + List groupList = toscaResourceStructure.getSdcCsarHelper() + .getGroupsOfOriginOfNodeTemplateByToscaGroupType(vfNodeTemplate, + "org.openecomp.groups.VfcInstanceGroup"); + + for (Group group : groupList) { + + VFCInstanceGroup vfcInstanceGroup = findExistingVnfcInstanceGroup(vnfResourceCustomization, + group.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + if(vfcInstanceGroup == null){ + VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization = createVNFCInstanceGroup( + vfNodeTemplate, group, vnfResourceCustomization); + + vnfcInstanceGroupCustomizationRepo.saveAndFlush(vnfcInstanceGroupCustomization); + } + } + + } + return vnfResourceCustomization; + } + + protected VnfResource findExistingVnfResource(Service service, String modelUUID) { + VnfResource vnfResource = null; + for(VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()){ + if (vnfResourceCustom.getVnfResources() != null + && vnfResourceCustom.getVnfResources().getModelUUID().equals(modelUUID)) { + vnfResource = vnfResourceCustom.getVnfResources(); + } + } + if(vnfResource==null) + vnfResource = vnfRepo.findResourceByModelUUID(modelUUID); + + return vnfResource; + } + + protected VnfResourceCustomization createVnfResourceCustomization(NodeTemplate vfNodeTemplate, + ToscaResourceStructure toscaResourceStructure, VnfResource vnfResource) { + VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization(); + vnfResourceCustomization.setModelCustomizationUUID( + testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); + vnfResourceCustomization.setModelInstanceName(vfNodeTemplate.getName()); + + vnfResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION))); + vnfResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, "nf_naming_code"))); + vnfResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE))); + vnfResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE))); + + vnfResourceCustomization.setMultiStageDesign(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, MULTI_STAGE_DESIGN)); + + vnfResourceCustomization.setVnfResources(vnfResource); + vnfResourceCustomization.setAvailabilityZoneMaxCount(Integer.getInteger( + vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT))); + + CapabilityAssignments vnfCustomizationCapability = toscaResourceStructure.getSdcCsarHelper() + .getCapabilitiesOf(vfNodeTemplate); + + if (vnfCustomizationCapability != null) { + CapabilityAssignment capAssign = vnfCustomizationCapability.getCapabilityByName(SCALABLE); + + if (capAssign != null) { + vnfResourceCustomization.setMinInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper() + .getCapabilityPropertyLeafValue(capAssign, SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); + vnfResourceCustomization.setMaxInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper() + .getCapabilityPropertyLeafValue(capAssign, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); + } + + } + + toscaResourceStructure.setCatalogVnfResourceCustomization(vnfResourceCustomization); + + return vnfResourceCustomization; + } + + protected VnfResource createVnfResource(NodeTemplate vfNodeTemplate) { + VnfResource vnfResource = new VnfResource(); + vnfResource.setModelInvariantUUID( + testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); + vnfResource.setModelName(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + vnfResource.setModelUUID(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); + + vnfResource.setModelVersion( + testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + vnfResource.setDescription( + testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + vnfResource.setOrchestrationMode(HEAT); + vnfResource.setToscaNodeType(testNull(vfNodeTemplate.getType())); + vnfResource.setAicVersionMax( + testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); + vnfResource.setAicVersionMin( + testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); + + return vnfResource; + } + + protected AllottedResourceCustomization createAllottedResource(NodeTemplate nodeTemplate, + ToscaResourceStructure toscaResourceStructure, Service service) { + AllottedResourceCustomization allottedResourceCustomization = allottedCustomizationRepo + .findOneByModelCustomizationUUID( + nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + + if(allottedResourceCustomization == null){ + AllottedResource allottedResource = findExistingAllottedResource(service, + nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + + if(allottedResource==null) + allottedResource=createAR(nodeTemplate); + + toscaResourceStructure.setAllottedResource(allottedResource); + allottedResourceCustomization = createAllottedResourceCustomization(nodeTemplate, toscaResourceStructure); + allottedResourceCustomization.setAllottedResource(allottedResource); + allottedResource.getAllotedResourceCustomization().add(allottedResourceCustomization); + } + return allottedResourceCustomization; + } + + protected AllottedResource findExistingAllottedResource(Service service, String modelUUID) { + AllottedResource allottedResource = null; + for(AllottedResourceCustomization allottedResourceCustom : service.getAllottedCustomizations()){ + if (allottedResourceCustom.getAllottedResource() != null + && allottedResourceCustom.getAllottedResource().getModelUUID().equals(modelUUID)) { + allottedResource = allottedResourceCustom.getAllottedResource(); + } + } + if(allottedResource==null) + allottedResource = allottedRepo.findResourceByModelUUID(modelUUID); + + return allottedResource; + } + + protected AllottedResourceCustomization createAllottedResourceCustomization(NodeTemplate nodeTemplate, + ToscaResourceStructure toscaResourceStructure) { + AllottedResourceCustomization allottedResourceCustomization = new AllottedResourceCustomization(); + allottedResourceCustomization.setModelCustomizationUUID( + testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); + allottedResourceCustomization.setModelInstanceName(nodeTemplate.getName()); + + + allottedResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION))); + allottedResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(nodeTemplate, "nf_naming_code"))); + allottedResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE))); + allottedResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE))); + + List vfcNodes = toscaResourceStructure.getSdcCsarHelper().getVfcListByVf(allottedResourceCustomization.getModelCustomizationUUID()); + + if(vfcNodes != null){ + for(NodeTemplate vfcNode : vfcNodes){ + + allottedResourceCustomization.setProvidingServiceModelUUID(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_uuid")); + allottedResourceCustomization.setProvidingServiceModelInvariantUUID(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_invariant_uuid")); + allottedResourceCustomization.setProvidingServiceModelName(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_name")); + } + } + + + CapabilityAssignments arCustomizationCapability = toscaResourceStructure.getSdcCsarHelper() + .getCapabilitiesOf(nodeTemplate); + + if (arCustomizationCapability != null) { + CapabilityAssignment capAssign = arCustomizationCapability.getCapabilityByName(SCALABLE); + + if (capAssign != null) { + allottedResourceCustomization.setMinInstances( + Integer.getInteger(toscaResourceStructure.getSdcCsarHelper().getCapabilityPropertyLeafValue( + capAssign, SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); + allottedResourceCustomization.setMaxInstances( + Integer.getInteger(toscaResourceStructure.getSdcCsarHelper().getCapabilityPropertyLeafValue( + capAssign, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); + } + } + return allottedResourceCustomization; + } + + protected AllottedResource createAR(NodeTemplate nodeTemplate) { + AllottedResource allottedResource = new AllottedResource(); + allottedResource + .setModelUUID(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); + allottedResource.setModelInvariantUUID( + testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); + allottedResource + .setModelName(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + allottedResource + .setModelVersion(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + allottedResource.setToscaNodeType(testNull(nodeTemplate.getType())); + allottedResource.setSubcategory( + testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY))); + allottedResource + .setDescription(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + return allottedResource; + } + + protected Set extractHeatTemplateParameters(String yamlFile, String artifactUUID) { + // Scan the payload downloadResult and extract the HeatTemplate + // parameters + YamlEditor yamlEditor = new YamlEditor(yamlFile.getBytes()); + return yamlEditor.getParameterList(artifactUUID); + } + + protected String testNull(Object object) { + + if (object == null) { + return null; + } else if (object.equals("NULL")) { + return null; + } else if (object instanceof Integer) { + return object.toString(); + } else if (object instanceof String) { + return (String) object; + } else { + return "Type not recognized"; + } + } + + protected static String identifyParentOfNestedTemplate(VfModuleStructure vfModuleStructure, + VfModuleArtifact heatNestedArtifact) { + + if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT) != null && vfModuleStructure + .getArtifactsMap().get(ASDCConfiguration.HEAT).get(0).getArtifactInfo().getRelatedArtifacts() != null) { + for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0) + .getArtifactInfo().getRelatedArtifacts()) { + if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) { + return ASDCConfiguration.HEAT; + } + + } + } + + if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) != null + && vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo() + .getRelatedArtifacts() != null) { + for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) + .get(0).getArtifactInfo().getRelatedArtifacts()) { + if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) { + return ASDCConfiguration.HEAT_VOL; + } + + } + } + + // Does not belong to anything + return null; + + } + + protected static String createVNFName(VfResourceStructure vfResourceStructure) { + + return vfResourceStructure.getNotification().getServiceName() + "/" + + vfResourceStructure.getResourceInstance().getResourceInstanceName(); + } + + protected static String createVfModuleName(VfModuleStructure vfModuleStructure) { + + return createVNFName(vfModuleStructure.getParentVfResource()) + "::" + + vfModuleStructure.getVfModuleMetadata().getVfModuleModelName(); + } + + + protected static Timestamp getCurrentTimeStamp() { + + return new Timestamp(new Date().getTime()); + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImpl.java new file mode 100644 index 0000000000..dcfeb10845 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImpl.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.tenantIsolation; + +import java.net.MalformedURLException; +import java.net.URL; + +import org.onap.so.client.aai.AAIProperties; +import org.onap.so.client.aai.AAIVersion; +import org.springframework.context.ApplicationContext; + +public class AaiClientPropertiesImpl implements AAIProperties { + + private String aaiEndpoint; + private String auth; + private String key; + private static final String SYSTEM_NAME = "MSO"; + + public AaiClientPropertiesImpl() { + ApplicationContext context = SpringContextHelper.getAppContext(); + aaiEndpoint = context.getEnvironment().getProperty("mso.aai.endpoint"); + this.auth = context.getEnvironment().getProperty("aai.auth"); + this.key = context.getEnvironment().getProperty("mso.msoKey"); + } + + @Override + public URL getEndpoint() throws MalformedURLException { + ApplicationContext context = SpringContextHelper.getAppContext(); + aaiEndpoint = context.getEnvironment().getProperty("mso.aai.endpoint"); + return new URL(aaiEndpoint); + } + + @Override + public String getSystemName() { + return SYSTEM_NAME; + } + + @Override + public AAIVersion getDefaultVersion() { + return AAIVersion.LATEST; + } + + @Override + public String getAuth() { + return this.auth; + } + + @Override + public String getKey() { + return this.key; + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/DistributionStatus.java b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/DistributionStatus.java new file mode 100644 index 0000000000..d092712a8b --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/DistributionStatus.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.tenantIsolation; + +public enum DistributionStatus { + + SUCCESS, + FAILURE, + TIMEOUT, + INCOMPLETE +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/SpringContextHelper.java b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/SpringContextHelper.java new file mode 100644 index 0000000000..5f30edd8d9 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/SpringContextHelper.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.tenantIsolation; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +@Component +public class SpringContextHelper implements ApplicationContextAware { + + private static ApplicationContext context; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + context = applicationContext; + } + + public static ApplicationContext getAppContext() { + return context; + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java new file mode 100644 index 0000000000..3f0392a04f --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java @@ -0,0 +1,194 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.tenantIsolation; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.client.graphinventory.entities.uri.Depth; +import org.onap.so.db.catalog.data.repository.ServiceRepository; +import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus; +import org.onap.so.db.request.beans.WatchdogDistributionStatus; +import org.onap.so.db.request.beans.WatchdogServiceModVerIdLookup; +import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatusRepository; +import org.onap.so.db.request.data.repository.WatchdogDistributionStatusRepository; +import org.onap.so.db.request.data.repository.WatchdogServiceModVerIdLookupRepository; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class WatchdogDistribution { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC,WatchdogDistribution.class); + + private AAIResourcesClient aaiClient; + + @Autowired + private WatchdogDistributionStatusRepository watchdogDistributionStatusRepository; + + @Autowired + private WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository; + + @Autowired + private WatchdogServiceModVerIdLookupRepository watchdogModVerIdLookupRepository; + + @Autowired + private ServiceRepository serviceRepo; + + @Value("${mso.asdc.config.components.componentNames}") + private String[] componentNames; + + public String getOverallDistributionStatus(String distributionId) throws Exception { + LOGGER.debug("Entered getOverallDistributionStatus method for distrubutionId: " + distributionId); + + String status = null; + try { + WatchdogDistributionStatus watchdogDistributionStatus = watchdogDistributionStatusRepository.findOne(distributionId); + if(watchdogDistributionStatus == null){ + watchdogDistributionStatus = new WatchdogDistributionStatus(); + watchdogDistributionStatus.setDistributionId(distributionId); + watchdogDistributionStatusRepository.save(watchdogDistributionStatus); + } + String distributionStatus = watchdogDistributionStatus.getDistributionIdStatus(); + + if(DistributionStatus.TIMEOUT.name().equalsIgnoreCase(distributionStatus)) { + LOGGER.debug("Ignoring to update WatchdogDistributionStatus as distributionId: " + distributionId + " status is set to: " + distributionStatus); + return DistributionStatus.TIMEOUT.name(); + } else { + List results = watchdogCDStatusRepository.findByDistributionId(distributionId); + LOGGER.debug("Executed RequestDB getWatchdogComponentDistributionStatus for distrubutionId: " + distributionId); + + //************************************************************************************************************************************************* + //**** Compare config values verse DB watchdog component names to see if every component has reported status before returning final result back to ASDC + //************************************************************************************************************************************************** + + List cdStatuses = watchdogCDStatusRepository.findByDistributionId(distributionId); + + boolean allComponentsComplete = true; + + for(String name : componentNames ) { + + boolean match = false; + + for(WatchdogComponentDistributionStatus cdStatus: cdStatuses){ + if(name.equals(cdStatus.getComponentName())){ + LOGGER.debug("Found componentName " + name + " in the WatchDog Component DB"); + match = true; + break; + } + } + if(!match){ + LOGGER.debug(name + " has not be updated in the the WatchDog Component DB yet, so ending the loop"); + allComponentsComplete = false; + break; + } + } + + + if(allComponentsComplete) { + LOGGER.debug("Components Size matched with the WatchdogComponentDistributionStatus results."); + + for(WatchdogComponentDistributionStatus componentDist : results) { + String componentDistributionStatus = componentDist.getComponentDistributionStatus(); + LOGGER.debug("Component status: " + componentDistributionStatus + " on componentName: " + componentDist.getComponentName()); + if(componentDistributionStatus.equalsIgnoreCase("COMPONENT_DONE_ERROR")) { + status = DistributionStatus.FAILURE.name(); + break; + } else if(componentDistributionStatus.equalsIgnoreCase("COMPONENT_DONE_OK")) { + status = DistributionStatus.SUCCESS.name(); + } else { + throw new Exception("Invalid Component distribution status: " + componentDistributionStatus); + } + } + + LOGGER.debug("Updating overall DistributionStatus to: " + status + " for distributionId: " + distributionId); + + watchdogDistributionStatus.setDistributionIdStatus(status); + watchdogDistributionStatusRepository.save(watchdogDistributionStatus); + } else { + LOGGER.debug("Components Size Didn't match with the WatchdogComponentDistributionStatus results."); + status = DistributionStatus.INCOMPLETE.name(); + return status; + } + } + }catch (Exception e) { + LOGGER.debug("Exception occurred on getOverallDistributionStatus : " + e.getMessage()); + LOGGER.error(e); + throw new Exception(e); + } + LOGGER.debug("Exiting getOverallDistributionStatus method in WatchdogDistribution"); + return status; + } + + public void executePatchAAI(String distributionId, String serviceModelInvariantUUID, String distributionStatus) throws Exception { + LOGGER.debug("Entered executePatchAAI method with distrubutionId: " + distributionId + " and distributionStatus: " + distributionStatus); + + try { + WatchdogServiceModVerIdLookup lookup = watchdogModVerIdLookupRepository.findOneByDistributionId(distributionId); + String serviceModelVersionId = ""; + + if(lookup != null) { + serviceModelVersionId = lookup.getServiceModelVersionId(); + } + + LOGGER.debug("Executed RequestDB getWatchdogServiceModVerIdLookup with distributionId: " + distributionId + " and serviceModelVersionId: " + serviceModelVersionId); + LOGGER.debug("ASDC Notification ServiceModelInvariantUUID : " + serviceModelInvariantUUID); + + if(serviceModelInvariantUUID == null || "".equals(serviceModelVersionId)) { + String error = "No Service found with serviceModelInvariantUUID: " + serviceModelInvariantUUID; + LOGGER.debug(error); + throw new Exception(error); + } + + AAIResourceUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, serviceModelInvariantUUID, serviceModelVersionId); + aaiUri.depth(Depth.ZERO); //Do not return relationships if any + LOGGER.debug("Target A&AI Resource URI: " + aaiUri.build().toString()); + + Map payload = new HashMap<>(); + payload.put("distribution-status", distributionStatus); + getAaiClient().update(aaiUri, payload); + + LOGGER.debug("A&AI UPDATE MODEL Version is success!"); + } catch (Exception e) { + LOGGER.debug("Exception occurred on executePatchAAI : " + e.getMessage()); + LOGGER.error(e); + throw new Exception(e); + } + } + + public AAIResourcesClient getAaiClient() { + if(aaiClient == null) { + aaiClient = new AAIResourcesClient(); + } + return aaiClient; + } + + public void setAaiClient(AAIResourcesClient aaiClient) { + this.aaiClient = aaiClient; + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java b/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java new file mode 100644 index 0000000000..ef5b889d09 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java @@ -0,0 +1,779 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.util; + + +import java.util.List; +import java.util.Map; + +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.tosca.parser.impl.SdcPropertyNames; +import org.onap.sdc.tosca.parser.impl.SdcTypes; +import org.onap.sdc.toscaparser.api.Group; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.so.asdc.installer.IVfModuleData; +import org.onap.so.asdc.installer.ToscaResourceStructure; + +public class ASDCNotificationLogging { + + public static String dumpASDCNotification(INotificationData asdcNotification) { + + if (asdcNotification == null) { + return "NULL"; + } + return "ASDC Notification:" + System.lineSeparator() + + "DistributionID:" + testNull(asdcNotification.getDistributionID()) + System.lineSeparator() + + "ServiceName:" + testNull(asdcNotification.getServiceName()) + System.lineSeparator() + + "ServiceVersion:" + testNull(asdcNotification.getServiceVersion()) + System.lineSeparator() + + "ServiceUUID:" + testNull(asdcNotification.getServiceUUID()) + System.lineSeparator() + + "ServiceInvariantUUID:" + testNull(asdcNotification.getServiceInvariantUUID()) + System.lineSeparator() + + "ServiceDescription:" + testNull(asdcNotification.getServiceDescription()) + System.lineSeparator() + + "Service Artifacts List:" + System.lineSeparator() + testNull(dumpArtifactInfoList(asdcNotification.getServiceArtifacts())) + System.lineSeparator() + + "Resource Instances List:" + System.lineSeparator() + testNull(dumpASDCResourcesList(asdcNotification)) + System.lineSeparator(); + } + + public static String dumpCSARNotification(INotificationData asdcNotification, ToscaResourceStructure toscaResourceStructure) { + + if (asdcNotification == null) { + return "NULL"; + } + + + StringBuilder buffer = new StringBuilder("CSAR Notification:"); + buffer.append(System.lineSeparator()); + buffer.append(System.lineSeparator()); + + + ISdcCsarHelper csarHelper = toscaResourceStructure.getSdcCsarHelper(); + + + buffer.append("Service Level Properties:"); + buffer.append(System.lineSeparator()); + buffer.append("Name:"); + buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + buffer.append(System.lineSeparator()); + buffer.append("Description:"); + buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + buffer.append(System.lineSeparator()); + buffer.append("Model UUID:"); + buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); + buffer.append(System.lineSeparator()); + buffer.append("Model Version:"); + buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + buffer.append(System.lineSeparator()); + buffer.append("Model InvariantUuid:"); + buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); + buffer.append(System.lineSeparator()); + buffer.append("Service Type:"); + buffer.append(csarHelper.getServiceMetadata().getValue("serviceType")); + buffer.append(System.lineSeparator()); + buffer.append("Service Role:"); + buffer.append(csarHelper.getServiceMetadata().getValue("serviceRole")); + buffer.append(System.lineSeparator()); + buffer.append("WorkLoad Context:"); + buffer.append(asdcNotification.getWorkloadContext()); + buffer.append(System.lineSeparator()); + buffer.append("Environment Context:"); + buffer.append(csarHelper.getServiceMetadata().getValue("environmentContext")); + + + List serviceProxyResourceList = toscaResourceStructure.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.SERVICE_PROXY); + + if(serviceProxyResourceList != null){ + + for (NodeTemplate serviceProxyNodeTemplate : serviceProxyResourceList) { + + buffer.append(System.lineSeparator()); + buffer.append(System.lineSeparator()); + buffer.append("Service Proxy Properties:"); + buffer.append(System.lineSeparator()); + buffer.append("Model Name:"); + buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + buffer.append(System.lineSeparator()); + buffer.append("Model UUID:"); + buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + buffer.append(System.lineSeparator()); + buffer.append("Description:"); + buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + buffer.append(System.lineSeparator()); + buffer.append("Version:"); + buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + buffer.append(System.lineSeparator()); + buffer.append("InvariantUuid:"); + buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + buffer.append(System.lineSeparator()); + + buffer.append(System.lineSeparator()); + buffer.append(System.lineSeparator()); + buffer.append("Service Proxy Customization Properties:"); + buffer.append(System.lineSeparator()); + + buffer.append("Model Customization UUID:"); + buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + buffer.append(System.lineSeparator()); + buffer.append("Model Instance Name:"); + buffer.append(serviceProxyNodeTemplate.getName()); + buffer.append(System.lineSeparator()); + buffer.append("Tosca Node Type:"); + buffer.append(serviceProxyNodeTemplate.getType()); + buffer.append(System.lineSeparator()); + buffer.append("Version:"); + buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + buffer.append(System.lineSeparator()); + buffer.append("InvariantUuid:"); + buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + buffer.append(System.lineSeparator()); + + } + } + + List configurationNodeTemplatesList = toscaResourceStructure.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION); + + if(configurationNodeTemplatesList != null){ + for (NodeTemplate configNodeTemplate : configurationNodeTemplatesList) { + + buffer.append(System.lineSeparator()); + buffer.append(System.lineSeparator()); + buffer.append("Configuration Properties:"); + buffer.append(System.lineSeparator()); + + buffer.append("Model Name:"); + buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + buffer.append(System.lineSeparator()); + buffer.append("Model UUID:"); + buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + buffer.append(System.lineSeparator()); + buffer.append("Description:"); + buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + buffer.append(System.lineSeparator()); + buffer.append("Version:"); + buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + buffer.append(System.lineSeparator()); + buffer.append("InvariantUuid:"); + buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + buffer.append(System.lineSeparator()); + buffer.append("Tosca Node Type:"); + buffer.append(configNodeTemplate.getType()); + + buffer.append(System.lineSeparator()); + buffer.append(System.lineSeparator()); + buffer.append("Configuration Customization Properties:"); + buffer.append(System.lineSeparator()); + + buffer.append("Model Customization UUID:"); + buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + buffer.append(System.lineSeparator()); + buffer.append("Model Instance Name:"); + buffer.append(configNodeTemplate.getName()); + buffer.append(System.lineSeparator()); + buffer.append("NFFunction:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)); + buffer.append(System.lineSeparator()); + buffer.append("NFRole:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)); + buffer.append(System.lineSeparator()); + buffer.append("NFType:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)); + buffer.append(System.lineSeparator()); + + } + } + + buffer.append(System.lineSeparator()); + buffer.append(System.lineSeparator()); + buffer.append("VNF Level Properties:"); + buffer.append(System.lineSeparator()); + + List vfNodeTemplatesList = toscaResourceStructure.getSdcCsarHelper().getServiceVfList(); + for (NodeTemplate vfNodeTemplate : vfNodeTemplatesList) { + + buffer.append("Model Name:"); + buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + buffer.append(System.lineSeparator()); + buffer.append("Description:"); + buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + buffer.append(System.lineSeparator()); + buffer.append("Version:"); + buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + buffer.append(System.lineSeparator()); + buffer.append("Type:"); + buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE))); + buffer.append(System.lineSeparator()); + buffer.append("InvariantUuid:"); + buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); + buffer.append(System.lineSeparator()); + buffer.append("Max Instances:"); + buffer.append(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)); + buffer.append(System.lineSeparator()); + buffer.append("Min Instances:"); + buffer.append(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES)); + buffer.append(System.lineSeparator()); + + buffer.append(System.lineSeparator()); + buffer.append("VNF Customization Properties:"); + buffer.append(System.lineSeparator()); + + buffer.append("Customization UUID:"); + buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); + buffer.append(System.lineSeparator()); + buffer.append("NFFunction:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)); + buffer.append(System.lineSeparator()); + buffer.append("NFCode:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, "nf_naming_code")); + buffer.append(System.lineSeparator()); + buffer.append("NFRole:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)); + buffer.append(System.lineSeparator()); + buffer.append("NFType:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)); + buffer.append(System.lineSeparator()); + buffer.append("MultiStageDesign:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, "multi_stage_design")); + buffer.append(System.lineSeparator()); + + List groupList = toscaResourceStructure.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType(vfNodeTemplate, "org.openecomp.groups.VfcInstanceGroup"); + + if(groupList != null){ + for (Group group : groupList) { + Metadata instanceMetadata = group.getMetadata(); + + buffer.append(System.lineSeparator()); + buffer.append("VNFC Instance Group Properties:"); + buffer.append(System.lineSeparator()); + + buffer.append("Model Name:"); + buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + buffer.append(System.lineSeparator()); + buffer.append("Version:"); + buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + buffer.append(System.lineSeparator()); + buffer.append("Type:"); + buffer.append(vfNodeTemplate.getType()); + buffer.append(System.lineSeparator()); + buffer.append("InvariantUuid:"); + buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + buffer.append(System.lineSeparator()); + } + + } + + + + buffer.append(System.lineSeparator()); + buffer.append("VF Module Properties:"); + buffer.append(System.lineSeparator()); + List vfGroups = toscaResourceStructure.getSdcCsarHelper().getVfModulesByVf(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); + + for(Group group : vfGroups){ + + Metadata vfMetadata = group.getMetadata(); + + buffer.append("ModelInvariantUuid:"); + buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID))); + buffer.append(System.lineSeparator()); + buffer.append("ModelName:"); + buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME))); + buffer.append(System.lineSeparator()); + buffer.append("ModelUuid:"); + buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID))); + buffer.append(System.lineSeparator()); + buffer.append("ModelVersion:"); + buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION))); + buffer.append(System.lineSeparator()); + buffer.append("Description:"); + buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + buffer.append(System.lineSeparator()); + } + + } + + + List nodeTemplatesVLList = toscaResourceStructure.getSdcCsarHelper().getServiceVlList(); + + if(nodeTemplatesVLList != null){ + + buffer.append(System.lineSeparator()); + buffer.append("NETWORK Level Properties:"); + buffer.append(System.lineSeparator()); + + for(NodeTemplate vlNode : nodeTemplatesVLList){ + + buffer.append("Model Name:"); + buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + buffer.append(System.lineSeparator()); + buffer.append("Model InvariantUuid:"); + buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); + buffer.append(System.lineSeparator()); + buffer.append("Model UUID:"); + buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); + buffer.append(System.lineSeparator()); + buffer.append("Model Version:"); + buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + buffer.append(System.lineSeparator()); + buffer.append("AIC Max Version:"); + buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); + buffer.append(System.lineSeparator()); + buffer.append("AIC Min Version:"); + buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); + buffer.append(System.lineSeparator()); + buffer.append("Tosca Node Type:"); + buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE))); + buffer.append(System.lineSeparator()); + buffer.append("Description:"); + buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + buffer.append(System.lineSeparator()); + + } + + } + + buffer.append(System.lineSeparator()); + buffer.append("Network Collection Resource Properties:"); + buffer.append(System.lineSeparator()); + + List networkCollectionList = toscaResourceStructure.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CR); + + if (networkCollectionList != null) { + for (NodeTemplate crNode : networkCollectionList) { + buffer.append("Model Name:"); + buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + buffer.append(System.lineSeparator()); + buffer.append("Model UUID:"); + buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + buffer.append(System.lineSeparator()); + buffer.append("InvariantUuid:"); + buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + buffer.append(System.lineSeparator()); + buffer.append("Description:"); + buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + buffer.append(System.lineSeparator()); + buffer.append("Version:"); + buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + buffer.append(System.lineSeparator()); + buffer.append("Tosca Node Type:"); + buffer.append(crNode.getType()); + buffer.append(System.lineSeparator()); + buffer.append("CR Function:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, "cr_function")); + buffer.append(System.lineSeparator()); + buffer.append("CR Role:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, "cr_role")); + buffer.append(System.lineSeparator()); + buffer.append("CR Type:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, "cr_type")); + buffer.append(System.lineSeparator()); + + List vlNodeList = toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(crNode, SdcTypes.VL); + + for(NodeTemplate vlNodeTemplate : vlNodeList){ + + Metadata vlMetadata = vlNodeTemplate.getMetaData(); + + buffer.append(System.lineSeparator()); + buffer.append("Network CR VL Properties:"); + buffer.append(System.lineSeparator()); + + buffer.append("Model Name:"); + buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + buffer.append(System.lineSeparator()); + buffer.append("Model UUID:"); + buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + buffer.append(System.lineSeparator()); + buffer.append("InvariantUuid:"); + buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + buffer.append(System.lineSeparator()); + buffer.append("Version:"); + buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + buffer.append(System.lineSeparator()); + buffer.append("AIC Max Version:"); + buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)); + buffer.append(System.lineSeparator()); + buffer.append("Description:"); + buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + buffer.append(System.lineSeparator()); + buffer.append("Tosca Node Type:"); + buffer.append(vlNodeTemplate.getType()); + buffer.append(System.lineSeparator()); + + } + + List groupList = toscaResourceStructure.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType(crNode, "org.openecomp.groups.NetworkCollection"); + + if(groupList != null){ + for (Group group : groupList) { + Metadata instanceMetadata = group.getMetadata(); + buffer.append(System.lineSeparator()); + buffer.append("Network Instance Group Properties:"); + buffer.append(System.lineSeparator()); + + buffer.append("Model Name:"); + buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + buffer.append(System.lineSeparator()); + buffer.append("Model UUID:"); + buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + buffer.append(System.lineSeparator()); + buffer.append("InvariantUuid:"); + buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + buffer.append(System.lineSeparator()); + buffer.append("Version:"); + buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + buffer.append(System.lineSeparator()); + } + + } + + buffer.append(System.lineSeparator()); + buffer.append("Network Collection Customization Properties:"); + buffer.append(System.lineSeparator()); + + buffer.append("Model Customization UUID:"); + buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + buffer.append(System.lineSeparator()); + buffer.append("Model Instance Name:"); + buffer.append(crNode.getName()); + buffer.append(System.lineSeparator()); + buffer.append("Network Scope:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE)); + buffer.append(System.lineSeparator()); + buffer.append("Network Role:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE)); + buffer.append(System.lineSeparator()); + buffer.append("Network Type:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE)); + buffer.append(System.lineSeparator()); + buffer.append("Network Technology:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY)); + buffer.append(System.lineSeparator()); + + } + } + + List allottedResourceList = toscaResourceStructure.getSdcCsarHelper().getAllottedResources(); + + if(allottedResourceList != null){ + + buffer.append(System.lineSeparator()); + buffer.append("Allotted Resource Properties:"); + buffer.append(System.lineSeparator()); + + for(NodeTemplate allottedNode : allottedResourceList){ + + buffer.append("Model Name:"); + buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + buffer.append(System.lineSeparator()); + buffer.append("Model Name:"); + buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + buffer.append(System.lineSeparator()); + buffer.append("Model InvariantUuid:"); + buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); + buffer.append(System.lineSeparator()); + buffer.append("Model Version:"); + buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + buffer.append(System.lineSeparator()); + buffer.append("Model UUID:"); + buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); + buffer.append(System.lineSeparator()); + buffer.append("Model Subcategory:"); + buffer.append(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)); + buffer.append(System.lineSeparator()); + buffer.append("Model Description:"); + buffer.append(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + buffer.append(System.lineSeparator()); + + + buffer.append("Allotted Resource Customization Properties:"); + buffer.append(System.lineSeparator()); + + buffer.append("Model Cutomization UUID:"); + buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); + buffer.append(System.lineSeparator()); + buffer.append("NFFunction:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)); + buffer.append(System.lineSeparator()); + buffer.append("NFCode:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode, "nf_naming_code")); + buffer.append(System.lineSeparator()); + buffer.append("NFRole:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode, SdcPropertyNames.PROPERTY_NAME_NFROLE)); + buffer.append(System.lineSeparator()); + buffer.append("NFType:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode, SdcPropertyNames.PROPERTY_NAME_NFTYPE)); + buffer.append(System.lineSeparator()); + + + } + } + + + return buffer.toString(); + } + + public static String dumpVfModuleMetaDataList(List moduleMetaDataList) { + if (moduleMetaDataList == null ) { + return null; + } + + StringBuilder buffer = new StringBuilder("VfModuleMetaData List:"); + buffer.append(System.lineSeparator()); + + buffer.append("{"); + + for (IVfModuleData moduleMetaData:moduleMetaDataList) { + buffer.append(System.lineSeparator()); + buffer.append(testNull(dumpVfModuleMetaData(moduleMetaData))); + buffer.append(System.lineSeparator()); + buffer.append(","); + + } + buffer.replace(buffer.length()-1,buffer.length(), System.lineSeparator()); + buffer.append("}"); + buffer.append(System.lineSeparator()); + + return buffer.toString(); + } + + private static String dumpVfModuleMetaData(IVfModuleData moduleMetaData) { + + if (moduleMetaData == null ) { + return "NULL"; + } + + StringBuilder stringBuilder = new StringBuilder("VfModuleMetaData:"); + stringBuilder.append(System.lineSeparator()); + + stringBuilder.append("VfModuleModelName:"); + stringBuilder.append(testNull(moduleMetaData.getVfModuleModelName())); + stringBuilder.append(System.lineSeparator()); + + stringBuilder.append("VfModuleModelVersion:"); + stringBuilder.append(testNull(moduleMetaData.getVfModuleModelVersion())); + stringBuilder.append(System.lineSeparator()); + + stringBuilder.append("VfModuleModelUUID:"); + stringBuilder.append(testNull(moduleMetaData.getVfModuleModelUUID())); + stringBuilder.append(System.lineSeparator()); + + stringBuilder.append("VfModuleModelInvariantUUID:"); + stringBuilder.append(testNull(moduleMetaData.getVfModuleModelInvariantUUID())); + stringBuilder.append(System.lineSeparator()); + + stringBuilder.append("VfModuleModelDescription:"); + stringBuilder.append(testNull(moduleMetaData.getVfModuleModelDescription())); + stringBuilder.append(System.lineSeparator()); + + stringBuilder.append("Artifacts UUID List:"); + + if (moduleMetaData.getArtifacts() != null) { + stringBuilder.append("{"); + + for (String artifactUUID:moduleMetaData.getArtifacts()) { + stringBuilder.append(System.lineSeparator()); + stringBuilder.append(testNull(artifactUUID)); + stringBuilder.append(System.lineSeparator()); + stringBuilder.append(","); + } + stringBuilder.replace(stringBuilder.length()-1,stringBuilder.length(), System.lineSeparator()); + stringBuilder.append("}"); + stringBuilder.append(System.lineSeparator()); + } else { + stringBuilder.append("NULL"); + } + + if (moduleMetaData.getProperties() != null) { + Map vfModuleMap = moduleMetaData.getProperties(); + stringBuilder.append("Properties List:"); + stringBuilder.append("{"); + + for (Map.Entry entry : vfModuleMap.entrySet()) { + stringBuilder.append(System.lineSeparator()); + stringBuilder.append(" ").append(entry.getKey()).append(" : ").append(entry.getValue()); + } + stringBuilder.replace(stringBuilder.length()-1,stringBuilder.length(), System.lineSeparator()); + stringBuilder.append("}"); + stringBuilder.append(System.lineSeparator()); + } else { + stringBuilder.append("NULL"); + } + + + stringBuilder.append(System.lineSeparator()); + + stringBuilder.append("isBase:"); + stringBuilder.append(moduleMetaData.isBase()); + stringBuilder.append(System.lineSeparator()); + + return stringBuilder.toString(); + } + + private static String testNull(Object object) { + if (object == null) { + return "NULL"; + } else if (object instanceof Integer) { + return object.toString(); + } else if (object instanceof String) { + return (String)object; + } else { + return "Type not recognized"; + } + } + + private static String dumpASDCResourcesList(INotificationData asdcNotification) { + if (asdcNotification == null || asdcNotification.getResources() == null) { + return null; + } + + StringBuilder buffer = new StringBuilder(); + buffer.append("{"); + + for (IResourceInstance resourceInstanceElem:asdcNotification.getResources()) { + buffer.append(System.lineSeparator()); + buffer.append(testNull(dumpASDCResourceInstance(resourceInstanceElem))); + buffer.append(System.lineSeparator()); + buffer.append(","); + } + buffer.replace(buffer.length()-1,buffer.length(), System.lineSeparator()); + buffer.append("}"); + buffer.append(System.lineSeparator()); + + return buffer.toString(); + + } + + private static String dumpASDCResourceInstance(IResourceInstance resourceInstance) { + + if (resourceInstance == null) { + return null; + } + + return "Resource Instance Info:" + System.lineSeparator() + + "ResourceInstanceName:" + testNull(resourceInstance.getResourceInstanceName()) + System.lineSeparator() + + "ResourceCustomizationUUID:" + testNull(resourceInstance.getResourceCustomizationUUID()) + System.lineSeparator() + + "ResourceInvariantUUID:" + testNull(resourceInstance.getResourceInvariantUUID()) + System.lineSeparator() + + "ResourceName:" + testNull(resourceInstance.getResourceName()) + System.lineSeparator() + + "ResourceType:" + testNull(resourceInstance.getResourceType()) + System.lineSeparator() + + "ResourceUUID:" + testNull(resourceInstance.getResourceUUID()) + System.lineSeparator() + + "ResourceVersion:" + testNull(resourceInstance.getResourceVersion()) + System.lineSeparator() + + "Category:" + testNull(resourceInstance.getCategory()) + System.lineSeparator() + + "SubCategory:" + testNull(resourceInstance.getSubcategory()) + System.lineSeparator() + + "Resource Artifacts List:" + System.lineSeparator() + testNull(dumpArtifactInfoList(resourceInstance.getArtifacts())) + System.lineSeparator(); + } + + + private static String dumpArtifactInfoList(List artifactsList) { + + if (artifactsList == null || artifactsList.isEmpty()) { + return null; + } + + StringBuilder buffer = new StringBuilder(); + buffer.append("{"); + for (IArtifactInfo artifactInfoElem:artifactsList) { + buffer.append(System.lineSeparator()); + buffer.append(testNull(dumpASDCArtifactInfo(artifactInfoElem))); + buffer.append(System.lineSeparator()); + buffer.append(","); + + } + buffer.replace(buffer.length()-1,buffer.length(), System.lineSeparator()); + buffer.append("}"); + buffer.append(System.lineSeparator()); + + return buffer.toString(); + } + + private static String dumpASDCArtifactInfo(IArtifactInfo artifactInfo) { + + if (artifactInfo == null) { + return null; + } + + StringBuilder buffer = new StringBuilder("Service Artifacts Info:"); + buffer.append(System.lineSeparator()); + + buffer.append("ArtifactName:"); + buffer.append(testNull(artifactInfo.getArtifactName())); + buffer.append(System.lineSeparator()); + + buffer.append("ArtifactVersion:"); + buffer.append(testNull(artifactInfo.getArtifactVersion())); + buffer.append(System.lineSeparator()); + + buffer.append("ArtifactType:"); + buffer.append(testNull(artifactInfo.getArtifactType())); + buffer.append(System.lineSeparator()); + + buffer.append("ArtifactDescription:"); + buffer.append(testNull(artifactInfo.getArtifactDescription())); + buffer.append(System.lineSeparator()); + + buffer.append("ArtifactTimeout:"); + buffer.append(testNull(artifactInfo.getArtifactTimeout())); + buffer.append(System.lineSeparator()); + + buffer.append("ArtifactURL:"); + buffer.append(testNull(artifactInfo.getArtifactURL())); + buffer.append(System.lineSeparator()); + + buffer.append("ArtifactUUID:"); + buffer.append(testNull(artifactInfo.getArtifactUUID())); + buffer.append(System.lineSeparator()); + + buffer.append("ArtifactChecksum:"); + buffer.append(testNull(artifactInfo.getArtifactChecksum())); + buffer.append(System.lineSeparator()); + + buffer.append("GeneratedArtifact:"); + buffer.append("{"); + buffer.append(testNull(dumpASDCArtifactInfo(artifactInfo.getGeneratedArtifact()))); + buffer.append(System.lineSeparator()); + buffer.append("}"); + buffer.append(System.lineSeparator()); + + buffer.append("RelatedArtifacts:"); + + + if (artifactInfo.getRelatedArtifacts() != null) { + buffer.append("{"); + buffer.append(System.lineSeparator()); + for (IArtifactInfo artifactInfoElem:artifactInfo.getRelatedArtifacts()) { + + buffer.append(testNull(dumpASDCArtifactInfo(artifactInfoElem))); + buffer.append(System.lineSeparator()); + buffer.append(","); + + } + buffer.replace(buffer.length()-1,buffer.length(), System.lineSeparator()); + buffer.append("}"); + buffer.append(System.lineSeparator()); + } else { + buffer.append("NULL"); + } + + buffer.append(System.lineSeparator()); + + return buffer.toString(); + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/util/NotificationLogging.java b/asdc-controller/src/main/java/org/onap/so/asdc/util/NotificationLogging.java new file mode 100644 index 0000000000..965f8b7d49 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/util/NotificationLogging.java @@ -0,0 +1,169 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + +package org.onap.so.asdc.util; + + + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.onap.so.logger.MsoLogger; +import org.onap.sdc.api.notification.INotificationData; + + +public class NotificationLogging implements InvocationHandler { + + private static Map> objectMethodsToLog = new HashMap<>(); + + protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC, NotificationLogging.class); + + private static InvocationHandler handler = (arg0, arg1, arg2) -> { + List methods = objectMethodsToLog.get(arg0); + if ((methods == null) || (methods.isEmpty())) { + // Do nothing for now... + return null; + } + methods.add(arg1); + return arg1.invoke(arg0, arg2); + }; + + public static InvocationHandler getHandler() { + return handler; + } + + /** + * + */ + private NotificationLogging() {} + + private static final String[] GETTER_PREFIXES = { "get", "is" }; + + public static String logNotification(INotificationData iNotif) { + if (iNotif == null) { + return "NULL"; + } + + Class clazz = iNotif.getClass(); + + Method[] declaredMethods = clazz.getDeclaredMethods(); + + if (declaredMethods == null || declaredMethods.length == 0) { + return "EMPTY"; // No declared methods in this class !!! + } + + StringBuilder buffer = new StringBuilder("ASDC Notification:"); + buffer.append(System.lineSeparator()); + + for (Method m : declaredMethods) { + if ((m != null) && isGetter(m)) { + for (String prefix : GETTER_PREFIXES) { + if (m.getName().startsWith(prefix)) { + buffer.append(m.getName().substring(prefix.length())); + break; + } + } + try { + buffer.append(testNull(m.invoke(iNotif, (Object[])null))); + } catch (IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + LOGGER.debug("Exception :"+e); + buffer.append("UNREADABLE"); + } + buffer.append(System.lineSeparator()); + } + } + + return buffer.toString(); + } + + private static boolean isGetter(Method method) { + + // Must start with a valid (and known) prefix + boolean prefixFound = false; + for (String prefix : GETTER_PREFIXES) { + if (method.getName().startsWith(prefix)) { + prefixFound = true; + break; + } + } + if (!prefixFound) { + return false; + } + + // Must not take any input arguments + if (method.getParameterTypes().length != 0) { + return false; + } + + // Must not have return type 'void' + if (void.class.equals(method.getReturnType())) { + return false; + } + + // Must be public + if (!Modifier.isPublic(method.getModifiers())) { + return false; + } + + return true; + } + + private static String testNull(Object object) { + if (object == null) { + return "NULL"; + } else if (object instanceof Integer) { + return object.toString(); + } else if (object instanceof String) { + return (String) object; + } else { + return "Type not recognized"; + } + } + + private static void registerForLog(INotificationData objectToLog) { + INotificationData proxy = (INotificationData) Proxy.newProxyInstance( + INotificationData.class.getClassLoader(), + new Class[] { INotificationData.class }, + NotificationLogging.getHandler()); + objectMethodsToLog.put(proxy, new ArrayList<>()); + } + + private static void methodToLog(T methodCall) { + // + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/util/ToLog.java b/asdc-controller/src/main/java/org/onap/so/asdc/util/ToLog.java new file mode 100644 index 0000000000..1f67b9cd91 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/util/ToLog.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + +package org.onap.so.asdc.util; + + + + +public @interface ToLog { + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/util/YamlEditor.java b/asdc-controller/src/main/java/org/onap/so/asdc/util/YamlEditor.java new file mode 100644 index 0000000000..fdeddf1f68 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/util/YamlEditor.java @@ -0,0 +1,176 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc.util; + + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.yaml.snakeyaml.Yaml; + +import org.onap.so.db.catalog.beans.HeatTemplateParam; + +public class YamlEditor { + + private static final String REFER_PATTERN = "file:///"; + private Map yml; + private Yaml yaml = new Yaml (); + + public YamlEditor () { + + } + + public YamlEditor (byte[] body) { + init (body); + } + + @SuppressWarnings("unchecked") + private synchronized void init (byte[] body) { + InputStream input = new ByteArrayInputStream (body); + yml = (Map ) yaml.load (input); + } + + public synchronized List getYamlNestedFileResourceTypeList () { + List typeList = new ArrayList<>(); + + @SuppressWarnings("unchecked") + Map resourceMap = (Map ) yml.get ("resources"); + Iterator > it = resourceMap.entrySet ().iterator (); + while (it.hasNext ()) { + Map.Entry pair = it.next (); + @SuppressWarnings("unchecked") + Map resourceEntry = (Map ) pair.getValue (); + String type = resourceEntry.get ("type"); + + if (type.contains (REFER_PATTERN)) { + typeList.add (type); + } + it.remove (); // avoids a ConcurrentModificationException + } + return typeList; + } + + public synchronized List getYamlResourceTypeList () { + List typeList = new ArrayList<>(); + + @SuppressWarnings("unchecked") + Map resourceMap = (Map ) yml.get ("resources"); + for (Entry pair : resourceMap.entrySet()) { + @SuppressWarnings("unchecked") + Map resourceEntry = (Map) pair.getValue(); + typeList.add(resourceEntry.get("type")); + } + return typeList; + } + + // Generate the parameter list based on the Heat Template + // Based on the email from Ella Kvetny: + // Within Heat Template, under parameters catalog, it might indicate the default value of the parameter + // If default value exist, the parameter is not mandatory, otherwise its value should be set + public synchronized Set getParameterList (String artifactUUID) { + Set paramSet = new HashSet<>(); + @SuppressWarnings("unchecked") + Map resourceMap = (Map ) yml.get ("parameters"); + + for (Entry stringObjectEntry : resourceMap.entrySet()) { + HeatTemplateParam param = new HeatTemplateParam(); + Entry pair = stringObjectEntry; + @SuppressWarnings("unchecked") + Map resourceEntry = (Map) pair.getValue(); + + param.setParamName(pair.getKey()); + // System.out.println(pair.getKey()+":"+type); + if (resourceEntry.containsKey("default")) { + param.setRequired(false); + } else { + param.setRequired(true); + } + // Now set the type + String value = resourceEntry.get("type"); + param.setParamType(value); + + param.setHeatTemplateArtifactUuid(artifactUUID); + + paramSet.add(param); + + } + return paramSet; + + } + + public synchronized void addParameterList (Set heatSet) { + + @SuppressWarnings("unchecked") + Map resourceMap = (Map ) yml.get ("parameters"); + if (resourceMap == null) { + resourceMap = new LinkedHashMap<>(); + this.yml.put ("parameters", resourceMap); + } + for (HeatTemplateParam heatParam : heatSet) { + Map paramInfo = new HashMap<>(); + paramInfo.put ("type", heatParam.getParamType ()); + + resourceMap.put (heatParam.getParamName (), paramInfo); + } + + // this.yml.put("parameters", resourceMap); + + } + + public boolean isParentTemplate (String templateBody) { + return templateBody.contains (REFER_PATTERN); + } + + public boolean verifyTemplate () { + // Verify whether the heat template is for Vnf Resource + // We don't support other template installation yet + + return true; + } + + public String encode (Map content) { + return yaml.dump (content); + } + + public synchronized String encode () { + return this.yaml.dump (this.yml); + } + + /** + * This method return the YAml file as a string. + * + */ + @Override + public String toString () { + + return encode (); + } + +} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/ASDCControllerSingleton.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/ASDCControllerSingleton.java deleted file mode 100644 index d5a8d0f15a..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/ASDCControllerSingleton.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc; - - -import javax.annotation.PreDestroy; -import javax.ejb.ConcurrencyManagement; -import javax.ejb.ConcurrencyManagementType; -import javax.ejb.Lock; -import javax.ejb.LockType; -import javax.ejb.Schedule; -import javax.ejb.Singleton; -import javax.ejb.Startup; - -import org.openecomp.mso.asdc.client.ASDCGlobalController; -import org.openecomp.mso.logger.MsoLogger; - -@Singleton(name = "ASDCController") -@Lock(LockType.READ) -@Startup -@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER) -public class ASDCControllerSingleton { - - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC); - private static boolean working = false; - - private ASDCGlobalController globalController = new ASDCGlobalController (); - - /** - * Main Constructor of the ASDC Singleton - */ - public ASDCControllerSingleton () { - } - - @Schedule(second ="30", minute = "*", hour = "*", persistent = false) - public void periodicControllerTask () { - if (isWorking ()) { - LOGGER.debug ("Another thread is already trying to init ASDC, cancel this periodic call"); - return; - } - try { - setWorking (true); - - globalController.updateControllersConfigIfNeeded(); - globalController.checkInStoppedState(); - - } finally { - setWorking (false); - } - } - - @PreDestroy - private void terminate () { - globalController.closeASDC (); - } - - private static synchronized boolean isWorking () { - return ASDCControllerSingleton.working; - } - - private static synchronized void setWorking (boolean working) { - ASDCControllerSingleton.working = working; - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCConfiguration.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCConfiguration.java deleted file mode 100644 index 7cc6ab8a89..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCConfiguration.java +++ /dev/null @@ -1,508 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client; - - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Properties; - -import org.openecomp.mso.asdc.client.exceptions.ASDCParametersException; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.properties.MsoJsonProperties; -import org.openecomp.mso.properties.MsoPropertiesException; -import org.openecomp.mso.properties.MsoPropertiesFactory; -import org.onap.sdc.api.consumer.IConfiguration; - -import com.fasterxml.jackson.databind.JsonNode; - -public class ASDCConfiguration implements IConfiguration { - - private MsoPropertiesFactory msoPropertiesFactory; - - // SHell command to obtain the same encryption, 128 bits key, key must be HEX - // echo -n "This is a test string" | openssl aes-128-ecb -e -K 546573746F736973546573746F736973 -nosalt | xxd - - private String configKey; - - private MsoJsonProperties msoProperties; - - private String asdcControllerName; - private String PASSWORD_ATTRIBUTE_NAME; - private String KEY_STORE_PASSWORD; - - public static final String MSO_PROP_ASDC = "MSO_PROP_ASDC"; - public static final String PARAMETER_PATTERN = "asdc-connections"; - public static final String MSG_BUS_ADDRESS_ATTRIBUTE_NAME = "messageBusAddress"; - public static final String COMPONENT_NAMES_ADDRESS_ATTRIBUTE_NAME = "componentNames"; - public static final String WATCHDOG_TIMEOUT_NAME = "watchDogTimeout"; - - public static final String CONSUMER_GROUP_ATTRIBUTE_NAME = "consumerGroup"; - public static final String CONSUMER_ID_ATTRIBUTE_NAME = "consumerId"; - public static final String ENVIRONMENT_NAME_ATTRIBUTE_NAME = "environmentName"; - public static final String POLLING_INTERVAL_ATTRIBUTE_NAME = "pollingInterval"; - public static final String RELEVANT_ARTIFACT_TYPES_ATTRIBUTE_NAME = "relevantArtifactTypes"; - public static final String USER_ATTRIBUTE_NAME = "user"; - public static final String ASDC_ADDRESS_ATTRIBUTE_NAME = "asdcAddress"; - public static final String POLLING_TIMEOUT_ATTRIBUTE_NAME = "pollingTimeout"; - public static final String ACTIVATE_SERVER_TLS_AUTH = "activateServerTLSAuth"; - public static final String KEY_STORE_PATH = "keyStorePath"; - - public static final String HEAT="HEAT"; - public static final String HEAT_ARTIFACT="HEAT_ARTIFACT"; - public static final String HEAT_ENV="HEAT_ENV"; - public static final String HEAT_NESTED="HEAT_NESTED"; - public static final String HEAT_NET="HEAT_NET"; - public static final String HEAT_VOL="HEAT_VOL"; - public static final String OTHER="OTHER"; - public static final String TOSCA_CSAR="TOSCA_CSAR"; - public static final String VF_MODULES_METADATA="VF_MODULES_METADATA"; - - private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.GENERAL); - - private static final String[] SUPPORTED_ARTIFACT_TYPES = {HEAT, - HEAT_ARTIFACT, - HEAT_ENV, - HEAT_NESTED, - HEAT_NET, - HEAT_VOL, - OTHER, - TOSCA_CSAR, - VF_MODULES_METADATA}; - - public static final List SUPPORTED_ARTIFACT_TYPES_LIST = Collections.unmodifiableList(Arrays.asList(SUPPORTED_ARTIFACT_TYPES)); - - /** - * Default constructor, the mso.properties is searched in the classpath (for testing) - * Or in /etc/ecomp/mso/config/mso.properties - * - * @param controllerName The controllerName of the config JSON tree - * @throws ASDCParametersException in case of issues with the parameters - * @throws IOException If the key file has not been loaded properly - */ - public ASDCConfiguration (String controllerName) throws ASDCParametersException, IOException { - - Properties keyProp = new Properties (); - this.asdcControllerName = controllerName; - - keyProp.load (Thread.currentThread ().getContextClassLoader ().getResourceAsStream ("config-key.properties")); - configKey = (String) keyProp.get ("asdc.config.key"); - - // This structure contains static values initialized by servlet initializer - this.msoPropertiesFactory = new MsoPropertiesFactory (); - - refreshASDCConfig (); - - } - - @Override - public java.lang.Boolean isUseHttpsWithDmaap() { - return false; - } - - @Override - public boolean isConsumeProduceStatusTopic(){ - return true; - } - - @Override - public List getMsgBusAddress(){ - - JsonNode masterConfigNode = getASDCControllerConfigJsonNode (); - if (masterConfigNode != null && masterConfigNode.get (MSG_BUS_ADDRESS_ATTRIBUTE_NAME) != null) { - List msgAddressList = new ArrayList<>(); - - Iterator config = masterConfigNode.get(MSG_BUS_ADDRESS_ATTRIBUTE_NAME).elements(); - - while( config.hasNext() ) { - String key = (String)config.next().asText(); - msgAddressList.add(key); - } - - if ("NULL".equals (msgAddressList) || msgAddressList.isEmpty ()) { - return null; - } else { - return msgAddressList; - } - } else { - return null; - } - - - } - - public String getAsdcControllerName () { - return asdcControllerName; - } - - private JsonNode getASDCControllerConfigJsonNode () { - if (this.msoProperties.getJsonRootNode ().get (PARAMETER_PATTERN) != null) { - return this.msoProperties.getJsonRootNode ().get (PARAMETER_PATTERN).get (this.asdcControllerName); - } else { - return null; - } - - } - - /** - * This method reload the config if needed. - * - * @return true if config has been reloaded, false otherwise - * @throws ASDCParametersException In case the parameters validation fails - * @throws MsoPropertiesException - */ - public boolean refreshASDCConfig () throws ASDCParametersException { - - try { - if (msoPropertiesFactory.propertiesHaveChanged (MSO_PROP_ASDC, msoProperties)) { - msoProperties = msoPropertiesFactory.getMsoJsonProperties (MSO_PROP_ASDC); - - this.testAllParameters (); - return true; - } else { - return false; - } - } catch (MsoPropertiesException e) { - throw new ASDCParametersException ("mso.asdc.json not initialized properly, ASDC config cannot be reloaded", - e); - } - } - - /** - * This method is useful to check whether a mso properties config has been changed. - * - * @return true is a new config is availabe, false otherwise - * @throws ASDCParametersException - * @throws MsoPropertiesException - */ - public boolean hasASDCConfigChanged () throws ASDCParametersException { - try { - return msoPropertiesFactory.propertiesHaveChanged (MSO_PROP_ASDC, msoProperties); - } catch (MsoPropertiesException e) { - throw new ASDCParametersException ("mso.asdc.json not initialized properly, ASDC config cannot be read", e); - } - } - - @Override - public String getConsumerGroup () { - JsonNode masterConfigNode = getASDCControllerConfigJsonNode (); - if (masterConfigNode != null && masterConfigNode.get (CONSUMER_GROUP_ATTRIBUTE_NAME) != null) { - String config = masterConfigNode.get (CONSUMER_GROUP_ATTRIBUTE_NAME).asText (); - - if ("NULL".equals (config) || config.isEmpty ()) { - return null; - } else { - return config; - } - } else { - return null; - } - } - - public int getWatchDogTimeout () { - JsonNode masterConfigNode = getASDCControllerConfigJsonNode (); - if (masterConfigNode != null && masterConfigNode.get (WATCHDOG_TIMEOUT_NAME) != null) { - - return masterConfigNode.get (WATCHDOG_TIMEOUT_NAME).asInt (); - } else { - return 0; - } - } - - @Override - public String getConsumerID () { - - JsonNode masterConfigNode = getASDCControllerConfigJsonNode (); - if (masterConfigNode != null && masterConfigNode.get (CONSUMER_ID_ATTRIBUTE_NAME) != null) { - String config = masterConfigNode.get (CONSUMER_ID_ATTRIBUTE_NAME).asText (); - - if (config.isEmpty ()) { - return null; - } else { - return config; - } - } else { - return null; - } - } - - @Override - public String getEnvironmentName () { - JsonNode masterConfigNode = getASDCControllerConfigJsonNode (); - if (masterConfigNode != null && masterConfigNode.get (ENVIRONMENT_NAME_ATTRIBUTE_NAME) != null) { - String config = masterConfigNode.get (ENVIRONMENT_NAME_ATTRIBUTE_NAME).asText (); - - if (config.isEmpty ()) { - return null; - } else { - return config; - } - } else { - return null; - } - } - - @Override - public String getPassword () { - Properties keyProp = new Properties (); - try { - keyProp.load (Thread.currentThread ().getContextClassLoader ().getResourceAsStream ("config-key.properties")); - PASSWORD_ATTRIBUTE_NAME=(String) keyProp.get ("password.attribute.name"); - JsonNode masterConfigNode = getASDCControllerConfigJsonNode (); - if (masterConfigNode != null && masterConfigNode.get (PASSWORD_ATTRIBUTE_NAME) != null) { - String config = this.msoProperties.getEncryptedProperty (masterConfigNode.get (PASSWORD_ATTRIBUTE_NAME), - null, - this.configKey); - - if (config.isEmpty ()) { - return null; - } else { - return config; - } - } else { - return null; - } - } catch (IOException e) { - msoLogger.debug("IOException occured", e); - return null; - } - } - - @Override - public int getPollingInterval () { - JsonNode masterConfigNode = getASDCControllerConfigJsonNode (); - if (masterConfigNode != null && masterConfigNode.get (POLLING_INTERVAL_ATTRIBUTE_NAME) != null) { - return masterConfigNode.get (POLLING_INTERVAL_ATTRIBUTE_NAME).asInt (); - } else { - return 0; - } - } - - @Override - public List getRelevantArtifactTypes () { - // DO not return the Static List SUPPORTED_ARTIFACT_TYPES_LIST because the ASDC Client will try to modify it !!! - return Arrays.asList(SUPPORTED_ARTIFACT_TYPES); - } - - @Override - public String getUser () { - JsonNode masterConfigNode = getASDCControllerConfigJsonNode (); - if (masterConfigNode != null && masterConfigNode.get (USER_ATTRIBUTE_NAME) != null) { - String config = masterConfigNode.get (USER_ATTRIBUTE_NAME).asText (); - - if (config.isEmpty ()) { - return null; - } else { - return config; - } - } else { - return null; - } - } - - @Override - public String getAsdcAddress () { - JsonNode masterConfigNode = getASDCControllerConfigJsonNode (); - if (masterConfigNode != null && masterConfigNode.get (ASDC_ADDRESS_ATTRIBUTE_NAME) != null) { - String config = masterConfigNode.get (ASDC_ADDRESS_ATTRIBUTE_NAME).asText (); - - if (config.isEmpty ()) { - return null; - } else { - return config; - } - } else { - return null; - } - } - - @Override - public int getPollingTimeout () { - JsonNode masterConfigNode = getASDCControllerConfigJsonNode (); - if (masterConfigNode != null && masterConfigNode.get (POLLING_TIMEOUT_ATTRIBUTE_NAME) != null) { - return masterConfigNode.get (POLLING_TIMEOUT_ATTRIBUTE_NAME).asInt (); - } else { - return 0; - } - } - - @Override - public boolean activateServerTLSAuth() { - JsonNode masterConfigNode = getASDCControllerConfigJsonNode(); - if (masterConfigNode != null && masterConfigNode.get(ACTIVATE_SERVER_TLS_AUTH) != null) { - return masterConfigNode.get(ACTIVATE_SERVER_TLS_AUTH).asBoolean(false); - } else { - return false; - } - } - - @Override - public String getKeyStorePassword() { - Properties keyProp = new Properties (); - try { - keyProp.load (Thread.currentThread ().getContextClassLoader ().getResourceAsStream ("config-key.properties")); - KEY_STORE_PASSWORD=(String) keyProp.get ("key.store.password"); - JsonNode masterConfigNode = getASDCControllerConfigJsonNode(); - if (masterConfigNode != null && masterConfigNode.get(KEY_STORE_PASSWORD) != null) { - String config = this.msoProperties.getEncryptedProperty(masterConfigNode.get(KEY_STORE_PASSWORD), null, - this.configKey); - - if (config.isEmpty()) { - return null; - } else { - return config; - } - } else { - return null; - } - } catch (IOException e) { - msoLogger.debug("IOException occured", e); - return null; - } - } - - @Override - public String getKeyStorePath() { - - JsonNode masterConfigNode = getASDCControllerConfigJsonNode(); - if (masterConfigNode != null && masterConfigNode.get(KEY_STORE_PATH) != null) { - String config = masterConfigNode.get(KEY_STORE_PATH).asText(); - - if (config.isEmpty()) { - return null; - } else { - return config; - } - } else { - return null; - } - - } - - public void testAllParameters () throws ASDCParametersException { - - // Special case for this attribute that can be null from getConsumerGroup - if (this.getConsumerGroup () == null - && (getASDCControllerConfigJsonNode () == null - || !"NULL".equals (getASDCControllerConfigJsonNode ().get (CONSUMER_GROUP_ATTRIBUTE_NAME).asText ()))) { - throw new ASDCParametersException (CONSUMER_GROUP_ATTRIBUTE_NAME - + " parameter cannot be found in config mso.properties"); - } - - if (this.getConsumerID () == null || this.getConsumerID ().isEmpty ()) { - throw new ASDCParametersException (CONSUMER_ID_ATTRIBUTE_NAME - + " parameter cannot be found in config mso.properties"); - } - - if (this.getEnvironmentName () == null || this.getEnvironmentName ().isEmpty ()) { - throw new ASDCParametersException (ENVIRONMENT_NAME_ATTRIBUTE_NAME - + " parameter cannot be found in config mso.properties"); - } - - if (this.getAsdcAddress () == null || this.getAsdcAddress ().isEmpty ()) { - throw new ASDCParametersException (ASDC_ADDRESS_ATTRIBUTE_NAME - + " parameter cannot be found in config mso.properties"); - } - - if (this.getPassword () == null || this.getPassword ().isEmpty ()) { - throw new ASDCParametersException (PASSWORD_ATTRIBUTE_NAME - + " parameter cannot be found in config mso.properties"); - } - - if (this.getPollingInterval () == 0) { - throw new ASDCParametersException (POLLING_INTERVAL_ATTRIBUTE_NAME - + " parameter cannot be found in config mso.properties"); - } - - if (this.getPollingTimeout () == 0) { - throw new ASDCParametersException (POLLING_TIMEOUT_ATTRIBUTE_NAME - + " parameter cannot be found in config mso.properties"); - } - - if (this.getWatchDogTimeout() == 0) { - throw new ASDCParametersException (WATCHDOG_TIMEOUT_NAME - + " parameter cannot be found in config mso.properties"); - } - - if (this.getRelevantArtifactTypes () == null || this.getRelevantArtifactTypes ().isEmpty ()) { - throw new ASDCParametersException (RELEVANT_ARTIFACT_TYPES_ATTRIBUTE_NAME - + " parameter cannot be found in config mso.properties"); - } - - if (this.getUser () == null || this.getUser ().isEmpty ()) { - throw new ASDCParametersException (USER_ATTRIBUTE_NAME - + " parameter cannot be found in config mso.properties"); - } - - if (this.getMsgBusAddress() == null || this.getMsgBusAddress().isEmpty ()) { - throw new ASDCParametersException (MSG_BUS_ADDRESS_ATTRIBUTE_NAME - + " parameter cannot be found in config mso.properties"); - } - - } - - /** - * This method triggers the MsoPropertiesFactory to get the ASDC config from the cache and extracts all controllers - * defined. - * - * @return A list of controller Names defined in the cache config - * @throws ASDCParametersException In cas of issues with the cache - */ - public static List getAllDefinedControllers () throws ASDCParametersException { - - MsoJsonProperties msoProp; - try { - List result = new ArrayList<>(); - msoProp = new MsoPropertiesFactory ().getMsoJsonProperties (MSO_PROP_ASDC); - - if (msoProp.getJsonRootNode ().get (PARAMETER_PATTERN) != null) { - Iterator > it = msoProp.getJsonRootNode () - .get (PARAMETER_PATTERN) - .fields(); - - Entry entry; - while (it.hasNext ()) { - entry = it.next (); - result.add (entry.getKey ()); - - } - } - return result; - } catch (MsoPropertiesException e) { - throw new ASDCParametersException ("Unable to get the JSON Properties in cache:" + MSO_PROP_ASDC, e); - } - - } - - /** - * The flag allows the client to receive metadata for all resources of the service regardless of the artifacts associated to them. - * Setting the flag to false will preserve legacy behavior. - */ - public boolean isFilterInEmptyResources() { - return true; - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCController.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCController.java deleted file mode 100644 index 867efd5840..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCController.java +++ /dev/null @@ -1,915 +0,0 @@ -/*- -d * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client; - - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; - -import org.onap.sdc.api.IDistributionClient; -import org.onap.sdc.api.consumer.IDistributionStatusMessage; -import org.onap.sdc.api.consumer.IFinalDistrStatusMessage; -import org.onap.sdc.api.consumer.INotificationCallback; -import org.onap.sdc.api.consumer.IStatusCallback; -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.INotificationData; -import org.onap.sdc.api.notification.IResourceInstance; -import org.onap.sdc.api.notification.IStatusData; -import org.onap.sdc.api.results.IDistributionClientDownloadResult; -import org.onap.sdc.api.results.IDistributionClientResult; -import org.onap.sdc.impl.DistributionClientFactory; -import org.onap.sdc.utils.DistributionActionResultEnum; -import org.onap.sdc.utils.DistributionStatusEnum; -import org.openecomp.mso.asdc.client.exceptions.ASDCControllerException; -import org.openecomp.mso.asdc.client.exceptions.ASDCDownloadException; -import org.openecomp.mso.asdc.client.exceptions.ASDCParametersException; -import org.openecomp.mso.asdc.client.exceptions.ArtifactInstallerException; -import org.openecomp.mso.asdc.installer.IVfResourceInstaller; -import org.openecomp.mso.asdc.installer.ToscaResourceStructure; -import org.openecomp.mso.asdc.installer.VfResourceStructure; -import org.openecomp.mso.asdc.installer.heat.ToscaResourceInstaller; -import org.openecomp.mso.asdc.installer.heat.VfResourceInstaller; -import org.openecomp.mso.asdc.tenantIsolation.DistributionStatus; -import org.openecomp.mso.asdc.tenantIsolation.WatchdogDistribution; -import org.openecomp.mso.asdc.util.ASDCNotificationLogging; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoAlarmLogger; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.properties.MsoPropertiesFactory; -import org.openecomp.mso.requestsdb.WatchdogDistributionStatusDb; -import org.openecomp.mso.utils.UUIDChecker; - -public class ASDCController { - - protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC); - - protected static MsoAlarmLogger alarmLogger = new MsoAlarmLogger (); - - protected boolean isAsdcClientAutoManaged = false; - - protected String controllerName; - - protected ToscaResourceInstaller toscaInstaller; - - private static MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory(); - - - private final class ResourceInstance implements IResourceInstance { - - @Override - public String getResourceInstanceName(){ - return new String(); - } - - @Override - public String getResourceName(){ - return new String(); - } - - @Override - public String getResourceVersion(){ - return new String(); - } - - @Override - public String getResourceType(){ - return new String(); - } - - @Override - public String getResourceUUID(){ - return new String(); - } - - // Method descriptor #10 ()Ljava/util/List; - @Override - public java.util.List getArtifacts(){ - return new ArrayList(); - } - - @Override - public String getResourceInvariantUUID(){ - return new String(); - } - - @Override - public String getResourceCustomizationUUID(){ - return new String(); - } - - @Override - public String getCategory(){ - return new String(); - } - - @Override - public String getSubcategory(){ - return new String(); - } - - } - - private final class ASDCStatusCallBack implements IStatusCallback { - - @Override - public void activateCallback (IStatusData iStatus) { - - long startTime = System.currentTimeMillis (); - UUIDChecker.generateUUID (LOGGER); - MsoLogger.setServiceName ("ASDCStatusCallBack"); - MsoLogger.setLogContext (iStatus.getDistributionID (), iStatus.getComponentName()); - String event = "Receive a callback componentStatus in ASDC, for componentName: " + iStatus.getComponentName() + " and status of " + iStatus.getStatus() + " distributionID of " + iStatus.getDistributionID() + - " consumerID of " + iStatus.getConsumerID() + " errorReason of " + iStatus.getErrorReason(); - - try{ - - if (iStatus.getStatus() == DistributionStatusEnum.COMPONENT_DONE_OK || - iStatus.getStatus() == DistributionStatusEnum.COMPONENT_DONE_ERROR) { - - LOGGER.debug(event); - - toscaInstaller.installTheComponentStatus(iStatus); - - } - - }catch(ArtifactInstallerException e){ - System.out.println("Error in ASDCStatusCallback " + e.getMessage()); - LOGGER.debug("Error in ASDCStatusCallback " + e.getMessage()); - } - LOGGER.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Completed the Status Call Back"); - } - - } - - - /** - * Inner class for Notification callback - * - * - */ - private final class ASDCNotificationCallBack implements INotificationCallback { - - private ASDCController asdcController; - - ASDCNotificationCallBack (ASDCController controller) { - asdcController = controller; - } - - /** - * This method can be called multiple times at the same moment. - * The controller must be thread safe ! - */ - @Override - public void activateCallback (INotificationData iNotif) { - long startTime = System.currentTimeMillis (); - UUIDChecker.generateUUID (LOGGER); - MsoLogger.setServiceName ("NotificationHandler"); - MsoLogger.setLogContext (iNotif.getDistributionID (), iNotif.getServiceUUID ()); - String event = "Receive a callback notification in ASDC, nb of resources: " + iNotif.getResources ().size (); - LOGGER.debug(event); - asdcController.treatNotification (iNotif); - LOGGER.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Completed the treatment of the notification"); - } - } - - - // ***** Controller STATUS code - - protected int nbOfNotificationsOngoing = 0; - - public int getNbOfNotificationsOngoing () { - return nbOfNotificationsOngoing; - } - - private ASDCControllerStatus controllerStatus = ASDCControllerStatus.STOPPED; - - protected synchronized final void changeControllerStatus (ASDCControllerStatus newControllerStatus) { - switch (newControllerStatus) { - - case BUSY: - ++this.nbOfNotificationsOngoing; - this.controllerStatus = newControllerStatus; - break; - - case IDLE: - if (this.nbOfNotificationsOngoing > 1) { - --this.nbOfNotificationsOngoing; - } else { - this.nbOfNotificationsOngoing = 0; - this.controllerStatus = newControllerStatus; - } - - break; - default: - this.controllerStatus = newControllerStatus; - break; - - } - } - - public synchronized final ASDCControllerStatus getControllerStatus () { - return this.controllerStatus; - } - - // ***** END of Controller STATUS code - protected ASDCConfiguration asdcConfig; - private IDistributionClient distributionClient; - private IVfResourceInstaller resourceInstaller; - - public ASDCController (String controllerConfigName) { - isAsdcClientAutoManaged = true; - this.controllerName = controllerConfigName; - this.resourceInstaller = new VfResourceInstaller(); - toscaInstaller = new ToscaResourceInstaller(); - } - - public ASDCController (String controllerConfigName, IDistributionClient asdcClient, IVfResourceInstaller resourceinstaller) { - - distributionClient = asdcClient; - this.resourceInstaller = resourceinstaller; - this.controllerName = controllerConfigName; - } - - public ASDCController (String controllerConfigName,IDistributionClient asdcClient) { - distributionClient = asdcClient; - this.controllerName = controllerConfigName; - this.resourceInstaller = new VfResourceInstaller(); - toscaInstaller = new ToscaResourceInstaller(); - } - - /** - * This method refresh the ASDC Controller config and restart the client. - * - * @return true if config has been reloaded, false otherwise - * @throws ASDCControllerException If case of issue with the init or close called during the config reload - * @throws ASDCParametersException If there is an issue with the parameters - * @throws IOException In case of the key file could not be loaded properly - */ - public boolean updateConfigIfNeeded () throws ASDCParametersException, ASDCControllerException, IOException { - LOGGER.debug ("Checking whether ASDC config must be reloaded"); - - try { - if (this.asdcConfig != null && this.asdcConfig.hasASDCConfigChanged ()) { - LOGGER.debug ("ASDC Config must be reloaded"); - this.closeASDC (); - this.asdcConfig.refreshASDCConfig (); - this.initASDC (); - return true; - } else { - LOGGER.debug ("ASDC Config must NOT be reloaded"); - return false; - } - } catch (ASDCParametersException ep) { - // Try to close it at least to make it consistent with the file specified - // We cannot let it run with a different config file, even if it's bad. - // This call could potentially throw a ASDCController exception if the controller is currently BUSY. - this.closeASDC (); - - throw ep; - } - } - - /** - * This method initializes the ASDC Controller and the ASDC Client. - * - * @throws ASDCControllerException It throws an exception if the ASDC Client cannot be instantiated or if an init - * attempt is done when already initialized - * @throws ASDCParametersException If there is an issue with the parameters provided - * @throws IOException In case of issues when trying to load the key file - */ - public void initASDC () throws ASDCControllerException, ASDCParametersException, IOException { - String event = "Initialize the ASDC Controller"; - MsoLogger.setServiceName ("InitASDC"); - LOGGER.debug (event); - if (this.getControllerStatus () != ASDCControllerStatus.STOPPED) { - String endEvent = "The controller is already initialized, call the closeASDC method first"; - throw new ASDCControllerException (endEvent); - } - - if (asdcConfig == null) { - asdcConfig = new ASDCConfiguration (this.controllerName); - - } - // attempt to refresh during init as MsoProperties is may be pointing to an old file - // Be careful this is static in MsoProperties - asdcConfig.refreshASDCConfig (); - - if (this.distributionClient == null) { - distributionClient = DistributionClientFactory.createDistributionClient (); - } - long initStartTime = System.currentTimeMillis (); - IDistributionClientResult result = this.distributionClient.init (asdcConfig, - new ASDCNotificationCallBack (this), new ASDCStatusCallBack()); - if (!result.getDistributionActionResult ().equals (DistributionActionResultEnum.SUCCESS)) { - String endEvent = "ASDC distribution client init failed with reason:" - + result.getDistributionMessageResult (); - LOGGER.recordMetricEvent (initStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.UnknownError, "Initialization of the ASDC Controller failed with reason:" + result.getDistributionMessageResult (), "ASDC", "init", null); - LOGGER.debug (endEvent); - asdcConfig = null; - - this.changeControllerStatus (ASDCControllerStatus.STOPPED); - throw new ASDCControllerException ("Initialization of the ASDC Controller failed with reason: " - + result.getDistributionMessageResult ()); - } - LOGGER.recordMetricEvent (initStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully initialize ASDC Controller", "ASDC", "init", null); - - long clientstartStartTime = System.currentTimeMillis (); - result = this.distributionClient.start (); - if (!result.getDistributionActionResult ().equals (DistributionActionResultEnum.SUCCESS)) { - String endEvent = "ASDC distribution client start failed with reason:" - + result.getDistributionMessageResult (); - LOGGER.recordMetricEvent (clientstartStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.UnknownError, endEvent, "ASDC", "start", null); - LOGGER.debug (endEvent); - asdcConfig = null; - this.changeControllerStatus (ASDCControllerStatus.STOPPED); - throw new ASDCControllerException ("Startup of the ASDC Controller failed with reason: " - + result.getDistributionMessageResult ()); - } - LOGGER.recordMetricEvent (clientstartStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully start ASDC distribution client", "ASDC", "start", null); - - - this.changeControllerStatus (ASDCControllerStatus.IDLE); - LOGGER.info (MessageEnum.ASDC_INIT_ASDC_CLIENT_SUC, "ASDC", "changeControllerStatus"); - } - - /** - * This method closes the ASDC Controller and the ASDC Client. - * - * @throws ASDCControllerException It throws an exception if the ASDC Client cannot be closed because - * it's currently BUSY in processing notifications. - */ - public void closeASDC () throws ASDCControllerException { - - MsoLogger.setServiceName ("CloseController"); - if (this.getControllerStatus () == ASDCControllerStatus.BUSY) { - throw new ASDCControllerException ("Cannot close the ASDC controller as it's currently in BUSY state"); - } - if (this.distributionClient != null) { - this.distributionClient.stop (); - // If auto managed we can set it to Null, ASDCController controls it. - // In the other case the client of this class has specified it, so we can't reset it - if (isAsdcClientAutoManaged) { - // Next init will initialize it with a new ASDC Client - this.distributionClient = null; - } - - } - this.changeControllerStatus (ASDCControllerStatus.STOPPED); - } - - private boolean checkResourceAlreadyDeployed (VfResourceStructure resource) throws ArtifactInstallerException { - - - if (toscaInstaller.isResourceAlreadyDeployed (resource)) { - LOGGER.info (MessageEnum.ASDC_ARTIFACT_ALREADY_EXIST, - resource.getResourceInstance().getResourceInstanceName(), - resource.getResourceInstance().getResourceUUID(), - resource.getResourceInstance().getResourceName(), "", ""); - - this.sendDeployNotificationsForResource(resource,DistributionStatusEnum.ALREADY_DOWNLOADED,null); - this.sendDeployNotificationsForResource(resource,DistributionStatusEnum.ALREADY_DEPLOYED,null); - - return true; - } else { - return false; - } - } - - private final static String UUID_PARAM = "(UUID:"; - - private IDistributionClientDownloadResult downloadTheArtifact (IArtifactInfo artifact, - String distributionId) throws ASDCDownloadException { - - LOGGER.debug ("Trying to download the artifact : " + artifact.getArtifactURL () - + UUID_PARAM - + artifact.getArtifactUUID () - + ")"); - IDistributionClientDownloadResult downloadResult; - - - try { - downloadResult = distributionClient.download (artifact); - if (null == downloadResult) { - LOGGER.info (MessageEnum.ASDC_ARTIFACT_NULL, artifact.getArtifactUUID (), "", ""); - return downloadResult; - } - } catch (RuntimeException e) { - LOGGER.debug ("Not able to download the artifact due to an exception: " + artifact.getArtifactURL ()); - this.sendASDCNotification (NotificationType.DOWNLOAD, - artifact.getArtifactURL (), - asdcConfig.getConsumerID (), - distributionId, - DistributionStatusEnum.DOWNLOAD_ERROR, - e.getMessage (), - System.currentTimeMillis ()); - - throw new ASDCDownloadException ("Exception caught when downloading the artifact", e); - } - - if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult ())) { - - LOGGER.info (MessageEnum.ASDC_ARTIFACT_DOWNLOAD_SUC, - artifact.getArtifactURL (), - artifact.getArtifactUUID (), - String.valueOf (downloadResult.getArtifactPayload ().length), "", ""); - - } else { - - LOGGER.error (MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL, - artifact.getArtifactName (), - artifact.getArtifactURL (), - artifact.getArtifactUUID (), - downloadResult.getDistributionMessageResult (), "", "", MsoLogger.ErrorCode.DataError, "ASDC artifact download fail"); - - this.sendASDCNotification (NotificationType.DOWNLOAD, - artifact.getArtifactURL (), - asdcConfig.getConsumerID (), - distributionId, - DistributionStatusEnum.DOWNLOAD_ERROR, - downloadResult.getDistributionMessageResult (), - System.currentTimeMillis ()); - - throw new ASDCDownloadException ("Artifact " + artifact.getArtifactName () - + " could not be downloaded from ASDC URL " - + artifact.getArtifactURL () - + UUID_PARAM - + artifact.getArtifactUUID () - + ")" - + System.lineSeparator () - + "Error message is " - + downloadResult.getDistributionMessageResult () - + System.lineSeparator ()); - - } - - this.sendASDCNotification (NotificationType.DOWNLOAD, - artifact.getArtifactURL (), - asdcConfig.getConsumerID (), - distributionId, - DistributionStatusEnum.DOWNLOAD_OK, - null, - System.currentTimeMillis ()); - return downloadResult; - - } - - private void writeArtifactToFile (IArtifactInfo artifact, - IDistributionClientDownloadResult resultArtifact) throws ASDCDownloadException { - - LOGGER.debug ("Trying to download the artifact : " + artifact.getArtifactURL () - + UUID_PARAM - + artifact.getArtifactUUID () - + ")"); - - File spoolFile = new File(System.getProperty("mso.config.path") + "/ASDC" + "/" + artifact.getArtifactName()); - - - byte[] payloadBytes = resultArtifact.getArtifactPayload(); - - try { - LOGGER.info(MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF, "***WRITE FILE ARTIFACT NAME", "ASDC", artifact.getArtifactName()); - - try (FileOutputStream outFile = new FileOutputStream(System.getProperty("mso.config.path") + "/ASDC" + "/" + artifact.getArtifactName())) { - outFile.write(payloadBytes, 0, payloadBytes.length); - } - } catch (Exception e) { - LOGGER.debug("Exception :",e); - LOGGER.error(MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL, - artifact.getArtifactName (), - artifact.getArtifactURL (), - artifact.getArtifactUUID (), - resultArtifact.getDistributionMessageResult (), "", "", MsoLogger.ErrorCode.DataError, "ASDC write to file failed"); - } - - } - - - private void sendDeployNotificationsForResource(VfResourceStructure vfResourceStructure,DistributionStatusEnum distribStatus, String errorReason) { - - for (IArtifactInfo artifactInfo : vfResourceStructure.getResourceInstance().getArtifacts()) { - - if ((DistributionStatusEnum.DEPLOY_OK.equals(distribStatus) && !artifactInfo.getArtifactType().equalsIgnoreCase("OTHER")) - // This could be NULL if the artifact is a VF module artifact, this won't be present in the MAP - && vfResourceStructure.getArtifactsMapByUUID().get(artifactInfo.getArtifactUUID()) != null - && vfResourceStructure.getArtifactsMapByUUID().get(artifactInfo.getArtifactUUID()).getDeployedInDb() == 0) { - this.sendASDCNotification (NotificationType.DEPLOY, - artifactInfo.getArtifactURL (), - asdcConfig.getConsumerID (), - vfResourceStructure.getNotification().getDistributionID(), - DistributionStatusEnum.DEPLOY_ERROR, - "The artifact has not been used by the modules defined in the resource", - System.currentTimeMillis ()); - } else { - this.sendASDCNotification (NotificationType.DEPLOY, - artifactInfo.getArtifactURL (), - asdcConfig.getConsumerID (), - vfResourceStructure.getNotification().getDistributionID(), - distribStatus, - errorReason, - System.currentTimeMillis ()); - } - } - } - - private void sendCsarDeployNotification(INotificationData iNotif, VfResourceStructure resourceStructure, ToscaResourceStructure toscaResourceStructure, boolean deploySuccessful, String errorReason) { - - IArtifactInfo csarArtifact = toscaResourceStructure.getToscaArtifact(); - - if(deploySuccessful){ - - this.sendASDCNotification (NotificationType.DEPLOY, - csarArtifact.getArtifactURL (), - asdcConfig.getConsumerID (), - resourceStructure.getNotification().getDistributionID(), - DistributionStatusEnum.DEPLOY_OK, - errorReason, - System.currentTimeMillis ()); - - } else { - - this.sendASDCNotification (NotificationType.DEPLOY, - csarArtifact.getArtifactURL (), - asdcConfig.getConsumerID (), - resourceStructure.getNotification().getDistributionID(), - DistributionStatusEnum.DEPLOY_ERROR, - errorReason, - System.currentTimeMillis ()); - - } - } - - private void deployResourceStructure (VfResourceStructure resourceStructure, ToscaResourceStructure toscaResourceStructure) throws ArtifactInstallerException { - - LOGGER.info (MessageEnum.ASDC_START_DEPLOY_ARTIFACT, resourceStructure.getResourceInstance().getResourceInstanceName(), resourceStructure.getResourceInstance().getResourceUUID(), "ASDC", "deployResourceStructure"); - try { - String resourceType = resourceStructure.getResourceInstance().getResourceType(); - String category = resourceStructure.getResourceInstance().getCategory(); - if("VF".equals(resourceType) && !"Allotted Resource".equalsIgnoreCase(category)){ - resourceStructure.createVfModuleStructures(); - } - - - toscaInstaller.installTheResource(toscaResourceStructure, resourceStructure); - - - } catch (ArtifactInstallerException e) { - LOGGER.info (MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL, - resourceStructure.getResourceInstance().getResourceName(), - resourceStructure.getResourceInstance().getResourceUUID(), - String.valueOf (resourceStructure.getVfModuleStructure().size()), "ASDC", "deployResourceStructure"); - sendDeployNotificationsForResource(resourceStructure,DistributionStatusEnum.DEPLOY_ERROR,e.getMessage()); - throw e; - } - - if (resourceStructure.isDeployedSuccessfully() || toscaResourceStructure.isDeployedSuccessfully()) { - LOGGER.info (MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC, - resourceStructure.getResourceInstance().getResourceName(), - resourceStructure.getResourceInstance().getResourceUUID(), - String.valueOf (resourceStructure.getVfModuleStructure().size()), "ASDC", "deployResourceStructure"); - sendDeployNotificationsForResource(resourceStructure,DistributionStatusEnum.DEPLOY_OK ,null); - } - - } - - - private enum NotificationType { - DOWNLOAD, DEPLOY - } - - private void sendASDCNotification (NotificationType notificationType, - String artifactURL, - String consumerID, - String distributionID, - DistributionStatusEnum status, - String errorReason, - long timestamp) { - - String event = "Sending " + notificationType.name () - + "(" - + status.name () - + ")" - + " notification to ASDC for artifact:" - + artifactURL; - - if (errorReason != null) { - event=event+"("+errorReason+")"; - } - LOGGER.info (MessageEnum.ASDC_SEND_NOTIF_ASDC, notificationType.name (), status.name (), artifactURL, "ASDC", "sendASDCNotification"); - LOGGER.debug (event); - - long subStarttime = System.currentTimeMillis (); - String action = ""; - try { - IDistributionStatusMessage message = new DistributionStatusMessage (artifactURL, - consumerID, - distributionID, - status, - timestamp); - - switch (notificationType) { - case DOWNLOAD: - if (errorReason != null) { - this.distributionClient.sendDownloadStatus (message, errorReason); - } else { - this.distributionClient.sendDownloadStatus (message); - } - action = "sendDownloadStatus"; - break; - case DEPLOY: - if (errorReason != null) { - this.distributionClient.sendDeploymentStatus (message, errorReason); - } else { - this.distributionClient.sendDeploymentStatus (message); - } - action = "sendDeploymentdStatus"; - break; - default: - break; - } - } catch (RuntimeException e) { - // TODO: May be a list containing the unsent notification should be - // kept - LOGGER.warn (MessageEnum.ASDC_SEND_NOTIF_ASDC_EXEC, "ASDC", "sendASDCNotification", MsoLogger.ErrorCode.SchemaError, "RuntimeException - sendASDCNotification", e); - } - LOGGER.recordMetricEvent (subStarttime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully sent notification to ASDC", "ASDC", action, null); - } - - private void sendFinalDistributionStatus ( - String distributionID, - DistributionStatusEnum status, - String errorReason) { - - - LOGGER.debug ("Enter sendFinalDistributionStatus with DistributionID " + distributionID + " and Status of " + status.name() + " and ErrorReason " + errorReason); - - long subStarttime = System.currentTimeMillis (); - try { - - - IFinalDistrStatusMessage finalDistribution = new FinalDistributionStatusMessage(distributionID,status,subStarttime, asdcConfig.getConsumerID()); - - if(errorReason == null){ - this.distributionClient.sendFinalDistrStatus(finalDistribution); - }else{ - this.distributionClient.sendFinalDistrStatus(finalDistribution, errorReason); - } - - - } catch (RuntimeException e) { - // TODO: May be a list containing the unsent notification should be - // kept - LOGGER.debug ("Exception caught in sendFinalDistributionStatus " + e.getMessage()); - LOGGER.warn (MessageEnum.ASDC_SEND_NOTIF_ASDC_EXEC, "ASDC", "sendASDCNotification", MsoLogger.ErrorCode.SchemaError, "RuntimeException - sendASDCNotification", e); - } - LOGGER.recordMetricEvent (subStarttime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully sent Final notification to ASDC", "ASDC", null, null); - } - - public void treatNotification (INotificationData iNotif) { - - int noOfArtifacts = 0; - WatchdogDistribution wd = new WatchdogDistribution(); - - for (IResourceInstance resource : iNotif.getResources ()) { - noOfArtifacts += resource.getArtifacts ().size (); - } - LOGGER.info (MessageEnum.ASDC_RECEIVE_CALLBACK_NOTIF, - String.valueOf (noOfArtifacts), - iNotif.getServiceUUID (), "ASDC", "treatNotification"); - - try { - LOGGER.debug(ASDCNotificationLogging.dumpASDCNotification(iNotif)); - LOGGER.info(MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF, iNotif.getServiceUUID(), "ASDC", "treatNotification"); - this.changeControllerStatus(ASDCControllerStatus.BUSY); - - - - // Process only the Resource artifacts in MSO - for (IResourceInstance resource : iNotif.getResources()) { - - // We process only VNF(VF), Network(VL) and PNF resources on MSO Side - //if ("VF".equals(resource.getResourceType()) || "VL".equals(resource.getResourceType()) || "PNF".equals(resource.getResourceType())){ - this.processResourceNotification(iNotif,resource); - //} - - } - - //Handle services without any resources - if (iNotif.getResources() == null || iNotif.getResources().size() < 1){ - - this.processResourceNotification(iNotif, new ResourceInstance()); - } - - //******************************************************************************************************** - //Start Watchdog loop and wait for all components to complete before reporting final status back. - // **If timer expires first then we will report a Distribution Error back to ASDC - //******************************************************************************************************** - long initialStartTime = System.currentTimeMillis(); - boolean componentsComplete = false; - String distributionStatus = null; - String watchdogError = null; - String overallStatus = null; - int watchDogTimeout = asdcConfig.getWatchDogTimeout() * 1000; - boolean isDeploySuccess = false; - WatchdogDistributionStatusDb wdDistributionStatus = WatchdogDistributionStatusDb.getInstance(); - - - while(componentsComplete == false && (System.currentTimeMillis() - initialStartTime) < watchDogTimeout) - { - - try{ - - distributionStatus = wd.getOverallDistributionStatus(iNotif.getDistributionID()); - Thread.sleep(watchDogTimeout / 10); - - }catch(Exception e){ - LOGGER.debug ("Exception in Watchdog Loop " + e.getMessage()); - Thread.sleep(watchDogTimeout / 10); - } - - if(distributionStatus != null && !distributionStatus.equalsIgnoreCase(DistributionStatus.INCOMPLETE.name())){ - - if(distributionStatus.equalsIgnoreCase(DistributionStatus.SUCCESS.name())){ - isDeploySuccess = true; - overallStatus = DistributionStatusEnum.DISTRIBUTION_COMPLETE_OK.name(); - }else{ - overallStatus = DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name(); - } - - componentsComplete = true; - } - } - - if(componentsComplete == false){ - LOGGER.debug("Timeout of " + watchDogTimeout + " seconds was reached before all components reported status"); - watchdogError = "Timeout occurred while waiting for all components to report status"; - overallStatus = DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name(); - } - - if(distributionStatus == null){ - overallStatus = DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name(); - LOGGER.debug("DistributionStatus is null for DistributionId: " + iNotif.getDistributionID()); - - } - - try { - wd.executePatchAAI(iNotif.getDistributionID(), iNotif.getServiceInvariantUUID(), overallStatus); - LOGGER.debug ("A&AI Updated succefully with Distribution Status!"); - } - catch(Exception e) { - LOGGER.debug ("Exception in Watchdog executePatchAAI(): " + e.getMessage()); - watchdogError = "Error calling A&AI " + e.getMessage(); - if(e.getCause() != null) { - LOGGER.debug ("Exception caused by: " + e.getCause().getMessage()); - } - } - - - if(isDeploySuccess && watchdogError == null){ - sendFinalDistributionStatus(iNotif.getDistributionID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_OK, null); - wdDistributionStatus.updateWatchdogDistributionIdStatus(iNotif.getDistributionID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_OK.name()); - } else { - sendFinalDistributionStatus(iNotif.getDistributionID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR, watchdogError); - wdDistributionStatus.updateWatchdogDistributionIdStatus(iNotif.getDistributionID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name()); - } - - - - } catch (Exception e) { - LOGGER.error (MessageEnum.ASDC_GENERAL_EXCEPTION_ARG, - "Unexpected exception caught during the notification processing", "ASDC", "treatNotification", MsoLogger.ErrorCode.SchemaError, "RuntimeException in treatNotification", - e); - - sendFinalDistributionStatus(iNotif.getDistributionID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR, e.getMessage()); - - } finally { - this.changeControllerStatus (ASDCControllerStatus.IDLE); - } - } - - - private void processResourceNotification (INotificationData iNotif,IResourceInstance resource) { - // For each artifact, create a structure describing the VFModule in a ordered flat level - VfResourceStructure resourceStructure = new VfResourceStructure(iNotif,resource); - ToscaResourceStructure toscaResourceStructure = new ToscaResourceStructure(); - boolean deploySuccessful = true; - String errorMessage = null; - - try { - - if (!this.checkResourceAlreadyDeployed(resourceStructure)) { - for (IArtifactInfo artifact : resource.getArtifacts()) { - - IDistributionClientDownloadResult resultArtifact = this.downloadTheArtifact(artifact, - iNotif.getDistributionID()); - - if (resultArtifact != null) { - if (ASDCConfiguration.VF_MODULES_METADATA.equals(artifact.getArtifactType())) { - LOGGER.debug("VF_MODULE_ARTIFACT: "+new String(resultArtifact.getArtifactPayload(),"UTF-8")); - LOGGER.debug(ASDCNotificationLogging.dumpVfModuleMetaDataList(resourceStructure.decodeVfModuleArtifact(resultArtifact.getArtifactPayload()))); - } - resourceStructure.addArtifactToStructure(distributionClient,artifact, resultArtifact); - - } - - } - this.processCsarServiceArtifacts(iNotif, toscaResourceStructure); - - try{ - - this.deployResourceStructure(resourceStructure, toscaResourceStructure); - - } catch(ArtifactInstallerException e){ - deploySuccessful = false; - errorMessage = e.getMessage(); - } - - this.sendCsarDeployNotification(iNotif, resourceStructure, toscaResourceStructure, deploySuccessful, errorMessage); - - - - } - } catch (ArtifactInstallerException | ASDCDownloadException | UnsupportedEncodingException e) { - LOGGER.error(MessageEnum.ASDC_GENERAL_EXCEPTION_ARG, - "Exception caught during Installation of artifact", "ASDC", "processResourceNotification", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in processResourceNotification", e); - } - } - - private void processCsarServiceArtifacts (INotificationData iNotif, ToscaResourceStructure toscaResourceStructure) { - - List serviceArtifacts = iNotif.getServiceArtifacts(); - - for(IArtifactInfo artifact : serviceArtifacts){ - - if(artifact.getArtifactType().equals(ASDCConfiguration.TOSCA_CSAR)){ - - try{ - - toscaResourceStructure.setToscaArtifact(artifact); - - IDistributionClientDownloadResult resultArtifact = this.downloadTheArtifact(artifact,iNotif.getDistributionID()); - - writeArtifactToFile(artifact, resultArtifact); - - toscaResourceStructure.updateResourceStructure(artifact); - - toscaResourceStructure.setServiceVersion(iNotif.getServiceVersion()); - - LOGGER.debug(ASDCNotificationLogging.dumpCSARNotification(iNotif, toscaResourceStructure)); - - - } catch(Exception e){ - System.out.println("Whats the error " + e.getMessage()); - LOGGER.error(MessageEnum.ASDC_GENERAL_EXCEPTION_ARG, - "Exception caught during processCsarServiceArtifacts", "ASDC", "processCsarServiceArtifacts", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in processCsarServiceArtifacts", e); - } - } - - } - } - - private static final String UNKNOWN="Unknown"; - - /** - * @return the address of the ASDC we are connected to. - */ - public String getAddress () { - if (asdcConfig != null) { - return asdcConfig.getAsdcAddress (); - } - return UNKNOWN; - } - - /** - * @return the environment name of the ASDC we are connected to. - */ - public String getEnvironment () { - if (asdcConfig != null) { - return asdcConfig.getEnvironmentName (); - } - return UNKNOWN; - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCControllerStatus.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCControllerStatus.java deleted file mode 100644 index db83a91b72..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCControllerStatus.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client; - - - -public enum ASDCControllerStatus { - STOPPED, IDLE, BUSY -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCGlobalController.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCGlobalController.java deleted file mode 100644 index 430bd10892..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/ASDCGlobalController.java +++ /dev/null @@ -1,217 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client; - - - -import java.io.IOException; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.openecomp.mso.asdc.client.exceptions.ASDCControllerException; -import org.openecomp.mso.asdc.client.exceptions.ASDCParametersException; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.properties.MsoJsonProperties; -import org.openecomp.mso.properties.MsoPropertiesException; -import org.openecomp.mso.properties.MsoPropertiesFactory; - - - -public class ASDCGlobalController { - - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC); - private Map controllers = new HashMap<>(); - - private MsoJsonProperties msoProp= null; - - private void loadControllers () throws ASDCParametersException { - - List controllerNames = ASDCConfiguration.getAllDefinedControllers(); - - StringBuilder controllerListLog = new StringBuilder("List of controllers loaded:"); - for (String controllerName : controllerNames) { - controllers.put(controllerName, new ASDCController(controllerName)); - controllerListLog.append(controllerName); - controllerListLog.append(";"); - } - LOGGER.debug(controllerListLog.toString()); - } - - private boolean sameControllersDefined() throws ASDCParametersException { - List controllerNames = ASDCConfiguration.getAllDefinedControllers(); - if (controllerNames.size() == controllers.size()) { - boolean areIdentical = true; - - for (String name:controllerNames) { - if (!controllers.containsKey(name)) { - areIdentical = false; - break; - } - } - return areIdentical; - - } else { - return false; - } - } - - /** - * Check that controllers list needs to be updated or not. - * return true if the list has been updated - */ - private boolean updateControllersListIfNeeded () { - boolean updateNeeded=false; - try { - - MsoPropertiesFactory msoPropFactory = new MsoPropertiesFactory(); - MsoJsonProperties newMsoProp; - - newMsoProp = msoPropFactory.getMsoJsonProperties(ASDCConfiguration.MSO_PROP_ASDC); - - if (msoPropFactory.propertiesHaveChanged(ASDCConfiguration.MSO_PROP_ASDC, msoProp) && !sameControllersDefined()) { - updateNeeded = true; - LOGGER.debug("List of ASDC controllers has been changed, trying to kill them"); - this.closeASDC(); - - // Wait that all controllers are down before restarting, next pass will kill them all - if (this.controllers.size() == 0) { - msoProp = newMsoProp; - this.loadControllers(); - } - } - - } catch (ASDCParametersException e) { - LOGGER.warn (MessageEnum.ASDC_LOAD_ASDC_CLIENT_EXC, - "All ASDC Hosts", - "All ASDC Envs", "ASDC", "", MsoLogger.ErrorCode.BusinessProcesssError, "ASDCParametersException in updateControllersListIfNeeded", - e); - } catch (MsoPropertiesException e) { - LOGGER.warn (MessageEnum.ASDC_LOAD_ASDC_CLIENT_EXC, - "All ASDC Hosts", - "All ASDC Envs", "ASDC", "", MsoLogger.ErrorCode.BusinessProcesssError, "MsoPropertiesException in updateControllersListIfNeeded", - e); - } - return updateNeeded; - - - } - - /** - * Checks for each controller if it is STOPPED and restart if it is the case. - */ - public void checkInStoppedState () { - - for (ASDCController controller : controllers.values()) { - if (ASDCControllerStatus.STOPPED.equals (controller.getControllerStatus ())) { - - // Try to restart just in case of issues - try { - controller.initASDC (); - } catch (ASDCControllerException ec) { - LOGGER.warn (MessageEnum.ASDC_INIT_ASDC_CLIENT_EXC, - controller.getAddress (), - controller.getEnvironment (), "ASDC", "", MsoLogger.ErrorCode.BusinessProcesssError, "ASDCControllerException in checkInStoppedState", - ec); - } catch (ASDCParametersException ep) { - LOGGER.warn (MessageEnum.ASDC_LOAD_ASDC_CLIENT_EXC, - controller.getAddress (), - controller.getEnvironment (), "ASDC", "", MsoLogger.ErrorCode.BusinessProcesssError, "ASDCParametersException in checkInStoppedState", - ep); - } catch (RuntimeException | IOException e) { - LOGGER.error (MessageEnum.ASDC_SINGLETON_CHECKT_EXC, - controller.getAddress (), - controller.getEnvironment (), "ASDC", "", MsoLogger.ErrorCode.BusinessProcesssError, "RuntimeException in checkInStoppedState", - e); - } - } - } - } - - public void closeASDC () { - List controllerToRemove = new LinkedList<>(); - - for (ASDCController controller : controllers.values()) { - try { - controller.closeASDC (); - controllerToRemove.add(controller.controllerName); - - } catch (RuntimeException e) { - LOGGER.warn (MessageEnum.ASDC_SHUTDOWN_ASDC_CLIENT_EXC, - "RuntimeException", - controller.getAddress (), - controller.getEnvironment (), "ASDC", "closeASDC", MsoLogger.ErrorCode.BusinessProcesssError, "RuntimeException in closeASDC", - e); - } catch (ASDCControllerException e) { - LOGGER.warn (MessageEnum.ASDC_SHUTDOWN_ASDC_CLIENT_EXC, - "ASDCControllerException", - controller.getAddress (), - controller.getEnvironment (), "ASDC", "closeASDC", MsoLogger.ErrorCode.BusinessProcesssError, "ASDCControllerException in closeASDC", - e); - } - } - - // Now remove the ones properly closed - for (String toRemove:controllerToRemove) { - controllers.remove(toRemove); - } - - } - - /** - * Check whether the config has been changed - */ - public boolean updateControllersConfigIfNeeded () { - boolean listUpdated=updateControllersListIfNeeded(); - if (!listUpdated) { - - for (ASDCController controller : controllers.values()) { - try { - controller.updateConfigIfNeeded (); - } catch (ASDCControllerException ec) { - LOGGER.warn (MessageEnum.ASDC_INIT_ASDC_CLIENT_EXC, - controller.getAddress (), - controller.getEnvironment (), "ASDC", "closeASDC", MsoLogger.ErrorCode.BusinessProcesssError, "ASDCControllerException in updateControllersConfigIfNeeded", - ec); - } catch (ASDCParametersException ep) { - LOGGER.warn (MessageEnum.ASDC_LOAD_ASDC_CLIENT_EXC, - controller.getAddress (), - controller.getEnvironment (), "ASDC", "closeASDC", MsoLogger.ErrorCode.BusinessProcesssError, "ASDCParametersException in updateControllersConfigIfNeeded", - ep); - } catch (RuntimeException | IOException e) { - LOGGER.error (MessageEnum.ASDC_SINGLETON_CHECKT_EXC, - controller.getAddress (), - controller.getEnvironment (), "ASDC", "closeASDC", MsoLogger.ErrorCode.BusinessProcesssError, "RuntimeException in updateControllersConfigIfNeeded", - e); - } - } - } - return listUpdated; - } - - public Map getControllers() { - return controllers; - } - - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/DistributionStatusMessage.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/DistributionStatusMessage.java deleted file mode 100644 index 60fa4a9f98..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/DistributionStatusMessage.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client; - - -import org.onap.sdc.api.consumer.IDistributionStatusMessage; -import org.onap.sdc.utils.DistributionStatusEnum; - -public class DistributionStatusMessage implements IDistributionStatusMessage { - - private String artifactURL; - - private String consumerID; - - private String distributionID; - - private DistributionStatusEnum distributionStatus; - - private long timestamp; - - public DistributionStatusMessage (final String artifactUrl, final String consumerId,final String distributionId, final DistributionStatusEnum distributionStatusEnum, final long timestampL) { - artifactURL = artifactUrl; - consumerID = consumerId; - distributionID = distributionId; - distributionStatus = distributionStatusEnum; - timestamp = timestampL; - } - - @Override - public String getArtifactURL() { - - return artifactURL; - } - - @Override - public String getConsumerID() { - - return consumerID; - } - - @Override - public String getDistributionID() { - - return distributionID; - } - - @Override - public DistributionStatusEnum getStatus() { - - return distributionStatus; - } - - @Override - public long getTimestamp() { - - return timestamp; - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/FinalDistributionStatusMessage.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/FinalDistributionStatusMessage.java deleted file mode 100644 index bf22d7e323..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/FinalDistributionStatusMessage.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client; - -import org.onap.sdc.api.consumer.IFinalDistrStatusMessage; -import org.onap.sdc.utils.DistributionStatusEnum; - -public class FinalDistributionStatusMessage implements IFinalDistrStatusMessage{ - - private String componentName; - - private String consumerID; - - private String distributionID; - - private DistributionStatusEnum status; - - private long timestamp; - - public FinalDistributionStatusMessage (String distributionId, final DistributionStatusEnum distributionStatusEnum, final long timestampL, String consumerId) { - //componentName = componentname; - consumerID = consumerId; - distributionID = distributionId; - status = distributionStatusEnum; - timestamp = timestampL; - } - - public DistributionStatusEnum getStatus() { - return status; - } - - public void setStatus(DistributionStatusEnum status) { - this.status = status; - } - - public String getDistributionID() { - return distributionID; - } - - public void setDistributionID(String distributionID) { - this.distributionID = distributionID; - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } - - public String getComponentName() { - return componentName; - } - - public void setComponentName(String componentName) { - this.componentName = componentName; - } - - public String getConsumerID() { - return consumerID; - } - - public void setConsumerID(String consumerID) { - this.consumerID = consumerID; - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ASDCControllerException.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ASDCControllerException.java deleted file mode 100644 index e8cb308073..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ASDCControllerException.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.exceptions; - - -/** - * Exception of the ASDC controller. - */ -public class ASDCControllerException extends Exception { - - /** - * serialization id. - */ - private static final long serialVersionUID = -4236006447255525130L; - - /** - * @param message The message to dump - * @param cause The Throwable cause object - */ - public ASDCControllerException (final String message) { - super (message); - - } - - /** - * @param message The message to dump - * @param cause The Throwable cause object - */ - public ASDCControllerException (final String message, final Throwable cause) { - super (message, cause); - - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ASDCDownloadException.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ASDCDownloadException.java deleted file mode 100644 index a8a0f150eb..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ASDCDownloadException.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.exceptions; - - -/** - * Exception during download from ASDC. - */ -public class ASDCDownloadException extends Exception { - - /** - * serialization id. - */ - private static final long serialVersionUID = -5276848693231134901L; - - /** - * @param message The message to dump - * @param cause The Throwable cause object - */ - public ASDCDownloadException (final String message) { - super (message); - - } - - /** - * @param message The message to dump - * @param cause The Throwable cause object - */ - public ASDCDownloadException (final String message, final Throwable cause) { - super (message, cause); - - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ASDCParametersException.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ASDCParametersException.java deleted file mode 100644 index b4bce4ed85..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ASDCParametersException.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.exceptions; - - -/** - * Exception of the ASDC controller. - */ -public class ASDCParametersException extends Exception { - - /** - * serialization id. - */ - private static final long serialVersionUID = 8425657297510362736L; - - /** - * @param message The message to dump - * @param cause The Throwable cause object - */ - public ASDCParametersException (final String message) { - super (message); - - } - - /** - * @param message The message to dump - * @param cause The Throwable cause object - */ - public ASDCParametersException (final String message, final Throwable cause) { - super (message, cause); - - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ArtifactInstallerException.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ArtifactInstallerException.java deleted file mode 100644 index e8a5e81abe..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/exceptions/ArtifactInstallerException.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.exceptions; - - -/** - * Exception during artifact installation. - */ -public class ArtifactInstallerException extends Exception { - - /** - * serialization id. - */ - private static final long serialVersionUID = 4095937499475915021L; - - /** - * @param message The message to dump - * @param cause The Throwable cause object - */ - public ArtifactInstallerException (final String message) { - super (message); - - } - - /** - * @param message The message to dump - * @param cause The Throwable cause object - */ - public ArtifactInstallerException (final String message, final Throwable cause) { - super (message, cause); - - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/DistributionClientEmulator.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/DistributionClientEmulator.java deleted file mode 100644 index 426e2353d8..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/DistributionClientEmulator.java +++ /dev/null @@ -1,204 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.test.emulators; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.LinkedList; -import java.util.List; - -import org.apache.commons.io.IOUtils; -import org.openecomp.mso.asdc.installer.IVfModuleData; -import org.onap.sdc.api.IDistributionClient; -import org.onap.sdc.api.consumer.IComponentDoneStatusMessage; -import org.onap.sdc.api.consumer.IConfiguration; -import org.onap.sdc.api.consumer.IDistributionStatusMessage; -import org.onap.sdc.api.consumer.IFinalDistrStatusMessage; -import org.onap.sdc.api.consumer.INotificationCallback; -import org.onap.sdc.api.consumer.IStatusCallback; -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.IVfModuleMetadata; -import org.onap.sdc.api.results.IDistributionClientDownloadResult; -import org.onap.sdc.api.results.IDistributionClientResult; -import org.onap.sdc.impl.DistributionClientDownloadResultImpl; -import org.onap.sdc.impl.DistributionClientResultImpl; -import org.onap.sdc.utils.DistributionActionResultEnum; - -public class DistributionClientEmulator implements IDistributionClient { - - private String resourcePath; - - private List listVFModuleMetaData; - - private List distributionMessageReceived = new LinkedList<>(); - - public DistributionClientEmulator(String notifFolderInResource) { - - resourcePath = notifFolderInResource; - } - - public List getDistributionMessageReceived() { - return distributionMessageReceived; - } - - @Override - public List decodeVfModuleArtifact(byte[] arg0) { - return null; - } - - /* @Override - public List decodeVfModuleArtifact(byte[] arg0) { - try { - listVFModuleMetaData = new ObjectMapper().readValue(arg0, new TypeReference>(){}); - return listVFModuleMetaData; - - } catch (JsonParseException e) { - e.printStackTrace(); - } catch (JsonMappingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } */ - - public List getListVFModuleMetaData() { - return listVFModuleMetaData; - } - - @Override - public IDistributionClientDownloadResult download (IArtifactInfo arg0) { - - - //String filename = resourcePath+"/artifacts/"+arg0.getArtifactURL(); - String filename = arg0.getArtifactURL(); - System.out.println("Emulating the download from resources files:"+filename); - - InputStream inputStream = null; - - if(arg0.getArtifactName().equals("service_PortMirroringContainer_csar.csar")){ - try{ - inputStream = new FileInputStream("C://Users//JM5423//git//mso//asdc-tosca-1712-test3//openecomp-mso//asdc-controller//src//main//resources//resource-examples//service_PortMirroringContainer_csar.csar"); - }catch(Exception e){ - System.out.println("Error " + e.getMessage()); - } - }else{ - - inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath + filename); - } - - if (inputStream == null) { - System.out.println("InputStream is NULL for:"+filename); - } - try { - return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name(),arg0.getArtifactName(),IOUtils.toByteArray(inputStream)); - } catch (IOException e) { - - e.printStackTrace(); - } - return null; - } - - @Override - public IConfiguration getConfiguration() { - return null; - } - - @Override - public IDistributionClientResult init(IConfiguration arg0, INotificationCallback arg1) { - return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); - } - - @Override - public IDistributionClientResult init(IConfiguration arg0, INotificationCallback arg1, IStatusCallback arg2) { - return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); - } - - @Override - public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage arg0) { - this.distributionMessageReceived.add(arg0); - return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); - } - - @Override - public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage arg0, String arg1) { - this.distributionMessageReceived.add(arg0); - return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); - } - - @Override - public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage arg0) { - this.distributionMessageReceived.add(arg0); - return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); - } - - @Override - public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage arg0, String arg1) { - this.distributionMessageReceived.add(arg0); - return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); - } - - @Override - public IDistributionClientResult start() { - return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); - } - - @Override - public IDistributionClientResult stop() { - return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); - - } - - @Override - public IDistributionClientResult updateConfiguration(IConfiguration arg0) { - return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name()); - } - - @Override - public IDistributionClientResult sendComponentDoneStatus( - IComponentDoneStatusMessage arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public IDistributionClientResult sendFinalDistrStatus( - IFinalDistrStatusMessage arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public IDistributionClientResult sendComponentDoneStatus( - IComponentDoneStatusMessage arg0, String arg1) { - // TODO Auto-generated method stub - return null; - } - - @Override - public IDistributionClientResult sendFinalDistrStatus( - IFinalDistrStatusMessage arg0, String arg1) { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonArtifactInfo.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonArtifactInfo.java deleted file mode 100644 index b57792e6d5..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonArtifactInfo.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.test.emulators; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.onap.sdc.api.notification.IArtifactInfo; - -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; - -public class JsonArtifactInfo implements IArtifactInfo { - - @JsonIgnore - private Map artifactsMapByUUID = new HashMap<>(); - - @JsonIgnore - private Map attributesMap = new HashMap<>(); - - public JsonArtifactInfo() { - - } - - public synchronized void addArtifactToUUIDMap (List artifactList) { - for (JsonArtifactInfo artifact:artifactList) { - artifactsMapByUUID.put(artifact.getArtifactUUID(), artifact); - } - - } - - @SuppressWarnings("unused") - @JsonAnySetter - public final void setAttribute(String attrName, Object attrValue) { - if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) { - this.attributesMap.put(attrName,attrValue); - } - } - - - - public Map getArtifactsMapByUUID() { - return artifactsMapByUUID; - } - - @Override - public String getArtifactChecksum() { - return (String)attributesMap.get("artifactCheckSum"); - } - - @Override - public String getArtifactDescription() { - return (String)attributesMap.get("artifactDescription"); - } - - @Override - public String getArtifactName() { - return (String)attributesMap.get("artifactName"); - } - - @Override - public Integer getArtifactTimeout() { - return (Integer)attributesMap.get("artifactTimeout"); - } - - @Override - public String getArtifactType() { - return (String)attributesMap.get("artifactType"); - } - - @Override - public String getArtifactURL() { - return (String)attributesMap.get("artifactURL"); - } - - @Override - public String getArtifactUUID() { - return (String)attributesMap.get("artifactUUID"); - } - - @Override - public String getArtifactVersion() { - return (String)attributesMap.get("artifactVersion"); - } - - @Override - public IArtifactInfo getGeneratedArtifact () { - return artifactsMapByUUID.get(attributesMap.get("generatedArtifact")); - } - - @Override - public List getRelatedArtifacts() { - List listArtifacts = new LinkedList<>(); - List uuidList = (List)attributesMap.get("relatedArtifact"); - if (uuidList != null) { - for(String uuid:uuidList) { - listArtifacts.add(artifactsMapByUUID.get(uuid)); - } - } - return listArtifacts; - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonArtifactInfoDeserializer.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonArtifactInfoDeserializer.java deleted file mode 100644 index 66863b562e..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonArtifactInfoDeserializer.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.test.emulators; - -import java.io.IOException; -import java.util.List; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JsonArtifactInfoDeserializer extends JsonDeserializer>{ - - @Override - public List deserialize(JsonParser jp, DeserializationContext ctxt) - throws IOException, JsonProcessingException { - List jsonArtifactInfoList = new ObjectMapper().readValue(jp, new TypeReference>(){}); - - // For each artifact add the list of artifact retrieved - // This could be used later to index by UUID - for (JsonArtifactInfo artifactInfo:jsonArtifactInfoList) { - artifactInfo.addArtifactToUUIDMap(jsonArtifactInfoList); - } - return jsonArtifactInfoList; - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonNotificationData.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonNotificationData.java deleted file mode 100644 index 3eddb4a7c5..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonNotificationData.java +++ /dev/null @@ -1,149 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.test.emulators; - -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.INotificationData; -import org.onap.sdc.api.notification.IResourceInstance; - -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - - -public class JsonNotificationData implements INotificationData { - - @JsonIgnore - private static ObjectMapper mapper = new ObjectMapper(); - - @JsonIgnore - private Map attributesMap = new HashMap<>(); - - @JsonProperty("serviceArtifacts") - @JsonDeserialize(using=JsonArtifactInfoDeserializer.class) - private List serviceArtifacts; - - @JsonProperty("resources") - @JsonDeserialize(using=JsonResourceInfoDeserializer.class) - private List resourcesList; - - public JsonNotificationData() { - - } - - /** - * Method instantiate a INotificationData implementation from a JSON file. - * - * @param notifFilePath The file path in String - * @return A JsonNotificationData instance - * @throws IOException in case of the file is not readable or not accessible - */ - public static JsonNotificationData instantiateNotifFromJsonFile(String notifFilePath) throws IOException { - - InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(notifFilePath + "notif-structure.json"); - - //String fileLocation = System.getProperty("mso.config.path") + "notif-structure.json"; - - //String source = fileLocation; - //InputStream is = IOUtils.toInputStream(source, "UTF-8"); - - //String myString = IOUtils.toString(is, "UTF-8"); - - - //System.out.println(myString); - - if (is == null) { - //throw new FileExistsException("Resource Path does not exist: "+notifFilePath); - } - return mapper.readValue(is, JsonNotificationData.class); - } - - @SuppressWarnings("unused") - @JsonAnySetter - public final void setAttribute(String attrName, Object attrValue) { - if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) { - this.attributesMap.put(attrName,attrValue); - } - } - - @Override - public String getWorkloadContext(){ - return (String)this.attributesMap.get("workloadContext"); - } - - @Override - public void setWorkloadContext(java.lang.String arg0){ - - } - - @Override - public IArtifactInfo getArtifactMetadataByUUID(String arg0) { - return null; - } - - @Override - public String getDistributionID() { - return (String)this.attributesMap.get("distributionID"); - } - - @Override - public List getResources() { - return resourcesList; - } - - @Override - public List getServiceArtifacts() { - return this.serviceArtifacts; - } - - @Override - public String getServiceDescription() { - return (String)this.attributesMap.get("serviceDescription"); - } - - @Override - public String getServiceInvariantUUID() { - return (String)this.attributesMap.get("serviceInvariantUUID"); - } - - @Override - public String getServiceName() { - return (String)this.attributesMap.get("serviceName"); - } - - @Override - public String getServiceUUID() { - return (String)this.attributesMap.get("serviceUUID"); - } - - @Override - public String getServiceVersion() { - return (String)this.attributesMap.get("serviceVersion"); - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonResourceInfo.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonResourceInfo.java deleted file mode 100644 index 6f26fd0daa..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonResourceInfo.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.test.emulators; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.IResourceInstance; - -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - -public class JsonResourceInfo implements IResourceInstance { - - @JsonIgnore - private Map attributesMap = new HashMap<>(); - - @JsonProperty("artifacts") - @JsonDeserialize(using=JsonArtifactInfoDeserializer.class) - private List artifacts; - - public JsonResourceInfo() { - - } - - @Override - public List getArtifacts() { - return artifacts; - } - - @Override - public String getResourceInstanceName() { - return (String)attributesMap.get("resourceInstanceName"); - } - - @Override - public String getResourceInvariantUUID() { - return (String)attributesMap.get("resourceInvariantUUID"); - } - - @Override - public String getResourceCustomizationUUID() { - return (String)attributesMap.get("resourceCustomizationUUID"); - } - - @Override - public String getResourceName() { - return (String)attributesMap.get("resourceName"); - } - - @Override - public String getResourceType() { - return (String)attributesMap.get("resourceType"); - } - - @Override - public String getResourceUUID() { - return (String)attributesMap.get("resourceUUID"); - } - - @Override - public String getResourceVersion() { - return (String)attributesMap.get("resourceVersion"); - } - - @Override - public String getSubcategory() { - return (String)attributesMap.get("subCategory"); - } - - @Override - public String getCategory() { - return (String)attributesMap.get("category"); - } - - @SuppressWarnings("unused") - @JsonAnySetter - public final void setAttribute(String attrName, Object attrValue) { - if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) { - this.attributesMap.put(attrName,attrValue); - } - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonResourceInfoDeserializer.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonResourceInfoDeserializer.java deleted file mode 100644 index 49908e71a0..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonResourceInfoDeserializer.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.test.emulators; - -import java.io.IOException; -import java.util.List; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JsonResourceInfoDeserializer extends JsonDeserializer>{ - - @Override - public List deserialize(JsonParser jp, DeserializationContext ctxt) - throws IOException, JsonProcessingException { - List jsonResourceInfoList = new ObjectMapper().readValue(jp, new TypeReference>(){}); - - return jsonResourceInfoList; - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonStatusData.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonStatusData.java deleted file mode 100644 index 25615b7a33..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonStatusData.java +++ /dev/null @@ -1,124 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.test.emulators; - -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; - -import org.onap.sdc.api.notification.IStatusData; -import org.onap.sdc.utils.DistributionStatusEnum; - -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.databind.ObjectMapper; - - -public class JsonStatusData implements IStatusData { - - @JsonIgnore - private static ObjectMapper mapper = new ObjectMapper(); - - @JsonIgnore - private Map attributesMap = new HashMap<>(); - - public JsonStatusData() { - - } - - @Override - public String getErrorReason(){ - return "MSO FAILURE"; - } - - @Override - public String getDistributionID(){ - //return (String)this.attributesMap.get("distributionID"); - return "35120a87-1f82-4276-9735-f6de5a244d65"; - } - - @Override - public String getConsumerID(){ - //return (String)this.attributesMap.get("consumerID"); - return "mso.123456"; - } - - @Override - public String getComponentName(){ - //return (String)this.attributesMap.get("componentName"); - return "SDN-C"; - } - - @Override - public Long getTimestamp(){ - //return (String)this.attributesMap.get("timestamp"); - return null; - } - - @Override - public String getArtifactURL(){ - //return (String)this.attributesMap.get("artifactURL"); - return "/sdc/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml"; - } - - @Override - public DistributionStatusEnum getStatus(){ - //return (DistributionStatusEnum)this.attributesMap.get(DistributionStatusEnum.DEPLOY_OK); - return DistributionStatusEnum.COMPONENT_DONE_OK; - } - - /** - * Method instantiate a INotificationData implementation from a JSON file. - * - * @param notifFilePath The file path in String - * @return A JsonNotificationData instance - * @throws IOException in case of the file is not readable or not accessible - */ - public static JsonStatusData instantiateNotifFromJsonFile(String notifFilePath) throws IOException { - - InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(notifFilePath + "status-structure.json"); - - //String fileLocation = System.getProperty("mso.config.path") + "notif-structure.json"; - - //String source = fileLocation; - //InputStream is = IOUtils.toInputStream(source, "UTF-8"); - - //String myString = IOUtils.toString(is, "UTF-8"); - - - //System.out.println(myString); - - if (is == null) { - //throw new FileExistsException("Resource Path does not exist: "+notifFilePath); - } - return mapper.readValue(is, JsonStatusData.class); - } - - @SuppressWarnings("unused") - @JsonAnySetter - public final void setAttribute(String attrName, Object attrValue) { - if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) { - this.attributesMap.put(attrName,attrValue); - } - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonVfModuleMetaData.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonVfModuleMetaData.java deleted file mode 100644 index 765f14f78e..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/emulators/JsonVfModuleMetaData.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.test.emulators; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.openecomp.mso.asdc.installer.IVfModuleData; - -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class JsonVfModuleMetaData implements IVfModuleData { - - @JsonProperty("artifacts") - private List artifacts; - @JsonProperty("properties") - //private List> properties = new ArrayList<>(); - private Map properties = new HashMap<>(); - - public Map getProperties() { - return properties; - } - - @JsonIgnore - private Map attributesMap = new HashMap<>(); - - @Override - public List getArtifacts() { - return artifacts; - } - - @Override - public String getVfModuleModelDescription() { - return (String)attributesMap.get("vfModuleModelDescription"); - } - - @Override - public String getVfModuleModelInvariantUUID() { - return (String)attributesMap.get("vfModuleModelInvariantUUID"); - } - - @Override - public String getVfModuleModelCustomizationUUID() { - return (String)attributesMap.get("vfModuleModelCustomizationUUID"); - } - - @Override - public String getVfModuleModelName() { - return (String)attributesMap.get("vfModuleModelName"); - } - - @Override - public String getVfModuleModelUUID() { - return (String)attributesMap.get("vfModuleModelUUID"); - } - - @Override - public String getVfModuleModelVersion() { - return (String)attributesMap.get("vfModuleModelVersion"); - } - - @Override - public boolean isBase() { - return (boolean)attributesMap.get("isBase"); - } - - @SuppressWarnings("unused") - @JsonAnySetter - public final void setAttribute(String attrName, Object attrValue) { - if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) { - this.attributesMap.put(attrName,attrValue); - } - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/rest/ASDCRestInterface.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/rest/ASDCRestInterface.java deleted file mode 100644 index ae434b1d3c..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/client/test/rest/ASDCRestInterface.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.client.test.rest; - - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.openecomp.mso.asdc.client.ASDCController; -import org.openecomp.mso.asdc.client.test.emulators.DistributionClientEmulator; -import org.openecomp.mso.asdc.client.test.emulators.JsonNotificationData; -import org.openecomp.mso.asdc.client.test.emulators.JsonStatusData; -import org.openecomp.mso.asdc.installer.heat.ToscaResourceInstaller; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; - -/** - * This is a TEST only rest interface. It is not used in production, it is used to aid in testing the ASDC service on jboss without the need to be connected - * to the ASDC service broker. It starts the test at the treatNotification step and simulates both the notification step as well as the artifact download step. - * - * i.e. http://localhost:8080/asdc/treatNotification/v1 - * - * i.e. http://localhost:8080/asdc/statusData/v1 - * - * @author jm5423 - * - */ - -@Path("/") -public class ASDCRestInterface { - - private static DistributionClientEmulator distributionClientEmulator; - - private static JsonNotificationData notifDataWithoutModuleInfo; - - private static JsonStatusData statusData; - - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC); - - @GET - @Path("/treatNotification/v1") - @Produces(MediaType.APPLICATION_JSON) - public Response invokeASDCService(String request) { - - try{ - distributionClientEmulator = new DistributionClientEmulator("resource-examples/"); - notifDataWithoutModuleInfo = JsonNotificationData.instantiateNotifFromJsonFile("resource-examples/"); - - ASDCController asdcController = new ASDCController("asdc-controller1", distributionClientEmulator); - LOGGER.info(MessageEnum.ASDC_INIT_ASDC_CLIENT_EXC, notifDataWithoutModuleInfo.getServiceUUID(), "ASDC", "initASDC()"); - asdcController.initASDC(); - LOGGER.info(MessageEnum.ASDC_INIT_ASDC_CLIENT_EXC, notifDataWithoutModuleInfo.getServiceUUID(), "ASDC", "treatNotification()"); - asdcController.treatNotification(notifDataWithoutModuleInfo); - LOGGER.info(MessageEnum.ASDC_INIT_ASDC_CLIENT_EXC, notifDataWithoutModuleInfo.getServiceUUID(), "ASDC", "closeASDC()"); - asdcController.closeASDC(); - }catch(Exception e){ - System.out.println("Error caught " + e.getMessage()); - LOGGER.error(MessageEnum.ASDC_GENERAL_EXCEPTION, - "Exception caught during ASDCRestInterface", "ASDC", "invokeASDCService", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in invokeASDCService", e); - } - System.out.println("ASDC Updates are complete"); - LOGGER.info(MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC, notifDataWithoutModuleInfo.getServiceUUID(), "ASDC", "ASDC Updates Are Complete"); - - return null; - } - - @GET - @Path("/statusData/v1") - @Produces(MediaType.APPLICATION_JSON) - public Response invokeASDCStatusData(String request) { - - ToscaResourceInstaller toscaInstaller = new ToscaResourceInstaller(); - - try{ - distributionClientEmulator = new DistributionClientEmulator("resource-examples/"); - statusData = JsonStatusData.instantiateNotifFromJsonFile("resource-examples/"); - - ASDCController asdcController = new ASDCController("asdc-controller1", distributionClientEmulator); - //LOGGER.info(MessageEnum.ASDC_INIT_ASDC_CLIENT_EXC, notifDataWithoutModuleInfo.getServiceUUID(), "ASDC", "initASDC()"); - asdcController.initASDC(); - //LOGGER.info(MessageEnum.ASDC_INIT_ASDC_CLIENT_EXC, notifDataWithoutModuleInfo.getServiceUUID(), "ASDC", "treatNotification()"); - toscaInstaller.installTheComponentStatus(statusData); - //asdcController.treatNotification(notifDataWithoutModuleInfo); - //LOGGER.info(MessageEnum.ASDC_INIT_ASDC_CLIENT_EXC, notifDataWithoutModuleInfo.getServiceUUID(), "ASDC", "closeASDC()"); - asdcController.closeASDC(); - }catch(Exception e){ - System.out.println("Error caught " + e.getMessage()); - LOGGER.error(MessageEnum.ASDC_GENERAL_EXCEPTION, - "Exception caught during ASDCRestInterface", "ASDC", "invokeASDCService", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in invokeASDCService", e); - } - System.out.println("ASDC Updates are complete"); - LOGGER.info(MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC, statusData.getDistributionID(), "ASDC", "ASDC Updates Are Complete"); - - return null; - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/healthcheck/HealthCheckHandler.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/healthcheck/HealthCheckHandler.java deleted file mode 100644 index 2162607bae..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/healthcheck/HealthCheckHandler.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.healthcheck; - - -import javax.ws.rs.GET; -import javax.ws.rs.HEAD; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; - -import org.apache.http.HttpStatus; -import org.openecomp.mso.HealthCheckUtils; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.properties.MsoJsonProperties; -import org.openecomp.mso.properties.MsoPropertiesFactory; -import org.openecomp.mso.utils.UUIDChecker; - - -@Path("/") - public class HealthCheckHandler { - - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.ASDC); - private static final String MSO_PROP_ASDC = "MSO_PROP_ASDC"; - private static MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory(); - - private static final String SUC_HTML = "Health CheckApplication ready"; - private static final String NOT_FOUND = "Application Not ReadyApplication Not Ready. Properties file missing or invalid or database Connection failed"; - - private static final Response OK_RESPONSE = Response.status (HttpStatus.SC_OK).entity (SUC_HTML).build (); - private static final Response NOK_RESPONSE = Response.status (HttpStatus.SC_SERVICE_UNAVAILABLE).entity (NOT_FOUND).build (); - - @HEAD - @GET - @Path("/healthcheck") - @Produces("text/html") - public Response healthcheck (@QueryParam("requestId") String requestId) { - long startTime = System.currentTimeMillis (); - MsoLogger.setServiceName ("Healthcheck"); - UUIDChecker.verifyOldUUID(requestId, msoLogger); - HealthCheckUtils healthCheck = new HealthCheckUtils (); - if (!healthCheck.siteStatusCheck(msoLogger)) { - return HealthCheckUtils.HEALTH_CHECK_NOK_RESPONSE; - } - - MsoJsonProperties props = loadMsoProperties (); - if (props == null) { - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.ServiceNotAvailable, "Application Not Ready"); - return HealthCheckUtils.NOT_STARTED_RESPONSE; - } - - if (!healthCheck.catalogDBCheck (msoLogger, startTime)) { - return HealthCheckUtils.NOT_STARTED_RESPONSE; - } - msoLogger.debug("healthcheck - Successful"); - return HealthCheckUtils.HEALTH_CHECK_RESPONSE; - } - - private MsoJsonProperties loadMsoProperties () { - MsoJsonProperties msoProperties; - try { - msoProperties = msoPropertiesFactory.getMsoJsonProperties(MSO_PROP_ASDC); - } catch (Exception e) { - msoLogger.error (MessageEnum.ASDC_PROPERTIES_NOT_FOUND, MSO_PROP_ASDC, "", "", MsoLogger.ErrorCode.DataError, "Exception - getMsoJsonProperties", e); - return null; - } - - if (msoProperties !=null && msoProperties.getJsonRootNode().elements().hasNext()) { - return msoProperties; - } else { - msoLogger.error (MessageEnum.ASDC_PROPERTIES_NOT_FOUND , MSO_PROP_ASDC, "", "", MsoLogger.ErrorCode.DataError, "ASDC properties not found"); - return null; - } - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/ASDCElementInfo.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/ASDCElementInfo.java deleted file mode 100644 index b6e130820a..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/ASDCElementInfo.java +++ /dev/null @@ -1,211 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.installer; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.IResourceInstance; -import org.openecomp.mso.asdc.client.ASDCConfiguration; - -/** - * A class representing a generic element whose information can be used for example to log artifacts, resource... data. - */ -public class ASDCElementInfo { - - /** - * A default, empty instance used in case a source element was not correctly provided. - */ - public static final ASDCElementInfo EMPTY_INSTANCE = new ASDCElementInfo(); - - /** - * Used to define the other possible ASDC Element types (usually in addition to existing artifact types, etc.).
      - *
      - * Possible types allowed:
      - *
        - *
      • {@link ASDCElementTypeEnum#VNF_RESOURCE}
      • - *
          - */ - public static enum ASDCElementTypeEnum { - /** - * The type VNF_RESOURCE. Represents a VNF_RESOURCE element. - */ - VNF_RESOURCE - }; - - /** - * The map of element information fields useful for logging. The complete contents of this list will be concatenated. - */ - private final Map elementInfoMap = new HashMap<>(); - - /** - * The type of this element. - */ - private final String type; - - private ASDCElementInfo () { - // Private parameterless constructor. Not visible, only used for EMPTY_INSTANCE. - this.type = ""; - } - - /** - * Artifact-type based constructor. Requires a valid artifact type. - * @param artifactType The artifact type - */ - private ASDCElementInfo (String artifactType) { - // We need the exact type name here... - this.type = artifactType; - } - - /** - * 'Other element type'-based constructor. Requires a valid element type. - * @param elementType An ASDCElementTypeEnum entry. This will usually contain enumerated types not in the existing - */ - private ASDCElementInfo (ASDCElementTypeEnum elementType) { - // We need the exact type name here... - this.type = elementType.name(); - } - - /** - * Add an information entry (name, UUID, etc.) from an artifact/resource/..., once a at time. - * - * @param key The key (name) of the information entry (Artifact UUID, Resource Name, etc.) - * @param value The value bound to the information entry. - */ - public final void addElementInfo(String key, String value) { - if ((key != null) && (value != null)) { - this.getElementInfoMap().put(key, value); - } - } - - /** - * Returns an aggregated, formatted list of the expected details about an ASDC element. - * (non-Javadoc) - * @return An aggregated list of element information entries, comma-separated. - * @see java.lang.Object#toString() - */ - @Override - public final String toString() { - StringBuilder sb = new StringBuilder(); - List aggregatedElements = new ArrayList<>(); - for (Entry entry : this.getElementInfoMap().entrySet()) { - aggregatedElements.add(entry.getKey() + ": " + entry.getValue()); - } - sb.append(aggregatedElements.size() > 0 ? aggregatedElements.get(0) : ""); - if (aggregatedElements.size() > 1) { - for (int i = 1; i < aggregatedElements.size(); ++i) { - sb.append (", "); - sb.append(aggregatedElements.get(i)); - } - } - return sb.toString(); - } - - /** - * The type that was defined at creation time. This is typically VNF_RESOURCE, VF_MODULE_METADATA, HEAT_ENV, etc. - * @return The type of this element information type. This will usually be either an ArtifactTypeEnum entry name or an ASDCElementTypeEnum entry name. - * @see ASDCElementInfo.ASDCElementTypeEnum - */ - public String getType() { - return type; - } - - /** - * Provides the map of all element information entries for this type. - * @return A map of all element information entries which will be used by the toString() method. - * @see ASDCElementInfo#toString() - */ - protected Map getElementInfoMap() { - return elementInfoMap; - } - - /** - * Create an ASDCElementInfo object from a VNF Resource.
          - *
          - * Used information:
          - *
            - *
          • Resource Instance Name
          • - *
          • Resource Instance UUID
          • - *
          - * - * @param vfResourceStructure The VfResourceStructure to use as source of information (see {@link VfResourceStructure}). - * @return an ASDCElementInfo using the information held in the VNF Resource. - */ - public static final ASDCElementInfo createElementFromVfResourceStructure (VfResourceStructure vfResourceStructure) { - if (vfResourceStructure == null) { - return EMPTY_INSTANCE; - } - ASDCElementInfo elementInfo = new ASDCElementInfo(ASDCElementTypeEnum.VNF_RESOURCE); - IResourceInstance resourceInstance = vfResourceStructure.getResourceInstance(); - elementInfo.addElementInfo("Resource Instance Name", resourceInstance.getResourceInstanceName()); - elementInfo.addElementInfo("Resource Instance Invariant UUID", resourceInstance.getResourceInvariantUUID()); - return elementInfo; - } - - /** - * Create an ASDCElementInfo object from a VF Module.
          - *
          - * Used information:
          - *
            - *
          • Module Model Name
          • - *
          • Module Model UUID
          • - *
          - * - * @param vfModuleStructure The VfModuleStructure to use as source of information (see {@link VfModuleStructure}). - * @return an ASDCElementInfo using the information held in the VF Module. - */ - public static final ASDCElementInfo createElementFromVfModuleStructure (VfModuleStructure vfModuleStructure) { - if (vfModuleStructure == null) { - return EMPTY_INSTANCE; - } - ASDCElementInfo elementInfo = new ASDCElementInfo(ASDCConfiguration.VF_MODULES_METADATA); - IVfModuleData moduleMetadata = vfModuleStructure.getVfModuleMetadata(); - elementInfo.addElementInfo("Module Model Name", moduleMetadata.getVfModuleModelName()); - elementInfo.addElementInfo("Module Model Invariant UUID", moduleMetadata.getVfModuleModelInvariantUUID()); - return elementInfo; - } - - /** - * Create an ASDCElementInfo object from an IArtfiactInfo instance.
          - *
          - * Used information:
          - *
            - *
          • IArtifactInfo Name
          • - *
          • IArtifactInfo UUID
          • - *
          - * - * @param artifactInfo The VfModuleStructure to use as source of information (see {@link IArtifactInfo}). - * @return an ASDCElementInfo using the information held in the IArtifactInfo instance. - */ - public static final ASDCElementInfo createElementFromVfArtifactInfo (IArtifactInfo artifactInfo) { - if (artifactInfo == null) { - return EMPTY_INSTANCE; - } - ASDCElementInfo elementInfo = new ASDCElementInfo(artifactInfo.getArtifactType()); - elementInfo.addElementInfo(elementInfo.getType() + " Name", artifactInfo.getArtifactName()); - elementInfo.addElementInfo(elementInfo.getType() + " UUID", artifactInfo.getArtifactUUID()); - return elementInfo; - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/BigDecimalVersion.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/BigDecimalVersion.java deleted file mode 100644 index c2faf1c0e8..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/BigDecimalVersion.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.installer; - - -import java.math.BigDecimal; - -public class BigDecimalVersion { - - /** - * This method truncates and convert the version String provided in the notification. - * - * @param version The version to check - * @return A BigDecimal value checked and truncated - */ - public static BigDecimal castAndCheckNotificationVersion(String version) { - // Truncate the version if bad type - String[] splitVersion = version.split("\\."); - StringBuilder newVersion = new StringBuilder(); - if (splitVersion.length > 1) { - newVersion.append(splitVersion[0]); - newVersion.append("."); - newVersion.append(splitVersion[1]); - } else { - return new BigDecimal(splitVersion[0]); - } - - for (int i=2;i; - public abstract java.util.List getArtifacts(); - - public abstract java.util.Map getProperties(); -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/IVfResourceInstaller.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/IVfResourceInstaller.java deleted file mode 100644 index 128239cf75..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/IVfResourceInstaller.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.installer; - - - -import org.openecomp.mso.asdc.client.exceptions.ArtifactInstallerException; - -public interface IVfResourceInstaller { - - boolean isResourceAlreadyDeployed (VfResourceStructure vfResourceStructure) throws ArtifactInstallerException; - - public void installTheResource (VfResourceStructure vfResourceStructure) throws ArtifactInstallerException; -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/ToscaResourceStructure.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/ToscaResourceStructure.java deleted file mode 100644 index 941787efe4..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/ToscaResourceStructure.java +++ /dev/null @@ -1,537 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.installer; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; - - -import java.util.List; - -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.INotificationData; -//import org.openecomp.generic.tosca.parser.model.Metadata; -//import org.onap.sdc.tosca.parser.factory.SdcCsarHelperFactory; -//import org.onap.sdc.tosca.parser.factory.SdcCsarHelperFactory; -///import org.openecomp.generic.tosca.parser.model.Metadata; -import org.onap.sdc.api.results.IDistributionClientDownloadResult; -import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; -import org.onap.sdc.tosca.parser.impl.SdcCsarHelperImpl; -import org.onap.sdc.tosca.parser.impl.SdcPropertyNames; - - -import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory; - - - -import org.onap.sdc.toscaparser.api.NodeTemplate; -import org.onap.sdc.toscaparser.api.elements.Metadata; -import org.openecomp.mso.asdc.client.exceptions.ASDCDownloadException; -import org.openecomp.mso.db.catalog.beans.AllottedResource; -import org.openecomp.mso.db.catalog.beans.AllottedResourceCustomization; -import org.openecomp.mso.db.catalog.beans.NetworkResource; -import org.openecomp.mso.db.catalog.beans.NetworkResourceCustomization; -import org.openecomp.mso.db.catalog.beans.Service; -import org.openecomp.mso.db.catalog.beans.ServiceToResourceCustomization; -import org.openecomp.mso.db.catalog.beans.TempNetworkHeatTemplateLookup; -import org.openecomp.mso.db.catalog.beans.ToscaCsar; -import org.openecomp.mso.db.catalog.beans.VfModule; -import org.openecomp.mso.db.catalog.beans.VfModuleCustomization; -import org.openecomp.mso.db.catalog.beans.VfModuleToHeatFiles; -import org.openecomp.mso.db.catalog.beans.VnfResCustomToVfModuleCustom; -import org.openecomp.mso.db.catalog.beans.VnfResource; -import org.openecomp.mso.db.catalog.beans.VnfResourceCustomization; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; - -public class ToscaResourceStructure { - - Metadata serviceMetadata; - private Service catalogService; - ISdcCsarHelper sdcCsarHelper; - List allottedList; - List networkTypes; - List vfTypes; - String heatTemplateUUID; - String volHeatTemplateUUID; - String volHeatEnvTemplateUUID; - String envHeatTemplateUUID; - String heatFilesUUID; - String workloadPerformance; - boolean isVnfAlreadyInstalled = false; - String serviceVersion; - private boolean isDeployedSuccessfully=false; - - - private NetworkResourceCustomization catalogNetworkResourceCustomization; - - private NetworkResource catalogNetworkResource; - - private AllottedResourceCustomization catalogResourceCustomization; - - private VfModule vfModule; - - private VfModuleCustomization vfModuleCustomization; - - private VnfResource vnfResource; - - private VnfResourceCustomization vnfResourceCustomization; - - private ServiceToResourceCustomization serviceToResourceCustomization; - - private AllottedResource allottedResource; - - private AllottedResourceCustomization allottedResourceCustomization; - - private VnfResCustomToVfModuleCustom vnfResCustomToVfModuleCustom; - - private TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup; - - private VfModuleToHeatFiles vfModuleToHeatFiles; - - private IArtifactInfo toscaArtifact; - - private ToscaCsar toscaCsar; - - private ServiceToResourceCustomization vfServiceToResourceCustomization; - - private ServiceToResourceCustomization allottedServiceToResourceCustomization; - - private ServiceToResourceCustomization vlServiceToResourceCustomization; - - protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC); - - - public ToscaResourceStructure(){ - } - - public void updateResourceStructure(IArtifactInfo artifact) throws ASDCDownloadException { - - - try { - - SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();//Autoclosable - - LOGGER.debug("MSO config path is: " + System.getProperty("mso.config.path")); - - File spoolFile = new File(System.getProperty("mso.config.path") + "ASDC/" + artifact.getArtifactName()); - - LOGGER.debug("ASDC File path is: " + spoolFile.getAbsolutePath()); - LOGGER.info(MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF, "***PATH", "ASDC", spoolFile.getAbsolutePath()); - - - sdcCsarHelper = factory.getSdcCsarHelper(spoolFile.getAbsolutePath()); - - }catch(Exception e){ - System.out.println("System out " + e.getMessage()); - LOGGER.error(MessageEnum.ASDC_GENERAL_EXCEPTION_ARG, - "Exception caught during parser *****LOOK********* " + artifact.getArtifactName(), "ASDC", "processResourceNotification", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in processResourceNotification", e); - - throw new ASDCDownloadException ("Exception caught when passing the csar file to the parser ", e); - } - - serviceMetadata = sdcCsarHelper.getServiceMetadata(); - - } - - public String getHeatTemplateUUID() { - return heatTemplateUUID; - } - - public void setHeatTemplateUUID(String heatTemplateUUID) { - this.heatTemplateUUID = heatTemplateUUID; - } - - public List getAllottedList() { - return allottedList; - } - - public void setAllottedList(List allottedList) { - this.allottedList = allottedList; - } - - public ISdcCsarHelper getSdcCsarHelper() { - return sdcCsarHelper; - } - - public void setSdcCsarHelper(ISdcCsarHelper sdcCsarHelper) { - this.sdcCsarHelper = sdcCsarHelper; - } - - public Metadata getServiceMetadata() { - return serviceMetadata; - } - - public Service getCatalogService() { - return catalogService; - } - - public void setServiceMetadata(Metadata serviceMetadata) { - this.serviceMetadata = serviceMetadata; - } - - public void setCatalogService(Service catalogService) { - this.catalogService = catalogService; - } - - public List getNetworkTypes() { - return networkTypes; - } - - public void setNetworkTypes(List networkTypes) { - this.networkTypes = networkTypes; - } - - public List getVfTypes() { - return vfTypes; - } - - public void setVfTypes(List vfTypes) { - this.vfTypes = vfTypes; - } - - public AllottedResourceCustomization getCatalogResourceCustomization() { - return catalogResourceCustomization; - } - - public void setCatalogResourceCustomization( - AllottedResourceCustomization catalogResourceCustomization) { - this.catalogResourceCustomization = catalogResourceCustomization; - } - - // Network Only - public NetworkResourceCustomization getCatalogNetworkResourceCustomization() { - return catalogNetworkResourceCustomization; - } - // Network Only - public void setCatalogNetworkResourceCustomization(NetworkResourceCustomization catalogNetworkResourceCustomization) { - this.catalogNetworkResourceCustomization = catalogNetworkResourceCustomization; - } - - public NetworkResource getCatalogNetworkResource() { - return catalogNetworkResource; - } - - public void setCatalogNetworkResource(NetworkResource catalogNetworkResource) { - this.catalogNetworkResource = catalogNetworkResource; - } - - public VfModule getCatalogVfModule() { - return vfModule; - } - - public void setCatalogVfModule(VfModule vfModule) { - this.vfModule = vfModule; - } - - public VnfResource getCatalogVnfResource() { - return vnfResource; - } - - public void setCatalogVnfResource(VnfResource vnfResource) { - this.vnfResource = vnfResource; - } - - public VnfResourceCustomization getCatalogVnfResourceCustomization() { - return vnfResourceCustomization; - } - - public void setCatalogVnfResourceCustomization( - VnfResourceCustomization vnfResourceCustomization) { - this.vnfResourceCustomization = vnfResourceCustomization; - } - - public VfModuleCustomization getCatalogVfModuleCustomization() { - return vfModuleCustomization; - } - - public void setCatalogVfModuleCustomization(VfModuleCustomization vfModuleCustomization) { - this.vfModuleCustomization = vfModuleCustomization; - } - - public ServiceToResourceCustomization getServiceToResourceCustomization() { - return serviceToResourceCustomization; - } - - public void setServiceToResourceCustomization( - ServiceToResourceCustomization serviceToResourceCustomization) { - this.serviceToResourceCustomization = serviceToResourceCustomization; - } - - public AllottedResource getAllottedResource() { - return allottedResource; - } - - public void setAllottedResource(AllottedResource allottedResource) { - this.allottedResource = allottedResource; - } - - public AllottedResourceCustomization getCatalogAllottedResourceCustomization() { - return allottedResourceCustomization; - } - - public void setCatalogAllottedResourceCustomization( - AllottedResourceCustomization allottedResourceCustomization) { - this.allottedResourceCustomization = allottedResourceCustomization; - } - - public VnfResCustomToVfModuleCustom getCatalogVnfResCustomToVfModuleCustom() { - return vnfResCustomToVfModuleCustom; - } - - public void setCatalogVnfResCustomToVfModuleCustom( - VnfResCustomToVfModuleCustom vnfResCustomToVfModuleCustom) { - this.vnfResCustomToVfModuleCustom = vnfResCustomToVfModuleCustom; - } - - public TempNetworkHeatTemplateLookup getCatalogTempNetworkHeatTemplateLookup() { - return tempNetworkHeatTemplateLookup; - } - - public void setCatalogTempNetworkHeatTemplateLookup( - TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup) { - this.tempNetworkHeatTemplateLookup = tempNetworkHeatTemplateLookup; - } - - public String getHeatFilesUUID() { - return heatFilesUUID; - } - - public void setHeatFilesUUID(String heatFilesUUID) { - this.heatFilesUUID = heatFilesUUID; - } - - public VfModuleToHeatFiles getCatalogVfModuleToHeatFiles() { - return vfModuleToHeatFiles; - } - - public void setCatalogVfModuleToHeatFiles(VfModuleToHeatFiles vfModuleToHeatFiles) { - this.vfModuleToHeatFiles = vfModuleToHeatFiles; - } - - public IArtifactInfo getToscaArtifact() { - return toscaArtifact; - } - - public void setToscaArtifact(IArtifactInfo toscaArtifact) { - this.toscaArtifact = toscaArtifact; - } - - public ToscaCsar getCatalogToscaCsar() { - return toscaCsar; - } - - public void setCatalogToscaCsar(ToscaCsar toscaCsar) { - this.toscaCsar = toscaCsar; - } - - public boolean isVnfAlreadyInstalled() { - return isVnfAlreadyInstalled; - } - - public void setVnfAlreadyInstalled(boolean isVnfAlreadyInstalled) { - this.isVnfAlreadyInstalled = isVnfAlreadyInstalled; - } - - public ServiceToResourceCustomization getCatalogVfServiceToResourceCustomization() { - return vfServiceToResourceCustomization; - } - - public void setCatalogVfServiceToResourceCustomization( - ServiceToResourceCustomization vfServiceToResourceCustomization) { - this.vfServiceToResourceCustomization = vfServiceToResourceCustomization; - } - - public ServiceToResourceCustomization getCatalogAllottedServiceToResourceCustomization() { - return allottedServiceToResourceCustomization; - } - - public void setCatalogAllottedServiceToResourceCustomization( - ServiceToResourceCustomization allottedServiceToResourceCustomization) { - this.allottedServiceToResourceCustomization = allottedServiceToResourceCustomization; - } - - public ServiceToResourceCustomization getCatalogVlServiceToResourceCustomization() { - return vlServiceToResourceCustomization; - } - - public void setCatalogVlServiceToResourceCustomization( - ServiceToResourceCustomization vlServiceToResourceCustomization) { - this.vlServiceToResourceCustomization = vlServiceToResourceCustomization; - } - - public String getVolHeatTemplateUUID() { - return volHeatTemplateUUID; - } - - public void setVolHeatTemplateUUID(String volHeatTemplateUUID) { - this.volHeatTemplateUUID = volHeatTemplateUUID; - } - - public String getEnvHeatTemplateUUID() { - return envHeatTemplateUUID; - } - - public void setEnvHeatTemplateUUID(String envHeatTemplateUUID) { - this.envHeatTemplateUUID = envHeatTemplateUUID; - } - - public String getVolHeatEnvTemplateUUID() { - return volHeatEnvTemplateUUID; - } - - public void setVolHeatEnvTemplateUUID(String volHeatEnvTemplateUUID) { - this.volHeatEnvTemplateUUID = volHeatEnvTemplateUUID; - } - - public String getServiceVersion() { - return serviceVersion; - } - - public void setServiceVersion(String serviceVersion) { - this.serviceVersion = serviceVersion; - } - - public String getWorkloadPerformance() { - return workloadPerformance; - } - - public void setWorkloadPerformance(String workloadPerformance) { - this.workloadPerformance = workloadPerformance; - } - - public VfModule getVfModule() { - return vfModule; - } - - public void setVfModule(VfModule vfModule) { - this.vfModule = vfModule; - } - - public VfModuleCustomization getVfModuleCustomization() { - return vfModuleCustomization; - } - - public void setVfModuleCustomization(VfModuleCustomization vfModuleCustomization) { - this.vfModuleCustomization = vfModuleCustomization; - } - - public VnfResource getVnfResource() { - return vnfResource; - } - - public void setVnfResource(VnfResource vnfResource) { - this.vnfResource = vnfResource; - } - - public VnfResourceCustomization getVnfResourceCustomization() { - return vnfResourceCustomization; - } - - public void setVnfResourceCustomization( - VnfResourceCustomization vnfResourceCustomization) { - this.vnfResourceCustomization = vnfResourceCustomization; - } - - public AllottedResourceCustomization getAllottedResourceCustomization() { - return allottedResourceCustomization; - } - - public void setAllottedResourceCustomization( - AllottedResourceCustomization allottedResourceCustomization) { - this.allottedResourceCustomization = allottedResourceCustomization; - } - - public VnfResCustomToVfModuleCustom getVnfResCustomToVfModuleCustom() { - return vnfResCustomToVfModuleCustom; - } - - public void setVnfResCustomToVfModuleCustom( - VnfResCustomToVfModuleCustom vnfResCustomToVfModuleCustom) { - this.vnfResCustomToVfModuleCustom = vnfResCustomToVfModuleCustom; - } - - public TempNetworkHeatTemplateLookup getTempNetworkHeatTemplateLookup() { - return tempNetworkHeatTemplateLookup; - } - - public void setTempNetworkHeatTemplateLookup( - TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup) { - this.tempNetworkHeatTemplateLookup = tempNetworkHeatTemplateLookup; - } - - public VfModuleToHeatFiles getVfModuleToHeatFiles() { - return vfModuleToHeatFiles; - } - - public void setVfModuleToHeatFiles(VfModuleToHeatFiles vfModuleToHeatFiles) { - this.vfModuleToHeatFiles = vfModuleToHeatFiles; - } - - public ToscaCsar getToscaCsar() { - return toscaCsar; - } - - public void setToscaCsar(ToscaCsar toscaCsar) { - this.toscaCsar = toscaCsar; - } - - public ServiceToResourceCustomization getVfServiceToResourceCustomization() { - return vfServiceToResourceCustomization; - } - - public void setVfServiceToResourceCustomization( - ServiceToResourceCustomization vfServiceToResourceCustomization) { - this.vfServiceToResourceCustomization = vfServiceToResourceCustomization; - } - - public ServiceToResourceCustomization getAllottedServiceToResourceCustomization() { - return allottedServiceToResourceCustomization; - } - - public void setAllottedServiceToResourceCustomization( - ServiceToResourceCustomization allottedServiceToResourceCustomization) { - this.allottedServiceToResourceCustomization = allottedServiceToResourceCustomization; - } - - public ServiceToResourceCustomization getVlServiceToResourceCustomization() { - return vlServiceToResourceCustomization; - } - - public void setVlServiceToResourceCustomization( - ServiceToResourceCustomization vlServiceToResourceCustomization) { - this.vlServiceToResourceCustomization = vlServiceToResourceCustomization; - } - - public static MsoLogger getLogger() { - return LOGGER; - } - - public boolean isDeployedSuccessfully() { - return isDeployedSuccessfully; - } - - public void setSuccessfulDeployment() { - isDeployedSuccessfully = true; - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleArtifact.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleArtifact.java deleted file mode 100644 index c1f836904d..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleArtifact.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.installer; - - -import java.io.UnsupportedEncodingException; - -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.results.IDistributionClientDownloadResult; - -/** - * The structure that contains the artifactInfo and its associated DownloadedResult. - * - */ -public final class VfModuleArtifact { - private final IArtifactInfo artifactInfo; - private int deployedInDb=0; - private final String result; - - private Object catalogObject; - - public VfModuleArtifact(IArtifactInfo artifactinfo,IDistributionClientDownloadResult clientResult) throws UnsupportedEncodingException { - artifactInfo=artifactinfo; - result = new String(clientResult.getArtifactPayload(), "UTF-8"); - - } - - public Object getCatalogObject() { - return catalogObject; - } - - public void setCatalogObject(Object catalogObject) { - this.catalogObject = catalogObject; - } - - public IArtifactInfo getArtifactInfo() { - return artifactInfo; - } - - public String getResult() { - return result; - } - - public int getDeployedInDb() { - return deployedInDb; - } - - public void incrementDeployedInDB() { - ++deployedInDb; - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleMetaData.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleMetaData.java deleted file mode 100644 index 8ee5302003..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleMetaData.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.installer; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class VfModuleMetaData implements IVfModuleData { - - @JsonProperty("artifacts") - private List artifacts; - - @JsonProperty("properties") - //private List> properties = new ArrayList<>(); - private Map properties = new HashMap<>(); - - @JsonIgnore - private Map attributesMap = new HashMap<>(); - - @Override - public List getArtifacts() { - return artifacts; - } - - public Map getProperties() { - return properties; - } - - @Override - public String getVfModuleModelDescription() { - return (String)attributesMap.get("vfModuleModelDescription"); - } - - @Override - public String getVfModuleModelInvariantUUID() { - return (String)attributesMap.get("vfModuleModelInvariantUUID"); - } - - public String getVfModuleModelCustomizationUUID() { - return (String)attributesMap.get("vfModuleModelCustomizationUUID"); - } - - @Override - public String getVfModuleModelName() { - return (String)attributesMap.get("vfModuleModelName"); - } - - @Override - public String getVfModuleModelUUID() { - return (String)attributesMap.get("vfModuleModelUUID"); - } - - @Override - public String getVfModuleModelVersion() { - return (String)attributesMap.get("vfModuleModelVersion"); - } - - @Override - public boolean isBase() { - return (boolean)attributesMap.get("isBase"); - } - - - - @SuppressWarnings("unused") - @JsonAnySetter - public final void setAttribute(String attrName, Object attrValue) { - if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) { - this.attributesMap.put(attrName,attrValue); - } - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleStructure.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleStructure.java deleted file mode 100644 index 2986a80b1f..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleStructure.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.installer; - - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import org.onap.sdc.api.notification.IVfModuleMetadata; -import org.openecomp.mso.asdc.client.ASDCConfiguration; -import org.openecomp.mso.asdc.client.exceptions.ArtifactInstallerException; -import org.openecomp.mso.db.catalog.beans.VfModule; - -public final class VfModuleStructure { - - private final IVfModuleData vfModuleMetadata; - - private final VfResourceStructure parentVfResource; - - private VfModule catalogVfModule; - /** - * The list of artifact existing in this resource hashed by artifactType. - */ - private final Map> artifactsMap; - - public VfModuleStructure(VfResourceStructure vfParentResource,IVfModuleData vfmoduleMetadata) throws ArtifactInstallerException { - - vfModuleMetadata = vfmoduleMetadata; - parentVfResource = vfParentResource; - - artifactsMap = new HashMap<>(); - - for (String artifactUUID:this.vfModuleMetadata.getArtifacts()) { - if (vfParentResource.getArtifactsMapByUUID().containsKey(artifactUUID)) { - this.addToStructure(vfParentResource.getArtifactsMapByUUID().get(artifactUUID)); - } else { - throw new ArtifactInstallerException("Artifact (UUID:"+artifactUUID+ ") referenced in the VFModule UUID list has not been downloaded, cancelling the Resource deployment"); - } - } - } - - private void addToStructure(VfModuleArtifact vfModuleArtifact) { - - if (artifactsMap.containsKey(vfModuleArtifact.getArtifactInfo().getArtifactType())) { - artifactsMap.get(vfModuleArtifact.getArtifactInfo().getArtifactType()).add(vfModuleArtifact); - - } else { - List nestedList = new LinkedList<>(); - nestedList.add(vfModuleArtifact); - - artifactsMap.put(vfModuleArtifact.getArtifactInfo().getArtifactType(), nestedList); - } - } - - public List getOrderedArtifactList() { - - List artifactsList = new LinkedList<>(); - - artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT)); - artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_ENV)); - artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_VOL)); - - artifactsList.addAll((artifactsMap.get(ASDCConfiguration.HEAT_NESTED))); - - artifactsList.addAll((artifactsMap.get(ASDCConfiguration.HEAT_ARTIFACT))); - - artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_VOL)); - - return null; - } - - public IVfModuleData getVfModuleMetadata() { - return vfModuleMetadata; - } - - public VfResourceStructure getParentVfResource() { - return parentVfResource; - } - - public Map> getArtifactsMap() { - return artifactsMap; - } - - - public VfModule getCatalogVfModule() { - return catalogVfModule; - } - - public void setCatalogVfModule(VfModule catalogVfModule) { - this.catalogVfModule = catalogVfModule; - } - - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfResourceStructure.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfResourceStructure.java deleted file mode 100644 index 10e936060d..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfResourceStructure.java +++ /dev/null @@ -1,246 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.installer; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.openecomp.mso.asdc.client.ASDCConfiguration; -import org.openecomp.mso.asdc.client.exceptions.ArtifactInstallerException; -import org.openecomp.mso.db.catalog.beans.AllottedResourceCustomization; -import org.openecomp.mso.db.catalog.beans.NetworkResourceCustomization; -import org.openecomp.mso.db.catalog.beans.Service; -import org.openecomp.mso.db.catalog.beans.ServiceToAllottedResources; -import org.openecomp.mso.db.catalog.beans.ServiceToNetworks; -import org.openecomp.mso.db.catalog.beans.VnfResource; -import org.openecomp.mso.logger.MsoLogger; -import org.onap.sdc.api.IDistributionClient; -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.INotificationData; -import org.onap.sdc.api.notification.IResourceInstance; -import org.onap.sdc.api.results.IDistributionClientDownloadResult; -import org.openecomp.mso.logger.MessageEnum; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -/** - * This structure exists to avoid having issues if the order of the vfResource/vfmodule artifact is not good (tree structure). - * - */ -public final class VfResourceStructure { - - protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC); - - private boolean isDeployedSuccessfully=false; - /** - * The Raw notification data. - */ - private final INotificationData notification; - - /** - * The resource we will try to deploy. - */ - private final IResourceInstance resourceInstance; - - /** - * The list of VfModules defined for this resource. - */ - private final List vfModulesStructureList; - - /** - * The list of VfModulesMetadata defined for this resource. - */ - private List vfModulesMetadataList; - - private VnfResource catalogVnfResource; - - private NetworkResourceCustomization catalogNetworkResourceCustomization; - - private ServiceToNetworks catalogServiceToNetworks; - - private ServiceToAllottedResources catalogServiceToAllottedResources; - - private AllottedResourceCustomization catalogResourceCustomization; - - private Service catalogService; - - private List vfArtifactUUIDList; - - /** - * The list of artifacts existing in this resource hashed by UUID. - */ - private final Map artifactsMapByUUID; - - - public VfResourceStructure(INotificationData notificationdata, IResourceInstance resourceinstance) { - notification=notificationdata; - resourceInstance=resourceinstance; - - - vfModulesStructureList = new LinkedList<>(); - artifactsMapByUUID = new HashMap<>(); - } - - //@Override - public void addArtifactToStructure(IDistributionClient distributionClient,IArtifactInfo artifactinfo,IDistributionClientDownloadResult clientResult) throws UnsupportedEncodingException { - VfModuleArtifact vfModuleArtifact = new VfModuleArtifact(artifactinfo,clientResult); - - switch(artifactinfo.getArtifactType()) { - case ASDCConfiguration.HEAT: - case ASDCConfiguration.HEAT_ENV: - case ASDCConfiguration.HEAT_VOL: - case ASDCConfiguration.HEAT_NESTED: // For 1607 only 1 level tree is supported - case ASDCConfiguration.HEAT_ARTIFACT: - case ASDCConfiguration.HEAT_NET: - case ASDCConfiguration.OTHER: - artifactsMapByUUID.put(artifactinfo.getArtifactUUID(), vfModuleArtifact); - break; - - case ASDCConfiguration.VF_MODULES_METADATA: - vfModulesMetadataList = this.decodeVfModuleArtifact(clientResult.getArtifactPayload()); - - for(IVfModuleData moduleData : vfModulesMetadataList){ - - } - - //vfArtifactUUIDList.add(artifactinfo.getArtifactUUID()); - //vfModulesMetadataList = distributionClient.decodeVfModuleArtifact(clientResult.getArtifactPayload()); - break; - - default: - break; - - } - } - - public void createVfModuleStructures() throws ArtifactInstallerException { - - //for vender tosca VNF there is no VFModule in VF - if (vfModulesMetadataList == null) { - LOGGER.info(MessageEnum.ASDC_GENERAL_INFO,"There is no VF mudules in the VF.", "ASDC", "createVfModuleStructures"); - return; - } - for (IVfModuleData vfModuleMeta:vfModulesMetadataList) { - vfModulesStructureList.add(new VfModuleStructure(this,vfModuleMeta)); - } - } - - public INotificationData getNotification() { - return notification; - } - - public IResourceInstance getResourceInstance() { - return resourceInstance; - } - - public List getVfModuleStructure() { - return vfModulesStructureList; - } - - public boolean isDeployedSuccessfully() { - return isDeployedSuccessfully; - } - - public void setSuccessfulDeployment() { - isDeployedSuccessfully = true; - } - - public Map getArtifactsMapByUUID() { - return artifactsMapByUUID; - } - - public List getVfModulesStructureList() { - return vfModulesStructureList; - } - - public VnfResource getCatalogVnfResource() { - return catalogVnfResource; - } - - public void setCatalogVnfResource(VnfResource catalogVnfResource) { - this.catalogVnfResource = catalogVnfResource; - } - - // Network Only - public NetworkResourceCustomization getCatalogNetworkResourceCustomization() { - return catalogNetworkResourceCustomization; - } - // Network Only - public void setCatalogNetworkResourceCustomization(NetworkResourceCustomization catalogNetworkResourceCustomization) { - this.catalogNetworkResourceCustomization = catalogNetworkResourceCustomization; - } - // Network Only - public ServiceToNetworks getCatalogServiceToNetworks() { - return catalogServiceToNetworks; - } - // Network Only - public void setCatalogServiceToNetworks( - ServiceToNetworks catalogServiceToNetworks) { - this.catalogServiceToNetworks = catalogServiceToNetworks; - } - - public ServiceToAllottedResources getCatalogServiceToAllottedResources() { - return catalogServiceToAllottedResources; - } - - public void setCatalogServiceToAllottedResources( - ServiceToAllottedResources catalogServiceToAllottedResources) { - this.catalogServiceToAllottedResources = catalogServiceToAllottedResources; - } - - public AllottedResourceCustomization getCatalogResourceCustomization() { - return catalogResourceCustomization; - } - - public void setCatalogResourceCustomization( - AllottedResourceCustomization catalogResourceCustomization) { - this.catalogResourceCustomization = catalogResourceCustomization; - } - - public Service getCatalogService() { - return catalogService; - } - - public void setCatalogService(Service catalogService) { - this.catalogService = catalogService; - } - - public List decodeVfModuleArtifact(byte[] arg0) { - try { - List listVFModuleMetaData = new ObjectMapper().readValue(arg0, new TypeReference>(){}); - return listVFModuleMetaData; - - } catch (JsonParseException e) { - LOGGER.debug("JsonParseException : ",e); - } catch (JsonMappingException e) { - LOGGER.debug("JsonMappingException : ",e); - } catch (IOException e) { - LOGGER.debug("IOException : ",e); - } - return null; - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/heat/ToscaResourceInstaller.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/heat/ToscaResourceInstaller.java deleted file mode 100644 index 9d986d9df7..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/heat/ToscaResourceInstaller.java +++ /dev/null @@ -1,1272 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.installer.heat; - -import java.sql.SQLIntegrityConstraintViolationException; -import java.sql.Timestamp; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; -import java.util.regex.Matcher; -import java.util.Comparator; - -import org.hibernate.exception.ConstraintViolationException; -import org.hibernate.exception.LockAcquisitionException; -import org.onap.sdc.api.consumer.IComponentDoneStatusMessage; -//import org.openecomp.generic.tosca.parser.model.Metadata; -//import org.openecomp.generic.tosca.parser.model.NodeTemplate; -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.IStatusData; -import org.onap.sdc.api.notification.IVfModuleMetadata; -import org.onap.sdc.api.results.IDistributionClientResult; -import org.onap.sdc.tosca.parser.impl.SdcPropertyNames; -import org.onap.sdc.toscaparser.api.Group; -import org.onap.sdc.toscaparser.api.NodeTemplate; -import org.onap.sdc.toscaparser.api.Property; -import org.onap.sdc.toscaparser.api.elements.Metadata; -import org.onap.sdc.toscaparser.api.parameters.Input; -import org.onap.sdc.utils.DistributionStatusEnum; -import org.openecomp.mso.asdc.client.ASDCConfiguration; -import org.openecomp.mso.asdc.client.exceptions.ArtifactInstallerException; -import org.openecomp.mso.asdc.installer.ASDCElementInfo; -import org.openecomp.mso.asdc.installer.BigDecimalVersion; -import org.openecomp.mso.asdc.installer.IVfModuleData; -import org.openecomp.mso.asdc.installer.IVfResourceInstaller; -import org.openecomp.mso.asdc.installer.ToscaResourceStructure; -import org.openecomp.mso.asdc.installer.VfModuleArtifact; -import org.openecomp.mso.asdc.installer.VfModuleStructure; -import org.openecomp.mso.asdc.installer.VfResourceStructure; -import org.openecomp.mso.asdc.tenantIsolation.DistributionStatus; -import org.openecomp.mso.asdc.tenantIsolation.WatchdogDistribution; -import org.openecomp.mso.asdc.util.ASDCNotificationLogging; -import org.openecomp.mso.asdc.util.YamlEditor; -import org.openecomp.mso.db.catalog.CatalogDatabase; -import org.openecomp.mso.db.catalog.beans.AllottedResource; -import org.openecomp.mso.db.catalog.beans.HeatEnvironment; -import org.openecomp.mso.db.catalog.beans.HeatFiles; -import org.openecomp.mso.db.catalog.beans.HeatTemplate; -import org.openecomp.mso.db.catalog.beans.HeatTemplateParam; -import org.openecomp.mso.db.catalog.beans.NetworkResource; -import org.openecomp.mso.db.catalog.beans.NetworkResourceCustomization; -import org.openecomp.mso.db.catalog.beans.AllottedResourceCustomization; -import org.openecomp.mso.db.catalog.beans.Service; -import org.openecomp.mso.db.catalog.beans.ServiceToAllottedResources; -import org.openecomp.mso.db.catalog.beans.ServiceToNetworks; -import org.openecomp.mso.db.catalog.beans.ServiceToResourceCustomization; -import org.openecomp.mso.db.catalog.beans.TempNetworkHeatTemplateLookup; -import org.openecomp.mso.db.catalog.beans.ToscaCsar; -import org.openecomp.mso.db.catalog.beans.VfModule; -import org.openecomp.mso.db.catalog.beans.VfModuleCustomization; -import org.openecomp.mso.db.catalog.beans.VfModuleToHeatFiles; -import org.openecomp.mso.db.catalog.beans.VnfResCustomToVfModuleCustom; -import org.openecomp.mso.db.catalog.beans.VnfResource; -import org.openecomp.mso.db.catalog.beans.VnfResourceCustomization; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.requestsdb.WatchdogComponentDistributionStatusDb; -import org.openecomp.mso.requestsdb.WatchdogDistributionStatusDb; -import org.openecomp.mso.requestsdb.WatchdogServiceModVerIdLookupDb; - -public class ToscaResourceInstaller {// implements IVfResourceInstaller { - - private MsoLogger logger; - - private static final Pattern lastDigit = Pattern.compile("(\\d+)$"); - - public ToscaResourceInstaller() { - logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.ASDC); - } - - //@Override - public boolean isResourceAlreadyDeployed(VfResourceStructure vfResourceStruct) - throws ArtifactInstallerException { - boolean status = false; - VfResourceStructure vfResourceStructure = (VfResourceStructure)vfResourceStruct; - try { - status = vfResourceStructure.isDeployedSuccessfully(); - } catch (RuntimeException e) { - status = false; - } - - try { - - String serviceUUID = vfResourceStruct.getNotification().getServiceUUID(); - - if (status) { - logger.info(MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED_DETAIL, - vfResourceStructure.getResourceInstance().getResourceInstanceName(), - vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(), - vfResourceStructure.getNotification().getServiceName(), - BigDecimalVersion.castAndCheckNotificationVersionToString( - vfResourceStructure.getNotification().getServiceVersion()), - vfResourceStructure.getNotification().getServiceUUID(), - vfResourceStructure.getResourceInstance().getResourceName(),"", ""); - } else { - logger.info(MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL, - vfResourceStructure.getResourceInstance().getResourceInstanceName(), - vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(), - vfResourceStructure.getNotification().getServiceName(), - BigDecimalVersion.castAndCheckNotificationVersionToString( - vfResourceStructure.getNotification().getServiceVersion()), - vfResourceStructure.getNotification().getServiceUUID(), - vfResourceStructure.getResourceInstance().getResourceName(),"", ""); - } - - return status; - - } catch (Exception e) { - logger.error(MessageEnum.ASDC_ARTIFACT_CHECK_EXC, "", "", MsoLogger.ErrorCode.SchemaError, "Exception - isResourceAlreadyDeployed"); - throw new ArtifactInstallerException("Exception caught during checking existence of the VNF Resource.", e); - } - } - - public void installTheComponentStatus(IStatusData iStatus) throws ArtifactInstallerException { - - logger.debug("Entering installTheComponentStatus for distributionId " + iStatus.getDistributionID() + " and ComponentName " + iStatus.getComponentName()); - - WatchdogComponentDistributionStatusDb wdComponentDistributionStatus = WatchdogComponentDistributionStatusDb.getInstance(); - - WatchdogDistributionStatusDb wdDistributionStatus = WatchdogDistributionStatusDb.getInstance(); - - - try{ - //Check to make sure the distributionId exists in the Distribution Status table first. If not then we'll need to add it - String distributionId = wdDistributionStatus.getWatchdogDistributionId(iStatus.getDistributionID()); - - if(distributionId == null){ - // Insert the record into the parent table first - WatchDogDistributionStatus - wdDistributionStatus.insertWatchdogDistributionId(iStatus.getDistributionID()); - } - - wdComponentDistributionStatus.insertWatchdogComponentDistributionStatus(iStatus.getDistributionID(), iStatus.getComponentName(), iStatus.getStatus().toString()); - - - WatchdogDistribution wd = new WatchdogDistribution(); - - String distributionStatus = wd.getOverallDistributionStatus(iStatus.getDistributionID()); - - logger.debug("Distribution status in installTheComponentStatus is : " + distributionStatus); - - }catch (Exception e){ - logger.debug("Exception caught in installTheComponentStatus " + e.getMessage()); - throw new ArtifactInstallerException("Exception caught in installTheComponentStatus " + e.getMessage()); - } - - } - - - public void installTheResource(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStruct) throws ArtifactInstallerException { - - logger.debug("installTheResource is called"); - - VfResourceStructure vfResourceStructure = (VfResourceStructure)vfResourceStruct; - - for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { - - switch (vfModuleArtifact.getArtifactInfo().getArtifactType()) { - case ASDCConfiguration.HEAT: - case ASDCConfiguration.HEAT_VOL: - case ASDCConfiguration.HEAT_NESTED: - ToscaResourceInstaller.createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, vfModuleArtifact); - break; - case ASDCConfiguration.HEAT_ENV: - ToscaResourceInstaller.createHeatEnvFromArtifact(vfResourceStructure, vfModuleArtifact); - break; - case ASDCConfiguration.HEAT_ARTIFACT: - ToscaResourceInstaller.createHeatFileFromArtifact(vfResourceStructure, vfModuleArtifact, toscaResourceStruct); - break; - case ASDCConfiguration.HEAT_NET: - case ASDCConfiguration.OTHER: - logger.warn(MessageEnum.ASDC_ARTIFACT_TYPE_NOT_SUPPORT, vfModuleArtifact.getArtifactInfo().getArtifactType()+"(Artifact Name:"+vfModuleArtifact.getArtifactInfo().getArtifactName()+")", "", "", MsoLogger.ErrorCode.DataError, "Artifact type not supported"); - break; - default: - break; - - } - } - // Those objects could be reused by different VfModule - - - - // PCLO: in case of deployment failure, use a string that will represent the type of artifact that failed... - List artifactListForLogging = new ArrayList<>(); - - CatalogDatabase catalogDB = CatalogDatabase.getInstance(); - - WatchdogServiceModVerIdLookupDb wdLookupDB = WatchdogServiceModVerIdLookupDb.getInstance(); - - WatchdogDistributionStatusDb wdDistributionStatus = WatchdogDistributionStatusDb.getInstance(); - - WatchdogComponentDistributionStatusDb wdComponentDistributionStatus = WatchdogComponentDistributionStatusDb.getInstance(); - // 2. Create the VFModules/VNFResource objects by linking them to the - // objects created before and store them in Resource/module structure - // Opening a DB transaction, starting from here - try { - - - createToscaCsar(toscaResourceStruct); - - catalogDB.saveToscaCsar(toscaResourceStruct.getCatalogToscaCsar()); - - ToscaResourceInstaller.createService(toscaResourceStruct, vfResourceStruct); - - catalogDB.saveService(toscaResourceStruct.getCatalogService()); - - wdLookupDB.insertWatchdogServiceModVerIdLookup(vfResourceStructure.getNotification().getDistributionID(), vfResourceStructure.getNotification().getServiceUUID()); - - wdDistributionStatus.insertWatchdogDistributionId(vfResourceStructure.getNotification().getDistributionID()); - - - /* VNF POPULATION - * ************************************************************************************************************ - */ - - // Ingest (VNF) Data - 1707 - List vfNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceVfList(); - int outerLoop = 0; - logger.debug("**vfMondeTEmplatesList.size()=" + vfNodeTemplatesList.size()); - for (NodeTemplate nodeTemplate : vfNodeTemplatesList) { - logger.debug("nodeTemplate outerLoop=" + outerLoop++); - // extract VF metadata - - Metadata metadata = nodeTemplate.getMetaData(); - - - - //************************Flexware code******************************************* - - String serviceType = toscaResourceStruct.getCatalogService().getServiceType(); - - - if(serviceType != null && serviceType.equalsIgnoreCase("Flexware")){ - - createVnfResource(nodeTemplate, toscaResourceStruct); - - // check for duplicate record already in the database - VnfResource vnfResource = catalogDB.getVnfResource(toscaResourceStruct.getCatalogVnfResource().getModelName(), - BigDecimalVersion.castAndCheckNotificationVersionToString( - toscaResourceStruct.getCatalogVnfResource().getVersion())); - - if (vnfResource != null) { - toscaResourceStruct.setVnfAlreadyInstalled(true); - } - - - if(!toscaResourceStruct.isVnfAlreadyInstalled()) { - - catalogDB.saveOrUpdateVnfResource(toscaResourceStruct.getCatalogVnfResource()); - - } - - - boolean saveVnfCustomization = catalogDB.saveVnfResourceCustomization(toscaResourceStruct.getCatalogVnfResourceCustomization()); - - if(saveVnfCustomization){ - catalogDB.saveServiceToResourceCustomization(toscaResourceStruct.getCatalogVfServiceToResourceCustomization()); - } - - - } - - - // *************************** END of FLEXWARE CODE **************************************************** - - String vfCustomizationCategory = toscaResourceStruct.getSdcCsarHelper().getMetadataPropertyValue(metadata, SdcPropertyNames.PROPERTY_NAME_CATEGORY); - - if(!vfCustomizationCategory.equalsIgnoreCase("Allotted Resource")) // Do not treat Allotted Resources as VNF resources - { - - String vfCustomizationUUID = toscaResourceStruct.getSdcCsarHelper().getMetadataPropertyValue(metadata, SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); - logger.debug("vfCustomizationUUID=" + vfCustomizationUUID); - - - /* HEAT TABLE POPULATION - * ******************************************************************************************************* - */ - - int nextLoop = 0; - for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) { - logger.debug("vfResourceStructure.getVfModuleStructure() loop, nextLoop = " + nextLoop++); - logger.debug("vfModuleStructure:" + vfModuleStructure.toString()); - - // Here we set the right db structure according to the Catalog - // DB - - // We expect only one MAIN HEAT per VFMODULE - // we can also obtain from it the Env ArtifactInfo, that's why - // we - // get the Main IArtifactInfo - - HeatTemplate heatMainTemplate = null; - HeatEnvironment heatEnv; - - HeatTemplate heatVolumeTemplate = null; - HeatEnvironment heatVolumeEnv; - - - IVfModuleData vfMetadata = vfModuleStructure.getVfModuleMetadata(); - - - if (vfModuleStructure.getArtifactsMap().containsKey(ASDCConfiguration.HEAT)) { - - List artifacts = vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT); - logger.debug("there are " + artifacts.size() + " artifacts"); - IArtifactInfo mainEnvArtifactInfo = null; - for (VfModuleArtifact vfma : artifacts) { - logger.debug("vmfa=" + vfma.toString()); - mainEnvArtifactInfo = - vfma.getArtifactInfo().getGeneratedArtifact(); - - // MAIN HEAT - heatMainTemplate = (HeatTemplate) vfma.getCatalogObject(); - - // Set HeatTemplateArtifactUUID to use later when setting the VfModule and NetworkResource - toscaResourceStruct.setHeatTemplateUUID(heatMainTemplate.getArtifactUuid()); - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo - .createElementFromVfArtifactInfo(vfma.getArtifactInfo())); - - catalogDB.saveHeatTemplate(heatMainTemplate, heatMainTemplate.getParameters()); - // Indicate we have deployed it in the DB - vfma.incrementDeployedInDB(); - } - - - // VOLUME HEAT - // We expect only one VOL HEAT per VFMODULE - // we can also obtain from it the Env ArtifactInfo, that's why - // we get the Volume IArtifactInfo - - if (vfModuleStructure.getArtifactsMap().containsKey(ASDCConfiguration.HEAT_VOL)) { - IArtifactInfo volEnvArtifactInfo = vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0) - .getArtifactInfo().getGeneratedArtifact(); - - heatVolumeTemplate = (HeatTemplate) vfModuleStructure.getArtifactsMap() - .get(ASDCConfiguration.HEAT_VOL).get(0).getCatalogObject(); - - // Set VolHeatTemplate ArtifactUUID to use later when setting the VfModule - toscaResourceStruct.setVolHeatTemplateUUID(heatVolumeTemplate.getArtifactUuid()); - - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo())); - - catalogDB.saveHeatTemplate(heatVolumeTemplate, heatVolumeTemplate.getParameters()); - // Indicate we have deployed it in the DB - vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).incrementDeployedInDB(); - - if (volEnvArtifactInfo != null) { - heatVolumeEnv = (HeatEnvironment) vfResourceStructure.getArtifactsMapByUUID() - .get(volEnvArtifactInfo.getArtifactUUID()).getCatalogObject(); - - // Set VolHeatTemplate ArtifactUUID to use later when setting the VfModule - toscaResourceStruct.setVolHeatEnvTemplateUUID(heatVolumeEnv.getArtifactUuid()); - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(volEnvArtifactInfo)); - - catalogDB.saveHeatEnvironment(heatVolumeEnv); - // Indicate we have deployed it in the DB - vfResourceStructure.getArtifactsMapByUUID().get(volEnvArtifactInfo.getArtifactUUID()).incrementDeployedInDB(); - } - - } - - // NESTED HEAT - // Here we expect many HEAT_NESTED template to be there - // XXX FIX BY PCLO: Defect# -36643 -US666034 - check first if we really have nested heat templates - if (vfModuleStructure.getArtifactsMap().containsKey(ASDCConfiguration.HEAT_NESTED)) { - for (VfModuleArtifact heatNestedArtifact : vfModuleStructure.getArtifactsMap() - .get(ASDCConfiguration.HEAT_NESTED)) { - - // Check if this nested is well referenced by the MAIN HEAT - String parentArtifactType = ToscaResourceInstaller.identifyParentOfNestedTemplate(vfModuleStructure,heatNestedArtifact); - HeatTemplate heatNestedTemplate = (HeatTemplate) heatNestedArtifact.getCatalogObject(); - - if (parentArtifactType != null) { - - switch (parentArtifactType) { - case ASDCConfiguration.HEAT: - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(heatNestedArtifact.getArtifactInfo())); - - catalogDB.saveNestedHeatTemplate (heatMainTemplate.getArtifactUuid(), heatNestedTemplate, heatNestedTemplate.getTemplateName()); - // Indicate we have deployed it in the DB - heatNestedArtifact.incrementDeployedInDB(); - break; - case ASDCConfiguration.HEAT_VOL: - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(heatNestedArtifact.getArtifactInfo())); - catalogDB.saveNestedHeatTemplate (heatVolumeTemplate.getArtifactUuid(), heatNestedTemplate, heatNestedTemplate.getTemplateName()); - // Indicate we have deployed it in the DB - heatNestedArtifact.incrementDeployedInDB(); - break; - - default: - break; - - } - } else { // Assume it belongs to HEAT MAIN - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(heatNestedArtifact.getArtifactInfo())); - - catalogDB.saveNestedHeatTemplate (heatMainTemplate.getArtifactUuid(), heatNestedTemplate, heatNestedTemplate.getTemplateName()); - // Indicate we have deployed it in the DB - heatNestedArtifact.incrementDeployedInDB(); - } - } - } - - if (mainEnvArtifactInfo != null) { - heatEnv = (HeatEnvironment) vfResourceStructure.getArtifactsMapByUUID() - .get(mainEnvArtifactInfo.getArtifactUUID()).getCatalogObject(); - - // Set HeatEnvironmentArtifactUUID to use later when setting the VfModule - toscaResourceStruct.setEnvHeatTemplateUUID(heatEnv.getArtifactUuid()); - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(mainEnvArtifactInfo)); - - catalogDB.saveHeatEnvironment(heatEnv); - // Indicate we have deployed it in the DB - vfResourceStructure.getArtifactsMapByUUID().get(mainEnvArtifactInfo.getArtifactUUID()).incrementDeployedInDB(); - } - - // here we expect one VFModule to be there - //VfResourceInstaller.createVfModule(vfModuleStructure,heatMainTemplate, heatVolumeTemplate, heatEnv, heatVolumeEnv); - //VfModule vfModule = vfModuleStructure.getCatalogVfModule(); - - // Add this one for logging - //artifactListForLogging.add(ASDCElementInfo.createElementFromVfModuleStructure(vfModuleStructure)); - - //catalogDB.saveOrUpdateVfModule(vfModule); - - - // extract VF metadata - createVnfResource(nodeTemplate, toscaResourceStruct); - - // check for duplicate record already in the database - VnfResource vnfResource = catalogDB.getVnfResource(toscaResourceStruct.getCatalogVnfResource().getModelName(), - BigDecimalVersion.castAndCheckNotificationVersionToString( - toscaResourceStruct.getCatalogVnfResource().getVersion())); - - if (vnfResource != null) { - toscaResourceStruct.setVnfAlreadyInstalled(true); - } - - - if(!toscaResourceStruct.isVnfAlreadyInstalled()) { - - catalogDB.saveOrUpdateVnfResource(toscaResourceStruct.getCatalogVnfResource()); - - } - - - catalogDB.saveVnfResourceCustomization(toscaResourceStruct.getCatalogVnfResourceCustomization()); - - catalogDB.saveServiceToResourceCustomization(toscaResourceStruct.getCatalogVfServiceToResourceCustomization()); - - - List vfGroups = toscaResourceStruct.getSdcCsarHelper().getVfModulesByVf(vfCustomizationUUID); - logger.debug("vfGroups:" + vfGroups.toString()); - - vfGroups.sort((group1, group2) -> { - //Field name1Field = group1.class.getDeclaredField("name"); - //name1Field.setAccessible(true); - String thisName = group1.getName(); //(String) name1Field.get(group1); - String thatName = group2.getName(); // (String) name1Field.get(group2); - - Matcher m = lastDigit.matcher(thisName); - Matcher m2 = lastDigit.matcher(thatName); - - String thisDigit = "0"; - String thatDigit = "0"; - if (m.find()) { - thisDigit = m.group(); - } else { - return -1; - } - if (m2.find()) { - thatDigit = m2.group(); - } else { - return 1; - } - - return new Integer(thisDigit).compareTo(new Integer(thatDigit)); - }); - - logger.debug("vfGroupsAfter:" + vfGroups.toString()); - - - for(Group group : vfGroups){ - - - //boolean saveVFModule = createVFModule(group, nodeTemplate, toscaResourceStruct, vfMetadata); - if (vfMetadata.getVfModuleModelCustomizationUUID() == null) { - logger.debug("NULL 1"); - } else { - logger.debug("vfMetadata.getMCU=" + vfMetadata.getVfModuleModelCustomizationUUID()); - } - if (group.getMetadata() == null) { - logger.debug("NULL 3"); - } else { - logger.debug("group.getMetadata().getValue() = " + group.getMetadata().getValue("vfModuleModelCustomizationUUID")); - } - if (vfMetadata.getVfModuleModelCustomizationUUID().equals(group.getMetadata().getValue("vfModuleModelCustomizationUUID"))) { - logger.debug("Found a match at " + vfMetadata.getVfModuleModelCustomizationUUID()); - createVFModule(group, nodeTemplate, toscaResourceStruct, vfResourceStructure, vfMetadata); - - catalogDB.saveOrUpdateVfModule(toscaResourceStruct.getCatalogVfModule()); - - catalogDB.saveOrUpdateVfModuleCustomization(toscaResourceStruct.getCatalogVfModuleCustomization()); - - catalogDB.saveVnfResourceToVfModuleCustomization(toscaResourceStruct.getCatalogVnfResourceCustomization(), toscaResourceStruct.getCatalogVfModuleCustomization()); - - - } else { - if(toscaResourceStruct.getCatalogVfModuleCustomization() != null){ - logger.debug("No match for " + toscaResourceStruct.getCatalogVfModuleCustomization().getModelCustomizationUuid()); - } else { - logger.debug("No match for vfModuleModelCustomizationUUID"); - } - } - - } - - } //Commented out to process VFModules each time - - // Here we expect many HEAT_TEMPLATE files to be there - if (vfModuleStructure.getArtifactsMap().containsKey(ASDCConfiguration.HEAT_ARTIFACT)) { - for (VfModuleArtifact heatArtifact : vfModuleStructure.getArtifactsMap() - .get(ASDCConfiguration.HEAT_ARTIFACT)) { - - HeatFiles heatFile = (HeatFiles) heatArtifact.getCatalogObject(); - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(heatArtifact.getArtifactInfo())); - - if(toscaResourceStruct.getCatalogVfModule() != null && heatFile != null){ - catalogDB.saveVfModuleToHeatFiles (toscaResourceStruct.getCatalogVfModule().getModelUUID(), heatFile); - } - // Indicate we will deploy it in the DB - heatArtifact.incrementDeployedInDB(); - } - } - - } - } - } - - /* END OF HEAT TABLE POPULATION - * *************************************************************************************************** - */ - - - // throw new ArtifactInstallerException("TESTING"); - - - List allottedResourceList = toscaResourceStruct.getSdcCsarHelper().getAllottedResources(); - - if(allottedResourceList != null){ - - for(NodeTemplate allottedNode : allottedResourceList){ - - createAllottedResource(allottedNode, toscaResourceStruct); - - catalogDB.saveAllottedResource(toscaResourceStruct.getAllottedResource()); - - catalogDB.saveAllottedResourceCustomization(toscaResourceStruct.getCatalogAllottedResourceCustomization()); - - catalogDB.saveServiceToResourceCustomization(toscaResourceStruct.getCatalogAllottedServiceToResourceCustomization()); - - } - } - - // handle VF resource - List serviceVfList = toscaResourceStruct.getSdcCsarHelper().getServiceVfList(); - if (serviceVfList != null) { - for (NodeTemplate vfNode : serviceVfList) { - createVnfResource(vfNode, toscaResourceStruct); - catalogDB.saveVnfResource(toscaResourceStruct.getCatalogVnfResource()); - catalogDB.saveVnfResourceCustomization(toscaResourceStruct.getCatalogVnfResourceCustomization()); - catalogDB.saveServiceToResourceCustomization(toscaResourceStruct.getCatalogVfServiceToResourceCustomization()); - } - } - - - List nodeTemplatesVLList = toscaResourceStruct.getSdcCsarHelper().getServiceVlList(); - - if(nodeTemplatesVLList != null){ - - for(NodeTemplate vlNode : nodeTemplatesVLList){ - - String networkResourceModelName = vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME); - - List networkHeatTemplateLookup = catalogDB.getTempNetworkHeatTemplateLookup(networkResourceModelName); - - if(networkHeatTemplateLookup != null && networkHeatTemplateLookup.size() > 0 ){ - - createNetworkResource(vlNode, toscaResourceStruct, networkHeatTemplateLookup.get(0)); - - } else { - logger.info(MessageEnum.ASDC_GENERAL_INFO, - "No NetworkResourceName found in TempNetworkHeatTemplateLookup for" + networkResourceModelName, "ASDC", - "createVfModuleStructures"); - createNetworkResource(vlNode, toscaResourceStruct, null); - } - - - catalogDB.saveNetworkResource(toscaResourceStruct.getCatalogNetworkResource()); - - catalogDB.saveNetworkResourceCustomization(toscaResourceStruct.getCatalogNetworkResourceCustomization()); - - catalogDB.saveServiceToResourceCustomization(toscaResourceStruct.getCatalogVlServiceToResourceCustomization()); - - } - } - - - //createServiceToResourceCustomization(toscaResourceStruct.getCatalogService(), toscaResourceStruct.getCatalogVnfResourceCustomization(), toscaResourceStruct); - - // catalogDB.saveToscaCsar(toscaResourceStruct.getCatalogToscaCsar()); - wdComponentDistributionStatus.insertWatchdogComponentDistributionStatus(vfResourceStruct.getNotification().getDistributionID(), "SO", DistributionStatusEnum.COMPONENT_DONE_OK.name()); - - catalogDB.commit(); - toscaResourceStruct.setSuccessfulDeployment(); - - }catch(Exception e){ - logger.debug("Exception :",e); - - wdDistributionStatus.insertWatchdogDistributionId(vfResourceStructure.getNotification().getDistributionID()); - - wdComponentDistributionStatus.insertWatchdogComponentDistributionStatus(vfResourceStruct.getNotification().getDistributionID(), "SO", DistributionStatusEnum.COMPONENT_DONE_ERROR.name()); - - wdDistributionStatus.updateWatchdogDistributionIdStatus(vfResourceStruct.getNotification().getDistributionID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name()); - - Throwable dbExceptionToCapture = e; - while (!(dbExceptionToCapture instanceof ConstraintViolationException || dbExceptionToCapture instanceof LockAcquisitionException) - && (dbExceptionToCapture.getCause() != null)) { - dbExceptionToCapture = dbExceptionToCapture.getCause(); - } - - if (dbExceptionToCapture instanceof ConstraintViolationException || dbExceptionToCapture instanceof LockAcquisitionException) { - logger.warn(MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED, vfResourceStructure.getResourceInstance().getResourceName(), - vfResourceStructure.getNotification().getServiceVersion(), "", "", MsoLogger.ErrorCode.DataError, "Exception - ASCDC Artifact already deployed", e); - } else { - String elementToLog = (artifactListForLogging.size() > 0 ? artifactListForLogging.get(artifactListForLogging.size()-1).toString() : "No element listed"); - logger.error(MessageEnum.ASDC_ARTIFACT_INSTALL_EXC, elementToLog, "", "", MsoLogger.ErrorCode.DataError, "Exception caught during installation of " + vfResourceStructure.getResourceInstance().getResourceName() + ". Transaction rollback", e); - catalogDB.rollback(); - throw new ArtifactInstallerException( - "Exception caught during installation of " + vfResourceStructure.getResourceInstance().getResourceName() + ". Transaction rollback.", e); - } - - } finally { - catalogDB.close(); - } - - } - - - public static String verifyTheFilePrefixInArtifacts(String filebody, VfResourceStructure vfResourceStructure, List listTypes) { - String newFileBody = filebody; - for (VfModuleArtifact moduleArtifact:vfResourceStructure.getArtifactsMapByUUID().values()) { - - if (listTypes.contains(moduleArtifact.getArtifactInfo().getArtifactType())) { - - newFileBody = verifyTheFilePrefixInString(newFileBody,moduleArtifact.getArtifactInfo().getArtifactName()); - } - } - return newFileBody; - } - - public static String verifyTheFilePrefixInString(final String body, final String filenameToVerify) { - - String needlePrefix = "file:///"; - String prefixedFilenameToVerify = needlePrefix+filenameToVerify; - - if ((body == null) || (body.length() == 0) || (filenameToVerify == null) || (filenameToVerify.length() == 0)) { - return body; - } - - StringBuilder sb = new StringBuilder(body.length()); - - int currentIndex = 0; - int startIndex = 0; - - while (currentIndex != -1) { - startIndex = currentIndex; - currentIndex = body.indexOf(prefixedFilenameToVerify, startIndex); - - if (currentIndex == -1) { - break; - } - - // We append from the startIndex up to currentIndex (start of File Name) - sb.append(body.substring(startIndex, currentIndex)); - sb.append(filenameToVerify); - - currentIndex += prefixedFilenameToVerify.length(); - } - - sb.append(body.substring(startIndex)); - - return sb.toString(); - } - - - private static void createHeatTemplateFromArtifact(VfResourceStructure vfResourceStructure,ToscaResourceStructure toscaResourceStruct, - VfModuleArtifact vfModuleArtifact) { - HeatTemplate heatTemplate = new HeatTemplate(); - - // TODO Set the label -// heatTemplate.setAsdcLabel("label"); - // Use the ResourceName of the ASDC template because the HEAT could be - // reused -// heatTemplate.setAsdcResourceName(vfResourceStructure.getResourceInstance().getResourceName()); - heatTemplate.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - - List typeList = new ArrayList<>(); - typeList.add(ASDCConfiguration.HEAT_NESTED); - typeList.add(ASDCConfiguration.HEAT_ARTIFACT); - - heatTemplate.setTemplateBody(verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(),vfResourceStructure,typeList)); - heatTemplate.setTemplateName(vfModuleArtifact.getArtifactInfo().getArtifactName()); - - if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) { - heatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout()); - } else { - heatTemplate.setTimeoutMinutes(240); - } - - //toscaResourceStruct.setHeatFilesUUID(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - - heatTemplate.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); - heatTemplate.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); - heatTemplate.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - - if(vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null){ - heatTemplate.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); - } else { - heatTemplate.setArtifactChecksum("MANUAL_RECORD"); - } - - Set heatParam = ToscaResourceInstaller - .extractHeatTemplateParameters(vfModuleArtifact.getResult(), vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - heatTemplate.setParameters(heatParam); - //heatTemplate.setCreated(getCurrentTimeStamp()); - - vfModuleArtifact.setCatalogObject(heatTemplate); - } - - private static void createHeatEnvFromArtifact(VfResourceStructure vfResourceStructure, - VfModuleArtifact vfModuleArtifact) { - HeatEnvironment heatEnvironment = new HeatEnvironment(); - - heatEnvironment.setName(vfModuleArtifact.getArtifactInfo().getArtifactName()); - // TODO Set the label -// heatEnvironment.setAsdcLabel("Label"); - - List typeList = new ArrayList<>(); - typeList.add(ASDCConfiguration.HEAT); - typeList.add(ASDCConfiguration.HEAT_VOL); - - heatEnvironment.setEnvironment(verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(),vfResourceStructure,typeList)); -// heatEnvironment.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - heatEnvironment.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); - heatEnvironment.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); -// heatEnvironment.setAsdcResourceName(VfResourceInstaller.createVNFName(vfResourceStructure)); - heatEnvironment.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - - if(vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null){ - heatEnvironment.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); - } else{ - heatEnvironment.setArtifactChecksum("MANUAL_RECORD"); - } - //heatEnvironment.setCreated(getCurrentTimeStamp()); - - vfModuleArtifact.setCatalogObject(heatEnvironment); - - } - - private static void createHeatFileFromArtifact(VfResourceStructure vfResourceStructure, - VfModuleArtifact vfModuleArtifact, ToscaResourceStructure toscaResourceStruct) { - - HeatFiles heatFile = new HeatFiles(); - // TODO Set the label -// heatFile.setAsdcLabel("Label"); - heatFile.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - heatFile.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); - heatFile.setFileBody(vfModuleArtifact.getResult()); - heatFile.setFileName(vfModuleArtifact.getArtifactInfo().getArtifactName()); - heatFile.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); - - toscaResourceStruct.setHeatFilesUUID(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - //heatFile.setCreated(getCurrentTimeStamp()); - -// heatFile.setAsdcResourceName(vfResourceStructure.getResourceInstance().getResourceName()); - - - if(vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null){ - heatFile.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); - } else { - heatFile.setArtifactChecksum("MANUAL_RECORD"); - } - - vfModuleArtifact.setCatalogObject(heatFile); - - } - - private static void createService(ToscaResourceStructure toscaResourceStructure, VfResourceStructure vfResourceStructure) { - - toscaResourceStructure.getServiceMetadata(); - - Metadata serviceMetadata = toscaResourceStructure.getServiceMetadata(); - - Service service = new Service(); - - // Service - if(serviceMetadata != null) { - - if(toscaResourceStructure.getServiceVersion() != null){ - service.setVersion(toscaResourceStructure.getServiceVersion()); - } - - service.setServiceType(serviceMetadata.getValue("serviceType")); - service.setServiceRole(serviceMetadata.getValue("serviceRole")); - - service.setDescription(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - service.setModelName(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - service.setModelUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - service.setEnvironmentContext(serviceMetadata.getValue("environmentContext")); - - - if(vfResourceStructure != null){ - service.setWorkloadContext(vfResourceStructure.getNotification().getWorkloadContext()); - } - //service.setVersion(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); - service.setModelInvariantUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - service.setCategory(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)); - service.setToscaCsarArtifactUUID(toscaResourceStructure.getToscaArtifact().getArtifactUUID()); - //service.setCreated(getCurrentTimeStamp()); - } - - toscaResourceStructure.setCatalogService(service); - } - - private static void createToscaCsar(ToscaResourceStructure toscaResourceStructure) { - - ToscaCsar toscaCsar = new ToscaCsar(); - if(toscaResourceStructure.getToscaArtifact().getArtifactChecksum() != null){ - toscaCsar.setArtifactChecksum(toscaResourceStructure.getToscaArtifact().getArtifactChecksum()); - } else { - toscaCsar.setArtifactChecksum("MANUAL_RECORD"); - } - toscaCsar.setArtifactUUID(toscaResourceStructure.getToscaArtifact().getArtifactUUID()); - toscaCsar.setName(toscaResourceStructure.getToscaArtifact().getArtifactName()); - toscaCsar.setVersion(toscaResourceStructure.getToscaArtifact().getArtifactVersion()); - toscaCsar.setDescription(toscaResourceStructure.getToscaArtifact().getArtifactDescription()); - toscaCsar.setUrl(toscaResourceStructure.getToscaArtifact().getArtifactURL()); - - toscaResourceStructure.setCatalogToscaCsar(toscaCsar); - } - - private static void createNetworkResource(NodeTemplate networkNodeTemplate, ToscaResourceStructure toscaResourceStructure, TempNetworkHeatTemplateLookup networkHeatTemplateLookup) { - NetworkResourceCustomization networkResourceCustomization = new NetworkResourceCustomization(); - - NetworkResource networkResource = new NetworkResource(); - - String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK); - - if("true".equalsIgnoreCase(providerNetwork)){ - networkResource.setNeutronNetworkType("PROVIDER"); - } else { - networkResource.setNeutronNetworkType("BASIC"); - } - - networkResource.setModelName(testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - - networkResource.setModelInvariantUUID(testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); - networkResource.setModelUUID(testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - networkResource.setModelVersion(testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - - networkResource.setAicVersionMax(testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); - String aicVersionMin = networkHeatTemplateLookup != null ? networkHeatTemplateLookup.getAicVersionMin() : "2.5"; - networkResource.setAicVersionMin(aicVersionMin); - networkResource.setToscaNodeType(networkNodeTemplate.getType()); - networkResource.setDescription(testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - networkResource.setOrchestrationMode("HEAT"); - networkResource.setCategory(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)); - networkResource.setSubCategory(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)); - //for tosca NS ,there is no heat for network VL - String heatTemplateArtifactUUID = networkHeatTemplateLookup != null ? networkHeatTemplateLookup.getHeatTemplateArtifactUuid() : "null"; - networkResource.setHeatTemplateArtifactUUID(heatTemplateArtifactUUID); - - toscaResourceStructure.setCatalogNetworkResource(networkResource); - - networkResourceCustomization.setModelInstanceName(testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - networkResourceCustomization.setModelCustomizationUuid(testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); - networkResourceCustomization.setNetworkResourceModelUuid(testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - - - networkResourceCustomization.setNetworkTechnology(testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY))); - networkResourceCustomization.setNetworkType(testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE))); - networkResourceCustomization.setNetworkRole(testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE))); - networkResourceCustomization.setNetworkScope(testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE))); - - toscaResourceStructure.setCatalogNetworkResourceCustomization(networkResourceCustomization); - - ServiceToResourceCustomization serviceToResourceCustomization = new ServiceToResourceCustomization(); - serviceToResourceCustomization.setServiceModelUUID(toscaResourceStructure.getCatalogService().getModelUUID()); - serviceToResourceCustomization.setResourceModelCustomizationUUID(testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); - serviceToResourceCustomization.setModelType("network"); - - toscaResourceStructure.setCatalogVlServiceToResourceCustomization(serviceToResourceCustomization); - - - } - - private static void createVFModule(Group group, NodeTemplate nodeTemplate, ToscaResourceStructure toscaResourceStructure, VfResourceStructure vfResourceStructure, IVfModuleData vfModuleData) { - VfModule vfModule = new VfModule(); - - Metadata vfMetadata = group.getMetadata(); - - String vfModuleModelUUID = vfModuleData.getVfModuleModelUUID(); - - - if(vfModuleModelUUID != null && vfModuleModelUUID.contains(".")){ - vfModuleModelUUID = vfModuleModelUUID.substring(0, vfModuleModelUUID.indexOf(".")); - } - - - for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()){ - - String vfModelUUID = vfModuleStructure.getVfModuleMetadata().getVfModuleModelUUID(); - - if(vfModelUUID != null && vfModelUUID.equalsIgnoreCase(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID))){ - - List artifacts = vfModuleStructure.getVfModuleMetadata().getArtifacts(); - - for(String artifact: artifacts){ - - - for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { - - - if(artifact.equals(vfModuleArtifact.getArtifactInfo().getArtifactUUID())){ - //if(vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ARTIFACT)){ - if(vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT)){ - vfModule.setHeatTemplateArtifactUUId(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - } - - if(vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_VOL)){ - vfModule.setVolHeatTemplateArtifactUUId(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - - } - } - - } - - - } - - - } - - - } - - vfModule.setModelInvariantUuid(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID))); - vfModule.setModelName(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME))); - vfModule.setModelUUID(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID))); - vfModule.setVersion(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION))); - vfModule.setDescription(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - //vfModule.setHeatTemplateArtifactUUId(toscaResourceStructure.getHeatTemplateUUID()); - //vfModule.setVolHeatTemplateArtifactUUId(toscaResourceStructure.getVolHeatTemplateUUID()); - - vfModule.setVnfResourceModelUUId(toscaResourceStructure.getCatalogVnfResource().getModelUuid()); - - String vfModuleType = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_VFMODULETYPE); - if(vfModuleType != null && "Base".equalsIgnoreCase(vfModuleType)){ - vfModule.setIsBase(1); - }else { - vfModule.setIsBase(0); - } - - - VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); - vfModuleCustomization.setModelCustomizationUuid(vfModuleData.getVfModuleModelCustomizationUUID()); - - - vfModuleCustomization.setVfModuleModelUuid(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)); - - vfModuleCustomization.setHeatEnvironmentArtifactUuid(toscaResourceStructure.getEnvHeatTemplateUUID()); - - - vfModuleCustomization.setVolEnvironmentArtifactUuid(toscaResourceStructure.getVolHeatEnvTemplateUUID()); - - String initialCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT); - if(initialCount != null && initialCount.length() > 0){ - vfModuleCustomization.setInitialCount(Integer.valueOf(initialCount)); - } - - vfModuleCustomization.setInitialCount(Integer.valueOf(toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT))); - - String availabilityZoneCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT); - if(availabilityZoneCount != null && availabilityZoneCount.length() > 0){ - vfModuleCustomization.setAvailabilityZoneCount(Integer.valueOf(availabilityZoneCount)); - } - - - vfModuleCustomization.setLabel(toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_VFMODULELABEL)); - - String maxInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_MAXVFMODULEINSTANCES); - if(maxInstances != null && maxInstances.length() > 0){ - vfModuleCustomization.setMaxInstances(Integer.valueOf(maxInstances)); - } - - String minInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_MINVFMODULEINSTANCES); - if(minInstances != null && minInstances.length() > 0){ - vfModuleCustomization.setMinInstances(Integer.valueOf(minInstances)); - } - - toscaResourceStructure.setCatalogVfModule(vfModule); - - toscaResourceStructure.setCatalogVfModuleCustomization(vfModuleCustomization); - - } - - private static void createVnfResourceToVfModuleCustomization(VnfResourceCustomization vnfResourceCustomization, - VfModuleCustomization vfModuleCustomization, - ToscaResourceStructure toscaResourceStructure) { - - VnfResCustomToVfModuleCustom vnfResCustomToVfModuleCustom = new VnfResCustomToVfModuleCustom(); - - vnfResCustomToVfModuleCustom.setVfModuleCustModelCustomizationUuid(vfModuleCustomization.getModelCustomizationUuid()); - vnfResCustomToVfModuleCustom.setVnfResourceCustModelCustomizationUuid(vnfResourceCustomization.getModelCustomizationUuid()); - - toscaResourceStructure.setCatalogVnfResCustomToVfModuleCustom(vnfResCustomToVfModuleCustom); - - - - } - - - private static void createTempNetworkHeatTemplateLookup(NetworkResource networkResource, - VfModule vfModule, - ToscaResourceStructure toscaResourceStructure) { - - TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup = new TempNetworkHeatTemplateLookup(); - - tempNetworkHeatTemplateLookup.setNetworkResourceModelName(networkResource.getModelName()); - tempNetworkHeatTemplateLookup.setHeatTemplateArtifactUuid(vfModule.getHeatTemplateArtifactUUId()); - tempNetworkHeatTemplateLookup.setAicVersionMin("1"); - - toscaResourceStructure.setCatalogTempNetworkHeatTemplateLookup(tempNetworkHeatTemplateLookup); - - - - } - - private static void createVnfResource(NodeTemplate vfNodeTemplate, ToscaResourceStructure toscaResourceStructure) { - VnfResource vnfResource = new VnfResource(); - - - //toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT) - - vnfResource.setModelInvariantUuid(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); - vnfResource.setModelName(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - vnfResource.setModelUuid(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - - vnfResource.setVersion(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - vnfResource.setDescription(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - vnfResource.setOrchestrationMode("HEAT"); - vnfResource.setToscaNodeType(testNull(vfNodeTemplate.getType())); - vnfResource.setAicVersionMax(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); - vnfResource.setAicVersionMin(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); - vnfResource.setCategory(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)); - vnfResource.setSubCategory(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)); - //vnfResource.setHeatTemplateArtifactUUId(toscaResourceStructure.getHeatTemplateUUID()); - - // vfNodeTemplate.getProperties() - toscaResourceStructure.setCatalogVnfResource(vnfResource); - - VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization(); - vnfResourceCustomization.setModelCustomizationUuid(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); - vnfResourceCustomization.setModelInstanceName(vfNodeTemplate.getName()); - - vnfResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION))); - vnfResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFCODE))); - vnfResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE))); - vnfResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE))); - - - vnfResourceCustomization.setMultiStageDesign(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, "multi_stage_design")); - - - vnfResourceCustomization.setVnfResourceModelUuid(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - vnfResourceCustomization.setAvailabilityZoneMaxCount(Integer.getInteger(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT))); - - //vnfResourceCustomization.setMultiStageDesign(vfNodeTemplate.getMetaData().getValue("multi_stage_design")); - //vnfResourceCustomization.setMultiStageDesign(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT).trim()); - - - vnfResourceCustomization.setMaxInstances(Integer.getInteger(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); - vnfResourceCustomization.setMinInstances(Integer.getInteger(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); - - - - toscaResourceStructure.setCatalogVnfResourceCustomization(vnfResourceCustomization); - - - ServiceToResourceCustomization serviceToResourceCustomization = new ServiceToResourceCustomization(); - serviceToResourceCustomization.setServiceModelUUID(toscaResourceStructure.getCatalogService().getModelUUID()); - serviceToResourceCustomization.setResourceModelCustomizationUUID(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - serviceToResourceCustomization.setModelType("vnf"); - - toscaResourceStructure.setCatalogVfServiceToResourceCustomization(serviceToResourceCustomization); - - - } - - private static void createAllottedResource(NodeTemplate nodeTemplate, ToscaResourceStructure toscaResourceStructure) { - AllottedResource allottedResource = new AllottedResource(); - - allottedResource.setModelUuid(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - allottedResource.setModelInvariantUuid(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); - allottedResource.setModelName(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - allottedResource.setModelVersion(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - allottedResource.setToscaNodeType(testNull(nodeTemplate.getType())); - allottedResource.setSubcategory(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY))); - allottedResource.setDescription(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - - toscaResourceStructure.setAllottedResource(allottedResource); - - AllottedResourceCustomization allottedResourceCustomization = new AllottedResourceCustomization(); - allottedResourceCustomization.setModelCustomizationUuid(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); - allottedResourceCustomization.setModelInstanceName(nodeTemplate.getName()); - allottedResourceCustomization.setArModelUuid(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - - - allottedResourceCustomization.setProvidingServiceModelInvariantUuid(toscaResourceStructure.getCatalogService().getModelInvariantUUID()); - allottedResourceCustomization.setProvidingServiceModelUuid(toscaResourceStructure.getCatalogService().getModelUUID()); - allottedResourceCustomization.setProvidingServiceModelName(toscaResourceStructure.getCatalogService().getModelName()); - allottedResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION))); - allottedResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFCODE))); - allottedResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE))); - allottedResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE))); - allottedResourceCustomization.setMinInstances(Integer.getInteger(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); - allottedResourceCustomization.setMaxInstances(Integer.getInteger(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); - allottedResourceCustomization.setTargetNetworkRole(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NETWORKROLE)); - - toscaResourceStructure.setCatalogAllottedResourceCustomization(allottedResourceCustomization); - - ServiceToResourceCustomization serviceToResourceCustomization = new ServiceToResourceCustomization(); - serviceToResourceCustomization.setServiceModelUUID(toscaResourceStructure.getCatalogService().getModelUUID()); - serviceToResourceCustomization.setResourceModelCustomizationUUID(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); - serviceToResourceCustomization.setModelType("allottedResource"); - - toscaResourceStructure.setCatalogAllottedServiceToResourceCustomization(serviceToResourceCustomization); - - } - - private static Set extractHeatTemplateParameters(String yamlFile, String artifactUUID) { - - // Scan the payload downloadResult and extract the HeatTemplate - // parameters - YamlEditor yamlEditor = new YamlEditor(yamlFile.getBytes()); - return yamlEditor.getParameterList(artifactUUID); - - } - - private static String identifyParentOfNestedTemplate(VfModuleStructure vfModuleStructure,VfModuleArtifact heatNestedArtifact) { - - if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT) != null - && vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0).getArtifactInfo().getRelatedArtifacts() != null) { - for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0) - .getArtifactInfo().getRelatedArtifacts()) { - if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) { - return ASDCConfiguration.HEAT; - } - - } - } - - if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) != null - && vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo().getRelatedArtifacts() != null) { - for (IArtifactInfo unknownArtifact:vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo().getRelatedArtifacts()) { - if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) { - return ASDCConfiguration.HEAT_VOL; - } - - } - } - - // Does not belong to anything - return null; - - } - - private static String testNull(Object object) { - - - if(object == null){ - return null; - }else if (object != null && object.equals("NULL")) { - return null; - }else if (object != null && object instanceof Integer) { - return object.toString(); - } else if (object != null && object instanceof String) { - return (String)object; - } else { - return "Type not recognized"; - } - } - - private static String createVNFName(VfResourceStructure vfResourceStructure) { - - return vfResourceStructure.getNotification().getServiceName() + "/" + vfResourceStructure.getResourceInstance().getResourceInstanceName(); - } - - private static String createVfModuleName(VfModuleStructure vfModuleStructure) { - - return createVNFName(vfModuleStructure.getParentVfResource())+"::"+vfModuleStructure.getVfModuleMetadata().getVfModuleModelName(); - } - - - private static Timestamp getCurrentTimeStamp() { - - return new Timestamp(new Date().getTime()); - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/heat/VfResourceInstaller.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/heat/VfResourceInstaller.java deleted file mode 100644 index d227961664..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/heat/VfResourceInstaller.java +++ /dev/null @@ -1,790 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.installer.heat; - -import java.sql.Timestamp; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.hibernate.exception.ConstraintViolationException; -import org.hibernate.exception.LockAcquisitionException; -import org.onap.sdc.api.notification.IArtifactInfo; - -import org.openecomp.mso.asdc.client.ASDCConfiguration; -import org.openecomp.mso.asdc.client.exceptions.ArtifactInstallerException; -import org.openecomp.mso.asdc.installer.ASDCElementInfo; -import org.openecomp.mso.asdc.installer.BigDecimalVersion; -import org.openecomp.mso.asdc.installer.IVfResourceInstaller; -import org.openecomp.mso.asdc.installer.VfModuleArtifact; -import org.openecomp.mso.asdc.installer.VfModuleStructure; -import org.openecomp.mso.asdc.installer.VfResourceStructure; -import org.openecomp.mso.asdc.util.YamlEditor; -import org.openecomp.mso.db.catalog.CatalogDatabase; -import org.openecomp.mso.db.catalog.beans.HeatEnvironment; -import org.openecomp.mso.db.catalog.beans.HeatFiles; -import org.openecomp.mso.db.catalog.beans.HeatTemplate; -import org.openecomp.mso.db.catalog.beans.HeatTemplateParam; -import org.openecomp.mso.db.catalog.beans.NetworkResourceCustomization; -import org.openecomp.mso.db.catalog.beans.AllottedResourceCustomization; -import org.openecomp.mso.db.catalog.beans.Service; -import org.openecomp.mso.db.catalog.beans.ServiceToAllottedResources; -import org.openecomp.mso.db.catalog.beans.ServiceToNetworks; -import org.openecomp.mso.db.catalog.beans.VfModule; -import org.openecomp.mso.db.catalog.beans.VnfResource; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; - -public class VfResourceInstaller implements IVfResourceInstaller { - - private MsoLogger logger; - - public VfResourceInstaller() { - logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.ASDC); - } - - @Override - public boolean isResourceAlreadyDeployed(VfResourceStructure vfResourceStruct) - throws ArtifactInstallerException { - - boolean status = false; - VfResourceStructure vfResourceStructure = (VfResourceStructure)vfResourceStruct; - - try(CatalogDatabase db = CatalogDatabase.getInstance()) { - - String resourceType = vfResourceStruct.getResourceInstance().getResourceType(); - String category = vfResourceStruct.getResourceInstance().getCategory(); - - // Check for duplicate VF Module that is not an Allotted Resource - if(resourceType.equals("VF") && !category.equalsIgnoreCase("Allotted Resource")){ - logger.info(MessageEnum.ASDC_CHECK_HEAT_TEMPLATE, "VNFResource", - VfResourceInstaller.createVNFName(vfResourceStructure), - BigDecimalVersion.castAndCheckNotificationVersionToString( - vfResourceStructure.getNotification().getServiceVersion()), "", ""); - - VnfResource vnfResource = db.getVnfResource( - VfResourceInstaller.createVNFName(vfResourceStructure), - BigDecimalVersion.castAndCheckNotificationVersionToString( - vfResourceStructure.getNotification().getServiceVersion())); - - if (vnfResource != null) { - status = true; - - } - - } - - // Check dup for VF Allotted Resource - if(resourceType.equals("VF") && category.equalsIgnoreCase("Allotted Resource")){ - logger.info(MessageEnum.ASDC_CHECK_HEAT_TEMPLATE, "AllottedResource", - vfResourceStruct.getResourceInstance().getResourceInstanceName(), - BigDecimalVersion.castAndCheckNotificationVersionToString( - vfResourceStructure.getNotification().getServiceVersion()), "", ""); - - List allottedResources = db.getAllAllottedResourcesByServiceModelUuid(vfResourceStruct.getNotification().getServiceUUID()); - - if(allottedResources != null && allottedResources.size() > 0){ - for(AllottedResourceCustomization allottedResource : allottedResources){ - - String existingAllottedResource = allottedResource.getModelCustomizationUuid(); - String notificationAllottedResource = vfResourceStruct.getResourceInstance().getResourceCustomizationUUID(); - - if(existingAllottedResource.equals(notificationAllottedResource)){ - status=true; - break; - } - } - - } - } - - // Check Network for duplicates - if(resourceType.equals("VL")){ - logger.info(MessageEnum.ASDC_CHECK_HEAT_TEMPLATE, "NetworkResource", - vfResourceStruct.getResourceInstance().getResourceInstanceName(), - BigDecimalVersion.castAndCheckNotificationVersionToString( - vfResourceStructure.getNotification().getServiceVersion()), "", ""); - - List networkResources = db.getAllNetworksByServiceModelUuid(vfResourceStruct.getNotification().getServiceUUID()); - - if(networkResources != null && networkResources.size() > 0){ - for(NetworkResourceCustomization networkResource : networkResources){ - - String existingNetworkResource = networkResource.getModelCustomizationUuid(); - String notificationNetworkResource = vfResourceStruct.getResourceInstance().getResourceCustomizationUUID(); - - if(existingNetworkResource.equals(notificationNetworkResource)){ - status=true; - break; - } - } - - } - } - - if (status) { - logger.info(MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED_DETAIL, - vfResourceStructure.getResourceInstance().getResourceInstanceName(), - vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(), - vfResourceStructure.getNotification().getServiceName(), - BigDecimalVersion.castAndCheckNotificationVersionToString( - vfResourceStructure.getNotification().getServiceVersion()), - vfResourceStructure.getNotification().getServiceUUID(), - vfResourceStructure.getResourceInstance().getResourceName(),"", ""); - } else { - logger.info(MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL, - vfResourceStructure.getResourceInstance().getResourceInstanceName(), - vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(), - vfResourceStructure.getNotification().getServiceName(), - BigDecimalVersion.castAndCheckNotificationVersionToString( - vfResourceStructure.getNotification().getServiceVersion()), - vfResourceStructure.getNotification().getServiceUUID(), - vfResourceStructure.getResourceInstance().getResourceName(),"", ""); - } - - return status; - - } catch (Exception e) { - logger.error(MessageEnum.ASDC_ARTIFACT_CHECK_EXC, "", "", MsoLogger.ErrorCode.SchemaError, "Exception - isResourceAlreadyDeployed"); - throw new ArtifactInstallerException("Exception caught during checking existence of the VNF Resource.", e); - } - } - - @Override - public void installTheResource(VfResourceStructure vfResourceStruct) throws ArtifactInstallerException { - - // 1. Add the DB object list (Hashed) to be created from the HashMap - // UUID - // The DB objects will be stored in each VfModuleArtifact objects - // Those objects could be reused by different VfModule - - VfResourceStructure vfResourceStructure = (VfResourceStructure)vfResourceStruct; - - for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { - - switch (vfModuleArtifact.getArtifactInfo().getArtifactType()) { - case ASDCConfiguration.HEAT: - case ASDCConfiguration.HEAT_VOL: - case ASDCConfiguration.HEAT_NESTED: - VfResourceInstaller.createHeatTemplateFromArtifact(vfResourceStructure, vfModuleArtifact); - break; - case ASDCConfiguration.HEAT_ENV: - VfResourceInstaller.createHeatEnvFromArtifact(vfResourceStructure, vfModuleArtifact); - break; - case ASDCConfiguration.HEAT_ARTIFACT: - VfResourceInstaller.createHeatFileFromArtifact(vfResourceStructure, vfModuleArtifact); - break; - case ASDCConfiguration.HEAT_NET: - case ASDCConfiguration.OTHER: - logger.warn(MessageEnum.ASDC_ARTIFACT_TYPE_NOT_SUPPORT, vfModuleArtifact.getArtifactInfo().getArtifactType()+"(Artifact Name:"+vfModuleArtifact.getArtifactInfo().getArtifactName()+")", "", "", MsoLogger.ErrorCode.DataError, "Artifact type not supported"); - break; - default: - break; - - } - } - - // in case of deployment failure, use a string that will represent the type of artifact that failed... - List artifactListForLogging = new ArrayList<>(); - - CatalogDatabase catalogDB = CatalogDatabase.getInstance(); - // 2. Create the VFModules/VNFResource objects by linking them to the - // objects created before and store them in Resource/module structure - // Opening a DB transaction, starting from here - try { - - VfResourceInstaller.createService(vfResourceStructure); - - String resourceType = vfResourceStructure.getResourceInstance().getResourceType(); - String resourceCategory = vfResourceStructure.getResourceInstance().getCategory(); - - if("VF".equals(resourceType)){ - - if(resourceCategory.equalsIgnoreCase("Allotted Resource")){ - VfResourceInstaller.createAllottedResourceCustomization(vfResourceStructure); - catalogDB.saveAllottedResourceCustomization(vfResourceStructure.getCatalogResourceCustomization()); - } else { - VfResourceInstaller.createVnfResource(vfResourceStructure); - catalogDB.saveOrUpdateVnfResource(vfResourceStructure.getCatalogVnfResource()); - } - } - - if("VL".equals(resourceType)){ - VfResourceInstaller.createNetworkResourceCustomization(vfResourceStructure); - catalogDB.saveNetworkResourceCustomization(vfResourceStructure.getCatalogNetworkResourceCustomization()); - } - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfResourceStructure(vfResourceStructure)); - - //catalogDB.saveOrUpdateVnfResource(vfResourceStructure.getCatalogVnfResource()); - catalogDB.saveService(vfResourceStructure.getCatalogService()); - - // Now that the service has been added we can populate the Service_to_AllottedResources table - if("VF".equals(resourceType) && "Allotted Resource".equalsIgnoreCase(resourceCategory)){ - catalogDB.saveServiceToAllottedResources(vfResourceStructure.getCatalogServiceToAllottedResources()); - } - - // Now that the service has been added we can populate the Service_to_Network table - if("VL".equals(resourceType)){ - catalogDB.saveServiceToNetworks(vfResourceStructure.getCatalogServiceToNetworks()); - } - - for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) { - - // Here we set the right db structure according to the Catalog - // DB - - // We expect only one MAIN HEAT per VFMODULE - // we can also obtain from it the Env ArtifactInfo, that's why - // we - // get the Main IArtifactInfo - - HeatTemplate heatMainTemplate = null; - HeatEnvironment heatEnv = null; - - HeatTemplate heatVolumeTemplate = null; - HeatEnvironment heatVolumeEnv = null; - - if (vfModuleStructure.getArtifactsMap().containsKey(ASDCConfiguration.HEAT)) { - IArtifactInfo mainEnvArtifactInfo = vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT) - .get(0).getArtifactInfo().getGeneratedArtifact(); - - // MAIN HEAT - heatMainTemplate = (HeatTemplate) vfModuleStructure.getArtifactsMap() - .get(ASDCConfiguration.HEAT).get(0).getCatalogObject(); - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo - .createElementFromVfArtifactInfo(vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0).getArtifactInfo())); - - catalogDB.saveHeatTemplate(heatMainTemplate, heatMainTemplate.getParameters()); - // Indicate we have deployed it in the DB - vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0).incrementDeployedInDB(); - - - // VOLUME HEAT - // We expect only one VOL HEAT per VFMODULE - // we can also obtain from it the Env ArtifactInfo, that's why - // we get the Volume IArtifactInfo - - if (vfModuleStructure.getArtifactsMap().containsKey(ASDCConfiguration.HEAT_VOL)) { - IArtifactInfo volEnvArtifactInfo = vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0) - .getArtifactInfo().getGeneratedArtifact(); - - heatVolumeTemplate = (HeatTemplate) vfModuleStructure.getArtifactsMap() - .get(ASDCConfiguration.HEAT_VOL).get(0).getCatalogObject(); - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo())); - - catalogDB.saveHeatTemplate(heatVolumeTemplate, heatVolumeTemplate.getParameters()); - // Indicate we have deployed it in the DB - vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).incrementDeployedInDB(); - - if (volEnvArtifactInfo != null) { - heatVolumeEnv = (HeatEnvironment) vfResourceStructure.getArtifactsMapByUUID() - .get(volEnvArtifactInfo.getArtifactUUID()).getCatalogObject(); - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(volEnvArtifactInfo)); - - catalogDB.saveHeatEnvironment(heatVolumeEnv); - // Indicate we have deployed it in the DB - vfResourceStructure.getArtifactsMapByUUID().get(volEnvArtifactInfo.getArtifactUUID()).incrementDeployedInDB(); - } - - } - - // NESTED HEAT - // Here we expect many HEAT_NESTED template to be there - // check first if we really have nested heat templates - if (vfModuleStructure.getArtifactsMap().containsKey(ASDCConfiguration.HEAT_NESTED)) { - for (VfModuleArtifact heatNestedArtifact : vfModuleStructure.getArtifactsMap() - .get(ASDCConfiguration.HEAT_NESTED)) { - - // Check if this nested is well referenced by the MAIN HEAT - String parentArtifactType = VfResourceInstaller.identifyParentOfNestedTemplate(vfModuleStructure,heatNestedArtifact); - HeatTemplate heatNestedTemplate = (HeatTemplate) heatNestedArtifact.getCatalogObject(); - - if (parentArtifactType != null) { - - switch (parentArtifactType) { - case ASDCConfiguration.HEAT: - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(heatNestedArtifact.getArtifactInfo())); - - catalogDB.saveNestedHeatTemplate (heatMainTemplate.getArtifactUuid(), heatNestedTemplate, heatNestedTemplate.getTemplateName()); - // Indicate we have deployed it in the DB - heatNestedArtifact.incrementDeployedInDB(); - break; - case ASDCConfiguration.HEAT_VOL: - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(heatNestedArtifact.getArtifactInfo())); - catalogDB.saveNestedHeatTemplate (heatVolumeTemplate.getArtifactUuid(), heatNestedTemplate, heatNestedTemplate.getTemplateName()); - // Indicate we have deployed it in the DB - heatNestedArtifact.incrementDeployedInDB(); - break; - - default: - break; - - } - } else { // Assume it belongs to HEAT MAIN - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(heatNestedArtifact.getArtifactInfo())); - - catalogDB.saveNestedHeatTemplate (heatMainTemplate.getArtifactUuid(), heatNestedTemplate, heatNestedTemplate.getTemplateName()); - // Indicate we have deployed it in the DB - heatNestedArtifact.incrementDeployedInDB(); - } - } - } - - if (mainEnvArtifactInfo != null) { - heatEnv = (HeatEnvironment) vfResourceStructure.getArtifactsMapByUUID() - .get(mainEnvArtifactInfo.getArtifactUUID()).getCatalogObject(); - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(mainEnvArtifactInfo)); - - catalogDB.saveHeatEnvironment(heatEnv); - // Indicate we have deployed it in the DB - vfResourceStructure.getArtifactsMapByUUID().get(mainEnvArtifactInfo.getArtifactUUID()).incrementDeployedInDB(); - } - - } - - - // here we expect one VFModule to be there -/* VfResourceInstaller.createVfModule(vfModuleStructure,heatMainTemplate, heatVolumeTemplate, heatEnv, heatVolumeEnv); - VfModule vfModule = vfModuleStructure.getCatalogVfModule(); - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfModuleStructure(vfModuleStructure)); - - catalogDB.saveOrUpdateVfModule(vfModule); - - // Here we expect many HEAT_TEMPLATE files to be there - if (vfModuleStructure.getArtifactsMap().containsKey(ASDCConfiguration.HEAT_ARTIFACT)) { - for (VfModuleArtifact heatArtifact : vfModuleStructure.getArtifactsMap() - .get(ASDCConfiguration.HEAT_ARTIFACT)) { - - HeatFiles heatFile = (HeatFiles) heatArtifact.getCatalogObject(); - - // Add this one for logging - artifactListForLogging.add(ASDCElementInfo.createElementFromVfArtifactInfo(heatArtifact.getArtifactInfo())); - - - catalogDB.saveVfModuleToHeatFiles (vfModule.getArtifactUuid(), heatFile); - // Indicate we will deploy it in the DB - heatArtifact.incrementDeployedInDB(); - } - } */ - - } - - catalogDB.commit(); - vfResourceStructure.setSuccessfulDeployment(); - - } catch (Exception e) { - - Throwable dbExceptionToCapture = e; - while (!(dbExceptionToCapture instanceof ConstraintViolationException || dbExceptionToCapture instanceof LockAcquisitionException) - && (dbExceptionToCapture.getCause() != null)) { - dbExceptionToCapture = dbExceptionToCapture.getCause(); - } - - if (dbExceptionToCapture instanceof ConstraintViolationException || dbExceptionToCapture instanceof LockAcquisitionException) { - logger.warn(MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED, vfResourceStructure.getResourceInstance().getResourceName(), - vfResourceStructure.getNotification().getServiceVersion(), "", "", MsoLogger.ErrorCode.DataError, "Exception - ASCDC Artifact already deployed", e); - } else { - String endEvent = "Exception caught during installation of " + vfResourceStructure.getResourceInstance().getResourceName() + ". Transaction rollback."; - String elementToLog = (artifactListForLogging.size() > 0 ? artifactListForLogging.get(artifactListForLogging.size()-1).toString() : "No element listed"); - logger.error(MessageEnum.ASDC_ARTIFACT_INSTALL_EXC, elementToLog, "", "", MsoLogger.ErrorCode.DataError, "Exception caught during installation of " + vfResourceStructure.getResourceInstance().getResourceName() + ". Transaction rollback", e); - catalogDB.rollback(); - throw new ArtifactInstallerException( - "Exception caught during installation of " + vfResourceStructure.getResourceInstance().getResourceName() + ". Transaction rollback.", e); - } - - } finally { - catalogDB.close(); - // Debug log the whole collection... - logger.debug(artifactListForLogging.toString()); - } - - } - - private static String identifyParentOfNestedTemplate(VfModuleStructure vfModuleStructure,VfModuleArtifact heatNestedArtifact) { - - if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT) != null - && vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0).getArtifactInfo().getRelatedArtifacts() != null) { - for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0) - .getArtifactInfo().getRelatedArtifacts()) { - if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) { - return ASDCConfiguration.HEAT; - } - - } - } - - if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) != null - && vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo().getRelatedArtifacts() != null) { - for (IArtifactInfo unknownArtifact:vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo().getRelatedArtifacts()) { - if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) { - return ASDCConfiguration.HEAT_VOL; - } - - } - } - - // Does not belong to anything - return null; - - } - - private static void createVnfResource(VfResourceStructure vfResourceStructure) { - VnfResource vnfResource = new VnfResource(); - - vnfResource.setModelUuid(vfResourceStructure.getResourceInstance().getResourceUUID()); - vnfResource.setDescription(vfResourceStructure.getNotification().getServiceDescription()); - - vnfResource.setOrchestrationMode("HEAT"); - // Set the version but Version is stored into ASDC_SERVICE_MODEL_VERSION - vnfResource.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfResourceStructure.getNotification().getServiceVersion())); -// vnfResource.setVnfType(VfResourceInstaller.createVNFName(vfResourceStructure)); - vnfResource.setModelVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfResourceStructure.getResourceInstance().getResourceVersion())); - - vnfResource.setModelInvariantUuid(vfResourceStructure.getResourceInstance().getResourceInvariantUUID()); - vnfResource.setModelVersion(vfResourceStructure.getResourceInstance().getResourceVersion()); -// vnfResource.setModelCustomizationName(vfResourceStructure.getResourceInstance().getResourceInstanceName()); -// vnfResource.setModelCustomizationUuid(vfResourceStructure.getResourceInstance().getResourceCustomizationUUID()); - vnfResource.setModelName(vfResourceStructure.getResourceInstance().getResourceName()); -// vnfResource.setServiceModelInvariantUUID(vfResourceStructure.getNotification().getServiceInvariantUUID()); - - //vnfResource.setCreated(getCurrentTimeStamp()); - - vfResourceStructure.setCatalogVnfResource(vnfResource); - } - - private static void createNetworkResourceCustomization(VfResourceStructure vfResourceStructure) { - NetworkResourceCustomization networkResourceCustomization = new NetworkResourceCustomization(); - - networkResourceCustomization.setModelCustomizationUuid(vfResourceStructure.getResourceInstance().getResourceCustomizationUUID().trim()); -// networkResourceCustomization.setModelName(vfResourceStructure.getResourceInstance().getResourceName().trim()); - networkResourceCustomization.setModelInstanceName(vfResourceStructure.getResourceInstance().getResourceInstanceName().trim()); -// networkResourceCustomization.setModelInvariantUuid(vfResourceStructure.getResourceInstance().getResourceInvariantUUID().trim()); -// networkResourceCustomization.setModelUuid(vfResourceStructure.getResourceInstance().getResourceUUID().trim()); -// networkResourceCustomization.setModelVersion(vfResourceStructure.getResourceInstance().getResourceVersion().trim()); - //networkResourceCustomization.setCreated(getCurrentTimeStamp()); - - vfResourceStructure.setCatalogNetworkResourceCustomization(networkResourceCustomization); - - ServiceToNetworks serviceNetworks = new ServiceToNetworks(); - serviceNetworks.setNetworkModelCustomizationUuid(networkResourceCustomization.getModelCustomizationUuid()); - serviceNetworks.setServiceModelUuid(vfResourceStructure.getNotification().getServiceUUID()); - - vfResourceStructure.setCatalogServiceToNetworks(serviceNetworks); - - } - - private static void createAllottedResourceCustomization(VfResourceStructure vfResourceStructure) { - AllottedResourceCustomization resourceCustomization = new AllottedResourceCustomization(); - - resourceCustomization.setModelCustomizationUuid(vfResourceStructure.getResourceInstance().getResourceCustomizationUUID().trim()); -// resourceCustomization.setModelName(vfResourceStructure.getResourceInstance().getResourceName().trim()); - resourceCustomization.setModelInstanceName(vfResourceStructure.getResourceInstance().getResourceInstanceName().trim()); -// resourceCustomization.setModelInvariantUuid(vfResourceStructure.getResourceInstance().getResourceInvariantUUID().trim()); -// resourceCustomization.setModelUuid(vfResourceStructure.getResourceInstance().getResourceUUID().trim()); - resourceCustomization.setVersion(vfResourceStructure.getResourceInstance().getResourceVersion().trim()); - //resourceCustomization.setCreated(getCurrentTimeStamp()); - - vfResourceStructure.setCatalogResourceCustomization(resourceCustomization); - - ServiceToAllottedResources serviceAllottedResources = new ServiceToAllottedResources(); - serviceAllottedResources.setArModelCustomizationUuid(resourceCustomization.getModelCustomizationUuid()); - serviceAllottedResources.setServiceModelUuid(vfResourceStructure.getNotification().getServiceUUID()); - - vfResourceStructure.setCatalogServiceToAllottedResources(serviceAllottedResources); - - } - - private static void createVfModule(VfModuleStructure vfModuleStructure,HeatTemplate heatMain, HeatTemplate heatVolume,HeatEnvironment heatEnv, HeatEnvironment heatVolumeEnv) { - VfModule vfModule = new VfModule(); -// vfModule.setType(createVfModuleName(vfModuleStructure)); -// vfModule.setAsdcUuid(vfModuleStructure.getVfModuleMetadata().getVfModuleModelUUID()); - vfModule.setDescription(vfModuleStructure.getVfModuleMetadata().getVfModuleModelDescription()); - - if (vfModuleStructure.getVfModuleMetadata().isBase()) { - vfModule.setIsBase(1); - } else { - vfModule.setIsBase(0); - } - -// vfModule.setModelCustomizationUuid(vfModuleStructure.getVfModuleMetadata().getVfModuleModelCustomizationUUID()); - vfModule.setModelInvariantUuid(vfModuleStructure.getVfModuleMetadata().getVfModuleModelInvariantUUID()); - vfModule.setModelName(vfModuleStructure.getVfModuleMetadata().getVfModuleModelName()); - - vfModule.setVersion(BigDecimalVersion.castAndCheckNotificationVersionToString(vfModuleStructure.getParentVfResource().getNotification().getServiceVersion())); - vfModule.setModelVersion(BigDecimalVersion.castAndCheckNotificationVersionToString( - vfModuleStructure.getVfModuleMetadata().getVfModuleModelVersion())); - - Map map = vfModuleStructure.getVfModuleMetadata().getProperties(); - - if(map != null){ - - if(map.get("vf_module_label") != null){ -// vfModule.setLabel(map.get("vf_module_label")); - } - if(map.get("initial_count") != null && map.get("initial_count").length() > 0){ -// vfModule.setInitialCount(Integer.parseInt(map.get("initial_count"))); - } - if(map.get("min_vf_module_instances") != null && map.get("min_vf_module_instances").length() > 0){ -// vfModule.setMinInstances(Integer.parseInt(map.get("min_vf_module_instances"))); - } - if(map.get("max_vf_module_instances") != null && map.get("max_vf_module_instances").length() > 0){ -// vfModule.setMaxInstances(Integer.parseInt(map.get("max_vf_module_instances"))); - } - - } - - vfModuleStructure.setCatalogVfModule(vfModule); - - VfResourceInstaller.createVfModuleLinks(vfModule, vfModuleStructure.getParentVfResource().getCatalogVnfResource(), heatMain,heatVolume, heatEnv,heatVolumeEnv); - } - - private static void createVfModuleLinks(VfModule vfModule, VnfResource vnfResource, HeatTemplate heatMain, - HeatTemplate heatVolume, HeatEnvironment heatEnv, HeatEnvironment heatVolumeEnv) { - - if (heatMain !=null) { -// vfModule.setTemplateId(heatMain.getId()); - } - if (heatEnv != null) { -// vfModule.setEnvironmentId(heatEnv.getId()); - } - if (heatVolume != null) { -// vfModule.setVolTemplateId(heatVolume.getId()); - } - if (heatVolumeEnv != null) { -// vfModule.setVolEnvironmentId(heatVolumeEnv.getId()); - } - -// vfModule.setVnfResourceId(vnfResource.getId()); - - } - - - private static Set extractHeatTemplateParameters(String yamlFile, String artifactUUID) { - - // Scan the payload downloadResult and extract the HeatTemplate - // parameters - YamlEditor yamlEditor = new YamlEditor(yamlFile.getBytes()); - return yamlEditor.getParameterList(artifactUUID); - - } - - - public static String verifyTheFilePrefixInArtifacts(String filebody, VfResourceStructure vfResourceStructure, List listTypes) { - String newFileBody = filebody; - for (VfModuleArtifact moduleArtifact:vfResourceStructure.getArtifactsMapByUUID().values()) { - - if (listTypes.contains(moduleArtifact.getArtifactInfo().getArtifactType())) { - - newFileBody = verifyTheFilePrefixInString(newFileBody,moduleArtifact.getArtifactInfo().getArtifactName()); - } - } - return newFileBody; - } - - public static String verifyTheFilePrefixInString(final String body, final String filenameToVerify) { - - String needlePrefix = "file:///"; - String prefixedFilenameToVerify = needlePrefix+filenameToVerify; - - if ((body == null) || (body.length() == 0) || (filenameToVerify == null) || (filenameToVerify.length() == 0)) { - return body; - } - - StringBuilder sb = new StringBuilder(body.length()); - - int currentIndex = 0; - int startIndex = 0; - - while (currentIndex != -1) { - startIndex = currentIndex; - currentIndex = body.indexOf(prefixedFilenameToVerify, startIndex); - - if (currentIndex == -1) { - break; - } - - // We append from the startIndex up to currentIndex (start of File Name) - sb.append(body.substring(startIndex, currentIndex)); - sb.append(filenameToVerify); - - currentIndex += prefixedFilenameToVerify.length(); - } - - sb.append(body.substring(startIndex)); - - return sb.toString(); - } - - private static void createHeatTemplateFromArtifact(VfResourceStructure vfResourceStructure, - VfModuleArtifact vfModuleArtifact) { - HeatTemplate heatTemplate = new HeatTemplate(); - - // TODO Set the label -// heatTemplate.setAsdcLabel("label"); - // Use the ResourceName of the ASDC template because the HEAT could be - // reused -// heatTemplate.setAsdcResourceName(vfResourceStructure.getResourceInstance().getResourceName()); - heatTemplate.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - - List typeList = new ArrayList<>(); - typeList.add(ASDCConfiguration.HEAT_NESTED); - typeList.add(ASDCConfiguration.HEAT_ARTIFACT); - - heatTemplate.setTemplateBody(verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(),vfResourceStructure,typeList)); - heatTemplate.setTemplateName(vfModuleArtifact.getArtifactInfo().getArtifactName()); - - if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) { - heatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout()); - } else { - heatTemplate.setTimeoutMinutes(240); - } - - heatTemplate.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); - heatTemplate.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); - heatTemplate.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - - if(vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null){ - heatTemplate.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); - } else { - heatTemplate.setArtifactChecksum("MANUAL_RECORD"); - } - - Set heatParam = VfResourceInstaller - .extractHeatTemplateParameters(vfModuleArtifact.getResult(), vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - heatTemplate.setParameters(heatParam); - //heatTemplate.setCreated(getCurrentTimeStamp()); - - vfModuleArtifact.setCatalogObject(heatTemplate); - } - - private static void createHeatEnvFromArtifact(VfResourceStructure vfResourceStructure, - VfModuleArtifact vfModuleArtifact) { - HeatEnvironment heatEnvironment = new HeatEnvironment(); - - heatEnvironment.setName(vfModuleArtifact.getArtifactInfo().getArtifactName()); - // TODO Set the label -// heatEnvironment.setAsdcLabel("Label"); - - List typeList = new ArrayList<>(); - typeList.add(ASDCConfiguration.HEAT); - typeList.add(ASDCConfiguration.HEAT_VOL); - - heatEnvironment.setEnvironment(verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(),vfResourceStructure,typeList)); -// heatEnvironment.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - heatEnvironment.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); - heatEnvironment.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); -// heatEnvironment.setAsdcResourceName(VfResourceInstaller.createVNFName(vfResourceStructure)); - heatEnvironment.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - - if(vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null){ - heatEnvironment.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); - } else{ - heatEnvironment.setArtifactChecksum("MANUAL_RECORD"); - } - //heatEnvironment.setCreated(getCurrentTimeStamp()); - - vfModuleArtifact.setCatalogObject(heatEnvironment); - - } - - private static void createHeatFileFromArtifact(VfResourceStructure vfResourceStructure, - VfModuleArtifact vfModuleArtifact) { - - HeatFiles heatFile = new HeatFiles(); - // TODO Set the label -// heatFile.setAsdcLabel("Label"); - heatFile.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - heatFile.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); - heatFile.setFileBody(vfModuleArtifact.getResult()); - heatFile.setFileName(vfModuleArtifact.getArtifactInfo().getArtifactName()); - heatFile.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); - //heatFile.setCreated(getCurrentTimeStamp()); - -// heatFile.setAsdcResourceName(vfResourceStructure.getResourceInstance().getResourceName()); - - if(vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null){ - heatFile.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); - } else { - heatFile.setArtifactChecksum("MANUAL_RECORD"); - } - - vfModuleArtifact.setCatalogObject(heatFile); - - } - - private static void createService(VfResourceStructure vfResourceStructure) { - - Service service = new Service(); - service.setDescription(vfResourceStructure.getNotification().getServiceDescription()); - service.setModelName(vfResourceStructure.getNotification().getServiceName()); - service.setModelUUID(vfResourceStructure.getNotification().getServiceUUID()); - service.setVersion(vfResourceStructure.getNotification().getServiceVersion()); - service.setModelInvariantUUID(vfResourceStructure.getNotification().getServiceInvariantUUID()); - //service.setCreated(getCurrentTimeStamp()); - - vfResourceStructure.setCatalogService(service); - } - - - private static String createVNFName(VfResourceStructure vfResourceStructure) { - - return vfResourceStructure.getNotification().getServiceName() + "/" + vfResourceStructure.getResourceInstance().getResourceInstanceName(); - } - - private static String createVfModuleName(VfModuleStructure vfModuleStructure) { - - return createVNFName(vfModuleStructure.getParentVfResource())+"::"+vfModuleStructure.getVfModuleMetadata().getVfModuleModelName(); - } - - - private static Timestamp getCurrentTimeStamp() { - - return new Timestamp(new Date().getTime()); - } - - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/AaiClientPropertiesImpl.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/AaiClientPropertiesImpl.java deleted file mode 100644 index be5af5d51f..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/AaiClientPropertiesImpl.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.tenantIsolation; - -import java.net.MalformedURLException; -import java.net.URL; - -import org.openecomp.mso.asdc.tenantIsolation.AsdcPropertiesUtils; -import org.openecomp.mso.client.aai.AAIProperties; -import org.openecomp.mso.client.aai.AAIVersion; -import org.openecomp.mso.properties.MsoJavaProperties; - -public class AaiClientPropertiesImpl implements AAIProperties { - - final MsoJavaProperties props; - public AaiClientPropertiesImpl() { - this.props = AsdcPropertiesUtils.loadMsoProperties (); - } - - @Override - public URL getEndpoint() throws MalformedURLException { - return new URL(props.getProperty("aai.endpoint", null)); - } - - @Override - public String getSystemName() { - return "MSO"; - } - - @Override - public AAIVersion getDefaultVersion() { - return AAIVersion.LATEST; - } - - @Override - public String getAuth() { - return props.getProperty("aai.auth", null); - } - - @Override - public String getKey() { - return props.getProperty("mso.msoKey", null); - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/AsdcPropertiesUtils.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/AsdcPropertiesUtils.java deleted file mode 100644 index 462ef0d51d..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/AsdcPropertiesUtils.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.openecomp.mso.asdc.tenantIsolation; - -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.properties.MsoJavaProperties; -import org.openecomp.mso.properties.MsoPropertiesFactory; - -public class AsdcPropertiesUtils { - - public final static String MSO_ASDC_CLIENTS = "MSO_ASDC_CLIENTS"; - - private static MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory (); - - private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC); - - private static boolean noProperties = true; - - public synchronized static MsoJavaProperties loadMsoProperties () { - MsoJavaProperties msoProperties; - try { - msoProperties = msoPropertiesFactory.getMsoJavaProperties (MSO_ASDC_CLIENTS); - } catch (Exception e) { - msoLogger.error (MessageEnum.ASDC_PROPERTIES_NOT_FOUND, MSO_ASDC_CLIENTS, "", "", MsoLogger.ErrorCode.DataError, "Exception when loading MSO ASDC Clients Properties", e); - return null; - } - - if (msoProperties != null && msoProperties.size () > 0) { - noProperties = false; - msoLogger.info (MessageEnum.ASDC_PROPERTIES_LOAD_SUCCESS, "", ""); - return msoProperties; - } else { - msoLogger.error (MessageEnum.ASDC_PROPERTIES_NOT_FOUND, MSO_ASDC_CLIENTS, "", "", MsoLogger.ErrorCode.DataError, "No MSO ASDC Clients Properties found"); - return null; - } - } - - public synchronized static final boolean getNoPropertiesState() { - return noProperties; - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/DistributionStatus.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/DistributionStatus.java deleted file mode 100644 index 4d04bfa59a..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/DistributionStatus.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.tenantIsolation; - -public enum DistributionStatus { - - SUCCESS, - FAILURE, - TIMEOUT, - INCOMPLETE -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/WatchdogDistribution.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/WatchdogDistribution.java deleted file mode 100644 index 6efcd64204..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/tenantIsolation/WatchdogDistribution.java +++ /dev/null @@ -1,239 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.tenantIsolation; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.openecomp.mso.asdc.client.ASDCConfiguration; -import org.openecomp.mso.client.aai.AAIObjectType; -import org.openecomp.mso.client.aai.AAIResourcesClient; -import org.openecomp.mso.client.aai.entities.uri.AAIResourceUri; -import org.openecomp.mso.client.aai.entities.uri.AAIUriFactory; -import org.openecomp.mso.client.aai.entities.uri.Depth; -import org.openecomp.mso.db.catalog.CatalogDatabase; -import org.openecomp.mso.db.catalog.beans.Service; -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.properties.MsoJsonProperties; -import org.openecomp.mso.properties.MsoPropertiesException; -import org.openecomp.mso.properties.MsoPropertiesFactory; -import org.openecomp.mso.requestsdb.WatchdogComponentDistributionStatus; -import org.openecomp.mso.requestsdb.WatchdogComponentDistributionStatusDb; -import org.openecomp.mso.requestsdb.WatchdogDistributionStatusDb; -import org.openecomp.mso.requestsdb.WatchdogServiceModVerIdLookupDb; - -import com.fasterxml.jackson.databind.JsonNode; - -public class WatchdogDistribution { - - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC); - private static final String MSO_PROP_ASDC = "MSO_PROP_ASDC"; - private static MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory(); - private WatchdogDistributionStatusDb watchdogDistDb; - private WatchdogComponentDistributionStatusDb watchdogCompDistDb; - private WatchdogServiceModVerIdLookupDb watchdogSerlookupDb; - private CatalogDatabase catalogDb; - private AAIResourcesClient aaiClient; - //protected ASDCConfiguration asdcConfig; - - public String getOverallDistributionStatus(String distributionId) throws MsoPropertiesException, Exception { - LOGGER.debug("Entered getOverallDistributionStatus method for distrubutionId: " + distributionId); - - String status = null; - try { - String distributionStatus = getWatchdogDistDb().getWatchdogDistributionIdStatus(distributionId); - - if(DistributionStatus.TIMEOUT.name().equalsIgnoreCase(distributionStatus)) { - LOGGER.debug("Ignoring to update WatchdogDistributionStatus as distributionId: " + distributionId + " status is set to: " + distributionStatus); - return DistributionStatus.TIMEOUT.name(); - } else { - List results = getWatchdogCompDistDb().getWatchdogComponentDistributionStatus(distributionId); - LOGGER.debug("Executed RequestDB getWatchdogComponentDistributionStatus for distrubutionId: " + distributionId); - - MsoJsonProperties properties = msoPropertiesFactory.getMsoJsonProperties(MSO_PROP_ASDC); - - //************************************************************************************************************************************************* - //**** Compare config values verse DB watchdog component names to see if every component has reported status before returning final result back to ASDC - //************************************************************************************************************************************************** - - //List configNames = asdcConfig.getComponentNames(); - - List dbNames = watchdogCompDistDb.getWatchdogComponentNames(distributionId); - - boolean allComponentsComplete = true; - - JsonNode masterConfigNode = properties.getJsonRootNode().get("componentNames"); - - if (masterConfigNode != null) { - - Iterator config = masterConfigNode.elements(); - - while( config.hasNext() ) { - String name = (String)config.next().asText(); - - boolean match = false; - - for(String dbName: dbNames){ - - if(name.equals(dbName)){ - LOGGER.debug("Found componentName " + name + " in the WatchDog Component DB"); - match = true; - break; - } - } - - if(match==false){ - LOGGER.debug(name + " has not be updated in the the WatchDog Component DB yet, so ending the loop"); - allComponentsComplete = false; - break; - } - - } - - } - - if(allComponentsComplete) { - //if(node.asInt() == results.size()) { - LOGGER.debug("Components Size matched with the WatchdogComponentDistributionStatus results."); - - for(WatchdogComponentDistributionStatus componentDist : results) { - String componentDistributionStatus = componentDist.getComponentDistributionStatus(); - LOGGER.debug("Component status: " + componentDistributionStatus + " on componentName: " + componentDist.getComponentName()); - if(componentDistributionStatus.equalsIgnoreCase("COMPONENT_DONE_ERROR")) { - status = DistributionStatus.FAILURE.name(); - break; - } else if(componentDistributionStatus.equalsIgnoreCase("COMPONENT_DONE_OK")) { - status = DistributionStatus.SUCCESS.name(); - } else { - throw new Exception("Invalid Component distribution status: " + componentDistributionStatus); - } - } - - LOGGER.debug("Updating overall DistributionStatus to: " + status + " for distributionId: " + distributionId); - getWatchdogDistDb().updateWatchdogDistributionIdStatus(distributionId, status); - } else { - LOGGER.debug("Components Size Didn't match with the WatchdogComponentDistributionStatus results."); - status = DistributionStatus.INCOMPLETE.name(); - return status; - } - } - } catch (MsoPropertiesException e) { - String error = "Error occurred when trying to load MSOJson Properties."; - LOGGER.debug(error); - throw new MsoPropertiesException(e.getMessage()); - } catch (Exception e) { - LOGGER.debug("Exception occurred on getOverallDistributionStatus : " + e.getMessage()); - throw new Exception(e); - } - - LOGGER.debug("Exciting getOverallDistributionStatus method in WatchdogDistribution"); - return status; - } - - public void executePatchAAI(String distributionId, String serviceModelInvariantUUID, String distributionStatus) throws Exception { - LOGGER.debug("Entered executePatchAAI method with distrubutionId: " + distributionId + " and distributionStatus: " + distributionStatus); - - try { - String serviceModelVersionId = getWatchdogSerlookupDb().getWatchdogServiceModVerId(distributionId); - LOGGER.debug("Executed RequestDB getWatchdogServiceModVerIdLookup with distributionId: " + distributionId + " and serviceModelVersionId: " + serviceModelVersionId); - - LOGGER.debug("ASDC Notification ServiceModelInvariantUUID : " + serviceModelInvariantUUID); - - if(serviceModelInvariantUUID == null) { - String error = "No Service found with serviceModelInvariantUUID: " + serviceModelInvariantUUID; - LOGGER.debug(error); - throw new Exception(error); - } - - AAIResourceUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, serviceModelInvariantUUID, serviceModelVersionId); - aaiUri.depth(Depth.ZERO); //Do not return relationships if any - LOGGER.debug("Target A&AI Resource URI: " + aaiUri.build().toString()); - - Map payload = new HashMap<>(); - payload.put("distribution-status", distributionStatus); - getAaiClient().update(aaiUri, payload); - - LOGGER.debug("A&AI UPDATE MODEL Version is success!"); - } catch (Exception e) { - LOGGER.debug("Exception occurred on executePatchAAI : " + e.getMessage()); - throw new Exception(e); - } - } - - public WatchdogDistributionStatusDb getWatchdogDistDb() { - if(watchdogDistDb == null) { - watchdogDistDb = WatchdogDistributionStatusDb.getInstance(); - } - return watchdogDistDb; - } - - public void setWatchdogDistDb(WatchdogDistributionStatusDb watchdogDistDb) { - this.watchdogDistDb = watchdogDistDb; - } - - public WatchdogComponentDistributionStatusDb getWatchdogCompDistDb() { - if(watchdogCompDistDb == null) { - watchdogCompDistDb = WatchdogComponentDistributionStatusDb.getInstance(); - } - return watchdogCompDistDb; - } - - public void setWatchdogCompDistDb(WatchdogComponentDistributionStatusDb watchdogCompDistDb) { - this.watchdogCompDistDb = watchdogCompDistDb; - } - - public WatchdogServiceModVerIdLookupDb getWatchdogSerlookupDb() { - if(watchdogSerlookupDb == null) { - watchdogSerlookupDb = WatchdogServiceModVerIdLookupDb.getInstance(); - } - return watchdogSerlookupDb; - } - - public void setWatchdogSerlookupDb(WatchdogServiceModVerIdLookupDb watchdogSerlookupDb) { - this.watchdogSerlookupDb = watchdogSerlookupDb; - } - - public CatalogDatabase getCatalogDb() { - if(catalogDb == null) { - catalogDb = CatalogDatabase.getInstance(); - } - return catalogDb; - } - - public void setCatalogDb(CatalogDatabase catalogDb) { - this.catalogDb = catalogDb; - } - - public AAIResourcesClient getAaiClient() { - if(aaiClient == null) { - aaiClient = new AAIResourcesClient(); - } - return aaiClient; - } - - public void setAaiClient(AAIResourcesClient aaiClient) { - this.aaiClient = aaiClient; - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/util/ASDCNotificationLogging.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/util/ASDCNotificationLogging.java deleted file mode 100644 index 834ad603a6..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/util/ASDCNotificationLogging.java +++ /dev/null @@ -1,525 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.util; - - -import java.util.List; -import java.util.Map; - -import org.onap.sdc.api.notification.IArtifactInfo; -import org.onap.sdc.api.notification.INotificationData; -import org.onap.sdc.api.notification.IResourceInstance; -import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; -import org.onap.sdc.tosca.parser.impl.SdcPropertyNames; -import org.onap.sdc.toscaparser.api.Group; -import org.onap.sdc.toscaparser.api.NodeTemplate; -import org.onap.sdc.toscaparser.api.elements.Metadata; -import org.openecomp.mso.asdc.installer.IVfModuleData; -import org.openecomp.mso.asdc.installer.ToscaResourceStructure; - -public class ASDCNotificationLogging { - - public static String dumpASDCNotification(INotificationData asdcNotification) { - - if (asdcNotification == null) { - return "NULL"; - } - return "ASDC Notification:" + System.lineSeparator() + - "DistributionID:" + testNull(asdcNotification.getDistributionID()) + System.lineSeparator() + - "ServiceName:" + testNull(asdcNotification.getServiceName()) + System.lineSeparator() + - "ServiceVersion:" + testNull(asdcNotification.getServiceVersion()) + System.lineSeparator() + - "ServiceUUID:" + testNull(asdcNotification.getServiceUUID()) + System.lineSeparator() + - "ServiceInvariantUUID:" + testNull(asdcNotification.getServiceInvariantUUID()) + System.lineSeparator() + - "ServiceDescription:" + testNull(asdcNotification.getServiceDescription()) + System.lineSeparator() + - "Service Artifacts List:" + System.lineSeparator() + testNull(dumpArtifactInfoList(asdcNotification.getServiceArtifacts())) + System.lineSeparator() + - "Resource Instances List:" + System.lineSeparator() + testNull(dumpASDCResourcesList(asdcNotification)) + System.lineSeparator(); - } - - public static String dumpCSARNotification(INotificationData asdcNotification, ToscaResourceStructure toscaResourceStructure) { - - if (asdcNotification == null) { - return "NULL"; - } - - - StringBuilder buffer = new StringBuilder("CSAR Notification:"); - buffer.append(System.lineSeparator()); - buffer.append(System.lineSeparator()); - - - ISdcCsarHelper csarHelper = toscaResourceStructure.getSdcCsarHelper(); - - - buffer.append("Service Level Properties:"); - buffer.append(System.lineSeparator()); - buffer.append("Name:"); - buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - buffer.append(System.lineSeparator()); - buffer.append("Description:"); - buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - buffer.append(System.lineSeparator()); - buffer.append("Model UUID:"); - buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - buffer.append(System.lineSeparator()); - buffer.append("Model Version:"); - buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - buffer.append(System.lineSeparator()); - buffer.append("Model InvariantUuid:"); - buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); - buffer.append(System.lineSeparator()); - buffer.append("Service Type:"); - buffer.append(csarHelper.getServiceMetadata().getValue("serviceType")); - buffer.append(System.lineSeparator()); - buffer.append("Service Role:"); - buffer.append(csarHelper.getServiceMetadata().getValue("serviceRole")); - buffer.append(System.lineSeparator()); - buffer.append("WorkLoad Context:"); - buffer.append(asdcNotification.getWorkloadContext()); - buffer.append(System.lineSeparator()); - buffer.append("Environment Context:"); - buffer.append(csarHelper.getServiceMetadata().getValue("environmentContext")); - - buffer.append(System.lineSeparator()); - buffer.append(System.lineSeparator()); - buffer.append("VNF Level Properties:"); - buffer.append(System.lineSeparator()); - - List vfNodeTemplatesList = toscaResourceStructure.getSdcCsarHelper().getServiceVfList(); - for (NodeTemplate vfNodeTemplate : vfNodeTemplatesList) { - - buffer.append("Model Name:"); - buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - buffer.append(System.lineSeparator()); - buffer.append("Description:"); - buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - buffer.append(System.lineSeparator()); - buffer.append("Version:"); - buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - buffer.append(System.lineSeparator()); - buffer.append("Type:"); - buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE))); - buffer.append(System.lineSeparator()); - buffer.append("InvariantUuid:"); - buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); - buffer.append(System.lineSeparator()); - buffer.append("Max Instances:"); - buffer.append(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)); - buffer.append(System.lineSeparator()); - buffer.append("Min Instances:"); - buffer.append(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES)); - buffer.append(System.lineSeparator()); - - buffer.append(System.lineSeparator()); - buffer.append("VNF Customization Properties:"); - buffer.append(System.lineSeparator()); - - buffer.append("Customization UUID:"); - buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); - buffer.append(System.lineSeparator()); - buffer.append("NFFunction:"); - buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)); - buffer.append(System.lineSeparator()); - buffer.append("NFCode:"); - buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, "nf_naming_code")); - buffer.append(System.lineSeparator()); - buffer.append("NFRole:"); - buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)); - buffer.append(System.lineSeparator()); - buffer.append("NFType:"); - buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)); - buffer.append(System.lineSeparator()); - buffer.append("MultiStageDesign:"); - buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, "multi_stage_design")); - - buffer.append(System.lineSeparator()); - buffer.append("VF Module Properties:"); - buffer.append(System.lineSeparator()); - List vfGroups = toscaResourceStructure.getSdcCsarHelper().getVfModulesByVf(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); - - for(Group group : vfGroups){ - - Metadata vfMetadata = group.getMetadata(); - - buffer.append("ModelInvariantUuid:"); - buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID))); - buffer.append(System.lineSeparator()); - buffer.append("ModelName:"); - buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME))); - buffer.append(System.lineSeparator()); - buffer.append("ModelUuid:"); - buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID))); - buffer.append(System.lineSeparator()); - buffer.append("ModelVersion:"); - buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION))); - buffer.append(System.lineSeparator()); - buffer.append("Description:"); - buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - buffer.append(System.lineSeparator()); - } - - } - - - List nodeTemplatesVLList = toscaResourceStructure.getSdcCsarHelper().getServiceVlList(); - - if(nodeTemplatesVLList != null){ - - buffer.append(System.lineSeparator()); - buffer.append("NETWORK Level Properties:"); - buffer.append(System.lineSeparator()); - - for(NodeTemplate vlNode : nodeTemplatesVLList){ - - buffer.append("Model Name:"); - buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - buffer.append(System.lineSeparator()); - buffer.append("Model InvariantUuid:"); - buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); - buffer.append(System.lineSeparator()); - buffer.append("Model UUID:"); - buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - buffer.append(System.lineSeparator()); - buffer.append("Model Version:"); - buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - buffer.append(System.lineSeparator()); - buffer.append("AIC Max Version:"); - buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); - buffer.append(System.lineSeparator()); - buffer.append("AIC Min Version:"); - buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); - buffer.append(System.lineSeparator()); - buffer.append("Tosca Node Type:"); - buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE))); - buffer.append(System.lineSeparator()); - buffer.append("Description:"); - buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - buffer.append(System.lineSeparator()); - - } - - } - - List allottedResourceList = toscaResourceStructure.getSdcCsarHelper().getAllottedResources(); - - if(allottedResourceList != null){ - - buffer.append(System.lineSeparator()); - buffer.append("Allotted Resource Properties:"); - buffer.append(System.lineSeparator()); - - for(NodeTemplate allottedNode : allottedResourceList){ - - buffer.append("Model Name:"); - buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - buffer.append(System.lineSeparator()); - buffer.append("Model Name:"); - buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - buffer.append(System.lineSeparator()); - buffer.append("Model InvariantUuid:"); - buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); - buffer.append(System.lineSeparator()); - buffer.append("Model Version:"); - buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - buffer.append(System.lineSeparator()); - buffer.append("Model UUID:"); - buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - buffer.append(System.lineSeparator()); - buffer.append("Model Subcategory:"); - buffer.append(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)); - buffer.append(System.lineSeparator()); - buffer.append("Model Description:"); - buffer.append(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - buffer.append(System.lineSeparator()); - - - buffer.append("Allotted Resource Customization Properties:"); - buffer.append(System.lineSeparator()); - - buffer.append("Model Cutomization UUID:"); - buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); - buffer.append(System.lineSeparator()); - buffer.append("NFFunction:"); - buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)); - buffer.append(System.lineSeparator()); - buffer.append("NFCode:"); - buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode, "nf_naming_code")); - buffer.append(System.lineSeparator()); - buffer.append("NFRole:"); - buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode, SdcPropertyNames.PROPERTY_NAME_NFROLE)); - buffer.append(System.lineSeparator()); - buffer.append("NFType:"); - buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode, SdcPropertyNames.PROPERTY_NAME_NFTYPE)); - buffer.append(System.lineSeparator()); - - - } - } - - - return buffer.toString(); - } - - public static String dumpVfModuleMetaDataList(List moduleMetaDataList) { - if (moduleMetaDataList == null ) { - return null; - } - - StringBuilder buffer = new StringBuilder("VfModuleMetaData List:"); - buffer.append(System.lineSeparator()); - - buffer.append("{"); - - for (IVfModuleData moduleMetaData:moduleMetaDataList) { - buffer.append(System.lineSeparator()); - buffer.append(testNull(dumpVfModuleMetaData(moduleMetaData))); - buffer.append(System.lineSeparator()); - buffer.append(","); - - } - buffer.replace(buffer.length()-1,buffer.length(), System.lineSeparator()); - buffer.append("}"); - buffer.append(System.lineSeparator()); - - return buffer.toString(); - } - - private static String dumpVfModuleMetaData(IVfModuleData moduleMetaData) { - - if (moduleMetaData == null ) { - return "NULL"; - } - - StringBuilder stringBuilder = new StringBuilder("VfModuleMetaData:"); - stringBuilder.append(System.lineSeparator()); - - stringBuilder.append("VfModuleModelName:"); - stringBuilder.append(testNull(moduleMetaData.getVfModuleModelName())); - stringBuilder.append(System.lineSeparator()); - - stringBuilder.append("VfModuleModelVersion:"); - stringBuilder.append(testNull(moduleMetaData.getVfModuleModelVersion())); - stringBuilder.append(System.lineSeparator()); - - stringBuilder.append("VfModuleModelUUID:"); - stringBuilder.append(testNull(moduleMetaData.getVfModuleModelUUID())); - stringBuilder.append(System.lineSeparator()); - - stringBuilder.append("VfModuleModelInvariantUUID:"); - stringBuilder.append(testNull(moduleMetaData.getVfModuleModelInvariantUUID())); - stringBuilder.append(System.lineSeparator()); - - stringBuilder.append("VfModuleModelDescription:"); - stringBuilder.append(testNull(moduleMetaData.getVfModuleModelDescription())); - stringBuilder.append(System.lineSeparator()); - - stringBuilder.append("Artifacts UUID List:"); - - if (moduleMetaData.getArtifacts() != null) { - stringBuilder.append("{"); - - for (String artifactUUID:moduleMetaData.getArtifacts()) { - stringBuilder.append(System.lineSeparator()); - stringBuilder.append(testNull(artifactUUID)); - stringBuilder.append(System.lineSeparator()); - stringBuilder.append(","); - } - stringBuilder.replace(stringBuilder.length()-1,stringBuilder.length(), System.lineSeparator()); - stringBuilder.append("}"); - stringBuilder.append(System.lineSeparator()); - } else { - stringBuilder.append("NULL"); - } - - if (moduleMetaData.getProperties() != null) { - Map vfModuleMap = moduleMetaData.getProperties(); - stringBuilder.append("Properties List:"); - stringBuilder.append("{"); - - for (Map.Entry entry : vfModuleMap.entrySet()) { - stringBuilder.append(System.lineSeparator()); - stringBuilder.append(" ").append(entry.getKey()).append(" : ").append(entry.getValue()); - } - stringBuilder.replace(stringBuilder.length()-1,stringBuilder.length(), System.lineSeparator()); - stringBuilder.append("}"); - stringBuilder.append(System.lineSeparator()); - } else { - stringBuilder.append("NULL"); - } - - - stringBuilder.append(System.lineSeparator()); - - stringBuilder.append("isBase:"); - stringBuilder.append(moduleMetaData.isBase()); - stringBuilder.append(System.lineSeparator()); - - return stringBuilder.toString(); - } - - private static String testNull(Object object) { - if (object == null) { - return "NULL"; - } else if (object instanceof Integer) { - return object.toString(); - } else if (object instanceof String) { - return (String)object; - } else { - return "Type not recognized"; - } - } - - private static String dumpASDCResourcesList(INotificationData asdcNotification) { - if (asdcNotification == null || asdcNotification.getResources() == null) { - return null; - } - - StringBuilder buffer = new StringBuilder(); - buffer.append("{"); - - for (IResourceInstance resourceInstanceElem:asdcNotification.getResources()) { - buffer.append(System.lineSeparator()); - buffer.append(testNull(dumpASDCResourceInstance(resourceInstanceElem))); - buffer.append(System.lineSeparator()); - buffer.append(","); - } - buffer.replace(buffer.length()-1,buffer.length(), System.lineSeparator()); - buffer.append("}"); - buffer.append(System.lineSeparator()); - - return buffer.toString(); - - } - - private static String dumpASDCResourceInstance(IResourceInstance resourceInstance) { - - if (resourceInstance == null) { - return null; - } - - return "Resource Instance Info:" + System.lineSeparator() + - "ResourceInstanceName:" + testNull(resourceInstance.getResourceInstanceName()) + System.lineSeparator() + - "ResourceCustomizationUUID:" + testNull(resourceInstance.getResourceCustomizationUUID()) + System.lineSeparator() + - "ResourceInvariantUUID:" + testNull(resourceInstance.getResourceInvariantUUID()) + System.lineSeparator() + - "ResourceName:" + testNull(resourceInstance.getResourceName()) + System.lineSeparator() + - "ResourceType:" + testNull(resourceInstance.getResourceType()) + System.lineSeparator() + - "ResourceUUID:" + testNull(resourceInstance.getResourceUUID()) + System.lineSeparator() + - "ResourceVersion:" + testNull(resourceInstance.getResourceVersion()) + System.lineSeparator() + - "Category:" + testNull(resourceInstance.getCategory()) + System.lineSeparator() + - "SubCategory:" + testNull(resourceInstance.getSubcategory()) + System.lineSeparator() + - "Resource Artifacts List:" + System.lineSeparator() + testNull(dumpArtifactInfoList(resourceInstance.getArtifacts())) + System.lineSeparator(); - } - - - private static String dumpArtifactInfoList(List artifactsList) { - - if (artifactsList == null || artifactsList.isEmpty()) { - return null; - } - - StringBuilder buffer = new StringBuilder(); - buffer.append("{"); - for (IArtifactInfo artifactInfoElem:artifactsList) { - buffer.append(System.lineSeparator()); - buffer.append(testNull(dumpASDCArtifactInfo(artifactInfoElem))); - buffer.append(System.lineSeparator()); - buffer.append(","); - - } - buffer.replace(buffer.length()-1,buffer.length(), System.lineSeparator()); - buffer.append("}"); - buffer.append(System.lineSeparator()); - - return buffer.toString(); - } - - private static String dumpASDCArtifactInfo(IArtifactInfo artifactInfo) { - - if (artifactInfo == null) { - return null; - } - - StringBuilder buffer = new StringBuilder("Service Artifacts Info:"); - buffer.append(System.lineSeparator()); - - buffer.append("ArtifactName:"); - buffer.append(testNull(artifactInfo.getArtifactName())); - buffer.append(System.lineSeparator()); - - buffer.append("ArtifactVersion:"); - buffer.append(testNull(artifactInfo.getArtifactVersion())); - buffer.append(System.lineSeparator()); - - buffer.append("ArtifactType:"); - buffer.append(testNull(artifactInfo.getArtifactType())); - buffer.append(System.lineSeparator()); - - buffer.append("ArtifactDescription:"); - buffer.append(testNull(artifactInfo.getArtifactDescription())); - buffer.append(System.lineSeparator()); - - buffer.append("ArtifactTimeout:"); - buffer.append(testNull(artifactInfo.getArtifactTimeout())); - buffer.append(System.lineSeparator()); - - buffer.append("ArtifactURL:"); - buffer.append(testNull(artifactInfo.getArtifactURL())); - buffer.append(System.lineSeparator()); - - buffer.append("ArtifactUUID:"); - buffer.append(testNull(artifactInfo.getArtifactUUID())); - buffer.append(System.lineSeparator()); - - buffer.append("ArtifactChecksum:"); - buffer.append(testNull(artifactInfo.getArtifactChecksum())); - buffer.append(System.lineSeparator()); - - buffer.append("GeneratedArtifact:"); - buffer.append("{"); - buffer.append(testNull(dumpASDCArtifactInfo(artifactInfo.getGeneratedArtifact()))); - buffer.append(System.lineSeparator()); - buffer.append("}"); - buffer.append(System.lineSeparator()); - - buffer.append("RelatedArtifacts:"); - - - if (artifactInfo.getRelatedArtifacts() != null) { - buffer.append("{"); - buffer.append(System.lineSeparator()); - for (IArtifactInfo artifactInfoElem:artifactInfo.getRelatedArtifacts()) { - - buffer.append(testNull(dumpASDCArtifactInfo(artifactInfoElem))); - buffer.append(System.lineSeparator()); - buffer.append(","); - - } - buffer.replace(buffer.length()-1,buffer.length(), System.lineSeparator()); - buffer.append("}"); - buffer.append(System.lineSeparator()); - } else { - buffer.append("NULL"); - } - - buffer.append(System.lineSeparator()); - - return buffer.toString(); - } -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/util/NotificationLogging.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/util/NotificationLogging.java deleted file mode 100644 index 617eefb0ae..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/util/NotificationLogging.java +++ /dev/null @@ -1,169 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - - -package org.openecomp.mso.asdc.util; - - - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.Proxy; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.openecomp.mso.logger.MsoLogger; -import org.onap.sdc.api.notification.INotificationData; - - -public class NotificationLogging implements InvocationHandler { - - private static Map> objectMethodsToLog = new HashMap<>(); - - protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.ASDC); - - private static InvocationHandler handler = (arg0, arg1, arg2) -> { - List methods = objectMethodsToLog.get(arg0); - if ((methods == null) || (methods.isEmpty())) { - // Do nothing for now... - return null; - } - methods.add(arg1); - return arg1.invoke(arg0, arg2); - }; - - public static InvocationHandler getHandler() { - return handler; - } - - /** - * - */ - private NotificationLogging() {} - - private static final String[] GETTER_PREFIXES = { "get", "is" }; - - public static String logNotification(INotificationData iNotif) { - if (iNotif == null) { - return "NULL"; - } - - Class clazz = iNotif.getClass(); - - Method[] declaredMethods = clazz.getDeclaredMethods(); - - if (declaredMethods == null || declaredMethods.length == 0) { - return "EMPTY"; // No declared methods in this class !!! - } - - StringBuilder buffer = new StringBuilder("ASDC Notification:"); - buffer.append(System.lineSeparator()); - - for (Method m : declaredMethods) { - if ((m != null) && isGetter(m)) { - for (String prefix : GETTER_PREFIXES) { - if (m.getName().startsWith(prefix)) { - buffer.append(m.getName().substring(prefix.length())); - break; - } - } - try { - buffer.append(testNull(m.invoke(iNotif, (Object[])null))); - } catch (IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { - LOGGER.debug("Exception :"+e); - buffer.append("UNREADABLE"); - } - buffer.append(System.lineSeparator()); - } - } - - return buffer.toString(); - } - - private static boolean isGetter(Method method) { - - // Must start with a valid (and known) prefix - boolean prefixFound = false; - for (String prefix : GETTER_PREFIXES) { - if (method.getName().startsWith(prefix)) { - prefixFound = true; - break; - } - } - if (!prefixFound) { - return false; - } - - // Must not take any input arguments - if (method.getParameterTypes().length != 0) { - return false; - } - - // Must not have return type 'void' - if (void.class.equals(method.getReturnType())) { - return false; - } - - // Must be public - if (!Modifier.isPublic(method.getModifiers())) { - return false; - } - - return true; - } - - private static String testNull(Object object) { - if (object == null) { - return "NULL"; - } else if (object instanceof Integer) { - return object.toString(); - } else if (object instanceof String) { - return (String) object; - } else { - return "Type not recognized"; - } - } - - private static void registerForLog(INotificationData objectToLog) { - INotificationData proxy = (INotificationData) Proxy.newProxyInstance( - INotificationData.class.getClassLoader(), - new Class[] { INotificationData.class }, - NotificationLogging.getHandler()); - objectMethodsToLog.put(proxy, new ArrayList<>()); - } - - private static void methodToLog(T methodCall) { - // - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/util/ToLog.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/util/ToLog.java deleted file mode 100644 index 59b3d68d2a..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/util/ToLog.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - - -package org.openecomp.mso.asdc.util; - - - - -public @interface ToLog { - -} diff --git a/asdc-controller/src/main/java/org/openecomp/mso/asdc/util/YamlEditor.java b/asdc-controller/src/main/java/org/openecomp/mso/asdc/util/YamlEditor.java deleted file mode 100644 index f6f1af5da6..0000000000 --- a/asdc-controller/src/main/java/org/openecomp/mso/asdc/util/YamlEditor.java +++ /dev/null @@ -1,176 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.asdc.util; - - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.yaml.snakeyaml.Yaml; - -import org.openecomp.mso.db.catalog.beans.HeatTemplateParam; - -public class YamlEditor { - - private static final String REFER_PATTERN = "file:///"; - private Map yml; - private Yaml yaml = new Yaml (); - - public YamlEditor () { - - } - - public YamlEditor (byte[] body) { - init (body); - } - - @SuppressWarnings("unchecked") - private synchronized void init (byte[] body) { - InputStream input = new ByteArrayInputStream (body); - yml = (Map ) yaml.load (input); - } - - public synchronized List getYamlNestedFileResourceTypeList () { - List typeList = new ArrayList<>(); - - @SuppressWarnings("unchecked") - Map resourceMap = (Map ) yml.get ("resources"); - Iterator > it = resourceMap.entrySet ().iterator (); - while (it.hasNext ()) { - Map.Entry pair = it.next (); - @SuppressWarnings("unchecked") - Map resourceEntry = (Map ) pair.getValue (); - String type = resourceEntry.get ("type"); - - if (type.contains (REFER_PATTERN)) { - typeList.add (type); - } - it.remove (); // avoids a ConcurrentModificationException - } - return typeList; - } - - public synchronized List getYamlResourceTypeList () { - List typeList = new ArrayList<>(); - - @SuppressWarnings("unchecked") - Map resourceMap = (Map ) yml.get ("resources"); - for (Entry pair : resourceMap.entrySet()) { - @SuppressWarnings("unchecked") - Map resourceEntry = (Map) pair.getValue(); - typeList.add(resourceEntry.get("type")); - } - return typeList; - } - - // Generate the parameter list based on the Heat Template - // Based on the email from Ella Kvetny: - // Within Heat Template, under parameters catalog, it might indicate the default value of the parameter - // If default value exist, the parameter is not mandatory, otherwise its value should be set - public synchronized Set getParameterList (String artifactUUID) { - Set paramSet = new HashSet<>(); - @SuppressWarnings("unchecked") - Map resourceMap = (Map ) yml.get ("parameters"); - - for (Entry stringObjectEntry : resourceMap.entrySet()) { - HeatTemplateParam param = new HeatTemplateParam(); - Entry pair = stringObjectEntry; - @SuppressWarnings("unchecked") - Map resourceEntry = (Map) pair.getValue(); - - param.setParamName(pair.getKey()); - // System.out.println(pair.getKey()+":"+type); - if (resourceEntry.containsKey("default")) { - param.setRequired(false); - } else { - param.setRequired(true); - } - // Now set the type - String value = resourceEntry.get("type"); - param.setParamType(value); - - param.setHeatTemplateArtifactUuid(artifactUUID); - - paramSet.add(param); - - } - return paramSet; - - } - - public synchronized void addParameterList (Set heatSet) { - - @SuppressWarnings("unchecked") - Map resourceMap = (Map ) yml.get ("parameters"); - if (resourceMap == null) { - resourceMap = new LinkedHashMap<>(); - this.yml.put ("parameters", resourceMap); - } - for (HeatTemplateParam heatParam : heatSet) { - Map paramInfo = new HashMap<>(); - paramInfo.put ("type", heatParam.getParamType ()); - - resourceMap.put (heatParam.getParamName (), paramInfo); - } - - // this.yml.put("parameters", resourceMap); - - } - - public boolean isParentTemplate (String templateBody) { - return templateBody.contains (REFER_PATTERN); - } - - public boolean verifyTemplate () { - // Verify whether the heat template is for Vnf Resource - // We don't support other template installation yet - - return true; - } - - public String encode (Map content) { - return yaml.dump (content); - } - - public synchronized String encode () { - return this.yaml.dump (this.yml); - } - - /** - * This method return the YAml file as a string. - * - */ - @Override - public String toString () { - - return encode (); - } - -} -- cgit 1.2.3-korg